@rexezuge/tooling 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +67 -34
  2. package/dist/eslint-options.d.ts +54 -0
  3. package/dist/eslint-options.d.ts.map +1 -0
  4. package/dist/eslint-options.js +0 -0
  5. package/dist/eslint-options.js.map +7 -0
  6. package/dist/eslint-rules.d.ts.map +1 -1
  7. package/dist/eslint-rules.js +1 -1
  8. package/dist/eslint-rules.js.map +2 -2
  9. package/dist/eslint-strict.d.ts +2 -1
  10. package/dist/eslint-strict.d.ts.map +1 -1
  11. package/dist/eslint-strict.js +2 -1
  12. package/dist/eslint-strict.js.map +3 -3
  13. package/dist/eslint.d.ts +2 -53
  14. package/dist/eslint.d.ts.map +1 -1
  15. package/dist/eslint.js.map +2 -2
  16. package/dist/manifest-validate.d.ts.map +1 -1
  17. package/dist/manifest-validate.js +1 -1
  18. package/dist/manifest-validate.js.map +3 -3
  19. package/dist/manifest.d.ts +21 -0
  20. package/dist/manifest.d.ts.map +1 -1
  21. package/dist/manifest.js.map +2 -2
  22. package/dist/pages-proxy.d.ts +2 -0
  23. package/dist/pages-proxy.d.ts.map +1 -0
  24. package/dist/pages-proxy.js +1 -0
  25. package/dist/pages-proxy.js.map +7 -0
  26. package/dist/plugin-option.d.ts +15 -0
  27. package/dist/plugin-option.d.ts.map +1 -0
  28. package/dist/plugin-option.js +1 -0
  29. package/dist/plugin-option.js.map +7 -0
  30. package/dist/scripts/backup/destinations.d.ts +40 -0
  31. package/dist/scripts/backup/destinations.d.ts.map +1 -0
  32. package/dist/scripts/backup/destinations.js +1 -0
  33. package/dist/scripts/backup/destinations.js.map +7 -0
  34. package/dist/scripts/backup/encrypt-backup.d.ts +5 -2
  35. package/dist/scripts/backup/encrypt-backup.d.ts.map +1 -1
  36. package/dist/scripts/backup/encrypt-backup.js +2 -3
  37. package/dist/scripts/backup/encrypt-backup.js.map +3 -3
  38. package/dist/scripts/backup/naming.d.ts +1 -1
  39. package/dist/scripts/backup/naming.d.ts.map +1 -1
  40. package/dist/scripts/backup/naming.js +1 -1
  41. package/dist/scripts/backup/naming.js.map +3 -3
  42. package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
  43. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
  44. package/dist/scripts/ensure-spa-shell-stub.js +1 -2
  45. package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
  46. package/dist/scripts/init-secrets.d.ts +1 -2
  47. package/dist/scripts/init-secrets.d.ts.map +1 -1
  48. package/dist/scripts/init-secrets.js +2 -3
  49. package/dist/scripts/init-secrets.js.map +3 -3
  50. package/dist/scripts/migrations-lock.d.ts +6 -2
  51. package/dist/scripts/migrations-lock.d.ts.map +1 -1
  52. package/dist/scripts/migrations-lock.js +1 -2
  53. package/dist/scripts/migrations-lock.js.map +3 -3
  54. package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
  55. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
  56. package/dist/scripts/prepare-wrangler-config.js +1 -2
  57. package/dist/scripts/prepare-wrangler-config.js.map +3 -3
  58. package/dist/scripts/validate-locales.d.ts +20 -2
  59. package/dist/scripts/validate-locales.d.ts.map +1 -1
  60. package/dist/scripts/validate-locales.js +5 -5
  61. package/dist/scripts/validate-locales.js.map +3 -3
  62. package/dist/scripts/verify-spa-shell.d.ts +7 -2
  63. package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
  64. package/dist/scripts/verify-spa-shell.js +1 -2
  65. package/dist/scripts/verify-spa-shell.js.map +3 -3
  66. package/dist/scripts/wrangler-config/resources.d.ts +11 -2
  67. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  68. package/dist/scripts/wrangler-config/resources.js +1 -1
  69. package/dist/scripts/wrangler-config/resources.js.map +3 -3
  70. package/dist/vite.d.ts +2 -1
  71. package/dist/vite.d.ts.map +1 -1
  72. package/dist/vite.js +3 -3
  73. package/dist/vite.js.map +3 -3
  74. package/dist/vitest-aliases.d.ts +7 -1
  75. package/dist/vitest-aliases.d.ts.map +1 -1
  76. package/dist/vitest-aliases.js +1 -1
  77. package/dist/vitest-aliases.js.map +3 -3
  78. package/dist/vitest-integration.d.ts +3 -2
  79. package/dist/vitest-integration.d.ts.map +1 -1
  80. package/dist/vitest-integration.js +1 -1
  81. package/dist/vitest-integration.js.map +3 -3
  82. package/dist/vitest-repo.d.ts +3 -2
  83. package/dist/vitest-repo.d.ts.map +1 -1
  84. package/dist/vitest-repo.js +1 -1
  85. package/dist/vitest-repo.js.map +3 -3
  86. package/dist/vitest-web.d.ts +3 -2
  87. package/dist/vitest-web.d.ts.map +1 -1
  88. package/dist/vitest-web.js +1 -1
  89. package/dist/vitest-web.js.map +3 -3
  90. package/dist/vitest.d.ts +4 -3
  91. package/dist/vitest.d.ts.map +1 -1
  92. package/dist/vitest.js +1 -1
  93. package/dist/vitest.js.map +3 -3
  94. package/package.json +3 -3
  95. package/presets/tsconfig/web.json +2 -2
  96. package/schema/manifest.schema.json +28 -1
  97. package/src/eslint-options.ts +54 -0
  98. package/src/eslint-rules.ts +4 -0
  99. package/src/eslint-strict.test.ts +29 -0
  100. package/src/eslint-strict.ts +36 -4
  101. package/src/eslint.ts +2 -53
  102. package/src/github/dependabot.yml +14 -4
  103. package/src/github/workflows/backup-d1.yml +15 -0
  104. package/src/github/workflows/backup-main.yml +9 -126
  105. package/src/github/workflows/continuous-deployment.yml +11 -180
  106. package/src/github/workflows/continuous-integration.yml +9 -249
  107. package/src/github/workflows/scheduled-version-update.yml +8 -31
  108. package/src/github/workflows/upstream-sync.yml +8 -49
  109. package/src/manifest-validate.ts +31 -2
  110. package/src/manifest.test.ts +22 -0
  111. package/src/manifest.ts +22 -0
  112. package/src/pages-proxy.test.ts +8 -0
  113. package/src/pages-proxy.ts +13 -0
  114. package/src/plugin-option.test.ts +13 -0
  115. package/src/plugin-option.ts +18 -0
  116. package/src/presets.test.ts +5 -1
  117. package/src/scripts/backup/backup-rules.test.ts +22 -0
  118. package/src/scripts/backup/destinations.ts +59 -0
  119. package/src/scripts/backup/encrypt-backup.ts +58 -48
  120. package/src/scripts/backup/naming.ts +2 -2
  121. package/src/scripts/ensure-spa-shell-stub.ts +18 -10
  122. package/src/scripts/entrypoints.test.ts +55 -0
  123. package/src/scripts/init-secrets.ts +8 -6
  124. package/src/scripts/migrations-lock.ts +22 -17
  125. package/src/scripts/prepare-wrangler-config.ts +34 -14
  126. package/src/scripts/validate-locales.ts +39 -17
  127. package/src/scripts/verify-spa-shell.ts +21 -20
  128. package/src/scripts/wrangler-config/resources.test.ts +10 -0
  129. package/src/scripts/wrangler-config/resources.ts +21 -4
  130. package/src/vite.ts +5 -3
  131. package/src/vitest-aliases.test.ts +33 -0
  132. package/src/vitest-aliases.ts +37 -7
  133. package/src/vitest-integration.ts +7 -8
  134. package/src/vitest-repo.ts +7 -5
  135. package/src/vitest-web.ts +7 -5
  136. package/src/vitest.ts +8 -6
  137. package/src/github/actions/retry-step/action.yml +0 -55
  138. package/src/github/actions/setup-env/action.yml +0 -20
