@rexezuge/tooling 1.12.0 → 1.14.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 (130) hide show
  1. package/README.md +149 -18
  2. package/dist/eslint-manifest.d.ts +25 -0
  3. package/dist/eslint-manifest.d.ts.map +1 -0
  4. package/dist/eslint-manifest.js +1 -0
  5. package/dist/eslint-manifest.js.map +7 -0
  6. package/dist/eslint-options.d.ts +54 -0
  7. package/dist/eslint-options.d.ts.map +1 -0
  8. package/dist/eslint-options.js +0 -0
  9. package/dist/eslint-options.js.map +7 -0
  10. package/dist/eslint-strict.d.ts +45 -0
  11. package/dist/eslint-strict.d.ts.map +1 -0
  12. package/dist/eslint-strict.js +1 -0
  13. package/dist/eslint-strict.js.map +7 -0
  14. package/dist/eslint.d.ts +2 -36
  15. package/dist/eslint.d.ts.map +1 -1
  16. package/dist/eslint.js +1 -1
  17. package/dist/eslint.js.map +3 -3
  18. package/dist/index.d.ts +5 -2
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +3 -3
  22. package/dist/manifest-validate.d.ts +14 -0
  23. package/dist/manifest-validate.d.ts.map +1 -0
  24. package/dist/manifest-validate.js +1 -0
  25. package/dist/manifest-validate.js.map +7 -0
  26. package/dist/manifest.d.ts +159 -0
  27. package/dist/manifest.d.ts.map +1 -0
  28. package/dist/manifest.js +3 -0
  29. package/dist/manifest.js.map +7 -0
  30. package/dist/pages-proxy.d.ts +2 -0
  31. package/dist/pages-proxy.d.ts.map +1 -0
  32. package/dist/pages-proxy.js +1 -0
  33. package/dist/pages-proxy.js.map +7 -0
  34. package/dist/plugin-option.d.ts +15 -0
  35. package/dist/plugin-option.d.ts.map +1 -0
  36. package/dist/plugin-option.js +1 -0
  37. package/dist/plugin-option.js.map +7 -0
  38. package/dist/scripts/check-god-files.d.ts.map +1 -1
  39. package/dist/scripts/check-god-files.js +2 -2
  40. package/dist/scripts/check-god-files.js.map +3 -3
  41. package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
  42. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
  43. package/dist/scripts/ensure-spa-shell-stub.js +1 -2
  44. package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
  45. package/dist/scripts/init-secrets.d.ts +1 -2
  46. package/dist/scripts/init-secrets.d.ts.map +1 -1
  47. package/dist/scripts/init-secrets.js +2 -3
  48. package/dist/scripts/init-secrets.js.map +3 -3
  49. package/dist/scripts/migrations-lock.d.ts +6 -2
  50. package/dist/scripts/migrations-lock.d.ts.map +1 -1
  51. package/dist/scripts/migrations-lock.js +1 -2
  52. package/dist/scripts/migrations-lock.js.map +3 -3
  53. package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
  54. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
  55. package/dist/scripts/prepare-wrangler-config.js +1 -2
  56. package/dist/scripts/prepare-wrangler-config.js.map +3 -3
  57. package/dist/scripts/validate-locales.d.ts +20 -2
  58. package/dist/scripts/validate-locales.d.ts.map +1 -1
  59. package/dist/scripts/validate-locales.js +5 -5
  60. package/dist/scripts/validate-locales.js.map +3 -3
  61. package/dist/scripts/verify-spa-shell.d.ts +7 -2
  62. package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
  63. package/dist/scripts/verify-spa-shell.js +1 -2
  64. package/dist/scripts/verify-spa-shell.js.map +3 -3
  65. package/dist/test/mocks/cloudflare-workers.d.ts +6 -103
  66. package/dist/test/mocks/cloudflare-workers.d.ts.map +1 -1
  67. package/dist/test/mocks/cloudflare-workers.js +1 -1
  68. package/dist/test/mocks/cloudflare-workers.js.map +3 -3
  69. package/dist/vite.d.ts +2 -1
  70. package/dist/vite.d.ts.map +1 -1
  71. package/dist/vite.js +3 -3
  72. package/dist/vite.js.map +3 -3
  73. package/dist/vitest-aliases.d.ts +3 -0
  74. package/dist/vitest-aliases.d.ts.map +1 -1
  75. package/dist/vitest-aliases.js +1 -1
  76. package/dist/vitest-aliases.js.map +3 -3
  77. package/dist/vitest-integration.d.ts +3 -2
  78. package/dist/vitest-integration.d.ts.map +1 -1
  79. package/dist/vitest-integration.js +1 -1
  80. package/dist/vitest-integration.js.map +3 -3
  81. package/dist/vitest-repo.d.ts +5 -3
  82. package/dist/vitest-repo.d.ts.map +1 -1
  83. package/dist/vitest-repo.js +1 -1
  84. package/dist/vitest-repo.js.map +3 -3
  85. package/dist/vitest-web.d.ts +3 -2
  86. package/dist/vitest-web.d.ts.map +1 -1
  87. package/dist/vitest-web.js +1 -1
  88. package/dist/vitest-web.js.map +3 -3
  89. package/dist/vitest.d.ts +5 -3
  90. package/dist/vitest.d.ts.map +1 -1
  91. package/dist/vitest.js +1 -1
  92. package/dist/vitest.js.map +3 -3
  93. package/package.json +14 -3
  94. package/presets/prettier.d.mts +4 -0
  95. package/presets/prettier.mjs +16 -0
  96. package/presets/tsconfig/base.json +19 -0
  97. package/presets/tsconfig/web.json +10 -0
  98. package/presets/tsconfig/worker.json +9 -0
  99. package/schema/manifest.schema.json +105 -0
  100. package/src/eslint-manifest.ts +71 -0
  101. package/src/eslint-options.ts +54 -0
  102. package/src/eslint-strict.test.ts +106 -0
  103. package/src/eslint-strict.ts +191 -0
  104. package/src/eslint.ts +18 -41
  105. package/src/index.ts +15 -2
  106. package/src/manifest-validate.ts +202 -0
  107. package/src/manifest.test.ts +228 -0
  108. package/src/manifest.ts +194 -0
  109. package/src/pages-proxy.test.ts +8 -0
  110. package/src/pages-proxy.ts +13 -0
  111. package/src/plugin-option.test.ts +13 -0
  112. package/src/plugin-option.ts +18 -0
  113. package/src/presets.test.ts +63 -0
  114. package/src/scripts/check-god-files.ts +3 -0
  115. package/src/scripts/ensure-spa-shell-stub.ts +18 -10
  116. package/src/scripts/entrypoints.test.ts +55 -0
  117. package/src/scripts/init-secrets.ts +8 -6
  118. package/src/scripts/migrations-lock.ts +22 -17
  119. package/src/scripts/prepare-wrangler-config.ts +26 -14
  120. package/src/scripts/validate-locales.ts +39 -17
  121. package/src/scripts/verify-spa-shell.ts +21 -20
  122. package/src/test/mocks/cloudflare-workers.ts +6 -113
  123. package/src/vite.ts +6 -3
  124. package/src/vitest-aliases.test.ts +23 -0
  125. package/src/vitest-aliases.ts +22 -1
  126. package/src/vitest-factories.test.ts +30 -1
  127. package/src/vitest-integration.ts +5 -3
  128. package/src/vitest-repo.ts +10 -5
  129. package/src/vitest-web.ts +5 -3
  130. package/src/vitest.ts +10 -5
