diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 079937c..77e6524 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -100,6 +100,24 @@ node --test scripts/guard/check.test.mjs The gates still run everything before a pull request. Use these commands only to check your work as you go. +## Screenshots for a UI change + +AGENTS.md asks every UI pull request for screenshots in both themes and both languages. The preview harness in `apps/mobile/preview` takes them for you: it renders the real screens in a browser with made-up data. It's dev-only, outside the pnpm workspace, and nothing in the app imports it. Run `pnpm install` at the root first, as in Set up: the bundle reads the app's `tsconfig.json`, which extends Expo's. + +```sh +cd apps/mobile/preview +pnpm install --ignore-workspace # once: the harness has its own lockfile +pnpm build # bundles the screens into dist/ +pnpm shoot about # the shots whose file name contains "about"; no filter shoots them all +``` + +- The filter matches file names in `shots.mjs`, such as `about` or `settings-x2`. +- The pictures land in `apps/mobile/preview/out/screens`, which git ignores, with `out/index.html` to look through them. +- To add a shot, add a line to `shots.mjs`: `core(...)` shoots light and dark in es-419 and English, `other(...)` light and dark in es-419 only. +- `pnpm compress` shrinks the pictures before you attach them. It's optional and needs Python with Pillow. + +The harness drives a headless Chromium and never downloads one. It uses `HERMIT_PREVIEW_CHROMIUM` when that holds the path to a Chromium or `chrome-headless-shell` executable. Otherwise it takes the newest `chromium_headless_shell-*` in Playwright's cache: `PLAYWRIGHT_BROWSERS_PATH` when it's set, else `~/Library/Caches/ms-playwright` on macOS, `~/.cache/ms-playwright` on Linux (or under `$XDG_CACHE_HOME`) and `%LOCALAPPDATA%\ms-playwright` on Windows. If you have none, `pnpm exec playwright-core install chromium-headless-shell` in `apps/mobile/preview` puts one there. When it finds nothing, it stops with a message that names the variable. + ## Make a change 1. Find the issue, or open one. A feature needs the `accepted` label first. A change to a non-negotiable needs an accepted RFC. diff --git a/apps/mobile/preview/browser.mjs b/apps/mobile/preview/browser.mjs new file mode 100644 index 0000000..46fb047 --- /dev/null +++ b/apps/mobile/preview/browser.mjs @@ -0,0 +1,82 @@ +// Dev-only: finds the headless Chromium the preview scripts drive (shoot.mjs, clips.mjs, words.mjs). It only looks, +// never downloads: HERMIT_PREVIEW_CHROMIUM first, then Playwright's own cache for this system. mascot/proof.mjs films +// with a full Chrome and keeps its own lookup. +import { existsSync, readdirSync } from "node:fs"; +import { createRequire } from "node:module"; +import { homedir } from "node:os"; +import { dirname, isAbsolute, join, resolve } from "node:path"; + +export const BROWSER_VAR = "HERMIT_PREVIEW_CHROMIUM"; + +/** The executable inside a chromium_headless_shell- folder, by system (as playwright-core names them). */ +const SHELL = { + "darwin-arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"], + "darwin-x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"], + "linux-x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"], + "linux-arm64": ["chrome-linux", "headless_shell"], + "win32-x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"], +}; +// playwright-core installs the x64 build on every Windows, ARM included. +const shellFor = (platform, arch) => SHELL[platform === "win32" ? "win32-x64" : `${platform}-${arch}`]; + +/** Where PLAYWRIGHT_BROWSERS_PATH=0 installs: .local-browsers inside the harness's own playwright-core. */ +const playwrightLocalBrowsers = () => + join(dirname(createRequire(import.meta.url).resolve("playwright-core/package.json")), ".local-browsers"); + +/** Playwright's browser cache, by the same rules playwright-core uses (PLAYWRIGHT_BROWSERS_PATH, then per system). */ +export function playwrightCache({ + env = process.env, + platform = process.platform, + home = homedir(), + cwd = process.cwd(), + localBrowsers = playwrightLocalBrowsers, +} = {}) { + const set = env.PLAYWRIGHT_BROWSERS_PATH; + let cache; + if (set === "0") cache = localBrowsers(); + else if (set) cache = set; + else if (platform === "darwin") cache = join(home, "Library", "Caches", "ms-playwright"); + else if (platform === "win32") cache = join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "ms-playwright"); + else cache = join(env.XDG_CACHE_HOME || join(home, ".cache"), "ms-playwright"); + // A relative path counts from where pnpm was started (INIT_CWD), as playwright-core reads it. + return isAbsolute(cache) ? cache : resolve(env.INIT_CWD || cwd, cache); +} + +/** The path to launch, or an Error that says how to point the harness at a browser. */ +export function findChromium({ + env = process.env, + platform = process.platform, + arch = process.arch, + home = homedir(), + cwd = process.cwd(), + localBrowsers = playwrightLocalBrowsers, + exists = existsSync, + list = (dir) => (existsSync(dir) ? readdirSync(dir) : []), +} = {}) { + const set = env[BROWSER_VAR]; + if (set) return exists(set) ? set : new Error(`${BROWSER_VAR} is set to ${set}, but there is no file there.`); + const cache = playwrightCache({ env, platform, home, cwd, localBrowsers }); + const shell = shellFor(platform, arch); + // Newest revision first: chromium_headless_shell-1255 before -999, so compare the numbers, not the text. + const revisions = list(cache) + .filter((d) => /^chromium_headless_shell-\d+$/.test(d)) + .sort((a, b) => Number(b.split("-")[1]) - Number(a.split("-")[1])); + for (const dir of shell ? revisions : []) { + const path = join(cache, dir, ...shell); + if (exists(path)) return path; + } + return new Error( + `No headless Chromium found in ${cache}. Set ${BROWSER_VAR} to the path of a Chromium or chrome-headless-shell executable. ` + + "The preview scripts never download a browser (CONTRIBUTING.md, Screenshots for a UI change).", + ); +} + +/** For the scripts: the path, or stop with the message. */ +export function chromiumPath() { + const found = findChromium(); + if (found instanceof Error) { + console.error(found.message); + process.exit(1); + } + return found; +} diff --git a/apps/mobile/preview/browser.test.mjs b/apps/mobile/preview/browser.test.mjs new file mode 100644 index 0000000..e8d53fd --- /dev/null +++ b/apps/mobile/preview/browser.test.mjs @@ -0,0 +1,174 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { join, resolve } from "node:path"; +import { BROWSER_VAR, findChromium, playwrightCache } from "./browser.mjs"; + +// A made-up disk: the folders in each directory, and the files that exist. Nothing here touches the real machine. +const disk = (dirs, files) => ({ + list: (dir) => dirs[dir] ?? [], + exists: (path) => files.includes(path), +}); + +const home = join("/", "home", "ana"); +const macCache = join(home, "Library", "Caches", "ms-playwright"); +const linuxCache = join(home, ".cache", "ms-playwright"); +// An absolute path on whatever system runs the test, standing in for C:\Users\ana\AppData\Local. +const winLocal = join("/", "Users", "ana", "AppData", "Local"); +const winCache = join(winLocal, "ms-playwright"); + +const macArm = (rev) => join(macCache, `chromium_headless_shell-${rev}`, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"); + +test("an Apple silicon Mac finds the shell where it always did, with no setting", () => { + const found = findChromium({ env: {}, platform: "darwin", arch: "arm64", home, ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [macArm(1208)]) }); + assert.equal(found, macArm(1208)); +}); + +test("the newest revision wins by number, not as text: 1000 before 999", () => { + const found = findChromium({ + env: {}, + platform: "darwin", + arch: "arm64", + home, + ...disk({ [macCache]: ["chromium_headless_shell-999", "chromium_headless_shell-1000"] }, [macArm(999), macArm(1000)]), + }); + assert.equal(found, macArm(1000)); +}); + +test("a revision folder without the executable falls back to the one before it", () => { + const found = findChromium({ + env: {}, + platform: "darwin", + arch: "arm64", + home, + ...disk({ [macCache]: ["chromium_headless_shell-1208", "chromium_headless_shell-1200"] }, [macArm(1200)]), + }); + assert.equal(found, macArm(1200)); +}); + +test("folders that aren't the headless shell are ignored", () => { + const found = findChromium({ + env: {}, + platform: "darwin", + arch: "arm64", + home, + ...disk({ [macCache]: ["ffmpeg-1011", "chromium-1208", "chromium_headless_shell-1208"] }, [macArm(1208)]), + }); + assert.equal(found, macArm(1208)); +}); + +test("an Intel Mac looks in the mac-x64 folder", () => { + const path = join(macCache, "chromium_headless_shell-1208", "chrome-headless-shell-mac-x64", "chrome-headless-shell"); + const found = findChromium({ env: {}, platform: "darwin", arch: "x64", home, ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [path]) }); + assert.equal(found, path); +}); + +test("Linux x64 looks in ~/.cache/ms-playwright, in the linux64 folder", () => { + const path = join(linuxCache, "chromium_headless_shell-1208", "chrome-headless-shell-linux64", "chrome-headless-shell"); + const found = findChromium({ env: {}, platform: "linux", arch: "x64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, [path]) }); + assert.equal(found, path); +}); + +test("Linux arm64 uses Playwright's own build, chrome-linux/headless_shell", () => { + const path = join(linuxCache, "chromium_headless_shell-1208", "chrome-linux", "headless_shell"); + const found = findChromium({ env: {}, platform: "linux", arch: "arm64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, [path]) }); + assert.equal(found, path); +}); + +test("Linux honors XDG_CACHE_HOME", () => { + const cache = join("/", "data", "cache"); + assert.equal(playwrightCache({ env: { XDG_CACHE_HOME: cache }, platform: "linux", home }), join(cache, "ms-playwright")); +}); + +test("Windows looks under LOCALAPPDATA, in the win64 folder", () => { + const local = winLocal; + const path = join(winCache, "chromium_headless_shell-1208", "chrome-headless-shell-win64", "chrome-headless-shell.exe"); + const found = findChromium({ + env: { LOCALAPPDATA: local }, + platform: "win32", + arch: "x64", + home, + ...disk({ [winCache]: ["chromium_headless_shell-1208"] }, [path]), + }); + assert.equal(found, path); +}); + +test("Windows on ARM uses the same win64 shell, as Playwright installs it there too", () => { + const path = join(winCache, "chromium_headless_shell-1208", "chrome-headless-shell-win64", "chrome-headless-shell.exe"); + const found = findChromium({ + env: { LOCALAPPDATA: winLocal }, + platform: "win32", + arch: "arm64", + home, + ...disk({ [winCache]: ["chromium_headless_shell-1208"] }, [path]), + }); + assert.equal(found, path); +}); + +test("PLAYWRIGHT_BROWSERS_PATH replaces the cache folder on every system", () => { + const custom = join("/", "opt", "browsers"); + for (const platform of ["darwin", "linux", "win32"]) { + assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: custom }, platform, home }), custom); + } + const path = join(custom, "chromium_headless_shell-1208", "chrome-headless-shell-linux64", "chrome-headless-shell"); + const found = findChromium({ + env: { PLAYWRIGHT_BROWSERS_PATH: custom }, + platform: "linux", + arch: "x64", + home, + ...disk({ [custom]: ["chromium_headless_shell-1208"] }, [path]), + }); + assert.equal(found, path); +}); + +test("PLAYWRIGHT_BROWSERS_PATH=0 means the browsers inside playwright-core's own folder, as Playwright installs them", () => { + const local = join("/", "work", "hermit", "apps", "mobile", "preview", "node_modules", "playwright-core", ".local-browsers"); + assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "0" }, platform: "linux", home, localBrowsers: () => local }), local); +}); + +test("a relative PLAYWRIGHT_BROWSERS_PATH resolves against INIT_CWD, then the working folder", () => { + const project = join("/", "work", "hermit"); + const preview = join(project, "apps", "mobile", "preview"); + assert.equal( + playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "browsers", INIT_CWD: project }, platform: "linux", home, cwd: preview }), + resolve(project, "browsers"), + ); + assert.equal(playwrightCache({ env: { PLAYWRIGHT_BROWSERS_PATH: "browsers" }, platform: "linux", home, cwd: preview }), resolve(preview, "browsers")); +}); + +test(`${BROWSER_VAR} wins over the cache when the file exists`, () => { + const own = join("/", "usr", "bin", "chromium"); + const found = findChromium({ + env: { [BROWSER_VAR]: own }, + platform: "darwin", + arch: "arm64", + home, + ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [own, macArm(1208)]), + }); + assert.equal(found, own); +}); + +test(`${BROWSER_VAR} pointing at nothing stops with a message, without falling back to the cache`, () => { + const found = findChromium({ + env: { [BROWSER_VAR]: "/no/such/chromium" }, + platform: "darwin", + arch: "arm64", + home, + ...disk({ [macCache]: ["chromium_headless_shell-1208"] }, [macArm(1208)]), + }); + assert.ok(found instanceof Error); + assert.match(found.message, new RegExp(`${BROWSER_VAR} is set to /no/such/chromium`)); +}); + +test(`an empty cache stops with a message that names ${BROWSER_VAR} and says nothing is downloaded`, () => { + const found = findChromium({ env: {}, platform: "linux", arch: "x64", home, ...disk({}, []) }); + assert.ok(found instanceof Error); + assert.ok(found.message.includes(linuxCache), found.message); + assert.ok(found.message.includes(BROWSER_VAR), found.message); + assert.match(found.message, /never download a browser/); +}); + +test("a system with no known shell folder stops with the same message", () => { + const found = findChromium({ env: {}, platform: "freebsd", arch: "x64", home, ...disk({ [linuxCache]: ["chromium_headless_shell-1208"] }, []) }); + assert.ok(found instanceof Error); + assert.ok(found.message.includes(BROWSER_VAR), found.message); +}); diff --git a/apps/mobile/preview/build.mjs b/apps/mobile/preview/build.mjs index fbe8df2..153624c 100644 --- a/apps/mobile/preview/build.mjs +++ b/apps/mobile/preview/build.mjs @@ -1,5 +1,5 @@ // Dev-only: bundles the real apps/mobile screens for a browser. react-native resolves to react-native-web; native -// modules, adapters and the runtime's ports resolve to the stubs in src/stubs (see README in docs/preview). +// modules, adapters and the runtime's ports resolve to the stubs in src/stubs (CONTRIBUTING.md, Screenshots for a UI change). import { build } from "esbuild"; import { copyFileSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; diff --git a/apps/mobile/preview/clips.mjs b/apps/mobile/preview/clips.mjs index 13ed5ef..bee1777 100644 --- a/apps/mobile/preview/clips.mjs +++ b/apps/mobile/preview/clips.mjs @@ -9,6 +9,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, s import { dirname, extname, join, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { chromium } from "playwright-core"; +import { chromiumPath } from "./browser.mjs"; const here = dirname(fileURLToPath(import.meta.url)); const dist = join(here, "dist"); @@ -31,12 +32,6 @@ const server = createServer((req, res) => { await new Promise((r) => server.listen(0, "127.0.0.1", r)); const base = `http://127.0.0.1:${server.address().port}/`; -function chromiumPath() { - const cache = join(process.env.HOME, "Library/Caches/ms-playwright"); - const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop(); - return join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"); -} - // The chat is its own route since the roster became home (HM-BOT-01): "index" here still means Hermit's chat. const url = (screen, { theme = "light", lang = "es-419", variant = "", params = {} } = {}) => `${base}?${new URLSearchParams({ screen: screen === "index" ? "chat" : screen, theme, lang, variant, params: JSON.stringify(screen === "index" ? { bot: "hermit", ...params } : params) })}`; diff --git a/apps/mobile/preview/shoot.mjs b/apps/mobile/preview/shoot.mjs index 147ce9d..fcb1fba 100644 --- a/apps/mobile/preview/shoot.mjs +++ b/apps/mobile/preview/shoot.mjs @@ -1,10 +1,11 @@ // Dev-only: serves dist/ and captures every shot in shots.mjs with headless Chromium at a 412x915 phone viewport, // into out/screens, then writes out/index.html (both gitignored). Usage: node shoot.mjs [filter] import { createServer } from "node:http"; -import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from "node:fs"; import { dirname, extname, join, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { chromium } from "playwright-core"; +import { chromiumPath } from "./browser.mjs"; import { shots } from "./shots.mjs"; import { audit, words } from "./audit.mjs"; @@ -28,14 +29,6 @@ const server = createServer((req, res) => { await new Promise((r) => server.listen(0, "127.0.0.1", r)); const base = `http://127.0.0.1:${server.address().port}/`; -/** The Chromium already on this Mac (Playwright's cache); nothing is downloaded. */ -function chromiumPath() { - const cache = join(process.env.HOME, "Library/Caches/ms-playwright"); - const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop(); - if (!shell) throw new Error("no headless Chromium in ~/Library/Caches/ms-playwright"); - return join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell"); -} - const filter = process.argv[2]; const browser = await chromium.launch({ executablePath: chromiumPath() }); const results = []; diff --git a/apps/mobile/preview/src/stubs/adapters.ts b/apps/mobile/preview/src/stubs/adapters.ts index 927b5b2..2d8c2a3 100644 --- a/apps/mobile/preview/src/stubs/adapters.ts +++ b/apps/mobile/preview/src/stubs/adapters.ts @@ -45,6 +45,7 @@ export const floorFacts = ok(scene.variant === "below" : { platform: "android" as const, apiLevel: 36, abis: ["arm64-v8a"], totalRamBytes: 11.2 * 1024 ** 3, isLowRamDevice: false, dotprod: true, manufacturer: "samsung", model: "SM-S942B", soc: "SM8850" }); export const nightConditions = ok({ charging: true, batteryLevel: 0.82, network: "wifi", screenOn: false, idleMinutes: 45 }); export const onReconnect = off; +export const pauseDownloadWhenLeaving = off; export const openStorageSettings = ok(undefined); export const modelFile = () => ({ exists: false, uri: "file:///model.gguf", size: 0 }); export const verifiedSha256 = () => undefined; @@ -90,6 +91,8 @@ export const actOnPermission = ok(undefined); // App lock and fingerprint. export const appLockEnabled = () => scene.variant === "locked"; export const saveAppLock = ok(undefined); +// The copy keeps its default biometric name: an Android phone's fingerprint. +export const applyBiometricName = ok(undefined); export const phoneSecurity = ok("biometric" as const); // The lock screen's shot waits at its own prompt, as on the phone before the fingerprint. export const confirmOwner = () => (scene.variant === "locked" ? new Promise(() => {}) : Promise.resolve(true)); diff --git a/apps/mobile/preview/words.mjs b/apps/mobile/preview/words.mjs index f382c9b..bd89449 100644 --- a/apps/mobile/preview/words.mjs +++ b/apps/mobile/preview/words.mjs @@ -2,10 +2,11 @@ // preview bundle, for the copy diet's before and after. Usage: node words.mjs // (build the bundle of the commit to compare with its own build.mjs first). import { createServer } from "node:http"; -import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { extname, join, resolve, sep } from "node:path"; import { chromium } from "playwright-core"; import { words } from "./audit.mjs"; +import { chromiumPath } from "./browser.mjs"; const [distArg, outArg] = process.argv.slice(2); if (!distArg || !outArg) throw new Error("usage: node words.mjs "); @@ -23,8 +24,6 @@ const server = createServer((req, res) => { }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const base = `http://127.0.0.1:${server.address().port}/`; -const cache = join(process.env.HOME, "Library/Caches/ms-playwright"); -const shell = readdirSync(cache).filter((d) => d.startsWith("chromium_headless_shell-")).sort().pop(); /** The hero states, as in shots.mjs. */ export const HERO = [ @@ -36,7 +35,7 @@ export const HERO = [ { key: "welcome", screen: "welcome", variant: "" }, ]; -const browser = await chromium.launch({ executablePath: join(cache, shell, "chrome-headless-shell-mac-arm64", "chrome-headless-shell") }); +const browser = await chromium.launch({ executablePath: chromiumPath() }); const out = {}; for (const h of HERO) { const ctx = await browser.newContext({ viewport: { width: 412, height: 915 }, deviceScaleFactor: 1, locale: "es-419" }); diff --git a/apps/mobile/src/a11y-scan.test.ts b/apps/mobile/src/a11y-scan.test.ts index 941d661..fe76127 100644 --- a/apps/mobile/src/a11y-scan.test.ts +++ b/apps/mobile/src/a11y-scan.test.ts @@ -5,11 +5,25 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; +import { fileURLToPath } from "node:url"; import { contrast, stripComments, unlabelledControls } from "./a11y-scan.ts"; import { palettes } from "./theme.ts"; -const SRC = new URL(".", import.meta.url).pathname; -const files = ["app", "components"].flatMap((dir) => readdirSync(join(SRC, dir)).filter((f) => f.endsWith(".tsx")).map((f) => join(dir, f))).concat(["app-lock.tsx"]); +const SRC = fileURLToPath(new URL(".", import.meta.url)); +const files = [ + ...["app", "components"].flatMap((dir) => + readdirSync(join(SRC, dir), { recursive: true }) + .map(String) + .filter((f) => f.endsWith(".tsx")) + .map((f) => join(dir, f)) + ), + ...readdirSync(SRC).filter((f) => f.endsWith(".tsx")), +]; + +test("the scanner walks nested route folders and top-level screens", () => { + assert.ok(files.includes(join("app", "oauth", "mcp.tsx"))); + assert.ok(files.includes("app-lock.tsx")); +}); test("the scanner flags a Pressable without a role or a label", () => { const src = ` go("/x")} style={s}>\n{t("a.b")}`; diff --git a/apps/mobile/src/copy-keys.test.ts b/apps/mobile/src/copy-keys.test.ts new file mode 100644 index 0000000..45d5985 --- /dev/null +++ b/apps/mobile/src/copy-keys.test.ts @@ -0,0 +1,60 @@ +/// +// CT-10: every literal copy key named in apps/mobile/src and packages/*/src exists in both locales. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { extractCopyKeys } from "./copy-keys.ts"; + +const SRC = fileURLToPath(new URL(".", import.meta.url)); +const ROOT = fileURLToPath(new URL("../../..", import.meta.url)); + +const loadLocale = (name: string): Record => + JSON.parse(readFileSync(join(ROOT, "packages", "copy", "locales", `${name}.json`), "utf8")) as Record; + +function collectSourceFiles(dir: string, labelPrefix: string): Array<{ label: string; fullPath: string }> { + return readdirSync(dir, { recursive: true }) + .map(String) + .filter((f) => /\.(ts|tsx)$/.test(f) && !/\.test\.(ts|tsx)$/.test(f)) + .map((f) => ({ label: join(labelPrefix, f), fullPath: join(dir, f) })); +} + +test("extractCopyKeys finds literal keys and skips templates and non-keys", () => { + const src = [ + `const a = t("HM-SET-01.title");`, + `const b = t('common.ok');`, + "const c = `HM-APPR-01.approve`;", + "const dyn = `HM-SET-10.failed.${reason}`;", + `const other = "not a copy key";`, + `const partial = "HM-SET-10";`, + ].join("\n"); + assert.deepEqual(extractCopyKeys(src), ["HM-SET-01.title", "common.ok", "HM-APPR-01.approve"]); +}); + +test("CT-10: every literal copy key in code exists in both en and es-419 locales", () => { + const locales: Array<[string, Record]> = [ + ["en", loadLocale("en")], + ["es-419", loadLocale("es-419")], + ]; + const packagesDir = join(ROOT, "packages"); + const pkgFiles = readdirSync(packagesDir).flatMap((pkg) => { + const srcDir = join(packagesDir, pkg, "src"); + try { + return collectSourceFiles(srcDir, join("packages", pkg, "src")); + } catch { + return []; + } + }); + const allFiles = [...collectSourceFiles(SRC, join("apps", "mobile", "src")), ...pkgFiles]; + const missing: string[] = []; + for (const { label, fullPath } of allFiles) { + const text = readFileSync(fullPath, "utf8"); + for (const key of extractCopyKeys(text)) { + for (const [localeName, dict] of locales) { + if (!Object.hasOwn(dict, key)) missing.push(`${label}: missing ${key} in ${localeName}`); + } + } + } + assert.deepEqual(missing, []); +}); diff --git a/apps/mobile/src/copy-keys.ts b/apps/mobile/src/copy-keys.ts new file mode 100644 index 0000000..fc32e8d --- /dev/null +++ b/apps/mobile/src/copy-keys.ts @@ -0,0 +1,16 @@ +// CT-10: pure source scan for copy keys written as whole string literals. +import { KEY_PATTERN } from "@hermit/copy"; + +const LITERAL_RE = /"([^"\\\n]*)"|'([^'\\\n]*)'|`([^`\\\n]*)`/g; + +/** Returns every copy key written as a whole string literal ("...", '...', or `...` without `${`). */ +export function extractCopyKeys(source: string): string[] { + const keys: string[] = []; + for (const match of source.matchAll(LITERAL_RE)) { + const template = match[3]; + if (template !== undefined && template.includes("${")) continue; + const value = match[1] ?? match[2] ?? template ?? ""; + if (KEY_PATTERN.test(value)) keys.push(value); + } + return keys; +} diff --git a/packages/core/test/profile.test.ts b/packages/core/test/profile.test.ts index 302de98..d7bc770 100644 --- a/packages/core/test/profile.test.ts +++ b/packages/core/test/profile.test.ts @@ -76,7 +76,9 @@ describe("profile values (US-FORM-03)", () => { test("a sealed value opens only with its key and for its own kind", async () => { const key = webcrypto.getRandomValues(new Uint8Array(32)); const sealed = await sealProfileValue(cipher, key, "id_number", "1-2345-6789"); - expect(sealed).not.toContain("2345"); + // The sealed value is hex: check the decoded bytes, not the hex text. + const sealedBytes = Buffer.from(sealed, "hex"); + expect(sealedBytes.includes(Buffer.from("1-2345-6789", "utf8"))).toBe(false); expect(await openProfileValue(cipher, key, "id_number", sealed)).toBe("1-2345-6789"); await expect(openProfileValue(cipher, key, "passport_number", sealed)).rejects.toThrow(); await expect(openProfileValue(cipher, new Uint8Array(32), "id_number", sealed)).rejects.toThrow();