package/src/manifest.ts CHANGED
@@ -37,6 +37,18 @@ export interface ManifestD1 {
37
37
  readonly migrationsDir?: string;
38
38
  }
39
39
 
40
+ export interface ManifestKv {
41
+ /**
42
+ KV binding names the deployment needs (UPPER_SNAKE). `prepare-wrangler` adds any a hand-written config lacks and provisions
43
+ their namespaces; a repo that declares none gets no KV binding and no namespace.
44
+ */
45
+ readonly bindings: readonly string[];
46
+ /**
47
+ Binding to namespace name, for a namespace that predates the kit's `<worker>-<binding>` convention. Keys must be listed in `bindings`.
48
+ */
49
+ readonly namespaceNames?: Readonly<Record<string, string>>;
50
+ }
51
+
40
52
  export interface ManifestWeb {
41
53
  /**
42
54
  The SPA is served by Cloudflare Pages.
@@ -46,10 +58,20 @@ export interface ManifestWeb {
46
58
  The SPA shell is embedded into the worker (`spa-shell` scripts).
47
59
  */
48
60
  readonly spaShell: boolean;
61
+ /**
62
+ A **root** `package.json` script that builds the SPA, for a repo whose build has wrappers (`verify:tailwind && build`).
63
+ CI and CD run `pnpm run <script>` instead of `pnpm --filter <scope>/web run build`.
64
+ */
65
+ readonly buildScript?: string;
66
+ /**
67
+ The Cloudflare Pages project, when it is not `<name>-web`. Wins over the `CLOUDFLARE_PAGES_PROJECT_NAME` variable.
68
+ */
69
+ readonly pagesProject?: string;
49
70
  }
