@rexezuge/tooling 1.13.0 → 1.15.0

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 (138) hide show
  1. package/README.md +67 -34
  2. package/dist/eslint-options.d.ts +54 -0
  3. package/dist/eslint-options.d.ts.map +1 -0
  4. package/dist/eslint-options.js +0 -0
  5. package/dist/eslint-options.js.map +7 -0
  6. package/dist/eslint-rules.d.ts.map +1 -1
  7. package/dist/eslint-rules.js +1 -1
  8. package/dist/eslint-rules.js.map +2 -2
  9. package/dist/eslint-strict.d.ts +2 -1
  10. package/dist/eslint-strict.d.ts.map +1 -1
  11. package/dist/eslint-strict.js +2 -1
  12. package/dist/eslint-strict.js.map +3 -3
  13. package/dist/eslint.d.ts +2 -53
  14. package/dist/eslint.d.ts.map +1 -1
  15. package/dist/eslint.js.map +2 -2
  16. package/dist/manifest-validate.d.ts.map +1 -1
  17. package/dist/manifest-validate.js +1 -1
  18. package/dist/manifest-validate.js.map +3 -3
  19. package/dist/manifest.d.ts +21 -0
  20. package/dist/manifest.d.ts.map +1 -1
  21. package/dist/manifest.js.map +2 -2
  22. package/dist/pages-proxy.d.ts +2 -0
  23. package/dist/pages-proxy.d.ts.map +1 -0
  24. package/dist/pages-proxy.js +1 -0
  25. package/dist/pages-proxy.js.map +7 -0
  26. package/dist/plugin-option.d.ts +15 -0
  27. package/dist/plugin-option.d.ts.map +1 -0
  28. package/dist/plugin-option.js +1 -0
  29. package/dist/plugin-option.js.map +7 -0
  30. package/dist/scripts/backup/destinations.d.ts +40 -0
  31. package/dist/scripts/backup/destinations.d.ts.map +1 -0
  32. package/dist/scripts/backup/destinations.js +1 -0
  33. package/dist/scripts/backup/destinations.js.map +7 -0
  34. package/dist/scripts/backup/encrypt-backup.d.ts +5 -2
  35. package/dist/scripts/backup/encrypt-backup.d.ts.map +1 -1
  36. package/dist/scripts/backup/encrypt-backup.js +2 -3
  37. package/dist/scripts/backup/encrypt-backup.js.map +3 -3
  38. package/dist/scripts/backup/naming.d.ts +1 -1
  39. package/dist/scripts/backup/naming.d.ts.map +1 -1
  40. package/dist/scripts/backup/naming.js +1 -1
  41. package/dist/scripts/backup/naming.js.map +3 -3
  42. package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
  43. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
  44. package/dist/scripts/ensure-spa-shell-stub.js +1 -2
  45. package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
  46. package/dist/scripts/init-secrets.d.ts +1 -2
  47. package/dist/scripts/init-secrets.d.ts.map +1 -1
  48. package/dist/scripts/init-secrets.js +2 -3
  49. package/dist/scripts/init-secrets.js.map +3 -3
  50. package/dist/scripts/migrations-lock.d.ts +6 -2
  51. package/dist/scripts/migrations-lock.d.ts.map +1 -1
  52. package/dist/scripts/migrations-lock.js +1 -2
  53. package/dist/scripts/migrations-lock.js.map +3 -3
  54. package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
  55. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
  56. package/dist/scripts/prepare-wrangler-config.js +1 -2
  57. package/dist/scripts/prepare-wrangler-config.js.map +3 -3
  58. package/dist/scripts/validate-locales.d.ts +20 -2
  59. package/dist/scripts/validate-locales.d.ts.map +1 -1
  60. package/dist/scripts/validate-locales.js +5 -5
  61. package/dist/scripts/validate-locales.js.map +3 -3
  62. package/dist/scripts/verify-spa-shell.d.ts +7 -2
  63. package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
  64. package/dist/scripts/verify-spa-shell.js +1 -2
  65. package/dist/scripts/verify-spa-shell.js.map +3 -3
  66. package/dist/scripts/wrangler-config/resources.d.ts +11 -2
  67. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  68. package/dist/scripts/wrangler-config/resources.js +1 -1
  69. package/dist/scripts/wrangler-config/resources.js.map +3 -3
  70. package/dist/vite.d.ts +2 -1
  71. package/dist/vite.d.ts.map +1 -1
  72. package/dist/vite.js +3 -3
  73. package/dist/vite.js.map +3 -3
  74. package/dist/vitest-aliases.d.ts +7 -1
  75. package/dist/vitest-aliases.d.ts.map +1 -1
  76. package/dist/vitest-aliases.js +1 -1
  77. package/dist/vitest-aliases.js.map +3 -3
  78. package/dist/vitest-integration.d.ts +3 -2
  79. package/dist/vitest-integration.d.ts.map +1 -1
  80. package/dist/vitest-integration.js +1 -1
  81. package/dist/vitest-integration.js.map +3 -3
  82. package/dist/vitest-repo.d.ts +3 -2
  83. package/dist/vitest-repo.d.ts.map +1 -1
  84. package/dist/vitest-repo.js +1 -1
  85. package/dist/vitest-repo.js.map +3 -3
  86. package/dist/vitest-web.d.ts +3 -2
  87. package/dist/vitest-web.d.ts.map +1 -1
  88. package/dist/vitest-web.js +1 -1
  89. package/dist/vitest-web.js.map +3 -3
  90. package/dist/vitest.d.ts +4 -3
  91. package/dist/vitest.d.ts.map +1 -1
  92. package/dist/vitest.js +1 -1
  93. package/dist/vitest.js.map +3 -3
  94. package/package.json +3 -3
  95. package/presets/tsconfig/web.json +2 -2
  96. package/schema/manifest.schema.json +28 -1
  97. package/src/eslint-options.ts +54 -0
  98. package/src/eslint-rules.ts +4 -0
  99. package/src/eslint-strict.test.ts +29 -0
  100. package/src/eslint-strict.ts +36 -4
  101. package/src/eslint.ts +2 -53
  102. package/src/github/dependabot.yml +14 -4
  103. package/src/github/workflows/backup-d1.yml +15 -0
  104. package/src/github/workflows/backup-main.yml +9 -126
  105. package/src/github/workflows/continuous-deployment.yml +11 -180
  106. package/src/github/workflows/continuous-integration.yml +9 -249
  107. package/src/github/workflows/scheduled-version-update.yml +8 -31
  108. package/src/github/workflows/upstream-sync.yml +8 -49
  109. package/src/manifest-validate.ts +31 -2
  110. package/src/manifest.test.ts +22 -0
  111. package/src/manifest.ts +22 -0
  112. package/src/pages-proxy.test.ts +8 -0
  113. package/src/pages-proxy.ts +13 -0
  114. package/src/plugin-option.test.ts +13 -0
  115. package/src/plugin-option.ts +18 -0
  116. package/src/presets.test.ts +5 -1
  117. package/src/scripts/backup/backup-rules.test.ts +22 -0
  118. package/src/scripts/backup/destinations.ts +59 -0
  119. package/src/scripts/backup/encrypt-backup.ts +58 -48
  120. package/src/scripts/backup/naming.ts +2 -2
  121. package/src/scripts/ensure-spa-shell-stub.ts +18 -10
  122. package/src/scripts/entrypoints.test.ts +55 -0
  123. package/src/scripts/init-secrets.ts +8 -6
  124. package/src/scripts/migrations-lock.ts +22 -17
  125. package/src/scripts/prepare-wrangler-config.ts +34 -14
  126. package/src/scripts/validate-locales.ts +39 -17
  127. package/src/scripts/verify-spa-shell.ts +21 -20
  128. package/src/scripts/wrangler-config/resources.test.ts +10 -0
  129. package/src/scripts/wrangler-config/resources.ts +21 -4
  130. package/src/vite.ts +5 -3
  131. package/src/vitest-aliases.test.ts +33 -0
  132. package/src/vitest-aliases.ts +37 -7
  133. package/src/vitest-integration.ts +7 -8
  134. package/src/vitest-repo.ts +7 -5
  135. package/src/vitest-web.ts +7 -5
  136. package/src/vitest.ts +8 -6
  137. package/src/github/actions/retry-step/action.yml +0 -55
  138. package/src/github/actions/setup-env/action.yml +0 -20
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/validate-locales.ts"],
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,IAA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7B,EAAW,KAAI,CAAE,EAAGU,EAAOe,CAAI,CAAC,CAE7D,OAAS7C,EAAgB,CACvBkB,EAAS,KAAK,CAAE,OAAQ,YAAa,QAAS,GAAG8C,CAAW,KAAKhE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAAE,CAC7H,CAGF,MAAMmE,EAAWjD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EACjEC,EAAanD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EAEzE,GAAID,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,gCAAgCnB,CAAG,KAAKmB,EAAS,MAAM,eAAe,EACpF,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EACzF,MAAO,EACT,CACA,GAAIC,EAAW,OAAS,EAAG,CACzB,QAAQ,KAAK,gCAAgCrB,CAAG,SAASqB,EAAW,MAAM,uBAAuB,EACjG,UAAWD,KAAWC,EAAY,QAAQ,KAAK,OAAOD,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,CAC5F,CACA,eAAQ,IAAI,6BAA6BF,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB/D,CAAK,IAAI,EAC7G,CACT,CA9CS3B,EAAAoF,EAAA,sBA0DLhG,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKgG,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["isEntrypoint", "existsSync", "readdirSync", "readFileSync", "path", "flatten", "value", "prefix", "out", "entries", "key", "child", "__name", "placeholdersOf", "left", "right", "readBundle", "file", "source", "parseObjectLiteral", "objectLiteralStart", "quote", "inLineComment", "inBlockComment", "index", "char", "next", "previous", "brace", "start", "depth", "end", "withoutTrailingCommas", "_match", "body", "unescapeLiteral", "error", "FLAT_EXTENSION", "layouts", "shape", "tagsOnDisk", "localesDir", "tags", "entry", "layout", "extension", "name", "bundleFor", "locale", "candidates", "candidate", "bundleAt", "baseLocale", "validateLocales", "problems", "baseFile", "baseBundle", "baseKeys", "locales", "a", "b", "bundle", "expected", "actual", "token", "collectCallSites", "scope", "full", "sourceFiles", "pattern", "match", "where", "inline", "readDefault", "bundled", "from", "rest", "decodeStringLiteral", "raw", "whole", "usedKeys", "used", "files", "walk", "dir", "collectUnusedKeys", "prefixes", "dynamicKeyPrefixes", "unused", "head", "declaredTags", "tag", "checkDeclaredTags", "declaredFile", "onDisk", "declared", "validateLocalesCli", "argv", "arg", "base", "callSiteDir", "tagsFile", "report", "failures", "problem", "advisories"]
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, problems } = collectLocaleProblems({ dir, base, shape, callSiteDir, tagsFile });\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\n/**\nWhat `collectLocaleProblems` checks: the bundles, and optionally the declared tags and the `t()` call sites.\n*/\ninterface LocaleCheckOptions {\n dir: string;\n base?: string;\n shape?: LocaleShape;\n callSiteDir?: string;\n tagsFile?: string;\n}\n\n/**\n * Every finding for one locales directory, as data. The CLI prints it and `rexezuge locales validate --json` serializes it;\n * advisories carry `advisory: true`, everything else is a failure.\n */\nfunction collectLocaleProblems(options: LocaleCheckOptions): { report: LocaleReport; problems: LocaleProblem[] } {\n const { dir, callSiteDir, tagsFile } = options;\n const base = options.base ?? 'en';\n const shape = options.shape ?? 'auto';\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 return { report, problems };\n}\n\nexport { collectLocaleProblems, parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleCheckOptions, 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,Y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AAQ,SAAAhD,CAAQ,CAC3B,CA7BS1C,EAAA2F,EAAA,yBAyCLvG,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", "collectLocaleProblems", "failures", "problem", "advisories", "options"]
7
7
  }
