@rexezuge/tooling 1.9.1 → 1.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/scripts/check-god-files.js +2 -2
- package/dist/scripts/check-god-files.js.map +3 -3
- package/dist/scripts/lib/entrypoint.d.ts +27 -0
- package/dist/scripts/lib/entrypoint.d.ts.map +1 -0
- package/dist/scripts/lib/entrypoint.js +1 -0
- package/dist/scripts/lib/entrypoint.js.map +7 -0
- package/dist/scripts/spa-shell.js +2 -2
- package/dist/scripts/spa-shell.js.map +3 -3
- package/dist/scripts/validate-locales.js +5 -5
- package/dist/scripts/validate-locales.js.map +3 -3
- package/dist/scripts/verify-migrations.js +2 -2
- package/dist/scripts/verify-migrations.js.map +3 -3
- package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/patches.js +3 -3
- package/dist/scripts/wrangler-config/patches.js.map +3 -3
- package/dist/scripts/wrangler-config/resources.d.ts +17 -7
- package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/resources.js +1 -1
- package/dist/scripts/wrangler-config/resources.js.map +3 -3
- package/dist/scripts/wrangler-config/types.d.ts +3 -2
- package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/types.js.map +2 -2
- package/package.json +2 -2
- package/src/scripts/check-god-files.ts +2 -2
- package/src/scripts/lib/entrypoint.test.ts +60 -0
- package/src/scripts/lib/entrypoint.ts +39 -0
- package/src/scripts/spa-shell.ts +2 -2
- package/src/scripts/validate-locales.ts +2 -2
- package/src/scripts/verify-migrations.ts +2 -2
- package/src/scripts/wrangler-config/patches.ts +11 -2
- package/src/scripts/wrangler-config/resources.test.ts +49 -0
- package/src/scripts/wrangler-config/resources.ts +38 -16
- package/src/scripts/wrangler-config/types.ts +3 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var w=Object.defineProperty;var a=(t,s)=>w(t,"name",{value:s,configurable:!0});import{readdirSync as S,readFileSync as
|
|
2
|
-
`).length;if(f<=s)continue;const p={file:l,lines:f,level:f>e?"critical":"warn"};
|
|
1
|
+
var w=Object.defineProperty;var a=(t,s)=>w(t,"name",{value:s,configurable:!0});import{readdirSync as S,readFileSync as u,statSync as $}from"node:fs";import d from"node:path";import{fail as v}from"./lib/github-actions.js";import{isEntrypoint as j}from"./lib/entrypoint.js";import{isSet as _,parseFlags as x,splitPositional as E,valueOf as g}from"./lib/cli-args.js";const y=300,O=400,I=new Set(["node_modules","dist",".wrangler","coverage","coverage-integration","coverage-web",".git"]),W=/\.(?:ts|tsx|js|mjs|cjs|css)$/,k=["test","spec"].flatMap(t=>[".ts",".tsx",".js",".jsx",".mjs",".cjs"].map(s=>`.${t}${s}`));function A(t){return/(?:^|\/)(?:locales|generated)\//.test(t)||/(?:^|\/)__(?:tests|mocks)__(?:\/|$)/.test(t)||/(?:^|\/)scripts\//.test(t)||/(?:^|\/)(?:test|tests|__tests__)\//.test(t)||/\.config\.(?:m?[jt]s|cjs)$/.test(t)||t.endsWith(".d.ts")||t.endsWith(".json")||t.endsWith(".sql")||t.endsWith(".md")?!0:k.some(s=>t.endsWith(s))}a(A,"shouldSkip");function L(t,s){return s.some(e=>e.endsWith("/")?t.startsWith(e):t===e)}a(L,"isAllowlisted");function T(t){const s=[],e=a(o=>{for(const n of S(o)){const r=d.join(o,n);let i;try{i=$(r)}catch{continue}if(i.isDirectory()){if(I.has(n))continue;e(r)}else W.test(n)&&s.push(d.relative(t,r))}},"visit");return e(t),s}a(T,"walk");function F(t){const s=t.soft??y,e=t.hard??O,o=t.allowlist??[],n=T(t.root).filter(l=>!A(l)),r=[],i=[];for(const l of n){const f=u(d.join(t.root,l),"utf8").split(`
|
|
2
|
+
`).length;if(f<=s)continue;const p={file:l,lines:f,level:f>e?"critical":"warn"};L(l,o)?i.push(p):r.push(p)}r.sort((l,f)=>f.lines-l.lines),i.sort((l,f)=>f.lines-l.lines);const c=r.filter(l=>l.level==="critical"),h=t.failOnHard!==!0||c.length===0,m=h?`God-file check passed (${n.length} files, ${r.length} over soft limit ${s}, ${i.length} allowlisted).`:`God-file check failed: ${c.length} file(s) exceed ${e} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;return{findings:r,allowlisted:i,scanned:n.length,passed:h,reported:m}}a(F,"checkGodFiles");function C(t){let s;try{s=u(t,"utf8")}catch{return[]}let e;try{e=JSON.parse(s)}catch(o){throw new Error(`${t} is not valid JSON: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new Error(`${t} must be a JSON array of repo-relative path strings.`);return e}a(C,"readAllowlist");function N(t=process.argv.slice(2)){const{positional:s,rest:e}=E(t,["root","allowlist"]),o=x(e,{value:["root","allowlist"],boolean:["fail-on-hard"]}),n=g(o,"root")??s[0]??".",r=g(o,"allowlist")??d.join(n,"scripts/god-files.allowlist.json"),i=F({root:n,allowlist:C(r),failOnHard:_(o,"fail-on-hard")});console.log(i.reported);for(const c of i.findings)console.log(`${c.level==="critical"?"CRITICAL":"WARN"} ${c.lines} ${c.file}`);for(const c of i.allowlisted)console.log(`ALLOWLISTED ${c.lines} ${c.file}`);return i.passed||v(`God-file check failed: run with --root ${n} to see the report.`),0}a(N,"checkGodFilesCli"),j(import.meta.url)&&process.exit(N(process.argv.slice(2)));export{O as HARD_LIMIT,y as SOFT_LIMIT,F as checkGodFiles,N as checkGodFilesCli,L as isAllowlisted,C as readAllowlist,A as shouldSkip,T as walk};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/check-god-files.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The rules behind `scripts/check-god-files.ts`.\n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\nimport { fail } from './lib/github-actions.ts';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /**\n Path relative to the root the check ran against.\n */\n readonly file: string;\n /**\n Lines it has.\n */\n readonly lines: number;\n /**\n `warn` past the soft limit, `critical` past the hard one.\n */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /**\n Files over a limit, worst first, minus the allowlisted.\n */\n readonly findings: readonly GodFileFinding[];\n /**\n How many files the walk measured.\n */\n readonly scanned: number;\n /**\n Allowlisted files that are over a limit — reported, never counted.\n */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /**\n The message to print, either way.\n */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /**\n Directory to walk.\n */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /**\n Soft limit, past which a file is reported as `warn`.\n */\n readonly soft?: number;\n /**\n Hard limit, past which a file is reported as `critical`.\n */\n readonly hard?: number;\n /**\n Make a `critical` finding fail the run.\n */\n readonly failOnHard?: boolean;\n}\n\n/**\nDefault soft limit, as every source repo uses.\n*/\nexport const SOFT_LIMIT = 300;\n/**\nDefault hard limit, as every source repo uses.\n*/\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (\n /(?:^|\\/)(?:locales|generated)\\//.test(rel) ||\n /(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel) ||\n /(?:^|\\/)scripts\\//.test(rel) ||\n /(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel) ||\n /\\.config\\.(?:m?[jt]s|cjs)$/.test(rel) ||\n rel.endsWith('.d.ts') ||\n rel.endsWith('.json') ||\n rel.endsWith('.sql') ||\n rel.endsWith('.md')\n )\n return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = path.join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(path.relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(path.join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(file: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(file, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${file} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? path.join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(checkGodFilesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
-
"mappings": "+EAgDA,OAAS,eAAAA,EAAa,gBAAAC,EAAc,YAAAC,MAAgB,UACpD,
|
|
6
|
-
"names": ["readdirSync", "readFileSync", "statSync", "
|
|
4
|
+
"sourcesContent": ["/**\n * The rules behind `scripts/check-god-files.ts`.\n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport path from 'node:path';\nimport { fail } from './lib/github-actions.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /**\n Path relative to the root the check ran against.\n */\n readonly file: string;\n /**\n Lines it has.\n */\n readonly lines: number;\n /**\n `warn` past the soft limit, `critical` past the hard one.\n */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /**\n Files over a limit, worst first, minus the allowlisted.\n */\n readonly findings: readonly GodFileFinding[];\n /**\n How many files the walk measured.\n */\n readonly scanned: number;\n /**\n Allowlisted files that are over a limit — reported, never counted.\n */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /**\n The message to print, either way.\n */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /**\n Directory to walk.\n */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /**\n Soft limit, past which a file is reported as `warn`.\n */\n readonly soft?: number;\n /**\n Hard limit, past which a file is reported as `critical`.\n */\n readonly hard?: number;\n /**\n Make a `critical` finding fail the run.\n */\n readonly failOnHard?: boolean;\n}\n\n/**\nDefault soft limit, as every source repo uses.\n*/\nexport const SOFT_LIMIT = 300;\n/**\nDefault hard limit, as every source repo uses.\n*/\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (\n /(?:^|\\/)(?:locales|generated)\\//.test(rel) ||\n /(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel) ||\n /(?:^|\\/)scripts\\//.test(rel) ||\n /(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel) ||\n /\\.config\\.(?:m?[jt]s|cjs)$/.test(rel) ||\n rel.endsWith('.d.ts') ||\n rel.endsWith('.json') ||\n rel.endsWith('.sql') ||\n rel.endsWith('.md')\n )\n return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = path.join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(path.relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(path.join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(file: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(file, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${file} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? path.join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (isEntrypoint(import.meta.url)) {\n process.exit(checkGodFilesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAgDA,OAA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,IAAI,GAAGjB,EAAQ,QAAU,WAAa,WAAa,MAAM,IAAIA,EAAQ,KAAK,IAAIA,EAAQ,IAAI,EAAE,EAEtG,UAAWA,KAAWiB,EAAO,YAC3B,QAAQ,IAAI,eAAejB,EAAQ,KAAK,IAAIA,EAAQ,IAAI,EAAE,EAE5D,OAAKiB,EAAO,QACVpD,EAAK,0CAA0CqB,CAAI,qBAAqB,EAEnE,CACT,CA1BgBL,EAAA8B,EAAA,oBAmCZ7C,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAK6C,EAAiB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["readdirSync", "readFileSync", "statSync", "path", "fail", "isEntrypoint", "isSet", "parseFlags", "splitPositional", "valueOf", "SOFT_LIMIT", "HARD_LIMIT", "EXCLUDE_DIRS", "SOURCE_EXTENSIONS", "TEST_SUFFIXES", "kind", "ext", "shouldSkip", "rel", "suffix", "__name", "isAllowlisted", "allowlist", "entry", "walk", "root", "out", "visit", "dir", "full", "stat", "checkGodFiles", "options", "soft", "hard", "scanned", "findings", "allowlisted", "lines", "finding", "left", "right", "critical", "passed", "reported", "readAllowlist", "file", "raw", "parsed", "error", "checkGodFilesCli", "argv", "positional", "rest", "flags", "allowlistPath", "report"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this module is the process's entrypoint.
|
|
3
|
+
*
|
|
4
|
+
* The comparison needs **both** sides resolved through `realpathSync`, and that
|
|
5
|
+
* is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm
|
|
6
|
+
* that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the
|
|
7
|
+
* store — while `import.meta.url` is always the realpath, because the ESM
|
|
8
|
+
* resolver follows links. So the two never matched, the guard never fired, and
|
|
9
|
+
* every script below exited 0 having printed nothing.
|
|
10
|
+
*
|
|
11
|
+
* That is the worst shape a gate can fail in: it looks green. `check-god-files`
|
|
12
|
+
* reported no file over the limit for every repository that adopted it,
|
|
13
|
+
* `validate-locales` passed with a key missing from eleven bundles, and neither
|
|
14
|
+
* said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`
|
|
15
|
+
* and finding that the replacement stopped catching the defect the old one
|
|
16
|
+
* reported on the same tree.
|
|
17
|
+
*
|
|
18
|
+
* It is worth a function rather than an inline comparison because four scripts
|
|
19
|
+
* carry the same guard, and a shared helper is what makes the fifth correct
|
|
20
|
+
* instead of a fourth copy of the same mistake.
|
|
21
|
+
*
|
|
22
|
+
* A missing or unreadable entrypoint is not the entrypoint, and the caller
|
|
23
|
+
* exports the rule functions precisely so the module stays importable — a suite
|
|
24
|
+
* imports these to test the rules, and there `process.argv[1]` is the test file.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isEntrypoint(moduleUrl: string, argv1?: string | undefined): boolean;
|
|
27
|
+
//# sourceMappingURL=entrypoint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entrypoint.d.ts","sourceRoot":"","sources":["../../../src/scripts/lib/entrypoint.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,GAAG,SAA2B,GAAG,OAAO,CAUpG"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=Object.defineProperty;var e=(t,r)=>n(t,"name",{value:r,configurable:!0});import{realpathSync as o}from"node:fs";import{pathToFileURL as f}from"node:url";function c(t,r=process.argv[1]){if(r===void 0)return!1;try{return t===f(o(r)).href}catch{return!1}}e(c,"isEntrypoint");export{c as isEntrypoint};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/scripts/lib/entrypoint.ts"],
|
|
4
|
+
"sourcesContent": ["import { realpathSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\n\n/**\n * Whether this module is the process's entrypoint.\n *\n * The comparison needs **both** sides resolved through `realpathSync`, and that\n * is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm\n * that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the\n * store — while `import.meta.url` is always the realpath, because the ESM\n * resolver follows links. So the two never matched, the guard never fired, and\n * every script below exited 0 having printed nothing.\n *\n * That is the worst shape a gate can fail in: it looks green. `check-god-files`\n * reported no file over the limit for every repository that adopted it,\n * `validate-locales` passed with a key missing from eleven bundles, and neither\n * said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`\n * and finding that the replacement stopped catching the defect the old one\n * reported on the same tree.\n *\n * It is worth a function rather than an inline comparison because four scripts\n * carry the same guard, and a shared helper is what makes the fifth correct\n * instead of a fourth copy of the same mistake.\n *\n * A missing or unreadable entrypoint is not the entrypoint, and the caller\n * exports the rule functions precisely so the module stays importable — a suite\n * imports these to test the rules, and there `process.argv[1]` is the test file.\n */\nexport function isEntrypoint(moduleUrl: string, argv1: string | undefined = process.argv[1]): boolean {\n if (argv1 === undefined) {\n return false;\n }\n try {\n return moduleUrl === pathToFileURL(realpathSync(argv1)).href;\n } catch {\n // A path that does not resolve cannot be the file that is running.\n return false;\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,UAC7B,OAAS,iBAAAC,MAAqB,WA2BxB,SAAUC,EAAaC,EAAmBC,EAA4B,QAAQ,KAAK,CAAC,EAAC,CACzF,GAAIA,IAAU,OACZ,MAAO,GAET,GAAI,CACF,OAAOD,IAAcF,EAAcD,EAAaI,CAAK,CAAC,EAAE,IAC1D,MAAQ,CAEN,MAAO,EACT,CACF,CAVgBC,EAAAH,EAAA",
|
|
6
|
+
"names": ["realpathSync", "pathToFileURL", "isEntrypoint", "moduleUrl", "argv1", "__name"]
|
|
7
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import{existsSync as
|
|
1
|
+
var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import{isEntrypoint as S}from"./lib/entrypoint.js";import{existsSync as a,mkdirSync as y,readFileSync as h,writeFileSync as $}from"node:fs";import l from"node:path";const A="apps/api/src/generated/spa-shell.ts",T="apps/web/dist/index.html",v=`// Auto-generated stub - real content is produced by the build step via the Vite plugin.
|
|
2
2
|
export const SPA_HTML: string = '';
|
|
3
|
-
`,x=200;function d(t){const e=l.resolve(t.root),
|
|
3
|
+
`,x=200;function d(t){const e=l.resolve(t.root),n=l.join(e,t.shellPath??A),r=l.join(e,t.distIndexPath??T);return{shell:n,distIndex:r,distAssets:l.join(l.dirname(r),"assets")}}u(d,"resolvePaths");function p(t){const{shell:e}=d(t);y(l.dirname(e),{recursive:!0});try{$(e,v,{encoding:"utf8",flag:"wx"})}catch(n){if(n?.code==="EEXIST")return{created:!1,path:e};throw n}return{created:!0,path:e}}u(p,"ensureSpaShellStub");function w(t,e){if(!a(t))return e.push(`${t} is missing \u2014 run the build (only apps/web has a build step).`),null;const n=h(t,"utf8"),r="export const SPA_HTML: string = ",s=n.indexOf(r);if(s===-1)return e.push(`${t} does not export SPA_HTML \u2014 regenerate it with the build.`),null;const o=n.slice(s+r.length).replace(/;\s*$/,"");if(o==="''"||o==='""')return e.push(`${t} still holds the empty postinstall stub \u2014 run the build. Until then every browser navigation served by the API worker is a blank page.`),null;let i;try{i=JSON.parse(o)}catch{return e.push(`${t} is not the generated shape \u2014 delete it and run the build.`),null}return typeof i!="string"||i.length<x?(e.push(`${t} holds no usable HTML \u2014 run the build. Until then every browser navigation is a blank page.`),null):i}u(w,"readEmbeddedHtml");function f(t){const{shell:e,distIndex:n,distAssets:r}=d(t),s=[],o=w(e,s);if(o===null)return{problems:s};const i=[...o.matchAll(/(?:src|href)="\/assets\/([^"]+)"/g)].map(c=>c[1]);i.length===0&&s.push("The embedded shell references no /assets/ bundles \u2014 it is not a real build output.");for(const c of new Set(i))a(l.join(r,c))||s.push(`The embedded shell references /assets/${c}, which is not in ${r} \u2014 run the build.`);return a(n)?h(n,"utf8")!==o&&s.push(`${e} does not match ${n} \u2014 run the build.`):s.push(`${n} is missing \u2014 run the build.`),{problems:s}}u(f,"verifySpaShell");const b="verify|ensure";function g(t=process.argv.slice(2)){const e=t[0]??"verify";if(!b.split("|").includes(e))return console.error(`Usage: tsx spa-shell.ts <${b}> [repo-root]`),1;const n={root:t[1]??process.cwd()};if(e==="ensure"){const s=p(n);return s.created?console.log(`ensure-spa-shell-stub: created stub at ${s.path}`):console.log(`ensure-spa-shell-stub: ${s.path} already present, left untouched`),0}const{problems:r}=f(n);if(r.length>0){console.error("SPA shell check failed:");for(const s of r)console.error(` - ${s}`);return 1}return console.log("SPA shell check passed."),0}u(g,"spaShellCli");S(import.meta.url)&&process.exit(g(process.argv.slice(2)));export{p as ensureSpaShellStub,g as spaShellCli,f as verifySpaShell};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/spa-shell.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The SPA shell pair: `ensure-spa-shell-stub` + `verify-spa-shell`.\n *\n * Provenance: the `scripts/ensure-spa-shell-stub.mjs` +\n * `scripts/verify-spa-shell.mjs` pair (Durable-DAV) and Edge-Sonic's typed\n * `scripts/build/{ensure-spa-shell-stub,spa-shell-checks,verify-spa-shell}.ts`.\n * The generate step itself is a Vite plugin (`spaShellEmbedPlugin` in\n * `vite.ts`) because it must run on every build; this module holds the\n * freshness contract around the generated file.\n *\n * Why the pair exists: `apps/api/src/generated/spa-shell.ts` and\n * `apps/web/dist/` are both gitignored build artifacts. A fresh clone gets the\n * empty postinstall stub and every browser navigation returns a blank page,\n * with nothing in the source tree saying so.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "
|
|
4
|
+
"sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\n * The SPA shell pair: `ensure-spa-shell-stub` + `verify-spa-shell`.\n *\n * Provenance: the `scripts/ensure-spa-shell-stub.mjs` +\n * `scripts/verify-spa-shell.mjs` pair (Durable-DAV) and Edge-Sonic's typed\n * `scripts/build/{ensure-spa-shell-stub,spa-shell-checks,verify-spa-shell}.ts`.\n * The generate step itself is a Vite plugin (`spaShellEmbedPlugin` in\n * `vite.ts`) because it must run on every build; this module holds the\n * freshness contract around the generated file.\n *\n * Why the pair exists: `apps/api/src/generated/spa-shell.ts` and\n * `apps/web/dist/` are both gitignored build artifacts. A fresh clone gets the\n * empty postinstall stub and every browser navigation returns a blank page,\n * with nothing in the source tree saying so.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\ninterface SpaShellPaths {\n /**\n Repo root.\n */\n root: string;\n /**\n Generated TS module path, relative to root.\n */\n shellPath?: string;\n /**\n Built SPA index.html path, relative to root.\n */\n distIndexPath?: string;\n}\n\ninterface VerifyResult {\n problems: string[];\n}\n\nconst DEFAULT_SHELL = 'apps/api/src/generated/spa-shell.ts';\nconst DEFAULT_DIST_INDEX = 'apps/web/dist/index.html';\nconst STUB_CONTENT =\n \"// Auto-generated stub - real content is produced by the build step via the Vite plugin.\\nexport const SPA_HTML: string = '';\\n\";\n\n/**\nA built shell is a full Vite index.html; any small threshold rejects the stub.\n*/\nconst MIN_HTML_CHARS = 200;\n\nfunction resolvePaths(options: SpaShellPaths): { shell: string; distIndex: string; distAssets: string } {\n const root = path.resolve(options.root);\n const shell = path.join(root, options.shellPath ?? DEFAULT_SHELL);\n const distIndex = path.join(root, options.distIndexPath ?? DEFAULT_DIST_INDEX);\n return { shell, distIndex, distAssets: path.join(path.dirname(distIndex), 'assets') };\n}\n\n/**\n * Create the empty stub when (and only when) nothing is there yet, so a fresh\n * clone typechecks and `pnpm run build` regenerates the real thing. Never\n * overwrites an existing file — overwriting would erase a real build with a\n * stub on the next `pnpm install`.\n */\nfunction ensureSpaShellStub(options: SpaShellPaths): { created: boolean; path: string } {\n const { shell } = resolvePaths(options);\n mkdirSync(path.dirname(shell), { recursive: true });\n try {\n writeFileSync(shell, STUB_CONTENT, { encoding: 'utf8', flag: 'wx' });\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'EEXIST') {\n return { created: false, path: shell };\n }\n throw error;\n }\n return { created: true, path: shell };\n}\n\n/**\nThe `SPA_HTML` string literal, decoded from the generated TS module.\n*/\nfunction readEmbeddedHtml(shell: string, problems: string[]): string | null {\n if (!existsSync(shell)) {\n problems.push(`${shell} is missing — run the build (only apps/web has a build step).`);\n return null;\n }\n const source = readFileSync(shell, 'utf8');\n const marker = 'export const SPA_HTML: string = ';\n const at = source.indexOf(marker);\n if (at === -1) {\n problems.push(`${shell} does not export SPA_HTML — regenerate it with the build.`);\n return null;\n }\n const literal = source.slice(at + marker.length).replace(/;\\s*$/, '');\n if (literal === \"''\" || literal === '\"\"') {\n problems.push(\n `${shell} still holds the empty postinstall stub — run the build. Until then every browser navigation served by the API worker is a blank page.`,\n );\n return null;\n }\n let html: unknown;\n try {\n html = JSON.parse(literal);\n } catch {\n problems.push(`${shell} is not the generated shape — delete it and run the build.`);\n return null;\n }\n if (typeof html !== 'string' || html.length < MIN_HTML_CHARS) {\n problems.push(`${shell} holds no usable HTML — run the build. Until then every browser navigation is a blank page.`);\n return null;\n }\n return html;\n}\n\n/**\n * Fail when the shell the API worker serves is missing or self-inconsistent:\n *\n * - the postinstall stub (or no build at all) still in place;\n * - `/assets/...` bundles referenced but not emitted (a half-cleaned dist,\n * which serves a shell whose JS 404s);\n * - `spa-shell.ts` and `dist/index.html` disagreeing — only one half of the\n * build was refreshed.\n *\n * Known limit, stated rather than papered over: a *stale but self-consistent*\n * pair passes. That class is covered at the source level by each repo's SPA\n * parser integration test; the remaining duty is operational — run the build\n * after touching `apps/web`, before deploy.\n */\nfunction verifySpaShell(options: SpaShellPaths): VerifyResult {\n const { shell, distIndex, distAssets } = resolvePaths(options);\n const problems: string[] = [];\n const html = readEmbeddedHtml(shell, problems);\n if (html === null) {\n return { problems };\n }\n const referenced = [...html.matchAll(/(?:src|href)=\"\\/assets\\/([^\"]+)\"/g)].map((match) => match[1]);\n if (referenced.length === 0) {\n problems.push('The embedded shell references no /assets/ bundles — it is not a real build output.');\n }\n for (const asset of new Set(referenced)) {\n if (!existsSync(path.join(distAssets, asset))) {\n problems.push(`The embedded shell references /assets/${asset}, which is not in ${distAssets} — run the build.`);\n }\n }\n if (!existsSync(distIndex)) {\n problems.push(`${distIndex} is missing — run the build.`);\n } else if (readFileSync(distIndex, 'utf8') !== html) {\n problems.push(`${shell} does not match ${distIndex} — run the build.`);\n }\n return { problems };\n}\n\nconst CLI_SHAPES = 'verify|ensure';\n\n/**\nCLI entry: `spaShellCli(['verify'|'ensure', 'repo-root?'])`.\n*/\nfunction spaShellCli(argv: readonly string[] = process.argv.slice(2)): number {\n const mode = argv[0] ?? 'verify';\n if (!CLI_SHAPES.split('|').includes(mode)) {\n console.error(`Usage: tsx spa-shell.ts <${CLI_SHAPES}> [repo-root]`);\n return 1;\n }\n const options: SpaShellPaths = { root: argv[1] ?? process.cwd() };\n if (mode === 'ensure') {\n const result = ensureSpaShellStub(options);\n if (result.created) {\n console.log(`ensure-spa-shell-stub: created stub at ${result.path}`);\n } else {\n console.log(`ensure-spa-shell-stub: ${result.path} already present, left untouched`);\n }\n return 0;\n }\n const { problems } = verifySpaShell(options);\n if (problems.length > 0) {\n console.error('SPA shell check failed:');\n for (const problem of problems) console.error(` - ${problem}`);\n return 1;\n }\n console.log('SPA shell check passed.');\n return 0;\n}\n\nexport { ensureSpaShellStub, spaShellCli, verifySpaShell };\nexport type { SpaShellPaths, VerifyResult };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (isEntrypoint(import.meta.url)) {\n process.exit(spaShellCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBAgB7B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YAqBjB,MAAMC,EAAgB,sCAChBC,EAAqB,2BACrBC,EACJ;;EAKIC,EAAiB,IAEvB,SAASC,EAAaC,EAAsB,CAC1C,MAAMC,EAAOP,EAAK,QAAQM,EAAQ,IAAI,EAChCE,EAAQR,EAAK,KAAKO,EAAMD,EAAQ,WAAaL,CAAa,EAC1DQ,EAAYT,EAAK,KAAKO,EAAMD,EAAQ,eAAiBJ,CAAkB,EAC7E,MAAO,CAAE,MAAAM,EAAO,UAAAC,EAAW,WAAYT,EAAK,KAAKA,EAAK,QAAQS,CAAS,EAAG,QAAQ,CAAC,CACrF,CALSC,EAAAL,EAAA,gBAaT,SAASM,EAAmBL,EAAsB,CAChD,KAAM,CAAE,MAAAE,CAAK,EAAKH,EAAaC,CAAO,EACtCT,EAAUG,EAAK,QAAQQ,CAAK,EAAG,CAAE,UAAW,EAAI,CAAE,EAClD,GAAI,CACFT,EAAcS,EAAOL,EAAc,CAAE,SAAU,OAAQ,KAAM,IAAI,CAAE,CACrE,OAASS,EAAO,CACd,GAAKA,GAAiC,OAAS,SAC7C,MAAO,CAAE,QAAS,GAAO,KAAMJ,CAAK,EAEtC,MAAMI,CACR,CACA,MAAO,CAAE,QAAS,GAAM,KAAMJ,CAAK,CACrC,CAZSE,EAAAC,EAAA,sBAiBT,SAASE,EAAiBL,EAAeM,EAAkB,CACzD,GAAI,CAAClB,EAAWY,CAAK,EACnB,OAAAM,EAAS,KAAK,GAAGN,CAAK,oEAA+D,EAC9E,KAET,MAAMO,EAASjB,EA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EAInD,CAAE,SAAAK,CAAQ,CACnB,CAtBSJ,EAAAU,EAAA,kBAwBT,MAAMK,EAAa,gBAKnB,SAASC,EAAYC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAClE,MAAMC,EAAOD,EAAK,CAAC,GAAK,SACxB,GAAI,CAACF,EAAW,MAAM,GAAG,EAAE,SAASG,CAAI,EACtC,eAAQ,MAAM,4BAA4BH,CAAU,eAAe,EAC5D,EAET,MAAMnB,EAAyB,CAAE,KAAMqB,EAAK,CAAC,GAAK,QAAQ,IAAG,CAAE,EAC/D,GAAIC,IAAS,SAAU,CACrB,MAAMC,EAASlB,EAAmBL,CAAO,EACzC,OAAIuB,EAAO,QACT,QAAQ,IAAI,0CAA0CA,EAAO,IAAI,EAAE,EAEnE,QAAQ,IAAI,0BAA0BA,EAAO,IAAI,kCAAkC,EAE9E,CACT,CACA,KAAM,CAAE,SAAAf,CAAQ,EAAKM,EAAed,CAAO,EAC3C,GAAIQ,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWgB,KAAWhB,EAAU,QAAQ,MAAM,OAAOgB,CAAO,EAAE,EAC9D,MAAO,EACT,CACA,eAAQ,IAAI,yBAAyB,EAC9B,CACT,CAxBSpB,EAAAgB,EAAA,eAoCL/B,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAK+B,EAAY,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["isEntrypoint", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "DEFAULT_SHELL", "DEFAULT_DIST_INDEX", "STUB_CONTENT", "MIN_HTML_CHARS", "resolvePaths", "options", "root", "shell", "distIndex", "__name", "ensureSpaShellStub", "error", "readEmbeddedHtml", "problems", "source", "marker", "at", "literal", "html", "verifySpaShell", "distAssets", "referenced", "match", "asset", "CLI_SHAPES", "spaShellCli", "argv", "mode", "result", "problem"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`&&(o=!1);continue}const c=e[s+1];if(n){r==="*"&&c==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&c==="-"){o=!0;continue}if(r==="/"&&c==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&c!=="="&&c!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const l=e.indexOf("{",s);return l===-1?-1:l}}return-1}f(
|
|
3
|
-
`&&(c=!1);continue}const m=e[h+1];if(a){d==="*"&&m==="/"&&(a=!1,h+=1);continue}if(r!==""){if(d==="\\"){h+=1;continue}d===r&&(r="");continue}if(d==="-"&&m==="-"){c=!0;continue}if(d==="/"&&m==="*"){a=!0;continue}if(d==="'"||d==='"'||d==="`"){r=d;continue}if(d==="{")n+=1;else if(d==="}"&&(n-=1,n===0)){s=h;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const u=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(h,d)=>JSON.stringify(
|
|
4
|
-
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(
|
|
5
|
-
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}f(q,"decodeStringLiteral");function B(e){const t=new Set;for(const o of
|
|
1
|
+
var v=Object.defineProperty;var f=(e,t)=>v(e,"name",{value:t,configurable:!0});import{isEntrypoint as L}from"./lib/entrypoint.js";import{existsSync as $,readdirSync as w,readFileSync as g}from"node:fs";import y from"node:path";function b(e,t="",o=new Map){if(e===null||typeof e!="object"||Array.isArray(e))return t&&o.set(t,e),o;const n=Object.entries(e);if(n.length===0)return t&&o.set(t,e),o;for(const[s,r]of n)b(r,t?`${t}.${s}`:s,o);return o}f(b,"flatten");function x(e){return typeof e!="string"?[]:[...new Set(e.match(/\{\{[^{}]+\}\}/g))].sort((t,o)=>t.localeCompare(o))}f(x,"placeholdersOf");function A(e){const t=g(e,"utf8");return e.endsWith(".ts")?O(t,e):JSON.parse(t)}f(A,"readBundle");function _(e){let t="",o=!1,n=!1;for(let s=0;s<e.length;s+=1){const r=e[s];if(o){r===`
|
|
2
|
+
`&&(o=!1);continue}const c=e[s+1];if(n){r==="*"&&c==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&c==="-"){o=!0;continue}if(r==="/"&&c==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&c!=="="&&c!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const l=e.indexOf("{",s);return l===-1?-1:l}}return-1}f(_,"objectLiteralStart");function O(e,t){const o=_(e);if(o===-1)throw new Error(`${t} has no object literal`);let n=0,s=-1,r="",c=!1,a=!1;for(let h=o;h<e.length;h+=1){const d=e[h];if(c){d===`
|
|
3
|
+
`&&(c=!1);continue}const m=e[h+1];if(a){d==="*"&&m==="/"&&(a=!1,h+=1);continue}if(r!==""){if(d==="\\"){h+=1;continue}d===r&&(r="");continue}if(d==="-"&&m==="-"){c=!0;continue}if(d==="/"&&m==="*"){a=!0;continue}if(d==="'"||d==='"'||d==="`"){r=d;continue}if(d==="{")n+=1;else if(d==="}"&&(n-=1,n===0)){s=h;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const u=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(h,d)=>JSON.stringify(J(d))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(u)}catch(h){throw new Error(`${t} object literal could not be parsed: ${h instanceof Error?h.message:String(h)}`)}}f(O,"parseObjectLiteral");function J(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
|
|
4
|
+
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(J,"unescapeLiteral");const j={file:"json",module:"ts"};function S(e){return e==="auto"?["dir","file","module"]:[e]}f(S,"layouts");function C(e,t){const o=[];S(t).includes("dir")&&o.push(...w(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of S(t)){if(n==="dir")continue;const s=j[n];o.push(...w(e).filter(r=>r.endsWith(`.${s}`)).map(r=>r.slice(0,-s.length-1)))}return o}f(C,"tagsOnDisk");function k(e,t,o){const n=[];S(o).includes("dir")&&n.push(y.join(e,t,"translation.json"));for(const s of S(o))s!=="dir"&&n.push(y.join(e,`${t}.${j[s]}`));return n.find(s=>$(s))}f(k,"bundleFor");function U(e,t,o){const n=k(e,t,o);if(n===void 0)throw new Error(`no bundle found for the base locale (expected ${t}/translation.json)`);return b(A(n))}f(U,"bundleAt");function N(e,t="en",o="auto"){const n=[];if(!$(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const s=k(e,t,o);if(s===void 0)return n.push({locale:t,problem:`no bundle found for the base locale (expected ${t}/translation.json)`}),{locales:[],keys:0,problems:n};let r;try{r=b(A(s))}catch(l){return n.push({locale:t,problem:`${s}: ${l instanceof Error?l.message:String(l)}`}),{locales:[],keys:0,problems:n}}const c=new Set(r.keys());if(c.size===0)return n.push({locale:t,problem:`${s} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const a=[...new Set([...C(e,o),t])].sort((l,p)=>l.localeCompare(p));for(const l of a){const p=k(e,l,o);if(p===void 0){n.push({locale:l,problem:"no bundle found"});continue}let i;try{i=b(A(p))}catch(u){n.push({locale:l,problem:`${p}: ${u instanceof Error?u.message:String(u)}`});continue}for(const u of c)i.has(u)||n.push({locale:l,problem:`missing key: ${u}`});for(const[u,h]of i){if(!c.has(u)){n.push({locale:l,problem:`extra key not in ${t}: ${u}`});continue}if(typeof h!="string"||h===""){n.push({locale:l,problem:`empty value: ${u} \u2014 indistinguishable from a missing key at runtime`});continue}const d=x(r.get(u));if(d.length===0)continue;const m=x(h);(d.length!==m.length||d.some((P,W)=>P!==m[W]))&&n.push({locale:l,problem:`placeholder mismatch at ${u}: ${l} has ${JSON.stringify(m)}, ${t} has ${JSON.stringify(d)}`})}}return{locales:a,keys:c.size,problems:n}}f(N,"validateLocales");function F(e,t,o){const n=[];for(const s of E(e)){const r=g(s,"utf8"),c=/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;for(const a of r.matchAll(c)){const l=a[2];if(l.includes("${")||l.includes("{{"))continue;const p=y.relative(process.cwd(),s)||s;if(!t.has(l)){n.push({locale:"call-site",problem:`${p}: t('${l}') is not in the bundle \u2014 it renders as the inline default and is untranslatable`});continue}if(!a[3])continue;const i=K(r,a.index+a[0].length);if(i===null)continue;const u=o.get(l);i!==u&&n.push({locale:"call-site",problem:`${p}: t('${l}', \u2026) default disagrees with the bundle \u2014 bundle=${JSON.stringify(u)} default=${JSON.stringify(i)}`})}}return n}f(F,"collectCallSites");function K(e,t){const o=e.slice(t).replace(/^\s+/,""),n=o[0];if(n!=="'"&&n!=='"')return null;const s=o.slice(1),c=(n==="'"?/^(?:[^'\\]|\\.)*'/:/^(?:[^"\\]|\\.)*"/).exec(s);return c?q(s.slice(0,c[0].length-1)):null}f(K,"readDefault");function q(e){return e.replaceAll(/\\(.)/gs,(t,o)=>{switch(o){case"n":return`
|
|
5
|
+
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}f(q,"decodeStringLiteral");function B(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1/g)){const s=n[2];!s.includes("${")&&!s.includes("{{")&&t.add(s)}return t}f(B,"usedKeys");function E(e){const t=[],o=f(n=>{for(const s of w(n,{withFileTypes:!0})){const r=y.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules"||s.name==="dist"||s.name==="coverage")continue;o(r);continue}e.extensions.some(c=>s.name.endsWith(c))&&t.push(r)}},"walk");return o(e.dir),t}f(E,"sourceFiles");function G(e,t,o){const n=R(t),s=e.filter(r=>!o.has(r)&&[...n].every(c=>!(r===c||r.startsWith(`${c}.`))));return s.length===0?[]:[{locale:"call-site",problem:`${s.length} base key(s) are not reached by any t() call site: ${s.slice(0,20).join(", ")}${s.length>20?", \u2026":""}`,advisory:!0}]}f(G,"collectUnusedKeys");function R(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*`([^`$]*)\$\{/g)){const s=n[1].replace(/\.$/,"");s&&t.add(s)}return t}f(R,"dynamicKeyPrefixes");function z(e){const t=g(e,"utf8"),o=/(?:export\s+)?const\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\s*=\s*\[([^\]]*)\]/.exec(t);if(!o)throw new Error(`${e} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);return[...(o[1]??"").matchAll(/['"]([^'"]+)['"]/g)].map(n=>n[1])}f(z,"declaredTags");function D(e,t,o){const n=z(t),s=[];for(const r of n)o.includes(r)||s.push({locale:"tags",problem:`${t} declares '${r}' but ${e}/${r} does not exist \u2014 selecting that language throws`});for(const r of o)n.includes(r)||s.push({locale:"tags",problem:`${e}/${r} exists but ${t} does not declare it \u2014 the selector cannot offer it`});return s}f(D,"checkDeclaredTags");function T(e=process.argv.slice(2)){const t=e.find(i=>!i.startsWith("--"))??"apps/web/src/locales",o=e.find(i=>i.startsWith("--shape="))?.slice(8)??"auto",n=e.find(i=>i.startsWith("--base="))?.slice(7)??"en",s=e.find(i=>i.startsWith("--call-sites="))?.slice(13),r=e.find(i=>i.startsWith("--tags="))?.slice(7),c=N(t,n,o),a=[...c.problems];if(r!==void 0&&$(r))try{a.push(...D(t,r,C(t,o)))}catch(i){a.push({locale:"tags",problem:`${r}: ${i instanceof Error?i.message:String(i)}`})}if(s!==void 0&&$(s))try{const i=U(t,n,o),u={dir:s,extensions:[".ts",".tsx"]},h=B(u);a.push(...F(u,new Set(i.keys()),i),...G([...i.keys()],u,h))}catch(i){a.push({locale:"call-site",problem:`${s}: ${i instanceof Error?i.message:String(i)}`})}const l=a.filter(i=>i.advisory!==!0),p=a.filter(i=>i.advisory===!0);if(l.length>0){console.error(`Locale validation failed for ${t} (${l.length} problem(s)):`);for(const i of l)console.error(` - ${i.locale}: ${i.problem}`);return 1}if(p.length>0){console.warn(`Locale validation passed for ${t} with ${p.length} advisory finding(s):`);for(const i of p)console.warn(` - ${i.locale}: ${i.problem}`)}return console.log(`Locale validation passed (${c.locales.length} locales, ${c.keys} keys each, shape ${o}).`),0}f(T,"validateLocalesCli");L(import.meta.url)&&process.exit(T(process.argv.slice(2)));export{O as parseObjectLiteral,N as validateLocales,T as validateLocalesCli};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/validate-locales.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Validate that every locale bundle carries exactly the base locale's keys.\n *\n * Provenance: `scripts/validate_locales.{mjs,ts}` in Durable-DAV, Edge-Git and\n * Mail-Meow, and Edge-Sonic's `scripts/i18n/locale-checks.ts` +\n * `validate_locales.ts`, converged. All four copies agree on the contract:\n * flattened dotted key paths, two-way parity (missing AND extra), no empty values,\n * no stray placeholders.\n *\n * ### What the convergence added\n *\n * Edge-Sonic's is the only copy that checks what a value *is*. The rest compare\n * bundle to bundle, so with one shipped language the whole per-tag body is skipped\n * and the script reports `ALL OK` having checked nothing about the application — it\n * could not see that `libraries.scanPausedRequests` was used and absent, because\n * the string in the bundle did not exist to be wrong *about* anything. Hence\n * `--call-sites`: every `t('key')` under `apps/web/src` must resolve.\n *\n * Key **order** drift against the base is a warning, not a failure: locale files\n * are maintained by mirroring new keys into every file, and failing on order would\n * turn an otherwise-correct translation update into a CI failure about formatting.\n *\n * ### Three on-disk shapes, one checker\n *\n * The family ships bundles in three shapes, and the shape is an argument rather\n * than a fork of the script:\n *\n * - `auto` (default) — every layout below, tried in order, so a repo that has\n * half-migrated is reported rather than silently skipped;\n * - `dir` — `<locales-dir>/<tag>/translation.json`, the i18next layout used by\n * seven repos;\n * - `file` — `<locales-dir>/<tag>.json`, one flat file per tag;\n * - `module` — `<locales-dir>/<tag>.ts` exporting an object literal, which is the\n * shape `@rexezuge/i18n` uses for the backend string bundles. The literal is\n * extracted and normalised here, so the same gate covers the backend catalogs\n * the kit ships and the SPA bundles the repos do.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\n\n/**\nThe bundle layouts the checker understands.\n*/\ntype LocaleShape = 'auto' | 'dir' | 'file' | 'module';\n\n/**\nOne defect, kept as a locale plus a message so a caller can group them.\n*/\ninterface LocaleProblem {\n locale: string;\n problem: string;\n /**\n * Reported, but not a failure.\n *\n * The distinction is **\"this build is wrong\"** against **\"this merge is still\n * in flight\"**, and a gate that cannot tell them apart gets switched off. A\n * key the bundles carry that no call site reaches is the ordinary state of a\n * bundle running ahead of its UI, and a translator adding a string for a screen\n * that has not been wired is doing the right thing. It is also the only thing\n * that catches a call site deleted or renamed without its key — which keeps a\n * translator re-translating a string no user will ever see.\n *\n * So it is reported and it does not fail the run.\n *\n * The finding that is **not** advisory is the mirror: a `t()` key the bundle\n * lacks. That one renders the inline default for every user in every language,\n * it is actionable in the same commit, and there is no in-flight state in which\n * it is the right answer — so it stays fatal, and the report below prints the\n * two classes separately rather than counting them together.\n */\n advisory?: boolean;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface LocaleReport {\n locales: string[];\n keys: number;\n problems: LocaleProblem[];\n}\n\n/**\nEvery dotted key path in a bundle, depth first.\n*/\nfunction flatten(value: unknown, prefix = '', out: Map<string, unknown> = new Map()): Map<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n for (const [key, child] of entries) {\n flatten(child, prefix ? `${prefix}.${key}` : key, out);\n }\n return out;\n}\n\n/**\n * The interpolation tokens in a value, sorted.\n *\n * Sorted so two values carrying the same tokens in different orders compare equal —\n * substitution is by name, so order carries no meaning. `localeCompare` rather than\n * the default comparator so a reported mismatch does not change with the machine's\n * locale.\n */\nfunction placeholdersOf(value: unknown): string[] {\n if (typeof value !== 'string') return [];\n return [...new Set(value.match(/\\{\\{[^{}]+\\}\\}/g))].sort((left: string, right: string) => left.localeCompare(right));\n}\n\n/**\n * A source file to check `t()` call sites under, and how far down to look.\n */\ninterface CallSiteScope {\n /**\n Directory walked for source files.\n */\n dir: string;\n /**\n Extensions treated as source.\n */\n extensions: readonly string[];\n}\n\n/**\n * Read a bundle as a value, in whichever shape it is written.\n *\n * `module` is the shape `@rexezuge/i18n` ships: `const enStrings: BackendStrings =\n * { common: { unauthorized: '…' } };`. Extracting the literal rather than importing\n * the module is the point — a validator that imported the bundle would typecheck it\n * against the kit's own types, and therefore agree with whatever it was given.\n */\nfunction readBundle(file: string): unknown {\n const source = readFileSync(file, 'utf8');\n // Decided by the file's extension, not by the caller's `shape`: under `auto` a\n // `.ts` bundle is found, and reading it as JSON would report a parse error for a\n // file that is perfectly well-formed.\n return file.endsWith('.ts') ? parseObjectLiteral(source, file) : (JSON.parse(source) as unknown);\n}\n\n/**\n * The first balanced object literal in a TypeScript module, as a value.\n *\n * Brace-matched outside strings and comments, and started at the **first\n * assignment** rather than at the first brace — see `objectLiteralStart` for why the\n * difference is the whole rule. Single-quoted strings are normalised to\n * double-quoted JSON, bare keys are quoted, and trailing commas are tolerated: that\n * is all the shape this needs, and a translator file that needs more is not a\n * translator file.\n */\n/**\n * Where the object literal begins: the first brace **after the first assignment**.\n *\n * The assignment matters. `const enStrings: BackendStrings = { ... }` is preceded by\n * an import line whose own braces open earlier in the file, so a plain\n * `indexOf('{')` returns the import's pair and the \"literal\" extracted is\n * `{ BackendStrings }` — an empty object that parses cleanly and then reports the\n * base bundle as having no keys. Finding the assignment first skips every brace that\n * is not the value being bound to it.\n */\nfunction objectLiteralStart(source: string): number {\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n // The assignment, and not a comparison or an arrow: `=>` and `==` both contain an\n // `=`, and neither is where a bundle's object literal is attached.\n const previous = source[index - 1];\n if (char === '=' && next !== '=' && next !== '>' && previous !== '=' && previous !== '!' && previous !== '<' && previous !== '>') {\n const brace = source.indexOf('{', index);\n return brace === -1 ? -1 : brace;\n }\n }\n return -1;\n}\n\nfunction parseObjectLiteral(source: string, file: string): unknown {\n const start = objectLiteralStart(source);\n if (start === -1) {\n throw new Error(`${file} has no object literal`);\n }\n\n let depth = 0;\n let end = -1;\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = start; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n // An escape consumes the next character, so `\\'` does not close the string.\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n end = index;\n break;\n }\n }\n }\n if (end === -1) {\n throw new Error(`${file} has an unterminated object literal`);\n }\n\n const literal = source.slice(start, end + 1);\n // Three normalisations, each of which a JSON parser needs and a TS literal does not:\n // single-quoted strings become double-quoted (applied only to string literals, so a\n // value containing an apostrophe keeps it), bare keys get quoted, and trailing\n // commas are dropped. A translator file that needs more than that is not a\n // translator file.\n const doubleQuoted = literal.replaceAll(/'((?:[^'\\\\]|\\\\.)*)'/g, (_match, body: string) => JSON.stringify(unescapeLiteral(body)));\n const quotedKeys = doubleQuoted.replaceAll(/([{,]\\s*)([A-Z_$][\\w$]*)(\\s*:)/gi, '$1\"$2\"$3');\n const withoutTrailingCommas = quotedKeys.replaceAll(/,(\\s*[}\\]])/g, '$1');\n\n try {\n return JSON.parse(withoutTrailingCommas) as unknown;\n } catch (error: unknown) {\n throw new Error(`${file} object literal could not be parsed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\nThe escapes a translator file actually uses; anything else is passed through.\n*/\nfunction unescapeLiteral(body: string): string {\n return body\n .replaceAll(String.raw`\\'`, \"'\")\n .replaceAll(String.raw`\\\"`, '\"')\n .replaceAll(String.raw`\\n`, '\\n')\n .replaceAll(String.raw`\\t`, '\\t')\n .replaceAll(String.raw`\\\\`, '\\\\');\n}\n\n/**\nThe extensions a flat layout uses, keyed by shape.\n*/\nconst FLAT_EXTENSION: Record<'file' | 'module', string> = { file: 'json', module: 'ts' };\n\n/**\nThe layouts `shape` covers. `auto` covers all three, in the order they are tried.\n*/\nfunction layouts(shape: LocaleShape): Array<'dir' | 'file' | 'module'> {\n return shape === 'auto' ? ['dir', 'file', 'module'] : [shape];\n}\n\n/**\nThe tags on disk, in whichever layouts `shape` covers.\n*/\nfunction tagsOnDisk(localesDir: string, shape: LocaleShape): string[] {\n const tags: string[] = [];\n if (layouts(shape).includes('dir')) {\n tags.push(\n ...readdirSync(localesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name),\n );\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n const extension = FLAT_EXTENSION[layout];\n tags.push(\n ...readdirSync(localesDir)\n .filter((name) => name.endsWith(`.${extension}`))\n .map((name) => name.slice(0, -extension.length - 1)),\n );\n }\n return tags;\n}\n\n/**\n * The file a tag's bundle lives in, or `undefined` when it is not there.\n *\n * Every candidate is tried rather than only the one `shape` names, because a repo\n * with a half-migrated tree is a repo whose missing half should be reported. A\n * checker that only looked where it was told would read a bundle that exists as\n * absent, and a missing bundle is the defect this script exists to find.\n */\nfunction bundleFor(localesDir: string, locale: string, shape: LocaleShape): string | undefined {\n const candidates: string[] = [];\n if (layouts(shape).includes('dir')) {\n candidates.push(path.join(localesDir, locale, 'translation.json'));\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n candidates.push(path.join(localesDir, `${locale}.${FLAT_EXTENSION[layout]}`));\n }\n return candidates.find((candidate) => existsSync(candidate));\n}\n\n/**\n * The base bundle, flattened, for a scope that checks the application against it.\n *\n * @throws when the bundle cannot be found or parsed — the caller reports that as a\n * problem rather than reporting \"all clear\" against an empty key set, which is\n * the one outcome a locale gate must never produce silently.\n */\nfunction bundleAt(localesDir: string, baseLocale: string, shape: LocaleShape): Map<string, unknown> {\n const file = bundleFor(localesDir, baseLocale, shape);\n if (file === undefined) {\n throw new Error(`no bundle found for the base locale (expected ${baseLocale}/translation.json)`);\n }\n return flatten(readBundle(file));\n}\n\n/**\n * Validate a directory of locale bundles against `baseLocale`'s key set.\n *\n * Two-way parity: a key the base has and a bundle lacks renders the fallback, and\n * a key a bundle has that the base lacks is dead weight nothing can translate from.\n */\nfunction validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleShape = 'auto'): LocaleReport {\n const problems: LocaleProblem[] = [];\n if (!existsSync(localesDir)) {\n problems.push({ locale: baseLocale, problem: `${localesDir} does not exist` });\n return { locales: [], keys: 0, problems };\n }\n\n const baseFile = bundleFor(localesDir, baseLocale, shape);\n if (baseFile === undefined) {\n problems.push({ locale: baseLocale, problem: `no bundle found for the base locale (expected ${baseLocale}/translation.json)` });\n return { locales: [], keys: 0, problems };\n }\n\n let baseBundle: Map<string, unknown>;\n try {\n baseBundle = flatten(readBundle(baseFile));\n } catch (error: unknown) {\n problems.push({ locale: baseLocale, problem: `${baseFile}: ${error instanceof Error ? error.message : String(error)}` });\n return { locales: [], keys: 0, problems };\n }\n const baseKeys = new Set(baseBundle.keys());\n\n if (baseKeys.size === 0) {\n // An empty base is the one defect that reaches the most users: it is the fallback\n // for every missing key, so an empty value here is indistinguishable from a\n // missing bundle at runtime.\n problems.push({ locale: baseLocale, problem: `${baseFile} has no keys — the base bundle is empty or unreadable` });\n return { locales: [baseLocale], keys: 0, problems };\n }\n\n const locales = [...new Set([...tagsOnDisk(localesDir, shape), baseLocale])].sort((a, b) => a.localeCompare(b));\n for (const locale of locales) {\n const file = bundleFor(localesDir, locale, shape);\n if (file === undefined) {\n problems.push({ locale, problem: 'no bundle found' });\n continue;\n }\n let bundle: Map<string, unknown>;\n try {\n bundle = flatten(readBundle(file));\n } catch (error: unknown) {\n problems.push({ locale, problem: `${file}: ${error instanceof Error ? error.message : String(error)}` });\n continue;\n }\n for (const key of baseKeys) {\n if (!bundle.has(key)) problems.push({ locale, problem: `missing key: ${key}` });\n }\n for (const [key, value] of bundle) {\n if (!baseKeys.has(key)) {\n problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });\n continue;\n }\n // An empty value is reported for the base too. i18next renders `''` for a key\n // whose value is empty and for a key that is absent, so the two are the same\n // blank screen — which is why a \"translated\" locale can look complete in a\n // diff and be missing on the page.\n if (typeof value !== 'string' || value === '') {\n problems.push({ locale, problem: `empty value: ${key} — indistinguishable from a missing key at runtime` });\n continue;\n }\n // Placeholder parity. Substitution is by name, so a translation that drops\n // `{{count}}` renders the sentence with a hole in it and no error anywhere.\n const expected = placeholdersOf(baseBundle.get(key));\n if (expected.length === 0) continue;\n const actual = placeholdersOf(value);\n if (expected.length !== actual.length || expected.some((token, index) => token !== actual[index])) {\n problems.push({\n locale,\n problem: `placeholder mismatch at ${key}: ${locale} has ${JSON.stringify(actual)}, ${baseLocale} has ${JSON.stringify(expected)}`,\n });\n }\n }\n }\n\n return { locales, keys: baseKeys.size, problems };\n}\n\n/**\n * Every `t('key')` call site under a scope, with its inline default if it has one.\n *\n * This is the only part of the check that reaches the application rather than the\n * bundles: the rest compare bundle to bundle, so with one shipped language the whole\n * per-tag body is skipped and the script reports `ALL OK` having checked nothing\n * about the product — it cannot see that a key was used and absent, because the\n * string in the bundle did not exist to be wrong *about* anything.\n *\n * Dynamic keys cannot be resolved statically and are skipped rather than guessed:\n * a computed key that happens to start with a literal is a finding nobody can act\n * on, and one finding nobody can act on trains people to ignore the report.\n */\nfunction collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {\n const problems: LocaleProblem[] = [];\n for (const full of sourceFiles(scope)) {\n const source = readFileSync(full, 'utf8');\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n const pattern = /\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1\\s*(,)?/g;\n for (const match of source.matchAll(pattern)) {\n const key = match[2];\n if (key.includes('${') || key.includes('{{')) continue;\n const where = path.relative(process.cwd(), full) || full;\n if (!baseKeys.has(key)) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,\n });\n continue;\n }\n // A default that disagrees with the shipped bundle **fails**: one of the two\n // is a bug, and the default is the one that renders verbatim the day the key\n // goes missing — which is the fallback path the whole check is about.\n if (!match[3]) continue;\n const inline = readDefault(source, match.index + match[0].length);\n if (inline === null) continue;\n const bundled = baseBundle.get(key);\n if (inline !== bundled) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,\n });\n }\n }\n }\n return problems;\n}\n\n/**\n * The first string literal at `from`, or `null` when the next token is not one.\n *\n * The terminator is the literal's **own** quote character and never the other one.\n * A default that contains an apostrophe is the ordinary case here — these bundles\n * say things like `D1's daily write allowance` — so a scan that accepts either\n * quote stops at the apostrophe and reports `D1` as the whole default, turning a\n * correct file into a \"default disagrees\" failure on every line that quotes an\n * English possessive.\n */\nfunction readDefault(source: string, from: number): string | null {\n const rest = source.slice(from).replace(/^\\s+/, '');\n const quote = rest[0];\n if (quote !== \"'\" && quote !== '\"') return null;\n const body = rest.slice(1);\n const closer = quote === \"'\" ? /^(?:[^'\\\\]|\\\\.)*'/ : /^(?:[^\"\\\\]|\\\\.)*\"/;\n const match = closer.exec(body);\n if (!match) return null;\n return decodeStringLiteral(body.slice(0, match[0].length - 1));\n}\n\n/**\n * Decode a JS string literal as written in source, escapes and all.\n *\n * Only the escapes these bundles use are handled. An unrecognised one is passed\n * through as the backslash plus the character rather than throwing: a validator\n * that crashes on an unfamiliar escape reports nothing at all, which is worse than\n * reporting a value it had to guess at.\n */\nfunction decodeStringLiteral(raw: string): string {\n return raw.replaceAll(/\\\\(.)/gs, (whole, char: string) => {\n switch (char) {\n case 'n': {\n return '\\n';\n }\n case 't': {\n return '\\t';\n }\n case 'r': {\n return '\\r';\n }\n case '\\\\':\n case \"'\":\n case '\"':\n case '`': {\n return char;\n }\n default: {\n return whole;\n }\n }\n });\n}\n\n/**\n * Every key a `t()` call site names literally, under one scope.\n *\n * Extracted from {@link collectCallSites} so the unused-key sweep and the\n * unresolved-key check read the **same** set. Two scanners that each carry their\n * own idea of what a call site looks like disagree on exactly the interesting\n * case — a shape one understands and the other does not — and then report a key\n * as both unused and used.\n */\nfunction usedKeys(scope: CallSiteScope): Set<string> {\n const used = new Set<string>();\n for (const file of sourceFiles(scope)) {\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1/g)) {\n const key = match[2];\n if (!key.includes('${') && !key.includes('{{')) used.add(key);\n }\n }\n return used;\n}\n\n/**\n * Every source file a scope covers, walking the skip list once.\n */\nfunction sourceFiles(scope: CallSiteScope): string[] {\n const files: string[] = [];\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;\n walk(full);\n continue;\n }\n if (scope.extensions.some((extension) => entry.name.endsWith(extension))) files.push(full);\n }\n };\n walk(scope.dir);\n return files;\n}\n\n/**\n * Base-bundle keys that no `t()` call site reaches.\n *\n * Advisory by construction, and for the reason {@link LocaleProblem.advisory}\n * gives: a bundle routinely runs ahead of its UI, and a translator adding a\n * string for a screen that has not been wired is doing the right thing. What it\n * also catches is the case that matters — a renamed or deleted call site whose\n * key was never removed, which keeps a translator re-translating a string no\n * user will ever see.\n *\n * Dynamic keys are **not** reported as unused. `` t(`section.${name}`) `` cannot\n * be resolved statically, so every key under that prefix would look dead; the\n * honest answer is \"unknown\", and an `unknown` reported as `unused` is the kind\n * of finding that makes a gate useless.\n */\nfunction collectUnusedKeys(baseKeys: readonly string[], scope: CallSiteScope, used: Set<string>): LocaleProblem[] {\n const prefixes = dynamicKeyPrefixes(scope);\n const unused = baseKeys.filter(\n (key) => !used.has(key) && [...prefixes].every((prefix) => !(key === prefix || key.startsWith(`${prefix}.`))),\n );\n if (unused.length === 0) return [];\n return [\n {\n locale: 'call-site',\n problem: `${unused.length} base key(s) are not reached by any t() call site: ${unused.slice(0, 20).join(', ')}${unused.length > 20 ? ', …' : ''}`,\n advisory: true,\n },\n ];\n}\n\n/**\n * The longest literal prefix of every dynamically-built key.\n *\n * A prefix rather than a whole key, because only the static head of\n * `` t(`nav.${item}`) `` is knowable, and the keys it may resolve to are exactly\n * the ones a static scan must not claim are dead.\n */\nfunction dynamicKeyPrefixes(scope: CallSiteScope): Set<string> {\n const prefixes = new Set<string>();\n for (const file of sourceFiles(scope)) {\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*`([^`$]*)\\$\\{/g)) {\n const head = match[1].replace(/\\.$/, '');\n if (head) prefixes.add(head);\n }\n }\n return prefixes;\n}\n\n/**\n * The string tags a locale directory declares, parsed from a source file.\n *\n * A declared list and a directory of bundles are two independent facts about the\n * same thing, and the only one that can be wrong *silently* is the declared list:\n * a tag with no directory makes a runtime `import.meta.glob` lookup throw the\n * moment that language is chosen, which is a support ticket and not a build\n * failure. A directory with no declaration is a translation nobody can select.\n *\n * Parsed as text rather than imported, because the declaring file is a TypeScript\n * module in the app being linted and importing it would run it.\n */\nfunction declaredTags(file: string): string[] {\n const source = readFileSync(file, 'utf8');\n const match = /(?:export\\s+)?const\\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\\s*=\\s*\\[([^\\]]*)\\]/.exec(source);\n if (!match) throw new Error(`${file} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);\n return [...(match[1] ?? '').matchAll(/['\"]([^'\"]+)['\"]/g)].map((tag) => tag[1]);\n}\n\n/**\n * Cross-check a declared tag list against the bundle directories, both ways.\n *\n * Both directions are findings because both are wrong states: declared-but-absent\n * is a runtime throw on selection, present-but-undeclared is a bundle no\n * selector offers.\n */\nfunction checkDeclaredTags(localesDir: string, declaredFile: string, onDisk: readonly string[]): LocaleProblem[] {\n const declared = declaredTags(declaredFile);\n const problems: LocaleProblem[] = [];\n for (const tag of declared) {\n if (!onDisk.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${declaredFile} declares '${tag}' but ${localesDir}/${tag} does not exist — selecting that language throws`,\n });\n }\n }\n for (const tag of onDisk) {\n if (!declared.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${localesDir}/${tag} exists but ${declaredFile} does not declare it — the selector cannot offer it`,\n });\n }\n }\n return problems;\n}\n\n/**\nCLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?, '--tags=<file>'?])`.\n\n`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under\n`<dir>` must resolve against the base bundle, and any inline default must equal the\nbundled value. Without the flag the script stays bundle-to-bundle, because that is\nthe only part it can answer for a repo whose bundles are consumed by something\nother than `t()` — a backend string table, for instance.\n\n`--tags=<file>` cross-checks a declared `SUPPORTED_LANGUAGES` / `SUPPORTED_LOCALES`\narray against the bundle directories, in both directions. It is separate from\n`--call-sites` because a repo can declare its tags in a file the scan never walks,\nand a directory of bundles with no declaration is exactly the state a\nbundle-to-bundle check reports as perfectly healthy.\n*/\nfunction validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';\n const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;\n const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';\n const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);\n const tagsFile = argv.find((arg) => arg.startsWith('--tags='))?.slice('--tags='.length);\n\n const report = validateLocales(dir, base, shape);\n const problems = [...report.problems];\n\n if (tagsFile !== undefined && existsSync(tagsFile)) {\n try {\n problems.push(...checkDeclaredTags(dir, tagsFile, tagsOnDisk(dir, shape)));\n } catch (error: unknown) {\n problems.push({ locale: 'tags', problem: `${tagsFile}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n if (callSiteDir !== undefined && existsSync(callSiteDir)) {\n try {\n const baseBundle = bundleAt(dir, base, shape);\n const scope = { dir: callSiteDir, extensions: ['.ts', '.tsx'] };\n const used = usedKeys(scope);\n problems.push(\n ...collectCallSites(scope, new Set(baseBundle.keys()), baseBundle),\n ...collectUnusedKeys([...baseBundle.keys()], scope, used),\n );\n } catch (error: unknown) {\n problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n const failures = problems.filter((problem) => problem.advisory !== true);\n const advisories = problems.filter((problem) => problem.advisory === true);\n\n if (failures.length > 0) {\n console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);\n for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);\n return 1;\n }\n if (advisories.length > 0) {\n console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);\n for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);\n }\n console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);\n return 0;\n}\n\nexport { parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleProblem, LocaleReport, LocaleShape };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
-
"mappings": "+EAqCA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YA+CjB,SAASC,EAAQC,EAAgBC,EAAS,GAAIC,EAA4B,IAAI,IAAK,CACjF,GAAIF,IAAU,MAAQ,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EACpE,OAAIC,GAAQC,EAAI,IAAID,EAAQD,CAAK,EAC1BE,EAET,MAAMC,EAAU,OAAO,Q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C,CAAW,KAAKhE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAAE,CAC7H,CAGF,MAAMmE,EAAWjD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EACjEC,EAAanD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EAEzE,GAAID,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,gCAAgCnB,CAAG,KAAKmB,EAAS,MAAM,eAAe,EACpF,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EACzF,MAAO,EACT,CACA,GAAIC,EAAW,OAAS,EAAG,CACzB,QAAQ,KAAK,gCAAgCrB,CAAG,SAASqB,EAAW,MAAM,uBAAuB,EACjG,UAAWD,KAAWC,EAAY,QAAQ,KAAK,OAAOD,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,CAC5F,CACA,eAAQ,IAAI,6BAA6BF,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB/D,CAAK,IAAI,EAC7G,CACT,CA9CS3B,EAAAoF,EAAA,sBA0DL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQ7F,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAK6F,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\n * Validate that every locale bundle carries exactly the base locale's keys.\n *\n * Provenance: `scripts/validate_locales.{mjs,ts}` in Durable-DAV, Edge-Git and\n * Mail-Meow, and Edge-Sonic's `scripts/i18n/locale-checks.ts` +\n * `validate_locales.ts`, converged. All four copies agree on the contract:\n * flattened dotted key paths, two-way parity (missing AND extra), no empty values,\n * no stray placeholders.\n *\n * ### What the convergence added\n *\n * Edge-Sonic's is the only copy that checks what a value *is*. The rest compare\n * bundle to bundle, so with one shipped language the whole per-tag body is skipped\n * and the script reports `ALL OK` having checked nothing about the application — it\n * could not see that `libraries.scanPausedRequests` was used and absent, because\n * the string in the bundle did not exist to be wrong *about* anything. Hence\n * `--call-sites`: every `t('key')` under `apps/web/src` must resolve.\n *\n * Key **order** drift against the base is a warning, not a failure: locale files\n * are maintained by mirroring new keys into every file, and failing on order would\n * turn an otherwise-correct translation update into a CI failure about formatting.\n *\n * ### Three on-disk shapes, one checker\n *\n * The family ships bundles in three shapes, and the shape is an argument rather\n * than a fork of the script:\n *\n * - `auto` (default) — every layout below, tried in order, so a repo that has\n * half-migrated is reported rather than silently skipped;\n * - `dir` — `<locales-dir>/<tag>/translation.json`, the i18next layout used by\n * seven repos;\n * - `file` — `<locales-dir>/<tag>.json`, one flat file per tag;\n * - `module` — `<locales-dir>/<tag>.ts` exporting an object literal, which is the\n * shape `@rexezuge/i18n` uses for the backend string bundles. The literal is\n * extracted and normalised here, so the same gate covers the backend catalogs\n * the kit ships and the SPA bundles the repos do.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\nThe bundle layouts the checker understands.\n*/\ntype LocaleShape = 'auto' | 'dir' | 'file' | 'module';\n\n/**\nOne defect, kept as a locale plus a message so a caller can group them.\n*/\ninterface LocaleProblem {\n locale: string;\n problem: string;\n /**\n * Reported, but not a failure.\n *\n * The distinction is **\"this build is wrong\"** against **\"this merge is still\n * in flight\"**, and a gate that cannot tell them apart gets switched off. A\n * key the bundles carry that no call site reaches is the ordinary state of a\n * bundle running ahead of its UI, and a translator adding a string for a screen\n * that has not been wired is doing the right thing. It is also the only thing\n * that catches a call site deleted or renamed without its key — which keeps a\n * translator re-translating a string no user will ever see.\n *\n * So it is reported and it does not fail the run.\n *\n * The finding that is **not** advisory is the mirror: a `t()` key the bundle\n * lacks. That one renders the inline default for every user in every language,\n * it is actionable in the same commit, and there is no in-flight state in which\n * it is the right answer — so it stays fatal, and the report below prints the\n * two classes separately rather than counting them together.\n */\n advisory?: boolean;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface LocaleReport {\n locales: string[];\n keys: number;\n problems: LocaleProblem[];\n}\n\n/**\nEvery dotted key path in a bundle, depth first.\n*/\nfunction flatten(value: unknown, prefix = '', out: Map<string, unknown> = new Map()): Map<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n for (const [key, child] of entries) {\n flatten(child, prefix ? `${prefix}.${key}` : key, out);\n }\n return out;\n}\n\n/**\n * The interpolation tokens in a value, sorted.\n *\n * Sorted so two values carrying the same tokens in different orders compare equal —\n * substitution is by name, so order carries no meaning. `localeCompare` rather than\n * the default comparator so a reported mismatch does not change with the machine's\n * locale.\n */\nfunction placeholdersOf(value: unknown): string[] {\n if (typeof value !== 'string') return [];\n return [...new Set(value.match(/\\{\\{[^{}]+\\}\\}/g))].sort((left: string, right: string) => left.localeCompare(right));\n}\n\n/**\n * A source file to check `t()` call sites under, and how far down to look.\n */\ninterface CallSiteScope {\n /**\n Directory walked for source files.\n */\n dir: string;\n /**\n Extensions treated as source.\n */\n extensions: readonly string[];\n}\n\n/**\n * Read a bundle as a value, in whichever shape it is written.\n *\n * `module` is the shape `@rexezuge/i18n` ships: `const enStrings: BackendStrings =\n * { common: { unauthorized: '…' } };`. Extracting the literal rather than importing\n * the module is the point — a validator that imported the bundle would typecheck it\n * against the kit's own types, and therefore agree with whatever it was given.\n */\nfunction readBundle(file: string): unknown {\n const source = readFileSync(file, 'utf8');\n // Decided by the file's extension, not by the caller's `shape`: under `auto` a\n // `.ts` bundle is found, and reading it as JSON would report a parse error for a\n // file that is perfectly well-formed.\n return file.endsWith('.ts') ? parseObjectLiteral(source, file) : (JSON.parse(source) as unknown);\n}\n\n/**\n * The first balanced object literal in a TypeScript module, as a value.\n *\n * Brace-matched outside strings and comments, and started at the **first\n * assignment** rather than at the first brace — see `objectLiteralStart` for why the\n * difference is the whole rule. Single-quoted strings are normalised to\n * double-quoted JSON, bare keys are quoted, and trailing commas are tolerated: that\n * is all the shape this needs, and a translator file that needs more is not a\n * translator file.\n */\n/**\n * Where the object literal begins: the first brace **after the first assignment**.\n *\n * The assignment matters. `const enStrings: BackendStrings = { ... }` is preceded by\n * an import line whose own braces open earlier in the file, so a plain\n * `indexOf('{')` returns the import's pair and the \"literal\" extracted is\n * `{ BackendStrings }` — an empty object that parses cleanly and then reports the\n * base bundle as having no keys. Finding the assignment first skips every brace that\n * is not the value being bound to it.\n */\nfunction objectLiteralStart(source: string): number {\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n // The assignment, and not a comparison or an arrow: `=>` and `==` both contain an\n // `=`, and neither is where a bundle's object literal is attached.\n const previous = source[index - 1];\n if (char === '=' && next !== '=' && next !== '>' && previous !== '=' && previous !== '!' && previous !== '<' && previous !== '>') {\n const brace = source.indexOf('{', index);\n return brace === -1 ? -1 : brace;\n }\n }\n return -1;\n}\n\nfunction parseObjectLiteral(source: string, file: string): unknown {\n const start = objectLiteralStart(source);\n if (start === -1) {\n throw new Error(`${file} has no object literal`);\n }\n\n let depth = 0;\n let end = -1;\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = start; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n // An escape consumes the next character, so `\\'` does not close the string.\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n end = index;\n break;\n }\n }\n }\n if (end === -1) {\n throw new Error(`${file} has an unterminated object literal`);\n }\n\n const literal = source.slice(start, end + 1);\n // Three normalisations, each of which a JSON parser needs and a TS literal does not:\n // single-quoted strings become double-quoted (applied only to string literals, so a\n // value containing an apostrophe keeps it), bare keys get quoted, and trailing\n // commas are dropped. A translator file that needs more than that is not a\n // translator file.\n const doubleQuoted = literal.replaceAll(/'((?:[^'\\\\]|\\\\.)*)'/g, (_match, body: string) => JSON.stringify(unescapeLiteral(body)));\n const quotedKeys = doubleQuoted.replaceAll(/([{,]\\s*)([A-Z_$][\\w$]*)(\\s*:)/gi, '$1\"$2\"$3');\n const withoutTrailingCommas = quotedKeys.replaceAll(/,(\\s*[}\\]])/g, '$1');\n\n try {\n return JSON.parse(withoutTrailingCommas) as unknown;\n } catch (error: unknown) {\n throw new Error(`${file} object literal could not be parsed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\nThe escapes a translator file actually uses; anything else is passed through.\n*/\nfunction unescapeLiteral(body: string): string {\n return body\n .replaceAll(String.raw`\\'`, \"'\")\n .replaceAll(String.raw`\\\"`, '\"')\n .replaceAll(String.raw`\\n`, '\\n')\n .replaceAll(String.raw`\\t`, '\\t')\n .replaceAll(String.raw`\\\\`, '\\\\');\n}\n\n/**\nThe extensions a flat layout uses, keyed by shape.\n*/\nconst FLAT_EXTENSION: Record<'file' | 'module', string> = { file: 'json', module: 'ts' };\n\n/**\nThe layouts `shape` covers. `auto` covers all three, in the order they are tried.\n*/\nfunction layouts(shape: LocaleShape): Array<'dir' | 'file' | 'module'> {\n return shape === 'auto' ? ['dir', 'file', 'module'] : [shape];\n}\n\n/**\nThe tags on disk, in whichever layouts `shape` covers.\n*/\nfunction tagsOnDisk(localesDir: string, shape: LocaleShape): string[] {\n const tags: string[] = [];\n if (layouts(shape).includes('dir')) {\n tags.push(\n ...readdirSync(localesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name),\n );\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n const extension = FLAT_EXTENSION[layout];\n tags.push(\n ...readdirSync(localesDir)\n .filter((name) => name.endsWith(`.${extension}`))\n .map((name) => name.slice(0, -extension.length - 1)),\n );\n }\n return tags;\n}\n\n/**\n * The file a tag's bundle lives in, or `undefined` when it is not there.\n *\n * Every candidate is tried rather than only the one `shape` names, because a repo\n * with a half-migrated tree is a repo whose missing half should be reported. A\n * checker that only looked where it was told would read a bundle that exists as\n * absent, and a missing bundle is the defect this script exists to find.\n */\nfunction bundleFor(localesDir: string, locale: string, shape: LocaleShape): string | undefined {\n const candidates: string[] = [];\n if (layouts(shape).includes('dir')) {\n candidates.push(path.join(localesDir, locale, 'translation.json'));\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n candidates.push(path.join(localesDir, `${locale}.${FLAT_EXTENSION[layout]}`));\n }\n return candidates.find((candidate) => existsSync(candidate));\n}\n\n/**\n * The base bundle, flattened, for a scope that checks the application against it.\n *\n * @throws when the bundle cannot be found or parsed — the caller reports that as a\n * problem rather than reporting \"all clear\" against an empty key set, which is\n * the one outcome a locale gate must never produce silently.\n */\nfunction bundleAt(localesDir: string, baseLocale: string, shape: LocaleShape): Map<string, unknown> {\n const file = bundleFor(localesDir, baseLocale, shape);\n if (file === undefined) {\n throw new Error(`no bundle found for the base locale (expected ${baseLocale}/translation.json)`);\n }\n return flatten(readBundle(file));\n}\n\n/**\n * Validate a directory of locale bundles against `baseLocale`'s key set.\n *\n * Two-way parity: a key the base has and a bundle lacks renders the fallback, and\n * a key a bundle has that the base lacks is dead weight nothing can translate from.\n */\nfunction validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleShape = 'auto'): LocaleReport {\n const problems: LocaleProblem[] = [];\n if (!existsSync(localesDir)) {\n problems.push({ locale: baseLocale, problem: `${localesDir} does not exist` });\n return { locales: [], keys: 0, problems };\n }\n\n const baseFile = bundleFor(localesDir, baseLocale, shape);\n if (baseFile === undefined) {\n problems.push({ locale: baseLocale, problem: `no bundle found for the base locale (expected ${baseLocale}/translation.json)` });\n return { locales: [], keys: 0, problems };\n }\n\n let baseBundle: Map<string, unknown>;\n try {\n baseBundle = flatten(readBundle(baseFile));\n } catch (error: unknown) {\n problems.push({ locale: baseLocale, problem: `${baseFile}: ${error instanceof Error ? error.message : String(error)}` });\n return { locales: [], keys: 0, problems };\n }\n const baseKeys = new Set(baseBundle.keys());\n\n if (baseKeys.size === 0) {\n // An empty base is the one defect that reaches the most users: it is the fallback\n // for every missing key, so an empty value here is indistinguishable from a\n // missing bundle at runtime.\n problems.push({ locale: baseLocale, problem: `${baseFile} has no keys — the base bundle is empty or unreadable` });\n return { locales: [baseLocale], keys: 0, problems };\n }\n\n const locales = [...new Set([...tagsOnDisk(localesDir, shape), baseLocale])].sort((a, b) => a.localeCompare(b));\n for (const locale of locales) {\n const file = bundleFor(localesDir, locale, shape);\n if (file === undefined) {\n problems.push({ locale, problem: 'no bundle found' });\n continue;\n }\n let bundle: Map<string, unknown>;\n try {\n bundle = flatten(readBundle(file));\n } catch (error: unknown) {\n problems.push({ locale, problem: `${file}: ${error instanceof Error ? error.message : String(error)}` });\n continue;\n }\n for (const key of baseKeys) {\n if (!bundle.has(key)) problems.push({ locale, problem: `missing key: ${key}` });\n }\n for (const [key, value] of bundle) {\n if (!baseKeys.has(key)) {\n problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });\n continue;\n }\n // An empty value is reported for the base too. i18next renders `''` for a key\n // whose value is empty and for a key that is absent, so the two are the same\n // blank screen — which is why a \"translated\" locale can look complete in a\n // diff and be missing on the page.\n if (typeof value !== 'string' || value === '') {\n problems.push({ locale, problem: `empty value: ${key} — indistinguishable from a missing key at runtime` });\n continue;\n }\n // Placeholder parity. Substitution is by name, so a translation that drops\n // `{{count}}` renders the sentence with a hole in it and no error anywhere.\n const expected = placeholdersOf(baseBundle.get(key));\n if (expected.length === 0) continue;\n const actual = placeholdersOf(value);\n if (expected.length !== actual.length || expected.some((token, index) => token !== actual[index])) {\n problems.push({\n locale,\n problem: `placeholder mismatch at ${key}: ${locale} has ${JSON.stringify(actual)}, ${baseLocale} has ${JSON.stringify(expected)}`,\n });\n }\n }\n }\n\n return { locales, keys: baseKeys.size, problems };\n}\n\n/**\n * Every `t('key')` call site under a scope, with its inline default if it has one.\n *\n * This is the only part of the check that reaches the application rather than the\n * bundles: the rest compare bundle to bundle, so with one shipped language the whole\n * per-tag body is skipped and the script reports `ALL OK` having checked nothing\n * about the product — it cannot see that a key was used and absent, because the\n * string in the bundle did not exist to be wrong *about* anything.\n *\n * Dynamic keys cannot be resolved statically and are skipped rather than guessed:\n * a computed key that happens to start with a literal is a finding nobody can act\n * on, and one finding nobody can act on trains people to ignore the report.\n */\nfunction collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {\n const problems: LocaleProblem[] = [];\n for (const full of sourceFiles(scope)) {\n const source = readFileSync(full, 'utf8');\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n const pattern = /\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1\\s*(,)?/g;\n for (const match of source.matchAll(pattern)) {\n const key = match[2];\n if (key.includes('${') || key.includes('{{')) continue;\n const where = path.relative(process.cwd(), full) || full;\n if (!baseKeys.has(key)) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,\n });\n continue;\n }\n // A default that disagrees with the shipped bundle **fails**: one of the two\n // is a bug, and the default is the one that renders verbatim the day the key\n // goes missing — which is the fallback path the whole check is about.\n if (!match[3]) continue;\n const inline = readDefault(source, match.index + match[0].length);\n if (inline === null) continue;\n const bundled = baseBundle.get(key);\n if (inline !== bundled) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,\n });\n }\n }\n }\n return problems;\n}\n\n/**\n * The first string literal at `from`, or `null` when the next token is not one.\n *\n * The terminator is the literal's **own** quote character and never the other one.\n * A default that contains an apostrophe is the ordinary case here — these bundles\n * say things like `D1's daily write allowance` — so a scan that accepts either\n * quote stops at the apostrophe and reports `D1` as the whole default, turning a\n * correct file into a \"default disagrees\" failure on every line that quotes an\n * English possessive.\n */\nfunction readDefault(source: string, from: number): string | null {\n const rest = source.slice(from).replace(/^\\s+/, '');\n const quote = rest[0];\n if (quote !== \"'\" && quote !== '\"') return null;\n const body = rest.slice(1);\n const closer = quote === \"'\" ? /^(?:[^'\\\\]|\\\\.)*'/ : /^(?:[^\"\\\\]|\\\\.)*\"/;\n const match = closer.exec(body);\n if (!match) return null;\n return decodeStringLiteral(body.slice(0, match[0].length - 1));\n}\n\n/**\n * Decode a JS string literal as written in source, escapes and all.\n *\n * Only the escapes these bundles use are handled. An unrecognised one is passed\n * through as the backslash plus the character rather than throwing: a validator\n * that crashes on an unfamiliar escape reports nothing at all, which is worse than\n * reporting a value it had to guess at.\n */\nfunction decodeStringLiteral(raw: string): string {\n return raw.replaceAll(/\\\\(.)/gs, (whole, char: string) => {\n switch (char) {\n case 'n': {\n return '\\n';\n }\n case 't': {\n return '\\t';\n }\n case 'r': {\n return '\\r';\n }\n case '\\\\':\n case \"'\":\n case '\"':\n case '`': {\n return char;\n }\n default: {\n return whole;\n }\n }\n });\n}\n\n/**\n * Every key a `t()` call site names literally, under one scope.\n *\n * Extracted from {@link collectCallSites} so the unused-key sweep and the\n * unresolved-key check read the **same** set. Two scanners that each carry their\n * own idea of what a call site looks like disagree on exactly the interesting\n * case — a shape one understands and the other does not — and then report a key\n * as both unused and used.\n */\nfunction usedKeys(scope: CallSiteScope): Set<string> {\n const used = new Set<string>();\n for (const file of sourceFiles(scope)) {\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1/g)) {\n const key = match[2];\n if (!key.includes('${') && !key.includes('{{')) used.add(key);\n }\n }\n return used;\n}\n\n/**\n * Every source file a scope covers, walking the skip list once.\n */\nfunction sourceFiles(scope: CallSiteScope): string[] {\n const files: string[] = [];\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;\n walk(full);\n continue;\n }\n if (scope.extensions.some((extension) => entry.name.endsWith(extension))) files.push(full);\n }\n };\n walk(scope.dir);\n return files;\n}\n\n/**\n * Base-bundle keys that no `t()` call site reaches.\n *\n * Advisory by construction, and for the reason {@link LocaleProblem.advisory}\n * gives: a bundle routinely runs ahead of its UI, and a translator adding a\n * string for a screen that has not been wired is doing the right thing. What it\n * also catches is the case that matters — a renamed or deleted call site whose\n * key was never removed, which keeps a translator re-translating a string no\n * user will ever see.\n *\n * Dynamic keys are **not** reported as unused. `` t(`section.${name}`) `` cannot\n * be resolved statically, so every key under that prefix would look dead; the\n * honest answer is \"unknown\", and an `unknown` reported as `unused` is the kind\n * of finding that makes a gate useless.\n */\nfunction collectUnusedKeys(baseKeys: readonly string[], scope: CallSiteScope, used: Set<string>): LocaleProblem[] {\n const prefixes = dynamicKeyPrefixes(scope);\n const unused = baseKeys.filter(\n (key) => !used.has(key) && [...prefixes].every((prefix) => !(key === prefix || key.startsWith(`${prefix}.`))),\n );\n if (unused.length === 0) return [];\n return [\n {\n locale: 'call-site',\n problem: `${unused.length} base key(s) are not reached by any t() call site: ${unused.slice(0, 20).join(', ')}${unused.length > 20 ? ', …' : ''}`,\n advisory: true,\n },\n ];\n}\n\n/**\n * The longest literal prefix of every dynamically-built key.\n *\n * A prefix rather than a whole key, because only the static head of\n * `` t(`nav.${item}`) `` is knowable, and the keys it may resolve to are exactly\n * the ones a static scan must not claim are dead.\n */\nfunction dynamicKeyPrefixes(scope: CallSiteScope): Set<string> {\n const prefixes = new Set<string>();\n for (const file of sourceFiles(scope)) {\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*`([^`$]*)\\$\\{/g)) {\n const head = match[1].replace(/\\.$/, '');\n if (head) prefixes.add(head);\n }\n }\n return prefixes;\n}\n\n/**\n * The string tags a locale directory declares, parsed from a source file.\n *\n * A declared list and a directory of bundles are two independent facts about the\n * same thing, and the only one that can be wrong *silently* is the declared list:\n * a tag with no directory makes a runtime `import.meta.glob` lookup throw the\n * moment that language is chosen, which is a support ticket and not a build\n * failure. A directory with no declaration is a translation nobody can select.\n *\n * Parsed as text rather than imported, because the declaring file is a TypeScript\n * module in the app being linted and importing it would run it.\n */\nfunction declaredTags(file: string): string[] {\n const source = readFileSync(file, 'utf8');\n const match = /(?:export\\s+)?const\\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\\s*=\\s*\\[([^\\]]*)\\]/.exec(source);\n if (!match) throw new Error(`${file} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);\n return [...(match[1] ?? '').matchAll(/['\"]([^'\"]+)['\"]/g)].map((tag) => tag[1]);\n}\n\n/**\n * Cross-check a declared tag list against the bundle directories, both ways.\n *\n * Both directions are findings because both are wrong states: declared-but-absent\n * is a runtime throw on selection, present-but-undeclared is a bundle no\n * selector offers.\n */\nfunction checkDeclaredTags(localesDir: string, declaredFile: string, onDisk: readonly string[]): LocaleProblem[] {\n const declared = declaredTags(declaredFile);\n const problems: LocaleProblem[] = [];\n for (const tag of declared) {\n if (!onDisk.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${declaredFile} declares '${tag}' but ${localesDir}/${tag} does not exist — selecting that language throws`,\n });\n }\n }\n for (const tag of onDisk) {\n if (!declared.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${localesDir}/${tag} exists but ${declaredFile} does not declare it — the selector cannot offer it`,\n });\n }\n }\n return problems;\n}\n\n/**\nCLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?, '--tags=<file>'?])`.\n\n`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under\n`<dir>` must resolve against the base bundle, and any inline default must equal the\nbundled value. Without the flag the script stays bundle-to-bundle, because that is\nthe only part it can answer for a repo whose bundles are consumed by something\nother than `t()` — a backend string table, for instance.\n\n`--tags=<file>` cross-checks a declared `SUPPORTED_LANGUAGES` / `SUPPORTED_LOCALES`\narray against the bundle directories, in both directions. It is separate from\n`--call-sites` because a repo can declare its tags in a file the scan never walks,\nand a directory of bundles with no declaration is exactly the state a\nbundle-to-bundle check reports as perfectly healthy.\n*/\nfunction validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';\n const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;\n const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';\n const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);\n const tagsFile = argv.find((arg) => arg.startsWith('--tags='))?.slice('--tags='.length);\n\n const report = validateLocales(dir, base, shape);\n const problems = [...report.problems];\n\n if (tagsFile !== undefined && existsSync(tagsFile)) {\n try {\n problems.push(...checkDeclaredTags(dir, tagsFile, tagsOnDisk(dir, shape)));\n } catch (error: unknown) {\n problems.push({ locale: 'tags', problem: `${tagsFile}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n if (callSiteDir !== undefined && existsSync(callSiteDir)) {\n try {\n const baseBundle = bundleAt(dir, base, shape);\n const scope = { dir: callSiteDir, extensions: ['.ts', '.tsx'] };\n const used = usedKeys(scope);\n problems.push(\n ...collectCallSites(scope, new Set(baseBundle.keys()), baseBundle),\n ...collectUnusedKeys([...baseBundle.keys()], scope, used),\n );\n } catch (error: unknown) {\n problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n const failures = problems.filter((problem) => problem.advisory !== true);\n const advisories = problems.filter((problem) => problem.advisory === true);\n\n if (failures.length > 0) {\n console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);\n for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);\n return 1;\n }\n if (advisories.length > 0) {\n console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);\n for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);\n }\n console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);\n return 0;\n}\n\nexport { parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleProblem, LocaleReport, LocaleShape };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (isEntrypoint(import.meta.url)) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBAsC7B,OAAS,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B,EAAOD,EAASd,CAAK,EAC3BZ,EAAS,KACP,GAAGW,EAAiBC,EAAO,IAAI,IAAIV,EAAW,KAAI,CAAE,EAAGA,CAAU,EACjE,GAAG6B,EAAkB,CAAC,GAAG7B,EAAW,KAAI,CAAE,EAAGU,EAAOe,CAAI,CAAC,CAE7D,OAAS7C,EAAgB,CACvBkB,EAAS,KAAK,CAAE,OAAQ,YAAa,QAAS,GAAG8C,CAAW,KAAKhE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAAE,CAC7H,CAGF,MAAMmE,EAAWjD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EACjEC,EAAanD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EAEzE,GAAID,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,gCAAgCnB,CAAG,KAAKmB,EAAS,MAAM,eAAe,EACpF,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EACzF,MAAO,EACT,CACA,GAAIC,EAAW,OAAS,EAAG,CACzB,QAAQ,KAAK,gCAAgCrB,CAAG,SAASqB,EAAW,MAAM,uBAAuB,EACjG,UAAWD,KAAWC,EAAY,QAAQ,KAAK,OAAOD,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,CAC5F,CACA,eAAQ,IAAI,6BAA6BF,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB/D,CAAK,IAAI,EAC7G,CACT,CA9CS3B,EAAAoF,EAAA,sBA0DLhG,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKgG,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["isEntrypoint", "existsSync", "readdirSync", "readFileSync", "path", "flatten", "value", "prefix", "out", "entries", "key", "child", "__name", "placeholdersOf", "left", "right", "readBundle", "file", "source", "parseObjectLiteral", "objectLiteralStart", "quote", "inLineComment", "inBlockComment", "index", "char", "next", "previous", "brace", "start", "depth", "end", "withoutTrailingCommas", "_match", "body", "unescapeLiteral", "error", "FLAT_EXTENSION", "layouts", "shape", "tagsOnDisk", "localesDir", "tags", "entry", "layout", "extension", "name", "bundleFor", "locale", "candidates", "candidate", "bundleAt", "baseLocale", "validateLocales", "problems", "baseFile", "baseBundle", "baseKeys", "locales", "a", "b", "bundle", "expected", "actual", "token", "collectCallSites", "scope", "full", "sourceFiles", "pattern", "match", "where", "inline", "readDefault", "bundled", "from", "rest", "decodeStringLiteral", "raw", "whole", "usedKeys", "used", "files", "walk", "dir", "collectUnusedKeys", "prefixes", "dynamicKeyPrefixes", "unused", "head", "declaredTags", "tag", "checkDeclaredTags", "declaredFile", "onDisk", "declared", "validateLocalesCli", "argv", "arg", "base", "callSiteDir", "tagsFile", "report", "failures", "problem", "advisories"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var w=Object.defineProperty;var a=(r,t)=>w(r,"name",{value:t,configurable:!0});import{
|
|
2
|
-
`,f=d.join(r,u);let g=null;try{g=p(f,"utf8")}catch(b){if(b?.code!=="ENOENT")throw b}return g!==i&&E(f,i,"utf8"),o.lock=e,o}const c=o.lock;if(c===null)return o.problems.push({problem:`${u} is missing \u2014 run migrations:lock`}),o;const l=new Map(c.migrations.map(e=>[e.name,e.sha256]));for(const e of o.files){const i=l.get(e);if(i===void 0){o.problems.push({problem:`${e} has no lock entry \u2014 run migrations:lock`});continue}if(h(e,s))continue;const f=
|
|
1
|
+
var w=Object.defineProperty;var a=(r,t)=>w(r,"name",{value:t,configurable:!0});import{isEntrypoint as M}from"./lib/entrypoint.js";import{createHash as _}from"node:crypto";import{existsSync as $,readFileSync as p,readdirSync as O,writeFileSync as E}from"node:fs";import d from"node:path";const u="migrations.lock.json",k=/^(\d{4})_[a-z0-9_]+\.sql$/,q=/^\d{4}_squash\.sql$/,m=1;function y(r){return _("sha256").update(r,"utf8").digest("hex")}a(y,"sha256Hex");function x(r){let t;for(const o of r)q.test(o)&&(t===void 0||o>t)&&(t=o);return t}a(x,"baselineOf");function h(r,t){return t!==void 0&&r<=t}a(h,"isSubsumed");function N(r){const t=[];if(!$(r))return t.push({problem:`${r} does not exist`}),{files:[],problems:t,lock:null};const o=O(r).filter(e=>e.endsWith(".sql")).sort((e,i)=>e.localeCompare(i));for(const e of o)k.test(e)||t.push({problem:`${e} does not match NNNN_snake_case.sql`});const s=x(o),c=o.map(e=>k.exec(e)?.[1]);for(let e=1;e<c.length;e+=1){const i=c[e-1],f=c[e];i!==void 0&&f!==void 0&&f<=i&&t.push({problem:`${o[e]??"?"} sorts at or before ${o[e-1]??"?"} \u2014 D1 applies in filename order, so one of the two can never run`})}if(s===void 0)for(const[e,i]of c.entries()){const f=String(e+1).padStart(4,"0");i!==f&&t.push({problem:`migration numbering is not contiguous: expected ${f}_*.sql, found ${o[e]??"?"}`})}const l=d.join(r,u);let n=null;if($(l))try{n=JSON.parse(p(l,"utf8"))}catch{t.push({problem:`${u} is not valid JSON`})}return{files:o,problems:t,lock:n}}a(N,"inspectMigrations");function C(r,t,o,s){const c=a(n=>y(p(d.join(r,n),"utf8")),"digestOf");if(o===null)return{version:m,...s!==void 0&&{baseline:s},migrations:t.map(n=>({name:n,sha256:c(n)}))};const l=new Map;for(const n of t){const e=o.migrations.find(i=>i.name===n);e!==void 0&&l.set(n,n===s?c(n):e.sha256)}for(const n of t)!l.has(n)&&o.migrations.every(e=>e.name!==n)&&l.set(n,c(n));for(const n of o.migrations)!t.includes(n.name)&&!h(n.name,s)&&l.set(n.name,n.sha256);return{version:m,...s!==void 0&&{baseline:s},migrations:[...l].sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>({name:n,sha256:e}))}}a(C,"buildUpdatedLock");function S(r,t={}){const o=N(r),s=x(o.files);if(o.problems.length>0)return o;if(t.write===!0){const e=C(r,o.files,o.lock,s),i=`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,f=d.join(r,u);let g=null;try{g=p(f,"utf8")}catch(b){if(b?.code!=="ENOENT")throw b}return g!==i&&E(f,i,"utf8"),o.lock=e,o}const c=o.lock;if(c===null)return o.problems.push({problem:`${u} is missing \u2014 run migrations:lock`}),o;const l=new Map(c.migrations.map(e=>[e.name,e.sha256]));for(const e of o.files){const i=l.get(e);if(i===void 0){o.problems.push({problem:`${e} has no lock entry \u2014 run migrations:lock`});continue}if(h(e,s))continue;const f=y(p(d.join(r,e),"utf8"));f!==i&&o.problems.push({problem:`${e} changed after locking (expected ${i.slice(0,12)}\u2026, got ${f.slice(0,12)}\u2026)`})}for(const e of c.migrations)o.files.includes(e.name)||h(e.name,s)||o.problems.push({problem:`${e.name} is in the lock but no longer exists`});const n=[...l.keys()].sort((e,i)=>e.localeCompare(i)).at(-1);if(n!==void 0)for(const e of o.files)e<n&&!l.has(e)&&o.problems.push({problem:`${e} sorts before ${n}, which is already locked \u2014 D1 applies in filename order, so it would never run on a database that has applied ${n}`});return o}a(S,"verifyMigrations");function v(r=process.argv.slice(2)){const t=r.find(c=>!c.startsWith("--"))??"migrations",o=r.includes("--write"),s=S(t,{write:o});if(s.problems.length>0){console.error(`Migration validation failed for ${t}:`);for(const c of s.problems)console.error(` - ${c.problem}`);return 1}return o?(console.log(`Migration lock written (${s.files.length} files).`),0):(console.log(`Migration validation passed (${s.files.length} files, lock in sync).`),0)}a(v,"verifyMigrationsCli");M(import.meta.url)&&process.exit(v(process.argv.slice(2)));export{u as LOCK_NAME,m as LOCK_VERSION,x as baselineOf,N as inspectMigrations,S as verifyMigrations,v as verifyMigrationsCli};
|