@rexezuge/tooling 1.1.0 → 1.3.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 (89) hide show
  1. package/README.md +66 -10
  2. package/dist/eslint-boundaries.d.ts +19 -3
  3. package/dist/eslint-boundaries.d.ts.map +1 -1
  4. package/dist/eslint-boundaries.js +89 -3
  5. package/dist/eslint-boundaries.js.map +1 -1
  6. package/dist/eslint.d.ts +12 -7
  7. package/dist/eslint.d.ts.map +1 -1
  8. package/dist/eslint.js +13 -8
  9. package/dist/eslint.js.map +1 -1
  10. package/dist/index.d.ts +20 -14
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +10 -7
  13. package/dist/index.js.map +1 -1
  14. package/dist/scripts/backup/d1-target.js +1 -1
  15. package/dist/scripts/backup/d1-target.js.map +1 -1
  16. package/dist/scripts/backup/encrypt-backup.js +2 -2
  17. package/dist/scripts/backup/encrypt-backup.js.map +1 -1
  18. package/dist/scripts/check-god-files.js +2 -2
  19. package/dist/scripts/check-god-files.js.map +1 -1
  20. package/dist/scripts/ensure-spa-shell-stub.js +1 -1
  21. package/dist/scripts/ensure-spa-shell-stub.js.map +1 -1
  22. package/dist/scripts/init-secrets.d.ts +1 -1
  23. package/dist/scripts/init-secrets.d.ts.map +1 -1
  24. package/dist/scripts/init-secrets.js +3 -3
  25. package/dist/scripts/init-secrets.js.map +1 -1
  26. package/dist/scripts/migrations-lock.js +1 -1
  27. package/dist/scripts/migrations-lock.js.map +1 -1
  28. package/dist/scripts/prepare-wrangler-config.js +3 -3
  29. package/dist/scripts/prepare-wrangler-config.js.map +1 -1
  30. package/dist/scripts/verify-spa-shell.js +1 -1
  31. package/dist/scripts/verify-spa-shell.js.map +1 -1
  32. package/dist/scripts/wrangler-config/patches.d.ts +1 -1
  33. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  34. package/dist/scripts/wrangler-config/patches.js +1 -1
  35. package/dist/scripts/wrangler-config/patches.js.map +1 -1
  36. package/dist/scripts/wrangler-config/resources.d.ts +1 -1
  37. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  38. package/dist/scripts/wrangler-config/resources.js +4 -4
  39. package/dist/scripts/wrangler-config/resources.js.map +1 -1
  40. package/dist/vitest-aliases.d.ts +90 -0
  41. package/dist/vitest-aliases.d.ts.map +1 -0
  42. package/dist/vitest-aliases.js +81 -0
  43. package/dist/vitest-aliases.js.map +1 -0
  44. package/dist/vitest-integration.d.ts +96 -0
  45. package/dist/vitest-integration.d.ts.map +1 -0
  46. package/dist/vitest-integration.js +64 -0
  47. package/dist/vitest-integration.js.map +1 -0
  48. package/dist/vitest-repo.d.ts +154 -0
  49. package/dist/vitest-repo.d.ts.map +1 -0
  50. package/dist/vitest-repo.js +146 -0
  51. package/dist/vitest-repo.js.map +1 -0
  52. package/dist/vitest-web.d.ts +76 -19
  53. package/dist/vitest-web.d.ts.map +1 -1
  54. package/dist/vitest-web.js +62 -25
  55. package/dist/vitest-web.js.map +1 -1
  56. package/dist/vitest.d.ts +70 -19
  57. package/dist/vitest.d.ts.map +1 -1
  58. package/dist/vitest.js +42 -37
  59. package/dist/vitest.js.map +1 -1
  60. package/package.json +8 -2
  61. package/src/eslint-boundaries.ts +99 -6
  62. package/src/eslint.test.ts +22 -1
  63. package/src/eslint.ts +14 -9
  64. package/src/functions/pages-proxy.test.ts +2 -2
  65. package/src/index.ts +23 -14
  66. package/src/scripts/backup/backup-rules.test.ts +3 -3
  67. package/src/scripts/backup/d1-target.ts +1 -1
  68. package/src/scripts/backup/encrypt-backup.ts +2 -2
  69. package/src/scripts/check-god-files.test.ts +1 -1
  70. package/src/scripts/check-god-files.ts +2 -2
  71. package/src/scripts/ensure-spa-shell-stub.ts +1 -1
  72. package/src/scripts/init-secrets.ts +3 -3
  73. package/src/scripts/migrations-lock.ts +1 -1
  74. package/src/scripts/prepare-wrangler-config.ts +3 -3
  75. package/src/scripts/spa-shell.test.ts +1 -1
  76. package/src/scripts/validate-locales.test.ts +1 -1
  77. package/src/scripts/verify-migrations.test.ts +1 -1
  78. package/src/scripts/verify-spa-shell.ts +1 -1
  79. package/src/scripts/wrangler-config/patches.ts +1 -1
  80. package/src/scripts/wrangler-config/resources.ts +4 -4
  81. package/src/test/integration-migrations.test.ts +1 -1
  82. package/src/vite.test.ts +1 -1
  83. package/src/vitest-aliases.test.ts +53 -0
  84. package/src/vitest-aliases.ts +127 -0
  85. package/src/vitest-factories.test.ts +127 -0
  86. package/src/vitest-integration.ts +118 -0
  87. package/src/vitest-repo.ts +269 -0
  88. package/src/vitest-web.ts +110 -28
  89. package/src/vitest.ts +96 -47
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGhD,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAGlD,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAGrD,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAGlE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAG3D,6EAA6E;AAC7E,EAAE;AACF,kFAAkF;AAClF,mCAAmC;AAEnC,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAG/F,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC","sourcesContent":["/**\n * `@rexezuge/tooling` — the tooling layer of the kit.\n *\n * The config factories and the test helpers are re-exported here, so a consumer has\n * one import for everything its `*.config.mts` files and its mocks need. The\n * scripts under `scripts/` are **not** re-exported: they resolve paths relative to\n * the repository they run in, so they are run from disk with `tsx`, not imported.\n * See `README.md` for the copy-in recipe and the per-script usage.\n *\n * The zero-dependency rule: nothing here imports another `@rexezuge/*` package. The\n * one exception in the tree is `scripts/backup/encrypt-backup.ts`, which uses\n * `@rexezuge/d1`'s AES-GCM so the backup and the workers share one definition of\n * \"what an encryption key looks like\"; that dependency is declared on the package\n * and is only ever resolved in the consumer's repo, where the kit is installed\n * alongside `@rexezuge/d1`.\n */\n\nexport { defineRepoLintConfig } from './eslint';\nexport type { RepoLintConfigOptions } from './eslint';\n\nexport { defineUnitVitestConfig } from './vitest';\nexport type { CoverageThresholds, UnitVitestConfigOptions, VitestAlias } from './vitest';\n\nexport { defineWebVitestConfig } from './vitest-web';\nexport type { WebVitestConfigOptions } from './vitest-web';\n\nexport { defineWebViteConfig, spaShellEmbedPlugin } from './vite';\nexport type { ProxyEntry, SpaShellTarget, WebViteConfigOptions } from './vite';\n\nexport { createPagesProxy } from './functions/pages-proxy';\nexport type { Fetcher, PagesFunction, PagesFunctionContext, PagesProxyEnv, PagesProxyOptions } from './functions/pages-proxy';\n\n// --- Test helpers ---------------------------------------------------------\n//\n// Aliased in a Vitest config, not imported by application code, so the mocks stay\n// where the suites can reach them.\n\nexport { DurableObject, RpcTarget, WorkflowEntrypoint } from './test/mocks/cloudflare-workers';\nexport type { DurableObjectState, ExecutionContext } from './test/mocks/cloudflare-workers';\n\nexport { createMigrationHelper, readMigrationFiles, splitSql } from './test/integration-migrations';\nexport type {\n D1DatabaseLike,\n D1PreparedStatementLike,\n MigrationFile,\n MigrationHelper,\n MigrationHelperOptions,\n MigrationRange,\n} from './test/integration-migrations';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAGrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AAGxE,OAAO,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG9H,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAGrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAG9D,6EAA6E;AAC7E,EAAE;AACF,kFAAkF;AAClF,mCAAmC;AAEnC,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAGlG,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC","sourcesContent":["/**\n * `@rexezuge/tooling` — the tooling layer of the kit.\n *\n * The config factories and the test helpers are re-exported here, so a consumer has\n * one import for everything its `*.config.mts` files and its mocks need. The\n * scripts under `scripts/` are **not** re-exported: they resolve paths relative to\n * the repository they run in, so they are run from disk with `tsx`, not imported.\n * See `README.md` for the copy-in recipe and the per-script usage.\n *\n * The zero-dependency rule: nothing here imports another `@rexezuge/*` package. The\n * one exception in the tree is `scripts/backup/encrypt-backup.ts`, which uses\n * `@rexezuge/d1`'s AES-GCM so the backup and the workers share one definition of\n * \"what an encryption key looks like\"; that dependency is declared on the package\n * and is only ever resolved in the consumer's repo, where the kit is installed\n * alongside `@rexezuge/d1`.\n */\n\nexport { defineRepoLintConfig } from './eslint.ts';\nexport type { RepoLintConfigOptions } from './eslint.ts';\n\nexport { defineUnitVitestConfig } from './vitest.ts';\nexport type { CoverageThresholds, UnitVitestConfigOptions, VitestAlias } from './vitest.ts';\n\nexport { defineWebVitestConfig } from './vitest-web.ts';\nexport type { WebVitestConfigOptions } from './vitest-web.ts';\n\nexport { defineRepoVitestConfig } from './vitest-repo.ts';\nexport type { RepoBackendOptions, RepoVitestConfigOptions, RepoWebOptions } from './vitest-repo.ts';\n\nexport { defineIntegrationVitestConfig } from './vitest-integration.ts';\nexport type { IntegrationVitestConfigOptions } from './vitest-integration.ts';\n\nexport { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';\nexport type { VitestAlias as WorkspaceAlias, WorkspaceAliasesOptions } from './vitest-aliases.ts';\n\nexport { defineWebViteConfig, spaShellEmbedPlugin } from './vite.ts';\nexport type { ProxyEntry, SpaShellTarget, WebViteConfigOptions } from './vite.ts';\n\nexport { createPagesProxy } from './functions/pages-proxy.ts';\nexport type { Fetcher, PagesFunction, PagesFunctionContext, PagesProxyEnv, PagesProxyOptions } from './functions/pages-proxy.ts';\n\n// --- Test helpers ---------------------------------------------------------\n//\n// Aliased in a Vitest config, not imported by application code, so the mocks stay\n// where the suites can reach them.\n\nexport { DurableObject, RpcTarget, WorkflowEntrypoint } from './test/mocks/cloudflare-workers.ts';\nexport type { DurableObjectState, ExecutionContext } from './test/mocks/cloudflare-workers.ts';\n\nexport { createMigrationHelper, readMigrationFiles, splitSql } from './test/integration-migrations.ts';\nexport type {\n D1DatabaseLike,\n D1PreparedStatementLike,\n MigrationFile,\n MigrationHelper,\n MigrationHelperOptions,\n MigrationRange,\n} from './test/integration-migrations.ts';\n"]}
@@ -5,7 +5,7 @@
5
5
  * empty-database guard is asserted without running Actions or touching a real
