@rexezuge/tooling 1.3.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 (128) hide show
  1. package/dist/eslint-boundaries.d.ts +12 -4
  2. package/dist/eslint-boundaries.d.ts.map +1 -1
  3. package/dist/eslint-boundaries.js +1 -224
  4. package/dist/eslint-boundaries.js.map +7 -1
  5. package/dist/eslint-rules.js +1 -273
  6. package/dist/eslint-rules.js.map +7 -1
  7. package/dist/eslint.js +1 -194
  8. package/dist/eslint.js.map +7 -1
  9. package/dist/functions/pages-proxy.d.ts.map +1 -1
  10. package/dist/functions/pages-proxy.js +1 -131
  11. package/dist/functions/pages-proxy.js.map +7 -1
  12. package/dist/index.js +1 -31
  13. package/dist/index.js.map +7 -1
  14. package/dist/scripts/backup/d1-target.d.ts +15 -5
  15. package/dist/scripts/backup/d1-target.d.ts.map +1 -1
  16. package/dist/scripts/backup/d1-target.js +1 -31
  17. package/dist/scripts/backup/d1-target.js.map +7 -1
  18. package/dist/scripts/backup/destination-config.d.ts +24 -8
  19. package/dist/scripts/backup/destination-config.d.ts.map +1 -1
  20. package/dist/scripts/backup/destination-config.js +1 -57
  21. package/dist/scripts/backup/destination-config.js.map +7 -1
  22. package/dist/scripts/backup/encrypt-backup.js +2 -97
  23. package/dist/scripts/backup/encrypt-backup.js.map +7 -1
  24. package/dist/scripts/backup/naming.d.ts +3 -1
  25. package/dist/scripts/backup/naming.d.ts.map +1 -1
  26. package/dist/scripts/backup/naming.js +1 -58
  27. package/dist/scripts/backup/naming.js.map +7 -1
  28. package/dist/scripts/check-god-files.d.ts +40 -14
  29. package/dist/scripts/check-god-files.d.ts.map +1 -1
  30. package/dist/scripts/check-god-files.js +2 -271
  31. package/dist/scripts/check-god-files.js.map +7 -1
  32. package/dist/scripts/ensure-spa-shell-stub.js +1 -29
  33. package/dist/scripts/ensure-spa-shell-stub.js.map +7 -1
  34. package/dist/scripts/init-secrets.d.ts +0 -16
  35. package/dist/scripts/init-secrets.d.ts.map +1 -1
  36. package/dist/scripts/init-secrets.js +2 -239
  37. package/dist/scripts/init-secrets.js.map +7 -1
  38. package/dist/scripts/lib/cli-args.d.ts.map +1 -1
  39. package/dist/scripts/lib/cli-args.js +1 -116
  40. package/dist/scripts/lib/cli-args.js.map +7 -1
  41. package/dist/scripts/lib/github-actions.js +3 -38
  42. package/dist/scripts/lib/github-actions.js.map +7 -1
  43. package/dist/scripts/lib/wrangler-table.d.ts.map +1 -1
  44. package/dist/scripts/lib/wrangler-table.js +2 -99
  45. package/dist/scripts/lib/wrangler-table.js.map +7 -1
  46. package/dist/scripts/migrations-lock.js +1 -44
  47. package/dist/scripts/migrations-lock.js.map +7 -1
  48. package/dist/scripts/prepare-wrangler-config.js +1 -49
  49. package/dist/scripts/prepare-wrangler-config.js.map +7 -1
  50. package/dist/scripts/spa-shell.d.ts +12 -4
  51. package/dist/scripts/spa-shell.d.ts.map +1 -1
  52. package/dist/scripts/spa-shell.js +3 -160
  53. package/dist/scripts/spa-shell.js.map +7 -1
  54. package/dist/scripts/validate-locales.d.ts +13 -5
  55. package/dist/scripts/validate-locales.d.ts.map +1 -1
  56. package/dist/scripts/validate-locales.js +4 -350
  57. package/dist/scripts/validate-locales.js.map +7 -1
  58. package/dist/scripts/verify-migrations.d.ts +27 -9
  59. package/dist/scripts/verify-migrations.d.ts.map +1 -1
  60. package/dist/scripts/verify-migrations.js +2 -312
  61. package/dist/scripts/verify-migrations.js.map +7 -1
  62. package/dist/scripts/verify-spa-shell.js +1 -52
  63. package/dist/scripts/verify-spa-shell.js.map +7 -1
  64. package/dist/scripts/wrangler-config/cli.js +3 -51
  65. package/dist/scripts/wrangler-config/cli.js.map +7 -1
  66. package/dist/scripts/wrangler-config/patches.d.ts +9 -3
  67. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  68. package/dist/scripts/wrangler-config/patches.js +4 -141
  69. package/dist/scripts/wrangler-config/patches.js.map +7 -1
  70. package/dist/scripts/wrangler-config/resources.d.ts +18 -6
  71. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  72. package/dist/scripts/wrangler-config/resources.js +1 -290
  73. package/dist/scripts/wrangler-config/resources.js.map +7 -1
  74. package/dist/scripts/wrangler-config/types.d.ts +24 -8
  75. package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
  76. package/dist/scripts/wrangler-config/types.js +1 -49
  77. package/dist/scripts/wrangler-config/types.js.map +7 -1
  78. package/dist/test/integration-migrations.d.ts +29 -12
  79. package/dist/test/integration-migrations.d.ts.map +1 -1
  80. package/dist/test/integration-migrations.js +2 -171
  81. package/dist/test/integration-migrations.js.map +7 -1
  82. package/dist/test/mocks/cloudflare-workers.js +1 -90
  83. package/dist/test/mocks/cloudflare-workers.js.map +7 -1
  84. package/dist/vite.d.ts +5 -3
  85. package/dist/vite.d.ts.map +1 -1
  86. package/dist/vite.js +3 -125
  87. package/dist/vite.js.map +7 -1
  88. package/dist/vitest-aliases.d.ts.map +1 -1
  89. package/dist/vitest-aliases.js +1 -81
  90. package/dist/vitest-aliases.js.map +7 -1
  91. package/dist/vitest-integration.js +1 -64
  92. package/dist/vitest-integration.js.map +7 -1
  93. package/dist/vitest-repo.js +1 -146
  94. package/dist/vitest-repo.js.map +7 -1
  95. package/dist/vitest-web.js +1 -109
  96. package/dist/vitest-web.js.map +7 -1
  97. package/dist/vitest.js +1 -133
  98. package/dist/vitest.js.map +7 -1
  99. package/package.json +3 -3
  100. package/src/eslint-boundaries.ts +13 -5
  101. package/src/eslint.test.ts +18 -8
  102. package/src/functions/pages-proxy.test.ts +1 -1
  103. package/src/functions/pages-proxy.ts +4 -2
  104. package/src/scripts/backup/backup-rules.test.ts +1 -1
  105. package/src/scripts/backup/d1-target.ts +15 -5
  106. package/src/scripts/backup/destination-config.ts +27 -9
  107. package/src/scripts/backup/encrypt-backup.ts +10 -8
  108. package/src/scripts/backup/naming.ts +3 -1
  109. package/src/scripts/check-god-files.test.ts +18 -18
  110. package/src/scripts/check-god-files.ts +60 -31
  111. package/src/scripts/init-secrets.ts +17 -7
  112. package/src/scripts/lib/cli-args.ts +6 -3
  113. package/src/scripts/lib/wrangler-table.ts +5 -3
  114. package/src/scripts/migrations-lock.ts +1 -1
  115. package/src/scripts/spa-shell.test.ts +17 -17
  116. package/src/scripts/spa-shell.ts +26 -14
  117. package/src/scripts/validate-locales.test.ts +17 -17
  118. package/src/scripts/validate-locales.ts +43 -25
  119. package/src/scripts/verify-migrations.test.ts +7 -7
  120. package/src/scripts/verify-migrations.ts +47 -24
  121. package/src/scripts/wrangler-config/patches.ts +12 -4
  122. package/src/scripts/wrangler-config/resources.ts +30 -14
  123. package/src/scripts/wrangler-config/types.ts +24 -8
  124. package/src/test/integration-migrations.test.ts +6 -6
  125. package/src/test/integration-migrations.ts +33 -14
  126. package/src/vite.test.ts +24 -13
  127. package/src/vite.ts +5 -5
  128. package/src/vitest-aliases.ts +1 -3