@@ -1,3 +1,8 @@
1
- #!/usr/bin/env tsx
2
- export {};
1
+ /**
2
+ * Verify the shell. `args[0]` is the repo root, derived from this file when absent
3
+ * rather than from `process.cwd()`: the gate reads the same tree whatever directory
4
+ * it is invoked from, which is the difference between a gate and a gate that passes
5
+ * because nobody ran it from the right place. Returns the exit code.
6
+ */
7
+ export declare function main(args?: readonly string[]): number;
3
8
  //# sourceMappingURL=verify-spa-shell.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"verify-spa-shell.d.ts","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"verify-spa-shell.d.ts","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":"AAmCA;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CAa5E"}
@@ -1,2 +1 @@
1
- #!/usr/bin/env tsx
2
- import e from"node:path";import{fileURLToPath as l}from"node:url";import{verifySpaShell as t}from"./spa-shell.js";const p=e.resolve(e.dirname(l(import.meta.url)),".."),o=process.argv[2]===void 0?p:e.resolve(process.argv[2]),{problems:r}=t({root:o});if(r.length>0){console.error("SPA shell check failed:");for(const s of r)console.error(` - ${s}`);process.exit(1)}console.log(`SPA shell check passed (${e.join(o,"apps/api/src/generated/spa-shell.ts")} matches ${e.join(o,"apps/web/dist")}).`);
1
+ var p=Object.defineProperty;var i=(e,r)=>p(e,"name",{value:r,configurable:!0});import o from"node:path";import{fileURLToPath as n}from"node:url";import{isEntrypoint as c}from"./lib/entrypoint.js";import{verifySpaShell as m}from"./spa-shell.js";function a(e=process.argv.slice(2)){const r=o.resolve(o.dirname(n(import.meta.url)),".."),t=e[0]===void 0?r:o.resolve(e[0]),{problems:s}=m({root:t});if(s.length>0){console.error("SPA shell check failed:");for(const l of s)console.error(` - ${l}`);return 1}return console.log(`SPA shell check passed (${o.join(t,"apps/api/src/generated/spa-shell.ts")} matches ${o.join(t,"apps/web/dist")}).`),0}i(a,"main"),c(import.meta.url)&&process.exit(a());export{a as main};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/verify-spa-shell.ts"],
4
- "sourcesContent": ["#!/usr/bin/env tsx\n/**\n * Fail when the SPA shell the API worker serves is missing or self-inconsistent.\n *\n * Provenance: Durable-DAV's and Durable-DAV-Router's `scripts/verify-spa-shell.mjs`\n * and Edge-Sonic's typed `scripts/build/verify-spa-shell.ts`. The rules — which of\n * the ways a shell can be wrong to look for — live in `spa-shell.ts`, so they are\n * unit tested without a build on disk; this file is the entrypoint that turns the\n * verdict into an exit code.\n *\n * What it catches:\n *\n * - the `postinstall` stub, or no build at all, still in place;\n * - `spa-shell.ts` referencing `/assets/...` bundles that were not emitted (a\n * partially cleaned or half-copied `dist/`, which serves a shell whose JS 404s\n * and therefore renders no operator UI at all);\n * - `spa-shell.ts` and `apps/web/dist/index.html` disagreeing, i.e. only one of\n * the two halves of the build was refreshed.\n *\n * **The build is a precondition of this check, not a convenience.** Both paths are\n * gitignored and `postinstall` writes a deliberately empty stub, so verifying\n * without building cannot pass — and it fails with precisely the message above,\n * which is the check working rather than the check being wrong.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/verify-spa-shell.ts # defaults to ./ as root\n * pnpm exec tsx scripts/verify-spa-shell.ts --root /path/to/repo\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { verifySpaShell } from './spa-shell.ts';\n\n/**\n * The repository root, derived from this file rather than from `process.cwd()`.\n *\n * Two levels up, because this file sits in `scripts/`. Deriving it means the gate\n * reads the same tree whatever directory it is invoked from — which is the\n * difference between a gate and a gate that passes because nobody ran it from the\n * right place.\n */\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\n\nconst root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);\n\nconst { problems } = verifySpaShell({ root });\n\nif (problems.length > 0) {\n console.error('SPA shell check failed:');\n for (const problem of problems) console.error(` - ${problem}`);\n process.exit(1);\n}\n\nconsole.log(\n `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,\n);\n"],
5
- "mappings": ";AA+BA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,kBAAAC,MAAsB,iBAU/B,MAAMC,EAAkBH,EAAK,QAAQA,EAAK,QAAQC,EAAc,YAAY,GAAG,CAAC,EAAG,IAAI,EAEjFG,EAAO,QAAQ,KAAK,CAAC,IAAM,OAAYD,EAAkBH,EAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,EAErF,CAAE,SAAAK,CAAQ,EAAKH,EAAe,CAAE,KAAAE,CAAI,CAAE,EAE5C,GAAIC,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,CAAO,EAAE,EAC9D,QAAQ,KAAK,CAAC,CAChB,CAEA,QAAQ,IACN,2BAA2BN,EAAK,KAAKI,EAAM,qCAAqC,CAAC,YAAYJ,EAAK,KAAKI,EAAM,eAAe,CAAC,IAAI",
6
- "names": ["path", "fileURLToPath", "verifySpaShell", "REPOSITORY_ROOT", "root", "problems", "problem"]
4
+ "sourcesContent": ["/**\n * Fail when the SPA shell the API worker serves is missing or self-inconsistent.\n *\n * Provenance: Durable-DAV's and Durable-DAV-Router's `scripts/verify-spa-shell.mjs`\n * and Edge-Sonic's typed `scripts/build/verify-spa-shell.ts`. The rules — which of\n * the ways a shell can be wrong to look for — live in `spa-shell.ts`, so they are\n * unit tested without a build on disk; this file is the entrypoint that turns the\n * verdict into an exit code.\n *\n * What it catches:\n *\n * - the `postinstall` stub, or no build at all, still in place;\n * - `spa-shell.ts` referencing `/assets/...` bundles that were not emitted (a\n * partially cleaned or half-copied `dist/`, which serves a shell whose JS 404s\n * and therefore renders no operator UI at all);\n * - `spa-shell.ts` and `apps/web/dist/index.html` disagreeing, i.e. only one of\n * the two halves of the build was refreshed.\n *\n * **The build is a precondition of this check, not a convenience.** Both paths are\n * gitignored and `postinstall` writes a deliberately empty stub, so verifying\n * without building cannot pass — and it fails with precisely the message above,\n * which is the check working rather than the check being wrong.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/verify-spa-shell.ts # defaults to ./ as root\n * pnpm exec tsx scripts/verify-spa-shell.ts --root /path/to/repo\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { verifySpaShell } from './spa-shell.ts';\n\n/**\n * Verify the shell. `args[0]` is the repo root, derived from this file when absent\n * rather than from `process.cwd()`: the gate reads the same tree whatever directory\n * it is invoked from, which is the difference between a gate and a gate that passes\n * because nobody ran it from the right place. Returns the exit code.\n */\nexport function main(args: readonly string[] = process.argv.slice(2)): number {\n const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\n const root = args[0] === undefined ? repositoryRoot : path.resolve(args[0]);\n const { problems } = verifySpaShell({ root });\n if (problems.length > 0) {\n console.error('SPA shell check failed:');\n for (const problem of problems) console.error(` - ${problem}`);\n return 1;\n }\n console.log(\n `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,\n );\n return 0;\n}\n\nif (isEntrypoint(import.meta.url)) {\n process.exit(main());\n}\n"],
5
+ "mappings": "+EA8BA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,kBAAAC,MAAsB,iBAQzB,SAAUC,EAAKC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAClE,MAAMC,EAAiBN,EAAK,QAAQA,EAAK,QAAQC,EAAc,YAAY,GAAG,CAAC,EAAG,IAAI,EAChFM,EAAOF,EAAK,CAAC,IAAM,OAAYC,EAAiBN,EAAK,QAAQK,EAAK,CAAC,CAAC,EACpE,CAAE,SAAAG,CAAQ,EAAKL,EAAe,CAAE,KAAAI,CAAI,CAAE,EAC5C,GAAIC,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,CAAO,EAAE,EAC9D,MAAO,EACT,CACA,eAAQ,IACN,2BAA2BT,EAAK,KAAKO,EAAM,qCAAqC,CAAC,YAAYP,EAAK,KAAKO,EAAM,eAAe,CAAC,IAAI,EAE5H,CACT,CAbgBG,EAAAN,EAAA,QAeZF,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKE,EAAI,CAAE",
6
+ "names": ["path", "fileURLToPath", "isEntrypoint", "verifySpaShell", "main", "args", "repositoryRoot", "root", "problems", "problem", "__name"]
7
7
  }