6
6
  * account.
7
7
  */
8
- import { DEFAULT_UUID } from '../wrangler-config/types';
8
+ import { DEFAULT_UUID } from "../wrangler-config/types.js";
9
9
  /**
10
10
  * Pick the export target from a parsed wrangler config.
11
11
  *
@@ -1 +1 @@
1
- {"version":3,"file":"d1-target.js","sourceRoot":"","sources":["../../../src/scripts/backup/d1-target.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAmBxD;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAAC,MAA8C;IAC5E,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC;IAE1C,MAAM,OAAO,GAAG,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1C,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CAAC,+DAA+D,CAAC,CAAC;IACnF,CAAC;IAED,MAAM,UAAU,GAAG,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACvD,IAAI,UAAU,KAAK,YAAY,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,sBAAsB,OAAO,sGAAsG,CACpI,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC;IAC1D,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Choosing which D1 database the backup workflow exports.\n *\n * Provenance: ported from Edge-Sonic's `scripts/backup/d1-target.ts`. Pure, so the\n * empty-database guard is asserted without running Actions or touching a real\n * account.\n */\n\nimport { DEFAULT_UUID } from '../wrangler-config/types';\n\n/** A D1 binding as a parsed wrangler config carries one. */\nexport interface D1DatabaseBinding {\n binding?: string;\n database_id?: string;\n database_name?: string;\n}\n\n/** The resolved export target. */\nexport interface D1Target {\n /** The binding name, used for log output and as the export fallback. */\n binding: string;\n /** The database id, verified against Cloudflare by the caller. */\n databaseId: string;\n /** What `wrangler d1 export` should be pointed at. */\n target: string;\n}\n\n/**\n * Pick the export target from a parsed wrangler config.\n *\n * `wrangler d1 export` takes a database *name*, so `database_name` wins when\n * present. Hand-written configs that omit it fall back to the binding name.\n *\n * @throws when there is no binding, or when `database_id` is still the template\n * placeholder — meaning the database was auto-provisioned and holds no data.\n */\nexport function resolveD1Target(config: { d1_databases?: D1DatabaseBinding[] }): D1Target {\n const database = config.d1_databases?.[0];\n\n const binding = database?.binding?.trim();\n if (binding === undefined || binding === '') {\n throw new Error('No d1_databases entry with a binding found in wrangler.jsonc.');\n }\n\n const databaseId = database?.database_id?.trim() ?? '';\n if (databaseId === DEFAULT_UUID) {\n throw new Error(\n `D1 database_id for ${binding} is still the template placeholder. The database does not exist yet, so there is nothing to back up.`,\n );\n }\n\n const target = database?.database_name?.trim() || binding;\n return { binding, databaseId, target };\n}\n"]}
1
+ {"version":3,"file":"d1-target.js","sourceRoot":"","sources":["../../../src/scripts/backup/d1-target.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAmB3D;;;;;;;;GAQG;AACH,MAAM,UAAU,eAAe,CAAC,MAA8C;IAC5E,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,CAAC;IAE1C,MAAM,OAAO,GAAG,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1C,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CAAC,+DAA+D,CAAC,CAAC;IACnF,CAAC;IAED,MAAM,UAAU,GAAG,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACvD,IAAI,UAAU,KAAK,YAAY,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,sBAAsB,OAAO,sGAAsG,CACpI,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC;IAC1D,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Choosing which D1 database the backup workflow exports.\n *\n * Provenance: ported from Edge-Sonic's `scripts/backup/d1-target.ts`. Pure, so the\n * empty-database guard is asserted without running Actions or touching a real\n * account.\n */\n\nimport { DEFAULT_UUID } from '../wrangler-config/types.ts';\n\n/** A D1 binding as a parsed wrangler config carries one. */\nexport interface D1DatabaseBinding {\n binding?: string;\n database_id?: string;\n database_name?: string;\n}\n\n/** The resolved export target. */\nexport interface D1Target {\n /** The binding name, used for log output and as the export fallback. */\n binding: string;\n /** The database id, verified against Cloudflare by the caller. */\n databaseId: string;\n /** What `wrangler d1 export` should be pointed at. */\n target: string;\n}\n\n/**\n * Pick the export target from a parsed wrangler config.\n *\n * `wrangler d1 export` takes a database *name*, so `database_name` wins when\n * present. Hand-written configs that omit it fall back to the binding name.\n *\n * @throws when there is no binding, or when `database_id` is still the template\n * placeholder — meaning the database was auto-provisioned and holds no data.\n */\nexport function resolveD1Target(config: { d1_databases?: D1DatabaseBinding[] }): D1Target {\n const database = config.d1_databases?.[0];\n\n const binding = database?.binding?.trim();\n if (binding === undefined || binding === '') {\n throw new Error('No d1_databases entry with a binding found in wrangler.jsonc.');\n }\n\n const databaseId = database?.database_id?.trim() ?? '';\n if (databaseId === DEFAULT_UUID) {\n throw new Error(\n `D1 database_id for ${binding} is still the template placeholder. The database does not exist yet, so there is nothing to back up.`,\n );\n }\n\n const target = database?.database_name?.trim() || binding;\n return { binding, databaseId, target };\n}\n"]}
@@ -35,8 +35,8 @@ import { encryptSecret } from '@rexezuge/d1';
35
35
  import { execFileSync } from 'node:child_process';
