@rexezuge/tooling 0.0.0-stage → 1.0.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 (160) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +297 -2
  3. package/dist/eslint.d.ts +120 -0
  4. package/dist/eslint.d.ts.map +1 -0
  5. package/dist/eslint.js +551 -0
  6. package/dist/eslint.js.map +1 -0
  7. package/dist/functions/pages-proxy.d.ts +113 -0
  8. package/dist/functions/pages-proxy.d.ts.map +1 -0
  9. package/dist/functions/pages-proxy.js +131 -0
  10. package/dist/functions/pages-proxy.js.map +1 -0
  11. package/dist/index.d.ts +31 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +28 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/scripts/backup/d1-target.d.ts +35 -0
  16. package/dist/scripts/backup/d1-target.d.ts.map +1 -0
  17. package/dist/scripts/backup/d1-target.js +31 -0
  18. package/dist/scripts/backup/d1-target.js.map +1 -0
  19. package/dist/scripts/backup/destination-config.d.ts +61 -0
  20. package/dist/scripts/backup/destination-config.d.ts.map +1 -0
  21. package/dist/scripts/backup/destination-config.js +57 -0
  22. package/dist/scripts/backup/destination-config.js.map +1 -0
  23. package/dist/scripts/backup/encrypt-backup.d.ts +35 -0
  24. package/dist/scripts/backup/encrypt-backup.d.ts.map +1 -0
  25. package/dist/scripts/backup/encrypt-backup.js +98 -0
  26. package/dist/scripts/backup/encrypt-backup.js.map +1 -0
  27. package/dist/scripts/backup/naming.d.ts +44 -0
  28. package/dist/scripts/backup/naming.d.ts.map +1 -0
  29. package/dist/scripts/backup/naming.js +58 -0
  30. package/dist/scripts/backup/naming.js.map +1 -0
  31. package/dist/scripts/check-god-files.d.ts +164 -0
  32. package/dist/scripts/check-god-files.d.ts.map +1 -0
  33. package/dist/scripts/check-god-files.js +271 -0
  34. package/dist/scripts/check-god-files.js.map +1 -0
  35. package/dist/scripts/ensure-spa-shell-stub.d.ts +3 -0
  36. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -0
  37. package/dist/scripts/ensure-spa-shell-stub.js +30 -0
  38. package/dist/scripts/ensure-spa-shell-stub.js.map +1 -0
  39. package/dist/scripts/init-secrets.d.ts +63 -0
  40. package/dist/scripts/init-secrets.d.ts.map +1 -0
  41. package/dist/scripts/init-secrets.js +240 -0
  42. package/dist/scripts/init-secrets.js.map +1 -0
  43. package/dist/scripts/lib/cli-args.d.ts +78 -0
  44. package/dist/scripts/lib/cli-args.d.ts.map +1 -0
  45. package/dist/scripts/lib/cli-args.js +116 -0
  46. package/dist/scripts/lib/cli-args.js.map +1 -0
  47. package/dist/scripts/lib/github-actions.d.ts +26 -0
  48. package/dist/scripts/lib/github-actions.d.ts.map +1 -0
  49. package/dist/scripts/lib/github-actions.js +38 -0
  50. package/dist/scripts/lib/github-actions.js.map +1 -0
  51. package/dist/scripts/lib/wrangler-table.d.ts +46 -0
  52. package/dist/scripts/lib/wrangler-table.d.ts.map +1 -0
  53. package/dist/scripts/lib/wrangler-table.js +99 -0
  54. package/dist/scripts/lib/wrangler-table.js.map +1 -0
  55. package/dist/scripts/migrations-lock.d.ts +3 -0
  56. package/dist/scripts/migrations-lock.d.ts.map +1 -0
  57. package/dist/scripts/migrations-lock.js +46 -0
  58. package/dist/scripts/migrations-lock.js.map +1 -0
  59. package/dist/scripts/prepare-wrangler-config.d.ts +3 -0
  60. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -0
  61. package/dist/scripts/prepare-wrangler-config.js +50 -0
  62. package/dist/scripts/prepare-wrangler-config.js.map +1 -0
  63. package/dist/scripts/spa-shell.d.ts +41 -0
  64. package/dist/scripts/spa-shell.d.ts.map +1 -0
  65. package/dist/scripts/spa-shell.js +155 -0
  66. package/dist/scripts/spa-shell.js.map +1 -0
  67. package/dist/scripts/validate-locales.d.ts +26 -0
  68. package/dist/scripts/validate-locales.d.ts.map +1 -0
  69. package/dist/scripts/validate-locales.js +350 -0
  70. package/dist/scripts/validate-locales.js.map +1 -0
  71. package/dist/scripts/verify-migrations.d.ts +62 -0
  72. package/dist/scripts/verify-migrations.d.ts.map +1 -0
  73. package/dist/scripts/verify-migrations.js +302 -0
  74. package/dist/scripts/verify-migrations.js.map +1 -0
  75. package/dist/scripts/verify-spa-shell.d.ts +3 -0
  76. package/dist/scripts/verify-spa-shell.d.ts.map +1 -0
  77. package/dist/scripts/verify-spa-shell.js +53 -0
  78. package/dist/scripts/verify-spa-shell.js.map +1 -0
  79. package/dist/scripts/wrangler-config/cli.d.ts +22 -0
  80. package/dist/scripts/wrangler-config/cli.d.ts.map +1 -0
  81. package/dist/scripts/wrangler-config/cli.js +51 -0
  82. package/dist/scripts/wrangler-config/cli.js.map +1 -0
  83. package/dist/scripts/wrangler-config/patches.d.ts +51 -0
  84. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -0
  85. package/dist/scripts/wrangler-config/patches.js +140 -0
  86. package/dist/scripts/wrangler-config/patches.js.map +1 -0
  87. package/dist/scripts/wrangler-config/resources.d.ts +70 -0
  88. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -0
  89. package/dist/scripts/wrangler-config/resources.js +290 -0
  90. package/dist/scripts/wrangler-config/resources.js.map +1 -0
  91. package/dist/scripts/wrangler-config/types.d.ts +103 -0
  92. package/dist/scripts/wrangler-config/types.d.ts.map +1 -0
  93. package/dist/scripts/wrangler-config/types.js +49 -0
  94. package/dist/scripts/wrangler-config/types.js.map +1 -0
  95. package/dist/test/integration-migrations.d.ts +167 -0
  96. package/dist/test/integration-migrations.d.ts.map +1 -0
  97. package/dist/test/integration-migrations.js +171 -0
  98. package/dist/test/integration-migrations.js.map +1 -0
  99. package/dist/test/mocks/cloudflare-workers.d.ts +106 -0
  100. package/dist/test/mocks/cloudflare-workers.d.ts.map +1 -0
  101. package/dist/test/mocks/cloudflare-workers.js +90 -0
  102. package/dist/test/mocks/cloudflare-workers.js.map +1 -0
  103. package/dist/vite.d.ts +117 -0
  104. package/dist/vite.d.ts.map +1 -0
  105. package/dist/vite.js +125 -0
  106. package/dist/vite.js.map +1 -0
  107. package/dist/vitest-web.d.ts +73 -0
  108. package/dist/vitest-web.d.ts.map +1 -0
  109. package/dist/vitest-web.js +72 -0
  110. package/dist/vitest-web.js.map +1 -0
  111. package/dist/vitest.d.ts +92 -0
  112. package/dist/vitest.d.ts.map +1 -0
  113. package/dist/vitest.js +128 -0
  114. package/dist/vitest.js.map +1 -0
  115. package/package.json +58 -3
  116. package/src/eslint.test.ts +175 -0
  117. package/src/eslint.ts +640 -0
  118. package/src/functions/pages-proxy.test.ts +72 -0
  119. package/src/functions/pages-proxy.ts +187 -0
  120. package/src/github/actions/retry-step/action.yml +39 -0
  121. package/src/github/actions/setup-env/action.yml +20 -0
  122. package/src/github/dependabot.yml +30 -0
  123. package/src/github/workflows/backup-main.yml +46 -0
  124. package/src/github/workflows/continuous-deployment.yml +188 -0
  125. package/src/github/workflows/continuous-integration.yml +259 -0
  126. package/src/github/workflows/scheduled-version-update.yml +38 -0
  127. package/src/github/workflows/upstream-sync.yml +56 -0
  128. package/src/index.ts +42 -0
  129. package/src/scripts/backup/backup-rules.test.ts +105 -0
  130. package/src/scripts/backup/d1-target.ts +54 -0
  131. package/src/scripts/backup/destination-config.ts +92 -0
  132. package/src/scripts/backup/encrypt-backup.ts +107 -0
  133. package/src/scripts/backup/naming.ts +62 -0
  134. package/src/scripts/check-god-files.test.ts +131 -0
  135. package/src/scripts/check-god-files.ts +327 -0
  136. package/src/scripts/ensure-spa-shell-stub.ts +34 -0
  137. package/src/scripts/init-secrets.ts +265 -0
  138. package/src/scripts/lib/cli-args.ts +154 -0
  139. package/src/scripts/lib/github-actions.ts +41 -0
  140. package/src/scripts/lib/wrangler-table.ts +105 -0
  141. package/src/scripts/migrations-lock.ts +52 -0
  142. package/src/scripts/prepare-wrangler-config.ts +51 -0
  143. package/src/scripts/spa-shell.test.ts +91 -0
  144. package/src/scripts/spa-shell.ts +179 -0
  145. package/src/scripts/validate-locales.test.ts +89 -0
  146. package/src/scripts/validate-locales.ts +380 -0
  147. package/src/scripts/verify-migrations.test.ts +71 -0
  148. package/src/scripts/verify-migrations.ts +364 -0
  149. package/src/scripts/verify-spa-shell.ts +56 -0
  150. package/src/scripts/wrangler-config/cli.ts +51 -0
  151. package/src/scripts/wrangler-config/patches.ts +157 -0
  152. package/src/scripts/wrangler-config/resources.ts +330 -0
  153. package/src/scripts/wrangler-config/types.ts +113 -0
  154. package/src/test/integration-migrations.test.ts +169 -0
  155. package/src/test/integration-migrations.ts +267 -0
  156. package/src/test/mocks/cloudflare-workers.ts +115 -0
  157. package/src/vite.test.ts +83 -0
  158. package/src/vite.ts +202 -0
  159. package/src/vitest-web.ts +109 -0
  160. package/src/vitest.ts +185 -0