@@ -0,0 +1,228 @@
1
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { loadManifest, ManifestError, MANIFEST_FILENAME, manifestCoverageThresholds, parseManifest, validateManifest } from './manifest.ts';
7
+ import { manifestBrowserDirs, manifestHttpDirs, manifestLayerBans } from './eslint-manifest.ts';
8
+
9
+ const MINIMAL = { name: 'mail-meow', scope: '@mail-meow' };
10
+
11
+ const LAYERED = {
12
+ ...MINIMAL,
13
+ layers: [
14
+ { name: 'shared', dir: 'packages/shared', mayImport: [] },
15
+ { name: 'data', dir: 'packages/backend-data', mayImport: ['shared'] },
16
+ { name: 'services', dir: 'packages/backend-services', mayImport: ['shared', 'data'] },
17
+ { name: 'api', dir: 'apps/api', mayImport: ['services', 'shared'], typeOnly: ['data'], http: true, forbid: ['aws4fetch'] },
18
+ { name: 'web', dir: 'apps/web', mayImport: [], browser: true },
19
+ ],
20
+ };
21
+
22
+ function errorsOf(input: unknown): string[] {
23
+ const result = validateManifest(input);
24
+ return result.ok ? [] : result.errors;
25
+ }
26
+
27
+ describe('validateManifest', () => {
28
+ it('accepts the minimal manifest and a full one', () => {
29
+ expect(validateManifest(MINIMAL).ok).toBe(true);
30
+ const full = {
31
+ $schema: './node_modules/@rexezuge/tooling/schema/manifest.schema.json',
32
+ ...LAYERED,
33
+ features: {
34
+ d1: { binding: 'DB', database: 'mail-meow', migrationsDir: 'migrations' },
35
+ web: { pages: true, spaShell: false },
36
+ background: true,
37
+ backupD1: true,
38
+ durableObjects: ['MailboxDO'],
39
+ queues: ['mail'],
40
+ workflows: ['SyncWorkflow'],
41
+ email: true,
42
+ android: false,
43
+ },
44
+ quality: { coverage: { lines: 80, branches: 70, functions: 80, statements: 80 }, godFiles: { soft: 250, hard: 350 } },
45
+ extensions: { 'mail-meow': { anything: [1, 2, 3] } },
46
+ };
47
+ expect(errorsOf(full)).toEqual([]);
48
+ });
49
+
50
+ it('names the field of every problem, all at once', () => {
51
+ const errors = errorsOf({ name: '', scope: 'mail-meow', features: { d1: { binding: 'db' }, bogus: 1 }, extra: true });
52
+ expect(errors).toEqual(
53
+ expect.arrayContaining([
54
+ expect.stringContaining('name: must be a non-empty string'),
55
+ expect.stringContaining('scope: "mail-meow" is invalid'),
56
+ expect.stringContaining('features.d1.binding: "db" is invalid'),
57
+ expect.stringContaining('features.d1.database: must be a non-empty string'),
58
+ expect.stringContaining('features.bogus: unknown key'),
59
+ expect.stringContaining('manifest.extra: unknown key'),
60
+ ]),
61
+ );
62
+ });
63
+
64
+ it('rejects a non-object manifest', () => {
65
+ expect(errorsOf([])).toEqual(['manifest: must be an object']);
66
+ expect(errorsOf(null)).toEqual(['manifest: must be an object']);
67
+ });
68
+
69
+ it('only lets god-file limits be lowered', () => {
70
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 350, hard: 400 } } })).toEqual([
71
+ 'quality.godFiles.soft: 350 is above the family limit 300: god-file limits may only be lowered',
72
+ ]);
73
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 300, hard: 500 } } })[0]).toContain('may only be lowered');
74
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 300, hard: 400 } } })).toEqual([]);
75
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 200, hard: 100 } } })).toEqual([
76
+ 'quality.godFiles.soft: must not exceed quality.godFiles.hard',
77
+ ]);
78
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 0.5, hard: 'x' } } })).toHaveLength(2);
79
+ });
80
+
81
+ it('checks coverage figures', () => {
82
+ expect(errorsOf({ ...MINIMAL, quality: { coverage: { lines: 101, branches: 1, functions: 1, statements: 1 } } })).toEqual([
83
+ 'quality.coverage.lines: must be a number from 0 to 100',
84
+ ]);
85
+ expect(errorsOf({ ...MINIMAL, quality: { coverage: { lines: 1 } } })).toHaveLength(3);
86
+ });
87
+
88
+ it('checks layers: names, dirs, references and the type-only overlap', () => {
89
+ const errors = errorsOf({
90
+ ...MINIMAL,
91
+ layers: [
92
+ { name: 'a', dir: 'packages/a', mayImport: ['ghost'], typeOnly: ['b'] },
93
+ { name: 'a', dir: '../b', mayImport: ['b'], typeOnly: ['b'] },
94
+ { name: 'B', dir: 'packages/*', mayImport: 'nope' },
95
+ 'text',
96
+ ],
97
+ });
98
+ expect(errors).toEqual(
99
+ expect.arrayContaining([
100
+ expect.stringContaining('layers[0].mayImport: unknown layer "ghost"'),
101
+ expect.stringContaining('layers[1].name: duplicate layer name "a"'),
102
+ expect.stringContaining('layers[1].dir: "../b" must be a repo-relative directory'),
103
+ expect.stringContaining('layers[2].dir: "packages/*" must be a repo-relative directory'),
104
+ expect.stringContaining('layers[2].mayImport: must be an array'),
105
+ expect.stringContaining('layers[3]: must be an object'),
106
+ ]),
107
+ );
108
+ expect(errorsOf({ ...MINIMAL, layers: {} })).toEqual(['layers: must be an array of layers']);
109
+ expect(
110
+ errorsOf({
111
+ ...MINIMAL,
112
+ layers: [
113
+ { name: 'a', dir: 'a', mayImport: [], http: 'yes' },
114
+ { name: 'b', dir: 'a', mayImport: ['a'], typeOnly: ['a'] },
115
+ ],
116
+ }),
117
+ ).toEqual(
118
+ expect.arrayContaining([
119
+ expect.stringContaining('layers[0].http: must be a boolean'),
120
+ expect.stringContaining('duplicate layer dir "a"'),
121
+ expect.stringContaining('already in mayImport'),
122
+ ]),
123
+ );
124
+ });
125
+
126
+ it('keeps extensions namespaced objects', () => {
127
+ expect(errorsOf({ ...MINIMAL, extensions: { Bad_Key: {}, ok: 3 } })).toEqual([
128
+ 'extensions.Bad_Key: namespace must be lower-case letters, digits and hyphens',
129
+ 'extensions.ok: must be an object (extensions are namespaced: one object per owner)',
130
+ ]);
131
+ expect(errorsOf({ ...MINIMAL, extensions: [] })).toEqual(['extensions: must be an object']);
132
+ });
133
+
134
+ it('checks feature value types', () => {
135
+ const errors = errorsOf({
136
+ ...MINIMAL,
137
+ features: { web: { pages: 1, spaShell: true, x: 1 }, background: 'yes', queues: [1], d1: [], durableObjects: 'X' },
138
+ });
139
+ expect(errors).toHaveLength(6);
140
+ });
141
+ });
142
+
143
+ describe('parseManifest and loadManifest', () => {
144
+ const dirs: string[] = [];
145
+ afterEach(() => {
146
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
147
+ });
148
+ const repoWith = (text?: string): string => {
149
+ const dir = mkdtempSync(path.join(tmpdir(), 'manifest-'));
150
+ dirs.push(dir);
151
+ if (text !== undefined) writeFileSync(path.join(dir, MANIFEST_FILENAME), text);
152
+ return dir;
153
+ };
154
+
155
+ it('parses JSONC with comments and trailing commas', () => {
156
+ const manifest = parseManifest('{\n // the repo\n "name": "x", "scope": "@x",\n}');
157
+ expect(manifest.scope).toBe('@x');
158
+ });
159
+
160
+ it('reports syntax errors and validation errors as ManifestError', () => {
161
+ expect(() => parseManifest('{ "name": ', 'm.jsonc')).toThrow(/m\.jsonc is not a valid family manifest[\s\S]*syntax error/);
162
+ const failure = (() => {
163
+ try {
164
+ parseManifest('{"name":"x"}');
165
+ } catch (error) {
166
+ return error as ManifestError;
167
+ }
168
+ return null;
169
+ })();
170
+ expect(failure).toBeInstanceOf(ManifestError);
171
+ expect(failure?.errors).toEqual(['scope: must be a non-empty string']);
172
+ });
173
+
174
+ it('loads null when absent, the manifest when present, and throws when invalid', () => {
175
+ expect(loadManifest(repoWith())).toBeNull();
176
+ expect(loadManifest(repoWith('{"name":"x","scope":"@x"}'))?.name).toBe('x');
177
+ expect(() => loadManifest(repoWith('{"name":"x"}'))).toThrow(ManifestError);
178
+ });
179
+
180
+ it('resolves coverage thresholds from a path or a file URL root', () => {
181
+ const dir = repoWith('{"name":"x","scope":"@x","quality":{"coverage":{"lines":1,"branches":2,"functions":3,"statements":4}}}');
182
+ const expected = { lines: 1, branches: 2, functions: 3, statements: 4 };
183
+ expect(manifestCoverageThresholds(dir)).toEqual(expected);
184
+ expect(manifestCoverageThresholds(pathToFileURL(`${dir}/`).href)).toEqual(expected);
185
+ expect(manifestCoverageThresholds(repoWith('{"name":"x","scope":"@x"}'))).toBeUndefined();
186
+ });
187
+ });
188
+
189
+ describe('the shipped JSON Schema', () => {
190
+ const schema = JSON.parse(readFileSync(new URL('../schema/manifest.schema.json', import.meta.url), 'utf8')) as {
191
+ properties: Record<string, { properties?: Record<string, unknown>; items?: { properties: Record<string, unknown> } }>;
192
+ };
193
+
194
+ it('names exactly the keys the validator accepts', () => {
195
+ const validator = (input: unknown): string[] => errorsOf(input).filter((line) => line.includes('unknown key'));
196
+ for (const key of Object.keys(schema.properties)) expect(validator({ ...MINIMAL, [key]: undefined })).toEqual([]);
197
+ expect(validator({ ...MINIMAL, nope: 1 })).toHaveLength(1);
198
+ const unknownIn = (section: string, keys: string[]): string[] =>
199
+ validator({ ...MINIMAL, [section]: Object.fromEntries(keys.map((key) => [key, undefined])) });
200
+ expect(unknownIn('features', Object.keys(schema.properties['features']?.properties ?? {}))).toEqual([]);
201
+ expect(unknownIn('quality', Object.keys(schema.properties['quality']?.properties ?? {}))).toEqual([]);
202
+ const layerKeys = Object.keys(schema.properties['layers']?.items?.properties ?? {});
203
+ expect(validator({ ...MINIMAL, layers: [Object.fromEntries(layerKeys.map((key) => [key, undefined]))] })).toEqual([]);
204
+ });
205
+ });
206
+
207
+ describe('manifest layers as lint boundaries', () => {
208
+ it('derives bans from what each layer may not import', () => {
209
+ const bans = manifestLayerBans(LAYERED as never);
210
+ const of = (dir: string) => bans.filter((ban) => ban.dir === dir);
211
+ expect(of('packages/shared')[0]?.ban).toEqual(['@mail-meow/*']);
212
+ expect(of('packages/backend-data')[0]?.ban).toEqual(['@mail-meow/backend-services', '@mail-meow/api', '@mail-meow/web']);
213
+ const api = of('apps/api');
214
+ expect(api[0]?.ban).toEqual(['@mail-meow/web']);
215
+ expect(api.find((ban) => ban.allowTypeImports === true)?.ban).toEqual(['@mail-meow/backend-data']);
216
+ expect(api.find((ban) => ban.ban.includes('aws4fetch'))?.message).toBe('api may not import this package');
217
+ expect(of('apps/web')[0]?.ban).toEqual(['@mail-meow/*']);
218
+ });
219
+
220
+ it('lists http and browser dirs', () => {
221
+ expect(manifestHttpDirs(LAYERED as never)).toEqual(['apps/api']);
222
+ expect(manifestHttpDirs(null)).toEqual([]);
223
+ expect(manifestBrowserDirs(null)).toEqual(['apps/web']);
224
+ expect(manifestBrowserDirs(LAYERED as never)).toEqual(['apps/web']);
225
+ expect(manifestBrowserDirs(MINIMAL as never)).toEqual([]);
226
+ expect(manifestBrowserDirs({ ...MINIMAL, features: { web: { pages: true, spaShell: true } } })).toEqual(['apps/web']);
227
+ });
228
+ });
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The family manifest: `.rexezuge.jsonc` at a repo root.
3
+ *
4
+ * One declarative file states what a repo *is* (its scope, the platform features
5
+ * it uses, its dependency layers) and how strict it holds itself (coverage
6
+ * floors, god-file limits). The tooling factories read it instead of each
7
+ * encoding consumer directory names, so the kit stays free of repo layouts and a
8
+ * repo's layout stays out of its lint config.
9
+ *
10
+ * The charter applies to the file itself. The **closed** side is the schema:
11
+ * unknown keys are refused (a typo is an error, not a silent no-op), and
12
+ * `quality.godFiles` may only be lowered below the family default, never raised.
13
+ * The **open** side is `extensions`: a free-form object, namespaced by the key
14
+ * that owns it, that the kit never reads.
15
+ *
16
+ * `manifest.schema.json` (shipped beside this module) describes the same shape
17
+ * for editor completion via `$schema`; a test keeps the two in step.
18
+ */
19
+
20
+ import { existsSync, readFileSync } from 'node:fs';
21
+ import path from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
24
+ import type { ParseError } from 'jsonc-parser';
25
+ import { validateManifest } from './manifest-validate.ts';
26
+
27
+ export { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';
28
+
29
+ /**
30
+ The file name, resolved against a repo root.
31
+ */
32
+ export const MANIFEST_FILENAME = '.rexezuge.jsonc';
33
+
34
+ export interface ManifestD1 {
35
+ readonly binding: string;
36
+ readonly database: string;
37
+ readonly migrationsDir?: string;
38
+ }
39
+
40
+ export interface ManifestWeb {
41
+ /**
42
+ The SPA is served by Cloudflare Pages.
43
+ */
44
+ readonly pages: boolean;
45
+ /**
46
+ The SPA shell is embedded into the worker (`spa-shell` scripts).
47
+ */
48
+ readonly spaShell: boolean;
49
+ }
50
+
51
+ export interface ManifestFeatures {
52
+ readonly d1?: ManifestD1;
53
+ readonly web?: ManifestWeb;
54
+ readonly background?: boolean;
55
+ readonly backupD1?: boolean;
56
+ /**
57
+ Durable Object class names.
58
+ */
59
+ readonly durableObjects?: readonly string[];
60
+ /**
61
+ Queue names.
62
+ */
63
+ readonly queues?: readonly string[];
64
+ /**
65
+ Workflow class names.
66
+ */
67
+ readonly workflows?: readonly string[];
68
+ readonly email?: boolean;
69
+ readonly android?: boolean;
70
+ }
71
+
72
+ /**
73
+ * One dependency layer: a directory, and the other layers it may import.
74
+ *
75
+ * Everything not named in `mayImport` / `typeOnly` is banned, by package name
76
+ * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer
77
+ * from the whole scope (`<scope>/*`).
78
+ */
79
+ export interface ManifestLayer {
80
+ readonly name: string;
81
+ /**
82
+ Repo-relative directory, no globs: `packages/backend-data`.
83
+ */
84
+ readonly dir: string;
85
+ /**
86
+ Package suffix when it is not the directory's basename.
87
+ */
88
+ readonly package?: string;
89
+ /**
90
+ Names of layers this layer may import.
91
+ */
92
+ readonly mayImport: readonly string[];
93
+ /**
94
+ Names of layers importable as `import type` only.
95
+ */
96
+ readonly typeOnly?: readonly string[];
97
+ /**
98
+ Extra external specifiers this layer may not import, e.g. `aws4fetch`.
99
+ */
100
+ readonly forbid?: readonly string[];
101
+ /**
102
+ Message for `forbid`; defaults to a generic one.
103
+ */
104
+ readonly forbidMessage?: string;
105
+ /**
106
+ May import `hono`/`chanfana` (and hand-build error envelopes).
107
+ */
108
+ readonly http?: boolean;
109
+ /**
110
+ Browser code: may use `console`, and lints with browser globals.
111
+ */
112
+ readonly browser?: boolean;
113
+ }
114
+
115
+ export interface ManifestCoverage {
116
+ readonly lines: number;
117
+ readonly branches: number;
118
+ readonly functions: number;
119
+ readonly statements: number;
120
+ }
121
+
122
+ export interface ManifestQuality {
123
+ readonly coverage?: ManifestCoverage;
124
+ readonly godFiles?: { readonly soft: number; readonly hard: number };
125
+ }
126
+
127
+ export interface FamilyManifest {
128
+ readonly $schema?: string;
129
+ readonly name: string;
130
+ /**
131
+ npm scope with the `@`, e.g. `@mail-meow`.
132
+ */
133
+ readonly scope: string;
134
+ readonly features?: ManifestFeatures;
135
+ readonly layers?: readonly ManifestLayer[];
136
+ readonly quality?: ManifestQuality;
137
+ /**
138
+ Repo-specific settings, namespaced by key. Never read by the kit.
139
+ */
140
+ readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
141
+ }
142
+
143
+ export type ManifestValidation =
144
+ { readonly ok: true; readonly manifest: FamilyManifest } | { readonly ok: false; readonly errors: string[] };
145
+
146
+ /**
147
+ Thrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.
148
+ */
149
+ export class ManifestError extends Error {
150
+ readonly errors: readonly string[];
151
+ constructor(source: string, errors: readonly string[]) {
152
+ super(`${source} is not a valid family manifest:\n${errors.map((line) => ` - ${line}`).join('\n')}`);
153
+ this.name = 'ManifestError';
154
+ this.errors = errors;
155
+ }
156
+ }
157
+
158
+ /**
159
+ Parse JSONC text and validate it. Throws {@link ManifestError}.
160
+ */
161
+ export function parseManifest(text: string, source: string = MANIFEST_FILENAME): FamilyManifest {
162
+ const syntax: ParseError[] = [];
163
+ const value: unknown = parseJsonc(text, syntax, { allowTrailingComma: true });
164
+ if (syntax.length > 0) {
165
+ throw new ManifestError(
166
+ source,
167
+ syntax.map((error) => `syntax error at offset ${error.offset}: ${printParseErrorCode(error.error)}`),
168
+ );
169
+ }
170
+ const result = validateManifest(value);
171
+ if (!result.ok) throw new ManifestError(source, result.errors);
172
+ return result.manifest;
173
+ }
174
+
175
+ /**
176
+ * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the
177
+ * repo has not adopted a manifest) and throws {@link ManifestError} when it is
178
+ * present but invalid: a broken manifest must fail the gate, not fall back.
179
+ */
180
+ export function loadManifest(root: string): FamilyManifest | null {
181
+ const file = path.join(root, MANIFEST_FILENAME);
182
+ if (!existsSync(file)) return null;
183
+ return parseManifest(readFileSync(file, 'utf8'), file);
184
+ }
185
+
186
+ /**
187
+ * The manifest's coverage floor for a vitest config, or `undefined` when the
188
+ * repo has no manifest or declares none. `root` is what the factories take: a
189
+ * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).
190
+ */
191
+ export function manifestCoverageThresholds(root: string): ManifestCoverage | undefined {
192
+ const dir = root.startsWith('file:') ? fileURLToPath(root) : root;
193
+ return loadManifest(dir)?.quality?.coverage;
194
+ }
@@ -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
+ }
@@ -0,0 +1,63 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { parse } from 'jsonc-parser';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ const here = (path: string): URL => new URL(`../${path}`, import.meta.url);
6
+ const json = <T>(path: string): T => parse(readFileSync(here(path), 'utf8')) as T;
7
+
8
+ interface TsConfig {
9
+ extends?: string;
10
+ compilerOptions: Record<string, unknown>;
11
+ }
12
+
13
+ describe('tsconfig presets', () => {
14
+ const base = json<TsConfig>('presets/tsconfig/base.json').compilerOptions;
15
+ const worker = json<TsConfig>('presets/tsconfig/worker.json');
16
+ const web = json<TsConfig>('presets/tsconfig/web.json');
17
+
18
+ it('base carries the options the family copies shared', () => {
19
+ expect(base).toMatchObject({
20
+ target: 'ES2022',
21
+ module: 'ES2022',
22
+ moduleResolution: 'Bundler',
23
+ strict: true,
24
+ isolatedModules: true,
25
+ noEmit: true,
26
+ skipLibCheck: true,
27
+ resolveJsonModule: true,
28
+ });
29
+ });
30
+
31
+ it('worker and web extend base; web adds the DOM libs and the JSX transform', () => {
32
+ expect(worker.extends).toBe('./base.json');
33
+ expect(web.extends).toBe('./base.json');
34
+ expect(worker.compilerOptions['lib']).toEqual(['ES2022', 'DOM']);
35
+ expect(web.compilerOptions).toMatchObject({ jsx: 'react-jsx', target: 'ES2020', lib: ['ES2020', 'DOM', 'DOM.Iterable'] });
36
+ });
37
+ });
38
+
39
+ describe('prettier preset', () => {
40
+ it('matches the .prettierrc the family repos carried', async () => {
41
+ const { default: config } = (await import('../presets/prettier.mjs')) as { default: unknown };
42
+ expect(config).toEqual({ printWidth: 140, singleQuote: true, semi: true, useTabs: false });
43
+ });
44
+ });
45
+
46
+ describe('package exports', () => {
47
+ const pkg = json<{ exports: Record<string, unknown>; files: string[] }>('package.json');
48
+
49
+ it('maps every preset and the schema to a file that ships', () => {
50
+ for (const key of ['./tsconfig/base.json', './tsconfig/worker.json', './tsconfig/web.json', './manifest.schema.json', './prettier']) {
51
+ const target = pkg.exports[key];
52
+ const file = typeof target === 'string' ? target : (target as { default: string }).default;
53
+ expect(existsSync(here(file)), `${key} -> ${file}`).toBe(true);
54
+ expect(pkg.files).toContain(file.split('/', 2)[1]);
55
+ }
56
+ });
57
+
58
+ it('lists the explicit entries before the `./*` wildcard that would shadow them', () => {
59
+ const keys = Object.keys(pkg.exports);
60
+ expect(keys.indexOf('./tsconfig/base.json')).toBeLessThan(keys.indexOf('./*'));
61
+ expect(keys.indexOf('./prettier')).toBeLessThan(keys.indexOf('./*'));
62
+ });
63
+ });
@@ -51,6 +51,7 @@ import path from 'node:path';
51
51
  import { fail } from './lib/github-actions.ts';
52
52
  import { isEntrypoint } from './lib/entrypoint.ts';
53
53
  import { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';
54
+ import { loadManifest } from '../manifest.ts';
54
55
 
55
56
  /**
56
57
  * A file past a size the guard reports on.
@@ -329,6 +330,8 @@ export function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)
329
330
  const report = checkGodFiles({
330
331
  root,
331
332
  allowlist: readAllowlist(allowlistPath),
333
+ // A manifest may only lower the family limits (the validator refuses more).
334
+ ...loadManifest(root)?.quality?.godFiles,
332
335
  failOnHard: isSet(flags, 'fail-on-hard'),
333
336
  });
334
337
  console.log(report.reported);
@@ -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
+ });