36
36
  import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
37
  import { basename } from 'node:path';
38
- import { fail, setOutput } from '../lib/github-actions';
39
- import { backupFileName } from './naming';
38
+ import { fail, setOutput } from "../lib/github-actions.js";
39
+ import { backupFileName } from "./naming.js";
40
40
  /** The dump the export step leaves in the working directory. */
41
41
  const SOURCE_FILE = 'backup.sql';
42
42
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"encrypt-backup.js","sourceRoot":"","sources":["../../../src/scripts/backup/encrypt-backup.ts"],"names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E,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC5G,MAAM,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAErC,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,KAAK,UAAU,CAAC,UAAU,oBAAoB,CAAC,CAAC;AACrF,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\n * Compress and encrypt the exported D1 dump.\n *\n * Provenance: Edge-Sonic's `scripts/backup/encrypt-backup.ts`, converged with the\n * AES-GCM envelope every repo in the family already uses for its secrets. This is\n * the one backup script that ported cleanly and changed *for the better* on the way\n * in: the source shelled out to `openssl enc -aes-256-cbc -pbkdf2`, which is a\n * password-derived key with a KDF whose cost is a constant somebody chose once,\n * and which is not authenticated — a flipped byte in the ciphertext is undetectable.\n *\n * The kit's version uses `@rexezuge/d1`'s `encryptSecret`, the same WebCrypto\n * AES-256-GCM primitive the workers use, over a base64 32-byte key — the same key\n * format `resolveReplicationKey` reads. One definition of \"what an encryption key\n * looks like\" across the deploy path and the backup path is the point: a second\n * implementation is how a deploy ends up generating something the worker cannot\n * read, and here it would be how a backup ends up unreadable by the restore path.\n *\n * Fail-closed: without `BACKUP_ENCRYPTION_KEY` the script refuses to run and\n * deletes nothing, so an unencrypted dump can never reach the artifact store the\n * upload jobs read from.\n *\n * The passphrase is read from the environment rather than passed as an argument,\n * because command-line arguments are visible to any process on the runner via `ps`.\n *\n * Emits the resulting file name as the `file` step output.\n *\n * Usage, from the repo root (after `wrangler d1 export … --output=backup.sql`):\n *\n * ```bash\n * BACKUP_ENCRYPTION_KEY=… pnpm exec tsx scripts/backup/encrypt-backup.ts\n * ```\n */\n\nimport { encryptSecret } from '@rexezuge/d1';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fail, setOutput } from '../lib/github-actions';\nimport { backupFileName } from './naming';\n\n/** The dump the export step leaves in the working directory. */\nconst SOURCE_FILE = 'backup.sql';\n\n/**\n * xz preset 6, chosen for ratio over speed: this runs once a day against a dump\n * that is mostly SQL text and JSON blobs, and LZMA typically beats gzip by 20-30%\n * there. `-T0` uses every available thread, which matters because xz is markedly\n * slower than gzip and the job is wall-clock bound.\n */\nconst XZ_ARGS = ['-T0', '-6'];\n\nfunction run(command: string, args: readonly string[]): void {\n execFileSync(command, [...args], { stdio: ['ignore', 'inherit', 'inherit'] });\n}\n\nif (!process.env['BACKUP_ENCRYPTION_KEY']) {\n fail('BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database.');\n}\n\nif (!existsSync(SOURCE_FILE)) {\n fail(`Expected ${SOURCE_FILE} from the export step, but it does not exist.`);\n}\n\nconst key = process.env['BACKUP_ENCRYPTION_KEY'] as string;\nconst file = backupFileName(new Date());\n\nlet plaintext: string;\ntry {\n plaintext = readFileSync(SOURCE_FILE, 'utf8');\n} catch (error: unknown) {\n fail(`Could not read ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nif (plaintext === '') {\n fail(`${SOURCE_FILE} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);\n}\n\n/**\n * Compress first, then encrypt.\n *\n * The order matters: compression over ciphertext buys nothing, and encrypting the\n * compressed bytes means the plaintext is never re-materialised on disk at full\n * size. Unlike gzip, xz leaves its input in place, so the plaintext SQL has to be\n * removed explicitly here or it survives into the artifact store.\n */\nlet compressed: Buffer;\ntry {\n compressed = execFileSync('xz', [...XZ_ARGS, '--keep', '--stdout', SOURCE_FILE], { maxBuffer: 512 * 1024 * 1024 });\n} catch (error: unknown) {\n fail(`xz failed on ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nlet envelope: { ciphertext: string; iv: string };\ntry {\n envelope = await encryptSecret(compressed.toString('base64'), key);\n} catch (error: unknown) {\n // A key that is not 32 base64 bytes, or not valid base64 at all, fails here\n // rather than producing a file nothing can open.\n fail(`Could not encrypt the dump: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nwriteFileSync(file, `${JSON.stringify({ ...envelope, source: basename(SOURCE_FILE) }, null, 2)}\\n`, 'utf8');\nrmSync(SOURCE_FILE, { force: true });\n\nconsole.log(`Backup encrypted: ${file} (${compressed.byteLength} compressed bytes)`);\nsetOutput('file', file);\n"]}
1
+ {"version":3,"file":"encrypt-backup.js","sourceRoot":"","sources":["../../../src/scripts/backup/encrypt-backup.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,gEAAgE;AAChE,MAAM,WAAW,GAAG,YAAY,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AAE9B,SAAS,GAAG,CAAC,OAAe,EAAE,IAAuB;IACnD,YAAY,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,CAAC,CAAC;AAChF,CAAC;AAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,EAAE,CAAC;IAC1C,IAAI,CAAC,+EAA+E,CAAC,CAAC;AACxF,CAAC;AAED,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;IAC7B,IAA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4EAA4E;IAC5E,iDAAiD;IACjD,IAAI,CAAC,+BAA+B,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAChG,CAAC;AAED,aAAa,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,WAAW,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC5G,MAAM,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAErC,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,KAAK,UAAU,CAAC,UAAU,oBAAoB,CAAC,CAAC;AACrF,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\n * Compress and encrypt the exported D1 dump.\n *\n * Provenance: Edge-Sonic's `scripts/backup/encrypt-backup.ts`, converged with the\n * AES-GCM envelope every repo in the family already uses for its secrets. This is\n * the one backup script that ported cleanly and changed *for the better* on the way\n * in: the source shelled out to `openssl enc -aes-256-cbc -pbkdf2`, which is a\n * password-derived key with a KDF whose cost is a constant somebody chose once,\n * and which is not authenticated — a flipped byte in the ciphertext is undetectable.\n *\n * The kit's version uses `@rexezuge/d1`'s `encryptSecret`, the same WebCrypto\n * AES-256-GCM primitive the workers use, over a base64 32-byte key — the same key\n * format `resolveReplicationKey` reads. One definition of \"what an encryption key\n * looks like\" across the deploy path and the backup path is the point: a second\n * implementation is how a deploy ends up generating something the worker cannot\n * read, and here it would be how a backup ends up unreadable by the restore path.\n *\n * Fail-closed: without `BACKUP_ENCRYPTION_KEY` the script refuses to run and\n * deletes nothing, so an unencrypted dump can never reach the artifact store the\n * upload jobs read from.\n *\n * The passphrase is read from the environment rather than passed as an argument,\n * because command-line arguments are visible to any process on the runner via `ps`.\n *\n * Emits the resulting file name as the `file` step output.\n *\n * Usage, from the repo root (after `wrangler d1 export … --output=backup.sql`):\n *\n * ```bash\n * BACKUP_ENCRYPTION_KEY=… pnpm exec tsx scripts/backup/encrypt-backup.ts\n * ```\n */\n\nimport { encryptSecret } from '@rexezuge/d1';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { fail, setOutput } from '../lib/github-actions.ts';\nimport { backupFileName } from './naming.ts';\n\n/** The dump the export step leaves in the working directory. */\nconst SOURCE_FILE = 'backup.sql';\n\n/**\n * xz preset 6, chosen for ratio over speed: this runs once a day against a dump\n * that is mostly SQL text and JSON blobs, and LZMA typically beats gzip by 20-30%\n * there. `-T0` uses every available thread, which matters because xz is markedly\n * slower than gzip and the job is wall-clock bound.\n */\nconst XZ_ARGS = ['-T0', '-6'];\n\nfunction run(command: string, args: readonly string[]): void {\n execFileSync(command, [...args], { stdio: ['ignore', 'inherit', 'inherit'] });\n}\n\nif (!process.env['BACKUP_ENCRYPTION_KEY']) {\n fail('BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database.');\n}\n\nif (!existsSync(SOURCE_FILE)) {\n fail(`Expected ${SOURCE_FILE} from the export step, but it does not exist.`);\n}\n\nconst key = process.env['BACKUP_ENCRYPTION_KEY'] as string;\nconst file = backupFileName(new Date());\n\nlet plaintext: string;\ntry {\n plaintext = readFileSync(SOURCE_FILE, 'utf8');\n} catch (error: unknown) {\n fail(`Could not read ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nif (plaintext === '') {\n fail(`${SOURCE_FILE} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);\n}\n\n/**\n * Compress first, then encrypt.\n *\n * The order matters: compression over ciphertext buys nothing, and encrypting the\n * compressed bytes means the plaintext is never re-materialised on disk at full\n * size. Unlike gzip, xz leaves its input in place, so the plaintext SQL has to be\n * removed explicitly here or it survives into the artifact store.\n */\nlet compressed: Buffer;\ntry {\n compressed = execFileSync('xz', [...XZ_ARGS, '--keep', '--stdout', SOURCE_FILE], { maxBuffer: 512 * 1024 * 1024 });\n} catch (error: unknown) {\n fail(`xz failed on ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nlet envelope: { ciphertext: string; iv: string };\ntry {\n envelope = await encryptSecret(compressed.toString('base64'), key);\n} catch (error: unknown) {\n // A key that is not 32 base64 bytes, or not valid base64 at all, fails here\n // rather than producing a file nothing can open.\n fail(`Could not encrypt the dump: ${error instanceof Error ? error.message : String(error)}`);\n}\n\nwriteFileSync(file, `${JSON.stringify({ ...envelope, source: basename(SOURCE_FILE) }, null, 2)}\\n`, 'utf8');\nrmSync(SOURCE_FILE, { force: true });\n\nconsole.log(`Backup encrypted: ${file} (${compressed.byteLength} compressed bytes)`);\nsetOutput('file', file);\n"]}
@@ -48,8 +48,8 @@
48
48
  import { readdirSync, readFileSync, statSync } from 'node:fs';