@@ -1,240 +1,3 @@
1
1
  #!/usr/bin/env tsx
2
- /**
3
- * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh
4
- * value for each one that does not exist yet.
5
- *
6
- * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's
7
- * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid
8
- * a broken deploy for a whole release, and both fixes are carried over.
9
- *
10
- * ### Why this script exists at all
11
- *
12
- * A `secrets_store_secrets` binding fails the deploy unless the named secret
13
- * already exists inside the named store. Nothing creates it: Cloudflare will not
14
- * generate a value, and the template cannot carry one. So this script is the only
15
- * thing standing between a fresh account and a deploy that cannot succeed.
16
- *
17
- * ### The two defects that hid a broken deploy
18
- *
19
- * **The generator list was stale.** Durable-DAV's copy carried an allowlist of
20
- * exact names from the repository it was inherited from, all deleted when the repo
21
- * was renamed, so the very first iteration threw `Unknown secret` and never created
22
- * anything. So the rule here is the secret's **name shape**, not a list of names:
23
- * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32
24
- * random bytes. Adding a secret to the template is then a one-line change needing
25
- * no matching edit here, which is the property the exact-name list did not have.
26
- *
27
- * **The throw was swallowed.** The original ended in `main().catch(console.error)`.
28
- * `console.error` returns `undefined` and never sets an exit status, so the process
29
- * exited **0** and CI marked the step green — the failure only surfaced one step
30
- * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is
31
- * validated **before** any Cloudflare call, and a rejection reaches the runner as
32
- * a non-zero exit with a workflow annotation.
33
- *
34
- * ### Create-if-absent is a correctness property, not laziness
35
- *
36
- * An existing secret is left untouched. A replication encryption key seals every
37
- * remote target's credential; regenerating it on a redeploy would strand them all
38
- * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,
39
- * not a side effect of deploying.
40
- *
41
- * Requires a materialized `wrangler.jsonc` — run
42
- * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the
43
- * config is missing, because a step reporting "Secret initialization complete"
44
- * having created nothing is worse than a named error.
45
- */
46
- import { execFileSync } from 'node:child_process';
47
- import { existsSync, readFileSync } from 'node:fs';
48
- import { parse } from 'jsonc-parser';
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
- /**
53
- * The secret names the AES-GCM key generator produces, matched by **shape**.
54
- *
55
- * Keyed on the suffix because the alternative is the exact-name map that went
56
- * stale. See the header: a template naming `*-encryption-key` is then a one-line
57
- * change with no matching edit here, and a new secret breaks the deploy loudly
58
- * instead of silently.
59
- */
60
- const ENCRYPTION_KEY_SUFFIX = '-encryption-key';
61
- /** The secret names the random signing secret generator produces. */
62
- const SIGNING_SECRET_SUFFIX = '-signing-secret';
63
- /** A 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts. */
64
- async function generateAESGCMKey() {
65
- const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
66
- const exported = await crypto.subtle.exportKey('raw', key);
67
- // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,
68
- // which is fine today and is a stack overflow the day the key is longer.
69
- let binary = '';
70
- for (const byte of new Uint8Array(exported)) {
71
- binary += String.fromCodePoint(byte);
72
- }
73
- return btoa(binary);
74
- }
75
- /** A 256-bit random signing secret for internal self-calls, hex-encoded. */
76
- function generateSigningSecret() {
77
- let hex = '';
78
- for (const byte of crypto.getRandomValues(new Uint8Array(32))) {
79
- hex += byte.toString(16).padStart(2, '0');
80
- }
81
- return Promise.resolve(hex);
82
- }
83
- /**
84
- * The generator for a secret name, chosen by the name's shape.
85
- *
86
- * A name matching neither is still refused rather than given a guess: the generator
87
- * is not the only thing that has to be right, and an unusable value that looks
88
- * provisioned is worse than a failure.
89
- */
90
- function generatorFor(secretName) {
91
- if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX))
92
- return generateAESGCMKey;
93
- if (secretName.endsWith(SIGNING_SECRET_SUFFIX))
94
- return generateSigningSecret;
95
- throw new Error(`Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +
96
- `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`);
97
- }
98
- /** Whether this script can produce a value for `secretName`. */
99
- export function canProvisionSecret(secretName) {
100
- try {
101
- generatorFor(secretName);
102
- return true;
103
- }
104
- catch {
105
- return false;
106
- }
107
- }
108
- /**
109
- * Runs a wrangler subcommand, optionally feeding `input` on stdin.
110
- *
111
- * Arguments are passed as an argv array rather than interpolated into a shell
112
- * string, so a value containing shell metacharacters cannot alter the command.
113
- */
114
- function wrangler(args, input) {
115
- try {
116
- // eslint-disable-next-line sonarjs/no-os-command-from-path
117
- return execFileSync('pnpm', ['exec', 'wrangler', ...args], {
118
- encoding: 'utf8',
119
- stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
120
- ...(input !== undefined && { input }),
121
- });
122
- }
123
- catch (error) {
124
- const maybeProcessError = error;
125
- const stdout = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';
126
- const stderr = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';
127
- throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\n${stdout}${stderr || maybeProcessError.message || ''}`);
128
- }
129
- }
130
- function parseWranglerConfig() {
131
- if (!existsSync(CONFIG_PATH)) {
132
- throw new Error(`${CONFIG_PATH} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`);
133
- }
134
- // `parse` is error-tolerant and returns a partial object, so an empty result means
135
- // malformed JSON rather than "no secrets declared". Treating that as an empty list
136
- // would report success having created nothing.
137
- const config = parse(readFileSync(CONFIG_PATH, 'utf8'));
138
- if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {
139
- throw new Error(`${CONFIG_PATH} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);
140
- }
141
- return config;
142
- }
143
- /**
144
- * Turn the config's bindings into a validated work list.
145
- *
146
- * Every entry is checked *before* the first Cloudflare call, so an
147
- * unprovisionable secret fails the step in milliseconds instead of after some other
148
- * secret has already been created.
149
- */
150
- export function planSecrets(config) {
151
- const plan = [];
152
- for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {
153
- const label = secret.binding ?? `index ${index}`;
154
- const storeId = secret.store_id;
155
- const secretName = secret.secret_name;
156
- if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {
157
- throw new Error(`secrets_store_secrets[${index}] ("${label}") needs both store_id and secret_name; ` +
158
- 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.');
159
- }
160
- if (!canProvisionSecret(secretName)) {
161
- throw new Error(`No generator for secret "${secretName}" (binding "${label}").`);
162
- }
163
- plan.push({ storeId, secretName });
164
- }
165
- return plan;
166
- }
167
- /**
168
- * List the secret names present in a store.
169
- *
170
- * Returns `undefined` when the listing itself failed, which is deliberately
171
- * distinct from an empty set: a transient CLI failure must not be read as "the
172
- * secret is missing" and cause a duplicate insert over a live value. An empty store
173
- * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.
174
- *
175
- * The name is taken exactly. `output.includes(secretName)` is not a membership test:
176
- * `my-replication-encryption-key-2` satisfies a search for
177
- * `my-replication-encryption-key`, so a store holding only the suffixed entry would
178
- * report the unsuffixed one as already present and it would never be created.
179
- */
180
- function listSecretNames(storeId) {
181
- let output;
182
- try {
183
- output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);
184
- }
185
- catch (error) {
186
- if (isEmptySecretsStoreListing(error)) {
187
- console.log(`Secrets Store ${storeId} is empty`);
188
- return new Set();
189
- }
190
- console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');
191
- return undefined;
192
- }
193
- return parseWranglerNames(output);
194
- }
195
- function createSecret(storeId, secretName, secretValue) {
196
- console.log(`Creating secret: ${secretName}`);
197
- // The value goes in on stdin, never as an argv entry: an argv is visible to every
198
- // process on the runner through `ps`, and the previous
199
- // `echo "${value}" | wrangler … ${name}` also broke on `"`, `$`, backticks and
200
- // newlines.
201
- wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);
202
- }
203
- async function main() {
204
- console.log('Initializing Cloudflare secrets...');
205
- const config = parseWranglerConfig();
206
- const plan = planSecrets(config);
207
- if (plan.length === 0) {
208
- throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');
209
- }
210
- const listedByStore = new Map();
211
- for (const { storeId, secretName } of plan) {
212
- if (!listedByStore.has(storeId)) {
213
- listedByStore.set(storeId, listSecretNames(storeId));
214
- }
215
- const existing = listedByStore.get(storeId);
216
- if (existing === undefined) {
217
- // Refuse to guess: creating a secret we could not read back risks overwriting
218
- // a live value with a freshly generated one.
219
- throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);
220
- }
221
- if (existing.has(secretName)) {
222
- console.log(`Secret ${secretName} already exists; leaving it untouched.`);
223
- continue;
224
- }
225
- createSecret(storeId, secretName, await generatorFor(secretName)());
226
- existing.add(secretName);
227
- }
228
- console.log('Secret initialization complete');
229
- }
230
- // Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces
231
- // as a stack trace with its cause intact and the process exits non-zero. Either way
232
- // the exit status has to be right: this runs in the deploy pipeline, and swallowing
233
- // the rejection reported a failed key bootstrap as a green step.
234
- try {
235
- await main();
236
- }
237
- catch (error) {
238
- fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));
239
- }
240
- //# sourceMappingURL=init-secrets.js.map
2
+ import{execFileSync as l}from"node:child_process";import{existsSync as d,readFileSync as g}from"node:fs";import{parse as u}from"jsonc-parser";import{fail as p}from"./lib/github-actions.js";import{isEmptySecretsStoreListing as m,parseWranglerNames as y}from"./lib/wrangler-table.js";import{CONFIG_PATH as c}from"./wrangler-config/types.js";const w="-encryption-key",h="-signing-secret";async function S(){const e=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("raw",e);let n="";for(const t of new Uint8Array(r))n+=String.fromCodePoint(t);return btoa(n)}function E(){let e="";for(const r of crypto.getRandomValues(new Uint8Array(32)))e+=r.toString(16).padStart(2,"0");return Promise.resolve(e)}function a(e){if(e.endsWith(w))return S;if(e.endsWith(h))return E;throw new Error(`Unknown secret: ${e}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`)}function b(e){try{return a(e),!0}catch{return!1}}function f(e,r){try{return l("pnpm",["exec","wrangler",...e],{encoding:"utf8",stdio:[r===void 0?"ignore":"pipe","pipe","pipe"],...r!==void 0&&{input:r}})}catch(n){const t=n,o=t.stdout?t.stdout.toString():"",s=t.stderr?t.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${e.join(" ")}
3
+ ${o}${s||t.message||""}`)}}function _(){if(!d(c))throw new Error(`${c} not found. Run scripts/prepare-wrangler-config.ts first \u2014 it is what creates the file this script reads.`);const e=u(g(c,"utf8"));if(e.secrets_store_secrets===void 0&&Object.keys(e).length===0)throw new Error(`${c} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);return e}function $(e){const r=[];for(const[n,t]of(e.secrets_store_secrets??[]).entries()){const o=t.binding??`index ${n}`,s=t.store_id,i=t.secret_name;if(s===void 0||s===""||i===void 0||i==="")throw new Error(`secrets_store_secrets[${n}] ("${o}") needs both store_id and secret_name; store_id is normally filled in by scripts/prepare-wrangler-config.ts.`);if(!b(i))throw new Error(`No generator for secret "${i}" (binding "${o}").`);r.push({storeId:s,secretName:i})}return r}function C(e){let r;try{r=f(["secrets-store","secret","list",e,"--remote"])}catch(n){if(m(n))return console.log(`Secrets Store ${e} is empty`),new Set;console.warn(`Unable to list secrets in store ${e}:`,n instanceof Error?n.message:"unknown error");return}return y(r)}function x(e,r,n){console.log(`Creating secret: ${r}`),f(["secrets-store","secret","create",e,"--name",r,"--scopes","workers","--remote"],n)}async function N(){console.log("Initializing Cloudflare secrets...");const e=_(),r=$(e);if(r.length===0)throw new Error("wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.");const n=new Map;for(const{storeId:t,secretName:o}of r){n.has(t)||n.set(t,C(t));const s=n.get(t);if(s===void 0)throw new Error(`Could not list secrets in store ${t}; refusing to create ${o} without confirming it is absent.`);if(s.has(o)){console.log(`Secret ${o} already exists; leaving it untouched.`);continue}x(t,o,await a(o)()),s.add(o)}console.log("Secret initialization complete")}try{await N()}catch(e){p(e instanceof Error?`Secret initialization failed: ${e.message}`:String(e))}
@@ -1 +1,7 @@
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,OA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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.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"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/scripts/init-secrets.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env tsx\n/**\n * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh\n * value for each one that does not exist yet.\n *\n * Provenance: Edge-Sonic's `scripts/deploy/init-secrets.ts` and Durable-DAV's\n * `scripts/init-secrets.ts`, converged. Both record the same two defects that hid\n * a broken deploy for a whole release, and both fixes are carried over.\n *\n * ### Why this script exists at all\n *\n * A `secrets_store_secrets` binding fails the deploy unless the named secret\n * already exists inside the named store. Nothing creates it: Cloudflare will not\n * generate a value, and the template cannot carry one. So this script is the only\n * thing standing between a fresh account and a deploy that cannot succeed.\n *\n * ### The two defects that hid a broken deploy\n *\n * **The generator list was stale.** Durable-DAV's copy carried an allowlist of\n * exact names from the repository it was inherited from, all deleted when the repo\n * was renamed, so the very first iteration threw `Unknown secret` and never created\n * anything. So the rule here is the secret's **name shape**, not a list of names:\n * `*-encryption-key` gets a generated AES-GCM key and `*-signing-secret` gets 32\n * random bytes. Adding a secret to the template is then a one-line change needing\n * no matching edit here, which is the property the exact-name list did not have.\n *\n * **The throw was swallowed.** The original ended in `main().catch(console.error)`.\n * `console.error` returns `undefined` and never sets an exit status, so the process\n * exited **0** and CI marked the step green — the failure only surfaced one step\n * later, as an unexplainable `wrangler deploy` failure. Hence: the whole plan is\n * validated **before** any Cloudflare call, and a rejection reaches the runner as\n * a non-zero exit with a workflow annotation.\n *\n * ### Create-if-absent is a correctness property, not laziness\n *\n * An existing secret is left untouched. A replication encryption key seals every\n * remote target's credential; regenerating it on a redeploy would strand them all\n * as undecryptable. Rotation has to be a deliberate act with a re-encrypt path,\n * not a side effect of deploying.\n *\n * Requires a materialized `wrangler.jsonc` — run\n * `scripts/prepare-wrangler-config.ts` first. Fails rather than skipping when the\n * config is missing, because a step reporting \"Secret initialization complete\"\n * having created nothing is worse than a named error.\n */\n\nimport { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { parse } from 'jsonc-parser';\nimport { fail } from './lib/github-actions.ts';\nimport { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';\nimport { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';\n\n/**\n * The secret names the AES-GCM key generator produces, matched by **shape**.\n *\n * Keyed on the suffix because the alternative is the exact-name map that went\n * stale. See the header: a template naming `*-encryption-key` is then a one-line\n * change with no matching edit here, and a new secret breaks the deploy loudly\n * instead of silently.\n */\nconst ENCRYPTION_KEY_SUFFIX = '-encryption-key';\n\n/**\nThe secret names the random signing secret generator produces.\n*/\nconst SIGNING_SECRET_SUFFIX = '-signing-secret';\n\n/**\nA 256-bit AES-GCM key, base64-encoded — the shape the worker's crypto layer accepts.\n*/\nasync function generateAESGCMKey(): Promise<string> {\n const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);\n const exported = await crypto.subtle.exportKey('raw', key);\n // Chunked rather than spread: `String.fromCharCode(...bytes)` passes 32 arguments,\n // which is fine today and is a stack overflow the day the key is longer.\n let binary = '';\n for (const byte of new Uint8Array(exported)) {\n binary += String.fromCodePoint(byte);\n }\n return btoa(binary);\n}\n\n/**\nA 256-bit random signing secret for internal self-calls, hex-encoded.\n*/\nfunction generateSigningSecret(): Promise<string> {\n let hex = '';\n for (const byte of crypto.getRandomValues(new Uint8Array(32))) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return Promise.resolve(hex);\n}\n\n/**\n * The generator for a secret name, chosen by the name's shape.\n *\n * A name matching neither is still refused rather than given a guess: the generator\n * is not the only thing that has to be right, and an unusable value that looks\n * provisioned is worse than a failure.\n */\nfunction generatorFor(secretName: string): () => Promise<string> {\n if (secretName.endsWith(ENCRYPTION_KEY_SUFFIX)) return generateAESGCMKey;\n if (secretName.endsWith(SIGNING_SECRET_SUFFIX)) return generateSigningSecret;\n throw new Error(\n `Unknown secret: ${secretName}. Name it '*-encryption-key' for a generated 32-byte AES-GCM key, ` +\n `or '*-signing-secret' for 32 random bytes, and teach this script the shape if neither fits.`,\n );\n}\n\n/**\nWhether this script can produce a value for `secretName`.\n*/\nfunction canProvisionSecret(secretName: string): boolean {\n try {\n generatorFor(secretName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Runs a wrangler subcommand, optionally feeding `input` on stdin.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nfunction wrangler(args: readonly string[], input?: string): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\nfunction parseWranglerConfig(): WranglerConfig {\n if (!existsSync(CONFIG_PATH)) {\n throw new Error(\n `${CONFIG_PATH} not found. Run scripts/prepare-wrangler-config.ts first — it is what creates the file this script reads.`,\n );\n }\n // `parse` is error-tolerant and returns a partial object, so an empty result means\n // malformed JSON rather than \"no secrets declared\". Treating that as an empty list\n // would report success having created nothing.\n const config = parse(readFileSync(CONFIG_PATH, 'utf8')) as WranglerConfig;\n if (config.secrets_store_secrets === undefined && Object.keys(config).length === 0) {\n throw new Error(`${CONFIG_PATH} is empty or not valid JSONC. Run scripts/prepare-wrangler-config.ts to regenerate it.`);\n }\n return config;\n}\n\n/**\nOne secret to create, as the plan names it.\n*/\ninterface PlannedSecret {\n storeId: string;\n secretName: string;\n}\n\n/**\n * Turn the config's bindings into a validated work list.\n *\n * Every entry is checked *before* the first Cloudflare call, so an\n * unprovisionable secret fails the step in milliseconds instead of after some other\n * secret has already been created.\n */\nfunction planSecrets(config: WranglerConfig): PlannedSecret[] {\n const plan: PlannedSecret[] = [];\n for (const [index, secret] of (config.secrets_store_secrets ?? []).entries()) {\n const label = secret.binding ?? `index ${index}`;\n const storeId = secret.store_id;\n const secretName = secret.secret_name;\n if (storeId === undefined || storeId === '' || secretName === undefined || secretName === '') {\n throw new Error(\n `secrets_store_secrets[${index}] (\"${label}\") needs both store_id and secret_name; ` +\n 'store_id is normally filled in by scripts/prepare-wrangler-config.ts.',\n );\n }\n if (!canProvisionSecret(secretName)) {\n throw new Error(`No generator for secret \"${secretName}\" (binding \"${label}\").`);\n }\n plan.push({ storeId, secretName });\n }\n return plan;\n}\n\n/**\n * List the secret names present in a store.\n *\n * Returns `undefined` when the listing itself failed, which is deliberately\n * distinct from an empty set: a transient CLI failure must not be read as \"the\n * secret is missing\" and cause a duplicate insert over a live value. An empty store\n * *is* a confirmed absence, so it maps to an empty set rather than `undefined`.\n *\n * The name is taken exactly. `output.includes(secretName)` is not a membership test:\n * `my-replication-encryption-key-2` satisfies a search for\n * `my-replication-encryption-key`, so a store holding only the suffixed entry would\n * report the unsuffixed one as already present and it would never be created.\n */\nfunction listSecretNames(storeId: string): Set<string> | undefined {\n let output: string;\n try {\n output = wrangler(['secrets-store', 'secret', 'list', storeId, '--remote']);\n } catch (error: unknown) {\n if (isEmptySecretsStoreListing(error)) {\n console.log(`Secrets Store ${storeId} is empty`);\n return new Set();\n }\n console.warn(`Unable to list secrets in store ${storeId}:`, error instanceof Error ? error.message : 'unknown error');\n return undefined;\n }\n return parseWranglerNames(output);\n}\n\nfunction createSecret(storeId: string, secretName: string, secretValue: string): void {\n console.log(`Creating secret: ${secretName}`);\n // The value goes in on stdin, never as an argv entry: an argv is visible to every\n // process on the runner through `ps`, and the previous\n // `echo \"${value}\" | wrangler … ${name}` also broke on `\"`, `$`, backticks and\n // newlines.\n wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);\n}\n\nasync function main(): Promise<void> {\n console.log('Initializing Cloudflare secrets...');\n const config = parseWranglerConfig();\n const plan = planSecrets(config);\n\n if (plan.length === 0) {\n throw new Error('wrangler.jsonc declares no secrets_store_secrets entries, so there is nothing to initialize.');\n }\n\n const listedByStore = new Map<string, Set<string> | undefined>();\n\n for (const { storeId, secretName } of plan) {\n if (!listedByStore.has(storeId)) {\n listedByStore.set(storeId, listSecretNames(storeId));\n }\n const existing = listedByStore.get(storeId);\n if (existing === undefined) {\n // Refuse to guess: creating a secret we could not read back risks overwriting\n // a live value with a freshly generated one.\n throw new Error(`Could not list secrets in store ${storeId}; refusing to create ${secretName} without confirming it is absent.`);\n }\n if (existing.has(secretName)) {\n console.log(`Secret ${secretName} already exists; leaving it untouched.`);\n continue;\n }\n createSecret(storeId, secretName, await generatorFor(secretName)());\n existing.add(secretName);\n }\n\n console.log('Secret initialization complete');\n}\n\n// Top-level await rather than `.catch(console.error)`, so a rejected `main` surfaces\n// as a stack trace with its cause intact and the process exits non-zero. Either way\n// the exit status has to be right: this runs in the deploy pipeline, and swallowing\n// the rejection reported a failed key bootstrap as a green step.\ntry {\n await main();\n} catch (error: unknown) {\n fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));\n}\n"],
5
+ "mappings": ";AA8CA,OAAS,gBAAAA,MAAoB,qBAC7B,OAAS,cAAAC,EAAY,gBAAAC,MAAoB,UACzC,OAAS,SAAAC,MAAa,eACtB,OAAS,QAAAC,MAAY,0BACrB,OAAS,8BAAAC,EAA4B,sBAAAC,MAA0B,0BAC/D,OAAS,eAAAC,MAAwC,6BAUjD,MAAMC,EAAwB,kBAKxBC,EAAwB,kBAK9B,eAAeC,GAAiB,CAC9B,MAAMC,EAAM,MAAM,OAAO,OAAO,YAAY,CAAE,KAAM,UAAW,OAAQ,GAAG,EAAI,GAAM,CAAC,UAAW,SAAS,CAAC,EACpGC,EAAW,MAAM,OAAO,OAAO,UAAU,MAAOD,CAAG,EAGzD,IAAIE,EAAS,GACb,UAAWC,KAAQ,IAAI,WAAWF,CAAQ,EAC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D,CAAM,EAE/B,GAAIE,EAAK,SAAW,EAClB,MAAM,IAAI,MAAM,8FAA8F,EAGhH,MAAMU,EAAgB,IAAI,IAE1B,SAAW,CAAE,QAAAN,EAAS,WAAAhB,CAAU,IAAMY,EAAM,CACrCU,EAAc,IAAIN,CAAO,GAC5BM,EAAc,IAAIN,EAASC,EAAgBD,CAAO,CAAC,EAErD,MAAMO,EAAWD,EAAc,IAAIN,CAAO,EAC1C,GAAIO,IAAa,OAGf,MAAM,IAAI,MAAM,mCAAmCP,CAAO,wBAAwBhB,CAAU,mCAAmC,EAEjI,GAAIuB,EAAS,IAAIvB,CAAU,EAAG,CAC5B,QAAQ,IAAI,UAAUA,CAAU,wCAAwC,EACxE,QACF,CACAmB,EAAaH,EAAShB,EAAY,MAAMD,EAAaC,CAAU,EAAC,CAAE,EAClEuB,EAAS,IAAIvB,CAAU,CACzB,CAEA,QAAQ,IAAI,gCAAgC,CAC9C,CAMA,GAAI,CACF,MAAMqB,EAAI,CACZ,OAAShB,EAAgB,CACvBnB,EAAKmB,aAAiB,MAAQ,iCAAiCA,EAAM,OAAO,GAAK,OAAOA,CAAK,CAAC,CAChG",
6
+ "names": ["execFileSync", "existsSync", "readFileSync", "parse", "fail", "isEmptySecretsStoreListing", "parseWranglerNames", "CONFIG_PATH", "ENCRYPTION_KEY_SUFFIX", "SIGNING_SECRET_SUFFIX", "generateAESGCMKey", "key", "exported", "binary", "byte", "generateSigningSecret", "hex", "generatorFor", "secretName", "canProvisionSecret", "wrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseWranglerConfig", "config", "planSecrets", "plan", "index", "secret", "label", "storeId", "listSecretNames", "output", "createSecret", "secretValue", "main", "listedByStore", "existing"]
7
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"cli-args.d.ts","sourceRoot":"","sources":["../../../src/scripts/lib/cli-args.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH;;GAEG;AACH,MAAM,MA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,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B;;OAEG;IACH,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAC1C;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,GAAG,WAAW,CA2C/E;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAG5E;AAED;;GAEG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,QAAQ,SAAI,GACX;IAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAA;CAAE,CAwB1C"}
@@ -1,116 +1 @@
1
- /**
2
- * Minimal flag parsing for the operator scripts.
3
- *
4
- * Provenance: ported from Edge-Sonic's `scripts/lib/cli-args.ts`, which is the
5
- * only typed arg parser in the family — every other repo reads `process.argv`
6
- * with `includes('--flag')` inline.
7
- *
8
- * The shape is generic: a declared set of value flags and boolean flags, so an
9
- * unknown or valueless flag is rejected **by name** rather than silently ignored.
10
- * A mistyped `--write` must not degrade into "ran with no flags" — which is what
11
- * an inline `argv.includes()` does, and what turns a migration-lock invocation
12
- * that misspelled the flag into a read-only run that reports success.
13
- *
14
- * Usage:
15
- *
16
- * ```ts
17
- * const flags = parseFlags(process.argv.slice(2), {
18
- * boolean: ['write', 'dry-run'],
19
- * value: ['locales-dir', 'root'],
20
- * });
21
- * if (isSet(flags, 'write')) { ... }
22
- * const dir = valueOf(flags, 'locales-dir');
23
- * ```
24
- */
25
- /**
26
- * Parses `--flag value` and `--boolean` pairs out of `argv`.
27
- *
28
- * @throws when a value flag is missing its value, when a flag is repeated, or
29
- * when an undeclared flag is seen. Each case names the offending flag.
30
- */
31
- export function parseFlags(argv, spec) {
32
- const valueFlags = new Set(spec.value);
33
- const booleanFlags = new Set(spec.boolean);
34
- const aliases = spec.alias ?? {};
35
- const flags = new Map();
36
- for (let index = 0; index < argv.length; index += 1) {
37
- const arg = argv[index];
38
- if (!arg.startsWith('-')) {
39
- throw new Error(`Unexpected argument: ${arg}`);
40
- }
41
- const raw = arg.replace(/^--?/, '');
42
- const name = aliases[raw] ?? raw;
43
- if (booleanFlags.has(name)) {
44
- if (flags.has(name)) {
45
- throw new Error(`--${name} was given more than once`);
46
- }
47
- flags.set(name, true);
48
- continue;
49
- }
50
- if (!valueFlags.has(name)) {
51
- throw new Error(`Unknown argument: ${arg}`);
52
- }
53
- if (flags.has(name)) {
54
- throw new Error(`--${name} was given more than once`);
55
- }
56
- const value = argv[index + 1];
57
- // A value that starts with `-` is treated as a missing value so that
58
- // `--to --dry-run` reports the real problem instead of capturing the flag.
59
- if (value === undefined || value.startsWith('-')) {
60
- throw new Error(`--${name} requires a value`);
61
- }
62
- flags.set(name, value);
63
- index += 1;
64
- }
65
- return flags;
66
- }
67
- /**
68
- * Reads a value flag, or `undefined` when it was not supplied.
69
- */
70
- export function valueOf(flags, name) {
71
- const value = flags.get(name);
72
- return typeof value === 'string' ? value : undefined;
73
- }
74
- /**
75
- * Reads a boolean flag, defaulting to `false`.
76
- */
77
- export function isSet(flags, name) {
78
- return flags.get(name) === true;
79
- }
80
- /**
81
- * Split `argv` into its positional arguments and the rest, so a caller can accept
82
- * `tsx script.ts <dir>` alongside `--root <dir>`.
83
- *
84
- * A token that follows a value flag *is* that flag's value, not a positional: the
85
- * naive `argv.filter((arg) => !arg.startsWith('-'))` takes `.` out of
86
- * `--root . --fail-on-hard` and then `parseFlags` reports `--root requires a value`.
87
- * The value flags are passed in rather than inferred, because only the caller knows
88
- * which of its declared flags take one.
89
- *
90
- * @throws when more than `expected` positionals are given, naming them: a second
91
- * directory is far more likely to be a mistyped flag than an intended argument.
92
- */
93
- export function splitPositional(argv, valueFlags, expected = 1) {
94
- const takes = new Set(valueFlags);
95
- const positional = [];
96
- const rest = [];
97
- for (let index = 0; index < argv.length; index += 1) {
98
- const arg = argv[index];
99
- if (arg.startsWith('-')) {
100
- rest.push(arg);
101
- continue;
102
- }
103
- const previous = argv[index - 1];
104
- const isFlagValue = previous !== undefined && previous.startsWith('-') && takes.has(previous.replace(/^--?/, ''));
105
- if (isFlagValue) {
106
- rest.push(arg);
107
- continue;
108
- }
109
- positional.push(arg);
110
- }
111
- if (positional.length > expected) {
112
- throw new Error(`Expected at most ${expected} positional argument(s), got: ${positional.join(', ')}`);
113
- }
114
- return { positional, rest };
115
- }
116
- //# sourceMappingURL=cli-args.js.map
1
+ function h(t,o){const a=new Set(o.value),l=new Set(o.boolean),i=o.alias??{},r=new Map;for(let e=0;e<t.length;e+=1){const s=t[e];if(!s.startsWith("-"))throw new Error(`Unexpected argument: ${s}`);const u=s.replace(/^--?/,""),n=i[u]??u;if(l.has(n)){if(r.has(n))throw new Error(`--${n} was given more than once`);r.set(n,!0);continue}if(!a.has(n))throw new Error(`Unknown argument: ${s}`);if(r.has(n))throw new Error(`--${n} was given more than once`);const c=e+1<t.length?t[e+1]:void 0;if(c===void 0||c.startsWith("-"))throw new Error(`--${n} requires a value`);r.set(n,c),e+=1}return r}function f(t,o){const a=t.get(o);return typeof a=="string"?a:void 0}function w(t,o){return t.get(o)===!0}function g(t,o,a=1){const l=new Set(o),i=[],r=[];for(let e=0;e<t.length;e+=1){const s=t[e];if(s.startsWith("-")){r.push(s);continue}const u=t[e-1];if(u!==void 0&&u.startsWith("-")&&l.has(u.replace(/^--?/,""))){r.push(s);continue}i.push(s)}if(i.length>a)throw new Error(`Expected at most ${a} positional argument(s), got: ${i.join(", ")}`);return{positional:i,rest:r}}export{w as isSet,h as parseFlags,g as splitPositional,f as valueOf};
@@ -1 +1,7 @@
1
- {"version":3,"file":"cli-args.js","sourceRoot":"","sources":["../../../src/scripts/lib/cli-args.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAyBH;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,IAAuB,EAAE,IAAc;IAChE,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACvC,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;IACjC,MAAM,KAAK,GAAgB,IAAI,GAAG,EAAE,CAAC;IAErC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAW,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,wBAAwB,GAAG,EAAE,CAAC,CAAC;QACjD,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC;QAEjC,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3B,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBACpB,MAAM,IAAI,KAAK,CAAC,KAAK,IAAI,2BAA2B,CAAC,CAAC;YACxD,CAAC;YACD,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACtB,SAAS;QACX,CAAC;QAED,IAAI,CAAC,U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GAAa,EAAE,CAAC;IAE1B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAW,CAAC;QAClC,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACf,SAAS;QACX,CAAC;QACD,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,GAAG,CAAC,CAAuB,CAAC;QACvD,MAAM,WAAW,GAAG,QAAQ,KAAK,SAAS,IAAI,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;QAClH,IAAI,WAAW,EAAE,CAAC;YAChB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACf,SAAS;QACX,CAAC;QACD,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,GAAG,QAAQ,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,iCAAiC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACxG,CAAC;IACD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Minimal flag parsing for the operator scripts.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/cli-args.ts`, which is the\n * only typed arg parser in the family — every other repo reads `process.argv`\n * with `includes('--flag')` inline.\n *\n * The shape is generic: a declared set of value flags and boolean flags, so an\n * unknown or valueless flag is rejected **by name** rather than silently ignored.\n * A mistyped `--write` must not degrade into \"ran with no flags\" — which is what\n * an inline `argv.includes()` does, and what turns a migration-lock invocation\n * that misspelled the flag into a read-only run that reports success.\n *\n * Usage:\n *\n * ```ts\n * const flags = parseFlags(process.argv.slice(2), {\n * boolean: ['write', 'dry-run'],\n * value: ['locales-dir', 'root'],\n * });\n * if (isSet(flags, 'write')) { ... }\n * const dir = valueOf(flags, 'locales-dir');\n * ```\n */\n\n/**\n * Parsed flags: value flags map to their string, boolean flags to `true`.\n */\nexport type ParsedFlags = Map<string, string | true>;\n\n/**\n * Declares which flags take a value and which are bare switches.\n */\nexport interface FlagSpec {\n /**\n * `--name` takes a value, e.g. `--to new@example.com`.\n */\n value?: readonly string[];\n /**\n * `--dry-run` takes no value.\n */\n boolean?: readonly string[];\n /**\n * Short form → long form, e.g. `{ h: 'help' }`.\n */\n alias?: Readonly<Record<string, string>>;\n}\n\n/**\n * Parses `--flag value` and `--boolean` pairs out of `argv`.\n *\n * @throws when a value flag is missing its value, when a flag is repeated, or\n * when an undeclared flag is seen. Each case names the offending flag.\n */\nexport function parseFlags(argv: readonly string[], spec: FlagSpec): ParsedFlags {\n const valueFlags = new Set(spec.value);\n const booleanFlags = new Set(spec.boolean);\n const aliases = spec.alias ?? {};\n const flags: ParsedFlags = new Map();\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index] as string;\n if (!arg.startsWith('-')) {\n throw new Error(`Unexpected argument: ${arg}`);\n }\n const raw = arg.replace(/^--?/, '');\n const name = aliases[raw] ?? raw;\n\n if (booleanFlags.has(name)) {\n if (flags.has(name)) {\n throw new Error(`--${name} was given more than once`);\n }\n flags.set(name, true);\n continue;\n }\n\n if (!valueFlags.has(name)) {\n throw new Error(`Unknown argument: ${arg}`);\n }\n if (flags.has(name)) {\n throw new Error(`--${name} was given more than once`);\n }\n\n const value = argv[index + 1];\n // A value that starts with `-` is treated as a missing value so that\n // `--to --dry-run` reports the real problem instead of capturing the flag.\n if (value === undefined || value.startsWith('-')) {\n throw new Error(`--${name} requires a value`);\n }\n flags.set(name, value);\n index += 1;\n }\n\n return flags;\n}\n\n/**\n * Reads a value flag, or `undefined` when it was not supplied.\n */\nexport function valueOf(flags: ParsedFlags, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Reads a boolean flag, defaulting to `false`.\n */\nexport function isSet(flags: ParsedFlags, name: string): boolean {\n return flags.get(name) === true;\n}\n\n/**\n * Split `argv` into its positional arguments and the rest, so a caller can accept\n * `tsx script.ts <dir>` alongside `--root <dir>`.\n *\n * A token that follows a value flag *is* that flag's value, not a positional: the\n * naive `argv.filter((arg) => !arg.startsWith('-'))` takes `.` out of\n * `--root . --fail-on-hard` and then `parseFlags` reports `--root requires a value`.\n * The value flags are passed in rather than inferred, because only the caller knows\n * which of its declared flags take one.\n *\n * @throws when more than `expected` positionals are given, naming them: a second\n * directory is far more likely to be a mistyped flag than an intended argument.\n */\nexport function splitPositional(\n argv: readonly string[],\n valueFlags: readonly string[],\n expected = 1,\n): { positional: string[]; rest: string[] } {\n const takes = new Set(valueFlags);\n const positional: string[] = [];\n const rest: string[] = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index] as string;\n if (arg.startsWith('-')) {\n rest.push(arg);\n continue;\n }\n const previous = argv[index - 1] as string | undefined;\n const isFlagValue = previous !== undefined && previous.startsWith('-') && takes.has(previous.replace(/^--?/, ''));\n if (isFlagValue) {\n rest.push(arg);\n continue;\n }\n positional.push(arg);\n }\n\n if (positional.length > expected) {\n throw new Error(`Expected at most ${expected} positional argument(s), got: ${positional.join(', ')}`);\n }\n return { positional, rest };\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/scripts/lib/cli-args.ts"],
4
+ "sourcesContent": ["/**\n * Minimal flag parsing for the operator scripts.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/cli-args.ts`, which is the\n * only typed arg parser in the family — every other repo reads `process.argv`\n * with `includes('--flag')` inline.\n *\n * The shape is generic: a declared set of value flags and boolean flags, so an\n * unknown or valueless flag is rejected **by name** rather than silently ignored.\n * A mistyped `--write` must not degrade into \"ran with no flags\" — which is what\n * an inline `argv.includes()` does, and what turns a migration-lock invocation\n * that misspelled the flag into a read-only run that reports success.\n *\n * Usage:\n *\n * ```ts\n * const flags = parseFlags(process.argv.slice(2), {\n * boolean: ['write', 'dry-run'],\n * value: ['locales-dir', 'root'],\n * });\n * if (isSet(flags, 'write')) { ... }\n * const dir = valueOf(flags, 'locales-dir');\n * ```\n */\n\n/**\n * Parsed flags: value flags map to their string, boolean flags to `true`.\n */\nexport type ParsedFlags = Map<string, string | true>;\n\n/**\n * Declares which flags take a value and which are bare switches.\n */\nexport interface FlagSpec {\n /**\n * `--name` takes a value, e.g. `--to new@example.com`.\n */\n value?: readonly string[];\n /**\n * `--dry-run` takes no value.\n */\n boolean?: readonly string[];\n /**\n * Short form → long form, e.g. `{ h: 'help' }`.\n */\n alias?: Readonly<Record<string, string>>;\n}\n\n/**\n * Parses `--flag value` and `--boolean` pairs out of `argv`.\n *\n * @throws when a value flag is missing its value, when a flag is repeated, or\n * when an undeclared flag is seen. Each case names the offending flag.\n */\nexport function parseFlags(argv: readonly string[], spec: FlagSpec): ParsedFlags {\n const valueFlags = new Set(spec.value);\n const booleanFlags = new Set(spec.boolean);\n const aliases = spec.alias ?? {};\n const flags: ParsedFlags = new Map();\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (!arg.startsWith('-')) {\n throw new Error(`Unexpected argument: ${arg}`);\n }\n const raw = arg.replace(/^--?/, '');\n const name = aliases[raw] ?? raw;\n\n if (booleanFlags.has(name)) {\n if (flags.has(name)) {\n throw new Error(`--${name} was given more than once`);\n }\n flags.set(name, true);\n continue;\n }\n\n if (!valueFlags.has(name)) {\n throw new Error(`Unknown argument: ${arg}`);\n }\n if (flags.has(name)) {\n throw new Error(`--${name} was given more than once`);\n }\n\n // `argv[index + 1]` is statically a string, but a value flag in last\n // position has no next element at runtime — the length check is what makes\n // the `undefined` below reachable rather than dead.\n const value = index + 1 < argv.length ? argv[index + 1] : undefined;\n // A value that starts with `-` is treated as a missing value so that\n // `--to --dry-run` reports the real problem instead of capturing the flag.\n if (value === undefined || value.startsWith('-')) {\n throw new Error(`--${name} requires a value`);\n }\n flags.set(name, value);\n index += 1;\n }\n\n return flags;\n}\n\n/**\n * Reads a value flag, or `undefined` when it was not supplied.\n */\nexport function valueOf(flags: ParsedFlags, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Reads a boolean flag, defaulting to `false`.\n */\nexport function isSet(flags: ParsedFlags, name: string): boolean {\n return flags.get(name) === true;\n}\n\n/**\n * Split `argv` into its positional arguments and the rest, so a caller can accept\n * `tsx script.ts <dir>` alongside `--root <dir>`.\n *\n * A token that follows a value flag *is* that flag's value, not a positional: the\n * naive `argv.filter((arg) => !arg.startsWith('-'))` takes `.` out of\n * `--root . --fail-on-hard` and then `parseFlags` reports `--root requires a value`.\n * The value flags are passed in rather than inferred, because only the caller knows\n * which of its declared flags take one.\n *\n * @throws when more than `expected` positionals are given, naming them: a second\n * directory is far more likely to be a mistyped flag than an intended argument.\n */\nexport function splitPositional(\n argv: readonly string[],\n valueFlags: readonly string[],\n expected = 1,\n): { positional: string[]; rest: string[] } {\n const takes = new Set(valueFlags);\n const positional: string[] = [];\n const rest: string[] = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (arg.startsWith('-')) {\n rest.push(arg);\n continue;\n }\n const previous = argv[index - 1] as string | undefined;\n const isFlagValue = previous !== undefined && previous.startsWith('-') && takes.has(previous.replace(/^--?/, ''));\n if (isFlagValue) {\n rest.push(arg);\n continue;\n }\n positional.push(arg);\n }\n\n if (positional.length > expected) {\n throw new Error(`Expected at most ${expected} positional argument(s), got: ${positional.join(', ')}`);\n }\n return { positional, rest };\n}\n"],
5
+ "mappings": "AAsDM,SAAUA,EAAWC,EAAyBC,EAAc,CAChE,MAAMC,EAAa,IAAI,IAAID,EAAK,KAAK,EAC/BE,EAAe,IAAI,I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QAASX,EAAQ,EAAGA,EAAQN,EAAK,OAAQM,GAAS,EAAG,CACnD,MAAMC,EAAMP,EAAKM,CAAK,EACtB,GAAIC,EAAI,WAAW,GAAG,EAAG,CACvBU,EAAK,KAAKV,CAAG,EACb,QACF,CACA,MAAMW,EAAWlB,EAAKM,EAAQ,CAAC,EAE/B,GADoBY,IAAa,QAAaA,EAAS,WAAW,GAAG,GAAKH,EAAM,IAAIG,EAAS,QAAQ,OAAQ,EAAE,CAAC,EAC/F,CACfD,EAAK,KAAKV,CAAG,EACb,QACF,CACAS,EAAW,KAAKT,CAAG,CACrB,CAEA,GAAIS,EAAW,OAASF,EACtB,MAAM,IAAI,MAAM,oBAAoBA,CAAQ,iCAAiCE,EAAW,KAAK,IAAI,CAAC,EAAE,EAEtG,MAAO,CAAE,WAAAA,EAAY,KAAAC,CAAI,CAC3B",
6
+ "names": ["parseFlags", "argv", "spec", "valueFlags", "booleanFlags", "aliases", "flags", "index", "arg", "raw", "name", "value", "valueOf", "isSet", "splitPositional", "expected", "takes", "positional", "rest", "previous"]
7
+ }
@@ -1,38 +1,3 @@
1
- /**
2
- * Minimal GitHub Actions step helpers shared by the CI scripts.
3
- *
4
- * Provenance: ported from Edge-Sonic's `scripts/lib/github-actions.ts`, the only
5
- * repo that factored these out. The scripts deliberately avoid `@actions/*`
6
- * dependencies so they stay runnable with plain `tsx` from a local shell, which
7
- * is how they are tested.
8
- */
9
- import { appendFileSync } from 'node:fs';
10
- /**
11
- * Append `name=value` to the step's output file. No-op outside Actions.
12
- */
13
- export function setOutput(name, value) {
14
- const outputFile = process.env.GITHUB_OUTPUT;
15
- if (!outputFile) {
16
- return;
17
- }
18
- appendFileSync(outputFile, `${name}=${value}\n`);
19
- }
20
- /**
21
- * Emit a workflow-command annotation so the failure is visible in the run log.
22
- */
23
- export function logError(message) {
24
- process.stderr.write(`::error::${message}\n`);
25
- }
26
- /**
27
- * Report a fatal error and exit non-zero.
28
- *
29
- * The annotation is written *before* exiting so the reason survives in the run
30
- * log. This is the whole point of the helper: the failure mode it exists to
31
- * prevent is a script that ends in `.catch(console.error)`, which reports success
32
- * while every side effect it was supposed to perform did not happen.
33
- */
34
- export function fail(message) {
35
- logError(message);
36
- process.exit(1);
37
- }
38
- //# sourceMappingURL=github-actions.js.map
1
+ import{appendFileSync as o}from"node:fs";function i(r,e){const t=process.env.GITHUB_OUTPUT;t&&o(t,`${r}=${e}
2
+ `)}function n(r){process.stderr.write(`::error::${r}
3
+ `)}function s(r){n(r),process.exit(1)}export{s as fail,n as logError,i as setOutput};
@@ -1 +1,7 @@
1
- {"version":3,"file":"github-actions.js","sourceRoot":"","sources":["../../../src/scripts/lib/github-actions.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC;IAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO;IACT,CAAC;IACD,cAAc,CAAC,UAAU,EAAE,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;AACnD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAe;IACtC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,OAAO,IAAI,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAC,OAAe;IAClC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAClB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Minimal GitHub Actions step helpers shared by the CI scripts.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/github-actions.ts`, the only\n * repo that factored these out. The scripts deliberately avoid `@actions/*`\n * dependencies so they stay runnable with plain `tsx` from a local shell, which\n * is how they are tested.\n */\n\nimport { appendFileSync } from 'node:fs';\n\n/**\n * Append `name=value` to the step's output file. No-op outside Actions.\n */\nexport function setOutput(name: string, value: string): void {\n const outputFile = process.env.GITHUB_OUTPUT;\n if (!outputFile) {\n return;\n }\n appendFileSync(outputFile, `${name}=${value}\\n`);\n}\n\n/**\n * Emit a workflow-command annotation so the failure is visible in the run log.\n */\nexport function logError(message: string): void {\n process.stderr.write(`::error::${message}\\n`);\n}\n\n/**\n * Report a fatal error and exit non-zero.\n *\n * The annotation is written *before* exiting so the reason survives in the run\n * log. This is the whole point of the helper: the failure mode it exists to\n * prevent is a script that ends in `.catch(console.error)`, which reports success\n * while every side effect it was supposed to perform did not happen.\n */\nexport function fail(message: string): never {\n logError(message);\n process.exit(1);\n}\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/scripts/lib/github-actions.ts"],
4
+ "sourcesContent": ["/**\n * Minimal GitHub Actions step helpers shared by the CI scripts.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/github-actions.ts`, the only\n * repo that factored these out. The scripts deliberately avoid `@actions/*`\n * dependencies so they stay runnable with plain `tsx` from a local shell, which\n * is how they are tested.\n */\n\nimport { appendFileSync } from 'node:fs';\n\n/**\n * Append `name=value` to the step's output file. No-op outside Actions.\n */\nexport function setOutput(name: string, value: string): void {\n const outputFile = process.env.GITHUB_OUTPUT;\n if (!outputFile) {\n return;\n }\n appendFileSync(outputFile, `${name}=${value}\\n`);\n}\n\n/**\n * Emit a workflow-command annotation so the failure is visible in the run log.\n */\nexport function logError(message: string): void {\n process.stderr.write(`::error::${message}\\n`);\n}\n\n/**\n * Report a fatal error and exit non-zero.\n *\n * The annotation is written *before* exiting so the reason survives in the run\n * log. This is the whole point of the helper: the failure mode it exists to\n * prevent is a script that ends in `.catch(console.error)`, which reports success\n * while every side effect it was supposed to perform did not happen.\n */\nexport function fail(message: string): never {\n logError(message);\n process.exit(1);\n}\n"],
5
+ "mappings": "AASA,OAAS,kBAAAA,MAAsB,UAKzB,SAAUC,EAAUC,EAAcC,EAAa,CACnD,MAAMC,EAAa,QAAQ,IAAI,cAC1BA,GAGLJ,EAAeI,EAAY,GAAGF,CAAI,IAAIC,CAAK;CAAI,CACjD,CAKM,SAAUE,EAASC,EAAe,CACtC,QAAQ,OAAO,MAAM,YAAYA,CAAO;CAAI,CAC9C,CAUM,SAAUC,EAAKD,EAAe,CAClCD,EAASC,CAAO,EAChB,QAAQ,KAAK,CAAC,CAChB",
6
+ "names": ["appendFileSync", "setOutput", "name", "value", "outputFile", "logError", "message", "fail"]
7
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"wrangler-table.d.ts","sourceRoot":"","sources":["../../../src/scripts/lib/wrangler-table.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAiBH;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,CAyBjE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAO9D;AASD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAGlE"}
1
+ {"version":3,"file":"wrangler-table.d.ts","sourceRoot":"","sources":["../../../src/scripts/lib/wrangler-table.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAiBH;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,CAyBjE;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAS9D;AASD;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAGlE"}