@rexezuge/tooling 1.9.1 → 1.9.3

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.
Files changed (42) hide show
  1. package/dist/eslint.d.ts.map +1 -1
  2. package/dist/eslint.js +1 -1
  3. package/dist/eslint.js.map +2 -2
  4. package/dist/scripts/check-god-files.js +2 -2
  5. package/dist/scripts/check-god-files.js.map +3 -3
  6. package/dist/scripts/lib/entrypoint.d.ts +27 -0
  7. package/dist/scripts/lib/entrypoint.d.ts.map +1 -0
  8. package/dist/scripts/lib/entrypoint.js +1 -0
  9. package/dist/scripts/lib/entrypoint.js.map +7 -0
  10. package/dist/scripts/spa-shell.js +2 -2
  11. package/dist/scripts/spa-shell.js.map +3 -3
  12. package/dist/scripts/validate-locales.js +5 -5
  13. package/dist/scripts/validate-locales.js.map +3 -3
  14. package/dist/scripts/verify-migrations.js +2 -2
  15. package/dist/scripts/verify-migrations.js.map +3 -3
  16. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  17. package/dist/scripts/wrangler-config/patches.js +3 -3
  18. package/dist/scripts/wrangler-config/patches.js.map +3 -3
  19. package/dist/scripts/wrangler-config/resources.d.ts +17 -7
  20. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  21. package/dist/scripts/wrangler-config/resources.js +1 -1
  22. package/dist/scripts/wrangler-config/resources.js.map +3 -3
  23. package/dist/scripts/wrangler-config/types.d.ts +3 -2
  24. package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
  25. package/dist/scripts/wrangler-config/types.js.map +2 -2
  26. package/dist/vite.d.ts +21 -0
  27. package/dist/vite.d.ts.map +1 -1
  28. package/dist/vite.js +3 -3
  29. package/dist/vite.js.map +2 -2
  30. package/package.json +3 -3
  31. package/src/eslint.ts +9 -1
  32. package/src/scripts/check-god-files.ts +2 -2
  33. package/src/scripts/lib/entrypoint.test.ts +60 -0
  34. package/src/scripts/lib/entrypoint.ts +39 -0
  35. package/src/scripts/spa-shell.ts +2 -2
  36. package/src/scripts/validate-locales.ts +2 -2
  37. package/src/scripts/verify-migrations.ts +2 -2
  38. package/src/scripts/wrangler-config/patches.ts +11 -2
  39. package/src/scripts/wrangler-config/resources.test.ts +49 -0
  40. package/src/scripts/wrangler-config/resources.ts +38 -16
  41. package/src/scripts/wrangler-config/types.ts +3 -2
  42. package/src/vite.ts +31 -1
