@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.
- package/README.md +67 -34
- package/dist/eslint-options.d.ts +54 -0
- package/dist/eslint-options.d.ts.map +1 -0
- package/dist/eslint-options.js +0 -0
- package/dist/eslint-options.js.map +7 -0
- package/dist/eslint-rules.d.ts.map +1 -1
- package/dist/eslint-rules.js +1 -1
- package/dist/eslint-rules.js.map +2 -2
- package/dist/eslint-strict.d.ts +2 -1
- package/dist/eslint-strict.d.ts.map +1 -1
- package/dist/eslint-strict.js +2 -1
- package/dist/eslint-strict.js.map +3 -3
- package/dist/eslint.d.ts +2 -53
- package/dist/eslint.d.ts.map +1 -1
- package/dist/eslint.js.map +2 -2
- package/dist/manifest-validate.d.ts.map +1 -1
- package/dist/manifest-validate.js +1 -1
- package/dist/manifest-validate.js.map +3 -3
- package/dist/manifest.d.ts +21 -0
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js.map +2 -2
- package/dist/pages-proxy.d.ts +2 -0
- package/dist/pages-proxy.d.ts.map +1 -0
- package/dist/pages-proxy.js +1 -0
- package/dist/pages-proxy.js.map +7 -0
- package/dist/plugin-option.d.ts +15 -0
- package/dist/plugin-option.d.ts.map +1 -0
- package/dist/plugin-option.js +1 -0
- package/dist/plugin-option.js.map +7 -0
- package/dist/scripts/backup/destinations.d.ts +40 -0
- package/dist/scripts/backup/destinations.d.ts.map +1 -0
- package/dist/scripts/backup/destinations.js +1 -0
- package/dist/scripts/backup/destinations.js.map +7 -0
- package/dist/scripts/backup/encrypt-backup.d.ts +5 -2
- package/dist/scripts/backup/encrypt-backup.d.ts.map +1 -1
- package/dist/scripts/backup/encrypt-backup.js +2 -3
- package/dist/scripts/backup/encrypt-backup.js.map +3 -3
- package/dist/scripts/backup/naming.d.ts +1 -1
- package/dist/scripts/backup/naming.d.ts.map +1 -1
- package/dist/scripts/backup/naming.js +1 -1
- package/dist/scripts/backup/naming.js.map +3 -3
- package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
- package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
- package/dist/scripts/ensure-spa-shell-stub.js +1 -2
- package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
- package/dist/scripts/init-secrets.d.ts +1 -2
- package/dist/scripts/init-secrets.d.ts.map +1 -1
- package/dist/scripts/init-secrets.js +2 -3
- package/dist/scripts/init-secrets.js.map +3 -3
- package/dist/scripts/migrations-lock.d.ts +6 -2
- package/dist/scripts/migrations-lock.d.ts.map +1 -1
- package/dist/scripts/migrations-lock.js +1 -2
- package/dist/scripts/migrations-lock.js.map +3 -3
- package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
- package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
- package/dist/scripts/prepare-wrangler-config.js +1 -2
- package/dist/scripts/prepare-wrangler-config.js.map +3 -3
- package/dist/scripts/validate-locales.d.ts +20 -2
- package/dist/scripts/validate-locales.d.ts.map +1 -1
- package/dist/scripts/validate-locales.js +5 -5
- package/dist/scripts/validate-locales.js.map +3 -3
- package/dist/scripts/verify-spa-shell.d.ts +7 -2
- package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
- package/dist/scripts/verify-spa-shell.js +1 -2
- package/dist/scripts/verify-spa-shell.js.map +3 -3
- package/dist/scripts/wrangler-config/resources.d.ts +11 -2
- package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/resources.js +1 -1
- package/dist/scripts/wrangler-config/resources.js.map +3 -3
- package/dist/vite.d.ts +2 -1
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +3 -3
- package/dist/vitest-aliases.d.ts +7 -1
- package/dist/vitest-aliases.d.ts.map +1 -1
- package/dist/vitest-aliases.js +1 -1
- package/dist/vitest-aliases.js.map +3 -3
- package/dist/vitest-integration.d.ts +3 -2
- package/dist/vitest-integration.d.ts.map +1 -1
- package/dist/vitest-integration.js +1 -1
- package/dist/vitest-integration.js.map +3 -3
- package/dist/vitest-repo.d.ts +3 -2
- package/dist/vitest-repo.d.ts.map +1 -1
- package/dist/vitest-repo.js +1 -1
- package/dist/vitest-repo.js.map +3 -3
- package/dist/vitest-web.d.ts +3 -2
- package/dist/vitest-web.d.ts.map +1 -1
- package/dist/vitest-web.js +1 -1
- package/dist/vitest-web.js.map +3 -3
- package/dist/vitest.d.ts +4 -3
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +1 -1
- package/dist/vitest.js.map +3 -3
- package/package.json +3 -3
- package/presets/tsconfig/web.json +2 -2
- package/schema/manifest.schema.json +28 -1
- package/src/eslint-options.ts +54 -0
- package/src/eslint-rules.ts +4 -0
- package/src/eslint-strict.test.ts +29 -0
- package/src/eslint-strict.ts +36 -4
- package/src/eslint.ts +2 -53
- package/src/github/dependabot.yml +14 -4
- package/src/github/workflows/backup-d1.yml +15 -0
- package/src/github/workflows/backup-main.yml +9 -126
- package/src/github/workflows/continuous-deployment.yml +11 -180
- package/src/github/workflows/continuous-integration.yml +9 -249
- package/src/github/workflows/scheduled-version-update.yml +8 -31
- package/src/github/workflows/upstream-sync.yml +8 -49
- package/src/manifest-validate.ts +31 -2
- package/src/manifest.test.ts +22 -0
- package/src/manifest.ts +22 -0
- package/src/pages-proxy.test.ts +8 -0
- package/src/pages-proxy.ts +13 -0
- package/src/plugin-option.test.ts +13 -0
- package/src/plugin-option.ts +18 -0
- package/src/presets.test.ts +5 -1
- package/src/scripts/backup/backup-rules.test.ts +22 -0
- package/src/scripts/backup/destinations.ts +59 -0
- package/src/scripts/backup/encrypt-backup.ts +58 -48
- package/src/scripts/backup/naming.ts +2 -2
- package/src/scripts/ensure-spa-shell-stub.ts +18 -10
- package/src/scripts/entrypoints.test.ts +55 -0
- package/src/scripts/init-secrets.ts +8 -6
- package/src/scripts/migrations-lock.ts +22 -17
- package/src/scripts/prepare-wrangler-config.ts +34 -14
- package/src/scripts/validate-locales.ts +39 -17
- package/src/scripts/verify-spa-shell.ts +21 -20
- package/src/scripts/wrangler-config/resources.test.ts +10 -0
- package/src/scripts/wrangler-config/resources.ts +21 -4
- package/src/vite.ts +5 -3
- package/src/vitest-aliases.test.ts +33 -0
- package/src/vitest-aliases.ts +37 -7
- package/src/vitest-integration.ts +7 -8
- package/src/vitest-repo.ts +7 -5
- package/src/vitest-web.ts +7 -5
- package/src/vitest.ts +8 -6
- package/src/github/actions/retry-step/action.yml +0 -55
- 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/backup/naming.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Backup artifact naming and retention-window handling.\n *\n * Provenance: Edge-Sonic's `scripts/backup/naming.ts` and `retention.ts`,\n * converged into one module because the two answer the same question from either\n * side — what a file is called, and which of them are still worth keeping — and a\n * consumer only ever imports one.\n */\n\n/**\n * The filename prefix.\n *\n * Exported rather than inlined, because the workflow uploads with\n * `<prefix>_*.sql.xz.enc` and `if-no-files-found: error`. That glob and this prefix\n * are one fact written in two places — the failure mode being a rename here that\n * silently stops every upload while each upload job still reports success, since\n * the upload jobs skip on `needs` rather than failing.\n */\nexport const BACKUP_FILE_PREFIX = 'backup_prod_';\n\n/**\n * `2026-10-01_04-15-00` — sortable, filename-safe, and UTC.\n *\n * UTC rather than local: a retention window computed across a DST boundary is one\n * day wide in one direction, and a backup pruned a day early is a backup that was\n * never needed.\n */\nexport function backupStamp(date: Date): string {\n const iso = date.toISOString();\n return `${iso.slice(0, 10)}_${iso.slice(11, 19).replaceAll(':', '-')}`;\n}\n\n/**\nThe full artifact name: `<prefix><stamp>.sql.xz.enc`.\n*/\nexport function backupFileName(date: Date): string {\n return `${BACKUP_FILE_PREFIX}${backupStamp(date)}.sql.xz.enc`;\n}\n\n/**\n * `YYYY-MM-DD`, `days` before `now`.\n */\nexport function retentionCutoff(now: Date, days: number): string {\n return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);\n}\n\n/**\n * Read `BACKUP_RETENTION_DAYS` from the environment, rejecting bad values.\n *\n * Rejected rather than defaulted: silently falling back would either prune\n * everything or keep backups forever, and both are worse than a failed run that\n * names the problem.\n *\n * `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would\n * silently accept a mistyped value and prune against the wrong window.\n */\nexport function requireRetentionDays(): number {\n const raw =
|
|
5
|
-
"mappings": "+EAkBO,MAAMA,EAAqB,eAS5B,SAAUC,EAAYC,EAAU,CACpC,MAAMC,EAAMD,EAAK,YAAW,EAC5B,MAAO,GAAGC,EAAI,MAAM,EAAG,EAAE,CAAC,IAAIA,EAAI,MAAM,GAAI,EAAE,EAAE,WAAW,IAAK,GAAG,CAAC,EACtE,CAHgBC,EAAAH,EAAA,eAQV,SAAUI,EAAeH,EAAU,CACvC,MAAO,GAAGF,CAAkB,GAAGC,EAAYC,CAAI,CAAC,aAClD,CAFgBE,EAAAC,EAAA,kBAOV,SAAUC,EAAgBC,EAAWC,EAAY,CACrD,OAAO,IAAI,KAAKD,EAAI,QAAO,EAAKC,EAAO,GAAK,GAAK,GAAK,GAAI,EAAE,YAAW,EAAG,MAAM,EAAG,EAAE,CACvF,CAFgBJ,EAAAE,EAAA,mBAcV,SAAUG,
|
|
6
|
-
"names": ["BACKUP_FILE_PREFIX", "backupStamp", "date", "iso", "__name", "backupFileName", "retentionCutoff", "now", "days", "requireRetentionDays", "raw"]
|
|
4
|
+
"sourcesContent": ["/**\n * Backup artifact naming and retention-window handling.\n *\n * Provenance: Edge-Sonic's `scripts/backup/naming.ts` and `retention.ts`,\n * converged into one module because the two answer the same question from either\n * side — what a file is called, and which of them are still worth keeping — and a\n * consumer only ever imports one.\n */\n\n/**\n * The filename prefix.\n *\n * Exported rather than inlined, because the workflow uploads with\n * `<prefix>_*.sql.xz.enc` and `if-no-files-found: error`. That glob and this prefix\n * are one fact written in two places — the failure mode being a rename here that\n * silently stops every upload while each upload job still reports success, since\n * the upload jobs skip on `needs` rather than failing.\n */\nexport const BACKUP_FILE_PREFIX = 'backup_prod_';\n\n/**\n * `2026-10-01_04-15-00` — sortable, filename-safe, and UTC.\n *\n * UTC rather than local: a retention window computed across a DST boundary is one\n * day wide in one direction, and a backup pruned a day early is a backup that was\n * never needed.\n */\nexport function backupStamp(date: Date): string {\n const iso = date.toISOString();\n return `${iso.slice(0, 10)}_${iso.slice(11, 19).replaceAll(':', '-')}`;\n}\n\n/**\nThe full artifact name: `<prefix><stamp>.sql.xz.enc`.\n*/\nexport function backupFileName(date: Date): string {\n return `${BACKUP_FILE_PREFIX}${backupStamp(date)}.sql.xz.enc`;\n}\n\n/**\n * `YYYY-MM-DD`, `days` before `now`.\n */\nexport function retentionCutoff(now: Date, days: number): string {\n return new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);\n}\n\n/**\n * Read `BACKUP_RETENTION_DAYS` from the environment, rejecting bad values.\n *\n * Rejected rather than defaulted: silently falling back would either prune\n * everything or keep backups forever, and both are worse than a failed run that\n * names the problem.\n *\n * `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would\n * silently accept a mistyped value and prune against the wrong window.\n */\nexport function requireRetentionDays(env: NodeJS.ProcessEnv = process.env): number {\n const raw = env['BACKUP_RETENTION_DAYS'];\n const days = Number(raw);\n if (!Number.isFinite(days) || days <= 0) {\n throw new Error(`BACKUP_RETENTION_DAYS must be a positive number, got ${JSON.stringify(raw)}.`);\n }\n return days;\n}\n"],
|
|
5
|
+
"mappings": "+EAkBO,MAAMA,EAAqB,eAS5B,SAAUC,EAAYC,EAAU,CACpC,MAAMC,EAAMD,EAAK,YAAW,EAC5B,MAAO,GAAGC,EAAI,MAAM,EAAG,EAAE,CAAC,IAAIA,EAAI,MAAM,GAAI,EAAE,EAAE,WAAW,IAAK,GAAG,CAAC,EACtE,CAHgBC,EAAAH,EAAA,eAQV,SAAUI,EAAeH,EAAU,CACvC,MAAO,GAAGF,CAAkB,GAAGC,EAAYC,CAAI,CAAC,aAClD,CAFgBE,EAAAC,EAAA,kBAOV,SAAUC,EAAgBC,EAAWC,EAAY,CACrD,OAAO,IAAI,KAAKD,EAAI,QAAO,EAAKC,EAAO,GAAK,GAAK,GAAK,GAAI,EAAE,YAAW,EAAG,MAAM,EAAG,EAAE,CACvF,CAFgBJ,EAAAE,EAAA,mBAcV,SAAUG,EAAqBC,EAAyB,QAAQ,IAAG,CACvE,MAAMC,EAAMD,EAAI,sBACVF,EAAO,OAAOG,CAAG,EACvB,GAAI,CAAC,OAAO,SAASH,CAAI,GAAKA,GAAQ,EACpC,MAAM,IAAI,MAAM,wDAAwD,KAAK,UAAUG,CAAG,CAAC,GAAG,EAEhG,OAAOH,CACT,CAPgBJ,EAAAK,EAAA",
|
|
6
|
+
"names": ["BACKUP_FILE_PREFIX", "backupStamp", "date", "iso", "__name", "backupFileName", "retentionCutoff", "now", "days", "requireRetentionDays", "env", "raw"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-spa-shell-stub.d.ts","sourceRoot":"","sources":["../../src/scripts/ensure-spa-shell-stub.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"ensure-spa-shell-stub.d.ts","sourceRoot":"","sources":["../../src/scripts/ensure-spa-shell-stub.ts"],"names":[],"mappings":"AAwBA;;GAEG;AACH,wBAAgB,IAAI,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CAU5E"}
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import e from"node:path";import{fileURLToPath as t}from"node:url";import{ensureSpaShellStub as s}from"./spa-shell.js";const o=e.resolve(e.dirname(t(import.meta.url)),".."),a=process.argv[2]===void 0?o:e.resolve(process.argv[2]),r=s({root:a});console.log(r.created?`ensure-spa-shell-stub: created stub at ${r.path}`:`ensure-spa-shell-stub: ${r.path} already present, left untouched`);
|
|
1
|
+
var p=Object.defineProperty;var s=(e,t)=>p(e,"name",{value:t,configurable:!0});import o from"node:path";import{fileURLToPath as i}from"node:url";import{isEntrypoint as l}from"./lib/entrypoint.js";import{ensureSpaShellStub as a}from"./spa-shell.js";function u(e=process.argv.slice(2)){const t=o.resolve(o.dirname(i(import.meta.url)),".."),n=e[0]===void 0?t:o.resolve(e[0]),r=a({root:n});return console.log(r.created?`ensure-spa-shell-stub: created stub at ${r.path}`:`ensure-spa-shell-stub: ${r.path} already present, left untouched`),0}s(u,"main"),l(import.meta.url)&&process.exit(u());export{u as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/ensure-spa-shell-stub.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["path", "fileURLToPath", "ensureSpaShellStub", "
|
|
4
|
+
"sourcesContent": ["/**\n * Write a placeholder `apps/api/src/generated/spa-shell.ts` when it is absent.\n *\n * Provenance: Durable-DAV's `scripts/ensure-spa-shell-stub.mjs` and Edge-Sonic's\n * `scripts/build/ensure-spa-shell-stub.ts`. The rule lives in `spa-shell.ts`; this\n * is the entrypoint that runs it from `postinstall`.\n *\n * `pnpm install` runs this before `typegen` so the API worker typechecks in a\n * fresh clone, where the real file has not been produced by the Vite build yet.\n * It exits having done nothing when the file already exists, so a real build\n * output is never overwritten — overwriting would erase the last build with a\n * stub on the next install. The file is gitignored.\n *\n * Usage, from the repo root (typically wired as `postinstall`):\n *\n * ```bash\n * pnpm exec tsx scripts/ensure-spa-shell-stub.ts [repo-root]\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { ensureSpaShellStub } from './spa-shell.ts';\n\n/**\n * Run the stub writer. `args[0]` is the repo root (default: the repo this file sits in).\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 result = ensureSpaShellStub({ root });\n console.log(\n result.created\n ? `ensure-spa-shell-stub: created stub at ${result.path}`\n : `ensure-spa-shell-stub: ${result.path} already present, left untouched`,\n );\n return 0;\n}\n\nif (isEntrypoint(import.meta.url)) {\n process.exit(main());\n}\n"],
|
|
5
|
+
"mappings": "+EAmBA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,sBAAAC,MAA0B,iBAK7B,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,EACpEG,EAASL,EAAmB,CAAE,KAAAI,CAAI,CAAE,EAC1C,eAAQ,IACNC,EAAO,QACH,0CAA0CA,EAAO,IAAI,GACrD,0BAA0BA,EAAO,IAAI,kCAAkC,EAEtE,CACT,CAVgBC,EAAAL,EAAA,QAYZF,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKE,EAAI,CAAE",
|
|
6
|
+
"names": ["path", "fileURLToPath", "isEntrypoint", "ensureSpaShellStub", "main", "args", "repositoryRoot", "root", "result", "__name"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
#!/usr/bin/env tsx
|
|
2
1
|
/**
|
|
3
2
|
* Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh
|
|
4
3
|
* value for each one that does not exist yet.
|
|
@@ -43,5 +42,5 @@
|
|
|
43
42
|
* config is missing, because a step reporting "Secret initialization complete"
|
|
44
43
|
* having created nothing is worse than a named error.
|
|
45
44
|
*/
|
|
46
|
-
export
|
|
45
|
+
export declare function main(): Promise<void>;
|
|
47
46
|
//# sourceMappingURL=init-secrets.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AA6LH,wBAAsB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA8B1C"}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
${o}${i||t.message||""}`)}}s(l,"wrangler");function C(){if(!u(a))throw new Error(`${a} not found. Run scripts/prepare-wrangler-config.ts first \u2014 it is what creates the file this script reads.`);const e=m(p(a,"utf8"));if(e.secrets_store_secrets===void 0&&Object.keys(e).length===0)throw new Error(`${a} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);return e}s(C,"parseWranglerConfig");function x(e){const r=[];for(const[n,t]of(e.secrets_store_secrets??[]).entries()){const o=t.binding??`index ${n}`,i=t.store_id,c=t.secret_name;if(i===void 0||i===""||c===void 0||c==="")throw new Error(`secrets_store_secrets[${n}] ("${o}") needs both store_id and secret_name; store_id is normally filled in by scripts/prepare-wrangler-config.ts.`);if(!$(c))throw new Error(`No generator for secret "${c}" (binding "${o}").`);r.push({storeId:i,secretName:c})}return r}s(x,"planSecrets");function N(e){let r;try{r=l(["secrets-store","secret","list",e,"--remote"])}catch(n){if(w(n))return console.log(`Secrets Store ${e} is empty`),new Set;console.warn(`Unable to list secrets in store ${e}:`,n instanceof Error?n.message:"unknown error");return}return h(r)}s(N,"listSecretNames");function k(e,r,n){console.log(`Creating secret: ${r}`),l(["secrets-store","secret","create",e,"--name",r,"--scopes","workers","--remote"],n)}s(k,"createSecret");async function F(){console.log("Initializing Cloudflare secrets...");const e=C(),r=x(e);if(r.length===0)throw new Error("wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.");const n=new Map;for(const{storeId:t,secretName:o}of r){n.has(t)||n.set(t,N(t));const i=n.get(t);if(i===void 0)throw new Error(`Could not list secrets in store ${t}; refusing to create ${o} without confirming it is absent.`);if(i.has(o)){console.log(`Secret ${o} already exists; leaving it untouched.`);continue}k(t,o,await f(o)()),i.add(o)}console.log("Secret initialization complete")}s(F,"main");try{await F()}catch(e){y(e instanceof Error?`Secret initialization failed: ${e.message}`:String(e))}
|
|
1
|
+
var d=Object.defineProperty;var s=(e,r)=>d(e,"name",{value:r,configurable:!0});import{execFileSync as g}from"node:child_process";import{existsSync as p,readFileSync as u}from"node:fs";import{parse as m}from"jsonc-parser";import{isEntrypoint as y}from"./lib/entrypoint.js";import{fail as w}from"./lib/github-actions.js";import{isEmptySecretsStoreListing as h,parseWranglerNames as S}from"./lib/wrangler-table.js";import{CONFIG_PATH as a}from"./wrangler-config/types.js";const E="-encryption-key",_="-signing-secret";async function $(){const e=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("raw",e);let n="";for(const t of new Uint8Array(r))n+=String.fromCodePoint(t);return btoa(n)}s($,"generateAESGCMKey");function b(){let e="";for(const r of crypto.getRandomValues(new Uint8Array(32)))e+=r.toString(16).padStart(2,"0");return Promise.resolve(e)}s(b,"generateSigningSecret");function f(e){if(e.endsWith(E))return $;if(e.endsWith(_))return b;throw new Error(`Unknown secret: ${e}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`)}s(f,"generatorFor");function C(e){try{return f(e),!0}catch{return!1}}s(C,"canProvisionSecret");function l(e,r){try{return g("pnpm",["exec","wrangler",...e],{encoding:"utf8",stdio:[r===void 0?"ignore":"pipe","pipe","pipe"],...r!==void 0&&{input:r}})}catch(n){const t=n,o=t.stdout?t.stdout.toString():"",i=t.stderr?t.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${e.join(" ")}
|
|
2
|
+
${o}${i||t.message||""}`)}}s(l,"wrangler");function x(){if(!p(a))throw new Error(`${a} not found. Run scripts/prepare-wrangler-config.ts first \u2014 it is what creates the file this script reads.`);const e=m(u(a,"utf8"));if(e.secrets_store_secrets===void 0&&Object.keys(e).length===0)throw new Error(`${a} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);return e}s(x,"parseWranglerConfig");function N(e){const r=[];for(const[n,t]of(e.secrets_store_secrets??[]).entries()){const o=t.binding??`index ${n}`,i=t.store_id,c=t.secret_name;if(i===void 0||i===""||c===void 0||c==="")throw new Error(`secrets_store_secrets[${n}] ("${o}") needs both store_id and secret_name; store_id is normally filled in by scripts/prepare-wrangler-config.ts.`);if(!C(c))throw new Error(`No generator for secret "${c}" (binding "${o}").`);r.push({storeId:i,secretName:c})}return r}s(N,"planSecrets");function k(e){let r;try{r=l(["secrets-store","secret","list",e,"--remote"])}catch(n){if(h(n))return console.log(`Secrets Store ${e} is empty`),new Set;console.warn(`Unable to list secrets in store ${e}:`,n instanceof Error?n.message:"unknown error");return}return S(r)}s(k,"listSecretNames");function F(e,r,n){console.log(`Creating secret: ${r}`),l(["secrets-store","secret","create",e,"--name",r,"--scopes","workers","--remote"],n)}s(F,"createSecret");async function I(){console.log("Initializing Cloudflare secrets...");const e=x(),r=N(e);if(r.length===0)throw new Error("wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.");const n=new Map;for(const{storeId:t,secretName:o}of r){n.has(t)||n.set(t,k(t));const i=n.get(t);if(i===void 0)throw new Error(`Could not list secrets in store ${t}; refusing to create ${o} without confirming it is absent.`);if(i.has(o)){console.log(`Secret ${o} already exists; leaving it untouched.`);continue}F(t,o,await f(o)()),i.add(o)}console.log("Secret initialization complete")}if(s(I,"main"),y(import.meta.url))try{await I()}catch(e){w(e instanceof Error?`Secret initialization failed: ${e.message}`:String(e))}export{I as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/init-secrets.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env tsx\n/**\n * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh\n * value for each one that does not exist yet.\n *\n * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's\n * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid\n * a broken deploy for a whole release, and both fixes are carried over.\n *\n * ### Why this script exists at all\n *\n * A `secrets_store_secrets` binding fails the deploy unless the named secret\n * already exists inside the named store. Nothing creates it: Cloudflare will not\n * generate a value, and the template cannot carry one. So this script is the only\n * thing standing between a fresh account and a deploy that cannot succeed.\n *\n * ### The two defects that hid a broken deploy\n *\n * **The generator list was stale.** Durable-DAV's copy carried an allowlist of\n * exact names from the repository it was inherited from, all deleted when the repo\n * was renamed, so the very first iteration threw `Unknown secret` and never created\n * anything. So the rule here is the secret's **name shape**, not a list of names:\n * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32\n * random bytes. Adding a secret to the template is then a one-line change needing\n * no matching edit here, which is the property the exact-name list did not have.\n *\n * **The throw was swallowed.** The original ended in `main().catch(console.error)`.\n * `console.error` returns `undefined` and never sets an exit status, so the process\n * exited **0** and CI marked the step green — the failure only surfaced one step\n * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is\n * validated **before** any Cloudflare call, and a rejection reaches the runner as\n * a non-zero exit with a workflow annotation.\n *\n * ### Create-if-absent is a correctness property, not laziness\n *\n * An existing secret is left untouched. A replication encryption key seals every\n * remote target's credential; regenerating it on a redeploy would strand them all\n * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,\n * not a side effect of deploying.\n *\n * Requires a materialized `wrangler.jsonc` — run\n * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the\n * config is missing, because a step reporting \"Secret initialization complete\"\n * having created nothing is worse than a named error.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { fail } from './lib/github-actions.ts';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';\nimport { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';\n\n/**\n * The secret names the AES-GCM key generator produces, matched by **shape**.\n *\n * Keyed on the suffix because the alternative is the exact-name map that went\n * stale. See the header: a template naming `*-encryption-key` is then a one-line\n * change with no matching edit here, and a new secret breaks the deploy loudly\n * instead of silently.\n */\nconst ENCRYPTION_KEY_SUFFIX = '-encryption-key';\n\n/**\nThe secret names the random signing secret generator produces.\n*/\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/**\nA 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts.\n*/\nasync function generateAESGCMKey(): Promise<string> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);\n const exported = await crypto.subtle.exportKey('raw', key);\n // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,\n // which is fine today and is a stack overflow the day the key is longer.\n let binary = '';\n for (const byte of new Uint8Array(exported)) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n}\n\n/**\nA 256-bit random signing secret for internal self-calls, hex-encoded.\n*/\nfunction generateSigningSecret(): Promise<string> {\n let hex = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(32))) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return Promise.resolve(hex);\n}\n\n/**\n * The generator for a secret name, chosen by the name's shape.\n *\n * A name matching neither is still refused rather than given a guess: the generator\n * is not the only thing that has to be right, and an unusable value that looks\n * provisioned is worse than a failure.\n */\nfunction generatorFor(secretName: string): () => Promise<string> {\n if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX)) return generateAESGCMKey;\n if (secretName.endsWith(SIGNING_SECRET_SUFFIX)) return generateSigningSecret;\n throw new Error(\n `Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +\n `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`,\n );\n}\n\n/**\nWhether this script can produce a value for `secretName`.\n*/\nfunction canProvisionSecret(secretName: string): boolean {\n try {\n generatorFor(secretName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs a wrangler subcommand, optionally feeding `input` on stdin.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nfunction wrangler(args: readonly string[], input?: string): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\nfunction parseWranglerConfig(): WranglerConfig {\n if (!existsSync(CONFIG_PATH)) {\n throw new Error(\n `${CONFIG_PATH} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`,\n );\n }\n // `parse` is error-tolerant and returns a partial object, so an empty result means\n // malformed JSON rather than \"no secrets declared\". Treating that as an empty list\n // would report success having created nothing.\n const config = parse(readFileSync(CONFIG_PATH, 'utf8')) as WranglerConfig;\n if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {\n throw new Error(`${CONFIG_PATH} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);\n }\n return config;\n}\n\n/**\nOne secret to create, as the plan names it.\n*/\ninterface PlannedSecret {\n storeId: string;\n secretName: string;\n}\n\n/**\n * Turn the config's bindings into a validated work list.\n *\n * Every entry is checked *before* the first Cloudflare call, so an\n * unprovisionable secret fails the step in milliseconds instead of after some other\n * secret has already been created.\n */\nfunction planSecrets(config: WranglerConfig): PlannedSecret[] {\n const plan: PlannedSecret[] = [];\n for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {\n const label = secret.binding ?? `index ${index}`;\n const storeId = secret.store_id;\n const secretName = secret.secret_name;\n if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {\n throw new Error(\n `secrets_store_secrets[${index}] (\"${label}\") needs both store_id and secret_name; ` +\n 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.',\n );\n }\n if (!canProvisionSecret(secretName)) {\n throw new Error(`No generator for secret \"${secretName}\" (binding \"${label}\").`);\n }\n plan.push({ storeId, secretName });\n }\n return plan;\n}\n\n/**\n * List the secret names present in a store.\n *\n * Returns `undefined` when the listing itself failed, which is deliberately\n * distinct from an empty set: a transient CLI failure must not be read as \"the\n * secret is missing\" and cause a duplicate insert over a live value. An empty store\n * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.\n *\n * The name is taken exactly. `output.includes(secretName)` is not a membership test:\n * `my-replication-encryption-key-2` satisfies a search for\n * `my-replication-encryption-key`, so a store holding only the suffixed entry would\n * report the unsuffixed one as already present and it would never be created.\n */\nfunction listSecretNames(storeId: string): Set<string> | undefined {\n let output: string;\n try {\n output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);\n } catch (error: unknown) {\n if (isEmptySecretsStoreListing(error)) {\n console.log(`Secrets Store ${storeId} is empty`);\n return new Set();\n }\n console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');\n return undefined;\n }\n return parseWranglerNames(output);\n}\n\nfunction createSecret(storeId: string, secretName: string, secretValue: string): void {\n console.log(`Creating secret: ${secretName}`);\n // The value goes in on stdin, never as an argv entry: an argv is visible to every\n // process on the runner through `ps`, and the previous\n // `echo \"${value}\" | wrangler … ${name}` also broke on `\"`, `$`, backticks and\n // newlines.\n wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);\n}\n\nasync function main(): Promise<void> {\n console.log('Initializing Cloudflare secrets...');\n const config = parseWranglerConfig();\n const plan = planSecrets(config);\n\n if (plan.length === 0) {\n throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');\n }\n\n const listedByStore = new Map<string, Set<string> | undefined>();\n\n for (const { storeId, secretName } of plan) {\n if (!listedByStore.has(storeId)) {\n listedByStore.set(storeId, listSecretNames(storeId));\n }\n const existing = listedByStore.get(storeId);\n if (existing === undefined) {\n // Refuse to guess: creating a secret we could not read back risks overwriting\n // a live value with a freshly generated one.\n throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);\n }\n if (existing.has(secretName)) {\n console.log(`Secret ${secretName} already exists; leaving it untouched.`);\n continue;\n }\n createSecret(storeId, secretName, await generatorFor(secretName)());\n existing.add(secretName);\n }\n\n console.log('Secret initialization complete');\n}\n\n// Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces\n// as a stack trace with its cause intact and the process exits non-zero. Either way\n// the exit status has to be right: this runs in the deploy pipeline, and swallowing\n// the rejection reported a failed key bootstrap as a green step.\ntry {\n await main();\n} catch (error: unknown) {\n fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["execFileSync", "existsSync", "readFileSync", "parse", "fail", "isEmptySecretsStoreListing", "parseWranglerNames", "CONFIG_PATH", "ENCRYPTION_KEY_SUFFIX", "SIGNING_SECRET_SUFFIX", "generateAESGCMKey", "key", "exported", "binary", "byte", "__name", "generateSigningSecret", "hex", "generatorFor", "secretName", "canProvisionSecret", "wrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseWranglerConfig", "config", "planSecrets", "plan", "index", "secret", "label", "storeId", "listSecretNames", "output", "createSecret", "secretValue", "main", "listedByStore", "existing"]
|
|
4
|
+
"sourcesContent": ["/**\n * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh\n * value for each one that does not exist yet.\n *\n * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's\n * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid\n * a broken deploy for a whole release, and both fixes are carried over.\n *\n * ### Why this script exists at all\n *\n * A `secrets_store_secrets` binding fails the deploy unless the named secret\n * already exists inside the named store. Nothing creates it: Cloudflare will not\n * generate a value, and the template cannot carry one. So this script is the only\n * thing standing between a fresh account and a deploy that cannot succeed.\n *\n * ### The two defects that hid a broken deploy\n *\n * **The generator list was stale.** Durable-DAV's copy carried an allowlist of\n * exact names from the repository it was inherited from, all deleted when the repo\n * was renamed, so the very first iteration threw `Unknown secret` and never created\n * anything. So the rule here is the secret's **name shape**, not a list of names:\n * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32\n * random bytes. Adding a secret to the template is then a one-line change needing\n * no matching edit here, which is the property the exact-name list did not have.\n *\n * **The throw was swallowed.** The original ended in `main().catch(console.error)`.\n * `console.error` returns `undefined` and never sets an exit status, so the process\n * exited **0** and CI marked the step green — the failure only surfaced one step\n * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is\n * validated **before** any Cloudflare call, and a rejection reaches the runner as\n * a non-zero exit with a workflow annotation.\n *\n * ### Create-if-absent is a correctness property, not laziness\n *\n * An existing secret is left untouched. A replication encryption key seals every\n * remote target's credential; regenerating it on a redeploy would strand them all\n * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,\n * not a side effect of deploying.\n *\n * Requires a materialized `wrangler.jsonc` — run\n * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the\n * config is missing, because a step reporting \"Secret initialization complete\"\n * having created nothing is worse than a named error.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { fail } from './lib/github-actions.ts';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';\nimport { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';\n\n/**\n * The secret names the AES-GCM key generator produces, matched by **shape**.\n *\n * Keyed on the suffix because the alternative is the exact-name map that went\n * stale. See the header: a template naming `*-encryption-key` is then a one-line\n * change with no matching edit here, and a new secret breaks the deploy loudly\n * instead of silently.\n */\nconst ENCRYPTION_KEY_SUFFIX = '-encryption-key';\n\n/**\nThe secret names the random signing secret generator produces.\n*/\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/**\nA 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts.\n*/\nasync function generateAESGCMKey(): Promise<string> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);\n const exported = await crypto.subtle.exportKey('raw', key);\n // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,\n // which is fine today and is a stack overflow the day the key is longer.\n let binary = '';\n for (const byte of new Uint8Array(exported)) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n}\n\n/**\nA 256-bit random signing secret for internal self-calls, hex-encoded.\n*/\nfunction generateSigningSecret(): Promise<string> {\n let hex = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(32))) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return Promise.resolve(hex);\n}\n\n/**\n * The generator for a secret name, chosen by the name's shape.\n *\n * A name matching neither is still refused rather than given a guess: the generator\n * is not the only thing that has to be right, and an unusable value that looks\n * provisioned is worse than a failure.\n */\nfunction generatorFor(secretName: string): () => Promise<string> {\n if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX)) return generateAESGCMKey;\n if (secretName.endsWith(SIGNING_SECRET_SUFFIX)) return generateSigningSecret;\n throw new Error(\n `Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +\n `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`,\n );\n}\n\n/**\nWhether this script can produce a value for `secretName`.\n*/\nfunction canProvisionSecret(secretName: string): boolean {\n try {\n generatorFor(secretName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs a wrangler subcommand, optionally feeding `input` on stdin.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nfunction wrangler(args: readonly string[], input?: string): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\nfunction parseWranglerConfig(): WranglerConfig {\n if (!existsSync(CONFIG_PATH)) {\n throw new Error(\n `${CONFIG_PATH} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`,\n );\n }\n // `parse` is error-tolerant and returns a partial object, so an empty result means\n // malformed JSON rather than \"no secrets declared\". Treating that as an empty list\n // would report success having created nothing.\n const config = parse(readFileSync(CONFIG_PATH, 'utf8')) as WranglerConfig;\n if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {\n throw new Error(`${CONFIG_PATH} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);\n }\n return config;\n}\n\n/**\nOne secret to create, as the plan names it.\n*/\ninterface PlannedSecret {\n storeId: string;\n secretName: string;\n}\n\n/**\n * Turn the config's bindings into a validated work list.\n *\n * Every entry is checked *before* the first Cloudflare call, so an\n * unprovisionable secret fails the step in milliseconds instead of after some other\n * secret has already been created.\n */\nfunction planSecrets(config: WranglerConfig): PlannedSecret[] {\n const plan: PlannedSecret[] = [];\n for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {\n const label = secret.binding ?? `index ${index}`;\n const storeId = secret.store_id;\n const secretName = secret.secret_name;\n if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {\n throw new Error(\n `secrets_store_secrets[${index}] (\"${label}\") needs both store_id and secret_name; ` +\n 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.',\n );\n }\n if (!canProvisionSecret(secretName)) {\n throw new Error(`No generator for secret \"${secretName}\" (binding \"${label}\").`);\n }\n plan.push({ storeId, secretName });\n }\n return plan;\n}\n\n/**\n * List the secret names present in a store.\n *\n * Returns `undefined` when the listing itself failed, which is deliberately\n * distinct from an empty set: a transient CLI failure must not be read as \"the\n * secret is missing\" and cause a duplicate insert over a live value. An empty store\n * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.\n *\n * The name is taken exactly. `output.includes(secretName)` is not a membership test:\n * `my-replication-encryption-key-2` satisfies a search for\n * `my-replication-encryption-key`, so a store holding only the suffixed entry would\n * report the unsuffixed one as already present and it would never be created.\n */\nfunction listSecretNames(storeId: string): Set<string> | undefined {\n let output: string;\n try {\n output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);\n } catch (error: unknown) {\n if (isEmptySecretsStoreListing(error)) {\n console.log(`Secrets Store ${storeId} is empty`);\n return new Set();\n }\n console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');\n return undefined;\n }\n return parseWranglerNames(output);\n}\n\nfunction createSecret(storeId: string, secretName: string, secretValue: string): void {\n console.log(`Creating secret: ${secretName}`);\n // The value goes in on stdin, never as an argv entry: an argv is visible to every\n // process on the runner through `ps`, and the previous\n // `echo \"${value}\" | wrangler … ${name}` also broke on `\"`, `$`, backticks and\n // newlines.\n wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);\n}\n\nexport async function main(): Promise<void> {\n console.log('Initializing Cloudflare secrets...');\n const config = parseWranglerConfig();\n const plan = planSecrets(config);\n\n if (plan.length === 0) {\n throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');\n }\n\n const listedByStore = new Map<string, Set<string> | undefined>();\n\n for (const { storeId, secretName } of plan) {\n if (!listedByStore.has(storeId)) {\n listedByStore.set(storeId, listSecretNames(storeId));\n }\n const existing = listedByStore.get(storeId);\n if (existing === undefined) {\n // Refuse to guess: creating a secret we could not read back risks overwriting\n // a live value with a freshly generated one.\n throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);\n }\n if (existing.has(secretName)) {\n console.log(`Secret ${secretName} already exists; leaving it untouched.`);\n continue;\n }\n createSecret(storeId, secretName, await generatorFor(secretName)());\n existing.add(secretName);\n }\n\n console.log('Secret initialization complete');\n}\n\n// Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces\n// as a stack trace with its cause intact and the process exits non-zero. Either way\n// the exit status has to be right: this runs in the deploy pipeline, and swallowing\n// the rejection reported a failed key bootstrap as a green step.\nif (isEntrypoint(import.meta.url)) {\n try {\n await main();\n } catch (error: unknown) {\n fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));\n }\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["execFileSync", "existsSync", "readFileSync", "parse", "isEntrypoint", "fail", "isEmptySecretsStoreListing", "parseWranglerNames", "CONFIG_PATH", "ENCRYPTION_KEY_SUFFIX", "SIGNING_SECRET_SUFFIX", "generateAESGCMKey", "key", "exported", "binary", "byte", "__name", "generateSigningSecret", "hex", "generatorFor", "secretName", "canProvisionSecret", "wrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseWranglerConfig", "config", "planSecrets", "plan", "index", "secret", "label", "storeId", "listSecretNames", "output", "createSecret", "secretValue", "main", "listedByStore", "existing"]
|
|
7
7
|
}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Write the lock. `args[0]` is the migrations directory (default `./migrations`
|
|
3
|
+
* beside the repo this file sits in). Returns the exit code; it is non-zero when a
|
|
4
|
+
* problem the write cannot resolve (an `edited` entry) remains.
|
|
5
|
+
*/
|
|
6
|
+
export declare function main(args?: readonly string[]): number;
|
|
3
7
|
//# sourceMappingURL=migrations-lock.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrations-lock.d.ts","sourceRoot":"","sources":["../../src/scripts/migrations-lock.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"migrations-lock.d.ts","sourceRoot":"","sources":["../../src/scripts/migrations-lock.ts"],"names":[],"mappings":"AAiCA;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CAa5E"}
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import o from"node:path";import{fileURLToPath as i}from"node:url";import{LOCK_NAME as s,verifyMigrations as n}from"./verify-migrations.js";const l=o.resolve(o.dirname(i(import.meta.url)),".."),e=process.argv[2]===void 0?o.join(l,"migrations"):o.resolve(process.argv[2]),r=n(e,{write:!0});for(const t of r.problems)console.error(`FAIL: ${t.problem}`);console.log(`${r.lock===null?"left":"wrote"} ${o.join(e,s)} (${r.files.length} migration(s) recorded)`),process.exit(r.problems.length===0?0:1);
|
|
1
|
+
var s=Object.defineProperty;var n=(r,t)=>s(r,"name",{value:t,configurable:!0});import o from"node:path";import{fileURLToPath as l}from"node:url";import{isEntrypoint as p}from"./lib/entrypoint.js";import{LOCK_NAME as f,verifyMigrations as c}from"./verify-migrations.js";function a(r=process.argv.slice(2)){const t=o.resolve(o.dirname(l(import.meta.url)),".."),i=r[0]===void 0?o.join(t,"migrations"):o.resolve(r[0]),e=c(i,{write:!0});for(const m of e.problems)console.error(`FAIL: ${m.problem}`);return console.log(`${e.lock===null?"left":"wrote"} ${o.join(i,f)} (${e.files.length} migration(s) recorded)`),e.problems.length===0?0:1}n(a,"main"),p(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/migrations-lock.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["path", "fileURLToPath", "LOCK_NAME", "verifyMigrations", "
|
|
4
|
+
"sourcesContent": ["/**\n * Record newly-added migration files in `migrations/migrations.lock.json`.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/verify-migrations.ts --write`,\n * which is the only repo that splits the two operations into two commands. The\n * other repos have one script with a flag; the split is kept here because the two\n * calls have different audiences and different blast radii — `verify-migrations`\n * runs in CI and changes nothing, while this one is an operator action that writes\n * a file into version control.\n *\n * The rules live once, in `verify-migrations.ts`, so the two entrypoints cannot\n * disagree. `--write` is add-only: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. It never touches\n * another existing entry, so an incremental migration that has drifted still\n * fails afterwards — re-baselining one means deleting its entry by hand, which\n * shows up in the diff.\n *\n * There is deliberately no `--force`, because a write that could bless a drift\n * without reading the drift is the operator blessing their own edit, and they are\n * by definition the one making it.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/migrations-lock.ts # ./migrations\n * pnpm exec tsx scripts/migrations-lock.ts path/to/migrations\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { LOCK_NAME, verifyMigrations } from './verify-migrations.ts';\n\n/**\n * Write the lock. `args[0]` is the migrations directory (default `./migrations`\n * beside the repo this file sits in). Returns the exit code; it is non-zero when a\n * problem the write cannot resolve (an `edited` entry) remains.\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 migrationsDir = args[0] === undefined ? path.join(repositoryRoot, 'migrations') : path.resolve(args[0]);\n const report = verifyMigrations(migrationsDir, { write: true });\n for (const problem of report.problems) {\n console.error(`FAIL: ${problem.problem}`);\n }\n console.log(\n `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} (${report.files.length} migration(s) recorded)`,\n );\n // The lock is re-checked by the caller: `verify-migrations.ts` re-reads from disk,\n // so running it after this command reports the same verdict CI will.\n return report.problems.length === 0 ? 0 : 1;\n}\n\nif (isEntrypoint(import.meta.url)) {\n process.exit(main());\n}\n"],
|
|
5
|
+
"mappings": "+EA4BA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,aAAAC,EAAW,oBAAAC,MAAwB,yBAOtC,SAAUC,EAAKC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAClE,MAAMC,EAAiBP,EAAK,QAAQA,EAAK,QAAQC,EAAc,YAAY,GAAG,CAAC,EAAG,IAAI,EAChFO,EAAgBF,EAAK,CAAC,IAAM,OAAYN,EAAK,KAAKO,EAAgB,YAAY,EAAIP,EAAK,QAAQM,EAAK,CAAC,CAAC,EACtGG,EAASL,EAAiBI,EAAe,CAAE,MAAO,EAAI,CAAE,EAC9D,UAAWE,KAAWD,EAAO,SAC3B,QAAQ,MAAM,SAASC,EAAQ,OAAO,EAAE,EAE1C,eAAQ,IACN,GAAGD,EAAO,OAAS,KAAO,OAAS,OAAO,IAAIT,EAAK,KAAKQ,EAAeL,CAAS,CAAC,KAAKM,EAAO,MAAM,MAAM,yBAAyB,EAI7HA,EAAO,SAAS,SAAW,EAAI,EAAI,CAC5C,CAbgBE,EAAAN,EAAA,QAeZH,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKG,EAAI,CAAE",
|
|
6
|
+
"names": ["path", "fileURLToPath", "isEntrypoint", "LOCK_NAME", "verifyMigrations", "main", "args", "repositoryRoot", "migrationsDir", "report", "problem", "__name"]
|
|
7
7
|
}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths
|
|
3
|
+
* resolve when `wrangler-config/types.ts` is first imported, so a caller changing
|
|
4
|
+
* directory must do so before importing this module). Returns the created resources.
|
|
5
|
+
*/
|
|
6
|
+
export declare function main(): string[];
|
|
3
7
|
//# sourceMappingURL=prepare-wrangler-config.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare-wrangler-config.d.ts","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"prepare-wrangler-config.d.ts","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":"AAwCA;;;;GAIG;AACH,wBAAgB,IAAI,IAAI,MAAM,EAAE,CAqB/B"}
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import{setOutput as r}from"./lib/github-actions.js";import{applyTopLevelPatch as e,applyVarsPatch as o,ensureMinimumConfigVersion as i,prepareConfigFile as n}from"./wrangler-config/patches.js";import{provisionWranglerResources as t}from"./wrangler-config/resources.js";n(),i(),e(),o();const a=t();r("created",a.join(",")),console.log("Wrangler configuration is ready.");
|
|
1
|
+
var i=Object.defineProperty;var o=(r,e)=>i(r,"name",{value:e,configurable:!0});import{loadManifest as n}from"../manifest.js";import{setOutput as t}from"./lib/github-actions.js";import{applyTopLevelPatch as a,applyVarsPatch as s,ensureMinimumConfigVersion as p,prepareConfigFile as m}from"./wrangler-config/patches.js";import{provisionWranglerResources as c}from"./wrangler-config/resources.js";import{isEntrypoint as f}from"./lib/entrypoint.js";function u(){m(),p(),a(),s();const r=n(process.cwd())?.features?.kv,e=c({namespaceNames:{...r?.namespaceNames},requiredKvBindings:r?.bindings??[]});return t("created",e.join(",")),console.log("Wrangler configuration is ready."),e}o(u,"main"),f(import.meta.url)&&u();export{u as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/prepare-wrangler-config.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "created"]
|
|
4
|
+
"sourcesContent": ["/**\n * Materialize `wrangler.jsonc` and provision what it refers to.\n *\n * Provenance: Durable-DAV's `scripts/prepare-wrangler-config.ts` and Edge-Sonic's\n * `scripts/deploy/prepare-wrangler-config.ts`, converged. The five ordered calls\n * live in `wrangler-config/`: read or copy the config, refuse one older than the\n * template requires, apply the caller's patches, then create whatever resources it\n * names and write their real ids over the placeholders. This file is only the\n * order; it has nothing else to do.\n *\n * Run by the deploy job before `wrangler deploy`, and by the backup workflow\n * before `wrangler d1 export` — so the database a backup covers is resolved from\n * the same config the deploy targets, with no second `D1_DATABASE_ID` secret to\n * keep in sync.\n *\n * The one thing it does beyond calling is publish what\n * `provisionWranglerResources` created, which the backup workflow reads to refuse\n * exporting a database that did not exist until this run.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/prepare-wrangler-config.ts\n * ```\n *\n * Environment:\n *\n * - `WRANGLER_JSONC` — the whole config, as a repository variable. When set it is\n * written verbatim instead of copying the template.\n * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.\n * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.\n *\n * KV bindings come from the manifest's `features.kv` (none declared: none added).\n */\nimport { loadManifest } from '../manifest.ts';\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { provisionWranglerResources } from './wrangler-config/resources.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\n\n/**\n * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths\n * resolve when `wrangler-config/types.ts` is first imported, so a caller changing\n * directory must do so before importing this module). Returns the created resources.\n */\nexport function main(): string[] {\n prepareConfigFile();\n ensureMinimumConfigVersion();\n applyTopLevelPatch();\n applyVarsPatch();\n // KV is manifest-driven: a repo that declares no `features.kv` gets no KV binding and no namespace (no phantom CACHE).\n const kv = loadManifest(process.cwd())?.features?.kv;\n const created = provisionWranglerResources({\n namespaceNames: { ...kv?.namespaceNames },\n requiredKvBindings: kv?.bindings ?? [],\n });\n\n // Published as a step output rather than only printed. The backup workflow needs\n // to know whether the D1 database *existed* or was created moments ago: a fresh one\n // holds no user data, and uploading that empty dump every night is a false sense\n // of safety. The alternative — re-reading the placeholder id out of\n // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches\n // the placeholder away before the reader ever runs.\n setOutput('created', created.join(','));\n console.log('Wrangler configuration is ready.');\n return created;\n}\n\nif (isEntrypoint(import.meta.url)) {\n main();\n}\n"],
|
|
5
|
+
"mappings": "+EAkCA,OAAS,gBAAAA,MAAoB,iBAC7B,OAAS,aAAAC,MAAiB,0BAC1B,OAAS,sBAAAC,EAAoB,kBAAAC,EAAgB,8BAAAC,EAA4B,qBAAAC,MAAyB,+BAClG,OAAS,8BAAAC,MAAkC,iCAC3C,OAAS,gBAAAC,MAAoB,sBAOvB,SAAUC,GAAI,CAClBH,EAAiB,EACjBD,EAA0B,EAC1BF,EAAkB,EAClBC,EAAc,EAEd,MAAMM,EAAKT,EAAa,QAAQ,IAAG,CAAE,GAAG,UAAU,GAC5CU,EAAUJ,EAA2B,CACzC,eAAgB,CAAE,GAAGG,GAAI,cAAc,EACvC,mBAAoBA,GAAI,UAAY,CAAA,EACrC,EAQD,OAAAR,EAAU,UAAWS,EAAQ,KAAK,GAAG,CAAC,EACtC,QAAQ,IAAI,kCAAkC,EACvCA,CACT,CArBgBC,EAAAH,EAAA,QAuBZD,EAAa,YAAY,GAAG,GAC9BC,EAAI",
|
|
6
|
+
"names": ["loadManifest", "setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "isEntrypoint", "main", "kv", "created", "__name"]
|
|
7
7
|
}
|
|
@@ -61,6 +61,24 @@ and a directory of bundles with no declaration is exactly the state a
|
|
|
61
61
|
bundle-to-bundle check reports as perfectly healthy.
|
|
62
62
|
*/
|
|
63
63
|
declare function validateLocalesCli(argv?: readonly string[]): number;
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
/**
|
|
65
|
+
What `collectLocaleProblems` checks: the bundles, and optionally the declared tags and the `t()` call sites.
|
|
66
|
+
*/
|
|
67
|
+
interface LocaleCheckOptions {
|
|
68
|
+
dir: string;
|
|
69
|
+
base?: string;
|
|
70
|
+
shape?: LocaleShape;
|
|
71
|
+
callSiteDir?: string;
|
|
72
|
+
tagsFile?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Every finding for one locales directory, as data. The CLI prints it and `rexezuge locales validate --json` serializes it;
|
|
76
|
+
* advisories carry `advisory: true`, everything else is a failure.
|
|
77
|
+
*/
|
|
78
|
+
declare function collectLocaleProblems(options: LocaleCheckOptions): {
|
|
79
|
+
report: LocaleReport;
|
|
80
|
+
problems: LocaleProblem[];
|
|
81
|
+
};
|
|
82
|
+
export { collectLocaleProblems, parseObjectLiteral, validateLocales, validateLocalesCli };
|
|
83
|
+
export type { LocaleCheckOptions, LocaleProblem, LocaleReport, LocaleShape };
|
|
66
84
|
//# sourceMappingURL=validate-locales.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-locales.d.ts","sourceRoot":"","sources":["../../src/scripts/validate-locales.ts"],"names":[],"mappings":"AAyCA;;EAEE;AACF,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEtD;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;EAEE;AACF,UAAU,YAAY;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B;AAsID,iBAAS,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CA4EjE;AAqFD;;;;;GAKG;AACH,iBAAS,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,SAAO,EAAE,KAAK,GAAE,WAAoB,GAAG,YAAY,CA2EzG;AAmPD;;;;;;;;;;;;;;EAcE;AACF,iBAAS,kBAAkB,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"validate-locales.d.ts","sourceRoot":"","sources":["../../src/scripts/validate-locales.ts"],"names":[],"mappings":"AAyCA;;EAEE;AACF,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEtD;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;EAEE;AACF,UAAU,YAAY;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B;AAsID,iBAAS,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CA4EjE;AAqFD;;;;;GAKG;AACH,iBAAS,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,SAAO,EAAE,KAAK,GAAE,WAAoB,GAAG,YAAY,CA2EzG;AAmPD;;;;;;;;;;;;;;EAcE;AACF,iBAAS,kBAAkB,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CAsBnF;AAED;;EAEE;AACF,UAAU,kBAAkB;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,iBAAS,qBAAqB,CAAC,OAAO,EAAE,kBAAkB,GAAG;IAAE,MAAM,EAAE,YAAY,CAAC;IAAC,QAAQ,EAAE,aAAa,EAAE,CAAA;CAAE,CA6B/G;AAED,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,eAAe,EAAE,kBAAkB,EAAE,CAAC;AAC1F,YAAY,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var v=Object.defineProperty;var
|
|
2
|
-
`&&(o=!1);continue}const
|
|
3
|
-
`&&(
|
|
4
|
-
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}
|
|
5
|
-
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}
|
|
1
|
+
var v=Object.defineProperty;var u=(e,t)=>v(e,"name",{value:t,configurable:!0});import{isEntrypoint as _}from"./lib/entrypoint.js";import{existsSync as $,readdirSync as w,readFileSync as g}from"node:fs";import b from"node:path";function y(e,t="",o=new Map){if(e===null||typeof e!="object"||Array.isArray(e))return t&&o.set(t,e),o;const n=Object.entries(e);if(n.length===0)return t&&o.set(t,e),o;for(const[s,r]of n)y(r,t?`${t}.${s}`:s,o);return o}u(y,"flatten");function x(e){return typeof e!="string"?[]:[...new Set(e.match(/\{\{[^{}]+\}\}/g))].sort((t,o)=>t.localeCompare(o))}u(x,"placeholdersOf");function A(e){const t=g(e,"utf8");return e.endsWith(".ts")?O(t,e):JSON.parse(t)}u(A,"readBundle");function F(e){let t="",o=!1,n=!1;for(let s=0;s<e.length;s+=1){const r=e[s];if(o){r===`
|
|
2
|
+
`&&(o=!1);continue}const l=e[s+1];if(n){r==="*"&&l==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&l==="-"){o=!0;continue}if(r==="/"&&l==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&l!=="="&&l!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const i=e.indexOf("{",s);return i===-1?-1:i}}return-1}u(F,"objectLiteralStart");function O(e,t){const o=F(e);if(o===-1)throw new Error(`${t} has no object literal`);let n=0,s=-1,r="",l=!1,a=!1;for(let p=o;p<e.length;p+=1){const f=e[p];if(l){f===`
|
|
3
|
+
`&&(l=!1);continue}const m=e[p+1];if(a){f==="*"&&m==="/"&&(a=!1,p+=1);continue}if(r!==""){if(f==="\\"){p+=1;continue}f===r&&(r="");continue}if(f==="-"&&m==="-"){l=!0;continue}if(f==="/"&&m==="*"){a=!0;continue}if(f==="'"||f==='"'||f==="`"){r=f;continue}if(f==="{")n+=1;else if(f==="}"&&(n-=1,n===0)){s=p;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const h=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(p,f)=>JSON.stringify(J(f))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(h)}catch(p){throw new Error(`${t} object literal could not be parsed: ${p instanceof Error?p.message:String(p)}`)}}u(O,"parseObjectLiteral");function J(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
|
|
4
|
+
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}u(J,"unescapeLiteral");const j={file:"json",module:"ts"};function S(e){return e==="auto"?["dir","file","module"]:[e]}u(S,"layouts");function C(e,t){const o=[];S(t).includes("dir")&&o.push(...w(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of S(t)){if(n==="dir")continue;const s=j[n];o.push(...w(e).filter(r=>r.endsWith(`.${s}`)).map(r=>r.slice(0,-s.length-1)))}return o}u(C,"tagsOnDisk");function k(e,t,o){const n=[];S(o).includes("dir")&&n.push(b.join(e,t,"translation.json"));for(const s of S(o))s!=="dir"&&n.push(b.join(e,`${t}.${j[s]}`));return n.find(s=>$(s))}u(k,"bundleFor");function U(e,t,o){const n=k(e,t,o);if(n===void 0)throw new Error(`no bundle found for the base locale (expected ${t}/translation.json)`);return y(A(n))}u(U,"bundleAt");function N(e,t="en",o="auto"){const n=[];if(!$(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const s=k(e,t,o);if(s===void 0)return n.push({locale:t,problem:`no bundle found for the base locale (expected ${t}/translation.json)`}),{locales:[],keys:0,problems:n};let r;try{r=y(A(s))}catch(i){return n.push({locale:t,problem:`${s}: ${i instanceof Error?i.message:String(i)}`}),{locales:[],keys:0,problems:n}}const l=new Set(r.keys());if(l.size===0)return n.push({locale:t,problem:`${s} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const a=[...new Set([...C(e,o),t])].sort((i,d)=>i.localeCompare(d));for(const i of a){const d=k(e,i,o);if(d===void 0){n.push({locale:i,problem:"no bundle found"});continue}let c;try{c=y(A(d))}catch(h){n.push({locale:i,problem:`${d}: ${h instanceof Error?h.message:String(h)}`});continue}for(const h of l)c.has(h)||n.push({locale:i,problem:`missing key: ${h}`});for(const[h,p]of c){if(!l.has(h)){n.push({locale:i,problem:`extra key not in ${t}: ${h}`});continue}if(typeof p!="string"||p===""){n.push({locale:i,problem:`empty value: ${h} \u2014 indistinguishable from a missing key at runtime`});continue}const f=x(r.get(h));if(f.length===0)continue;const m=x(p);(f.length!==m.length||f.some((L,W)=>L!==m[W]))&&n.push({locale:i,problem:`placeholder mismatch at ${h}: ${i} has ${JSON.stringify(m)}, ${t} has ${JSON.stringify(f)}`})}}return{locales:a,keys:l.size,problems:n}}u(N,"validateLocales");function K(e,t,o){const n=[];for(const s of E(e)){const r=g(s,"utf8"),l=/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;for(const a of r.matchAll(l)){const i=a[2];if(i.includes("${")||i.includes("{{"))continue;const d=b.relative(process.cwd(),s)||s;if(!t.has(i)){n.push({locale:"call-site",problem:`${d}: t('${i}') is not in the bundle \u2014 it renders as the inline default and is untranslatable`});continue}if(!a[3])continue;const c=q(r,a.index+a[0].length);if(c===null)continue;const h=o.get(i);c!==h&&n.push({locale:"call-site",problem:`${d}: t('${i}', \u2026) default disagrees with the bundle \u2014 bundle=${JSON.stringify(h)} default=${JSON.stringify(c)}`})}}return n}u(K,"collectCallSites");function q(e,t){const o=e.slice(t).replace(/^\s+/,""),n=o[0];if(n!=="'"&&n!=='"')return null;const s=o.slice(1),l=(n==="'"?/^(?:[^'\\]|\\.)*'/:/^(?:[^"\\]|\\.)*"/).exec(s);return l?B(s.slice(0,l[0].length-1)):null}u(q,"readDefault");function B(e){return e.replaceAll(/\\(.)/gs,(t,o)=>{switch(o){case"n":return`
|
|
5
|
+
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}u(B,"decodeStringLiteral");function G(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1/g)){const s=n[2];!s.includes("${")&&!s.includes("{{")&&t.add(s)}return t}u(G,"usedKeys");function E(e){const t=[],o=u(n=>{for(const s of w(n,{withFileTypes:!0})){const r=b.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules"||s.name==="dist"||s.name==="coverage")continue;o(r);continue}e.extensions.some(l=>s.name.endsWith(l))&&t.push(r)}},"walk");return o(e.dir),t}u(E,"sourceFiles");function R(e,t,o){const n=D(t),s=e.filter(r=>!o.has(r)&&[...n].every(l=>!(r===l||r.startsWith(`${l}.`))));return s.length===0?[]:[{locale:"call-site",problem:`${s.length} base key(s) are not reached by any t() call site: ${s.slice(0,20).join(", ")}${s.length>20?", \u2026":""}`,advisory:!0}]}u(R,"collectUnusedKeys");function D(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*`([^`$]*)\$\{/g)){const s=n[1].replace(/\.$/,"");s&&t.add(s)}return t}u(D,"dynamicKeyPrefixes");function z(e){const t=g(e,"utf8"),o=/(?:export\s+)?const\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\s*=\s*\[([^\]]*)\]/.exec(t);if(!o)throw new Error(`${e} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);return[...(o[1]??"").matchAll(/['"]([^'"]+)['"]/g)].map(n=>n[1])}u(z,"declaredTags");function Q(e,t,o){const n=z(t),s=[];for(const r of n)o.includes(r)||s.push({locale:"tags",problem:`${t} declares '${r}' but ${e}/${r} does not exist \u2014 selecting that language throws`});for(const r of o)n.includes(r)||s.push({locale:"tags",problem:`${e}/${r} exists but ${t} does not declare it \u2014 the selector cannot offer it`});return s}u(Q,"checkDeclaredTags");function T(e=process.argv.slice(2)){const t=e.find(c=>!c.startsWith("--"))??"apps/web/src/locales",o=e.find(c=>c.startsWith("--shape="))?.slice(8)??"auto",n=e.find(c=>c.startsWith("--base="))?.slice(7)??"en",s=e.find(c=>c.startsWith("--call-sites="))?.slice(13),r=e.find(c=>c.startsWith("--tags="))?.slice(7),{report:l,problems:a}=P({dir:t,base:n,shape:o,callSiteDir:s,tagsFile:r}),i=a.filter(c=>c.advisory!==!0),d=a.filter(c=>c.advisory===!0);if(i.length>0){console.error(`Locale validation failed for ${t} (${i.length} problem(s)):`);for(const c of i)console.error(` - ${c.locale}: ${c.problem}`);return 1}if(d.length>0){console.warn(`Locale validation passed for ${t} with ${d.length} advisory finding(s):`);for(const c of d)console.warn(` - ${c.locale}: ${c.problem}`)}return console.log(`Locale validation passed (${l.locales.length} locales, ${l.keys} keys each, shape ${o}).`),0}u(T,"validateLocalesCli");function P(e){const{dir:t,callSiteDir:o,tagsFile:n}=e,s=e.base??"en",r=e.shape??"auto",l=N(t,s,r),a=[...l.problems];if(n!==void 0&&$(n))try{a.push(...Q(t,n,C(t,r)))}catch(i){a.push({locale:"tags",problem:`${n}: ${i instanceof Error?i.message:String(i)}`})}if(o!==void 0&&$(o))try{const i=U(t,s,r),d={dir:o,extensions:[".ts",".tsx"]},c=G(d);a.push(...K(d,new Set(i.keys()),i),...R([...i.keys()],d,c))}catch(i){a.push({locale:"call-site",problem:`${o}: ${i instanceof Error?i.message:String(i)}`})}return{report:l,problems:a}}u(P,"collectLocaleProblems");_(import.meta.url)&&process.exit(T(process.argv.slice(2)));export{P as collectLocaleProblems,O as parseObjectLiteral,N as validateLocales,T as validateLocalesCli};
|