49
49
  import { pathToFileURL } from 'node:url';
50
50
  import { join, relative } from 'node:path';
51
- import { fail } from './lib/github-actions';
52
- import { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args';
51
+ import { fail } from "./lib/github-actions.js";
52
+ import { isSet, parseFlags, splitPositional, valueOf } from "./lib/cli-args.js";
53
53
  /** Default soft limit, as every source repo uses. */
54
54
  export const SOFT_LIMIT = 300;
55
55
  /** Default hard limit, as every source repo uses. */
@@ -1 +1 @@
1
- {"version":3,"file":"check-god-files.js","sourceRoot":"","sources":["../../src/scripts/check-god-files.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,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n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport { join, relative } from 'node:path';\nimport { fail } from './lib/github-actions';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /** Path relative to the root the check ran against. */\n readonly file: string;\n /** Lines it has. */\n readonly lines: number;\n /** `warn` past the soft limit, `critical` past the hard one. */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /** Files over a limit, worst first, minus the allowlisted. */\n readonly findings: readonly GodFileFinding[];\n /** How many files the walk measured. */\n readonly scanned: number;\n /** Allowlisted files that are over a limit — reported, never counted. */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /** The message to print, either way. */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /** Directory to walk. */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /** Soft limit, past which a file is reported as `warn`. */\n readonly soft?: number;\n /** Hard limit, past which a file is reported as `critical`. */\n readonly hard?: number;\n /** Make a `critical` finding fail the run. */\n readonly failOnHard?: boolean;\n}\n\n/** Default soft limit, as every source repo uses. */\nexport const SOFT_LIMIT = 300;\n/** Default hard limit, as every source repo uses. */\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (/(?:^|\\/)(?:locales|generated)\\//.test(rel)) return true;\n if (/(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel)) return true;\n if (/(?:^|\\/)scripts\\//.test(rel)) return true;\n if (/(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel)) return true;\n if (/\\.config\\.(?:m?[jt]s|cjs)$/.test(rel)) return true;\n if (rel.endsWith('.d.ts')) return true;\n if (rel.endsWith('.json')) return true;\n if (rel.endsWith('.sql')) return true;\n if (rel.endsWith('.md')) return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(path: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${path} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${path} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(checkGodFilesCli(process.argv.slice(2)));\n}\n"]}
1
+ {"version":3,"file":"check-god-files.js","sourceRoot":"","sources":["../../src/scripts/check-god-files.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAuDhF,qDAAqD;AACrD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAC9B,qDAAqD;AACrD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;;;GAKG;AACH,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,WAAW,EA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CAAC,MAAM,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACxG,CAAC;IACD,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;QACzC,OAAO,CAAC,GAAG,CAAC,eAAe,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAC9D,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,IAAI,CAAC,0CAA0C,IAAI,qBAAqB,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAED,6CAA6C;AAC7C,EAAE;AACF,iFAAiF;AACjF,oFAAoF;AACpF,kFAAkF;AAClF,oFAAoF;AACpF,uCAAuC;AACvC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC7F,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACxD,CAAC","sourcesContent":["/**\n * The rules behind `scripts/check-god-files.ts`.\n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport { join, relative } from 'node:path';\nimport { fail } from './lib/github-actions.ts';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /** Path relative to the root the check ran against. */\n readonly file: string;\n /** Lines it has. */\n readonly lines: number;\n /** `warn` past the soft limit, `critical` past the hard one. */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /** Files over a limit, worst first, minus the allowlisted. */\n readonly findings: readonly GodFileFinding[];\n /** How many files the walk measured. */\n readonly scanned: number;\n /** Allowlisted files that are over a limit — reported, never counted. */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /** The message to print, either way. */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /** Directory to walk. */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /** Soft limit, past which a file is reported as `warn`. */\n readonly soft?: number;\n /** Hard limit, past which a file is reported as `critical`. */\n readonly hard?: number;\n /** Make a `critical` finding fail the run. */\n readonly failOnHard?: boolean;\n}\n\n/** Default soft limit, as every source repo uses. */\nexport const SOFT_LIMIT = 300;\n/** Default hard limit, as every source repo uses. */\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (/(?:^|\\/)(?:locales|generated)\\//.test(rel)) return true;\n if (/(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel)) return true;\n if (/(?:^|\\/)scripts\\//.test(rel)) return true;\n if (/(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel)) return true;\n if (/\\.config\\.(?:m?[jt]s|cjs)$/.test(rel)) return true;\n if (rel.endsWith('.d.ts')) return true;\n if (rel.endsWith('.json')) return true;\n if (rel.endsWith('.sql')) return true;\n if (rel.endsWith('.md')) return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(path: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${path} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${path} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(checkGodFilesCli(process.argv.slice(2)));\n}\n"]}
@@ -20,7 +20,7 @@
20
20
  */
21
21
  import path from 'node:path';
22
22
  import { fileURLToPath } from 'node:url';
23
- import { ensureSpaShellStub } from './spa-shell';
23
+ import { ensureSpaShellStub } from "./spa-shell.js";
24
24
  const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
25
25
  const root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);
26
26
  const result = ensureSpaShellStub({ root });
@@ -1 +1 @@
1
- {"version":3,"file":"ensure-spa-shell-stub.js","sourceRoot":"","sources":["../../src/scripts/ensure-spa-shell-stub.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AACzF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7F,MAAM,MAAM,GAAG,kBAAkB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;AAE5C,OAAO,CAAC,GAAG,CACT,MAAM,CAAC,OAAO;IACZ,CAAC,CAAC,0CAA0C,MAAM,CAAC,IAAI,EAAE;IACzD,CAAC,CAAC,0BAA0B,MAAM,CAAC,IAAI,kCAAkC,CAC5E,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\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 { ensureSpaShellStub } from './spa-shell';\n\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\nconst root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);\n\nconst result = ensureSpaShellStub({ root });\n\nconsole.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"]}
1
+ {"version":3,"file":"ensure-spa-shell-stub.js","sourceRoot":"","sources":["../../src/scripts/ensure-spa-shell-stub.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AACzF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7F,MAAM,MAAM,GAAG,kBAAkB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;AAE5C,OAAO,CAAC,GAAG,CACT,MAAM,CAAC,OAAO;IACZ,CAAC,CAAC,0CAA0C,MAAM,CAAC,IAAI,EAAE;IACzD,CAAC,CAAC,0BAA0B,MAAM,CAAC,IAAI,kCAAkC,CAC5E,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\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 { ensureSpaShellStub } from './spa-shell.ts';\n\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\nconst root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);\n\nconst result = ensureSpaShellStub({ root });\n\nconsole.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"]}
@@ -43,7 +43,7 @@
43
43
  * config is missing, because a step reporting "Secret initialization complete"
44
44
  * having created nothing is worse than a named error.
45
45
  */
46
- import { type WranglerConfig } from './wrangler-config/types';
46
+ import { type WranglerConfig } from './wrangler-config/types.ts';
47
47
  /** Whether this script can produce a value for `secretName`. */
48
48
  export declare function canProvisionSecret(secretName: string): boolean;
49
49
  /** One secret to create, as the plan names it. */
@@ -1 +1 @@
1
- {"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAOH,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAqD3E,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAO9D;AAwCD,kDAAkD;AAClD,UAAU,aAAa;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,cAAc,GAAG,aAAa,EAAE,CAkBnE"}
1
+ {"version":3,"file":"init-secrets.d.ts","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAOH,OAAO,EAAe,KAAK,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAqD9E,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAO9D;AAwCD,kDAAkD;AAClD,UAAU,aAAa;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,cAAc,GAAG,aAAa,EAAE,CAkBnE"}
@@ -46,9 +46,9 @@
46
46
  import { execFileSync } from 'node:child_process';
47
47
  import { existsSync, readFileSync } from 'node:fs';
48
48
  import { parse } from 'jsonc-parser';
49
- import { fail } from './lib/github-actions';
50
- import { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table';
51
- import { CONFIG_PATH } from './wrangler-config/types';
49
+ import { fail } from "./lib/github-actions.js";
50
+ import { isEmptySecretsStoreListing, parseWranglerNames } from "./lib/wrangler-table.js";
51
+ import { CONFIG_PATH } from "./wrangler-config/types.js";
52
52
  /**
53
53
  * The secret names the AES-GCM key generator produces, matched by **shape**.
54
54
  *
@@ -1 +1 @@
1
- {"version":3,"file":"init-secrets.js","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,WAAW,EAAuB,MAAM,yBAAyB,CAAC;AAE3E;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEhD,qEAAqE;AACrE,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEhD,2FAA2F;AAC3F,KAAK,UAAU,iBAAiB;IAC9B,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;IAC5G,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,C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AAC,OAAO,CAAC,EAAE,CAAC;YAChC,aAAa,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;QACvD,CAAC;QACD,MAAM,QAAQ,GAAG,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,8EAA8E;YAC9E,6CAA6C;YAC7C,MAAM,IAAI,KAAK,CAAC,mCAAmC,OAAO,wBAAwB,UAAU,mCAAmC,CAAC,CAAC;QACnI,CAAC;QACD,IAAI,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7B,OAAO,CAAC,GAAG,CAAC,UAAU,UAAU,wCAAwC,CAAC,CAAC;YAC1E,SAAS;QACX,CAAC;QACD,YAAY,CAAC,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QACpE,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AAChD,CAAC;AAED,qFAAqF;AACrF,oFAAoF;AACpF,oFAAoF;AACpF,iEAAiE;AACjE,IAAI,CAAC;IACH,MAAM,IAAI,EAAE,CAAC;AACf,CAAC;AAAC,OAAO,KAAc,EAAE,CAAC;IACxB,IAAI,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,iCAAiC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AAClG,CAAC","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';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table';\nimport { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types';\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/** The secret names the random signing secret generator produces. */\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/** A 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts. */\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/** A 256-bit random signing secret for internal self-calls, hex-encoded. */\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/** Whether this script can produce a value for `secretName`. */\nexport function 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/** One secret to create, as the plan names it. */\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 */\nexport function 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"]}
1
+ {"version":3,"file":"init-secrets.js","sourceRoot":"","sources":["../../src/scripts/init-secrets.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,WAAW,EAAuB,MAAM,4BAA4B,CAAC;AAE9E;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEhD,qEAAqE;AACrE,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEhD,2FAA2F;AAC3F,KAAK,UAAU,iBAAiB;IAC9B,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,SAAS,EAA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resh\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/** The secret names the random signing secret generator produces. */\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/** A 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts. */\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/** A 256-bit random signing secret for internal self-calls, hex-encoded. */\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/** Whether this script can produce a value for `secretName`. */\nexport function 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/** One secret to create, as the plan names it. */\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 */\nexport function 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"]}
@@ -29,7 +29,7 @@
29
29
  */
30
30
  import path from 'node:path';
31
31
  import { fileURLToPath } from 'node:url';
32
- import { LOCK_NAME, verifyMigrations } from './verify-migrations';
32
+ import { LOCK_NAME, verifyMigrations } from "./verify-migrations.js";
33
33
  const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
34
34
  const migrationsDir = process.argv[2] === undefined ? path.join(REPOSITORY_ROOT, 'migrations') : path.resolve(process.argv[2]);
35
35
  const report = verifyMigrations(migrationsDir, { write: true });
@@ -1 +1 @@
1
- {"version":3,"file":"migrations-lock.js","sourceRoot":"","sources":["../../src/scripts/migrations-lock.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAElE,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AACzF,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE/H,MAAM,MAAM,GAAG,gBAAgB,CAAC,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAEhE,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,QAAQ,EAAE,CAAC;IACtC,OAAO,CAAC,KAAK,CAAC,SAAS,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;AAC5C,CAAC;AAED,OAAO,CAAC,GAAG,CACT,GAAG,MAAM,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,yBAAyB,CACxI,CAAC;AAEF,mFAAmF;AACnF,iFAAiF;AACjF,+EAA+E;AAC/E,2EAA2E;AAC3E,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\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 { LOCK_NAME, verifyMigrations } from './verify-migrations';\n\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\nconst migrationsDir = process.argv[2] === undefined ? path.join(REPOSITORY_ROOT, 'migrations') : path.resolve(process.argv[2]);\n\nconst report = verifyMigrations(migrationsDir, { write: true });\n\nfor (const problem of report.problems) {\n console.error(`FAIL: ${problem.problem}`);\n}\n\nconsole.log(\n `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} ` + `(${report.files.length} migration(s) recorded)`,\n);\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. A `--write`\n// that could not resolve everything still exits non-zero here, which is why an\n// incremental `edited` finding does not vanish just because someone wrote.\nprocess.exit(report.problems.length === 0 ? 0 : 1);\n"]}
1
+ {"version":3,"file":"migrations-lock.js","sourceRoot":"","sources":["../../src/scripts/migrations-lock.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAA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ic'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 { LOCK_NAME, verifyMigrations } from './verify-migrations.ts';\n\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\nconst migrationsDir = process.argv[2] === undefined ? path.join(REPOSITORY_ROOT, 'migrations') : path.resolve(process.argv[2]);\n\nconst report = verifyMigrations(migrationsDir, { write: true });\n\nfor (const problem of report.problems) {\n console.error(`FAIL: ${problem.problem}`);\n}\n\nconsole.log(\n `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} ` + `(${report.files.length} migration(s) recorded)`,\n);\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. A `--write`\n// that could not resolve everything still exits non-zero here, which is why an\n// incremental `edited` finding does not vanish just because someone wrote.\nprocess.exit(report.problems.length === 0 ? 0 : 1);\n"]}
@@ -31,9 +31,9 @@
31
31
  * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.
32
32
  * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.
33
33
  */
34
- import { setOutput } from './lib/github-actions';
35
- import { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches';
36
- import { provisionWranglerResources } from './wrangler-config/resources';
34
+ import { setOutput } from "./lib/github-actions.js";
35
+ import { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from "./wrangler-config/patches.js";
36
+ import { provisionWranglerResources } from "./wrangler-config/resources.js";
37
37
  prepareConfigFile();
38
38
  ensureMinimumConfigVersion();
39
39
  applyTopLevelPatch();
@@ -1 +1 @@
1
- {"version":3,"file":"prepare-wrangler-config.js","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9H,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAEzE,iBAAiB,EAAE,CAAC;AACpB,0BAA0B,EAAE,CAAC;AAC7B,kBAAkB,EAAE,CAAC;AACrB,cAAc,EAAE,CAAC;AACjB,MAAM,OAAO,GAAG,0BAA0B,EAAE,CAAC;AAE7C,iFAAiF;AACjF,oFAAoF;AACpF,iFAAiF;AACjF,oEAAoE;AACpE,kFAAkF;AAClF,oDAAoD;AACpD,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACxC,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\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 */\nimport { setOutput } from './lib/github-actions';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches';\nimport { provisionWranglerResources } from './wrangler-config/resources';\n\nprepareConfigFile();\nensureMinimumConfigVersion();\napplyTopLevelPatch();\napplyVarsPatch();\nconst created = provisionWranglerResources();\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.\nsetOutput('created', created.join(','));\nconsole.log('Wrangler configuration is ready.');\n"]}
1
+ {"version":3,"file":"prepare-wrangler-config.js","sourceRoot":"","sources":["../../src/scripts/prepare-wrangler-config.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjI,OAAO,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAE5E,iBAAiB,EAAE,CAAC;AACpB,0BAA0B,EAAE,CAAC;AAC7B,kBAAkB,EAAE,CAAC;AACrB,cAAc,EAAE,CAAC;AACjB,MAAM,OAAO,GAAG,0BAA0B,EAAE,CAAC;AAE7C,iFAAiF;AACjF,oFAAoF;AACpF,iFAAiF;AACjF,oEAAoE;AACpE,kFAAkF;AAClF,oDAAoD;AACpD,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACxC,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env tsx\n/**\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 */\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { provisionWranglerResources } from './wrangler-config/resources.ts';\n\nprepareConfigFile();\nensureMinimumConfigVersion();\napplyTopLevelPatch();\napplyVarsPatch();\nconst created = provisionWranglerResources();\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.\nsetOutput('created', created.join(','));\nconsole.log('Wrangler configuration is ready.');\n"]}
@@ -31,7 +31,7 @@
31
31
  */
32
32
  import path from 'node:path';
33
33
  import { fileURLToPath } from 'node:url';
34
- import { verifySpaShell } from './spa-shell';
34
+ import { verifySpaShell } from "./spa-shell.js";
35
35
  /**
36
36
  * The repository root, derived from this file rather than from `process.cwd()`.
37
37
  *
@@ -1 +1 @@
1
- {"version":3,"file":"verify-spa-shell.js","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C;;;;;;;GAOG;AACH,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AAEzF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7F,MAAM,EAAE,QAAQ,EAAE,GAAG,cAAc,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;AAE9C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;IACxB,OAAO,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;IACzC,KAAK,MAAM,OAAO,IAAI,QAAQ;QAAE,OAAO,CAAC,KAAK,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;IAChE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,OAAO,CAAC,GAAG,CACT,2BAA2B,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qCAAqC,CAAC,YAAY,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,IAAI,CAClI,CAAC","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';\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"]}
1
+ {"version":3,"file":"verify-spa-shell.js","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD;;;;;;;GAOG;AACH,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;AAEzF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE7F,MAAM,EAAE,QAAQ,EAAE,GAAG,cAAc,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;AAE9C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;IACxB,OAAO,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;IACzC,KAAK,MAAM,OAAO,IAAI,QAAQ;QAAE,OAAO,CAAC,KAAK,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;IAChE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,OAAO,CAAC,GAAG,CACT,2BAA2B,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qCAAqC,CAAC,YAAY,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,IAAI,CAClI,CAAC","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"]}
@@ -9,7 +9,7 @@
9
9
  * file, which is a diff nobody can review and a reason to regenerate the config by
10
10
  * hand instead.
11
11
  */
12
- import { type WranglerConfig } from './types';
12
+ import { type WranglerConfig } from './types.ts';
13
13
  /** The config's current text and its parsed form. */
14
14
  export interface ConfigFile {
15
15
  content: string;
@@ -1 +1 @@
1
- {"version":3,"file":"patches.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAA8B,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAE1E,qDAAqD;AACrD,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,cAAc,CAAC;CACxB;AAED,wBAAgB,UAAU,IAAI,UAAU,CAGvC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,CAGtG;AAED,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAEjD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,IA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CAYzC;AAED,wBAAgB,cAAc,IAAI,IAAI,CAsBrC"}
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { copyFileSync, readFileSync, writeFileSync } from 'node:fs';
13
13
  import { applyEdits, modify, parse } from 'jsonc-parser';
14
- import { CONFIG_PATH, TEMPLATE_PATH } from './types';
14
+ import { CONFIG_PATH, TEMPLATE_PATH } from "./types.js";
15
15
  export function readConfig() {
16
16
  const content = readFileSync(CONFIG_PATH, 'utf8');
17
17
  return { content, config: parse(content) };
@@ -1 +1 @@
1
- {"version":3,"file":"patches.js","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAuB,MAAM,SAAS,CAAC;AAQ1E,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAClD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAmB,EAAE,CAAC;AAC/D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAE,IAA4B,EAAE,KAAc;IAC5F,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,iBAAiB,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IACjH,OAAO,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,aAAa,CAAC,WAAW,EAAE,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AAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,EAClH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iFAAiF,CAAC,CAAC;IACrG,CAAC;IACD,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QACxE,OAAO,GAAG,gBAAgB,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;IACpD,CAAC;IACD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;QACnC,OAAO,GAAG,gBAAgB,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC;IAC5D,CAAC;IACD,WAAW,CAAC,OAAO,CAAC,CAAC;IACrB,OAAO,CAAC,GAAG,CAAC,WAAW,OAAO,CAAC,MAAM,4BAA4B,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["/**\n * Reading, writing and patching `wrangler.jsonc`.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/patches.ts`.\n *\n * The config is JSONC — `//` comments and trailing commas — so it is edited\n * through jsonc-parser's `modify`/`applyEdits` rather than parsed and re-serialized.\n * A round trip through `JSON.parse` would drop every comment and reformat the\n * file, which is a diff nobody can review and a reason to regenerate the config by\n * hand instead.\n */\n\nimport { copyFileSync, readFileSync, writeFileSync } from 'node:fs';\nimport { applyEdits, modify, parse } from 'jsonc-parser';\nimport { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types';\n\n/** The config's current text and its parsed form. */\nexport interface ConfigFile {\n content: string;\n config: WranglerConfig;\n}\n\nexport function readConfig(): ConfigFile {\n const content = readFileSync(CONFIG_PATH, 'utf8');\n return { content, config: parse(content) as WranglerConfig };\n}\n\n/**\n * Apply one edit to the config text, preserving comments and formatting.\n */\nexport function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string {\n const edits = modify(content, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\\n' } });\n return applyEdits(content, edits);\n}\n\n/** Write the config, guaranteeing a trailing newline so Prettier sees a fixed point. */\nexport function writeConfig(content: string): void {\n writeFileSync(CONFIG_PATH, content.endsWith('\\n') ? content : `${content}\\n`);\n}\n\n/**\n * The top-level keys a caller wants to merge into the config, from the environment.\n *\n * `WRANGLER_PATCH_JSON` is how a repository variable supplies per-environment\n * settings without a second file: a repo with one worker and three environments\n * patches the routes and the vars rather than keeping three templates in step.\n */\nexport function parseTopLevelPatch(): Record<string, unknown> | undefined {\n return parseJsonObject(process.env['WRANGLER_PATCH_JSON'], 'WRANGLER_PATCH_JSON', 'a JSON object');\n}\n\n/** The `vars` entries a caller wants to merge, from the environment. */\nexport function parseVarsPatch(): Record<string, string> | undefined {\n const parsed = parseJsonObject(process.env['WRANGLER_VARS_PATCH_JSON'], 'WRANGLER_VARS_PATCH_JSON', 'a JSON object of string values');\n if (parsed === undefined) {\n return undefined;\n }\n const patch: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error('WRANGLER_VARS_PATCH_JSON contains an empty variable name.');\n }\n if (typeof value !== 'string') {\n throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${key} must be a string.`);\n }\n patch[key] = value;\n }\n return patch;\n}\n\nfunction parseJsonObject(raw: string | undefined, name: string, expected: string): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n throw new Error(`${name} must be ${expected}.`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${name} must be ${expected}.`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Materialize the config: the repository variable when it is set, otherwise the\n * committed template.\n */\nexport function prepareConfigFile(): void {\n const dumpedConfig = process.env['WRANGLER_JSONC'];\n if (dumpedConfig?.trim()) {\n writeConfig(dumpedConfig);\n console.log('Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.');\n return;\n }\n copyFileSync(TEMPLATE_PATH, CONFIG_PATH);\n console.log('WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.');\n}\n\n/**\n * Refuse a config older than the template requires.\n *\n * The template is the one file in the repo that says which wrangler behaviour the\n * worker was written against, and a config written by an older template can name\n * bindings the worker no longer reads. Failing here rather than at deploy time is\n * the whole reason the check exists.\n */\nexport function ensureMinimumConfigVersion(): void {\n const template = parse(readFileSync(TEMPLATE_PATH, 'utf8')) as { $minimumVersion?: unknown };\n if (typeof template.$minimumVersion !== 'number') {\n return;\n }\n const { config } = readConfig();\n const currentVersion = config.$version;\n if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {\n throw new Error(\n `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`,\n );\n }\n}\n\nexport function applyTopLevelPatch(): void {\n const patch = parseTopLevelPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n let { content } = readConfig();\n for (const [key, value] of entries) {\n content = writeConfigValue(content, [key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler top-level patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n\nexport function applyVarsPatch(): void {\n const patch = parseVarsPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n const prepared = readConfig();\n let content = prepared.content;\n if (\n prepared.config.vars !== undefined &&\n (prepared.config.vars === null || typeof prepared.config.vars !== 'object' || Array.isArray(prepared.config.vars))\n ) {\n throw new Error('wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.');\n }\n if (prepared.config.vars === undefined || prepared.config.vars === null) {\n content = writeConfigValue(content, ['vars'], {});\n }\n for (const [key, value] of entries) {\n content = writeConfigValue(content, ['vars', key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler vars patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n"]}
1
+ {"version":3,"file":"patches.js","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/patches.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAuB,MAAM,YAAY,CAAC;AAQ7E,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAClD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAmB,EAAE,CAAC;AAC/D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAE,IAA4B,EAAE,KAAc;IAC5F,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,iBAAiB,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IACjH,OAAO,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,aAAa,CAAC,WAAW,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,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IAAI,CAAC,CAAC,EAClH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,iFAAiF,CAAC,CAAC;IACrG,CAAC;IACD,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QACxE,OAAO,GAAG,gBAAgB,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;IACpD,CAAC;IACD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;QACnC,OAAO,GAAG,gBAAgB,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC;IAC5D,CAAC;IACD,WAAW,CAAC,OAAO,CAAC,CAAC;IACrB,OAAO,CAAC,GAAG,CAAC,WAAW,OAAO,CAAC,MAAM,4BAA4B,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC;AAC1G,CAAC","sourcesContent":["/**\n * Reading, writing and patching `wrangler.jsonc`.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/patches.ts`.\n *\n * The config is JSONC — `//` comments and trailing commas — so it is edited\n * through jsonc-parser's `modify`/`applyEdits` rather than parsed and re-serialized.\n * A round trip through `JSON.parse` would drop every comment and reformat the\n * file, which is a diff nobody can review and a reason to regenerate the config by\n * hand instead.\n */\n\nimport { copyFileSync, readFileSync, writeFileSync } from 'node:fs';\nimport { applyEdits, modify, parse } from 'jsonc-parser';\nimport { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';\n\n/** The config's current text and its parsed form. */\nexport interface ConfigFile {\n content: string;\n config: WranglerConfig;\n}\n\nexport function readConfig(): ConfigFile {\n const content = readFileSync(CONFIG_PATH, 'utf8');\n return { content, config: parse(content) as WranglerConfig };\n}\n\n/**\n * Apply one edit to the config text, preserving comments and formatting.\n */\nexport function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string {\n const edits = modify(content, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\\n' } });\n return applyEdits(content, edits);\n}\n\n/** Write the config, guaranteeing a trailing newline so Prettier sees a fixed point. */\nexport function writeConfig(content: string): void {\n writeFileSync(CONFIG_PATH, content.endsWith('\\n') ? content : `${content}\\n`);\n}\n\n/**\n * The top-level keys a caller wants to merge into the config, from the environment.\n *\n * `WRANGLER_PATCH_JSON` is how a repository variable supplies per-environment\n * settings without a second file: a repo with one worker and three environments\n * patches the routes and the vars rather than keeping three templates in step.\n */\nexport function parseTopLevelPatch(): Record<string, unknown> | undefined {\n return parseJsonObject(process.env['WRANGLER_PATCH_JSON'], 'WRANGLER_PATCH_JSON', 'a JSON object');\n}\n\n/** The `vars` entries a caller wants to merge, from the environment. */\nexport function parseVarsPatch(): Record<string, string> | undefined {\n const parsed = parseJsonObject(process.env['WRANGLER_VARS_PATCH_JSON'], 'WRANGLER_VARS_PATCH_JSON', 'a JSON object of string values');\n if (parsed === undefined) {\n return undefined;\n }\n const patch: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error('WRANGLER_VARS_PATCH_JSON contains an empty variable name.');\n }\n if (typeof value !== 'string') {\n throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${key} must be a string.`);\n }\n patch[key] = value;\n }\n return patch;\n}\n\nfunction parseJsonObject(raw: string | undefined, name: string, expected: string): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n throw new Error(`${name} must be ${expected}.`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${name} must be ${expected}.`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Materialize the config: the repository variable when it is set, otherwise the\n * committed template.\n */\nexport function prepareConfigFile(): void {\n const dumpedConfig = process.env['WRANGLER_JSONC'];\n if (dumpedConfig?.trim()) {\n writeConfig(dumpedConfig);\n console.log('Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.');\n return;\n }\n copyFileSync(TEMPLATE_PATH, CONFIG_PATH);\n console.log('WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.');\n}\n\n/**\n * Refuse a config older than the template requires.\n *\n * The template is the one file in the repo that says which wrangler behaviour the\n * worker was written against, and a config written by an older template can name\n * bindings the worker no longer reads. Failing here rather than at deploy time is\n * the whole reason the check exists.\n */\nexport function ensureMinimumConfigVersion(): void {\n const template = parse(readFileSync(TEMPLATE_PATH, 'utf8')) as { $minimumVersion?: unknown };\n if (typeof template.$minimumVersion !== 'number') {\n return;\n }\n const { config } = readConfig();\n const currentVersion = config.$version;\n if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {\n throw new Error(\n `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`,\n );\n }\n}\n\nexport function applyTopLevelPatch(): void {\n const patch = parseTopLevelPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n let { content } = readConfig();\n for (const [key, value] of entries) {\n content = writeConfigValue(content, [key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler top-level patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n\nexport function applyVarsPatch(): void {\n const patch = parseVarsPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n const prepared = readConfig();\n let content = prepared.content;\n if (\n prepared.config.vars !== undefined &&\n (prepared.config.vars === null || typeof prepared.config.vars !== 'object' || Array.isArray(prepared.config.vars))\n ) {\n throw new Error('wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.');\n }\n if (prepared.config.vars === undefined || prepared.config.vars === null) {\n content = writeConfigValue(content, ['vars'], {});\n }\n for (const [key, value] of entries) {\n content = writeConfigValue(content, ['vars', key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler vars patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n"]}
@@ -11,7 +11,7 @@
11
11
  * refused rather than skipped, because a silently skipped placeholder is a deploy
12
12
  * that fails later with no link back to the reason.
13
13
  */
14
- import { type D1Database, type KVNamespace, type SecretStore, type WranglerConfig } from './types';
14
+ import { type D1Database, type KVNamespace, type SecretStore, type WranglerConfig } from './types.ts';
15
15
  /** What `ensure*` did, so a caller can act on the difference. */
16
16
  export interface Provisioned {
17
17
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"resources.d.ts","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/resources.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,EAQL,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,cAAc,EACpB,MAAM,SAAS,CAAC;AAIjB,iEAAiE;AACjE,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,0EAA0E;AAC1E,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,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAkBtF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,WAAW,EAAE,CAEhD;AAED,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAElF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAkBtF;AAED,yFAAyF;AACzF,wBAAgB,qBAAqB,IAAI,MAAM,EAAE,CAEhD;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,MAAM,CAYxF;AAED,wDAAwD;AACxD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,EAAE,CAiBpE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAQhD;AAED,wBAAgB,iBAAiB,IAAI,MAAM,CAmB1C;AAED,gFAAgF;AAChF,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;AA+DD;;;;;;;;GAQG;AACH,wBAAgB,0BAA0B,IAAI,MAAM,EAAE,CAqCrD"}
@@ -12,10 +12,10 @@
12
12
  * that fails later with no link back to the reason.
13
13
  */
14
14
  import { parse } from 'jsonc-parser';
15
- import { parseWranglerTableRows } from '../lib/wrangler-table';
16
- import { DEFAULT_HEX_ID, DEFAULT_KV_NAMESPACE_NAMES, DEFAULT_SECRET_STORE_NAME, DEFAULT_UUID, DEFAULT_WORKER_NAME, VECTORIZE_DIMENSIONS, } from './types';
17
- import { parseJsonArray, runWrangler } from './cli';
18
- import { readConfig, writeConfig, writeConfigValue } from './patches';
15
+ import { parseWranglerTableRows } from "../lib/wrangler-table.js";
16
+ import { DEFAULT_HEX_ID, DEFAULT_KV_NAMESPACE_NAMES, DEFAULT_SECRET_STORE_NAME, DEFAULT_UUID, DEFAULT_WORKER_NAME, VECTORIZE_DIMENSIONS, } from "./types.js";
17
+ import { parseJsonArray, runWrangler } from "./cli.js";
18
+ import { readConfig, writeConfig, writeConfigValue } from "./patches.js";
19
19
  /** The id a D1 database is reported under, whichever key the CLI used. */
20
20
  export function getD1Id(database) {
21
21
  return database.uuid ?? database.database_id ?? database.id;