@@ -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,QAAQH,CAAgC,EAC/D,GAAIG,EAAQ,SAAW,EACrB,OAAIF,GAAQC,EAAI,IAAID,EAAQD,CAAK,EAC1BE,EAET,SAAW,CAACE,EAAKC,CAAK,IAAKF,EACzBJ,EAAQM,EAAOJ,EAAS,GAAGA,CAAM,IAAIG,CAAG,GAAKA,EAAKF,CAAG,EAEvD,OAAOA,CACT,CAdSI,EAAAP,EAAA,WAwBT,SAASQ,EAAeP,EAAc,CACpC,OAAI,OAAOA,GAAU,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AAWC,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": ["existsSync", "readdirSync", "readFileSync", "pathToFileURL", "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"]
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,cAAAC,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,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,QAAQH,CAAgC,EAC/D,GAAIG,EAAQ,SAAW,EACrB,OAAIF,GAAQC,EAAI,IAAID,EAAQD,CAAK,EAC1BE,EAET,SAAW,CAACE,EAAKC,CAAK,IAAKF,EACzBJ,EAAQM,EAAOJ,EAAS,GAAGA,CAAM,IAAIG,CAAG,GAAKA,EAAKF,CAAG,EAEvD,OAAOA,CACT,CAdSI,EAAAP,EAAA,WAwBT,SAASQ,EAAeP,EAAc,CACpC,OAAI,OAAOA,GAAU,SAAiB,CAAA,EAC/B,CAAC,GAAG,IAAI,IAAIA,EAAM,MAAM,iBAAiB,CAAC,CAAC,EAAE,KAAK,CAACQ,EAAcC,IAAkBD,EAAK,cAAcC,CAAK,CAAC,CACrH,CAHSH,EAAAC,EAAA,kBA2BT,SAASG,EAAWC,EAAY,CAC9B,MAAMC,EAASf,EAAac,EAAM,MAAM,EAIxC,OAAOA,EAAK,SAAS,KAAK,EAAIE,EAAmBD,EAAQD,CAAI,EAAK,KAAK,MAAMC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O,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{createHash as M}from"node:crypto";import{pathToFileURL as _}from"node:url";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 x(r){return M("sha256").update(r,"utf8").digest("hex")}a(x,"sha256Hex");function y(r){let t;for(const o of r)q.test(o)&&(t===void 0||o>t)&&(t=o);return t}a(y,"baselineOf");function h(r,t){return t!==void 0&&r<=t}a(h,"isSubsumed");function v(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=y(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(v,"inspectMigrations");function C(r,t,o,s){const c=a(n=>x(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 N(r,t={}){const o=v(r),s=y(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=x(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(N,"verifyMigrations");function S(r=process.argv.slice(2)){const t=r.find(c=>!c.startsWith("--"))??"migrations",o=r.includes("--write"),s=N(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(S,"verifyMigrationsCli");process.argv[1]!==void 0&&import.meta.url===_(process.argv[1]).href&&process.exit(S(process.argv.slice(2)));export{u as LOCK_NAME,m as LOCK_VERSION,y as baselineOf,v as inspectMigrations,N as verifyMigrations,S as verifyMigrationsCli};
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};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/verify-migrations.ts"],
4
- "sourcesContent": ["/**\n * Verify the migration set is complete, ordered, and locked; write the lock.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`\n * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,\n * converged. Every copy checks the same properties of a `migrations/` directory;\n * they differ in lock-file naming, in whether the lock is enforced on CI, and in\n * how much of D1's ordering semantics they encode.\n *\n * ### Why a checksum lock at all\n *\n * D1 records *which* migrations it has applied — the filename and a timestamp —\n * but not *what the file contained* when it applied them. So editing a migration\n * that has already run is not caught by anything: the deploy still succeeds, the\n * local database built from the baseline plus the edited file picks up the new\n * statements, and production keeps the schema it had. The two databases then\n * differ silently and permanently, and the next migration that assumes the newer\n * shape fails only in production. A committed digest per file turns that into a\n * CI failure.\n *\n * ### What the checks are, and where each comes from\n *\n * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by\n * filename, so a file that sorts *after* the ones already applied is the only\n * kind that can be introduced safely.\n * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and\n * 0003 while another applied only 0001, and nothing downstream can tell which.\n * Checked **only when no squash baseline exists**: a squash legitimately\n * absorbs its predecessors, so numbering restarts wherever it starts, and a\n * contiguity rule that fires on a squash is a rule that blocks the squash.\n * - **One entry per file** (all) — a file with no recorded digest is one nothing\n * can say anything about.\n * - **Digest unchanged** (all) — the edited-after-locking failure.\n * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been\n * applied to a live database and is no longer reproducible from this repo.\n * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file\n * sorting *before* the newest locked one can never reach a database that has\n * applied that newest one, so its statements would only run on a fresh build.\n * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a\n * style problem: D1 orders them by the rest of the filename, so which one lands\n * on a given database depends on a lexicographic tiebreak nobody intended.\n *\n * ### The squash baseline\n *\n * `0008_squash.sql` holds the combined schema of every migration before it, and\n * those files are deleted when it is created. A later squash repeats that. So a\n * squash legitimately (a) rewrites one file and (b) removes files the lock still\n * lists, and neither may be reported as drift. The baseline is the\n * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims\n * — deriving it means a stale or forged `baseline` cannot widen the exempt set.\n *\n * ### The one write path\n *\n * `--write` is add-only where it counts: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. Every other\n * entry is left exactly as it is, so an incremental `edited` finding **survives a\n * `--write`** — re-baselining one means deleting its entry by hand, which shows\n * up in the diff. There is deliberately no `--force`, because a write that could\n * bless a drift would be the operator blessing their own edit.\n */\nimport { createHash } from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\nOne migration as the lock records it.\n*/\ninterface MigrationEntry {\n name: string;\n sha256: string;\n}\n\n/**\nThe parsed `migrations/migrations.lock.json`.\n*/\ninterface MigrationLockFile {\n version: 1;\n /**\n * The squashed-baseline filename, when the repo has squashed.\n *\n * Everything at or before it is exempt from the `edited` and `orphan` checks,\n * because that is exactly the set a squash rewrites or absorbs.\n */\n baseline?: string;\n migrations: MigrationEntry[];\n}\n\n/**\nOne failure, phrased for the operator.\n*/\ninterface MigrationProblem {\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface MigrationReport {\n /**\n Migration filenames, in apply order.\n */\n files: string[];\n problems: MigrationProblem[];\n /**\n The lock as it reads after the run.\n */\n lock: MigrationLockFile | null;\n}\n\n/**\n * The lock's filename, beside the `.sql` files.\n *\n * Named `migrations.lock.json` rather than `migrations.json` so it cannot be\n * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like\n * one would be a deploy-time mystery.\n */\nconst LOCK_NAME = 'migrations.lock.json';\n\n/**\nThe filename shape every migration must have. `NNNN_` is fixed at four digits.\n*/\nconst NAME_PATTERN = /^(\\d{4})_[a-z0-9_]+\\.sql$/;\n\n/**\nThe squashed-baseline shape. The highest-numbered match is the baseline.\n*/\nconst SQUASH_PATTERN = /^\\d{4}_squash\\.sql$/;\n\n/**\nThe lock's format version. Bumped only on an incompatible shape change.\n*/\nconst LOCK_VERSION = 1;\n\nfunction sha256Hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo\n * has not squashed — in which case every migration is incremental and therefore\n * every one of them is immutable.\n */\nexport function baselineOf(files: readonly string[]): string | undefined {\n let highest: string | undefined;\n for (const name of files) {\n if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {\n highest = name;\n }\n }\n return highest;\n}\n\n/**\nTrue when `name` is at or before the baseline, i.e. the set a squash absorbs.\n*/\nfunction isSubsumed(name: string, baseline: string | undefined): boolean {\n return baseline !== undefined && name <= baseline;\n}\n\n/**\n * Read the migration set and validate its shape without consulting the lock.\n *\n * The lock is read here too, so one walk answers both \"what is on disk\" and \"what\n * is recorded\"; a lock that is merely *absent* is reported by `verifyMigrations`\n * rather than here, because that is the bootstrap case rather than a defect.\n */\nfunction inspectMigrations(migrationsDir: string): MigrationReport {\n const problems: MigrationProblem[] = [];\n if (!existsSync(migrationsDir)) {\n problems.push({ problem: `${migrationsDir} does not exist` });\n return { files: [], problems, lock: null };\n }\n\n // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the\n // lock describes exactly the set wrangler will run. `migrations.lock.json` is\n // not one of them, because it is not a `.sql` file.\n const files = readdirSync(migrationsDir)\n .filter((name) => name.endsWith('.sql'))\n .sort((left, right) => left.localeCompare(right));\n\n for (const name of files) {\n if (!NAME_PATTERN.test(name)) {\n problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });\n }\n }\n\n const baseline = baselineOf(files);\n const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);\n\n // Strictly increasing: the property D1 actually depends on. A duplicate or a\n // descending prefix means two files compete for the same slot in the apply\n // order, and which one wins is a lexicographic tiebreak nobody intended.\n for (let index = 1; index < prefixes.length; index += 1) {\n const previous = prefixes[index - 1];\n const current = prefixes[index];\n if (previous !== undefined && current !== undefined && current <= previous) {\n problems.push({\n problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,\n });\n }\n }\n\n // Contiguity is checked only with no squash on disk: a squash deletes the files\n // it absorbs, so numbering restarts wherever it starts and a hole is the\n // expected shape rather than a defect.\n if (baseline === undefined) {\n for (const [index, prefix] of prefixes.entries()) {\n const expected = String(index + 1).padStart(4, '0');\n if (prefix !== expected) {\n problems.push({\n problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,\n });\n }\n }\n }\n\n const lockPath = path.join(migrationsDir, LOCK_NAME);\n let lock: MigrationLockFile | null = null;\n if (existsSync(lockPath)) {\n try {\n lock = JSON.parse(readFileSync(lockPath, 'utf8')) as MigrationLockFile;\n } catch {\n problems.push({ problem: `${LOCK_NAME} is not valid JSON` });\n }\n }\n\n return { files, problems, lock };\n}\n\n/**\n * The lock as `--write` would leave it.\n *\n * `null` when the existing lock cannot be trusted as a base, which is exactly\n * when a `--write` must refuse rather than overwrite contents it failed to\n * understand. A lock that is merely *absent* is not malformed: that is the\n * bootstrap case, and it is built from disk like any other.\n */\nfunction buildUpdatedLock(\n migrationsDir: string,\n files: readonly string[],\n existing: MigrationLockFile | null,\n baseline: string | undefined,\n): MigrationLockFile | null {\n const digestOf = (name: string): string => sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n\n if (existing === null) {\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: files.map((name) => ({ name, sha256: digestOf(name) })),\n };\n }\n\n const kept = new Map<string, string>();\n for (const file of files) {\n const recorded = existing.migrations.find((entry) => entry.name === file);\n if (recorded === undefined) continue;\n // The baseline is the one file a squash is allowed to rewrite.\n kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);\n }\n // Unlocked files are added — that is the new-migration case. Every other entry\n // is carried across untouched, so an `edited` finding survives the write.\n for (const file of files) {\n if (!kept.has(file) && existing.migrations.every((entry) => entry.name !== file)) {\n kept.set(file, digestOf(file));\n }\n }\n // Entries the baseline absorbed are dropped: committing a squash looks exactly\n // like this, and neither it nor a rewritten baseline can hide a divergence,\n // because a database that applied those files already has them recorded in D1's\n // own `d1_migrations`.\n for (const entry of existing.migrations) {\n if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {\n kept.set(entry.name, entry.sha256);\n }\n }\n\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),\n };\n}\n\n/**\nVerify (or with `write: true`, record) the lock against the files.\n*/\nfunction verifyMigrations(migrationsDir: string, options: { write?: boolean } = {}): MigrationReport {\n const report = inspectMigrations(migrationsDir);\n const baseline = baselineOf(report.files);\n\n // A malformed lock is a finding in its own right, and a `--write` must not\n // overwrite contents it failed to understand.\n if (report.problems.length > 0) {\n return report;\n }\n\n if (options.write === true) {\n const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);\n const next = `${JSON.stringify(updated, null, 2)}\\n`;\n const lockfile = path.join(migrationsDir, LOCK_NAME);\n let before: string | null = null;\n try {\n before = readFileSync(lockfile, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw error;\n }\n }\n if (before !== next) {\n writeFileSync(lockfile, next, 'utf8');\n }\n report.lock = updated;\n return report;\n }\n\n const lock = report.lock;\n if (lock === null) {\n report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });\n return report;\n }\n\n const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));\n for (const name of report.files) {\n const expected = recorded.get(name);\n if (expected === undefined) {\n report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });\n continue;\n }\n // At or before the baseline, a squash rewrites its own file, and that is the\n // whole reason a baseline exists.\n if (isSubsumed(name, baseline)) continue;\n const actual = sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n if (actual !== expected) {\n report.problems.push({\n problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n });\n }\n }\n\n for (const entry of lock.migrations) {\n if (report.files.includes(entry.name) || isSubsumed(entry.name, baseline)) continue;\n report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });\n }\n\n // A file sorting before the newest locked one can never reach a database that\n // has already applied that newest one, so its statements would only run on a\n // fresh build — the same silent split the checksum exists to prevent.\n const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);\n if (newest !== undefined) {\n for (const name of report.files) {\n if (name < newest && !recorded.has(name)) {\n report.problems.push({\n problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,\n });\n }\n }\n }\n\n return report;\n}\n\n/**\nCLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`.\n*/\nfunction verifyMigrationsCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';\n const write = argv.includes('--write');\n const report = verifyMigrations(dir, { write });\n if (report.problems.length > 0) {\n console.error(`Migration validation failed for ${dir}:`);\n for (const problem of report.problems) console.error(` - ${problem.problem}`);\n return 1;\n }\n if (write) {\n console.log(`Migration lock written (${report.files.length} files).`);\n return 0;\n }\n console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);\n return 0;\n}\n\nexport { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };\nexport type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationReport };\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(verifyMigrationsCli(process.argv.slice(2)));\n}\n"],
5
- "mappings": "+EA4DA,OAAS,cAAAA,MAAkB,cAC3B,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,iBAAA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,MAAM,CAAC,EAAC,CAC1E,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,aACnDC,EAAQH,EAAK,SAAS,SAAS,EAC/BT,EAASF,EAAiBY,EAAK,CAAE,MAAAE,CAAK,CAAE,EAC9C,GAAIZ,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,mCAAmCU,CAAG,GAAG,EACvD,UAAWG,KAAWb,EAAO,SAAU,QAAQ,MAAM,OAAOa,EAAQ,OAAO,EAAE,EAC7E,MAAO,EACT,CACA,OAAID,GACF,QAAQ,IAAI,2BAA2BZ,EAAO,MAAM,MAAM,UAAU,EAC7D,IAET,QAAQ,IAAI,gCAAgCA,EAAO,MAAM,MAAM,wBAAwB,EAChF,EACT,CAfS9B,EAAAsC,EAAA,uBA2BL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQlD,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKkD,EAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["createHash", "pathToFileURL", "existsSync", "readFileSync", "readdirSync", "writeFileSync", "path", "LOCK_NAME", "NAME_PATTERN", "SQUASH_PATTERN", "LOCK_VERSION", "sha256Hex", "content", "__name", "baselineOf", "files", "highest", "name", "isSubsumed", "baseline", "inspectMigrations", "migrationsDir", "problems", "left", "right", "prefixes", "index", "previous", "current", "prefix", "expected", "lockPath", "lock", "buildUpdatedLock", "existing", "digestOf", "kept", "file", "recorded", "entry", "sha256", "verifyMigrations", "options", "report", "updated", "next", "lockfile", "before", "error", "actual", "newest", "verifyMigrationsCli", "argv", "dir", "arg", "write", "problem"]
4
+ "sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\n * Verify the migration set is complete, ordered, and locked; write the lock.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`\n * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,\n * converged. Every copy checks the same properties of a `migrations/` directory;\n * they differ in lock-file naming, in whether the lock is enforced on CI, and in\n * how much of D1's ordering semantics they encode.\n *\n * ### Why a checksum lock at all\n *\n * D1 records *which* migrations it has applied — the filename and a timestamp —\n * but not *what the file contained* when it applied them. So editing a migration\n * that has already run is not caught by anything: the deploy still succeeds, the\n * local database built from the baseline plus the edited file picks up the new\n * statements, and production keeps the schema it had. The two databases then\n * differ silently and permanently, and the next migration that assumes the newer\n * shape fails only in production. A committed digest per file turns that into a\n * CI failure.\n *\n * ### What the checks are, and where each comes from\n *\n * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by\n * filename, so a file that sorts *after* the ones already applied is the only\n * kind that can be introduced safely.\n * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and\n * 0003 while another applied only 0001, and nothing downstream can tell which.\n * Checked **only when no squash baseline exists**: a squash legitimately\n * absorbs its predecessors, so numbering restarts wherever it starts, and a\n * contiguity rule that fires on a squash is a rule that blocks the squash.\n * - **One entry per file** (all) — a file with no recorded digest is one nothing\n * can say anything about.\n * - **Digest unchanged** (all) — the edited-after-locking failure.\n * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been\n * applied to a live database and is no longer reproducible from this repo.\n * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file\n * sorting *before* the newest locked one can never reach a database that has\n * applied that newest one, so its statements would only run on a fresh build.\n * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a\n * style problem: D1 orders them by the rest of the filename, so which one lands\n * on a given database depends on a lexicographic tiebreak nobody intended.\n *\n * ### The squash baseline\n *\n * `0008_squash.sql` holds the combined schema of every migration before it, and\n * those files are deleted when it is created. A later squash repeats that. So a\n * squash legitimately (a) rewrites one file and (b) removes files the lock still\n * lists, and neither may be reported as drift. The baseline is the\n * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims\n * — deriving it means a stale or forged `baseline` cannot widen the exempt set.\n *\n * ### The one write path\n *\n * `--write` is add-only where it counts: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. Every other\n * entry is left exactly as it is, so an incremental `edited` finding **survives a\n * `--write`** — re-baselining one means deleting its entry by hand, which shows\n * up in the diff. There is deliberately no `--force`, because a write that could\n * bless a drift would be the operator blessing their own edit.\n */\nimport { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\nOne migration as the lock records it.\n*/\ninterface MigrationEntry {\n name: string;\n sha256: string;\n}\n\n/**\nThe parsed `migrations/migrations.lock.json`.\n*/\ninterface MigrationLockFile {\n version: 1;\n /**\n * The squashed-baseline filename, when the repo has squashed.\n *\n * Everything at or before it is exempt from the `edited` and `orphan` checks,\n * because that is exactly the set a squash rewrites or absorbs.\n */\n baseline?: string;\n migrations: MigrationEntry[];\n}\n\n/**\nOne failure, phrased for the operator.\n*/\ninterface MigrationProblem {\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface MigrationReport {\n /**\n Migration filenames, in apply order.\n */\n files: string[];\n problems: MigrationProblem[];\n /**\n The lock as it reads after the run.\n */\n lock: MigrationLockFile | null;\n}\n\n/**\n * The lock's filename, beside the `.sql` files.\n *\n * Named `migrations.lock.json` rather than `migrations.json` so it cannot be\n * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like\n * one would be a deploy-time mystery.\n */\nconst LOCK_NAME = 'migrations.lock.json';\n\n/**\nThe filename shape every migration must have. `NNNN_` is fixed at four digits.\n*/\nconst NAME_PATTERN = /^(\\d{4})_[a-z0-9_]+\\.sql$/;\n\n/**\nThe squashed-baseline shape. The highest-numbered match is the baseline.\n*/\nconst SQUASH_PATTERN = /^\\d{4}_squash\\.sql$/;\n\n/**\nThe lock's format version. Bumped only on an incompatible shape change.\n*/\nconst LOCK_VERSION = 1;\n\nfunction sha256Hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo\n * has not squashed — in which case every migration is incremental and therefore\n * every one of them is immutable.\n */\nexport function baselineOf(files: readonly string[]): string | undefined {\n let highest: string | undefined;\n for (const name of files) {\n if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {\n highest = name;\n }\n }\n return highest;\n}\n\n/**\nTrue when `name` is at or before the baseline, i.e. the set a squash absorbs.\n*/\nfunction isSubsumed(name: string, baseline: string | undefined): boolean {\n return baseline !== undefined && name <= baseline;\n}\n\n/**\n * Read the migration set and validate its shape without consulting the lock.\n *\n * The lock is read here too, so one walk answers both \"what is on disk\" and \"what\n * is recorded\"; a lock that is merely *absent* is reported by `verifyMigrations`\n * rather than here, because that is the bootstrap case rather than a defect.\n */\nfunction inspectMigrations(migrationsDir: string): MigrationReport {\n const problems: MigrationProblem[] = [];\n if (!existsSync(migrationsDir)) {\n problems.push({ problem: `${migrationsDir} does not exist` });\n return { files: [], problems, lock: null };\n }\n\n // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the\n // lock describes exactly the set wrangler will run. `migrations.lock.json` is\n // not one of them, because it is not a `.sql` file.\n const files = readdirSync(migrationsDir)\n .filter((name) => name.endsWith('.sql'))\n .sort((left, right) => left.localeCompare(right));\n\n for (const name of files) {\n if (!NAME_PATTERN.test(name)) {\n problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });\n }\n }\n\n const baseline = baselineOf(files);\n const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);\n\n // Strictly increasing: the property D1 actually depends on. A duplicate or a\n // descending prefix means two files compete for the same slot in the apply\n // order, and which one wins is a lexicographic tiebreak nobody intended.\n for (let index = 1; index < prefixes.length; index += 1) {\n const previous = prefixes[index - 1];\n const current = prefixes[index];\n if (previous !== undefined && current !== undefined && current <= previous) {\n problems.push({\n problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,\n });\n }\n }\n\n // Contiguity is checked only with no squash on disk: a squash deletes the files\n // it absorbs, so numbering restarts wherever it starts and a hole is the\n // expected shape rather than a defect.\n if (baseline === undefined) {\n for (const [index, prefix] of prefixes.entries()) {\n const expected = String(index + 1).padStart(4, '0');\n if (prefix !== expected) {\n problems.push({\n problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,\n });\n }\n }\n }\n\n const lockPath = path.join(migrationsDir, LOCK_NAME);\n let lock: MigrationLockFile | null = null;\n if (existsSync(lockPath)) {\n try {\n lock = JSON.parse(readFileSync(lockPath, 'utf8')) as MigrationLockFile;\n } catch {\n problems.push({ problem: `${LOCK_NAME} is not valid JSON` });\n }\n }\n\n return { files, problems, lock };\n}\n\n/**\n * The lock as `--write` would leave it.\n *\n * `null` when the existing lock cannot be trusted as a base, which is exactly\n * when a `--write` must refuse rather than overwrite contents it failed to\n * understand. A lock that is merely *absent* is not malformed: that is the\n * bootstrap case, and it is built from disk like any other.\n */\nfunction buildUpdatedLock(\n migrationsDir: string,\n files: readonly string[],\n existing: MigrationLockFile | null,\n baseline: string | undefined,\n): MigrationLockFile | null {\n const digestOf = (name: string): string => sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n\n if (existing === null) {\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: files.map((name) => ({ name, sha256: digestOf(name) })),\n };\n }\n\n const kept = new Map<string, string>();\n for (const file of files) {\n const recorded = existing.migrations.find((entry) => entry.name === file);\n if (recorded === undefined) continue;\n // The baseline is the one file a squash is allowed to rewrite.\n kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);\n }\n // Unlocked files are added — that is the new-migration case. Every other entry\n // is carried across untouched, so an `edited` finding survives the write.\n for (const file of files) {\n if (!kept.has(file) && existing.migrations.every((entry) => entry.name !== file)) {\n kept.set(file, digestOf(file));\n }\n }\n // Entries the baseline absorbed are dropped: committing a squash looks exactly\n // like this, and neither it nor a rewritten baseline can hide a divergence,\n // because a database that applied those files already has them recorded in D1's\n // own `d1_migrations`.\n for (const entry of existing.migrations) {\n if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {\n kept.set(entry.name, entry.sha256);\n }\n }\n\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),\n };\n}\n\n/**\nVerify (or with `write: true`, record) the lock against the files.\n*/\nfunction verifyMigrations(migrationsDir: string, options: { write?: boolean } = {}): MigrationReport {\n const report = inspectMigrations(migrationsDir);\n const baseline = baselineOf(report.files);\n\n // A malformed lock is a finding in its own right, and a `--write` must not\n // overwrite contents it failed to understand.\n if (report.problems.length > 0) {\n return report;\n }\n\n if (options.write === true) {\n const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);\n const next = `${JSON.stringify(updated, null, 2)}\\n`;\n const lockfile = path.join(migrationsDir, LOCK_NAME);\n let before: string | null = null;\n try {\n before = readFileSync(lockfile, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw error;\n }\n }\n if (before !== next) {\n writeFileSync(lockfile, next, 'utf8');\n }\n report.lock = updated;\n return report;\n }\n\n const lock = report.lock;\n if (lock === null) {\n report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });\n return report;\n }\n\n const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));\n for (const name of report.files) {\n const expected = recorded.get(name);\n if (expected === undefined) {\n report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });\n continue;\n }\n // At or before the baseline, a squash rewrites its own file, and that is the\n // whole reason a baseline exists.\n if (isSubsumed(name, baseline)) continue;\n const actual = sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n if (actual !== expected) {\n report.problems.push({\n problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n });\n }\n }\n\n for (const entry of lock.migrations) {\n if (report.files.includes(entry.name) || isSubsumed(entry.name, baseline)) continue;\n report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });\n }\n\n // A file sorting before the newest locked one can never reach a database that\n // has already applied that newest one, so its statements would only run on a\n // fresh build — the same silent split the checksum exists to prevent.\n const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);\n if (newest !== undefined) {\n for (const name of report.files) {\n if (name < newest && !recorded.has(name)) {\n report.problems.push({\n problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,\n });\n }\n }\n }\n\n return report;\n}\n\n/**\nCLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`.\n*/\nfunction verifyMigrationsCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';\n const write = argv.includes('--write');\n const report = verifyMigrations(dir, { write });\n if (report.problems.length > 0) {\n console.error(`Migration validation failed for ${dir}:`);\n for (const problem of report.problems) console.error(` - ${problem.problem}`);\n return 1;\n }\n if (write) {\n console.log(`Migration lock written (${report.files.length} files).`);\n return 0;\n }\n console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);\n return 0;\n}\n\nexport { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };\nexport type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationReport };\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(verifyMigrationsCli(process.argv.slice(2)));\n}\n"],
5
+ "mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBA6D7B,OAAS,cAAAC,MAAkB,cAC3B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,iBAAA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MAAM,CAAC,EAAC,CAC1E,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,aACnDC,EAAQH,EAAK,SAAS,SAAS,EAC/BT,EAASF,EAAiBY,EAAK,CAAE,MAAAE,CAAK,CAAE,EAC9C,GAAIZ,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,mCAAmCU,CAAG,GAAG,EACvD,UAAWG,KAAWb,EAAO,SAAU,QAAQ,MAAM,OAAOa,EAAQ,OAAO,EAAE,EAC7E,MAAO,EACT,CACA,OAAID,GACF,QAAQ,IAAI,2BAA2BZ,EAAO,MAAM,MAAM,UAAU,EAC7D,IAET,QAAQ,IAAI,gCAAgCA,EAAO,MAAM,MAAM,wBAAwB,EAChF,EACT,CAfS9B,EAAAsC,EAAA,uBA2BLnD,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKmD,EAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["isEntrypoint", "createHash", "existsSync", "readFileSync", "readdirSync", "writeFileSync", "path", "LOCK_NAME", "NAME_PATTERN", "SQUASH_PATTERN", "LOCK_VERSION", "sha256Hex", "content", "__name", "baselineOf", "files", "highest", "name", "isSubsumed", "baseline", "inspectMigrations", "migrationsDir", "problems", "left", "right", "prefixes", "index", "previous", "current", "prefix", "expected", "lockPath", "lock", "buildUpdatedLock", "existing", "digestOf", "kept", "file", "recorded", "entry", "sha256", "verifyMigrations", "options", "report", "updated", "next", "lockfile", "before", "error", "actual", "newest", "verifyMigrationsCli", "argv", "dir", "arg", "write", "problem"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"patches.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAA8B,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAE7E;;EAEE;AACF,MAAM,WAAW,UAAU;IACzB,OAAO,EA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AI,CAEjD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAExE;AAED;;EAEE;AACF,wBAAgB,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAgBnE;AA0BD;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,IAAI,CASxC;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,IAAI,IAAI,CAYjD;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CAYzC;AAED,wBAAgB,cAAc,IAAI,IAAI,CAwBrC"}
@@ -1,4 +1,4 @@
1
- var A=Object.defineProperty;var o=(e,n)=>A(e,"name",{value:n,configurable:!0});import{copyFileSync as y,readFileSync as f,writeFileSync as R}from"node:fs";import{applyEdits as d,modify as v,parse as l}from"jsonc-parser";import{CONFIG_PATH as s,TEMPLATE_PATH as u}from"./types.js";function a(){const e=f(s,"utf8");return{content:e,config:l(e)}}o(a,"readConfig");function c(e,n,r){const t=v(e,n,r,{formattingOptions:{insertSpaces:!0,tabSize:2,eol:`
2
- `}});return d(e,t)}o(c,"writeConfigValue");function p(e){R(s,e.endsWith(`
1
+ var y=Object.defineProperty;var o=(e,n)=>y(e,"name",{value:n,configurable:!0});import{copyFileSync as d,readFileSync as l,writeFileSync as v}from"node:fs";import R from"node:path";import{applyEdits as h,modify as N,parse as m}from"jsonc-parser";import{CONFIG_PATH as i,TEMPLATE_PATH as s}from"./types.js";function a(){const e=l(i,"utf8");return{content:e,config:m(e)}}o(a,"readConfig");function f(e,n,r){const t=N(e,n,r,{formattingOptions:{insertSpaces:!0,tabSize:2,eol:`
2
+ `}});return h(e,t)}o(f,"writeConfigValue");function p(e){v(i,e.endsWith(`
3
3
  `)?e:`${e}
4
- `)}o(p,"writeConfig");function N(){return m(process.env.WRANGLER_PATCH_JSON,"WRANGLER_PATCH_JSON","a JSON object")}o(N,"parseTopLevelPatch");function _(){const e=m(process.env.WRANGLER_VARS_PATCH_JSON,"WRANGLER_VARS_PATCH_JSON","a JSON object of string values");if(e===void 0)return;const n={};for(const[r,t]of Object.entries(e)){if(!r.trim())throw new Error("WRANGLER_VARS_PATCH_JSON contains an empty variable name.");if(typeof t!="string")throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${r} must be a string.`);n[r]=t}return n}o(_,"parseVarsPatch");function m(e,n,r){if(e===void 0||!e.trim())return;let t;try{t=JSON.parse(e)}catch{throw new Error(`${n} must be ${r}.`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${n} must be ${r}.`);return t}o(m,"parseJsonObject");function E(){const e=process.env.WRANGLER_JSONC;if(e?.trim()){p(e),console.log("Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.");return}y(u,s),console.log("WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.")}o(E,"prepareConfigFile");function O(){const e=l(f(u,"utf8"));if(typeof e.$minimumVersion!="number")return;const{config:n}=a(),r=n.$version;if(typeof r!="number"||r<e.$minimumVersion)throw new Error(`wrangler.jsonc version (${typeof r=="number"?r:"missing"}) is below minimum template version (${e.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`)}o(O,"ensureMinimumConfigVersion");function C(){const e=N(),n=Object.entries(e??{});if(n.length===0)return;let{content:r}=a();for(const[t,i]of n)r=c(r,[t],i);p(r),console.log(`Applied ${n.length} Wrangler top-level patch entr${n.length===1?"y":"ies"}.`)}o(C,"applyTopLevelPatch");function $(){const e=_(),n=Object.entries(e??{});if(n.length===0)return;const r=a();let t=r.content;if(r.config.vars!==void 0&&(r.config.vars===null||typeof r.config.vars!="object"||Array.isArray(r.config.vars)))throw new Error("wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.");r.config.vars===void 0&&(t=c(t,["vars"],{}));for(const[i,g]of n)t=c(t,["vars",i],g);p(t),console.log(`Applied ${n.length} Wrangler vars patch entr${n.length===1?"y":"ies"}.`)}o($,"applyVarsPatch");export{C as applyTopLevelPatch,$ as applyVarsPatch,O as ensureMinimumConfigVersion,N as parseTopLevelPatch,_ as parseVarsPatch,E as prepareConfigFile,a as readConfig,p as writeConfig,c as writeConfigValue};
4
+ `)}o(p,"writeConfig");function _(){return g(process.env.WRANGLER_PATCH_JSON,"WRANGLER_PATCH_JSON","a JSON object")}o(_,"parseTopLevelPatch");function S(){const e=g(process.env.WRANGLER_VARS_PATCH_JSON,"WRANGLER_VARS_PATCH_JSON","a JSON object of string values");if(e===void 0)return;const n={};for(const[r,t]of Object.entries(e)){if(!r.trim())throw new Error("WRANGLER_VARS_PATCH_JSON contains an empty variable name.");if(typeof t!="string")throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${r} must be a string.`);n[r]=t}return n}o(S,"parseVarsPatch");function g(e,n,r){if(e===void 0||!e.trim())return;let t;try{t=JSON.parse(e)}catch{throw new Error(`${n} must be ${r}.`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${n} must be ${r}.`);return t}o(g,"parseJsonObject");function u(e){return R.relative(process.cwd(),e)||e}o(u,"displayPath");function C(){const e=process.env.WRANGLER_JSONC;if(e?.trim()){p(e),console.log("Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.");return}d(s,i),console.log(`WRANGLER_JSONC is empty; copied ${u(s)} to ${u(i)}.`)}o(C,"prepareConfigFile");function J(){const e=m(l(s,"utf8"));if(typeof e.$minimumVersion!="number")return;const{config:n}=a(),r=n.$version;if(typeof r!="number"||r<e.$minimumVersion)throw new Error(`wrangler.jsonc version (${typeof r=="number"?r:"missing"}) is below minimum template version (${e.$minimumVersion}). Regenerate it from ${u(s)}.`)}o(J,"ensureMinimumConfigVersion");function P(){const e=_(),n=Object.entries(e??{});if(n.length===0)return;let{content:r}=a();for(const[t,c]of n)r=f(r,[t],c);p(r),console.log(`Applied ${n.length} Wrangler top-level patch entr${n.length===1?"y":"ies"}.`)}o(P,"applyTopLevelPatch");function T(){const e=S(),n=Object.entries(e??{});if(n.length===0)return;const r=a();let t=r.content;if(r.config.vars!==void 0&&(r.config.vars===null||typeof r.config.vars!="object"||Array.isArray(r.config.vars)))throw new Error("wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.");r.config.vars===void 0&&(t=f(t,["vars"],{}));for(const[c,A]of n)t=f(t,["vars",c],A);p(t),console.log(`Applied ${n.length} Wrangler vars patch entr${n.length===1?"y":"ies"}.`)}o(T,"applyVarsPatch");export{P as applyTopLevelPatch,T as applyVarsPatch,J as ensureMinimumConfigVersion,_ as parseTopLevelPatch,S as parseVarsPatch,C as prepareConfigFile,a as readConfig,p as writeConfig,f as writeConfigValue};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/wrangler-config/patches.ts"],
4
- "sourcesContent": ["/**\n * Reading, writing and patching `wrangler.jsonc`.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/patches.ts`.\n *\n * The config is JSONC — `//` comments and trailing commas — so it is edited\n * through jsonc-parser's `modify`/`applyEdits` rather than parsed and re-serialized.\n * A round trip through `JSON.parse` would drop every comment and reformat the\n * file, which is a diff nobody can review and a reason to regenerate the config by\n * hand instead.\n */\n\nimport { copyFileSync, readFileSync, writeFileSync } from 'node:fs';\nimport { applyEdits, modify, parse } from 'jsonc-parser';\nimport { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';\n\n/**\nThe config's current text and its parsed form.\n*/\nexport interface ConfigFile {\n content: string;\n config: WranglerConfig;\n}\n\nexport function readConfig(): ConfigFile {\n const content = readFileSync(CONFIG_PATH, 'utf8');\n return { content, config: parse(content) as WranglerConfig };\n}\n\n/**\n * Apply one edit to the config text, preserving comments and formatting.\n */\nexport function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string {\n const edits = modify(content, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\\n' } });\n return applyEdits(content, edits);\n}\n\n/**\nWrite the config, guaranteeing a trailing newline so Prettier sees a fixed point.\n*/\nexport function writeConfig(content: string): void {\n writeFileSync(CONFIG_PATH, content.endsWith('\\n') ? content : `${content}\\n`);\n}\n\n/**\n * The top-level keys a caller wants to merge into the config, from the environment.\n *\n * `WRANGLER_PATCH_JSON` is how a repository variable supplies per-environment\n * settings without a second file: a repo with one worker and three environments\n * patches the routes and the vars rather than keeping three templates in step.\n */\nexport function parseTopLevelPatch(): Record<string, unknown> | undefined {\n return parseJsonObject(process.env['WRANGLER_PATCH_JSON'], 'WRANGLER_PATCH_JSON', 'a JSON object');\n}\n\n/**\nThe `vars` entries a caller wants to merge, from the environment.\n*/\nexport function parseVarsPatch(): Record<string, string> | undefined {\n const parsed = parseJsonObject(process.env['WRANGLER_VARS_PATCH_JSON'], 'WRANGLER_VARS_PATCH_JSON', 'a JSON object of string values');\n if (parsed === undefined) {\n return undefined;\n }\n const patch: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error('WRANGLER_VARS_PATCH_JSON contains an empty variable name.');\n }\n if (typeof value !== 'string') {\n throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${key} must be a string.`);\n }\n patch[key] = value;\n }\n return patch;\n}\n\nfunction parseJsonObject(raw: string | undefined, name: string, expected: string): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n throw new Error(`${name} must be ${expected}.`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${name} must be ${expected}.`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Materialize the config: the repository variable when it is set, otherwise the\n * committed template.\n */\nexport function prepareConfigFile(): void {\n const dumpedConfig = process.env['WRANGLER_JSONC'];\n if (dumpedConfig?.trim()) {\n writeConfig(dumpedConfig);\n console.log('Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.');\n return;\n }\n copyFileSync(TEMPLATE_PATH, CONFIG_PATH);\n console.log('WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.');\n}\n\n/**\n * Refuse a config older than the template requires.\n *\n * The template is the one file in the repo that says which wrangler behaviour the\n * worker was written against, and a config written by an older template can name\n * bindings the worker no longer reads. Failing here rather than at deploy time is\n * the whole reason the check exists.\n */\nexport function ensureMinimumConfigVersion(): void {\n const template = parse(readFileSync(TEMPLATE_PATH, 'utf8')) as { $minimumVersion?: unknown };\n if (typeof template.$minimumVersion !== 'number') {\n return;\n }\n const { config } = readConfig();\n const currentVersion = config.$version;\n if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {\n throw new Error(\n `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`,\n );\n }\n}\n\nexport function applyTopLevelPatch(): void {\n const patch = parseTopLevelPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n let { content } = readConfig();\n for (const [key, value] of entries) {\n content = writeConfigValue(content, [key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler top-level patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n\nexport function applyVarsPatch(): void {\n const patch = parseVarsPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n const prepared = readConfig();\n let content = prepared.content;\n if (\n prepared.config.vars !== undefined &&\n (prepared.config.vars === null || typeof prepared.config.vars !== 'object' || Array.isArray(prepared.config.vars))\n ) {\n throw new Error('wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.');\n }\n // `null` needs no branch here: the guard above throws for it, so by this\n // line `vars` is either absent or an object.\n if (prepared.config.vars === undefined) {\n content = writeConfigValue(content, ['vars'], {});\n }\n for (const [key, value] of entries) {\n content = writeConfigValue(content, ['vars', key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length}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iBF,EAAS,CAACY,CAAG,EAAGR,CAAK,EAElDE,EAAYN,CAAO,EACnB,QAAQ,IAAI,WAAWuB,EAAQ,MAAM,iCAAiCA,EAAQ,SAAW,EAAI,IAAM,KAAK,GAAG,CAC7G,CAZgBtB,EAAAqB,EAAA,sBAcV,SAAUE,GAAc,CAC5B,MAAMb,EAAQF,EAAc,EACtBc,EAAU,OAAO,QAAQZ,GAAS,CAAA,CAAE,EAC1C,GAAIY,EAAQ,SAAW,EACrB,OAEF,MAAME,EAAW1B,EAAU,EAC3B,IAAIC,EAAUyB,EAAS,QACvB,GACEA,EAAS,OAAO,OAAS,SACxBA,EAAS,OAAO,OAAS,MAAQ,OAAOA,EAAS,OAAO,MAAS,UAAY,MAAM,QAAQA,EAAS,OAAO,IAAI,GAEhH,MAAM,IAAI,MAAM,iFAAiF,EAI/FA,EAAS,OAAO,OAAS,SAC3BzB,EAAUE,EAAiBF,EAAS,CAAC,MAAM,EAAG,CAAA,CAAE,GAElD,SAAW,CAACY,EAAKR,CAAK,IAAKmB,EACzBvB,EAAUE,EAAiBF,EAAS,CAAC,OAAQY,CAAG,EAAGR,CAAK,EAE1DE,EAAYN,CAAO,EACnB,QAAQ,IAAI,WAAWuB,EAAQ,MAAM,4BAA4BA,EAAQ,SAAW,EAAI,IAAM,KAAK,GAAG,CACxG,CAxBgBtB,EAAAuB,EAAA",
6
- "names": ["copyFileSync", "readFileSync", "writeFileSync", "applyEdits", "modify", "parse", "CONFIG_PATH", "TEMPLATE_PATH", "readConfig", "content", "__name", "writeConfigValue", "path", "value", "edits", "writeConfig", "parseTopLevelPatch", "parseJsonObject", "parseVarsPatch", "parsed", "patch", "key", "raw", "name", "expected", "prepareConfigFile", "dumpedConfig", "ensureMinimumConfigVersion", "template", "config", "currentVersion", "applyTopLevelPatch", "entries", "applyVarsPatch", "prepared"]
4
+ "sourcesContent": ["/**\n * Reading, writing and patching `wrangler.jsonc`.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/patches.ts`.\n *\n * The config is JSONC — `//` comments and trailing commas — so it is edited\n * through jsonc-parser's `modify`/`applyEdits` rather than parsed and re-serialized.\n * A round trip through `JSON.parse` would drop every comment and reformat the\n * file, which is a diff nobody can review and a reason to regenerate the config by\n * hand instead.\n */\n\nimport { copyFileSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { applyEdits, modify, parse } from 'jsonc-parser';\nimport { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';\n\n/**\nThe config's current text and its parsed form.\n*/\nexport interface ConfigFile {\n content: string;\n config: WranglerConfig;\n}\n\nexport function readConfig(): ConfigFile {\n const content = readFileSync(CONFIG_PATH, 'utf8');\n return { content, config: parse(content) as WranglerConfig };\n}\n\n/**\n * Apply one edit to the config text, preserving comments and formatting.\n */\nexport function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string {\n const edits = modify(content, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\\n' } });\n return applyEdits(content, edits);\n}\n\n/**\nWrite the config, guaranteeing a trailing newline so Prettier sees a fixed point.\n*/\nexport function writeConfig(content: string): void {\n writeFileSync(CONFIG_PATH, content.endsWith('\\n') ? content : `${content}\\n`);\n}\n\n/**\n * The top-level keys a caller wants to merge into the config, from the environment.\n *\n * `WRANGLER_PATCH_JSON` is how a repository variable supplies per-environment\n * settings without a second file: a repo with one worker and three environments\n * patches the routes and the vars rather than keeping three templates in step.\n */\nexport function parseTopLevelPatch(): Record<string, unknown> | undefined {\n return parseJsonObject(process.env['WRANGLER_PATCH_JSON'], 'WRANGLER_PATCH_JSON', 'a JSON object');\n}\n\n/**\nThe `vars` entries a caller wants to merge, from the environment.\n*/\nexport function parseVarsPatch(): Record<string, string> | undefined {\n const parsed = parseJsonObject(process.env['WRANGLER_VARS_PATCH_JSON'], 'WRANGLER_VARS_PATCH_JSON', 'a JSON object of string values');\n if (parsed === undefined) {\n return undefined;\n }\n const patch: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error('WRANGLER_VARS_PATCH_JSON contains an empty variable name.');\n }\n if (typeof value !== 'string') {\n throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${key} must be a string.`);\n }\n patch[key] = value;\n }\n return patch;\n}\n\nfunction parseJsonObject(raw: string | undefined, name: string, expected: string): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n throw new Error(`${name} must be ${expected}.`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${name} must be ${expected}.`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * A path as a log line should name it: relative to the working directory the\n * script was invoked from, which is the repo root in every consumer.\n */\nfunction displayPath(filePath: string): string {\n return path.relative(process.cwd(), filePath) || filePath;\n}\n\n/**\n * Materialize the config: the repository variable when it is set, otherwise the\n * committed template.\n */\nexport function prepareConfigFile(): void {\n const dumpedConfig = process.env['WRANGLER_JSONC'];\n if (dumpedConfig?.trim()) {\n writeConfig(dumpedConfig);\n console.log('Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.');\n return;\n }\n copyFileSync(TEMPLATE_PATH, CONFIG_PATH);\n console.log(`WRANGLER_JSONC is empty; copied ${displayPath(TEMPLATE_PATH)} to ${displayPath(CONFIG_PATH)}.`);\n}\n\n/**\n * Refuse a config older than the template requires.\n *\n * The template is the one file in the repo that says which wrangler behaviour the\n * worker was written against, and a config written by an older template can name\n * bindings the worker no longer reads. Failing here rather than at deploy time is\n * the whole reason the check exists.\n */\nexport function ensureMinimumConfigVersion(): void {\n const template = parse(readFileSync(TEMPLATE_PATH, 'utf8')) as { $minimumVersion?: unknown };\n if (typeof template.$minimumVersion !== 'number') {\n return;\n }\n const { config } = readConfig();\n const currentVersion = config.$version;\n if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {\n throw new Error(\n `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from ${displayPath(TEMPLATE_PATH)}.`,\n );\n }\n}\n\nexport function applyTopLevelPatch(): void {\n const patch = parseTopLevelPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n let { content } = readConfig();\n for (const [key, value] of entries) {\n content = writeConfigValue(content, [key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler top-level patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n\nexport function applyVarsPatch(): void {\n const patch = parseVarsPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n const prepared = readConfig();\n let content = prepared.content;\n if (\n prepared.config.vars !== undefined &&\n (prepared.config.vars === null || typeof prepared.config.vars !== 'object' || Array.isArray(prepared.config.vars))\n ) {\n throw new Error('wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.');\n }\n // `null` needs no branch here: the guard above throws for it, so by this\n // line `vars` is either absent or an object.\n if (prepared.config.vars === undefined) {\n content = writeConfigValue(content, ['vars'], {});\n }\n for (const [key, value] of entries) {\n content = writeConfigValue(content, ['vars', key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler vars patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n"],
5
+ "mappings": "+EAYA,OAAS,gBAAAA,EAAc,gBAAAC,EAAc,iBAAAC,MAAqB,UAC1D,OAAOC,MAAU,YACjB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,SAAAC,MAAa,eAC1C,OAAS,eAAAC,EAAa,iBAAAC,MAA0C,aAU1D,SAAUC,GAAU,CACxB,MAAMC,EAAUT,EAAaM,EAAa,MAAM,EAChD,MAAO,CAAE,QAAAG,EAAS,OAAQJ,EAAMI,CAAO,CAAmB,CAC5D,CAHgBC,EAAAF,EAAA,cAQV,SAAUG,EAAiBF,EAAiBP,EAA8BU,EAAc,CAC5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EAAc,EACtBgB,EAAU,OAAO,QAAQd,GAAS,CAAA,CAAE,EAC1C,GAAIc,EAAQ,SAAW,EACrB,OAEF,MAAME,EAAW3B,EAAU,EAC3B,IAAIC,EAAU0B,EAAS,QACvB,GACEA,EAAS,OAAO,OAAS,SACxBA,EAAS,OAAO,OAAS,MAAQ,OAAOA,EAAS,OAAO,MAAS,UAAY,MAAM,QAAQA,EAAS,OAAO,IAAI,GAEhH,MAAM,IAAI,MAAM,iFAAiF,EAI/FA,EAAS,OAAO,OAAS,SAC3B1B,EAAUE,EAAiBF,EAAS,CAAC,MAAM,EAAG,CAAA,CAAE,GAElD,SAAW,CAACW,EAAKR,CAAK,IAAKqB,EACzBxB,EAAUE,EAAiBF,EAAS,CAAC,OAAQW,CAAG,EAAGR,CAAK,EAE1DE,EAAYL,CAAO,EACnB,QAAQ,IAAI,WAAWwB,EAAQ,MAAM,4BAA4BA,EAAQ,SAAW,EAAI,IAAM,KAAK,GAAG,CACxG,CAxBgBvB,EAAAwB,EAAA",
6
+ "names": ["copyFileSync", "readFileSync", "writeFileSync", "path", "applyEdits", "modify", "parse", "CONFIG_PATH", "TEMPLATE_PATH", "readConfig", "content", "__name", "writeConfigValue", "value", "edits", "writeConfig", "parseTopLevelPatch", "parseJsonObject", "parseVarsPatch", "parsed", "patch", "key", "raw", "name", "expected", "displayPath", "filePath", "prepareConfigFile", "dumpedConfig", "ensureMinimumConfigVersion", "template", "config", "currentVersion", "applyTopLevelPatch", "entries", "applyVarsPatch", "prepared"]
7
7
  }
@@ -35,21 +35,26 @@ export declare function listD1Databases(): D1Database[];
35
35
  export declare function ensureD1Database(databaseName: string): Provisioned;
36
36
  export declare function listKVNamespaces(): KVNamespace[];
37
37
  /**
38
- The namespace name a binding's namespace is created under.
39
- */
40
- export declare function getKVNamespaceName(config: WranglerConfig, binding: string): string;
41
- export declare function ensureKVNamespace(config: WranglerConfig, binding: string): Provisioned;
38
+ * The namespace name a binding's namespace is created under.
39
+ *
40
+ * `namespaceNames` is the binding → namespace map, defaulting to the kit's
41
+ * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention
42
+ * passes its own, so provisioning finds the namespace that already holds the data
43
+ * instead of creating an empty one beside it and binding the worker to the new one.
44
+ */
45
+ export declare function getKVNamespaceName(config: WranglerConfig, binding: string, namespaceNames?: Record<string, string>): string;
46
+ export declare function ensureKVNamespace(config: WranglerConfig, binding: string, namespaceNames?: Record<string, string>): Provisioned;
42
47
  /**
43
48
  The bindings a deployment always needs, whether or not a custom config lists them.
44
49
  */
45
- export declare function getRequiredKvBindings(): string[];
50
+ export declare function getRequiredKvBindings(namespaceNames?: Record<string, string>): string[];
46
51
  /**
47
52
  * Add the always-needed KV bindings a hand-written config left out.
48
53
  *
49
54
  * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without
50
55
  * this the worker starts with an unbound `CACHE` and fails on the first read.
51
56
  */
52
- export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig): string;
57
+ export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig, namespaceNames?: Record<string, string>): string;
53
58
  /**
54
59
  The stores in a `secrets-store store list` table.
55
60
  */
@@ -73,10 +78,15 @@ export declare function ensureVectorizeIndex(indexName: string, dimensions: numb
73
78
  * Create every resource the config names, and write the real ids over the
74
79
  * placeholders.
75
80
  *
81
+ * `namespaceNames` is the binding → namespace map KV provisioning reconciles
82
+ * against, defaulting to the kit's `DEFAULT_KV_NAMESPACE_NAMES`; a consumer whose
83
+ * namespaces were named before that convention passes its own so the existing
84
+ * namespace is found instead of a second empty one being created.
85
+ *
76
86
  * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,
77
87
  * because a caller acts on it: the backup workflow refuses to export a D1 database
78
88
  * that appears here, since one created moments ago holds no user data and an empty
79
89
  * dump uploaded on schedule is a false sense of safety.
80
90
  */
81
- export declare function provisionWranglerResources(): string[];
91
+ export declare function provisionWranglerResources(namespaceNames?: Record<string, string>): string[];
82
92
  //# sourceMappingURL=resources.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAOL,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AAIpB;;EAEE;AACF,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;EAEE;AACF,wBAAgB,OAAO,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAEhE;AAED,wBAAgB,eAAe,IAAI,UAAU,EAAE,CAE9C;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,WAAW,CAclE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAEhD;AAED;;EAEE;AACF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAkBtF;AAED;;EAEE;AACF,wBAAgB,qBAAqB,IAAI,MAAM,EAAE,CAEhD;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,MAAM,CAYxF;AAED;;EAEE;AACF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,CAmBpE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAQhD;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAmB1C;AAED;;EAEE;AACF,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAUtD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAc7D;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAQhF;AAmED;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,IAAI,MAAM,EAAE,CAqCrD"}
1
+ {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAOL,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AAIpB;;EAEE;AACF,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;EAEE;AACF,wBAAgB,OAAO,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAEhE;AAED,wBAAgB,eAAe,IAAI,UAAU,EAAE,CAE9C;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,WAAW,CAclE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAEhD;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,MAAM,EACf,cAAc,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAClE,MAAM,CAER;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,MAAM,EACf,cAAc,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAClE,WAAW,CAkBb;AAED;;EAEE;AACF,wBAAgB,qBAAqB,CAAC,cAAc,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAAG,MAAM,EAAE,CAEnH;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,cAAc,EACtB,cAAc,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAClE,MAAM,CAYR;AAED;;EAEE;AACF,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,CAmBpE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAQhD;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAmB1C;AAED;;EAEE;AACF,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAUtD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAc7D;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAQhF;AAmED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,0BAA0B,CAAC,cAAc,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAAG,MAAM,EAAE,CAqCxH"}
@@ -1 +1 @@
1
- var v=Object.defineProperty;var a=(e,n)=>v(e,"name",{value:n,configurable:!0});import{parse as f}from"jsonc-parser";import{parseWranglerTableRows as S}from"../lib/wrangler-table.js";import{DEFAULT_HEX_ID as p,DEFAULT_KV_NAMESPACE_NAMES as _,DEFAULT_SECRET_STORE_NAME as u,DEFAULT_UUID as D,DEFAULT_WORKER_NAME as b,VECTORIZE_DIMENSIONS as E}from"./types.js";import{parseJsonArray as m,runWrangler as c}from"./cli.js";import{readConfig as w,writeConfig as q,writeConfigValue as l}from"./patches.js";function I(e){return e.uuid??e.database_id??e.id}a(I,"getD1Id");function h(){return m(c(["d1","list","--json"]),"wrangler d1 list --json")}a(h,"listD1Databases");function V(e){let n=h().find(i=>i.name===e),r=!1;n===void 0&&(console.log(`Creating D1 database: ${e}`),c(["d1","create",e]),n=h().find(i=>i.name===e),r=!0);const t=n===void 0?void 0:I(n);if(t===void 0||t==="")throw new Error(`Unable to discover D1 database ID for ${e}.`);return{id:t,created:r}}a(V,"ensureD1Database");function $(){return m(c(["kv","namespace","list"]),"wrangler kv namespace list")}a($,"listKVNamespaces");function x(e,n){return _[n]??`${e.name??b}-${n.toLowerCase()}`}a(x,"getKVNamespaceName");function K(e,n){const r=x(e,n),t=new Set([r,`${e.name??b}-${n}`,n]);let i=$().find(o=>{const d=o.title??o.name;return o.id!==void 0&&d!==void 0&&t.has(d)}),s=!1;if(i===void 0&&(console.log(`Creating KV namespace: ${r}`),c(["kv","namespace","create",r]),i=$().find(o=>o.id!==void 0&&(o.title??o.name)===r),s=!0),i?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${r}.`);return{id:i.id,created:s}}a(K,"ensureKVNamespace");function U(){return Object.keys(_)}a(U,"getRequiredKvBindings");function A(e,n){const r=new Set((n.kv_namespaces??[]).map(s=>s.binding).filter(s=>s!==void 0)),t=U().filter(s=>!r.has(s));if(t.length===0)return e;const i=[...n.kv_namespaces??[]];for(const s of t)console.log(`Adding missing KV namespace binding: ${s}`),i.push({binding:s,id:p});return l(e,["kv_namespaces"],i)}a(A,"ensureRequiredKvBindings");function C(e){const n=[];for(const r of S(e)){const t=r.at(0),i=r.at(1);t!==void 0&&i!==void 0&&/^[a-f0-9]{32}$/i.test(i)&&n.push({name:t,id:i})}return n}a(C,"parseSecretStoresTable");function g(){const e=c(["secrets-store","store","list","--remote"]);try{return m(e,"wrangler secrets-store store list --remote")}catch{return C(e)}}a(g,"listSecretStores");function k(){const e=g(),n=e.find(o=>o.name===u)??e.at(0);if(n!==void 0)return n.id;console.log(`Creating Secrets Store: ${u}`);const r=c(["secrets-store","store","create",u,"--remote"]),t=/ID:\s*([a-f0-9]{32})/i.exec(r)?.[1];if(t!==void 0)return t;const i=g(),s=i.find(o=>o.name===u)??i.at(0);if(s?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${u}.`);return s.id}a(k,"ensureSecretStore");function T(e){try{return c(["queues","info",e]),console.log(`Queue ${e} already exists.`),!1}catch{return console.log(`Creating queue: ${e}`),c(["queues","create",e]),!0}}a(T,"ensureQueue");function R(e){const n=[],r=new Set;for(const t of e.queues?.producers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));for(const t of e.queues?.consumers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));return n}a(R,"queueNamesIn");function y(e,n){try{c(["vectorize","info",e]),console.log(`Vectorize index ${e} already exists.`)}catch{console.log(`Creating Vectorize index: ${e} with ${n} dimensions`),c(["vectorize","create",e,`--dimensions=${n}`,"--metric=cosine"])}}a(y,"ensureVectorizeIndex");function N(e,n,r){let t=e;for(const[i,s]of n.d1_databases?.entries()??[]){if(s.database_id!==D)continue;if(s.database_name===void 0||s.database_name==="")throw new Error(`D1 database binding ${s.binding??i} has a placeholder database_id but no database_name.`);const o=V(s.database_name);o.created&&r.push(`d1:${s.database_name}`),console.log(`Using D1 database ${s.database_name}: ${o.id}`),t=l(t,["d1_databases",i,"database_id"],o.id)}return t}a(N,"provisionD1Databases");function z(e,n,r){let t=e;for(const[i,s]of n.kv_namespaces?.entries()??[]){if(s.id!==p)continue;if(s.binding===void 0||s.binding==="")throw new Error(`KV namespace at index ${i} has a placeholder id but no binding.`);const o=K(n,s.binding),d=x(n,s.binding);o.created&&r.push(`kv:${d}`),console.log(`Using KV namespace ${d}: ${o.id}`),t=l(t,["kv_namespaces",i,"id"],o.id)}return t}a(z,"provisionKvNamespaces");function L(e,n,r){const t=(n.secrets_store_secrets??[]).map((o,d)=>({secret:o,index:d})).filter(({secret:o})=>o.store_id===p);if(t.length===0)return e;const i=g().some(o=>o.name===u),s=k();return i||r.push(`secrets-store:${u}`),console.log(`Using Secrets Store: ${s}`),t.reduce((o,{index:d})=>l(o,["secrets_store_secrets",d,"store_id"],s),e)}a(L,"provisionSecretStore");function Q(){const e=[];let{content:n,config:r}=w();n=A(n,r),r=f(n),n=N(n,r,e),r=f(n),n=z(n,r,e),r=f(n),n=L(n,r,e),q(n),r=f(n);for(const t of R(r))T(t)&&e.push(`queue:${t}`);for(const t of r.vectorize??[])y(t.index_name,E);return e}a(Q,"provisionWranglerResources");export{V as ensureD1Database,K as ensureKVNamespace,T as ensureQueue,A as ensureRequiredKvBindings,k as ensureSecretStore,y as ensureVectorizeIndex,I as getD1Id,x as getKVNamespaceName,U as getRequiredKvBindings,h as listD1Databases,$ as listKVNamespaces,g as listSecretStores,C as parseSecretStoresTable,Q as provisionWranglerResources,R as queueNamesIn};
1
+ var S=Object.defineProperty;var a=(e,t)=>S(e,"name",{value:t,configurable:!0});import{parse as p}from"jsonc-parser";import{parseWranglerTableRows as D}from"../lib/wrangler-table.js";import{DEFAULT_HEX_ID as g,DEFAULT_KV_NAMESPACE_NAMES as l,DEFAULT_SECRET_STORE_NAME as u,DEFAULT_UUID as E,DEFAULT_WORKER_NAME as h,VECTORIZE_DIMENSIONS as w}from"./types.js";import{parseJsonArray as _,runWrangler as d}from"./cli.js";import{readConfig as q,writeConfig as I,writeConfigValue as m}from"./patches.js";function V(e){return e.uuid??e.database_id??e.id}a(V,"getD1Id");function $(){return _(d(["d1","list","--json"]),"wrangler d1 list --json")}a($,"listD1Databases");function K(e){let t=$().find(o=>o.name===e),r=!1;t===void 0&&(console.log(`Creating D1 database: ${e}`),d(["d1","create",e]),t=$().find(o=>o.name===e),r=!0);const n=t===void 0?void 0:V(t);if(n===void 0||n==="")throw new Error(`Unable to discover D1 database ID for ${e}.`);return{id:n,created:r}}a(K,"ensureD1Database");function x(){return _(d(["kv","namespace","list"]),"wrangler kv namespace list")}a(x,"listKVNamespaces");function v(e,t,r=l){return r[t]??`${e.name??h}-${t.toLowerCase()}`}a(v,"getKVNamespaceName");function U(e,t,r=l){const n=v(e,t,r),o=new Set([n,`${e.name??h}-${t}`,t]);let i=x().find(c=>{const f=c.title??c.name;return c.id!==void 0&&f!==void 0&&o.has(f)}),s=!1;if(i===void 0&&(console.log(`Creating KV namespace: ${n}`),d(["kv","namespace","create",n]),i=x().find(c=>c.id!==void 0&&(c.title??c.name)===n),s=!0),i?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${n}.`);return{id:i.id,created:s}}a(U,"ensureKVNamespace");function A(e=l){return Object.keys(e)}a(A,"getRequiredKvBindings");function C(e,t,r=l){const n=new Set((t.kv_namespaces??[]).map(s=>s.binding).filter(s=>s!==void 0)),o=A(r).filter(s=>!n.has(s));if(o.length===0)return e;const i=[...t.kv_namespaces??[]];for(const s of o)console.log(`Adding missing KV namespace binding: ${s}`),i.push({binding:s,id:g});return m(e,["kv_namespaces"],i)}a(C,"ensureRequiredKvBindings");function k(e){const t=[];for(const r of D(e)){const n=r.at(0),o=r.at(1);n!==void 0&&o!==void 0&&/^[a-f0-9]{32}$/i.test(o)&&t.push({name:n,id:o})}return t}a(k,"parseSecretStoresTable");function b(){const e=d(["secrets-store","store","list","--remote"]);try{return _(e,"wrangler secrets-store store list --remote")}catch{return k(e)}}a(b,"listSecretStores");function T(){const e=b(),t=e.find(s=>s.name===u)??e.at(0);if(t!==void 0)return t.id;console.log(`Creating Secrets Store: ${u}`);const r=d(["secrets-store","store","create",u,"--remote"]),n=/ID:\s*([a-f0-9]{32})/i.exec(r)?.[1];if(n!==void 0)return n;const o=b(),i=o.find(s=>s.name===u)??o.at(0);if(i?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${u}.`);return i.id}a(T,"ensureSecretStore");function R(e){try{return d(["queues","info",e]),console.log(`Queue ${e} already exists.`),!1}catch{return console.log(`Creating queue: ${e}`),d(["queues","create",e]),!0}}a(R,"ensureQueue");function y(e){const t=[],r=new Set;for(const n of e.queues?.producers??[])n.queue===""||r.has(n.queue)||(r.add(n.queue),t.push(n.queue));for(const n of e.queues?.consumers??[])n.queue===""||r.has(n.queue)||(r.add(n.queue),t.push(n.queue));return t}a(y,"queueNamesIn");function z(e,t){try{d(["vectorize","info",e]),console.log(`Vectorize index ${e} already exists.`)}catch{console.log(`Creating Vectorize index: ${e} with ${t} dimensions`),d(["vectorize","create",e,`--dimensions=${t}`,"--metric=cosine"])}}a(z,"ensureVectorizeIndex");function L(e,t,r){let n=e;for(const[o,i]of t.d1_databases?.entries()??[]){if(i.database_id!==E)continue;if(i.database_name===void 0||i.database_name==="")throw new Error(`D1 database binding ${i.binding??o} has a placeholder database_id but no database_name.`);const s=K(i.database_name);s.created&&r.push(`d1:${i.database_name}`),console.log(`Using D1 database ${i.database_name}: ${s.id}`),n=m(n,["d1_databases",o,"database_id"],s.id)}return n}a(L,"provisionD1Databases");function F(e,t,r,n){let o=e;for(const[i,s]of t.kv_namespaces?.entries()??[]){if(s.id!==g)continue;if(s.binding===void 0||s.binding==="")throw new Error(`KV namespace at index ${i} has a placeholder id but no binding.`);const c=U(t,s.binding,n),f=v(t,s.binding,n);c.created&&r.push(`kv:${f}`),console.log(`Using KV namespace ${f}: ${c.id}`),o=m(o,["kv_namespaces",i,"id"],c.id)}return o}a(F,"provisionKvNamespaces");function M(e,t,r){const n=(t.secrets_store_secrets??[]).map((s,c)=>({secret:s,index:c})).filter(({secret:s})=>s.store_id===g);if(n.length===0)return e;const o=b().some(s=>s.name===u),i=T();return o||r.push(`secrets-store:${u}`),console.log(`Using Secrets Store: ${i}`),n.reduce((s,{index:c})=>m(s,["secrets_store_secrets",c,"store_id"],i),e)}a(M,"provisionSecretStore");function H(e=l){const t=[];let{content:r,config:n}=q();r=C(r,n,e),n=p(r),r=L(r,n,t),n=p(r),r=F(r,n,t,e),n=p(r),r=M(r,n,t),I(r),n=p(r);for(const o of y(n))R(o)&&t.push(`queue:${o}`);for(const o of n.vectorize??[])z(o.index_name,w);return t}a(H,"provisionWranglerResources");export{K as ensureD1Database,U as ensureKVNamespace,R as ensureQueue,C as ensureRequiredKvBindings,T as ensureSecretStore,z as ensureVectorizeIndex,V as getD1Id,v as getKVNamespaceName,A as getRequiredKvBindings,$ as listD1Databases,x as listKVNamespaces,b as listSecretStores,k as parseSecretStoresTable,H as provisionWranglerResources,y as queueNamesIn};