@@ -37,6 +37,7 @@ export declare function listKVNamespaces(): KVNamespace[];
37
37
  /**
38
38
  * The namespace name a binding's namespace is created under.
39
39
  *
40
+ * Takes either {@link ProvisionOptions} or (legacy) the bare binding → namespace map. `requiredKvBindings` defaults to the map's keys.
40
41
  * `namespaceNames` is the binding → namespace map, defaulting to the kit's
41
42
  * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention
42
43
  * passes its own, so provisioning finds the namespace that already holds the data
@@ -48,13 +49,21 @@ export declare function ensureKVNamespace(config: WranglerConfig, binding: strin
48
49
  The bindings a deployment always needs, whether or not a custom config lists them.
49
50
  */
50
51
  export declare function getRequiredKvBindings(namespaceNames?: Record<string, string>): string[];
52
+ /**
53
+ What `prepare-wrangler` provisions beyond the placeholders a config already carries: the manifest-declared KV bindings
54
+ (`features.kv`). Nothing declared means no KV binding is added.
55
+ */
56
+ export interface ProvisionOptions {
57
+ readonly namespaceNames?: Record<string, string>;
58
+ readonly requiredKvBindings?: readonly string[];
59
+ }
51
60
  /**
52
61
  * Add the always-needed KV bindings a hand-written config left out.
53
62
  *
54
63
  * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without
55
64
  * this the worker starts with an unbound `CACHE` and fails on the first read.
56
65
  */
57
- export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig, namespaceNames?: Record<string, string>): string;
66
+ export declare function ensureRequiredKvBindings(content: string, config: WranglerConfig, namespaceNames?: Record<string, string>, requiredBindings?: readonly string[]): string;
58
67
  /**
59
68
  The stores in a `secrets-store store list` table.
60
69
  */