50
71
 
51
72
  export interface ManifestFeatures {
52
73
  readonly d1?: ManifestD1;
74
+ readonly kv?: ManifestKv;
53
75
  readonly web?: ManifestWeb;
54
76
  readonly background?: boolean;
55
77
  readonly backupD1?: boolean;
@@ -0,0 +1,8 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { onRequest } from './pages-proxy.ts';
3
+
4
+ describe('pages-proxy re-export', () => {
5
+ it('is the default proxy handler', () => {
6
+ expect(typeof onRequest).toBe('function');
7
+ });
8
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The whole `functions/[[path]].ts` of a Pages project that proxies to `API_WORKER`, as a re-export:
3
+ *
4
+ * ```ts
5
+ * export { onRequest } from '@rexezuge/tooling/pages-proxy';
6
+ * ```
7
+ *
8
+ * The default `createPagesProxy()`. A repo that needs an option (`forwardClientIp: false`) keeps
9
+ * the two-line `createPagesProxy({ ... })` form from `@rexezuge/tooling/functions/pages-proxy`.
10
+ */
11
+ import { createPagesProxy } from './functions/pages-proxy.ts';
12
+
13
+ export const onRequest = createPagesProxy();
@@ -0,0 +1,13 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { asVitePlugins } from './plugin-option.ts';
3
+ import type { PluginOption } from './plugin-option.ts';
4
+
5
+ describe('asVitePlugins', () => {
6
+ it('passes plugins, nested arrays and falsy placeholders through in order, as a copy', () => {
7
+ const plugin = { name: 'p' };
8
+ const input: PluginOption[] = [plugin, [{ name: 'q' }], false, null, undefined];
9
+ const output = asVitePlugins(input);
10
+ expect(output).toEqual(input);
11
+ expect(output).not.toBe(input);
12
+ });
13
+ });
@@ -0,0 +1,18 @@
1
+ import type { ViteUserConfig } from 'vitest/config';
2
+
3
+ /**
4
+ * What a `plugins` option accepts: whatever a Vite `plugins` array does (a plugin, a nested array of them as
5
+ * `@vitejs/plugin-react` and `@tailwindcss/vite` return, a promise, a falsy placeholder).
6
+ *
7
+ * Deliberately structural rather than Vite's own `PluginOption`: the app's `vite` and the `vite` that
8
+ * `vitest` brings are separate installs more often than not, and their `Plugin` types are not assignable to
9
+ * each other even at the same version ("Excessive stack depth comparing types"). The kit never inspects a plugin.
10
+ */
11
+ export type PluginOption = object | false | null | undefined;
12
+
13
+ /**
14
+ * Hand the plugins to Vite. One assertion, here, for the reason above.
15
+ */
16
+ export function asVitePlugins(plugins: readonly PluginOption[]): NonNullable<ViteUserConfig['plugins']> {
17
+ return [...plugins] as NonNullable<ViteUserConfig['plugins']>;
18
+ }
@@ -32,7 +32,11 @@ describe('tsconfig presets', () => {
32
32
  expect(worker.extends).toBe('./base.json');
33
33
  expect(web.extends).toBe('./base.json');
34
34
  expect(worker.compilerOptions['lib']).toEqual(['ES2022', 'DOM']);
35
- expect(web.compilerOptions).toMatchObject({ jsx: 'react-jsx', target: 'ES2020', lib: ['ES2020', 'DOM', 'DOM.Iterable'] });
35
+ expect(web.compilerOptions).toMatchObject({ jsx: 'react-jsx', target: 'ES2022', lib: ['ES2022', 'DOM', 'DOM.Iterable'] });
36
+ // The SPA type-checks the shared contracts package, so it may never be behind the base on target or lib.
37
+ expect(web.compilerOptions['target']).toBe(base['target']);
38
+ expect(web.compilerOptions['lib']).toEqual(expect.arrayContaining(base['lib'] as string[]));
39
+ expect(worker.compilerOptions['lib']).toEqual(base['lib']);
36
40
  });
37
41
  });
38
42
 
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { resolveD1Target } from './d1-target.ts';
3
3
  import { evaluateConfig } from './destination-config.ts';
4
+ import { backupPrefix, isBackupArtifact, parseS3ListRow, shouldDeleteBackup, webdavTargetDir } from './destinations.ts';
4
5
  import { backupFileName, backupStamp, requireRetentionDays, retentionCutoff } from './naming.ts';
5
6
 
6
7
  describe('resolveD1Target', () => {
@@ -103,3 +104,24 @@ describe('naming', () => {
103
104
  }
104
105
  });
105
106
  });