package/src/eslint.ts ADDED
@@ -0,0 +1,640 @@
1
+ /**
2
+ * The converged ESLint flat config for a monorepo in the Rexezuge family.
3
+ *
4
+ * Provenance: the base is Durable-DAV's `eslint.config.mjs` (380+ lines, the most
5
+ * elaborate of the nine repos, with the layered `no-restricted-imports` boundary
6
+ * rules). Merged in from the other three stacks that share the same plugin set:
7
+ *
8
+ * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,
9
+ * with a narrow override block for Vitest idioms), and
10
+ * `unicorn/prefer-ternary` is off. Edge-Sonic's per-rule "deliberately does not
11
+ * follow" block is carried over verbatim in spirit: each entry is off because
12
+ * complying would make the code worse for what the project is, and each is
13
+ * listed rather than dropped so the decision stays reviewable.
14
+ * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.
15
+ * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.
16
+ * - **AWS-AccessBridge** — the `apps/api` DAO/service boundary uses
17
+ * `allowTypeImports` where the source repos do. It is also the source for the
18
+ * anchored skip patterns and the symlink-safe walk that came out of its own backlog.
19
+ * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,
20
+ * with a narrow override block for Vitest idioms), `unicorn/prefer-ternary` is off
21
+ * with a documented reason, and the `import()` hole in `no-restricted-imports` is
22
+ * covered by a matching `no-restricted-syntax` rule. Edge-Sonic's per-rule
23
+ * "deliberately does not follow" block is carried over verbatim in spirit: each
24
+ * entry is off because complying would make the code worse for what the project
25
+ * is, and each is listed rather than dropped so the decision stays reviewable.
26
+ *
27
+ * Canonical decisions, and why each one:
28
+ *
29
+ * 1. **`prettier/prettier: 'error'`.** Three of the four source repos had it at
30
+ * `warn`, which under `eslint --quiet` is unenforceable — a gate nobody can see
31
+ * is a gate that has never run. Formatting drift is therefore a hard failure.
32
+ * 2. **The layered boundary rules are parameterized by `scope`.** Every source
33
+ * repo wrote the same seven blocks with a different npm scope hardcoded; the
34
+ * factory takes `scope` (`'@myapp'`) and generates the `@myapp/*` patterns.
35
+ * 3. **`test/**` is linted, not ignored.** Durable-DAV/AWS/Mail-Meow ignored it;
36
+ * Edge-Sonic does not, and records why: ~200 KB of test code had accumulated
37
+ * violations that nothing reported.
38
+ * 4. **`apps/web` is a layer in its own right**, banned from every `@scope/*`
39
+ * package. Edge-Sonic is the only source with that block; the others had none,
40
+ * which is how their layer table's "may import: the browser" was a convention
41
+ * rather than a gate. A backend package imported by the SPA compiles and then
42
+ * fails at bundle time, with the error pointing at the bundler.
43
+ * 5. **jsdom + node globals for web files.** The sources ran `globals.node` only;
44
+ * `apps/web` needs browser globals as well, and the vitest config for the SPA
45
+ * runs under jsdom, so the lint environment matches the test environment.
46
+ * 6. **`eslint-plugin-react-hooks` is NOT imported here.** The kit stays
47
+ * zero-dependency, and the plugin belongs to the app that has JSX. A consumer
48
+ * appends it — the README shows the four lines.
49
+ *
50
+ * The consumer's repo-level `eslint.config.mjs` becomes four lines, and a repo that
51
+ * needs a boundary the canonical table does not name passes `extraLayers` — see
52
+ * {@link RepoLintConfigOptions}.
53
+ */
54
+
55
+ import globals from 'globals';
56
+ import tseslint from 'typescript-eslint';
57
+ import unicorn from 'eslint-plugin-unicorn';
58
+ import { configs as sonarjsConfigs } from 'eslint-plugin-sonarjs';
59
+ import pluginRegexp from 'eslint-plugin-regexp';
60
+ import eslintConfigPrettier from 'eslint-config-prettier';
61
+ import prettier from 'eslint-plugin-prettier';
62
+ import type { FlatConfig } from 'typescript-eslint';
63
+
64
+ /**
65
+ * What `defineRepoLintConfig` accepts.
66
+ */
67
+ export interface RepoLintConfigOptions {
68
+ /**
69
+ * The consuming repo's npm scope, e.g. `'@myapp'`. Every `no-restricted-imports`
70
+ * pattern in the boundary rules is derived from it, so the same factory serves
71
+ * all nine repos.
72
+ */
73
+ readonly scope: string;
74
+ /**
75
+ * The workspace directories the layered boundary rules are scoped to, as repo-
76
+ * relative globs. Defaults to the canonical layout the nine repos share.
77
+ */
78
+ readonly projectDirs?: readonly string[];
79
+ /**
80
+ * Extra ignore globs, merged with the canonical set.
81
+ */
82
+ readonly extraIgnores?: readonly string[];
83
+ /**
84
+ * Where `projectService` resolves the tsconfig from. Defaults to the directory
85
+ * ESLint is invoked in, which is the repo root in every CI job.
86
+ */
87
+ readonly tsconfigRootDir?: string;
88
+ /**
89
+ * Extra boundary layers, appended to the canonical table.
90
+ *
91
+ * The escape valve for a repo whose layout has a boundary the canonical table
92
+ * does not name — AWS-AccessBridge's `apps/api/src/endpoints/**` rule ("route
93
+ * classes must not import DAOs directly") and its `aws4fetch` ban are the shape.
94
+ * Same {@link LayerBan} form, so `extraLayers` flows through the
95
+ * `no-restricted-imports` and the `no-restricted-syntax` guard alike.
96
+ */
97
+ readonly extraLayers?: readonly LayerBan[];
98
+ }
99
+
100
+ /**
101
+ * One argument to `tseslint.config()`.
102
+ */
103
+ type ConfigInput = Parameters<typeof tseslint.config>[number];
104
+
105
+ /**
106
+ * A plugin preset or config object as the source repos pass it.
107
+ */
108
+ type MaybeConfig = FlatConfig.Config | readonly FlatConfig.Config[];
109
+
110
+ /**
111
+ * Bridge a third-party preset into `tseslint.config()`.
112
+ *
113
+ * `sonarjs`' `recommended` preset is typed as a union that includes the legacy
114
+ * config shape, which `tseslint.config()` does not accept — but ESLint accepts it
115
+ * at runtime, which is the only thing that matters here. One checked assertion,
116
+ * rather than forking the plugin's own types.
117
+ */
118
+ function asConfig(config: MaybeConfig): ConfigInput {
119
+ return config as ConfigInput;
120
+ }
121
+
122
+ /**
123
+ * The directories the boundary rules cover, in the canonical layout.
124
+ */
125
+ const DEFAULT_PROJECT_DIRS: readonly string[] = [
126
+ 'packages/shared',
127
+ 'packages/backend-errors',
128
+ 'packages/backend-runtime',
129
+ 'packages/backend-data',
130
+ 'packages/backend-services',
131
+ 'apps/api',
132
+ 'apps/background',
133
+ 'apps/web',
134
+ ];
135
+
136
+ /**
137
+ * One layer's ban list, as the repo-relative package suffixes it may not import.
138
+ *
139
+ * Converged from the four source stacks. `backend-data` and `backend-services`
140
+ * appear in all four; `webdav`/`dav-store` are Durable-DAV's, `provider-clients`
141
+ * is Mail-Meow's and AWS's. A layer only bans what exists in its repo, so the
142
+ * union is safe: a repo without `provider-clients` simply never imports it.
143
+ */
144
+ export interface LayerBan {
145
+ /** Directory the rule is scoped to. */
146
+ readonly dir: string;
147
+ /** Package suffixes (relative to `scope`) that may not be imported from here. */
148
+ readonly ban: readonly string[];
149
+ /** Message shown when the rule fires. */
150
+ readonly message: string;
151
+ /** Type-only imports are allowed, for the DAO boundary in `apps/api`. */
152
+ readonly allowTypeImports?: boolean;
153
+ }
154
+
155
+ /**
156
+ * The layer table, parameterized by `scope`.
157
+ *
158
+ * Each entry reproduces the corresponding block in Durable-DAV's
159
+ * `eslint.config.mjs` with `@durable-dav/` replaced by the caller's scope. The
160
+ * table is data rather than seven inline blocks so the dynamic-`import()` guard
161
+ * below can be generated from the same list — a rule that derived its banned set
162
+ * from another rule's configuration would be a second source of truth for the
163
+ * layer table, and that table is what the docs describe.
164
+ */
165
+ function layerBans(scope: string): readonly LayerBan[] {
166
+ const at = (name: string): string => `${scope}/${name}`;
167
+ return [
168
+ {
169
+ dir: 'packages/shared',
170
+ ban: [at('*')],
171
+ message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,
172
+ },
173
+ {
174
+ dir: 'packages/backend-errors',
175
+ ban: [at('*')],
176
+ message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,
177
+ },
178
+ {
179
+ dir: 'packages/backend-runtime',
180
+ ban: [at('backend-data'), at('webdav'), at('backend-services'), at('api'), at('background')],
181
+ message: 'backend-runtime must not import from a higher layer',
182
+ },
183
+ {
184
+ dir: 'packages/backend-data',
185
+ ban: [at('backend-runtime'), at('webdav'), at('backend-services'), at('api'), at('background')],
186
+ message: 'backend-data must not import from a higher layer',
187
+ },
188
+ {
189
+ dir: 'packages/backend-services',
190
+ ban: [at('api'), at('background')],
191
+ message: 'backend-services must not import from apps',
192
+ },
193
+ {
194
+ dir: 'apps/api',
195
+ ban: [at('backend-data/dao'), at('backend-data')],
196
+ allowTypeImports: true,
197
+ message: 'apps/api must not import DAOs or backend-data values directly; use backend-services instead',
198
+ },
199
+ {
200
+ dir: 'apps/background',
201
+ ban: [at('api')],
202
+ message: 'apps/background must not import from apps/api',
203
+ },
204
+ // The browser half, and the only layer that bans the namespace wholesale
205
+ // rather than a list of siblings: a backend package imported by the SPA
206
+ // typechecks and then fails at bundle time, with the error pointing at the
207
+ // bundler rather than at the boundary. Edge-Sonic is the source; the others had
208
+ // no block for it at all, which is how their layer table's "may import: the
209
+ // browser" was a convention instead of a gate.
210
+ {
211
+ dir: 'apps/web',
212
+ ban: [at('*')],
213
+ message: `${at('apps/web')} ships zero backend dependencies — this module is the SPA's own copy`,
214
+ },
215
+ ];
216
+ }
217
+
218
+ /**
219
+ * The `no-restricted-imports` entries for one layer.
220
+ *
221
+ * Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`
222
+ * and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`
223
+ * is passed through only where the source repos set it, because
224
+ * `apps/api` legitimately types its filters and models against DAO shapes.
225
+ */
226
+ function restrictedImports(bans: readonly LayerBan[]): FlatConfig.Config[] {
227
+ return bans.map(({ dir, ban, message, allowTypeImports }) => ({
228
+ files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
229
+ rules: {
230
+ 'no-restricted-imports': [
231
+ 'error',
232
+ {
233
+ patterns: ban.map((group) => ({
234
+ group: [group, `${group}/*`],
235
+ message,
236
+ ...(allowTypeImports === true && { allowTypeImports: true }),
237
+ })),
238
+ },
239
+ ],
240
+ },
241
+ }));
242
+ }
243
+
244
+ /**
245
+ * The dynamic-`import()` guard, generated from the same table.
246
+ *
247
+ * `no-restricted-imports` reads `ImportDeclaration` nodes only; a dynamic
248
+ * `import()` is an `ImportExpression`, and this ESLint version does not report it
249
+ * under that rule at all. Edge-Sonic verified this rather than assumed it — a
250
+ * static import of a restricted specifier from the same file is an `error`, and
251
+ * the identical specifier reached through `await import(...)` is silent. That
252
+ * hole was load-bearing there: the credential path reached a banned module
253
+ * through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is
254
+ * stated a second way.
255
+ *
256
+ * The specifier list is duplicated from the layer table on purpose; see the
257
+ * comment on `layerBans`.
258
+ */
259
+ function restrictedDynamicImports(bans: readonly LayerBan[]): FlatConfig.Config[] {
260
+ return bans.map(({ dir, ban, message }) => ({
261
+ files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
262
+ rules: {
263
+ 'no-restricted-syntax': [
264
+ 'error',
265
+ ...ban.map((specifier) => ({
266
+ selector: `ImportExpression[source.type='Literal'][source.value=/^${specifier.replaceAll('/', '\\/')}/]`,
267
+ message: `A dynamic import() is not covered by no-restricted-imports, so this layer reaches \`${specifier}\` through the one syntax that gate does not see. Both say no: ${message}`,
268
+ })),
269
+ ],
270
+ },
271
+ }));
272
+ }
273
+
274
+ /**
275
+ * Build the repo's flat config.
276
+ *
277
+ * Consumed from the repo root as three lines:
278
+ *
279
+ * ```js
280
+ * // eslint.config.mjs
281
+ * import { defineRepoLintConfig } from '@rexezuge/tooling/eslint';
282
+ * export default defineRepoLintConfig({ scope: '@myapp' });
283
+ * ```
284
+ */
285
+ export function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {
286
+ const { scope } = options;
287
+ const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;
288
+ const canonical = layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)));
289
+ const extra = options.extraLayers ?? [];
290
+ const bans = [...canonical, ...extra];
291
+
292
+ return tseslint.config(
293
+ {
294
+ ignores: [
295
+ 'eslint.config.mjs',
296
+ 'eslint.config.js',
297
+ 'scripts/**',
298
+ 'worker-configuration.d.ts',
299
+ 'local/**',
300
+ 'app/dist/**',
301
+ 'apps/web/dist/**',
302
+ 'apps/*/dist/**',
303
+ 'src/generated/**',
304
+ 'apps/api/src/generated/**',
305
+ 'coverage/**',
306
+ 'coverage-integration/**',
307
+ 'coverage-web/**',
308
+ 'node_modules/**',
309
+ ...(options.extraIgnores ?? []),
310
+ ],
311
+ },
312
+
313
+ // Base: globals for all JS/TS source files. Node is the floor because the
314
+ // scripts and the workers both run on it; the web block below adds browser
315
+ // globals rather than replacing them, so a shared file that touches both
316
+ // (there are several in `shared/`) still lints.
317
+ {
318
+ files: ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'],
319
+ languageOptions: {
320
+ globals: globals.node,
321
+ },
322
+ },
323
+
324
+ // Type-aware TS rules, scoped to TS files only.
325
+ {
326
+ files: ['**/*.{ts,mts,cts,tsx}'],
327
+ extends: tseslint.configs.recommendedTypeChecked,
328
+ languageOptions: {
329
+ parserOptions: {
330
+ projectService: true,
331
+ tsconfigRootDir: options.tsconfigRootDir ?? process.cwd(),
332
+ },
333
+ },
334
+ },
335
+
336
+ // --- typescript-eslint overrides (identical in all four source stacks) ---
337
+ {
338
+ files: ['**/*.{ts,mts,cts,tsx}'],
339
+ rules: {
340
+ '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
341
+ // Allow `void expr` for intentional fire-and-forget in Workers.
342
+ '@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }],
343
+ // Relax the unsafe-any rules to warn: the external API boundaries
344
+ // (Cloudflare bindings, provider SDKs) are typed `any` upstream, and the
345
+ // alternative is a config that cannot be adopted.
346
+ '@typescript-eslint/no-explicit-any': 'warn',
347
+ '@typescript-eslint/no-unsafe-assignment': 'warn',
348
+ '@typescript-eslint/no-unsafe-member-access': 'warn',
349
+ '@typescript-eslint/no-unsafe-call': 'warn',
350
+ '@typescript-eslint/no-unsafe-return': 'warn',
351
+ '@typescript-eslint/no-unsafe-argument': 'warn',
352
+ // JSX event handlers and hook callback objects commonly use async
353
+ // functions where void is expected.
354
+ '@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: { attributes: false, properties: false } }],
355
+ },
356
+ },
357
+
358
+ // --- Unicorn: modern JS/TS quality rules ---
359
+ asConfig(unicorn.configs['flat/recommended']),
360
+ {
361
+ rules: {
362
+ // Codebase uses ctx, req, res, env, err, util, db, dao, etc. — too
363
+ // invasive to rename.
364
+ 'unicorn/prevent-abbreviations': 'off',
365
+ // D1/DAO layer returns null; disabling this avoids mass rewrites.
366
+ 'unicorn/no-null': 'off',
367
+ // Monorepo uses CommonJS-compatible module style in some configs.
368
+ 'unicorn/prefer-module': 'off',
369
+ // Top-level await not available in all Workers entry points.
370
+ 'unicorn/prefer-top-level-await': 'off',
371
+ // Error subclassing via `new MyError()` is intentional in backend-errors.
372
+ 'unicorn/custom-error-definition': 'off',
373
+ // Allow process.exit in build/script files.
374
+ 'unicorn/no-process-exit': 'off',
375
+ // Array reduce is used intentionally in analytics/data transformation.
376
+ 'unicorn/no-array-reduce': 'off',
377
+ // Allow Number() — parseInt/parseFloat are used in some cases intentionally.
378
+ 'unicorn/prefer-number-properties': ['error', { checkInfinity: false }],
379
+ // Allow nested ternaries in JSX (React render patterns).
380
+ 'unicorn/no-nested-ternary': 'off',
381
+ // Allow Array.from — codebase uses it for iterables.
382
+ 'unicorn/prefer-spread': 'off',
383
+ // Entire codebase uses PascalCase for TS files; kebab-case would require
384
+ // mass renames.
385
+ 'unicorn/filename-case': 'off',
386
+ // Established names should not be force-renamed.
387
+ 'unicorn/name-replacements': 'off',
388
+ // Zod schema builder chains and other deep method chains are intentional.
389
+ 'unicorn/max-nested-calls': 'off',
390
+ // import.meta.dirname is not available in all test environments.
391
+ 'unicorn/prefer-import-meta-properties': 'off',
392
+ // Codebase uses `err` as catch parameter name throughout.
393
+ 'unicorn/catch-error-name': 'off',
394
+ // Established boolean param names (retryable, enabled, etc.).
395
+ 'unicorn/consistent-boolean-name': 'off',
396
+ // Uint8Array#toBase64 / fromBase64 are not in all Workers runtime versions.
397
+ 'unicorn/prefer-uint8array-base64': 'off',
398
+ // Class member ordering would require extensive restructuring.
399
+ 'unicorn/consistent-class-member-order': 'off',
400
+ // API response fields use verb prefixes by convention.
401
+ 'unicorn/no-non-function-verb-prefix': 'off',
402
+ // forEach is used intentionally throughout the provider and utility layers.
403
+ 'unicorn/no-for-each': 'off',
404
+ // .then() chains in DAO and provider layers are often intentional.
405
+ 'unicorn/prefer-await': 'warn',
406
+ // Callback references (e.g. .map(Number)) are sometimes intentional.
407
+ 'unicorn/no-array-callback-reference': 'warn',
408
+ // toSorted() is ES2023 and may not be in all tsconfig lib targets.
409
+ 'unicorn/no-array-sort': 'warn',
410
+ // Early-return guard clauses are the established style; the rule only
411
+ // rewrites the final guard of a ladder, which yields asymmetric mixed
412
+ // style and long inline ternaries. Off in Mail-Meow and Edge-Sonic;
413
+ // canonical here because it is the family's established style.
414
+ 'unicorn/prefer-ternary': 'off',
415
+ // `(await x).y` -> a named intermediate. Fires constantly in the tests,
416
+ // where destructuring beside the assertion it serves is clearer.
417
+ 'unicorn/no-await-expression-member': 'off',
418
+ // `Number(x)` over `+x`: the `+` form is used where an explicit typeof
419
+ // check has already narrowed the operand.
420
+ 'unicorn/prefer-number-coercion': 'off',
421
+ // Code-point iteration: the byte-level readers index deliberately,
422
+ // because the offset *is* what they are reading.
423
+ 'unicorn/prefer-code-point': 'off',
424
+ // `if (!x) return;` over a compound condition: one guard per line, each
425
+ // with its own comment, is what keeps endpoint guards readable.
426
+ 'unicorn/prefer-simple-condition-first': 'off',
427
+ // Module-scope `let` assigned from `beforeEach` in the test harnesses.
428
+ 'unicorn/no-top-level-assignment-in-function': 'off',
429
+ // Sequential `for...of` with `await` in the DAOs — D1's subrequest
430
+ // budget is the scarce resource.
431
+ 'unicorn/no-unreadable-for-of-expression': 'off',
432
+ // `Object.hasOwn` over `in`: used where a prototype-chain hit is harmless.
433
+ 'unicorn/no-computed-property-existence-check': 'off',
434
+ // A labeled `break` out of two loops.
435
+ 'unicorn/no-break-in-nested-loop': 'off',
436
+ // `this` outside a class body: the module-level cache singletons
437
+ // document their `this` contract in prose.
438
+ 'unicorn/no-this-outside-of-class': 'off',
439
+ // A class named inside its own static method.
440
+ 'unicorn/class-reference-in-static-methods': 'off',
441
+ // `void promise` where initiating the call is the point and the rejection
442
+ // is handled at a named site elsewhere.
443
+ 'sonarjs/void-use': 'off',
444
+ // An `async` function with no `await`: every handler and DAO method is
445
+ // `async` by shape so a future `await` does not change its signature.
446
+ '@typescript-eslint/require-await': 'off',
447
+ // Backtracking risk in bounded-prefix readers that run over a file the
448
+ // server already chose to fetch, never over a request parameter.
449
+ 'sonarjs/super-linear-regex': 'off',
450
+ // Assigning `globalThis.fetch` in a test — the only way to intercept the
451
+ // ambient fetch in Node without a module mock.
452
+ 'unicorn/no-global-object-property-assignment': 'off',
453
+ // `(a ? b : c) && d`: written longhand so each precedence decision is
454
+ // visible.
455
+ 'unicorn/prefer-logical-operator-over-ternary': 'off',
456
+ // `children[0]` in the XML helpers, which index a child list positionally.
457
+ 'unicorn/better-dom-traversing': 'off',
458
+ // `entries()` -> `keys()`/`values()`: the full entry is destructured.
459
+ 'unicorn/prefer-iterator-to-array': 'off',
460
+ // `.map(fn, thisArg)`: rejected on purpose.
461
+ 'unicorn/no-array-method-this-argument': 'off',
462
+ // A module-scope function that closes over nothing.
463
+ 'unicorn/consistent-function-scoping': 'off',
464
+ // `foo[0] === 'a' || foo[0] === 'b'` written longhand where the
465
+ // alternatives are not adjacent.
466
+ 'unicorn/prefer-includes-over-repeated-comparisons': 'off',
467
+ // A `type` alias over an inline union, where the name is what makes the
468
+ // signature and its doc comment readable.
469
+ 'sonarjs/use-type-alias': 'off',
470
+ // A short local alias for a type imported from a protocol package.
471
+ 'sonarjs/redundant-type-aliases': 'off',
472
+ // `type: value` narrowing the other way, where both spellings appear in
473
+ // the same schema and the code follows whichever the spec uses there.
474
+ 'sonarjs/no-nested-assignment': 'off',
475
+ // `Number.isInteger` plus a separate range check, where the bounds come
476
+ // from the caller's own options in one place.
477
+ 'unicorn/prefer-number-is-safe-integer': 'off',
478
+ // `\u{...}` over a `\xNN` escape: the table is written in the byte form
479
+ // the spec prints.
480
+ 'unicorn/prefer-unicode-code-point-escapes': 'off',
481
+ // `self.x = this.x` in an entry model: the alias makes the verbatim
482
+ // round-trip explicit.
483
+ 'unicorn/no-this-assignment': 'off',
484
+ // Building a `Set` at module scope from a constant list, for O(1)
485
+ // membership on a path that runs per parameter.
486
+ 'unicorn/no-top-level-side-effects': 'off',
487
+ // `await` on a value the types say is not thenable, where the value is a
488
+ // `PromiseLike` from an interface declared that way.
489
+ '@typescript-eslint/await-thenable': 'off',
490
+ // A conditional whose branches are identical, kept where the two branches
491
+ // are named separately to document that they are meant to diverge.
492
+ 'sonarjs/no-all-duplicated-branches': 'off',
493
+ // An `else` after a `return`: the flat form keeps the remaining cases at
494
+ // one indent level in the dispatch tables.
495
+ 'unicorn/prefer-else-if': 'off',
496
+ // A nested ternary in a sort comparator, where the three-way order is the
497
+ // point.
498
+ 'unicorn/prefer-minimal-ternary': 'off',
499
+ // `x === undefined` reported as always-true/false. With
500
+ // `noUncheckedIndexedAccess` on, the guard is exactly right.
501
+ 'sonarjs/different-types-comparison': 'off',
502
+ // An accumulating loop with a sequential `await` in it, over D1 writes.
503
+ 'unicorn/prefer-array-from-async': 'off',
504
+ },
505
+ },
506
+
507
+ // --- SonarJS: code smell and bug detection ---
508
+ asConfig(sonarjsConfigs.recommended),
509
+ {
510
+ rules: {
511
+ // Raise duplicate-string threshold to avoid flagging intentional repeated
512
+ // literals like provider IDs.
513
+ 'sonarjs/no-duplicate-string': ['warn', { threshold: 5 }],
514
+ // Cognitive complexity — warn rather than error, so the ratchet can move
515
+ // without a red build. Raise the number only as files are decomposed.
516
+ 'sonarjs/cognitive-complexity': ['warn', 20],
517
+ // False positives: connection method names like 'imap-password' and
518
+ // field names like 'password_hash'.
519
+ 'sonarjs/no-hardcoded-passwords': 'off',
520
+ // Third-party deprecations are warnings, not errors.
521
+ 'sonarjs/deprecation': 'warn',
522
+ // Nested ternaries in complex data-mapping code.
523
+ 'sonarjs/no-nested-conditional': 'warn',
524
+ // React component props are commonly not marked Readonly<>.
525
+ 'sonarjs/prefer-read-only-props': 'warn',
526
+ // Static readonly properties require invasive refactoring.
527
+ 'sonarjs/public-static-readonly': 'warn',
528
+ // Nested template literals in SQL queries and prompt construction.
529
+ 'sonarjs/no-nested-template-literals': 'warn',
530
+ },
531
+ },
532
+
533
+ // --- Regexp: static analysis for regular expressions ---
534
+ asConfig(pluginRegexp.configs['flat/recommended']),
535
+
536
+ // --- Prettier: formatting drift is a hard error ---
537
+ //
538
+ // Mail-Meow's decision, adopted repo-wide because the alternative is
539
+ // unenforceable: `pnpm run lint` is `eslint --fix --quiet` in three of the
540
+ // four source repos, and `--quiet` discards every warning, so a
541
+ // `prettier/prettier` *warning* is a silent no-op. 242 files were in that
542
+ // state in Edge-Sonic: the gate had never run.
543
+ asConfig(eslintConfigPrettier),
544
+ {
545
+ plugins: { prettier },
546
+ rules: {
547
+ 'prettier/prettier': 'error',
548
+ },
549
+ },
550
+
551
+ // --- Import direction guardrails (parameterized by scope) ---
552
+ ...restrictedImports(bans),
553
+ ...restrictedDynamicImports(bans),
554
+
555
+ // --- Web: browser globals, matching the jsdom test environment ---
556
+ //
557
+ // The sources linted `apps/web` under `globals.node` only, so `window`,
558
+ // `document` and `localStorage` read as undefined globals. The vitest web
559
+ // config runs those suites under jsdom; the lint environment should agree
560
+ // with the environment the code is executed in, or the rule is reporting
561
+ // something untrue about how the file behaves.
562
+ {
563
+ files: ['apps/web/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}'],
564
+ languageOptions: {
565
+ globals: { ...globals.node, ...globals.browser },
566
+ },
567
+ },
568
+
569
+ // --- Test suite ---
570
+ //
571
+ // `test/**` is deliberately NOT in the ignores list above. Durable-DAV,
572
+ // AWS and Mail-Meow all ignored it, and ~200 KB of test code had accumulated
573
+ // violations that nothing reported. This block puts the suite back under the
574
+ // same rules as the rest of the workspace and switches off only the handful
575
+ // whose findings are structural artefacts of test code rather than defects.
576
+ // It does not disable correctness rules: the unused-variable, dead-store,
577
+ // regex and sorting findings in the suite are real and are fixed, not
578
+ // suppressed.
579
+ {
580
+ files: ['test/**/*.{ts,tsx,mts,cts}', '**/*.test.{ts,tsx,mts,cts}', '**/*.spec.{ts,tsx,mts,cts}'],
581
+ rules: {
582
+ // `it('…', async () => …)` is the Vitest idiom.
583
+ '@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: { arguments: false, attributes: false } }],
584
+ // Unbound method is a common false positive in mock assertions like
585
+ // expect(fn).toHaveBeenCalledWith(...).
586
+ '@typescript-eslint/unbound-method': 'off',
587
+ // Test helpers and stubs routinely use async functions without await.
588
+ '@typescript-eslint/require-await': 'off',
589
+ // Redundant type constituents appear in typed mock stubs.
590
+ '@typescript-eslint/no-redundant-type-constituents': 'off',
591
+ // `as never` casts are the standard fake-DB double pattern in tests.
592
+ '@typescript-eslint/no-unnecessary-type-assertion': 'off',
593
+ // Promise.withResolvers() and function-scoping refactors are cosmetic.
594
+ 'unicorn/prefer-promise-with-resolvers': 'off',
595
+ 'unicorn/consistent-function-scoping': 'off',
596
+ // Fake-DB builders push-then-return and sort without comparators.
597
+ 'unicorn/no-return-array-push': 'off',
598
+ 'unicorn/require-array-sort-compare': 'off',
599
+ // Iterator-helper rewrites churn test fakes with no runtime benefit.
600
+ 'unicorn/prefer-iterator-helpers': 'off',
601
+ 'unicorn/prefer-iterator-to-array': 'off',
602
+ // String replacement with test-driven values is intentional in assertions.
603
+ 'unicorn/no-unsafe-string-replacement': 'off',
604
+ // Fake-D1 doubles await a DAO thunk and call straight onto the result.
605
+ 'unicorn/no-await-expression-member': 'off',
606
+ // `void promise` marks a deliberately unawaited promise in a test.
607
+ 'sonarjs/void-use': 'off',
608
+ // A test asserting request routing has to name `http://` hosts, and a
609
+ // proxy test has to name a loopback upstream. Both are the subject
610
+ // matter, not leaked configuration. `unicorn/prefer-https` must stay off
611
+ // here and this is not a style preference: it rewrites `http://` to
612
+ // `https://` *inside string literals*, and `--fix` applies it silently.
613
+ 'sonarjs/no-clear-text-protocols': 'off',
614
+ 'sonarjs/no-hardcoded-ip': 'off',
615
+ 'unicorn/prefer-https': 'off',
616
+ // sonarjs/assertions-in-tests fires false positives when test helpers
617
+ // handle assertions indirectly.
618
+ 'sonarjs/assertions-in-tests': 'off',
619
+ // sonarjs/no-extra-arguments fires incorrectly on Vitest mock overloads.
620
+ 'sonarjs/no-extra-arguments': 'off',
621
+ // Union/inline types in test fakes are more readable than aliases.
622
+ 'sonarjs/use-type-alias': 'off',
623
+ // Alphabetical-sort rule fights deterministic fixture ordering.
624
+ 'sonarjs/no-alphabetical-sort': 'off',
625
+ // Repeated string literals in fixtures/assertions are clearer inline.
626
+ 'sonarjs/no-duplicate-string': 'off',
627
+ // Fake-D1 doubles break out of a nested loop to model a statement miss.
628
+ 'unicorn/no-break-in-nested-loop': 'off',
629
+ // Fixtures are naturally built with sort()/for…of over composed expressions.
630
+ 'unicorn/no-array-sort': 'off',
631
+ 'unicorn/no-unreadable-for-of-expression': 'off',
632
+ 'unicorn/no-useless-template-literals': 'off',
633
+ 'unicorn/no-declarations-before-early-exit': 'off',
634
+ 'unicorn/prefer-includes-over-repeated-comparisons': 'off',
635
+ 'sonarjs/prefer-specific-assertions': 'off',
636
+ 'sonarjs/no-inverted-boolean-check': 'off',
637
+ },
638
+ },
639
+ );
640
+ }