@@ -88,5 +97,5 @@ export declare function ensureVectorizeIndex(indexName: string, dimensions: numb
88
97
  * that appears here, since one created moments ago holds no user data and an empty
89
98
  * dump uploaded on schedule is a false sense of safety.
90
99
  */
91
- export declare function provisionWranglerResources(namespaceNames?: Record<string, string>): string[];
100
+ export declare function provisionWranglerResources(options?: ProvisionOptions | Record<string, string>): string[];
92
101
  //# 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;;;;;;;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
+ {"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,gBAAg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AAM,GAAG,IAAI,CAQhF;AAuED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,GAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAA8B,GAAG,MAAM,EAAE,CAuCpI"}
@@ -1 +1 @@
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};
1
+ var D=Object.defineProperty;var c=(e,t)=>D(e,"name",{value:t,configurable:!0});import{parse as p}from"jsonc-parser";import{parseWranglerTableRows as E}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 w,DEFAULT_WORKER_NAME as h,VECTORIZE_DIMENSIONS as q}from"./types.js";import{parseJsonArray as _,runWrangler as d}from"./cli.js";import{readConfig as I,writeConfig as K,writeConfigValue as m}from"./patches.js";function V(e){return e.uuid??e.database_id??e.id}c(V,"getD1Id");function $(){return _(d(["d1","list","--json"]),"wrangler d1 list --json")}c($,"listD1Databases");function U(e){let t=$().find(o=>o.name===e),a=!1;t===void 0&&(console.log(`Creating D1 database: ${e}`),d(["d1","create",e]),t=$().find(o=>o.name===e),a=!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:a}}c(U,"ensureD1Database");function v(){return _(d(["kv","namespace","list"]),"wrangler kv namespace list")}c(v,"listKVNamespaces");function x(e,t,a=l){return a[t]??`${e.name??h}-${t.toLowerCase()}`}c(x,"getKVNamespaceName");function A(e,t,a=l){const n=x(e,t,a),o=new Set([n,`${e.name??h}-${t}`,t]);let r=v().find(i=>{const f=i.title??i.name;return i.id!==void 0&&f!==void 0&&o.has(f)}),s=!1;if(r===void 0&&(console.log(`Creating KV namespace: ${n}`),d(["kv","namespace","create",n]),r=v().find(i=>i.id!==void 0&&(i.title??i.name)===n),s=!0),r?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${n}.`);return{id:r.id,created:s}}c(A,"ensureKVNamespace");function S(e=l){return Object.keys(e)}c(S,"getRequiredKvBindings");function C(e,t,a=l,n=S(a)){const o=new Set((t.kv_namespaces??[]).map(i=>i.binding).filter(i=>i!==void 0)),r=n.filter(i=>!o.has(i));if(r.length===0)return e;const s=[...t.kv_namespaces??[]];for(const i of r)console.log(`Adding missing KV namespace binding: ${i}`),s.push({binding:i,id:g});return m(e,["kv_namespaces"],s)}c(C,"ensureRequiredKvBindings");function k(e){const t=[];for(const a of E(e)){const n=a.at(0),o=a.at(1);n!==void 0&&o!==void 0&&/^[a-f0-9]{32}$/i.test(o)&&t.push({name:n,id:o})}return t}c(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)}}c(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 a=d(["secrets-store","store","create",u,"--remote"]),n=/ID:\s*([a-f0-9]{32})/i.exec(a)?.[1];if(n!==void 0)return n;const o=b(),r=o.find(s=>s.name===u)??o.at(0);if(r?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${u}.`);return r.id}c(T,"ensureSecretStore");function N(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}}c(N,"ensureQueue");function R(e){const t=[],a=new Set;for(const n of e.queues?.producers??[])n.queue===""||a.has(n.queue)||(a.add(n.queue),t.push(n.queue));for(const n of e.queues?.consumers??[])n.queue===""||a.has(n.queue)||(a.add(n.queue),t.push(n.queue));return t}c(R,"queueNamesIn");function y(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"])}}c(y,"ensureVectorizeIndex");function z(e,t,a){let n=e;for(const[o,r]of t.d1_databases?.entries()??[]){if(r.database_id!==w)continue;if(r.database_name===void 0||r.database_name==="")throw new Error(`D1 database binding ${r.binding??o} has a placeholder database_id but no database_name.`);const s=U(r.database_name);s.created&&a.push(`d1:${r.database_name}`),console.log(`Using D1 database ${r.database_name}: ${s.id}`),n=m(n,["d1_databases",o,"database_id"],s.id)}return n}c(z,"provisionD1Databases");function L(e,t,a,n){let o=e;for(const[r,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 ${r} has a placeholder id but no binding.`);const i=A(t,s.binding,n),f=x(t,s.binding,n);i.created&&a.push(`kv:${f}`),console.log(`Using KV namespace ${f}: ${i.id}`),o=m(o,["kv_namespaces",r,"id"],i.id)}return o}c(L,"provisionKvNamespaces");function O(e,t,a){const n=(t.secrets_store_secrets??[]).map((s,i)=>({secret:s,index:i})).filter(({secret:s})=>s.store_id===g);if(n.length===0)return e;const o=b().some(s=>s.name===u),r=T();return o||a.push(`secrets-store:${u}`),console.log(`Using Secrets Store: ${r}`),n.reduce((s,{index:i})=>m(s,["secrets_store_secrets",i,"store_id"],r),e)}c(O,"provisionSecretStore");function F(e){return"namespaceNames"in e||"requiredKvBindings"in e}c(F,"isProvisionOptions");function H(e=l){const{namespaceNames:t,requiredKvBindings:a}=F(e)?e:{namespaceNames:e},n=t??{},o=[];let{content:r,config:s}=I();r=C(r,s,n,a??S(n)),s=p(r),r=z(r,s,o),s=p(r),r=L(r,s,o,n),s=p(r),r=O(r,s,o),K(r),s=p(r);for(const i of R(s))N(i)&&o.push(`queue:${i}`);for(const i of s.vectorize??[])y(i.index_name,q);return o}c(H,"provisionWranglerResources");export{U as ensureD1Database,A as ensureKVNamespace,N as ensureQueue,C as ensureRequiredKvBindings,T as ensureSecretStore,y as ensureVectorizeIndex,V as getD1Id,x as getKVNamespaceName,S as getRequiredKvBindings,$ as listD1Databases,v as listKVNamespaces,b as listSecretStores,k as parseSecretStoresTable,H as provisionWranglerResources,R as queueNamesIn};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/wrangler-config/resources.ts"],
4
- "sourcesContent": ["/**\n * Creating the resources `wrangler.jsonc` names, and writing their real ids over\n * the placeholders.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/resources.ts`.\n *\n * The placeholder rule: a template carries an all-zero id meaning \"resolve me\",\n * and a config carrying one cannot be deployed. So provisioning walks the config,\n * creates what is missing, and patches the id in place. A placeholder with nothing\n * to create it *under* — a KV id with no binding, a D1 id with no name — is\n * refused rather than skipped, because a silently skipped placeholder is a deploy\n * that fails later with no link back to the reason.\n */\n\nimport { parse } from 'jsonc-parser';\nimport { parseWranglerTableRows } from '../lib/wrangler-table.ts';\nimport {\n DEFAULT_HEX_ID,\n DEFAULT_KV_NAMESPACE_NAMES,\n DEFAULT_SECRET_STORE_NAME,\n DEFAULT_UUID,\n DEFAULT_WORKER_NAME,\n VECTORIZE_DIMENSIONS,\n type D1Database,\n type KVNamespace,\n type SecretStore,\n type WranglerConfig,\n} from './types.ts';\nimport { parseJsonArray, runWrangler } from './cli.ts';\nimport { readConfig, writeConfig, writeConfigValue } from './patches.ts';\n\n/**\nWhat `ensure*` did, so a caller can act on the difference.\n*/\nexport interface Provisioned {\n id: string;\n created: boolean;\n}\n\n/**\nThe id a D1 database is reported under, whichever key the CLI used.\n*/\nexport function getD1Id(database: D1Database): string | undefined {\n return database.uuid ?? database.database_id ?? database.id;\n}\n\nexport function listD1Databases(): D1Database[] {\n return parseJsonArray<D1Database>(runWrangler(['d1', 'list', '--json']), 'wrangler d1 list --json');\n}\n\n/**\n * The D1 database `binding` names, created when it does not exist.\n *\n * Whether it was created is reported, not inferred: a database created moments ago\n * holds no user data, so a backup workflow must refuse to upload its empty dump.\n * The caller cannot re-derive that from the config, because this very function\n * patches the placeholder away before the reader ever runs.\n */\nexport function ensureD1Database(databaseName: string): Provisioned {\n let database = listD1Databases().find((candidate) => candidate.name === databaseName);\n let created = false;\n if (database === undefined) {\n console.log(`Creating D1 database: ${databaseName}`);\n runWrangler(['d1', 'create', databaseName]);\n database = listD1Databases().find((candidate) => candidate.name === databaseName);\n created = true;\n }\n const databaseId = database === undefined ? undefined : getD1Id(database);\n if (databaseId === undefined || databaseId === '') {\n throw new Error(`Unable to discover D1 database ID for ${databaseName}.`);\n }\n return { id: databaseId, created };\n}\n\nexport function listKVNamespaces(): KVNamespace[] {\n return parseJsonArray<KVNamespace>(runWrangler(['kv', 'namespace', 'list']), 'wrangler kv namespace list');\n}\n\n/**\n * The namespace name a binding's namespace is created under.\n *\n * `namespaceNames` is the binding → namespace map, defaulting to the kit's\n * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention\n * passes its own, so provisioning finds the namespace that already holds the data\n * instead of creating an empty one beside it and binding the worker to the new one.\n */\nexport function getKVNamespaceName(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): string {\n return namespaceNames[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding, namespaceNames);\n const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);\n let namespace = listKVNamespaces().find((candidate) => {\n const candidateName = candidate.title ?? candidate.name;\n return candidate.id !== undefined && candidateName !== undefined && candidateNames.has(candidateName);\n });\n let created = false;\n if (namespace === undefined) {\n console.log(`Creating KV namespace: ${namespaceName}`);\n runWrangler(['kv', 'namespace', 'create', namespaceName]);\n namespace = listKVNamespaces().find((candidate) => candidate.id !== undefined && (candidate.title ?? candidate.name) === namespaceName);\n created = true;\n }\n if (namespace?.id === undefined) {\n throw new Error(`Unable to discover KV namespace ID for ${namespaceName}.`);\n }\n return { id: namespace.id, created };\n}\n\n/**\nThe bindings a deployment always needs, whether or not a custom config lists them.\n*/\nexport function getRequiredKvBindings(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n return Object.keys(namespaceNames);\n}\n\n/**\n * Add the always-needed KV bindings a hand-written config left out.\n *\n * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without\n * this the worker starts with an unbound `CACHE` and fails on the first read.\n */\nexport function ensureRequiredKvBindings(\n content: string,\n config: WranglerConfig,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = getRequiredKvBindings(namespaceNames).filter((binding) => !existing.has(binding));\n if (missing.length === 0) {\n return content;\n }\n const next = [...(config.kv_namespaces ?? [])];\n for (const binding of missing) {\n console.log(`Adding missing KV namespace binding: ${binding}`);\n next.push({ binding, id: DEFAULT_HEX_ID });\n }\n return writeConfigValue(content, ['kv_namespaces'], next);\n}\n\n/**\nThe stores in a `secrets-store store list` table.\n*/\nexport function parseSecretStoresTable(output: string): SecretStore[] {\n const stores: SecretStore[] = [];\n // Through the shared table parser rather than a second inline split: `wrangler`\n // renders through `cli-table3`, whose cells are separated by U+2502 and are *not*\n // space-aligned, so a parser written for aligned output silently matches nothing\n // — which reads as \"the store does not exist\" and makes provisioning create a\n // duplicate.\n for (const row of parseWranglerTableRows(output)) {\n // `.at()` rather than indexing: a short row is possible when the table\n // shape drifts, and the guards below are what skip it.\n const name = row.at(0);\n const id = row.at(1);\n // Store ids are 32 hex characters; a row without one is a header, a border, or\n // an unrelated column, and is skipped rather than stored with an undefined id.\n if (name !== undefined && id !== undefined && /^[a-f0-9]{32}$/i.test(id)) {\n stores.push({ name, id });\n }\n }\n return stores;\n}\n\nexport function listSecretStores(): SecretStore[] {\n const output = runWrangler(['secrets-store', 'store', 'list', '--remote']);\n try {\n return parseJsonArray<SecretStore>(output, 'wrangler secrets-store store list --remote');\n } catch {\n // The subcommand prints a table rather than JSON on some versions.\n return parseSecretStoresTable(output);\n }\n}\n\nexport function ensureSecretStore(): string {\n const stores = listSecretStores();\n const existing = stores.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? stores.at(0);\n if (existing !== undefined) {\n return existing.id;\n }\n console.log(`Creating Secrets Store: ${DEFAULT_SECRET_STORE_NAME}`);\n const output = runWrangler(['secrets-store', 'store', 'create', DEFAULT_SECRET_STORE_NAME, '--remote']);\n const createdStoreId = /ID:\\s*([a-f0-9]{32})/i.exec(output)?.[1];\n if (createdStoreId !== undefined) {\n return createdStoreId;\n }\n // The create output did not name the id, so read it back rather than guessing.\n const refreshed = listSecretStores();\n const store = refreshed.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? refreshed.at(0);\n if (store?.id === undefined) {\n throw new Error(`Unable to discover Secrets Store ID for ${DEFAULT_SECRET_STORE_NAME}.`);\n }\n return store.id;\n}\n\n/**\nCreate a queue when it is absent, reporting whether it had to be created.\n*/\nexport function ensureQueue(queueName: string): boolean {\n try {\n runWrangler(['queues', 'info', queueName]);\n console.log(`Queue ${queueName} already exists.`);\n return false;\n } catch {\n console.log(`Creating queue: ${queueName}`);\n runWrangler(['queues', 'create', queueName]);\n return true;\n }\n}\n\n/**\n * Queue names a deployment needs, in first-seen order.\n *\n * Producers and consumers name the same queue twice — one queue, two roles — and a\n * name appearing in both must be created once. Pure so it is testable without\n * wrangler.\n */\nexport function queueNamesIn(config: WranglerConfig): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const producer of config.queues?.producers ?? []) {\n if (producer.queue === '' || seen.has(producer.queue)) continue;\n seen.add(producer.queue);\n names.push(producer.queue);\n }\n for (const consumer of config.queues?.consumers ?? []) {\n if (consumer.queue === '' || seen.has(consumer.queue)) continue;\n seen.add(consumer.queue);\n names.push(consumer.queue);\n }\n return names;\n}\n\nexport function ensureVectorizeIndex(indexName: string, dimensions: number): void {\n try {\n runWrangler(['vectorize', 'info', indexName]);\n console.log(`Vectorize index ${indexName} already exists.`);\n } catch {\n console.log(`Creating Vectorize index: ${indexName} with ${dimensions} dimensions`);\n runWrangler(['vectorize', 'create', indexName, `--dimensions=${dimensions}`, '--metric=cosine']);\n }\n}\n\n/**\nReplace each placeholder D1 `database_id` with a real one.\n*/\nfunction provisionD1Databases(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, database] of config.d1_databases?.entries() ?? []) {\n if (database.database_id !== DEFAULT_UUID) continue;\n if (database.database_name === undefined || database.database_name === '') {\n throw new Error(`D1 database binding ${database.binding ?? index} has a placeholder database_id but no database_name.`);\n }\n const resolved = ensureD1Database(database.database_name);\n if (resolved.created) {\n created.push(`d1:${database.database_name}`);\n }\n console.log(`Using D1 database ${database.database_name}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['d1_databases', index, 'database_id'], resolved.id);\n }\n return patched;\n}\n\n/**\nReplace each placeholder KV namespace id with a real one.\n*/\nfunction provisionKvNamespaces(content: string, config: WranglerConfig, created: string[], namespaceNames: Record<string, string>): string {\n let patched = content;\n for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {\n if (namespace.id !== DEFAULT_HEX_ID) continue;\n if (namespace.binding === undefined || namespace.binding === '') {\n throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);\n }\n const resolved = ensureKVNamespace(config, namespace.binding, namespaceNames);\n const namespaceName = getKVNamespaceName(config, namespace.binding, namespaceNames);\n if (resolved.created) {\n created.push(`kv:${namespaceName}`);\n }\n console.log(`Using KV namespace ${namespaceName}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['kv_namespaces', index, 'id'], resolved.id);\n }\n return patched;\n}\n\n/**\n * Point every placeholder Secrets Store `store_id` at one store, creating it if\n * absent. `existed` is read **before** the create, because whether the store was\n * created is what the caller reports.\n */\nfunction provisionSecretStore(content: string, config: WranglerConfig, created: string[]): string {\n const placeholders = (config.secrets_store_secrets ?? [])\n .map((secret, index) => ({ secret, index }))\n .filter(({ secret }) => secret.store_id === DEFAULT_HEX_ID);\n if (placeholders.length === 0) {\n return content;\n }\n const existed = listSecretStores().some((store) => store.name === DEFAULT_SECRET_STORE_NAME);\n const storeId = ensureSecretStore();\n if (!existed) {\n created.push(`secrets-store:${DEFAULT_SECRET_STORE_NAME}`);\n }\n console.log(`Using Secrets Store: ${storeId}`);\n return placeholders.reduce(\n (patched, { index }) => writeConfigValue(patched, ['secrets_store_secrets', index, 'store_id'], storeId),\n content,\n );\n}\n\n/**\n * Create every resource the config names, and write the real ids over the\n * placeholders.\n *\n * `namespaceNames` is the binding → namespace map KV provisioning reconciles\n * against, defaulting to the kit's `DEFAULT_KV_NAMESPACE_NAMES`; a consumer whose\n * namespaces were named before that convention passes its own so the existing\n * namespace is found instead of a second empty one being created.\n *\n * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,\n * because a caller acts on it: the backup workflow refuses to export a D1 database\n * that appears here, since one created moments ago holds no user data and an empty\n * dump uploaded on schedule is a false sense of safety.\n */\nexport function provisionWranglerResources(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config, namespaceNames);\n config = parse(content) as WranglerConfig;\n\n // Each of the three below re-parses before it patches, because each writes into\n // the config text the previous one produced. They are separate functions because\n // they are separate resources with separate rules, and one loop holding all\n // three would read as a single resource list with the differences hidden in the\n // bodies.\n content = provisionD1Databases(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionKvNamespaces(content, config, created, namespaceNames);\n config = parse(content) as WranglerConfig;\n\n content = provisionSecretStore(content, config, created);\n\n writeConfig(content);\n\n config = parse(content) as WranglerConfig;\n for (const queueName of queueNamesIn(config)) {\n if (ensureQueue(queueName)) {\n created.push(`queue:${queueName}`);\n }\n }\n\n // Vectorize indexes are name-based, so nothing in the file is patched — but the\n // created names are still reported like every other resource, so a deploy log\n // shows what appeared.\n for (const binding of config.vectorize ?? []) {\n ensureVectorizeIndex(binding.index_name, VECTORIZE_DIMENSIONS);\n }\n\n return created;\n}\n"],
5
- "mappings": "+EAcA,OAAS,SAAAA,MAAa,eACtB,OAAS,0BAAAC,MAA8B,2BACvC,OACE,kBAAAC,EACA,8BAAAC,EACA,6BAAAC,EACA,gBAAAC,EACA,uBAAAC,EACA,wBAAAC,MAKK,aACP,OAAS,kBAAAC,EAAgB,eAAAC,MAAmB,WAC5C,OAAS,cAAAC,EAAY,eAAAC,EAAa,oBAA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vB,EAAgB,EAAG,KAAMI,GAAUA,EAAM,OAAS5C,CAAyB,EACrFgE,EAAUvB,EAAiB,EACjC,OAAKsB,GACH/C,EAAQ,KAAK,iBAAiBhB,CAAyB,EAAE,EAE3D,QAAQ,IAAI,wBAAwBgE,CAAO,EAAE,EACtCH,EAAa,OAClB,CAACL,EAAS,CAAE,MAAAC,CAAK,IAAOjD,EAAiBgD,EAAS,CAAC,wBAAyBC,EAAO,UAAU,EAAGO,CAAO,EACvGlC,CAAO,CAEX,CAjBSnB,EAAAiD,EAAA,wBAiCH,SAAUK,EAA2B3C,EAAyCvB,EAA0B,CAC5G,MAAMiB,EAAoB,CAAA,EAC1B,GAAI,CAAE,QAAAc,EAAS,OAAAV,CAAM,EAAKd,EAAU,EAEpCwB,EAAUD,EAAyBC,EAASV,EAAQE,CAAc,EAClEF,EAASxB,EAAMkC,CAAO,EAOtBA,EAAUyB,EAAqBzB,EAASV,EAAQJ,CAAO,EACvDI,EAASxB,EAAMkC,CAAO,EAEtBA,EAAU6B,EAAsB7B,EAASV,EAAQJ,EAASM,CAAc,EACxEF,EAASxB,EAAMkC,CAAO,EAEtBA,EAAU8B,EAAqB9B,EAASV,EAAQJ,CAAO,EAEvDT,EAAYuB,CAAO,EAEnBV,EAASxB,EAAMkC,CAAO,EACtB,UAAWgB,KAAaC,EAAa3B,CAAM,EACrCyB,EAAYC,CAAS,GACvB9B,EAAQ,KAAK,SAAS8B,CAAS,EAAE,EAOrC,UAAWzB,KAAWD,EAAO,WAAa,CAAA,EACxCgC,EAAqB/B,EAAQ,WAAYlB,CAAoB,EAG/D,OAAOa,CACT,CArCgBL,EAAAsD,EAAA",
6
- "names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "__name", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "namespaceNames", "ensureKVNamespace", "namespaceName", "candidateNames", "namespace", "candidateName", "getRequiredKvBindings", "ensureRequiredKvBindings", "content", "existing", "missing", "next", "parseSecretStoresTable", "output", "stores", "row", "name", "id", "listSecretStores", "ensureSecretStore", "createdStoreId", "refreshed", "store", "ensureQueue", "queueName", "queueNamesIn", "names", "seen", "producer", "consumer", "ensureVectorizeIndex", "indexName", "dimensions", "provisionD1Databases", "patched", "index", "resolved", "provisionKvNamespaces", "provisionSecretStore", "placeholders", "secret", "existed", "storeId", "provisionWranglerResources"]
4
+ "sourcesContent": ["/**\n * Creating the resources `wrangler.jsonc` names, and writing their real ids over\n * the placeholders.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/resources.ts`.\n *\n * The placeholder rule: a template carries an all-zero id meaning \"resolve me\",\n * and a config carrying one cannot be deployed. So provisioning walks the config,\n * creates what is missing, and patches the id in place. A placeholder with nothing\n * to create it *under* — a KV id with no binding, a D1 id with no name — is\n * refused rather than skipped, because a silently skipped placeholder is a deploy\n * that fails later with no link back to the reason.\n */\n\nimport { parse } from 'jsonc-parser';\nimport { parseWranglerTableRows } from '../lib/wrangler-table.ts';\nimport {\n DEFAULT_HEX_ID,\n DEFAULT_KV_NAMESPACE_NAMES,\n DEFAULT_SECRET_STORE_NAME,\n DEFAULT_UUID,\n DEFAULT_WORKER_NAME,\n VECTORIZE_DIMENSIONS,\n type D1Database,\n type KVNamespace,\n type SecretStore,\n type WranglerConfig,\n} from './types.ts';\nimport { parseJsonArray, runWrangler } from './cli.ts';\nimport { readConfig, writeConfig, writeConfigValue } from './patches.ts';\n\n/**\nWhat `ensure*` did, so a caller can act on the difference.\n*/\nexport interface Provisioned {\n id: string;\n created: boolean;\n}\n\n/**\nThe id a D1 database is reported under, whichever key the CLI used.\n*/\nexport function getD1Id(database: D1Database): string | undefined {\n return database.uuid ?? database.database_id ?? database.id;\n}\n\nexport function listD1Databases(): D1Database[] {\n return parseJsonArray<D1Database>(runWrangler(['d1', 'list', '--json']), 'wrangler d1 list --json');\n}\n\n/**\n * The D1 database `binding` names, created when it does not exist.\n *\n * Whether it was created is reported, not inferred: a database created moments ago\n * holds no user data, so a backup workflow must refuse to upload its empty dump.\n * The caller cannot re-derive that from the config, because this very function\n * patches the placeholder away before the reader ever runs.\n */\nexport function ensureD1Database(databaseName: string): Provisioned {\n let database = listD1Databases().find((candidate) => candidate.name === databaseName);\n let created = false;\n if (database === undefined) {\n console.log(`Creating D1 database: ${databaseName}`);\n runWrangler(['d1', 'create', databaseName]);\n database = listD1Databases().find((candidate) => candidate.name === databaseName);\n created = true;\n }\n const databaseId = database === undefined ? undefined : getD1Id(database);\n if (databaseId === undefined || databaseId === '') {\n throw new Error(`Unable to discover D1 database ID for ${databaseName}.`);\n }\n return { id: databaseId, created };\n}\n\nexport function listKVNamespaces(): KVNamespace[] {\n return parseJsonArray<KVNamespace>(runWrangler(['kv', 'namespace', 'list']), 'wrangler kv namespace list');\n}\n\n/**\n * The namespace name a binding's namespace is created under.\n *\n * Takes either {@link ProvisionOptions} or (legacy) the bare binding → namespace map. `requiredKvBindings` defaults to the map's keys.\n * `namespaceNames` is the binding → namespace map, defaulting to the kit's\n * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention\n * passes its own, so provisioning finds the namespace that already holds the data\n * instead of creating an empty one beside it and binding the worker to the new one.\n */\nexport function getKVNamespaceName(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): string {\n return namespaceNames[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(\n config: WranglerConfig,\n binding: string,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding, namespaceNames);\n const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);\n let namespace = listKVNamespaces().find((candidate) => {\n const candidateName = candidate.title ?? candidate.name;\n return candidate.id !== undefined && candidateName !== undefined && candidateNames.has(candidateName);\n });\n let created = false;\n if (namespace === undefined) {\n console.log(`Creating KV namespace: ${namespaceName}`);\n runWrangler(['kv', 'namespace', 'create', namespaceName]);\n namespace = listKVNamespaces().find((candidate) => candidate.id !== undefined && (candidate.title ?? candidate.name) === namespaceName);\n created = true;\n }\n if (namespace?.id === undefined) {\n throw new Error(`Unable to discover KV namespace ID for ${namespaceName}.`);\n }\n return { id: namespace.id, created };\n}\n\n/**\nThe bindings a deployment always needs, whether or not a custom config lists them.\n*/\nexport function getRequiredKvBindings(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n return Object.keys(namespaceNames);\n}\n\n/**\nWhat `prepare-wrangler` provisions beyond the placeholders a config already carries: the manifest-declared KV bindings\n(`features.kv`). Nothing declared means no KV binding is added.\n*/\nexport interface ProvisionOptions {\n readonly namespaceNames?: Record<string, string>;\n readonly requiredKvBindings?: readonly string[];\n}\n\n/**\n * Add the always-needed KV bindings a hand-written config left out.\n *\n * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without\n * this the worker starts with an unbound `CACHE` and fails on the first read.\n */\nexport function ensureRequiredKvBindings(\n content: string,\n config: WranglerConfig,\n namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,\n requiredBindings: readonly string[] = getRequiredKvBindings(namespaceNames),\n): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = requiredBindings.filter((binding) => !existing.has(binding));\n if (missing.length === 0) {\n return content;\n }\n const next = [...(config.kv_namespaces ?? [])];\n for (const binding of missing) {\n console.log(`Adding missing KV namespace binding: ${binding}`);\n next.push({ binding, id: DEFAULT_HEX_ID });\n }\n return writeConfigValue(content, ['kv_namespaces'], next);\n}\n\n/**\nThe stores in a `secrets-store store list` table.\n*/\nexport function parseSecretStoresTable(output: string): SecretStore[] {\n const stores: SecretStore[] = [];\n // Through the shared table parser rather than a second inline split: `wrangler`\n // renders through `cli-table3`, whose cells are separated by U+2502 and are *not*\n // space-aligned, so a parser written for aligned output silently matches nothing\n // — which reads as \"the store does not exist\" and makes provisioning create a\n // duplicate.\n for (const row of parseWranglerTableRows(output)) {\n // `.at()` rather than indexing: a short row is possible when the table\n // shape drifts, and the guards below are what skip it.\n const name = row.at(0);\n const id = row.at(1);\n // Store ids are 32 hex characters; a row without one is a header, a border, or\n // an unrelated column, and is skipped rather than stored with an undefined id.\n if (name !== undefined && id !== undefined && /^[a-f0-9]{32}$/i.test(id)) {\n stores.push({ name, id });\n }\n }\n return stores;\n}\n\nexport function listSecretStores(): SecretStore[] {\n const output = runWrangler(['secrets-store', 'store', 'list', '--remote']);\n try {\n return parseJsonArray<SecretStore>(output, 'wrangler secrets-store store list --remote');\n } catch {\n // The subcommand prints a table rather than JSON on some versions.\n return parseSecretStoresTable(output);\n }\n}\n\nexport function ensureSecretStore(): string {\n const stores = listSecretStores();\n const existing = stores.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? stores.at(0);\n if (existing !== undefined) {\n return existing.id;\n }\n console.log(`Creating Secrets Store: ${DEFAULT_SECRET_STORE_NAME}`);\n const output = runWrangler(['secrets-store', 'store', 'create', DEFAULT_SECRET_STORE_NAME, '--remote']);\n const createdStoreId = /ID:\\s*([a-f0-9]{32})/i.exec(output)?.[1];\n if (createdStoreId !== undefined) {\n return createdStoreId;\n }\n // The create output did not name the id, so read it back rather than guessing.\n const refreshed = listSecretStores();\n const store = refreshed.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? refreshed.at(0);\n if (store?.id === undefined) {\n throw new Error(`Unable to discover Secrets Store ID for ${DEFAULT_SECRET_STORE_NAME}.`);\n }\n return store.id;\n}\n\n/**\nCreate a queue when it is absent, reporting whether it had to be created.\n*/\nexport function ensureQueue(queueName: string): boolean {\n try {\n runWrangler(['queues', 'info', queueName]);\n console.log(`Queue ${queueName} already exists.`);\n return false;\n } catch {\n console.log(`Creating queue: ${queueName}`);\n runWrangler(['queues', 'create', queueName]);\n return true;\n }\n}\n\n/**\n * Queue names a deployment needs, in first-seen order.\n *\n * Producers and consumers name the same queue twice — one queue, two roles — and a\n * name appearing in both must be created once. Pure so it is testable without\n * wrangler.\n */\nexport function queueNamesIn(config: WranglerConfig): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const producer of config.queues?.producers ?? []) {\n if (producer.queue === '' || seen.has(producer.queue)) continue;\n seen.add(producer.queue);\n names.push(producer.queue);\n }\n for (const consumer of config.queues?.consumers ?? []) {\n if (consumer.queue === '' || seen.has(consumer.queue)) continue;\n seen.add(consumer.queue);\n names.push(consumer.queue);\n }\n return names;\n}\n\nexport function ensureVectorizeIndex(indexName: string, dimensions: number): void {\n try {\n runWrangler(['vectorize', 'info', indexName]);\n console.log(`Vectorize index ${indexName} already exists.`);\n } catch {\n console.log(`Creating Vectorize index: ${indexName} with ${dimensions} dimensions`);\n runWrangler(['vectorize', 'create', indexName, `--dimensions=${dimensions}`, '--metric=cosine']);\n }\n}\n\n/**\nReplace each placeholder D1 `database_id` with a real one.\n*/\nfunction provisionD1Databases(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, database] of config.d1_databases?.entries() ?? []) {\n if (database.database_id !== DEFAULT_UUID) continue;\n if (database.database_name === undefined || database.database_name === '') {\n throw new Error(`D1 database binding ${database.binding ?? index} has a placeholder database_id but no database_name.`);\n }\n const resolved = ensureD1Database(database.database_name);\n if (resolved.created) {\n created.push(`d1:${database.database_name}`);\n }\n console.log(`Using D1 database ${database.database_name}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['d1_databases', index, 'database_id'], resolved.id);\n }\n return patched;\n}\n\n/**\nReplace each placeholder KV namespace id with a real one.\n*/\nfunction provisionKvNamespaces(content: string, config: WranglerConfig, created: string[], namespaceNames: Record<string, string>): string {\n let patched = content;\n for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {\n if (namespace.id !== DEFAULT_HEX_ID) continue;\n if (namespace.binding === undefined || namespace.binding === '') {\n throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);\n }\n const resolved = ensureKVNamespace(config, namespace.binding, namespaceNames);\n const namespaceName = getKVNamespaceName(config, namespace.binding, namespaceNames);\n if (resolved.created) {\n created.push(`kv:${namespaceName}`);\n }\n console.log(`Using KV namespace ${namespaceName}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['kv_namespaces', index, 'id'], resolved.id);\n }\n return patched;\n}\n\n/**\n * Point every placeholder Secrets Store `store_id` at one store, creating it if\n * absent. `existed` is read **before** the create, because whether the store was\n * created is what the caller reports.\n */\nfunction provisionSecretStore(content: string, config: WranglerConfig, created: string[]): string {\n const placeholders = (config.secrets_store_secrets ?? [])\n .map((secret, index) => ({ secret, index }))\n .filter(({ secret }) => secret.store_id === DEFAULT_HEX_ID);\n if (placeholders.length === 0) {\n return content;\n }\n const existed = listSecretStores().some((store) => store.name === DEFAULT_SECRET_STORE_NAME);\n const storeId = ensureSecretStore();\n if (!existed) {\n created.push(`secrets-store:${DEFAULT_SECRET_STORE_NAME}`);\n }\n console.log(`Using Secrets Store: ${storeId}`);\n return placeholders.reduce(\n (patched, { index }) => writeConfigValue(patched, ['secrets_store_secrets', index, 'store_id'], storeId),\n content,\n );\n}\n\nfunction isProvisionOptions(value: ProvisionOptions | Record<string, string>): value is ProvisionOptions {\n return 'namespaceNames' in value || 'requiredKvBindings' in value;\n}\n\n/**\n * Create every resource the config names, and write the real ids over the\n * placeholders.\n *\n * `namespaceNames` is the binding → namespace map KV provisioning reconciles\n * against, defaulting to the kit's `DEFAULT_KV_NAMESPACE_NAMES`; a consumer whose\n * namespaces were named before that convention passes its own so the existing\n * namespace is found instead of a second empty one being created.\n *\n * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,\n * because a caller acts on it: the backup workflow refuses to export a D1 database\n * that appears here, since one created moments ago holds no user data and an empty\n * dump uploaded on schedule is a false sense of safety.\n */\nexport function provisionWranglerResources(options: ProvisionOptions | Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {\n const { namespaceNames, requiredKvBindings }: ProvisionOptions = isProvisionOptions(options) ? options : { namespaceNames: options };\n const names = namespaceNames ?? {};\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config, names, requiredKvBindings ?? getRequiredKvBindings(names));\n config = parse(content) as WranglerConfig;\n\n // Each of the three below re-parses before it patches, because each writes into\n // the config text the previous one produced. They are separate functions because\n // they are separate resources with separate rules, and one loop holding all\n // three would read as a single resource list with the differences hidden in the\n // bodies.\n content = provisionD1Databases(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionKvNamespaces(content, config, created, names);\n config = parse(content) as WranglerConfig;\n\n content = provisionSecretStore(content, config, created);\n\n writeConfig(content);\n\n config = parse(content) as WranglerConfig;\n for (const queueName of queueNamesIn(config)) {\n if (ensureQueue(queueName)) {\n created.push(`queue:${queueName}`);\n }\n }\n\n // Vectorize indexes are name-based, so nothing in the file is patched — but the\n // created names are still reported like every other resource, so a deploy log\n // shows what appeared.\n for (const binding of config.vectorize ?? []) {\n ensureVectorizeIndex(binding.index_name, VECTORIZE_DIMENSIONS);\n }\n\n return created;\n}\n"],
5
+ "mappings": "+EAcA,OAAS,SAAAA,MAAa,eACtB,OAAS,0BAAAC,MAA8B,2BACvC,OACE,kBAAAC,EACA,8BAAAC,EACA,6BAAAC,EACA,gBAAAC,EACA,uBAAAC,EACA,wBAAAC,MAKK,aACP,OAAS,kBAAAC,EAAgB,eAAAC,MAAmB,WAC5C,OAAS,cAAAC,EAAY,eAAAC,EAAa,oBAAAC,MAAwB,eAapD,SAAUC,EAAQC,EAAoB,CAC1C,OAAOA,EAAS,MAAQA,EAAS,aAAeA,EAAS,EA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 "names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "__name", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "namespaceNames", "ensureKVNamespace", "namespaceName", "candidateNames", "namespace", "candidateName", "getRequiredKvBindings", "ensureRequiredKvBindings", "content", "requiredBindings", "existing", "missing", "next", "parseSecretStoresTable", "output", "stores", "row", "name", "id", "listSecretStores", "ensureSecretStore", "createdStoreId", "refreshed", "store", "ensureQueue", "queueName", "queueNamesIn", "names", "seen", "producer", "consumer", "ensureVectorizeIndex", "indexName", "dimensions", "provisionD1Databases", "patched", "index", "resolved", "provisionKvNamespaces", "provisionSecretStore", "placeholders", "secret", "existed", "storeId", "isProvisionOptions", "value", "provisionWranglerResources", "options", "requiredKvBindings"]
7
7
  }
