@rexezuge/tooling 1.2.0 → 1.4.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 (153) hide show
  1. package/README.md +66 -10
  2. package/dist/eslint-boundaries.d.ts +31 -7
  3. package/dist/eslint-boundaries.d.ts.map +1 -1
  4. package/dist/eslint-boundaries.js +1 -138
  5. package/dist/eslint-boundaries.js.map +7 -1
  6. package/dist/eslint-rules.js +1 -273
  7. package/dist/eslint-rules.js.map +7 -1
  8. package/dist/eslint.d.ts +12 -7
  9. package/dist/eslint.d.ts.map +1 -1
  10. package/dist/eslint.js +1 -189
  11. package/dist/eslint.js.map +7 -1
  12. package/dist/functions/pages-proxy.d.ts.map +1 -1
  13. package/dist/functions/pages-proxy.js +1 -131
  14. package/dist/functions/pages-proxy.js.map +7 -1
  15. package/dist/index.d.ts +20 -14
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -28
  18. package/dist/index.js.map +7 -1
  19. package/dist/scripts/backup/d1-target.d.ts +15 -5
  20. package/dist/scripts/backup/d1-target.d.ts.map +1 -1
  21. package/dist/scripts/backup/d1-target.js +1 -31
  22. package/dist/scripts/backup/d1-target.js.map +7 -1
  23. package/dist/scripts/backup/destination-config.d.ts +24 -8
  24. package/dist/scripts/backup/destination-config.d.ts.map +1 -1
  25. package/dist/scripts/backup/destination-config.js +1 -57
  26. package/dist/scripts/backup/destination-config.js.map +7 -1
  27. package/dist/scripts/backup/encrypt-backup.js +2 -97
  28. package/dist/scripts/backup/encrypt-backup.js.map +7 -1
  29. package/dist/scripts/backup/naming.d.ts +3 -1
  30. package/dist/scripts/backup/naming.d.ts.map +1 -1
  31. package/dist/scripts/backup/naming.js +1 -58
  32. package/dist/scripts/backup/naming.js.map +7 -1
  33. package/dist/scripts/check-god-files.d.ts +40 -14
  34. package/dist/scripts/check-god-files.d.ts.map +1 -1
  35. package/dist/scripts/check-god-files.js +2 -271
  36. package/dist/scripts/check-god-files.js.map +7 -1
  37. package/dist/scripts/ensure-spa-shell-stub.js +1 -29
  38. package/dist/scripts/ensure-spa-shell-stub.js.map +7 -1
  39. package/dist/scripts/init-secrets.d.ts +0 -16
  40. package/dist/scripts/init-secrets.d.ts.map +1 -1
  41. package/dist/scripts/init-secrets.js +2 -239
  42. package/dist/scripts/init-secrets.js.map +7 -1
  43. package/dist/scripts/lib/cli-args.d.ts.map +1 -1
  44. package/dist/scripts/lib/cli-args.js +1 -116
  45. package/dist/scripts/lib/cli-args.js.map +7 -1
  46. package/dist/scripts/lib/github-actions.js +3 -38
  47. package/dist/scripts/lib/github-actions.js.map +7 -1
  48. package/dist/scripts/lib/wrangler-table.d.ts.map +1 -1
  49. package/dist/scripts/lib/wrangler-table.js +2 -99
  50. package/dist/scripts/lib/wrangler-table.js.map +7 -1
  51. package/dist/scripts/migrations-lock.js +1 -44
  52. package/dist/scripts/migrations-lock.js.map +7 -1
  53. package/dist/scripts/prepare-wrangler-config.js +1 -49
  54. package/dist/scripts/prepare-wrangler-config.js.map +7 -1
  55. package/dist/scripts/spa-shell.d.ts +12 -4
  56. package/dist/scripts/spa-shell.d.ts.map +1 -1
  57. package/dist/scripts/spa-shell.js +3 -160
  58. package/dist/scripts/spa-shell.js.map +7 -1
  59. package/dist/scripts/validate-locales.d.ts +13 -5
  60. package/dist/scripts/validate-locales.d.ts.map +1 -1
  61. package/dist/scripts/validate-locales.js +4 -350
  62. package/dist/scripts/validate-locales.js.map +7 -1
  63. package/dist/scripts/verify-migrations.d.ts +27 -9
  64. package/dist/scripts/verify-migrations.d.ts.map +1 -1
  65. package/dist/scripts/verify-migrations.js +2 -312
  66. package/dist/scripts/verify-migrations.js.map +7 -1
  67. package/dist/scripts/verify-spa-shell.js +1 -52
  68. package/dist/scripts/verify-spa-shell.js.map +7 -1
  69. package/dist/scripts/wrangler-config/cli.js +3 -51
  70. package/dist/scripts/wrangler-config/cli.js.map +7 -1
  71. package/dist/scripts/wrangler-config/patches.d.ts +10 -4
  72. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  73. package/dist/scripts/wrangler-config/patches.js +4 -141
  74. package/dist/scripts/wrangler-config/patches.js.map +7 -1
  75. package/dist/scripts/wrangler-config/resources.d.ts +19 -7
  76. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  77. package/dist/scripts/wrangler-config/resources.js +1 -290
  78. package/dist/scripts/wrangler-config/resources.js.map +7 -1
  79. package/dist/scripts/wrangler-config/types.d.ts +24 -8
  80. package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
  81. package/dist/scripts/wrangler-config/types.js +1 -49
  82. package/dist/scripts/wrangler-config/types.js.map +7 -1
  83. package/dist/test/integration-migrations.d.ts +29 -12
  84. package/dist/test/integration-migrations.d.ts.map +1 -1
  85. package/dist/test/integration-migrations.js +2 -171
  86. package/dist/test/integration-migrations.js.map +7 -1
  87. package/dist/test/mocks/cloudflare-workers.js +1 -90
  88. package/dist/test/mocks/cloudflare-workers.js.map +7 -1
  89. package/dist/vite.d.ts +5 -3
  90. package/dist/vite.d.ts.map +1 -1
  91. package/dist/vite.js +3 -125
  92. package/dist/vite.js.map +7 -1
  93. package/dist/vitest-aliases.d.ts +90 -0
  94. package/dist/vitest-aliases.d.ts.map +1 -0
  95. package/dist/vitest-aliases.js +1 -0
  96. package/dist/vitest-aliases.js.map +7 -0
  97. package/dist/vitest-integration.d.ts +96 -0
  98. package/dist/vitest-integration.d.ts.map +1 -0
  99. package/dist/vitest-integration.js +1 -0
  100. package/dist/vitest-integration.js.map +7 -0
  101. package/dist/vitest-repo.d.ts +154 -0
  102. package/dist/vitest-repo.d.ts.map +1 -0
  103. package/dist/vitest-repo.js +1 -0
  104. package/dist/vitest-repo.js.map +7 -0
  105. package/dist/vitest-web.d.ts +76 -19
  106. package/dist/vitest-web.d.ts.map +1 -1
  107. package/dist/vitest-web.js +1 -72
  108. package/dist/vitest-web.js.map +7 -1
  109. package/dist/vitest.d.ts +70 -19
  110. package/dist/vitest.d.ts.map +1 -1
  111. package/dist/vitest.js +1 -128
  112. package/dist/vitest.js.map +7 -1
  113. package/package.json +9 -3
  114. package/src/eslint-boundaries.ts +112 -11
  115. package/src/eslint.test.ts +40 -9
  116. package/src/eslint.ts +14 -9
  117. package/src/functions/pages-proxy.test.ts +3 -3
  118. package/src/functions/pages-proxy.ts +4 -2
  119. package/src/index.ts +23 -14
  120. package/src/scripts/backup/backup-rules.test.ts +4 -4
  121. package/src/scripts/backup/d1-target.ts +16 -6
  122. package/src/scripts/backup/destination-config.ts +27 -9
  123. package/src/scripts/backup/encrypt-backup.ts +12 -10
  124. package/src/scripts/backup/naming.ts +3 -1
  125. package/src/scripts/check-god-files.test.ts +19 -19
  126. package/src/scripts/check-god-files.ts +62 -33
  127. package/src/scripts/ensure-spa-shell-stub.ts +1 -1
  128. package/src/scripts/init-secrets.ts +20 -10
  129. package/src/scripts/lib/cli-args.ts +6 -3
  130. package/src/scripts/lib/wrangler-table.ts +5 -3
  131. package/src/scripts/migrations-lock.ts +2 -2
  132. package/src/scripts/prepare-wrangler-config.ts +3 -3
  133. package/src/scripts/spa-shell.test.ts +18 -18
  134. package/src/scripts/spa-shell.ts +26 -14
  135. package/src/scripts/validate-locales.test.ts +18 -18
  136. package/src/scripts/validate-locales.ts +43 -25
  137. package/src/scripts/verify-migrations.test.ts +8 -8
  138. package/src/scripts/verify-migrations.ts +47 -24
  139. package/src/scripts/verify-spa-shell.ts +1 -1
  140. package/src/scripts/wrangler-config/patches.ts +13 -5
  141. package/src/scripts/wrangler-config/resources.ts +34 -18
  142. package/src/scripts/wrangler-config/types.ts +24 -8
  143. package/src/test/integration-migrations.test.ts +7 -7
  144. package/src/test/integration-migrations.ts +33 -14
  145. package/src/vite.test.ts +25 -14
  146. package/src/vite.ts +5 -5
  147. package/src/vitest-aliases.test.ts +53 -0
  148. package/src/vitest-aliases.ts +125 -0
  149. package/src/vitest-factories.test.ts +127 -0
  150. package/src/vitest-integration.ts +118 -0
  151. package/src/vitest-repo.ts +269 -0
  152. package/src/vitest-web.ts +110 -28
  153. package/src/vitest.ts +96 -47