107
+
108
+ describe('destinations', () => {
109
+ it('prefixes every backup with the repo name, and only prunes backup artifacts older than the cutoff', () => {
110
+ expect(backupPrefix('mail-meow')).toBe('mail-meow/production');
111
+ expect(parseS3ListRow('2026-01-02 03:04:05 123 backup_prod_x.sql.xz.enc')).toStrictEqual({
112
+ fileDate: '2026-01-02',
113
+ fileName: 'backup_prod_x.sql.xz.enc',
114
+ });
115
+ expect(parseS3ListRow('PRE nested/')).toBeUndefined();
116
+ const old = { fileDate: '2026-01-01', fileName: 'a.sql.xz.enc' };
117
+ expect(shouldDeleteBackup(old, '2026-01-02')).toBe(true);
118
+ expect(shouldDeleteBackup(old, '2026-01-01')).toBe(false);
119
+ expect(shouldDeleteBackup({ fileDate: '2020-01-01', fileName: 'notes.txt' }, '2026-01-02')).toBe(false);
120
+ expect(isBackupArtifact('a.sql.gz')).toBe(true);
121
+ });
122
+
123
+ it('resolves the WebDAV directory, falling back to the repo name', () => {
124
+ expect(webdavTargetDir('', 'mail-meow')).toBe('webdav:mail-meow/production');
125
+ expect(webdavTargetDir('custom', 'mail-meow')).toBe('webdav:custom/production');
126
+ });
127
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Where backups land, and which listed objects the retention prune may delete.
3
+ *
4
+ * Provenance: the `s3-prune.ts` and `webdav-target.ts` that Mail-Meow, Edge-Sonic and AWS-AccessBridge each carry,
5
+ * converged with the repo-specific prefix lifted into a parameter (the manifest's `name`). Pure, so the safety rules
6
+ * are asserted without a bucket or a WebDAV host.
7
+ */
8
+
9
+ /**
10
+ * Every backup of one repo lives under `<name>/production`, so a prune can never touch an unrelated object.
11
+ */
12
+ export function backupPrefix(name: string): string {
13
+ return `${name}/production`;
14
+ }
15
+
16
+ export interface BackupListingEntry {
17
+ /**
18
+ `YYYY-MM-DD` as reported by `aws s3 ls`.
19
+ */
20
+ fileDate: string;
21
+ fileName: string;
22
+ }
23
+
24
+ /**
25
+ * True only for files this workflow produced. The prune is the one destructive operation in the backup, so it refuses
26
+ * anything that is not a backup artifact. `.gz` is kept so objects written before the switch to xz still age out.
27
+ */
28
+ export function isBackupArtifact(fileName: string): boolean {
29
+ return (
30
+ fileName.endsWith('.sql.xz') || fileName.endsWith('.sql.xz.enc') || fileName.endsWith('.sql.gz') || fileName.endsWith('.sql.gz.enc')
31
+ );
32
+ }
33
+
34
+ /**
35
+ * Parse one `aws s3 ls` row: `<date> <time> <size> <key>`.
36
+ */
37
+ export function parseS3ListRow(line: string): BackupListingEntry | undefined {
38
+ const fields = line.trim().split(/\s+/);
39
+ return fields.length < 4 ? undefined : { fileDate: fields[0], fileName: fields.slice(3).join(' ') };
40
+ }
41
+
42
+ /**
43
+ * Decide whether a listed object should be pruned. Dates are `YYYY-MM-DD`, so lexicographic and chronological order agree.
44
+ */
45
+ export function shouldDeleteBackup(entry: BackupListingEntry, cutoffDate: string): boolean {
46
+ return isBackupArtifact(entry.fileName) && entry.fileDate < cutoffDate;
47
+ }
48
+
49
+ /**
50
+ * The rclone remote name the WebDAV upload configures from the environment.
51
+ */
52
+ export const WEBDAV_REMOTE = 'webdav';
53
+
54
+ /**
55
+ * Where backups land on the remote, e.g. `webdav:my-app/production`. An empty base path falls back to `name`.
56
+ */
57
+ export function webdavTargetDir(basePath: string, name: string): string {
58
+ return `${WEBDAV_REMOTE}:${basePath || name}/production`;
59
+ }
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Compress and encrypt the exported D1 dump.
4
3
  *
@@ -37,6 +36,7 @@ import { execFileSync } from 'node:child_process';
37
36
  import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
38
37
  import path from 'node:path';
39
38
  import { fail, setOutput } from '../lib/github-actions.ts';
39
+ import { isEntrypoint } from '../lib/entrypoint.ts';
40
40
  import { backupFileName } from './naming.ts';
41
41
 
42
42
  /**
@@ -52,58 +52,68 @@ const SOURCE_FILE = 'backup.sql';
52
52
  */
53
53
  const XZ_ARGS = ['-T0', '-6'];
54
54
 
55
- if (!process.env['BACKUP_ENCRYPTION_KEY']) {
56
- fail('BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database.');
57
- }
55
+ /**
56
+ * Compress and encrypt `backup.sql` in the working directory, remove the plaintext, and publish the file name as the
57
+ * `file` step output. Calls `fail` (exits 1) on any problem, so no unencrypted dump is left for an upload job.
58
+ */
59
+ export async function main(): Promise<void> {
60
+ if (!process.env['BACKUP_ENCRYPTION_KEY']) {
61
+ fail('BACKUP_ENCRYPTION_KEY is not set. Refusing to export an unencrypted database.');
62
+ }
58
63
 
59
- if (!existsSync(SOURCE_FILE)) {
60
- fail(`Expected ${SOURCE_FILE} from the export step, but it does not exist.`);
61
- }
64
+ if (!existsSync(SOURCE_FILE)) {
65
+ fail(`Expected ${SOURCE_FILE} from the export step, but it does not exist.`);
66
+ }
62
67
 
63
- const key = process.env['BACKUP_ENCRYPTION_KEY'];
64
- const file = backupFileName(new Date());
68
+ const key = process.env['BACKUP_ENCRYPTION_KEY'];
69
+ const file = backupFileName(new Date());
65
70
 
66
- let plaintext: string;
67
- try {
68
- plaintext = readFileSync(SOURCE_FILE, 'utf8');
69
- } catch (error: unknown) {
70
- fail(`Could not read ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);
71
- }
71
+ let plaintext: string;
72
+ try {
73
+ plaintext = readFileSync(SOURCE_FILE, 'utf8');
74
+ } catch (error: unknown) {
75
+ fail(`Could not read ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);
76
+ }
72
77
 
73
- if (plaintext === '') {
74
- fail(`${SOURCE_FILE} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);
75
- }
78
+ if (plaintext === '') {
79
+ fail(`${SOURCE_FILE} is empty. An empty dump is not a backup, and uploading one is a false sense of safety.`);
80
+ }
76
81
 
77
- /**
78
- * Compress first, then encrypt.
79
- *
80
- * The order matters: compression over ciphertext buys nothing, and encrypting the
81
- * compressed bytes means the plaintext is never re-materialised on disk at full
82
- * size. Unlike gzip, xz leaves its input in place, so the plaintext SQL has to be
83
- * removed explicitly here or it survives into the artifact store.
84
- */
85
- let compressed: Buffer;
86
- try {
87
- // `xz` is resolved from PATH deliberately: the script runs wherever the
88
- // operator compresses backups, and pinning an absolute path would break
89
- // every platform but one.
90
- // eslint-disable-next-line sonarjs/no-os-command-from-path
91
- compressed = execFileSync('xz', [...XZ_ARGS, '--keep', '--stdout', SOURCE_FILE], { maxBuffer: 512 * 1024 * 1024 });
92
- } catch (error: unknown) {
93
- fail(`xz failed on ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);
94
- }
82
+ /**
83
+ * Compress first, then encrypt.
84
+ *
85
+ * The order matters: compression over ciphertext buys nothing, and encrypting the
86
+ * compressed bytes means the plaintext is never re-materialised on disk at full
87
+ * size. Unlike gzip, xz leaves its input in place, so the plaintext SQL has to be
88
+ * removed explicitly here or it survives into the artifact store.
89
+ */
90
+ let compressed: Buffer;
91
+ try {
92
+ // `xz` is resolved from PATH deliberately: the script runs wherever the
93
+ // operator compresses backups, and pinning an absolute path would break
94
+ // every platform but one.
95
+ // eslint-disable-next-line sonarjs/no-os-command-from-path
96
+ compressed = execFileSync('xz', [...XZ_ARGS, '--keep', '--stdout', SOURCE_FILE], { maxBuffer: 512 * 1024 * 1024 });
97
+ } catch (error: unknown) {
98
+ fail(`xz failed on ${SOURCE_FILE}: ${error instanceof Error ? error.message : String(error)}`);
99
+ }
95
100
 
96
- let envelope: { ciphertext: string; iv: string };
97
- try {
98
- envelope = await encryptSecret(compressed.toString('base64'), key);
99
- } catch (error: unknown) {
100
- // A key that is not 32 base64 bytes, or not valid base64 at all, fails here
101
- // rather than producing a file nothing can open.
102
- fail(`Could not encrypt the dump: ${error instanceof Error ? error.message : String(error)}`);
103
- }
101
+ let envelope: { ciphertext: string; iv: string };
102
+ try {
103
+ envelope = await encryptSecret(compressed.toString('base64'), key);
104
+ } catch (error: unknown) {
105
+ // A key that is not 32 base64 bytes, or not valid base64 at all, fails here
106
+ // rather than producing a file nothing can open.
107
+ fail(`Could not encrypt the dump: ${error instanceof Error ? error.message : String(error)}`);
108
+ }
104
109
 
105
- writeFileSync(file, `${JSON.stringify({ ...envelope, source: path.basename(SOURCE_FILE) }, null, 2)}\n`, 'utf8');
106
- rmSync(SOURCE_FILE, { force: true });
110
+ writeFileSync(file, `${JSON.stringify({ ...envelope, source: path.basename(SOURCE_FILE) }, null, 2)}\n`, 'utf8');
111
+ rmSync(SOURCE_FILE, { force: true });
107
112
 
108
- console.log(`Backup encrypted: ${file} (${compressed.byteLength} compressed bytes)`);
109
- setOutput('file', file);
113
+ console.log(`Backup encrypted: ${file} (${compressed.byteLength} compressed bytes)`);
114
+ setOutput('file', file);
115
+ }
116
+
117
+ if (isEntrypoint(import.meta.url)) {
118
+ await main();
119
+ }
@@ -54,8 +54,8 @@ export function retentionCutoff(now: Date, days: number): string {
54
54
  * `Number()` rather than `parseInt()`: `parseInt('30d')` yields 30, which would
55
55
  * silently accept a mistyped value and prune against the wrong window.
56
56
  */
57
- export function requireRetentionDays(): number {
58
- const raw = process.env['BACKUP_RETENTION_DAYS'];
57
+ export function requireRetentionDays(env: NodeJS.ProcessEnv = process.env): number {
58
+ const raw = env['BACKUP_RETENTION_DAYS'];
59
59
  const days = Number(raw);
60
60
  if (!Number.isFinite(days) || days <= 0) {
61
61
  throw new Error(`BACKUP_RETENTION_DAYS must be a positive number, got ${JSON.stringify(raw)}.`);
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Write a placeholder `apps/api/src/generated/spa-shell.ts` when it is absent.
4
3
  *
@@ -20,15 +19,24 @@
20
19
  */
21
20
  import path from 'node:path';
22
21
  import { fileURLToPath } from 'node:url';
22
+ import { isEntrypoint } from './lib/entrypoint.ts';
23
23
  import { ensureSpaShellStub } from './spa-shell.ts';
24
24
 
25
- const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
26
- const root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);
27
-
28
- const result = ensureSpaShellStub({ root });
25
+ /**
26
+ * Run the stub writer. `args[0]` is the repo root (default: the repo this file sits in).
27
+ */
28
+ export function main(args: readonly string[] = process.argv.slice(2)): number {
29
+ const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
30
+ const root = args[0] === undefined ? repositoryRoot : path.resolve(args[0]);
31
+ const result = ensureSpaShellStub({ root });
32
+ console.log(
33
+ result.created
34
+ ? `ensure-spa-shell-stub: created stub at ${result.path}`
35
+ : `ensure-spa-shell-stub: ${result.path} already present, left untouched`,
36
+ );
37
+ return 0;
38
+ }
29
39
 
30
- console.log(
31
- result.created
32
- ? `ensure-spa-shell-stub: created stub at ${result.path}`
33
- : `ensure-spa-shell-stub: ${result.path} already present, left untouched`,
34
- );
40
+ if (isEntrypoint(import.meta.url)) {
41
+ process.exit(main());
42
+ }
@@ -0,0 +1,55 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { main as ensureStub } from './ensure-spa-shell-stub.ts';
6
+ import { main as lockMigrations } from './migrations-lock.ts';
7
+ import { collectLocaleProblems } from './validate-locales.ts';
8
+ import { main as verifyShell } from './verify-spa-shell.ts';
9
+
10
+ const tmp = (): string => mkdtempSync(path.join(tmpdir(), 'tooling-scripts-'));
11
+
12
+ afterEach(() => vi.restoreAllMocks());
13
+
14
+ describe('script entrypoints export main(args)', () => {
15
+ it('ensure-spa-shell-stub writes the stub once and exits 0', () => {
16
+ const log = vi.spyOn(console, 'log').mockImplementation(vi.fn());
17
+ const root = tmp();
18
+ expect(ensureStub([root])).toBe(0);
19
+ expect(existsSync(path.join(root, 'apps/api/src/generated/spa-shell.ts'))).toBe(true);
20
+ expect(ensureStub([root])).toBe(0);
21
+ expect(log.mock.calls.map(String)).toEqual([expect.stringContaining('created stub'), expect.stringContaining('already present')]);
22
+ });
23
+
24
+ it('verify-spa-shell rejects the stub with exit 1', () => {
25
+ vi.spyOn(console, 'log').mockImplementation(vi.fn());
26
+ const error = vi.spyOn(console, 'error').mockImplementation(vi.fn());
27
+ const root = tmp();
28
+ ensureStub([root]);
29
+ expect(verifyShell([root])).toBe(1);
30
+ expect(error).toHaveBeenCalledWith('SPA shell check failed:');
31
+ });
32
+
33
+ it('migrations-lock records the files and exits 0', () => {
34
+ const log = vi.spyOn(console, 'log').mockImplementation(vi.fn());
35
+ const root = tmp();
36
+ mkdirSync(path.join(root, 'migrations'));
37
+ writeFileSync(path.join(root, 'migrations/0001_init.sql'), 'CREATE TABLE t (id TEXT);\n');
38
+ expect(lockMigrations([path.join(root, 'migrations')])).toBe(0);
39
+ expect(readFileSync(path.join(root, 'migrations/migrations.lock.json'), 'utf8')).toContain('0001_init.sql');
40
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('1 migration(s) recorded'));
41
+ });
42
+ });
43
+
44
+ describe('collectLocaleProblems', () => {
45
+ it('returns the findings as data without printing', () => {
46
+ const root = tmp();
47
+ mkdirSync(path.join(root, 'en'));
48
+ mkdirSync(path.join(root, 'de'));
49
+ writeFileSync(path.join(root, 'en/translation.json'), JSON.stringify({ a: 'A', b: 'B' }));
50
+ writeFileSync(path.join(root, 'de/translation.json'), JSON.stringify({ a: 'A' }));
51
+ const { report, problems } = collectLocaleProblems({ dir: root });
52
+ expect(report.locales).toContain('de');
53
+ expect(problems.some((problem) => problem.locale === 'de')).toBe(true);
54
+ });
55
+ });
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh
4
3
  * value for each one that does not exist yet.
@@ -47,6 +46,7 @@
47
46
  import { execFileSync } from 'node:child_process';
48
47
  import { existsSync, readFileSync } from 'node:fs';
49
48
  import { parse } from 'jsonc-parser';
49
+ import { isEntrypoint } from './lib/entrypoint.ts';
50
50
  import { fail } from './lib/github-actions.ts';
51
51
  import { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';
52
52
  import { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';
@@ -230,7 +230,7 @@ function createSecret(storeId: string, secretName: string, secretValue: string):
230
230
  wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);
231
231
  }
232
232
 
233
- async function main(): Promise<void> {
233
+ export async function main(): Promise<void> {
234
234
  console.log('Initializing Cloudflare secrets...');
235
235
  const config = parseWranglerConfig();
236
236
  const plan = planSecrets(config);
@@ -266,8 +266,10 @@ async function main(): Promise<void> {
266
266
  // as a stack trace with its cause intact and the process exits non-zero. Either way
267
267
  // the exit status has to be right: this runs in the deploy pipeline, and swallowing
268
268
  // the rejection reported a failed key bootstrap as a green step.
269
- try {
270
- await main();
271
- } catch (error: unknown) {
272
- fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));
269
+ if (isEntrypoint(import.meta.url)) {
270
+ try {
271
+ await main();
272
+ } catch (error: unknown) {
273
+ fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));
274
+ }
273
275
  }
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Record newly-added migration files in `migrations/migrations.lock.json`.
4
3
  *
@@ -29,23 +28,29 @@
29
28
  */
30
29
  import path from 'node:path';
31
30
  import { fileURLToPath } from 'node:url';
31
+ import { isEntrypoint } from './lib/entrypoint.ts';
32
32
  import { LOCK_NAME, verifyMigrations } from './verify-migrations.ts';
33
33
 
34
- const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
35
- const migrationsDir = process.argv[2] === undefined ? path.join(REPOSITORY_ROOT, 'migrations') : path.resolve(process.argv[2]);
36
-
37
- const report = verifyMigrations(migrationsDir, { write: true });
38
-
39
- for (const problem of report.problems) {
40
- console.error(`FAIL: ${problem.problem}`);
34
+ /**
35
+ * Write the lock. `args[0]` is the migrations directory (default `./migrations`
36
+ * beside the repo this file sits in). Returns the exit code; it is non-zero when a
37
+ * problem the write cannot resolve (an `edited` entry) remains.
38
+ */
39
+ export function main(args: readonly string[] = process.argv.slice(2)): number {
40
+ const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
41
+ const migrationsDir = args[0] === undefined ? path.join(repositoryRoot, 'migrations') : path.resolve(args[0]);
42
+ const report = verifyMigrations(migrationsDir, { write: true });
43
+ for (const problem of report.problems) {
44
+ console.error(`FAIL: ${problem.problem}`);
45
+ }
46
+ console.log(
47
+ `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} (${report.files.length} migration(s) recorded)`,
48
+ );
49
+ // The lock is re-checked by the caller: `verify-migrations.ts` re-reads from disk,
50
+ // so running it after this command reports the same verdict CI will.
51
+ return report.problems.length === 0 ? 0 : 1;
41
52
  }
42
53
 
43
- console.log(
44
- `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} (${report.files.length} migration(s) recorded)`,
45
- );
46
-
47
- // The lock is re-checked by the caller: `verify-migrations.ts` re-reads from disk,
48
- // so running it after this command reports the same verdict CI will. A `--write`
49
- // that could not resolve everything still exits non-zero here, which is why an
50
- // incremental `edited` finding does not vanish just because someone wrote.
51
- process.exit(report.problems.length === 0 ? 0 : 1);
54
+ if (isEntrypoint(import.meta.url)) {
55
+ process.exit(main());
56
+ }
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Materialize `wrangler.jsonc` and provision what it refers to.
4
3
  *
@@ -30,22 +29,43 @@
30
29
  * written verbatim instead of copying the template.
31
30
  * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.
32
31
  * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.
32
+ *
33
+ * KV bindings come from the manifest's `features.kv` (none declared: none added).
33
34
  */
35
+ import { loadManifest } from '../manifest.ts';
34
36
  import { setOutput } from './lib/github-actions.ts';
35
37
  import { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';
36
38
  import { provisionWranglerResources } from './wrangler-config/resources.ts';
39
+ import { isEntrypoint } from './lib/entrypoint.ts';
40
+
41
+ /**
42
+ * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths
43
+ * resolve when `wrangler-config/types.ts` is first imported, so a caller changing
44
+ * directory must do so before importing this module). Returns the created resources.
45
+ */
46
+ export function main(): string[] {
47
+ prepareConfigFile();
48
+ ensureMinimumConfigVersion();
49
+ applyTopLevelPatch();
50
+ applyVarsPatch();
51
+ // KV is manifest-driven: a repo that declares no `features.kv` gets no KV binding and no namespace (no phantom CACHE).
52
+ const kv = loadManifest(process.cwd())?.features?.kv;
53
+ const created = provisionWranglerResources({
54
+ namespaceNames: { ...kv?.namespaceNames },
55
+ requiredKvBindings: kv?.bindings ?? [],
56
+ });
37
57
 
38
- prepareConfigFile();
39
- ensureMinimumConfigVersion();
40
- applyTopLevelPatch();
41
- applyVarsPatch();
42
- const created = provisionWranglerResources();
58
+ // Published as a step output rather than only printed. The backup workflow needs
59
+ // to know whether the D1 database *existed* or was created moments ago: a fresh one
60
+ // holds no user data, and uploading that empty dump every night is a false sense
61
+ // of safety. The alternative — re-reading the placeholder id out of
62
+ // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches
63
+ // the placeholder away before the reader ever runs.
64
+ setOutput('created', created.join(','));
65
+ console.log('Wrangler configuration is ready.');
66
+ return created;
67
+ }
43
68
 
44
- // Published as a step output rather than only printed. The backup workflow needs
45
- // to know whether the D1 database *existed* or was created moments ago: a fresh one
46
- // holds no user data, and uploading that empty dump every night is a false sense
47
- // of safety. The alternative — re-reading the placeholder id out of
48
- // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches
49
- // the placeholder away before the reader ever runs.
50
- setOutput('created', created.join(','));
51
- console.log('Wrangler configuration is ready.');
69
+ if (isEntrypoint(import.meta.url)) {
70
+ main();
71
+ }