package/dist/vite.d.ts CHANGED
@@ -29,6 +29,7 @@
29
29
  * README.
30
30
  */
31
31
  import { type Plugin, type ViteUserConfig } from 'vitest/config';
32
+ import type { PluginOption } from './plugin-option.ts';
32
33
  /**
33
34
  * One dev-server proxy entry, as Vite's `server.proxy` accepts it.
34
35
  */
@@ -99,7 +100,7 @@ export interface WebViteConfigOptions {
99
100
  * needs. Applied before the spa-shell plugin so the shell is written after the
100
101
  * bundle exists.
101
102
  */
102
- readonly plugins?: readonly Plugin[];
103
+ readonly plugins?: readonly PluginOption[];
103
104
  /**
104
105
  * Dev-server proxy entries. Keyed by path prefix.
105
106
  */
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EAAgB,KAAK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AAC;IACtD;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC;IACnC;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AA4DD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,IAAI,CAAA;CAAE,CAoChG;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,cAAc,CActF"}
package/dist/vite.js CHANGED
@@ -1,3 +1,3 @@
1
- var f=Object.defineProperty;var t=(e,n)=>f(e,"name",{value:n,configurable:!0});import{existsSync as l,mkdirSync as p,readFileSync as c,writeFileSync as h}from"node:fs";import m from"node:path";import{fileURLToPath as i,pathToFileURL as x}from"node:url";import{defineConfig as y}from"vitest/config";function d(e){return e instanceof URL?e:e.startsWith("file:")?new URL(e):x(e)}t(d,"toUrl");function a(e){const n=d(e);return n.href.endsWith("/")?n:new URL(`${n.href}/`)}t(a,"toDirUrl");function U(e){return{name:"spa-shell-embed",closeBundle(){const n=a(e.root??process.cwd()),r=i(new URL(e.path,n)),o=e.distIndex===void 0?i(new URL("dist/index.html",n)):i(typeof e.distIndex=="string"&&!/^[a-z][a-z\d+\-.]*:/i.test(e.distIndex)?new URL(e.distIndex,n):d(e.distIndex));if(!l(o)){console.warn("spa-shell-embed: dist/index.html not found, skipping");return}const s=c(o,"utf8"),u=`// Auto-generated by Vite build plugin - DO NOT EDIT.
2
- export const SPA_HTML: string = ${JSON.stringify(s)};
3
- `;p(m.dirname(r),{recursive:!0}),h(r,u)}}}t(U,"spaShellEmbedPlugin");function g(e={}){const n=[...e.plugins??[]];return e.spaShell!==void 0&&n.push(U(e.spaShell)),y({...n.length>0&&{plugins:n},...e.proxy!==void 0&&{server:{proxy:{...e.proxy}}},build:{outDir:e.outDir??"dist",emptyOutDir:!0}})}t(g,"defineWebViteConfig");export{g as defineWebViteConfig,U as spaShellEmbedPlugin};
1
+ var l=Object.defineProperty;var t=(n,e)=>l(n,"name",{value:e,configurable:!0});import{existsSync as f,mkdirSync as p,readFileSync as c,writeFileSync as h}from"node:fs";import m from"node:path";import{fileURLToPath as i,pathToFileURL as x}from"node:url";import{defineConfig as a}from"vitest/config";import{asVitePlugins as y}from"./plugin-option.js";function s(n){return n instanceof URL?n:n.startsWith("file:")?new URL(n):x(n)}t(s,"toUrl");function U(n){const e=s(n);return e.href.endsWith("/")?e:new URL(`${e.href}/`)}t(U,"toDirUrl");function L(n){return{name:"spa-shell-embed",closeBundle(){const e=U(n.root??process.cwd()),r=i(new URL(n.path,e)),o=n.distIndex===void 0?i(new URL("dist/index.html",e)):i(typeof n.distIndex=="string"&&!/^[a-z][a-z\d+\-.]*:/i.test(n.distIndex)?new URL(n.distIndex,e):s(n.distIndex));if(!f(o)){console.warn("spa-shell-embed: dist/index.html not found, skipping");return}const d=c(o,"utf8"),u=`// Auto-generated by Vite build plugin - DO NOT EDIT.
2
+ export const SPA_HTML: string = ${JSON.stringify(d)};
3
+ `;p(m.dirname(r),{recursive:!0}),h(r,u)}}}t(L,"spaShellEmbedPlugin");function I(n={}){const e=[...n.plugins??[]];return n.spaShell!==void 0&&e.push(L(n.spaShell)),a({...e.length>0&&{plugins:y(e)},...n.proxy!==void 0&&{server:{proxy:{...n.proxy}}},build:{outDir:n.outDir??"dist",emptyOutDir:!0}})}t(I,"defineWebViteConfig");export{I as defineWebViteConfig,L as spaShellEmbedPlugin};