@@ -1,312 +1,2 @@
1
- /**
2
- * Verify the migration set is complete, ordered, and locked; write the lock.
3
- *
4
- * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`
5
- * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,
6
- * converged. Every copy checks the same properties of a `migrations/` directory;
7
- * they differ in lock-file naming, in whether the lock is enforced on CI, and in
8
- * how much of D1's ordering semantics they encode.
9
- *
10
- * ### Why a checksum lock at all
11
- *
12
- * D1 records *which* migrations it has applied — the filename and a timestamp —
13
- * but not *what the file contained* when it applied them. So editing a migration
14
- * that has already run is not caught by anything: the deploy still succeeds, the
15
- * local database built from the baseline plus the edited file picks up the new
16
- * statements, and production keeps the schema it had. The two databases then
17
- * differ silently and permanently, and the next migration that assumes the newer
18
- * shape fails only in production. A committed digest per file turns that into a
19
- * CI failure.
20
- *
21
- * ### What the checks are, and where each comes from
22
- *
23
- * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by
24
- * filename, so a file that sorts *after* the ones already applied is the only
25
- * kind that can be introduced safely.
26
- * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and
27
- * 0003 while another applied only 0001, and nothing downstream can tell which.
28
- * Checked **only when no squash baseline exists**: a squash legitimately
29
- * absorbs its predecessors, so numbering restarts wherever it starts, and a
30
- * contiguity rule that fires on a squash is a rule that blocks the squash.
31
- * - **One entry per file** (all) — a file with no recorded digest is one nothing
32
- * can say anything about.
33
- * - **Digest unchanged** (all) — the edited-after-locking failure.
34
- * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been
35
- * applied to a live database and is no longer reproducible from this repo.
36
- * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file
37
- * sorting *before* the newest locked one can never reach a database that has
38
- * applied that newest one, so its statements would only run on a fresh build.
39
- * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a
40
- * style problem: D1 orders them by the rest of the filename, so which one lands
41
- * on a given database depends on a lexicographic tiebreak nobody intended.
42
- *
43
- * ### The squash baseline
44
- *
45
- * `0008_squash.sql` holds the combined schema of every migration before it, and
46
- * those files are deleted when it is created. A later squash repeats that. So a
47
- * squash legitimately (a) rewrites one file and (b) removes files the lock still
48
- * lists, and neither may be reported as drift. The baseline is the
49
- * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims
50
- * — deriving it means a stale or forged `baseline` cannot widen the exempt set.
51
- *
52
- * ### The one write path
53
- *
54
- * `--write` is add-only where it counts: it records unlocked files, refreshes the
55
- * baseline's own entry, and drops entries the baseline absorbed. Every other
56
- * entry is left exactly as it is, so an incremental `edited` finding **survives a
57
- * `--write`** — re-baselining one means deleting its entry by hand, which shows
58
- * up in the diff. There is deliberately no `--force`, because a write that could
59
- * bless a drift would be the operator blessing their own edit.
60
- */
61
- import { createHash } from 'node:crypto';
62
- import { pathToFileURL } from 'node:url';
63
- import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
64
- import { join } from 'node:path';
65
- /**
66
- * The lock's filename, beside the `.sql` files.
67
- *
68
- * Named `migrations.lock.json` rather than `migrations.json` so it cannot be
69
- * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like
70
- * one would be a deploy-time mystery.
71
- */
72
- const LOCK_NAME = 'migrations.lock.json';
73
- /** The filename shape every migration must have. `NNNN_` is fixed at four digits. */
74
- const NAME_PATTERN = /^(\d{4})_[a-z0-9_]+\.sql$/;
75
- /** The squashed-baseline shape. The highest-numbered match is the baseline. */
76
- const SQUASH_PATTERN = /^\d{4}_squash\.sql$/;
77
- /** The lock's format version. Bumped only on an incompatible shape change. */
78
- const LOCK_VERSION = 1;
79
- function sha256Hex(content) {
80
- return createHash('sha256').update(content, 'utf8').digest('hex');
81
- }
82
- /**
83
- * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo
84
- * has not squashed — in which case every migration is incremental and therefore
85
- * every one of them is immutable.
86
- */
87
- export function baselineOf(files) {
88
- let highest;
89
- for (const name of files) {
90
- if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {
91
- highest = name;
92
- }
93
- }
94
- return highest;
95
- }
96
- /** True when `name` is at or before the baseline, i.e. the set a squash absorbs. */
97
- function isSubsumed(name, baseline) {
98
- return baseline !== undefined && name <= baseline;
99
- }
100
- /**
101
- * Read the migration set and validate its shape without consulting the lock.
102
- *
103
- * The lock is read here too, so one walk answers both "what is on disk" and "what
104
- * is recorded"; a lock that is merely *absent* is reported by `verifyMigrations`
105
- * rather than here, because that is the bootstrap case rather than a defect.
106
- */
107
- function inspectMigrations(migrationsDir) {
108
- const problems = [];
109
- if (!existsSync(migrationsDir)) {
110
- problems.push({ problem: `${migrationsDir} does not exist` });
111
- return { files: [], problems, lock: null };
112
- }
113
- // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the
114
- // lock describes exactly the set wrangler will run. `migrations.lock.json` is
115
- // not one of them, because it is not a `.sql` file.
116
- const files = readdirSync(migrationsDir)
117
- .filter((name) => name.endsWith('.sql'))
118
- .sort((left, right) => left.localeCompare(right));
119
- for (const name of files) {
120
- if (!NAME_PATTERN.test(name)) {
121
- problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });
122
- }
123
- }
124
- const baseline = baselineOf(files);
125
- const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);
126
- // Strictly increasing: the property D1 actually depends on. A duplicate or a
127
- // descending prefix means two files compete for the same slot in the apply
128
- // order, and which one wins is a lexicographic tiebreak nobody intended.
129
- for (let index = 1; index < prefixes.length; index += 1) {
130
- const previous = prefixes[index - 1];
131
- const current = prefixes[index];
132
- if (previous !== undefined && current !== undefined && current <= previous) {
133
- problems.push({
134
- problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,
135
- });
136
- }
137
- }
138
- // Contiguity is checked only with no squash on disk: a squash deletes the files
139
- // it absorbs, so numbering restarts wherever it starts and a hole is the
140
- // expected shape rather than a defect.
141
- if (baseline === undefined) {
142
- for (let index = 0; index < prefixes.length; index += 1) {
143
- const expected = String(index + 1).padStart(4, '0');
144
- if (prefixes[index] !== expected) {
145
- problems.push({
146
- problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,
147
- });
148
- }
149
- }
150
- }
151
- const lockPath = join(migrationsDir, LOCK_NAME);
152
- let lock = null;
153
- if (existsSync(lockPath)) {
154
- try {
155
- lock = JSON.parse(readFileSync(lockPath, 'utf8'));
156
- }
157
- catch {
158
- problems.push({ problem: `${LOCK_NAME} is not valid JSON` });
159
- }
160
- }
161
- return { files, problems, lock };
162
- }
163
- /**
164
- * The lock as `--write` would leave it.
165
- *
166
- * `null` when the existing lock cannot be trusted as a base, which is exactly
167
- * when a `--write` must refuse rather than overwrite contents it failed to
168
- * understand. A lock that is merely *absent* is not malformed: that is the
169
- * bootstrap case, and it is built from disk like any other.
170
- */
171
- function buildUpdatedLock(migrationsDir, files, existing, baseline) {
172
- const digestOf = (name) => sha256Hex(readFileSync(join(migrationsDir, name), 'utf8'));
173
- if (existing === null) {
174
- return {
175
- version: LOCK_VERSION,
176
- ...(baseline !== undefined && { baseline }),
177
- migrations: files.map((name) => ({ name, sha256: digestOf(name) })),
178
- };
179
- }
180
- const kept = new Map();
181
- for (const file of files) {
182
- const recorded = existing.migrations.find((entry) => entry.name === file);
183
- if (recorded === undefined)
184
- continue;
185
- // The baseline is the one file a squash is allowed to rewrite.
186
- kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);
187
- }
188
- // Unlocked files are added — that is the new-migration case. Every other entry
189
- // is carried across untouched, so an `edited` finding survives the write.
190
- for (const file of files) {
191
- if (!kept.has(file) && !existing.migrations.some((entry) => entry.name === file)) {
192
- kept.set(file, digestOf(file));
193
- }
194
- }
195
- // Entries the baseline absorbed are dropped: committing a squash looks exactly
196
- // like this, and neither it nor a rewritten baseline can hide a divergence,
197
- // because a database that applied those files already has them recorded in D1's
198
- // own `d1_migrations`.
199
- for (const entry of existing.migrations) {
200
- if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {
201
- kept.set(entry.name, entry.sha256);
202
- }
203
- }
204
- return {
205
- version: LOCK_VERSION,
206
- ...(baseline !== undefined && { baseline }),
207
- migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),
208
- };
209
- }
210
- /** Verify (or with `write: true`, record) the lock against the files. */
211
- function verifyMigrations(migrationsDir, options = {}) {
212
- const report = inspectMigrations(migrationsDir);
213
- const baseline = baselineOf(report.files);
214
- // A malformed lock is a finding in its own right, and a `--write` must not
215
- // overwrite contents it failed to understand.
216
- if (report.problems.length > 0) {
217
- return report;
218
- }
219
- if (options.write === true) {
220
- const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);
221
- const next = `${JSON.stringify(updated, null, 2)}\n`;
222
- const path = join(migrationsDir, LOCK_NAME);
223
- let before = null;
224
- try {
225
- before = readFileSync(path, 'utf8');
226
- }
227
- catch (error) {
228
- if (error?.code !== 'ENOENT') {
229
- throw error;
230
- }
231
- }
232
- if (before !== next) {
233
- writeFileSync(path, next, 'utf8');
234
- }
235
- report.lock = updated;
236
- return report;
237
- }
238
- const lock = report.lock;
239
- if (lock === null) {
240
- report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });
241
- return report;
242
- }
243
- const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));
244
- for (const name of report.files) {
245
- const expected = recorded.get(name);
246
- if (expected === undefined) {
247
- report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });
248
- continue;
249
- }
250
- // At or before the baseline, a squash rewrites its own file, and that is the
251
- // whole reason a baseline exists.
252
- if (isSubsumed(name, baseline))
253
- continue;
254
- const actual = sha256Hex(readFileSync(join(migrationsDir, name), 'utf8'));
255
- if (actual !== expected) {
256
- report.problems.push({
257
- problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,
258
- });
259
- }
260
- }
261
- for (const entry of lock.migrations) {
262
- if (report.files.includes(entry.name))
263
- continue;
264
- if (isSubsumed(entry.name, baseline))
265
- continue;
266
- report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });
267
- }
268
- // A file sorting before the newest locked one can never reach a database that
269
- // has already applied that newest one, so its statements would only run on a
270
- // fresh build — the same silent split the checksum exists to prevent.
271
- const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);
272
- if (newest !== undefined) {
273
- for (const name of report.files) {
274
- if (name < newest && !recorded.has(name)) {
275
- report.problems.push({
276
- problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,
277
- });
278
- }
279
- }
280
- }
281
- return report;
282
- }
283
- /** CLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`. */
284
- function verifyMigrationsCli(argv = process.argv.slice(2)) {
285
- const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';
286
- const write = argv.includes('--write');
287
- const report = verifyMigrations(dir, { write });
288
- if (report.problems.length > 0) {
289
- console.error(`Migration validation failed for ${dir}:`);
290
- for (const problem of report.problems)
291
- console.error(` - ${problem.problem}`);
292
- return 1;
293
- }
294
- if (write) {
295
- console.log(`Migration lock written (${report.files.length} files).`);
296
- return 0;
297
- }
298
- console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);
299
- return 0;
300
- }
301
- export { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };
302
- // Run only when this file is the entrypoint.
303
- //
304
- // The rules above are pure and the tests import them directly, so a module-level
305
- // call would shell out (and exit) during a test run. The URL comparison rather than
306
- // an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
307
- // it is what keeps the rule modules importable — which is the whole reason they are
308
- // separate modules in the first place.
309
- if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
310
- process.exit(verifyMigrationsCli(process.argv.slice(2)));
311
- }
312
- //# sourceMappingURL=verify-migrations.js.map
1
+ import{createHash as S}from"node:crypto";import{pathToFileURL as w}from"node:url";import{existsSync as b,readFileSync as u,readdirSync as M,writeFileSync as _}from"node:fs";import p from"node:path";const a="migrations.lock.json",$=/^(\d{4})_[a-z0-9_]+\.sql$/,O=/^\d{4}_squash\.sql$/,d=1;function k(r){return S("sha256").update(r,"utf8").digest("hex")}function x(r){let t;for(const o of r)O.test(o)&&(t===void 0||o>t)&&(t=o);return t}function m(r,t){return t!==void 0&&r<=t}function y(r){const t=[];if(!b(r))return t.push({problem:`${r} does not exist`}),{files:[],problems:t,lock:null};const o=M(r).filter(e=>e.endsWith(".sql")).sort((e,i)=>e.localeCompare(i));for(const e of o)$.test(e)||t.push({problem:`${e} does not match NNNN_snake_case.sql`});const s=x(o),c=o.map(e=>$.exec(e)?.[1]);for(let e=1;e<c.length;e+=1){const i=c[e-1],f=c[e];i!==void 0&&f!==void 0&&f<=i&&t.push({problem:`${o[e]??"?"} sorts at or before ${o[e-1]??"?"} \u2014 D1 applies in filename order, so one of the two can never run`})}if(s===void 0)for(const[e,i]of c.entries()){const f=String(e+1).padStart(4,"0");i!==f&&t.push({problem:`migration numbering is not contiguous: expected ${f}_*.sql, found ${o[e]??"?"}`})}const l=p.join(r,a);let n=null;if(b(l))try{n=JSON.parse(u(l,"utf8"))}catch{t.push({problem:`${a} is not valid JSON`})}return{files:o,problems:t,lock:n}}function E(r,t,o,s){const c=n=>k(u(p.join(r,n),"utf8"));if(o===null)return{version:d,...s!==void 0&&{baseline:s},migrations:t.map(n=>({name:n,sha256:c(n)}))};const l=new Map;for(const n of t){const e=o.migrations.find(i=>i.name===n);e!==void 0&&l.set(n,n===s?c(n):e.sha256)}for(const n of t)!l.has(n)&&o.migrations.every(e=>e.name!==n)&&l.set(n,c(n));for(const n of o.migrations)!t.includes(n.name)&&!m(n.name,s)&&l.set(n.name,n.sha256);return{version:d,...s!==void 0&&{baseline:s},migrations:[...l].sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>({name:n,sha256:e}))}}function v(r,t={}){const o=y(r),s=x(o.files);if(o.problems.length>0)return o;if(t.write===!0){const e=E(r,o.files,o.lock,s),i=`${JSON.stringify(e,null,2)}
2
+ `,f=p.join(r,a);let h=null;try{h=u(f,"utf8")}catch(g){if(g?.code!=="ENOENT")throw g}return h!==i&&_(f,i,"utf8"),o.lock=e,o}const c=o.lock;if(c===null)return o.problems.push({problem:`${a} is missing \u2014 run migrations:lock`}),o;const l=new Map(c.migrations.map(e=>[e.name,e.sha256]));for(const e of o.files){const i=l.get(e);if(i===void 0){o.problems.push({problem:`${e} has no lock entry \u2014 run migrations:lock`});continue}if(m(e,s))continue;const f=k(u(p.join(r,e),"utf8"));f!==i&&o.problems.push({problem:`${e} changed after locking (expected ${i.slice(0,12)}\u2026, got ${f.slice(0,12)}\u2026)`})}for(const e of c.migrations)o.files.includes(e.name)||m(e.name,s)||o.problems.push({problem:`${e.name} is in the lock but no longer exists`});const n=[...l.keys()].sort((e,i)=>e.localeCompare(i)).at(-1);if(n!==void 0)for(const e of o.files)e<n&&!l.has(e)&&o.problems.push({problem:`${e} sorts before ${n}, which is already locked \u2014 D1 applies in filename order, so it would never run on a database that has applied ${n}`});return o}function N(r=process.argv.slice(2)){const t=r.find(c=>!c.startsWith("--"))??"migrations",o=r.includes("--write"),s=v(t,{write:o});if(s.problems.length>0){console.error(`Migration validation failed for ${t}:`);for(const c of s.problems)console.error(` - ${c.problem}`);return 1}return o?(console.log(`Migration lock written (${s.files.length} files).`),0):(console.log(`Migration validation passed (${s.files.length} files, lock in sync).`),0)}process.argv[1]!==void 0&&import.meta.url===w(process.argv[1]).href&&process.exit(N(process.argv.slice(2)));export{a as LOCK_NAME,d as LOCK_VERSION,x as baselineOf,y as inspectMigrations,v as verifyMigrations,N as verifyMigrationsCli};
@@ -1 +1,7 @@
1
- {"version":3,"file":"verify-migrations.js","sourceRoot":"","sources":["../../src/scripts/verify-migrations.ts"],"names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CAAC,KAAK,CAAC,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;QAC/E,OAAO,CAAC,CAAC;IACX,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACV,OAAO,CAAC,GAAG,CAAC,2BAA2B,MAAM,CAAC,KAAK,CAAC,MAAM,UAAU,CAAC,CAAC;QACtE,OAAO,CAAC,CAAC;IACX,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gCAAgC,MAAM,CAAC,KAAK,CAAC,MAAM,wBAAwB,CAAC,CAAC;IACzF,OAAO,CAAC,CAAC;AACX,CAAC;AAED,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC;AAG7F,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,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["/**\n * Verify the migration set is complete, ordered, and locked; write the lock.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`\n * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,\n * converged. Every copy checks the same properties of a `migrations/` directory;\n * they differ in lock-file naming, in whether the lock is enforced on CI, and in\n * how much of D1's ordering semantics they encode.\n *\n * ### Why a checksum lock at all\n *\n * D1 records *which* migrations it has applied — the filename and a timestamp —\n * but not *what the file contained* when it applied them. So editing a migration\n * that has already run is not caught by anything: the deploy still succeeds, the\n * local database built from the baseline plus the edited file picks up the new\n * statements, and production keeps the schema it had. The two databases then\n * differ silently and permanently, and the next migration that assumes the newer\n * shape fails only in production. A committed digest per file turns that into a\n * CI failure.\n *\n * ### What the checks are, and where each comes from\n *\n * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by\n * filename, so a file that sorts *after* the ones already applied is the only\n * kind that can be introduced safely.\n * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and\n * 0003 while another applied only 0001, and nothing downstream can tell which.\n * Checked **only when no squash baseline exists**: a squash legitimately\n * absorbs its predecessors, so numbering restarts wherever it starts, and a\n * contiguity rule that fires on a squash is a rule that blocks the squash.\n * - **One entry per file** (all) — a file with no recorded digest is one nothing\n * can say anything about.\n * - **Digest unchanged** (all) — the edited-after-locking failure.\n * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been\n * applied to a live database and is no longer reproducible from this repo.\n * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file\n * sorting *before* the newest locked one can never reach a database that has\n * applied that newest one, so its statements would only run on a fresh build.\n * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a\n * style problem: D1 orders them by the rest of the filename, so which one lands\n * on a given database depends on a lexicographic tiebreak nobody intended.\n *\n * ### The squash baseline\n *\n * `0008_squash.sql` holds the combined schema of every migration before it, and\n * those files are deleted when it is created. A later squash repeats that. So a\n * squash legitimately (a) rewrites one file and (b) removes files the lock still\n * lists, and neither may be reported as drift. The baseline is the\n * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims\n * — deriving it means a stale or forged `baseline` cannot widen the exempt set.\n *\n * ### The one write path\n *\n * `--write` is add-only where it counts: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. Every other\n * entry is left exactly as it is, so an incremental `edited` finding **survives a\n * `--write`** — re-baselining one means deleting its entry by hand, which shows\n * up in the diff. There is deliberately no `--force`, because a write that could\n * bless a drift would be the operator blessing their own edit.\n */\nimport { createHash } from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** One migration as the lock records it. */\ninterface MigrationEntry {\n name: string;\n sha256: string;\n}\n\n/** The parsed `migrations/migrations.lock.json`. */\ninterface MigrationLockFile {\n version: 1;\n /**\n * The squashed-baseline filename, when the repo has squashed.\n *\n * Everything at or before it is exempt from the `edited` and `orphan` checks,\n * because that is exactly the set a squash rewrites or absorbs.\n */\n baseline?: string;\n migrations: MigrationEntry[];\n}\n\n/** One failure, phrased for the operator. */\ninterface MigrationProblem {\n problem: string;\n}\n\n/** The outcome of one run. */\ninterface MigrationReport {\n /** Migration filenames, in apply order. */\n files: string[];\n problems: MigrationProblem[];\n /** The lock as it reads after the run. */\n lock: MigrationLockFile | null;\n}\n\n/**\n * The lock's filename, beside the `.sql` files.\n *\n * Named `migrations.lock.json` rather than `migrations.json` so it cannot be\n * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like\n * one would be a deploy-time mystery.\n */\nconst LOCK_NAME = 'migrations.lock.json';\n\n/** The filename shape every migration must have. `NNNN_` is fixed at four digits. */\nconst NAME_PATTERN = /^(\\d{4})_[a-z0-9_]+\\.sql$/;\n\n/** The squashed-baseline shape. The highest-numbered match is the baseline. */\nconst SQUASH_PATTERN = /^\\d{4}_squash\\.sql$/;\n\n/** The lock's format version. Bumped only on an incompatible shape change. */\nconst LOCK_VERSION = 1;\n\nfunction sha256Hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo\n * has not squashed — in which case every migration is incremental and therefore\n * every one of them is immutable.\n */\nexport function baselineOf(files: readonly string[]): string | undefined {\n let highest: string | undefined;\n for (const name of files) {\n if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {\n highest = name;\n }\n }\n return highest;\n}\n\n/** True when `name` is at or before the baseline, i.e. the set a squash absorbs. */\nfunction isSubsumed(name: string, baseline: string | undefined): boolean {\n return baseline !== undefined && name <= baseline;\n}\n\n/**\n * Read the migration set and validate its shape without consulting the lock.\n *\n * The lock is read here too, so one walk answers both \"what is on disk\" and \"what\n * is recorded\"; a lock that is merely *absent* is reported by `verifyMigrations`\n * rather than here, because that is the bootstrap case rather than a defect.\n */\nfunction inspectMigrations(migrationsDir: string): MigrationReport {\n const problems: MigrationProblem[] = [];\n if (!existsSync(migrationsDir)) {\n problems.push({ problem: `${migrationsDir} does not exist` });\n return { files: [], problems, lock: null };\n }\n\n // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the\n // lock describes exactly the set wrangler will run. `migrations.lock.json` is\n // not one of them, because it is not a `.sql` file.\n const files = readdirSync(migrationsDir)\n .filter((name) => name.endsWith('.sql'))\n .sort((left, right) => left.localeCompare(right));\n\n for (const name of files) {\n if (!NAME_PATTERN.test(name)) {\n problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });\n }\n }\n\n const baseline = baselineOf(files);\n const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);\n\n // Strictly increasing: the property D1 actually depends on. A duplicate or a\n // descending prefix means two files compete for the same slot in the apply\n // order, and which one wins is a lexicographic tiebreak nobody intended.\n for (let index = 1; index < prefixes.length; index += 1) {\n const previous = prefixes[index - 1];\n const current = prefixes[index];\n if (previous !== undefined && current !== undefined && current <= previous) {\n problems.push({\n problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,\n });\n }\n }\n\n // Contiguity is checked only with no squash on disk: a squash deletes the files\n // it absorbs, so numbering restarts wherever it starts and a hole is the\n // expected shape rather than a defect.\n if (baseline === undefined) {\n for (let index = 0; index < prefixes.length; index += 1) {\n const expected = String(index + 1).padStart(4, '0');\n if (prefixes[index] !== expected) {\n problems.push({\n problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,\n });\n }\n }\n }\n\n const lockPath = join(migrationsDir, LOCK_NAME);\n let lock: MigrationLockFile | null = null;\n if (existsSync(lockPath)) {\n try {\n lock = JSON.parse(readFileSync(lockPath, 'utf8')) as MigrationLockFile;\n } catch {\n problems.push({ problem: `${LOCK_NAME} is not valid JSON` });\n }\n }\n\n return { files, problems, lock };\n}\n\n/**\n * The lock as `--write` would leave it.\n *\n * `null` when the existing lock cannot be trusted as a base, which is exactly\n * when a `--write` must refuse rather than overwrite contents it failed to\n * understand. A lock that is merely *absent* is not malformed: that is the\n * bootstrap case, and it is built from disk like any other.\n */\nfunction buildUpdatedLock(\n migrationsDir: string,\n files: readonly string[],\n existing: MigrationLockFile | null,\n baseline: string | undefined,\n): MigrationLockFile | null {\n const digestOf = (name: string): string => sha256Hex(readFileSync(join(migrationsDir, name), 'utf8'));\n\n if (existing === null) {\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: files.map((name) => ({ name, sha256: digestOf(name) })),\n };\n }\n\n const kept = new Map<string, string>();\n for (const file of files) {\n const recorded = existing.migrations.find((entry) => entry.name === file);\n if (recorded === undefined) continue;\n // The baseline is the one file a squash is allowed to rewrite.\n kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);\n }\n // Unlocked files are added — that is the new-migration case. Every other entry\n // is carried across untouched, so an `edited` finding survives the write.\n for (const file of files) {\n if (!kept.has(file) && !existing.migrations.some((entry) => entry.name === file)) {\n kept.set(file, digestOf(file));\n }\n }\n // Entries the baseline absorbed are dropped: committing a squash looks exactly\n // like this, and neither it nor a rewritten baseline can hide a divergence,\n // because a database that applied those files already has them recorded in D1's\n // own `d1_migrations`.\n for (const entry of existing.migrations) {\n if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {\n kept.set(entry.name, entry.sha256);\n }\n }\n\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),\n };\n}\n\n/** Verify (or with `write: true`, record) the lock against the files. */\nfunction verifyMigrations(migrationsDir: string, options: { write?: boolean } = {}): MigrationReport {\n const report = inspectMigrations(migrationsDir);\n const baseline = baselineOf(report.files);\n\n // A malformed lock is a finding in its own right, and a `--write` must not\n // overwrite contents it failed to understand.\n if (report.problems.length > 0) {\n return report;\n }\n\n if (options.write === true) {\n const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);\n const next = `${JSON.stringify(updated, null, 2)}\\n`;\n const path = join(migrationsDir, LOCK_NAME);\n let before: string | null = null;\n try {\n before = readFileSync(path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw error;\n }\n }\n if (before !== next) {\n writeFileSync(path, next, 'utf8');\n }\n report.lock = updated;\n return report;\n }\n\n const lock = report.lock;\n if (lock === null) {\n report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });\n return report;\n }\n\n const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));\n for (const name of report.files) {\n const expected = recorded.get(name);\n if (expected === undefined) {\n report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });\n continue;\n }\n // At or before the baseline, a squash rewrites its own file, and that is the\n // whole reason a baseline exists.\n if (isSubsumed(name, baseline)) continue;\n const actual = sha256Hex(readFileSync(join(migrationsDir, name), 'utf8'));\n if (actual !== expected) {\n report.problems.push({\n problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n });\n }\n }\n\n for (const entry of lock.migrations) {\n if (report.files.includes(entry.name)) continue;\n if (isSubsumed(entry.name, baseline)) continue;\n report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });\n }\n\n // A file sorting before the newest locked one can never reach a database that\n // has already applied that newest one, so its statements would only run on a\n // fresh build — the same silent split the checksum exists to prevent.\n const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);\n if (newest !== undefined) {\n for (const name of report.files) {\n if (name < newest && !recorded.has(name)) {\n report.problems.push({\n problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,\n });\n }\n }\n }\n\n return report;\n}\n\n/** CLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`. */\nfunction verifyMigrationsCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';\n const write = argv.includes('--write');\n const report = verifyMigrations(dir, { write });\n if (report.problems.length > 0) {\n console.error(`Migration validation failed for ${dir}:`);\n for (const problem of report.problems) console.error(` - ${problem.problem}`);\n return 1;\n }\n if (write) {\n console.log(`Migration lock written (${report.files.length} files).`);\n return 0;\n }\n console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);\n return 0;\n}\n\nexport { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };\nexport type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationReport };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(verifyMigrationsCli(process.argv.slice(2)));\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/scripts/verify-migrations.ts"],
4
+ "sourcesContent": ["/**\n * Verify the migration set is complete, ordered, and locked; write the lock.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`\n * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,\n * converged. Every copy checks the same properties of a `migrations/` directory;\n * they differ in lock-file naming, in whether the lock is enforced on CI, and in\n * how much of D1's ordering semantics they encode.\n *\n * ### Why a checksum lock at all\n *\n * D1 records *which* migrations it has applied — the filename and a timestamp —\n * but not *what the file contained* when it applied them. So editing a migration\n * that has already run is not caught by anything: the deploy still succeeds, the\n * local database built from the baseline plus the edited file picks up the new\n * statements, and production keeps the schema it had. The two databases then\n * differ silently and permanently, and the next migration that assumes the newer\n * shape fails only in production. A committed digest per file turns that into a\n * CI failure.\n *\n * ### What the checks are, and where each comes from\n *\n * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by\n * filename, so a file that sorts *after* the ones already applied is the only\n * kind that can be introduced safely.\n * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and\n * 0003 while another applied only 0001, and nothing downstream can tell which.\n * Checked **only when no squash baseline exists**: a squash legitimately\n * absorbs its predecessors, so numbering restarts wherever it starts, and a\n * contiguity rule that fires on a squash is a rule that blocks the squash.\n * - **One entry per file** (all) — a file with no recorded digest is one nothing\n * can say anything about.\n * - **Digest unchanged** (all) — the edited-after-locking failure.\n * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been\n * applied to a live database and is no longer reproducible from this repo.\n * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file\n * sorting *before* the newest locked one can never reach a database that has\n * applied that newest one, so its statements would only run on a fresh build.\n * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a\n * style problem: D1 orders them by the rest of the filename, so which one lands\n * on a given database depends on a lexicographic tiebreak nobody intended.\n *\n * ### The squash baseline\n *\n * `0008_squash.sql` holds the combined schema of every migration before it, and\n * those files are deleted when it is created. A later squash repeats that. So a\n * squash legitimately (a) rewrites one file and (b) removes files the lock still\n * lists, and neither may be reported as drift. The baseline is the\n * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims\n * — deriving it means a stale or forged `baseline` cannot widen the exempt set.\n *\n * ### The one write path\n *\n * `--write` is add-only where it counts: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. Every other\n * entry is left exactly as it is, so an incremental `edited` finding **survives a\n * `--write`** — re-baselining one means deleting its entry by hand, which shows\n * up in the diff. There is deliberately no `--force`, because a write that could\n * bless a drift would be the operator blessing their own edit.\n */\nimport { createHash } from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\nOne migration as the lock records it.\n*/\ninterface MigrationEntry {\n name: string;\n sha256: string;\n}\n\n/**\nThe parsed `migrations/migrations.lock.json`.\n*/\ninterface MigrationLockFile {\n version: 1;\n /**\n * The squashed-baseline filename, when the repo has squashed.\n *\n * Everything at or before it is exempt from the `edited` and `orphan` checks,\n * because that is exactly the set a squash rewrites or absorbs.\n */\n baseline?: string;\n migrations: MigrationEntry[];\n}\n\n/**\nOne failure, phrased for the operator.\n*/\ninterface MigrationProblem {\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface MigrationReport {\n /**\n Migration filenames, in apply order.\n */\n files: string[];\n problems: MigrationProblem[];\n /**\n The lock as it reads after the run.\n */\n lock: MigrationLockFile | null;\n}\n\n/**\n * The lock's filename, beside the `.sql` files.\n *\n * Named `migrations.lock.json` rather than `migrations.json` so it cannot be\n * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like\n * one would be a deploy-time mystery.\n */\nconst LOCK_NAME = 'migrations.lock.json';\n\n/**\nThe filename shape every migration must have. `NNNN_` is fixed at four digits.\n*/\nconst NAME_PATTERN = /^(\\d{4})_[a-z0-9_]+\\.sql$/;\n\n/**\nThe squashed-baseline shape. The highest-numbered match is the baseline.\n*/\nconst SQUASH_PATTERN = /^\\d{4}_squash\\.sql$/;\n\n/**\nThe lock's format version. Bumped only on an incompatible shape change.\n*/\nconst LOCK_VERSION = 1;\n\nfunction sha256Hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo\n * has not squashed — in which case every migration is incremental and therefore\n * every one of them is immutable.\n */\nexport function baselineOf(files: readonly string[]): string | undefined {\n let highest: string | undefined;\n for (const name of files) {\n if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {\n highest = name;\n }\n }\n return highest;\n}\n\n/**\nTrue when `name` is at or before the baseline, i.e. the set a squash absorbs.\n*/\nfunction isSubsumed(name: string, baseline: string | undefined): boolean {\n return baseline !== undefined && name <= baseline;\n}\n\n/**\n * Read the migration set and validate its shape without consulting the lock.\n *\n * The lock is read here too, so one walk answers both \"what is on disk\" and \"what\n * is recorded\"; a lock that is merely *absent* is reported by `verifyMigrations`\n * rather than here, because that is the bootstrap case rather than a defect.\n */\nfunction inspectMigrations(migrationsDir: string): MigrationReport {\n const problems: MigrationProblem[] = [];\n if (!existsSync(migrationsDir)) {\n problems.push({ problem: `${migrationsDir} does not exist` });\n return { files: [], problems, lock: null };\n }\n\n // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the\n // lock describes exactly the set wrangler will run. `migrations.lock.json` is\n // not one of them, because it is not a `.sql` file.\n const files = readdirSync(migrationsDir)\n .filter((name) => name.endsWith('.sql'))\n .sort((left, right) => left.localeCompare(right));\n\n for (const name of files) {\n if (!NAME_PATTERN.test(name)) {\n problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });\n }\n }\n\n const baseline = baselineOf(files);\n const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);\n\n // Strictly increasing: the property D1 actually depends on. A duplicate or a\n // descending prefix means two files compete for the same slot in the apply\n // order, and which one wins is a lexicographic tiebreak nobody intended.\n for (let index = 1; index < prefixes.length; index += 1) {\n const previous = prefixes[index - 1];\n const current = prefixes[index];\n if (previous !== undefined && current !== undefined && current <= previous) {\n problems.push({\n problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,\n });\n }\n }\n\n // Contiguity is checked only with no squash on disk: a squash deletes the files\n // it absorbs, so numbering restarts wherever it starts and a hole is the\n // expected shape rather than a defect.\n if (baseline === undefined) {\n for (const [index, prefix] of prefixes.entries()) {\n const expected = String(index + 1).padStart(4, '0');\n if (prefix !== expected) {\n problems.push({\n problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,\n });\n }\n }\n }\n\n const lockPath = path.join(migrationsDir, LOCK_NAME);\n let lock: MigrationLockFile | null = null;\n if (existsSync(lockPath)) {\n try {\n lock = JSON.parse(readFileSync(lockPath, 'utf8')) as MigrationLockFile;\n } catch {\n problems.push({ problem: `${LOCK_NAME} is not valid JSON` });\n }\n }\n\n return { files, problems, lock };\n}\n\n/**\n * The lock as `--write` would leave it.\n *\n * `null` when the existing lock cannot be trusted as a base, which is exactly\n * when a `--write` must refuse rather than overwrite contents it failed to\n * understand. A lock that is merely *absent* is not malformed: that is the\n * bootstrap case, and it is built from disk like any other.\n */\nfunction buildUpdatedLock(\n migrationsDir: string,\n files: readonly string[],\n existing: MigrationLockFile | null,\n baseline: string | undefined,\n): MigrationLockFile | null {\n const digestOf = (name: string): string => sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n\n if (existing === null) {\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: files.map((name) => ({ name, sha256: digestOf(name) })),\n };\n }\n\n const kept = new Map<string, string>();\n for (const file of files) {\n const recorded = existing.migrations.find((entry) => entry.name === file);\n if (recorded === undefined) continue;\n // The baseline is the one file a squash is allowed to rewrite.\n kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);\n }\n // Unlocked files are added — that is the new-migration case. Every other entry\n // is carried across untouched, so an `edited` finding survives the write.\n for (const file of files) {\n if (!kept.has(file) && existing.migrations.every((entry) => entry.name !== file)) {\n kept.set(file, digestOf(file));\n }\n }\n // Entries the baseline absorbed are dropped: committing a squash looks exactly\n // like this, and neither it nor a rewritten baseline can hide a divergence,\n // because a database that applied those files already has them recorded in D1's\n // own `d1_migrations`.\n for (const entry of existing.migrations) {\n if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {\n kept.set(entry.name, entry.sha256);\n }\n }\n\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),\n };\n}\n\n/**\nVerify (or with `write: true`, record) the lock against the files.\n*/\nfunction verifyMigrations(migrationsDir: string, options: { write?: boolean } = {}): MigrationReport {\n const report = inspectMigrations(migrationsDir);\n const baseline = baselineOf(report.files);\n\n // A malformed lock is a finding in its own right, and a `--write` must not\n // overwrite contents it failed to understand.\n if (report.problems.length > 0) {\n return report;\n }\n\n if (options.write === true) {\n const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);\n const next = `${JSON.stringify(updated, null, 2)}\\n`;\n const lockfile = path.join(migrationsDir, LOCK_NAME);\n let before: string | null = null;\n try {\n before = readFileSync(lockfile, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw error;\n }\n }\n if (before !== next) {\n writeFileSync(lockfile, next, 'utf8');\n }\n report.lock = updated;\n return report;\n }\n\n const lock = report.lock;\n if (lock === null) {\n report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });\n return report;\n }\n\n const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));\n for (const name of report.files) {\n const expected = recorded.get(name);\n if (expected === undefined) {\n report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });\n continue;\n }\n // At or before the baseline, a squash rewrites its own file, and that is the\n // whole reason a baseline exists.\n if (isSubsumed(name, baseline)) continue;\n const actual = sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n if (actual !== expected) {\n report.problems.push({\n problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n });\n }\n }\n\n for (const entry of lock.migrations) {\n if (report.files.includes(entry.name) || isSubsumed(entry.name, baseline)) continue;\n report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });\n }\n\n // A file sorting before the newest locked one can never reach a database that\n // has already applied that newest one, so its statements would only run on a\n // fresh build — the same silent split the checksum exists to prevent.\n const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);\n if (newest !== undefined) {\n for (const name of report.files) {\n if (name < newest && !recorded.has(name)) {\n report.problems.push({\n problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,\n });\n }\n }\n }\n\n return report;\n}\n\n/**\nCLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`.\n*/\nfunction verifyMigrationsCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';\n const write = argv.includes('--write');\n const report = verifyMigrations(dir, { write });\n if (report.problems.length > 0) {\n console.error(`Migration validation failed for ${dir}:`);\n for (const problem of report.problems) console.error(` - ${problem.problem}`);\n return 1;\n }\n if (write) {\n console.log(`Migration lock written (${report.files.length} files).`);\n return 0;\n }\n console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);\n return 0;\n}\n\nexport { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };\nexport type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationReport };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(verifyMigrationsCli(process.argv.slice(2)));\n}\n"],
5
+ "mappings": "AA4DA,OAAS,cAAAA,MAAkB,cAC3B,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,iBAAAC,MAAqB,UACrE,OAAOC,MAAU,YAsDjB,MAAMC,EAAY,uBAKZC,EAAe,4BAKfC,EAAiB,sBAKjBC,EAAe,EAErB,SAASC,EAAUC,EAAe,CAChC,OAAOZ,EAAW,QAAQ,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U,QAAQ,MAAM,OAAOa,EAAQ,OAAO,EAAE,EAC7E,MAAO,EACT,CACA,OAAID,GACF,QAAQ,IAAI,2BAA2BZ,EAAO,MAAM,MAAM,UAAU,EAC7D,IAET,QAAQ,IAAI,gCAAgCA,EAAO,MAAM,MAAM,wBAAwB,EAChF,EACT,CAYI,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQzC,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKiD,EAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["createHash", "pathToFileURL", "existsSync", "readFileSync", "readdirSync", "writeFileSync", "path", "LOCK_NAME", "NAME_PATTERN", "SQUASH_PATTERN", "LOCK_VERSION", "sha256Hex", "content", "baselineOf", "files", "highest", "name", "isSubsumed", "baseline", "inspectMigrations", "migrationsDir", "problems", "left", "right", "prefixes", "index", "previous", "current", "prefix", "expected", "lockPath", "lock", "buildUpdatedLock", "existing", "digestOf", "kept", "file", "recorded", "entry", "sha256", "verifyMigrations", "options", "report", "updated", "next", "lockfile", "before", "error", "actual", "newest", "verifyMigrationsCli", "argv", "dir", "arg", "write", "problem"]
7
+ }
@@ -1,53 +1,2 @@
1
1
  #!/usr/bin/env tsx
2
- /**
3
- * Fail when the SPA shell the API worker serves is missing or self-inconsistent.
4
- *
5
- * Provenance: Durable-DAV's and Durable-DAV-Router's `scripts/verify-spa-shell.mjs`
6
- * and Edge-Sonic's typed `scripts/build/verify-spa-shell.ts`. The rules — which of
7
- * the ways a shell can be wrong to look for — live in `spa-shell.ts`, so they are
8
- * unit tested without a build on disk; this file is the entrypoint that turns the
9
- * verdict into an exit code.
10
- *
11
- * What it catches:
12
- *
13
- * - the `postinstall` stub, or no build at all, still in place;
14
- * - `spa-shell.ts` referencing `/assets/...` bundles that were not emitted (a
15
- * partially cleaned or half-copied `dist/`, which serves a shell whose JS 404s
16
- * and therefore renders no operator UI at all);
17
- * - `spa-shell.ts` and `apps/web/dist/index.html` disagreeing, i.e. only one of
18
- * the two halves of the build was refreshed.
19
- *
20
- * **The build is a precondition of this check, not a convenience.** Both paths are
21
- * gitignored and `postinstall` writes a deliberately empty stub, so verifying
22
- * without building cannot pass — and it fails with precisely the message above,
23
- * which is the check working rather than the check being wrong.
24
- *
25
- * Usage, from the repo root:
26
- *
27
- * ```bash
28
- * pnpm exec tsx scripts/verify-spa-shell.ts # defaults to ./ as root
29
- * pnpm exec tsx scripts/verify-spa-shell.ts --root /path/to/repo
30
- * ```
31
- */
32
- import path from 'node:path';
33
- import { fileURLToPath } from 'node:url';
34
- import { verifySpaShell } from './spa-shell';
35
- /**
36
- * The repository root, derived from this file rather than from `process.cwd()`.
37
- *
38
- * Two levels up, because this file sits in `scripts/`. Deriving it means the gate
39
- * reads the same tree whatever directory it is invoked from — which is the
40
- * difference between a gate and a gate that passes because nobody ran it from the
41
- * right place.
42
- */
43
- const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
44
- const root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);
45
- const { problems } = verifySpaShell({ root });
46
- if (problems.length > 0) {
47
- console.error('SPA shell check failed:');
48
- for (const problem of problems)
49
- console.error(` - ${problem}`);
50
- process.exit(1);
51
- }
52
- console.log(`SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`);
53
- //# sourceMappingURL=verify-spa-shell.js.map
2
+ import e from"node:path";import{fileURLToPath as l}from"node:url";import{verifySpaShell as t}from"./spa-shell.js";const p=e.resolve(e.dirname(l(import.meta.url)),".."),o=process.argv[2]===void 0?p:e.resolve(process.argv[2]),{problems:r}=t({root:o});if(r.length>0){console.error("SPA shell check failed:");for(const s of r)console.error(` - ${s}`);process.exit(1)}console.log(`SPA shell check passed (${e.join(o,"apps/api/src/generated/spa-shell.ts")} matches ${e.join(o,"apps/web/dist")}).`);
@@ -1 +1,7 @@
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
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/scripts/verify-spa-shell.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env tsx\n/**\n * Fail when the SPA shell the API worker serves is missing or self-inconsistent.\n *\n * Provenance: Durable-DAV's and Durable-DAV-Router's `scripts/verify-spa-shell.mjs`\n * and Edge-Sonic's typed `scripts/build/verify-spa-shell.ts`. The rules — which of\n * the ways a shell can be wrong to look for — live in `spa-shell.ts`, so they are\n * unit tested without a build on disk; this file is the entrypoint that turns the\n * verdict into an exit code.\n *\n * What it catches:\n *\n * - the `postinstall` stub, or no build at all, still in place;\n * - `spa-shell.ts` referencing `/assets/...` bundles that were not emitted (a\n * partially cleaned or half-copied `dist/`, which serves a shell whose JS 404s\n * and therefore renders no operator UI at all);\n * - `spa-shell.ts` and `apps/web/dist/index.html` disagreeing, i.e. only one of\n * the two halves of the build was refreshed.\n *\n * **The build is a precondition of this check, not a convenience.** Both paths are\n * gitignored and `postinstall` writes a deliberately empty stub, so verifying\n * without building cannot pass — and it fails with precisely the message above,\n * which is the check working rather than the check being wrong.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/verify-spa-shell.ts # defaults to ./ as root\n * pnpm exec tsx scripts/verify-spa-shell.ts --root /path/to/repo\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { verifySpaShell } from './spa-shell.ts';\n\n/**\n * The repository root, derived from this file rather than from `process.cwd()`.\n *\n * Two levels up, because this file sits in `scripts/`. Deriving it means the gate\n * reads the same tree whatever directory it is invoked from — which is the\n * difference between a gate and a gate that passes because nobody ran it from the\n * right place.\n */\nconst REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\n\nconst root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);\n\nconst { problems } = verifySpaShell({ root });\n\nif (problems.length > 0) {\n console.error('SPA shell check failed:');\n for (const problem of problems) console.error(` - ${problem}`);\n process.exit(1);\n}\n\nconsole.log(\n `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,\n);\n"],
5
+ "mappings": ";AA+BA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,kBAAAC,MAAsB,iBAU/B,MAAMC,EAAkBH,EAAK,QAAQA,EAAK,QAAQC,EAAc,YAAY,GAAG,CAAC,EAAG,IAAI,EAEjFG,EAAO,QAAQ,KAAK,CAAC,IAAM,OAAYD,EAAkBH,EAAK,QAAQ,QAAQ,KAAK,CAAC,CAAC,EAErF,CAAE,SAAAK,CAAQ,EAAKH,EAAe,CAAE,KAAAE,CAAI,CAAE,EAE5C,GAAIC,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,CAAO,EAAE,EAC9D,QAAQ,KAAK,CAAC,CAChB,CAEA,QAAQ,IACN,2BAA2BN,EAAK,KAAKI,EAAM,qCAAqC,CAAC,YAAYJ,EAAK,KAAKI,EAAM,eAAe,CAAC,IAAI",
6
+ "names": ["path", "fileURLToPath", "verifySpaShell", "REPOSITORY_ROOT", "root", "problems", "problem"]
7
+ }
@@ -1,51 +1,3 @@
1
- /**
2
- * Running `wrangler` and reading its output.
3
- *
4
- * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/cli.ts`.
5
- */
6
- import { execFileSync } from 'node:child_process';
7
- /**
8
- * Runs a wrangler subcommand and returns stdout.
9
- *
10
- * Arguments are passed as an argv array rather than interpolated into a shell
11
- * string, so a value containing shell metacharacters cannot alter the command.
12
- */
13
- export function runWrangler(args, input) {
14
- try {
15
- // `pnpm` is resolved from PATH deliberately: the scripts run on CI runners and
16
- // in local shells, and both resolve it the same way.
17
- // eslint-disable-next-line sonarjs/no-os-command-from-path
18
- return execFileSync('pnpm', ['exec', 'wrangler', ...args], {
19
- encoding: 'utf8',
20
- stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
21
- ...(input !== undefined && { input }),
22
- });
23
- }
24
- catch (error) {
25
- const maybeProcessError = error;
26
- const stdout = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';
27
- const stderr = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';
28
- throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\n${stdout}${stderr || maybeProcessError.message || ''}`);
29
- }
30
- }
31
- /**
32
- * Parses a JSON array from a command's stdout, naming the command on failure.
33
- *
34
- * Several wrangler subcommands print a human-readable table when they detect a
35
- * TTY, so "not JSON" is an expected outcome that the caller often has a table
36
- * parser for. Passing the command description turns that into a catchable,
37
- * self-explanatory error instead of an unlabelled `SyntaxError`.
38
- */
39
- export function parseJsonArray(output, commandDescription) {
40
- try {
41
- const parsed = JSON.parse(output);
42
- if (Array.isArray(parsed)) {
43
- return parsed;
44
- }
45
- }
46
- catch {
47
- // Fall through to the explicit error below.
48
- }
49
- throw new Error(`Expected JSON array output from ${commandDescription}. Output:\n${output}`);
50
- }
51
- //# sourceMappingURL=cli.js.map
1
+ import{execFileSync as c}from"node:child_process";function d(r,e){try{return c("pnpm",["exec","wrangler",...r],{encoding:"utf8",stdio:[e===void 0?"ignore":"pipe","pipe","pipe"],...e!==void 0&&{input:e}})}catch(n){const t=n,o=t.stdout?t.stdout.toString():"",s=t.stderr?t.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${r.join(" ")}
2
+ ${o}${s||t.message||""}`)}}function i(r,e){try{const n=JSON.parse(r);if(Array.isArray(n))return n}catch{}throw new Error(`Expected JSON array output from ${e}. Output:
3
+ ${r}`)}export{i as parseJsonArray,d as runWrangler};
@@ -1 +1,7 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../../src/scripts/wrangler-config/cli.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,IAAuB,EAAE,KAAc;IACjE,IAAI,CAAC;QACH,+EAA+E;QAC/E,q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M,EAAE,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["/**\n * Running `wrangler` and reading its output.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/cli.ts`.\n */\n\nimport { execFileSync } from 'node:child_process';\n\n/**\n * Runs a wrangler subcommand and returns stdout.\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 */\nexport function runWrangler(args: readonly string[], input?: string): string {\n try {\n // `pnpm` is resolved from PATH deliberately: the scripts run on CI runners and\n // in local shells, and both resolve it the same way.\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\n/**\n * Parses a JSON array from a command's stdout, naming the command on failure.\n *\n * Several wrangler subcommands print a human-readable table when they detect a\n * TTY, so \"not JSON\" is an expected outcome that the caller often has a table\n * parser for. Passing the command description turns that into a catchable,\n * self-explanatory error instead of an unlabelled `SyntaxError`.\n */\nexport function parseJsonArray<T>(output: string, commandDescription: string): T[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (Array.isArray(parsed)) {\n return parsed as T[];\n }\n } catch {\n // Fall through to the explicit error below.\n }\n throw new Error(`Expected JSON array output from ${commandDescription}. Output:\\n${output}`);\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/scripts/wrangler-config/cli.ts"],
4
+ "sourcesContent": ["/**\n * Running `wrangler` and reading its output.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/cli.ts`.\n */\n\nimport { execFileSync } from 'node:child_process';\n\n/**\n * Runs a wrangler subcommand and returns stdout.\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 */\nexport function runWrangler(args: readonly string[], input?: string): string {\n try {\n // `pnpm` is resolved from PATH deliberately: the scripts run on CI runners and\n // in local shells, and both resolve it the same way.\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\n/**\n * Parses a JSON array from a command's stdout, naming the command on failure.\n *\n * Several wrangler subcommands print a human-readable table when they detect a\n * TTY, so \"not JSON\" is an expected outcome that the caller often has a table\n * parser for. Passing the command description turns that into a catchable,\n * self-explanatory error instead of an unlabelled `SyntaxError`.\n */\nexport function parseJsonArray<T>(output: string, commandDescription: string): T[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (Array.isArray(parsed)) {\n return parsed as T[];\n }\n } catch {\n // Fall through to the explicit error below.\n }\n throw new Error(`Expected JSON array output from ${commandDescription}. Output:\\n${output}`);\n}\n"],
5
+ "mappings": "AAMA,OAAS,gBAAAA,MAAoB,qBAQvB,SAAUC,EAAYC,EAAyBC,EAAc,CACjE,GAAI,CAIF,OAAOH,EAAa,OAAQ,CAAC,OAAQ,WAAY,GAAGE,CAAI,EAAG,CACzD,SAAU,OACV,MAAO,CAACC,IAAU,OAAY,SAAW,OAAQ,OAAQ,MAAM,EAC/D,GAAIA,IAAU,QAAa,CAAE,MAAAA,CAAK,EACnC,CACH,OAASC,EAAgB,CACvB,MAAMC,EAAoBD,EACpBE,EAAiBD,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GAClFE,EAAiBF,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GACxF,MAAM,IAAI,MAAM,sCAAsCH,EAAK,KAAK,GAAG,CAAC;EAAKI,CAAM,GAAGC,GAAUF,EAAkB,SAAW,EAAE,EAAE,CAC/H,CACF,CAUM,SAAUG,EAAkBC,EAAgBC,EAA0B,CAC1E,GAAI,CACF,MAAMC,EAAkB,KAAK,MAAMF,CAAM,EACzC,GAAI,MAAM,QAAQE,CAAM,EACtB,OAAOA,CAEX,MAAQ,CAER,CACA,MAAM,IAAI,MAAM,mCAAmCD,CAAkB;EAAcD,CAAM,EAAE,CAC7F",
6
+ "names": ["execFileSync", "runWrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseJsonArray", "output", "commandDescription", "parsed"]
7
+ }
@@ -9,8 +9,10 @@
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';
13
- /** The config's current text and its parsed form. */
12
+ import { type WranglerConfig } from './types.ts';
13
+ /**
14
+ The config's current text and its parsed form.
15
+ */
14
16
  export interface ConfigFile {
15
17
  content: string;
16
18
  config: WranglerConfig;
@@ -20,7 +22,9 @@ export declare function readConfig(): ConfigFile;
20
22
  * Apply one edit to the config text, preserving comments and formatting.
21
23
  */
22
24
  export declare function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string;
23
- /** Write the config, guaranteeing a trailing newline so Prettier sees a fixed point. */
25
+ /**
26
+ Write the config, guaranteeing a trailing newline so Prettier sees a fixed point.
27
+ */
24
28
  export declare function writeConfig(content: string): void;
25
29
  /**
26
30
  * The top-level keys a caller wants to merge into the config, from the environment.
@@ -30,7 +34,9 @@ export declare function writeConfig(content: string): void;
30
34
  * patches the routes and the vars rather than keeping three templates in step.
31
35
  */
32
36
  export declare function parseTopLevelPatch(): Record<string, unknown> | undefined;
33
- /** The `vars` entries a caller wants to merge, from the environment. */
37
+ /**
38
+ The `vars` entries a caller wants to merge, from the environment.
39
+ */
34
40
  export declare function parseVarsPatch(): Record<string, string> | undefined;
35
41
  /**
36
42
  * Materialize the config: the repository variable when it is set, otherwise the