app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

shell.spec.ts (15812B)


      1 import { expect, test } from '@playwright/test';
      2 import { createHash } from 'node:crypto';
      3 import { execFileSync } from 'node:child_process';
      4 import {
      5   cp,
      6   mkdtemp,
      7   mkdir,
      8   readFile,
      9   readdir,
     10   rm,
     11   writeFile
     12 } from 'node:fs/promises';
     13 import { tmpdir } from 'node:os';
     14 import path from 'node:path';
     15 import { fileURLToPath } from 'node:url';
     16 import { createStaticHarness } from '../integration/harness/static.ts';
     17 
     18 // Isolated qualification clone: actual components compile into disposable output.
     19 // The primary static payload and product route source are never overwritten.
     20 const capsule = fileURLToPath(new URL('../../../', import.meta.url));
     21 let directory: string;
     22 let server: Awaited<ReturnType<typeof createStaticHarness>>;
     23 test.beforeAll(async () => {
     24   test.setTimeout(86_400_000);
     25   directory = await mkdtemp(path.join(tmpdir(), 'hcp014-shell-'));
     26   try {
     27     const checkout = path.join(directory, 'checkout');
     28     execFileSync('git', [
     29       'clone',
     30       '--quiet',
     31       '--no-hardlinks',
     32       capsule,
     33       checkout
     34     ]);
     35     for (const relative of [
     36       'web/src/lib/components/AppShell.svelte',
     37       'web/src/lib/components/CapabilityGate.svelte',
     38       'web/src/lib/runtime/view-context.ts',
     39       'web/src/lib/runtime/capabilities.ts',
     40       'web/src/lib/config/operation-flags.ts',
     41       'web/src/app.css',
     42       'web/src/routes/+layout.svelte',
     43       'web/tests/unit/components/shell.test.ts',
     44       'web/tests/e2e/shell.spec.ts',
     45       'web/tests/e2e/harness/shell.svelte',
     46       'web/tests/integration/harness/static.ts'
     47     ])
     48       await cp(path.join(capsule, relative), path.join(checkout, relative), {
     49         recursive: true
     50       });
     51     const fixture = await readFile(
     52       path.join(capsule, 'web/tests/e2e/harness/shell.svelte'),
     53       'utf8'
     54     );
     55     await writeFile(
     56       path.join(checkout, 'web/src/routes/+page.svelte'),
     57       fixture.replaceAll('../../../src/lib/', '../lib/')
     58     );
     59     // Runtime store metadata is volume-specific; install the exact locked graph
     60     // into this disposable clone without a network or lock-repair fallback.
     61     const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], {
     62       cwd: path.join(capsule, 'web')
     63     })
     64       .toString()
     65       .trim();
     66     const installed = execFileSync(
     67       'corepack',
     68       [
     69         'pnpm',
     70         'install',
     71         '--offline',
     72         '--frozen-lockfile',
     73         '--store-dir',
     74         path.dirname(sourceStore)
     75       ],
     76       { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 86400000 }
     77     );
     78     const fixtureLayout =
     79       '<script lang="ts">import "../theme.css"; import "../app.css"; import type { Snippet } from "svelte"; let { children }: { children: Snippet } = $props();</script>{@render children()}';
     80     await writeFile(
     81       path.join(checkout, 'web/src/routes/+layout.svelte'),
     82       fixtureLayout
     83     );
     84     // Labelled test destinations only: no product feature/controller qualification.
     85     const derivedTargets = [];
     86     for (const route of ['search', 'sell', 'selling', 'about', 'privacy']) {
     87       const relative = 'web/src/routes/' + route + '/+page.svelte';
     88       const source =
     89         '<h1>HC_TEST_ONLY_NAVIGATION_TARGET</h1><p id="help">Test destination: ' +
     90         route +
     91         '</p>';
     92       await mkdir(path.dirname(path.join(checkout, relative)), {
     93         recursive: true
     94       });
     95       await writeFile(path.join(checkout, relative), source);
     96       derivedTargets.push({
     97         path: relative,
     98         source,
     99         sha256: createHash('sha256').update(source).digest('hex')
    100       });
    101     }
    102     const sourceAudit = execFileSync(
    103       process.execPath,
    104       ['tools/check-source.mjs'],
    105       { cwd: path.join(checkout, 'web') }
    106     ).toString();
    107     const identities = [];
    108     for (const relative of [
    109       'web/src/lib/components/AppShell.svelte',
    110       'web/src/app.css'
    111     ]) {
    112       identities.push({
    113         name: relative,
    114         sha256: createHash('sha256')
    115           .update(await readFile(path.join(checkout, relative)))
    116           .digest('hex')
    117       });
    118     }
    119     execFileSync(process.execPath, ['tools/build-info.mjs'], {
    120       cwd: path.join(checkout, 'web')
    121     });
    122     const compiled = execFileSync(
    123       process.execPath,
    124       ['node_modules/vite/bin/vite.js', 'build'],
    125       {
    126         cwd: path.join(checkout, 'web'),
    127         stdio: 'pipe',
    128         timeout: 86400000
    129       }
    130     );
    131     async function payload(
    132       directory: string,
    133       prefix = ''
    134     ): Promise<{ path: string; sha256: string }[]> {
    135       const files = [];
    136       for (const entry of await readdir(directory, { withFileTypes: true })) {
    137         const relative = prefix + entry.name;
    138         if (entry.isDirectory())
    139           files.push(
    140             ...(await payload(path.join(directory, entry.name), relative + '/'))
    141           );
    142         else
    143           files.push({
    144             path: relative,
    145             sha256: createHash('sha256')
    146               .update(await readFile(path.join(directory, entry.name)))
    147               .digest('hex')
    148           });
    149       }
    150       return files.sort((left, right) => left.path.localeCompare(right.path));
    151     }
    152     console.log(
    153       JSON.stringify({
    154         fixture: 'HCP014_TEST_ONLY_COMPILE',
    155         identities,
    156         sourceAudit,
    157         fixtureSourceSha256: createHash('sha256').update(fixture).digest('hex'),
    158         compiledRouteSha256: createHash('sha256')
    159           .update(
    160             await readFile(path.join(checkout, 'web/src/routes/+page.svelte'))
    161           )
    162           .digest('hex'),
    163         compiledLayoutSha256: createHash('sha256')
    164           .update(fixtureLayout)
    165           .digest('hex'),
    166         compiledLayout: fixtureLayout,
    167         derivedTargets,
    168         payload: await payload(path.join(checkout, 'web/build')),
    169         sourceStore,
    170         installed: installed.toString(),
    171         compiled: compiled.toString(),
    172         metadata: JSON.parse(
    173           await readFile(
    174             path.join(checkout, 'web/build/build-info.json'),
    175             'utf8'
    176           )
    177         ) as unknown
    178       })
    179     );
    180     server = await createStaticHarness({
    181       buildRoot: path.join(checkout, 'web/build')
    182     });
    183   } catch (error) {
    184     await rm(directory, { recursive: true, force: true });
    185     throw error;
    186   }
    187 });
    188 test.afterAll(async () => {
    189   await server?.close();
    190   if (directory) await rm(directory, { recursive: true, force: true });
    191   if (server)
    192     expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
    193 });
    194 
    195 async function measure(page: import('@playwright/test').Page, stage: string) {
    196   const measured = await page.evaluate(() => ({
    197     width: innerWidth,
    198     scroll: globalThis.document.documentElement.scrollWidth,
    199     navigation: Array.from(
    200       globalThis.document.querySelectorAll(
    201         'nav[aria-label="Primary"] > .cluster > :is(a,span,button,details)'
    202       )
    203     ).map((element) => {
    204       const rect = element.getBoundingClientRect();
    205       return {
    206         label: element.textContent?.trim().replace(/\s+/g, ' '),
    207         x: rect.x,
    208         y: rect.y,
    209         width: rect.width,
    210         height: rect.height
    211       };
    212     }),
    213     heights: Array.from(
    214       globalThis.document.querySelectorAll(
    215         'nav a,nav span[aria-disabled],button,summary'
    216       )
    217     )
    218       .filter((element) => element.getBoundingClientRect().height > 0)
    219       .map((element) => element.getBoundingClientRect().height)
    220   }));
    221   expect(measured.scroll).toBeLessThanOrEqual(measured.width);
    222   for (const height of measured.heights)
    223     expect(height).toBeGreaterThanOrEqual(44);
    224   for (let index = 1; index < measured.navigation.length; index++) {
    225     const previous = measured.navigation[index - 1];
    226     const current = measured.navigation[index];
    227     expect(current.y + current.height / 2).toBeGreaterThanOrEqual(
    228       previous.y + previous.height / 2
    229     );
    230     if (current.y < previous.y + previous.height)
    231       expect(current.x).toBeGreaterThanOrEqual(previous.x + previous.width);
    232   }
    233   if (measured.width === 320)
    234     expect(measured.navigation.at(-1)!.y).toBeGreaterThan(
    235       measured.navigation[0].y
    236     );
    237   console.log(
    238     JSON.stringify({
    239       fixture: 'HCP014_CONTROLLED_PRESENTATION_ONLY',
    240       stage,
    241       measured
    242     })
    243   );
    244   return measured;
    245 }
    246 
    247 for (const width of [320, 1024]) {
    248   test(`actual shell keyboard, guest/connected order and unavailable callbacks at ${width}px`, async ({
    249     browser
    250   }) => {
    251     const context = await browser.newContext({
    252       viewport: { width, height: 900 }
    253     });
    254     const external: string[] = [];
    255     try {
    256       await context.route('**/*', (route) => {
    257         if (new URL(route.request().url()).origin === server.url)
    258           return route.continue();
    259         external.push(route.request().url());
    260         return route.abort();
    261       });
    262       const page = await context.newPage();
    263       await page.goto(server.url);
    264       const skip = page.getByRole('link', { name: 'Skip to main content' });
    265       await expect(
    266         page.getByRole('button', { name: 'Connect extension' })
    267       ).toBeEnabled();
    268       await page.keyboard.press('Tab');
    269       await expect(skip).toBeFocused();
    270       await expect(skip).toBeVisible();
    271       await page.keyboard.press('Enter');
    272       await expect(page.getByRole('main')).toBeFocused();
    273       await expect(page.locator('main')).toHaveCount(1);
    274       await expect(page.locator('[id="main-content"]')).toHaveCount(1);
    275       const primary = page.getByRole('navigation', {
    276         name: 'Primary',
    277         exact: true
    278       });
    279       await expect(primary).toHaveText(
    280         'HarvestCircle Search List food Messages Use your Nostr extension to choose your identity. Connect extension'
    281       );
    282       await expect(
    283         page.getByRole('link', { name: 'Search', exact: true })
    284       ).toHaveAttribute('aria-current', 'page');
    285       expect(await page.locator('a[aria-current="page"]').count()).toBe(1);
    286       const guest = await measure(page, 'guest');
    287       expect(guest.navigation.map((item) => item.label)).toEqual([
    288         'HarvestCircle',
    289         'Search',
    290         'List food',
    291         'Messages',
    292         'Connect extension'
    293       ]);
    294       const guestConnect = page.getByRole('button', {
    295         name: 'Connect extension'
    296       });
    297       await guestConnect.focus();
    298       await expect(guestConnect).toBeFocused();
    299       await page.keyboard.press('Enter');
    300       await expect(
    301         page.getByRole('status').filter({ hasText: /^Commands:/ })
    302       ).toHaveText('Commands: 1');
    303       await expect(primary).toContainText(
    304         'HarvestCircle Search Messages Selling Identity'
    305       );
    306       await expect(page.getByText('Messages', { exact: true })).toHaveAttribute(
    307         'aria-disabled',
    308         'true'
    309       );
    310       await expect(page.getByRole('link', { name: 'Messages' })).toHaveCount(0);
    311       await expect(page.getByRole('link', { name: 'Selling' })).toHaveAttribute(
    312         'href',
    313         '/selling'
    314       );
    315       const connectedClosed = await measure(page, 'connected-closed');
    316       expect(
    317         connectedClosed.navigation.map((item) => item.label?.split(' ')[0])
    318       ).toEqual(['HarvestCircle', 'Search', 'Messages', 'Selling', 'Identity']);
    319       const summary = page.locator('nav[aria-label="Primary"] summary');
    320       await summary.focus();
    321       await page.keyboard.press('Enter');
    322       await expect(
    323         page.locator('nav[aria-label="Primary"] details')
    324       ).toHaveAttribute('open', '');
    325       await page.keyboard.press('Space');
    326       await expect(
    327         page.locator('nav[aria-label="Primary"] details')
    328       ).not.toHaveAttribute('open', '');
    329       await page.keyboard.press('Enter');
    330       await expect(
    331         page.locator('nav[aria-label="Primary"] details')
    332       ).toHaveAttribute('open', '');
    333       await expect(page.locator('.key')).toHaveText(
    334         'HC_TEST_ONLY_PUBLIC_KEY_' + 'a'.repeat(64)
    335       );
    336       await page.keyboard.press('Tab');
    337       const disconnect = page.getByRole('button', {
    338         name: 'Disconnect',
    339         exact: true
    340       });
    341       await expect(disconnect).toBeFocused();
    342       await page
    343         .getByRole('button', { name: 'Toggle command availability' })
    344         .click();
    345       await expect(disconnect).toBeDisabled();
    346       await disconnect.evaluate((element) =>
    347         (element as HTMLButtonElement).click()
    348       );
    349       await disconnect.evaluate((element) =>
    350         element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
    351       );
    352       await expect(
    353         page.getByRole('status').filter({ hasText: /^Commands:/ })
    354       ).toHaveText('Commands: 1');
    355       await measure(page, 'connected-open-long-key');
    356       await expect(page.locator('header')).not.toContainText(/unread/i);
    357       await page
    358         .getByRole('button', { name: 'Toggle command availability' })
    359         .click();
    360       await disconnect.focus();
    361       await expect(disconnect).toBeFocused();
    362       await page.keyboard.press('Enter');
    363       await expect(
    364         page.getByRole('status').filter({ hasText: /^Commands:/ })
    365       ).toHaveText('Commands: 2');
    366       await page
    367         .getByRole('button', { name: 'Toggle command availability' })
    368         .click();
    369       const connect = page.getByRole('button', { name: 'Connect extension' });
    370       await expect(connect).toBeDisabled();
    371       await connect.evaluate((element) =>
    372         (element as HTMLButtonElement).click()
    373       );
    374       await connect.evaluate((element) =>
    375         element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
    376       );
    377       await expect(
    378         page.getByRole('status').filter({ hasText: /^Commands:/ })
    379       ).toHaveText('Commands: 2');
    380       expect(external).toEqual([]);
    381     } finally {
    382       await context.close();
    383     }
    384     expect(context.pages()).toHaveLength(0);
    385   });
    386 }
    387 
    388 test('controlled shell callbacks become available only after actual hydration', async ({
    389   browser
    390 }) => {
    391   const context = await browser.newContext({
    392     viewport: { width: 320, height: 900 }
    393   });
    394   let releaseScripts!: () => void;
    395   const scriptsReady = new Promise<void>((resolve) => {
    396     releaseScripts = resolve;
    397   });
    398   let delayedScripts = 0;
    399   const external: string[] = [];
    400   try {
    401     await context.route('**/*', async (route) => {
    402       if (new URL(route.request().url()).origin !== server.url) {
    403         external.push(route.request().url());
    404         return route.abort();
    405       }
    406       if (new URL(route.request().url()).pathname.endsWith('.js')) {
    407         delayedScripts++;
    408         await scriptsReady;
    409       }
    410       return route.continue();
    411     });
    412     const page = await context.newPage();
    413     await page.goto(server.url, { waitUntil: 'commit' });
    414     const connect = page.getByRole('button', { name: 'Connect extension' });
    415     await expect(
    416       page.getByRole('heading', { name: 'HC_TEST_ONLY_SHELL' })
    417     ).toBeVisible();
    418     await expect.poll(() => delayedScripts).toBeGreaterThan(0);
    419     await expect(connect).toBeDisabled();
    420     await expect(
    421       page.getByRole('status').filter({ hasText: /^Commands:/ })
    422     ).toHaveText('Commands: 0');
    423     releaseScripts();
    424     await expect(connect).toBeEnabled();
    425     await connect.focus();
    426     await expect(connect).toBeFocused();
    427     await page.keyboard.press('Enter');
    428     await expect(
    429       page.getByRole('status').filter({ hasText: /^Commands:/ })
    430     ).toHaveText('Commands: 1');
    431     const identity = page.locator('nav[aria-label="Primary"] summary');
    432     await identity.focus();
    433     await expect(identity).toBeFocused();
    434     await page.keyboard.press('Enter');
    435     await expect(
    436       page.locator('nav[aria-label="Primary"] details')
    437     ).toHaveAttribute('open', '');
    438     await expect(
    439       page.getByRole('button', { name: 'Disconnect', exact: true })
    440     ).toBeEnabled();
    441     expect(external).toEqual([]);
    442   } finally {
    443     releaseScripts();
    444     await context.close();
    445   }
    446   expect(context.pages()).toHaveLength(0);
    447 });