@starci/eslint-canon-fe 5.1.2 → 6.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 (68) hide show
  1. package/CHANGELOG.md +78 -2
  2. package/README.md +17 -18
  3. package/brand-values.mjs +1 -3
  4. package/class-names.mjs +9 -9
  5. package/client-boundary.mjs +125 -37
  6. package/comments.mjs +14 -21
  7. package/docs/client-boundary.md +26 -1
  8. package/docs/grammar-boundary.md +33 -0
  9. package/docs/hygiene.md +15 -4
  10. package/docs/lint-escape-hatch.md +3 -1
  11. package/docs/next-conventions.md +26 -0
  12. package/docs/size-growth.md +29 -0
  13. package/docs/spec-quality.md +15 -7
  14. package/docs/status-colors.md +32 -0
  15. package/docs/translation.md +4 -0
  16. package/docs/transport.md +36 -9
  17. package/e2e-shape.mjs +20 -23
  18. package/env-owner.mjs +1 -1
  19. package/file-layout.mjs +105 -103
  20. package/formatting.mjs +2 -4
  21. package/grammar-boundary.mjs +85 -9
  22. package/hooks-folder.mjs +17 -16
  23. package/hygiene.mjs +370 -92
  24. package/icon.mjs +21 -20
  25. package/index.mjs +27 -85
  26. package/landmark.mjs +0 -11
  27. package/lib/bindings.mjs +144 -0
  28. package/lib/config.mjs +79 -0
  29. package/lib/hfs.mjs +48 -0
  30. package/lib/next.mjs +6 -0
  31. package/lib/platform.mjs +66 -0
  32. package/lib/react.mjs +28 -0
  33. package/lib/scope.mjs +119 -19
  34. package/lib/status-tones.generated.mjs +9 -0
  35. package/lib/types.mjs +63 -0
  36. package/lib/why.mjs +41 -11
  37. package/lint-escape-hatch.mjs +17 -15
  38. package/loading.mjs +9 -16
  39. package/naming.mjs +8 -2
  40. package/next-conventions.mjs +109 -25
  41. package/package.json +9 -4
  42. package/props-and-slots.mjs +19 -13
  43. package/runtime/engine/plain-object.mjs +5 -0
  44. package/runtime/engine/runtime-root.mjs +32 -0
  45. package/runtime/engine/yaml.mjs +161 -0
  46. package/runtime/knowledge/hfs/slots.yaml +1072 -0
  47. package/runtime/scripts/lib/git.mjs +53 -0
  48. package/runtime/scripts/lib/glob.mjs +23 -0
  49. package/runtime/scripts/lib/hfs-allows.mjs +42 -0
  50. package/runtime/scripts/lib/hfs-slots.mjs +722 -0
  51. package/runtime/scripts/lib/hfs-view.mjs +68 -0
  52. package/runtime/scripts/lib/next-contract.mjs +14 -0
  53. package/runtime/scripts/lib/path-key.mjs +17 -0
  54. package/runtime/scripts/lib/recorded-lines.mjs +27 -0
  55. package/served-locale.mjs +30 -16
  56. package/shape-slot.mjs +22 -20
  57. package/size-and-state-budget.mjs +41 -23
  58. package/size-growth.mjs +58 -0
  59. package/spec-quality.mjs +95 -16
  60. package/status-colors.mjs +139 -0
  61. package/the-split.mjs +13 -13
  62. package/tokens.mjs +26 -34
  63. package/translation.mjs +52 -19
  64. package/transport.mjs +437 -89
  65. package/type-safety.mjs +8 -17
  66. package/typography.mjs +7 -11
  67. package/vendor-boundary.mjs +5 -27
  68. package/lint-adoption.mjs +0 -79
package/transport.mjs CHANGED
@@ -2,8 +2,9 @@
2
2
  * The rules that hold `transport.md` (HFS R50 `FE_TRANSPORT_OWNER`, R51 `FE_HTTP_STATUS_COLLAPSE`,
3
3
  * R52 `FE_WIRE_GENERATED`).
4
4
  *
5
- * ONE WIRE, ONE VOCABULARY. An app talks to its backend through exactly one module,
6
- * `modules/api/client.ts`, and that module answers in exactly one vocabulary, `Outcome<T>`. The
5
+ * ONE WIRE, ONE VOCABULARY. A repository talks to its backend through exactly one module, the api client (HFS slot
6
+ * `fe.transport.client`: `modules/api/client.ts`, or `fe.package.api.client`: the shared api package's `src/client.ts`),
7
+ * and that module answers in exactly one vocabulary, `Outcome<T>` (slot `fe.transport.outcome` / `fe.package.api.outcome`). The
7
8
  * defects the three halves prevent were measured on real apps: seven transports and six result
8
9
  * shapes in one repository, and in another a client that folded every non-2xx into "could not
9
10
  * read", so the state a real backend produces for a signed-out reader - 401, which must become
@@ -16,64 +17,137 @@
16
17
  * it, no shared mutable state, a 401/403 branch, and no null standing in for a status.
17
18
  */
18
19
 
19
- import { isApiClient, isSpecFile } from "./lib/scope.mjs"
20
- import { normalizePath } from "./lib/path.mjs"
21
-
22
- /** Any other way to send an HTTP request: a second transport is a second owner. */
23
- const OTHER_TRANSPORTS = /^(?:axios|ky|ky-universal|got|node-fetch|undici|cross-fetch|isomorphic-fetch|superagent|ofetch|whatwg-fetch)$/
24
-
25
- /** `fetch`, `globalThis.fetch`, `window.fetch`, `self.fetch`. */
26
- const isFetchCall = (node) => {
27
- const callee = node.callee
28
- if (callee.type === "Identifier") return callee.name === "fetch"
29
- return (
30
- callee.type === "MemberExpression" &&
31
- !callee.computed &&
32
- callee.property.name === "fetch" &&
33
- callee.object.type === "Identifier" &&
34
- ["globalThis", "window", "self", "global"].includes(callee.object.name)
35
- )
20
+ import ts from "typescript"
21
+ import { hfsOf } from "./lib/hfs.mjs"
22
+ import { globalReferences, isApiClient, isOutcomeModule, isSpecFile, slotOfFile } from "./lib/scope.mjs"
23
+ import { typed } from "./lib/types.mjs"
24
+
25
+ /** Packages that send an HTTP request: a second transport is a second owner. Matched on the module specifier, never on a file name. */
26
+ const TRANSPORT_PACKAGES = new Set([
27
+ "axios", "ky", "ky-universal", "got", "node-fetch", "undici", "cross-fetch", "isomorphic-fetch", "superagent", "ofetch",
28
+ "whatwg-fetch", "graphql-request", "urql", "next-urql", "apollo-client",
29
+ ])
30
+
31
+ /** Package scopes and prefixes whose every package is a GraphQL/HTTP client of its own (`@apollo/client`, `@urql/core`, `apollo-link-http`). */
32
+ const TRANSPORT_SCOPES = ["@apollo/", "@urql/", "apollo-"]
33
+
34
+ /** True when a module specifier resolves to an HTTP client library. */
35
+ const isTransportLibrary = (specifier) => {
36
+ const parts = String(specifier).split("/")
37
+ const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]
38
+ return TRANSPORT_PACKAGES.has(name) || TRANSPORT_SCOPES.some((prefix) => name.startsWith(prefix))
36
39
  }
37
40
 
38
- /** Files under `modules/api/` that the wire law governs (the contract copy and generated output are data). */
39
- const isApiModuleFile = (filename) => {
40
- const file = normalizePath(filename)
41
- return /\/modules\/api\//.test(file) && !/\/(?:contract|__generated__)\//.test(file)
41
+ /** The global objects that carry the same globals as the bare names. */
42
+ const GLOBAL_OBJECTS = new Set(["globalThis", "window", "self", "global"])
43
+
44
+ /** The bare globals that open a connection. */
45
+ const TRANSPORT_GLOBALS = new Set(["fetch", "Request", "EventSource", "XMLHttpRequest", "navigator"])
46
+
47
+ /** The static name of a member's property, else null. */
48
+ const propertyName = (member) => {
49
+ if (!member.computed) return member.property.type === "Identifier" ? member.property.name : null
50
+ return member.property.type === "Literal" && typeof member.property.value === "string" ? member.property.value : null
51
+ }
52
+
53
+ /**
54
+ * Every use of a global transport in the file, found by scope resolution (an imported, declared or parameter `fetch` is not
55
+ * one): `fetch` however it is reached (`fetch(...)`, `globalThis.fetch`, `window.fetch`, `const f = fetch`,
56
+ * `const { fetch } = globalThis`), `new Request`, `new EventSource`, `navigator.sendBeacon`, `new XMLHttpRequest`.
57
+ *
58
+ * @param {object} context - The ESLint rule context.
59
+ * @returns {Array<{ node: object, kind: "fetch" | "channel" | "xhr", name: string, call: object | null }>} The uses; `call` is the call of `fetch` when it is called there.
60
+ */
61
+ const transportUses = (context) => {
62
+ const uses = []
63
+ const calledBy = (node) => (node.parent?.type === "CallExpression" && node.parent.callee === node ? node.parent : null)
64
+ const constructedBy = (node) => node.parent?.type === "NewExpression" && node.parent.callee === node
65
+ const classify = (node, name) => {
66
+ if (name === "fetch") uses.push({ node, kind: "fetch", name, call: calledBy(node) })
67
+ else if ((name === "Request" || name === "EventSource") && constructedBy(node)) uses.push({ node, kind: "channel", name, call: null })
68
+ else if (name === "XMLHttpRequest" && constructedBy(node)) uses.push({ node, kind: "xhr", name, call: null })
69
+ else if (name === "navigator" && node.parent?.type === "MemberExpression" && node.parent.object === node && propertyName(node.parent) === "sendBeacon") {
70
+ uses.push({ node: node.parent, kind: "channel", name: "navigator.sendBeacon", call: calledBy(node.parent) })
71
+ }
72
+ }
73
+ for (const id of globalReferences(context, new Set([...TRANSPORT_GLOBALS, ...GLOBAL_OBJECTS]))) {
74
+ // `typeof fetch` names the type of the function; it does not call it.
75
+ if (id.parent?.type === "TSTypeQuery") continue
76
+ if (!GLOBAL_OBJECTS.has(id.name)) {
77
+ classify(id, id.name)
78
+ continue
79
+ }
80
+ const parent = id.parent
81
+ if (parent?.type === "MemberExpression" && parent.object === id) {
82
+ const name = propertyName(parent)
83
+ if (name !== null && TRANSPORT_GLOBALS.has(name)) classify(parent, name)
84
+ } else if (parent?.type === "VariableDeclarator" && parent.init === id && parent.id.type === "ObjectPattern") {
85
+ for (const property of parent.id.properties) {
86
+ if (property.type === "Property" && !property.computed && property.key.type === "Identifier" && property.key.name === "fetch") {
87
+ uses.push({ node: property, kind: "fetch", name: "fetch", call: null })
88
+ }
89
+ }
90
+ }
91
+ }
92
+ return uses
42
93
  }
43
94
 
44
95
  // -- FE-TRANSPORT-1 --------------------------------------------------------------------------------
45
96
 
46
- /** `fetch` is called in one module, and no other HTTP library exists. */
97
+ /**
98
+ * `fetch` is reached in one file per repository, and no other HTTP library exists.
99
+ *
100
+ * The one file is the one whose HFS slot is `fe.transport.client` (`apps/<app>/src/modules/api/client.ts`, a one-app repository)
101
+ * or `fe.package.api.client` (`packages/<family>-api/src/client.ts`, the shared client of a multi-app repository). Every other
102
+ * file, including another file of the same package, is a finding.
103
+ */
47
104
  export const fetchOnlyInApiClient = {
48
105
  meta: {
49
106
  type: "problem",
50
- docs: { description: "The app's single `fetch` lives in `modules/api/client.ts`." },
107
+ docs: { description: "The repository's single `fetch` (and `Request`, `EventSource`, `sendBeacon`) lives in the api client slot." },
51
108
  schema: [],
52
109
  messages: {
53
110
  outside:
54
- "`fetch` outside `modules/api/client.ts`. The app has exactly one transport; a second one is a second place that must remember the timeout, the credential and the status mapping, and it will forget one. Call the client and take its `Outcome`.",
111
+ "`fetch` outside the api client (`modules/api/client.ts`, or the shared api package's `src/client.ts`). The repository has exactly one transport; a second one is a second place that must remember the timeout, the credential and the status mapping, and it will forget one. Call the client and take its `Outcome`.",
112
+ channel:
113
+ "`{{name}}` opens a connection outside the api client. `Request`, `EventSource` and `navigator.sendBeacon` are transports of their own; the repository's one client owns every request. Call the client and take its `Outcome`.",
55
114
  library:
56
- "`{{name}}` is a second HTTP transport. The app's one client is `modules/api/client.ts`, built on `fetch`; another library there is another set of timeout, retry and error rules. Use the client.",
57
- xhr: "`XMLHttpRequest` is a second transport. Use `modules/api/client.ts`.",
115
+ "`{{name}}` is a second HTTP transport. The repository's one client (`modules/api/client.ts` or the api package's `src/client.ts`) is built on `fetch`; another library is another set of timeout, retry and error rules. Use the client.",
116
+ xhr: "`XMLHttpRequest` is a second transport. Use the repository's api client.",
58
117
  },
59
118
  },
60
119
  create(context) {
61
120
  const filename = context.filename || context.getFilename()
62
121
  if (isSpecFile(filename)) return {}
63
- const client = isApiClient(filename)
122
+ const client = isApiClient(context)
123
+ const library = (node, source) => {
124
+ if (typeof source === "string" && isTransportLibrary(source)) context.report({ node, messageId: "library", data: { name: source } })
125
+ }
64
126
  return {
65
- CallExpression(node) {
66
- if (!client && isFetchCall(node)) context.report({ node, messageId: "outside" })
67
- },
68
- NewExpression(node) {
69
- if (node.callee.type === "Identifier" && node.callee.name === "XMLHttpRequest") {
70
- context.report({ node, messageId: "xhr" })
127
+ "Program:exit"() {
128
+ for (const use of transportUses(context)) {
129
+ if (use.kind === "xhr") context.report({ node: use.node, messageId: "xhr" })
130
+ else if (client) continue
131
+ else if (use.kind === "fetch") context.report({ node: use.node, messageId: "outside" })
132
+ else context.report({ node: use.node, messageId: "channel", data: { name: use.name } })
71
133
  }
72
134
  },
73
135
  ImportDeclaration(node) {
74
- const source = String(node.source.value)
75
- const name = source.split("/")[0]
76
- if (OTHER_TRANSPORTS.test(name)) context.report({ node, messageId: "library", data: { name: source } })
136
+ if (node.importKind !== "type") library(node, node.source.value)
137
+ },
138
+ ExportNamedDeclaration(node) {
139
+ if (node.source && node.exportKind !== "type") library(node, node.source.value)
140
+ },
141
+ ExportAllDeclaration(node) {
142
+ if (node.exportKind !== "type") library(node, node.source.value)
143
+ },
144
+ ImportExpression(node) {
145
+ if (node.source.type === "Literal") library(node, node.source.value)
146
+ },
147
+ CallExpression(node) {
148
+ // `require("axios")` where `require` is the CommonJS global.
149
+ if (node.callee.type !== "Identifier" || node.callee.name !== "require" || node.arguments[0]?.type !== "Literal") return
150
+ if (globalReferences(context, new Set(["require"])).includes(node.callee)) library(node, node.arguments[0].value)
77
151
  },
78
152
  }
79
153
  },
@@ -93,25 +167,48 @@ export const clientFetchHasSignal = {
93
167
  },
94
168
  },
95
169
  create(context) {
96
- if (!isApiClient(context.filename || context.getFilename())) return {}
170
+ if (!isApiClient(context)) return {}
97
171
  return {
98
- CallExpression(node) {
99
- if (!isFetchCall(node)) return
100
- const options = node.arguments[1]
101
- if (!options) return context.report({ node, messageId: "signal" })
102
- // A spread or a computed value may carry it; only a literal object that plainly lacks it is wrong.
103
- if (options.type !== "ObjectExpression") return
104
- const carries = options.properties.some(
105
- (property) =>
106
- property.type === "SpreadElement" ||
107
- (property.type === "Property" && property.key.type === "Identifier" && property.key.name === "signal"),
108
- )
109
- if (!carries) context.report({ node, messageId: "signal" })
172
+ "Program:exit"() {
173
+ // The global `fetch` however it is reached; a request built as `new Request(url, init)` carries its signal in `init`.
174
+ for (const { call } of transportUses(context)) {
175
+ if (!call) continue
176
+ const options = call.arguments[1]
177
+ if (!options) {
178
+ context.report({ node: call, messageId: "signal" })
179
+ continue
180
+ }
181
+ // A spread or a computed value may carry it; only a literal object that plainly lacks it is wrong.
182
+ if (options.type !== "ObjectExpression") continue
183
+ const carries = options.properties.some(
184
+ (property) =>
185
+ property.type === "SpreadElement" ||
186
+ (property.type === "Property" && property.key.type === "Identifier" && property.key.name === "signal"),
187
+ )
188
+ if (!carries) context.report({ node: call, messageId: "signal" })
189
+ }
110
190
  },
111
191
  }
112
192
  },
113
193
  }
114
194
 
195
+ /** The slots that make up the API layer: the app's `modules/api` and the shared api package. */
196
+ const API_LAYER_SLOTS = ["fe.modules.api", "fe.transport.client", "fe.transport.outcome", "fe.package.api", "fe.package.api.client", "fe.package.api.outcome"]
197
+
198
+ /**
199
+ * True for a file of the API layer, except the data folders its slot allows (`contract/`, `__generated__/`: the contract copy
200
+ * and generated output are data, not code the wire law governs).
201
+ */
202
+ const isTransportFile = (context) => {
203
+ const slotId = slotOfFile(context)
204
+ if (!API_LAYER_SLOTS.includes(slotId)) return false
205
+ const hfs = hfsOf(context)
206
+ const dataFolders = (hfs.slot(slotId).allows ?? []).filter((entry) => entry.endsWith("/")).map((entry) => entry.slice(0, -1))
207
+ const { root } = hfs.classify(context.filename || context.getFilename())
208
+ const below = hfs.relative(context.filename || context.getFilename()).slice(root.length + 1).split("/")
209
+ return !dataFolders.includes(below[0])
210
+ }
211
+
115
212
  // -- FE-TRANSPORT-3 --------------------------------------------------------------------------------
116
213
 
117
214
  /** No module-level mutable state in the API layer: a token or locale in a `let` leaks across requests. */
@@ -127,7 +224,7 @@ export const noSharedTransportState = {
127
224
  },
128
225
  create(context) {
129
226
  const filename = context.filename || context.getFilename()
130
- if (!isApiModuleFile(filename) || isSpecFile(filename)) return {}
227
+ if (!isTransportFile(context) || isSpecFile(filename)) return {}
131
228
  const check = (node) => {
132
229
  const declaration = node.type === "VariableDeclaration" ? node : node.declaration
133
230
  if (!declaration || declaration.type !== "VariableDeclaration" || declaration.kind === "const") return
@@ -142,34 +239,187 @@ export const noSharedTransportState = {
142
239
 
143
240
  // -- FE-TRANSPORT-4 --------------------------------------------------------------------------------
144
241
 
145
- /** The client maps 401/403 to `refused`, so "sign in" is a state a reader can reach. */
242
+ /** Removes the wrappers that do not change what an expression is. */
243
+ const unwrap = (node) => {
244
+ let current = node
245
+ while (
246
+ current &&
247
+ (current.type === "TSAsExpression" || current.type === "TSNonNullExpression" || current.type === "TSSatisfiesExpression" || current.type === "ChainExpression")
248
+ ) {
249
+ current = current.expression
250
+ }
251
+ return current
252
+ }
253
+
254
+ /** The variable a name binds to, walking up from the scope of a node. */
255
+ const variableOf = (context, identifier) => {
256
+ let scope = (context.sourceCode ?? context.getSourceCode()).getScope(identifier)
257
+ while (scope) {
258
+ const variable = scope.set.get(identifier.name)
259
+ if (variable) return variable
260
+ scope = scope.upper
261
+ }
262
+ return null
263
+ }
264
+
265
+ /** True when the type of an expression is a fetch `Response`: it has `ok`, `status` and `headers`. */
266
+ const isResponseLike = (context, node) => {
267
+ const { checker, toTs } = typed(context)
268
+ const tsNode = toTs(node)
269
+ if (!tsNode) return false
270
+ const type = checker.getTypeAtLocation(tsNode)
271
+ const parts = type.isUnion?.() ? type.types : [type]
272
+ return parts.some((part) => ["ok", "status", "headers"].every((name) => part.getProperty?.(name)))
273
+ }
274
+
275
+ /**
276
+ * True when an expression is the HTTP status of a fetch response: `response.status` where the object's type is a Response, or a
277
+ * local bound to one (`const status = response.status`, `const { status } = response`). A parameter that is only typed `number` is
278
+ * not: the rule does not guess what a bare number means.
279
+ */
280
+ /**
281
+ * A parameter stands for the response status when its function is called in this file, and every call passes a response status in
282
+ * that position: `const failureForResponse = (status: number) => ...` called as `failureForResponse(response.status)`.
283
+ */
284
+ const isStatusParameter = (context, definition, depth) => {
285
+ const fn = definition.node
286
+ const index = fn.params?.findIndex((param) => param === definition.name || (param.type === "AssignmentPattern" && param.left === definition.name))
287
+ if (index === undefined || index < 0) return false
288
+ const binding = fn.type === "FunctionDeclaration" ? fn.id : fn.parent?.type === "VariableDeclarator" && fn.parent.init === fn ? fn.parent.id : null
289
+ if (!binding || binding.type !== "Identifier") return false
290
+ const variable = variableOf(context, binding)
291
+ const calls = (variable?.references ?? []).map((reference) => reference.identifier.parent).filter((parent) => parent?.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === binding.name)
292
+ return calls.length > 0 && calls.every((call) => call.arguments[index] !== undefined && isResponseStatus(context, call.arguments[index], depth + 1))
293
+ }
294
+
295
+ const isResponseStatus = (context, node, depth = 0) => {
296
+ const expression = unwrap(node)
297
+ if (!expression || depth > 4) return false
298
+ if (expression.type === "MemberExpression") return propertyName(expression) === "status" && isResponseLike(context, unwrap(expression.object))
299
+ if (expression.type !== "Identifier") return false
300
+ const definition = variableOf(context, expression)?.defs[0]
301
+ if (definition?.type === "Parameter") return isStatusParameter(context, definition, depth)
302
+ if (!definition || definition.type !== "Variable") return false
303
+ const declarator = definition.node
304
+ if (declarator.id === definition.name) return declarator.init ? isResponseStatus(context, declarator.init, depth + 1) : false
305
+ if (declarator.id.type !== "ObjectPattern" || !declarator.init) return false
306
+ const bound = declarator.id.properties.find(
307
+ (property) => property.type === "Property" && (property.value === definition.name || (property.value.type === "AssignmentPattern" && property.value.left === definition.name)),
308
+ )
309
+ const key = bound?.key
310
+ const keyName = key?.type === "Identifier" ? key.name : key?.type === "Literal" ? key.value : null
311
+ return keyName === "status" && isResponseLike(context, unwrap(declarator.init.type === "AwaitExpression" ? declarator.init.argument : declarator.init))
312
+ }
313
+
314
+ /** The numbers a literal list stands for (`[401, 403]`, `new Set([401, 403])`, or a const bound to one), else null. */
315
+ const numbersOf = (context, node, depth = 0) => {
316
+ const expression = unwrap(node)
317
+ if (!expression || depth > 3) return null
318
+ if (expression.type === "ArrayExpression") {
319
+ const values = expression.elements.map((element) => (element && element.type === "Literal" && typeof element.value === "number" ? element.value : null))
320
+ return values.includes(null) ? null : new Set(values)
321
+ }
322
+ if (expression.type === "NewExpression" && expression.callee.type === "Identifier" && expression.callee.name === "Set" && expression.arguments.length === 1) {
323
+ return numbersOf(context, expression.arguments[0], depth + 1)
324
+ }
325
+ if (expression.type === "Identifier") {
326
+ const declarator = variableOf(context, expression)?.defs[0]?.node
327
+ return declarator?.type === "VariableDeclarator" && declarator.init ? numbersOf(context, declarator.init, depth + 1) : null
328
+ }
329
+ return null
330
+ }
331
+
332
+ /**
333
+ * The status codes a test is true for, when it is a plain status comparison: `status === 401`, `a || b` of such, or a literal list
334
+ * containing the status (`[401, 403].includes(status)`, `new Set([401, 403]).has(status)`). Null for anything else.
335
+ */
336
+ const codesOf = (context, test) => {
337
+ const expression = unwrap(test)
338
+ if (!expression) return null
339
+ if (expression.type === "LogicalExpression" && expression.operator === "||") {
340
+ const left = codesOf(context, expression.left)
341
+ const right = codesOf(context, expression.right)
342
+ return left && right ? new Set([...left, ...right]) : null
343
+ }
344
+ if (expression.type === "BinaryExpression" && (expression.operator === "===" || expression.operator === "==")) {
345
+ for (const [side, other] of [[expression.left, expression.right], [expression.right, expression.left]]) {
346
+ const literal = unwrap(other)
347
+ if (literal?.type === "Literal" && typeof literal.value === "number" && isResponseStatus(context, side)) return new Set([literal.value])
348
+ }
349
+ return null
350
+ }
351
+ if (expression.type === "CallExpression" && expression.callee.type === "MemberExpression" && expression.arguments.length === 1) {
352
+ const method = propertyName(expression.callee)
353
+ if ((method === "includes" || method === "has") && isResponseStatus(context, expression.arguments[0])) return numbersOf(context, expression.callee.object)
354
+ }
355
+ return null
356
+ }
357
+
358
+ /** True when a subtree builds an outcome of kind `"refused"`: an object whose `kind` is that literal, or a call whose first argument is it. */
359
+ const buildsRefused = (node) => {
360
+ let found = false
361
+ const visit = (current) => {
362
+ if (found || !current || typeof current.type !== "string") return
363
+ if (current.type === "Property" && !current.computed) {
364
+ const key = current.key
365
+ const named = (key.type === "Identifier" && key.name === "kind") || (key.type === "Literal" && key.value === "kind")
366
+ const value = unwrap(current.value)
367
+ if (named && value?.type === "Literal" && value.value === "refused") found = true
368
+ }
369
+ // A constructor of the Outcome vocabulary named by its kind: `failed("refused", { ... })`.
370
+ if (current.type === "CallExpression" && current.arguments[0]?.type === "Literal" && current.arguments[0].value === "refused") found = true
371
+ for (const [name, child] of Object.entries(current)) {
372
+ if (name === "parent") continue
373
+ if (Array.isArray(child)) child.forEach(visit)
374
+ else if (child && typeof child.type === "string") visit(child)
375
+ }
376
+ }
377
+ visit(node)
378
+ return found
379
+ }
380
+
381
+ /**
382
+ * The client maps 401 and 403 to `refused`, so "sign in" is a state a reader can reach.
383
+ *
384
+ * It judges a real branch in the client file: a comparison of the fetch response's status (typed as a `Response`) with 401 and with
385
+ * 403 (`===`, `||`, a literal list, a `switch` with both cases), whose consequent builds an object with `kind: "refused"`. The three
386
+ * literals lying anywhere in the file do not pass. A mapping delegated to a function in another file is not visible here and does
387
+ * not pass either: the client is the one file that owns the status meaning.
388
+ */
146
389
  export const clientMapsAuthToRefused = {
147
390
  meta: {
148
391
  type: "problem",
149
- docs: { description: "`modules/api/client.ts` handles 401 and 403 and produces `refused`." },
392
+ docs: { description: "The api client branches on the response status 401 and 403 and builds a `refused` outcome there." },
150
393
  schema: [],
151
394
  messages: {
152
395
  refused:
153
- "This client calls `fetch` but does not map 401 and 403 to a `refused` outcome. Without that branch a signed-out reader is reported as \"could not load\" and never reaches the sign-in state.",
396
+ "This client calls `fetch` but has no branch that turns a 401 and a 403 status of the response into an outcome of kind `refused`. Without that branch a signed-out reader is reported as \"could not load\" and never reaches the sign-in state. Compare `response.status` with 401 and 403 and return `{ ok: false, kind: \"refused\" }` there.",
154
397
  },
155
398
  },
156
399
  create(context) {
157
- if (!isApiClient(context.filename || context.getFilename())) return {}
158
- let fetches = false
159
- const seen = { refused: false, 401: false, 403: false }
400
+ if (!isApiClient(context)) return {}
401
+ const covered = new Set()
402
+ const cover = (test, consequent) => {
403
+ const codes = codesOf(context, test)
404
+ if (codes && buildsRefused(consequent)) codes.forEach((code) => covered.add(code))
405
+ }
160
406
  return {
161
- CallExpression(node) {
162
- if (isFetchCall(node)) fetches = true
163
- },
164
- Literal(node) {
165
- if (node.value === "refused") seen.refused = true
166
- if (node.value === 401) seen[401] = true
167
- if (node.value === 403) seen[403] = true
407
+ IfStatement: (node) => cover(node.test, node.consequent),
408
+ ConditionalExpression: (node) => cover(node.test, node.consequent),
409
+ SwitchStatement(node) {
410
+ if (!isResponseStatus(context, node.discriminant)) return
411
+ let pending = new Set()
412
+ for (const entry of node.cases) {
413
+ const label = unwrap(entry.test)
414
+ if (label?.type === "Literal" && typeof label.value === "number") pending.add(label.value)
415
+ if (entry.consequent.length === 0) continue
416
+ if (entry.consequent.some(buildsRefused)) pending.forEach((code) => covered.add(code))
417
+ pending = new Set()
418
+ }
168
419
  },
169
420
  "Program:exit"(program) {
170
- if (fetches && !(seen.refused && seen[401] && seen[403])) {
171
- context.report({ node: program, messageId: "refused" })
172
- }
421
+ const fetches = transportUses(context).some((use) => use.kind === "fetch")
422
+ if (fetches && !(covered.has(401) && covered.has(403))) context.report({ node: program, messageId: "refused" })
173
423
  },
174
424
  }
175
425
  },
@@ -299,44 +549,71 @@ const isJsonRead = (node) => {
299
549
  /** A GraphQL operation written as text. */
300
550
  const GRAPHQL_TEXT = /^\s*(?:query|mutation|subscription|fragment)\b[^{]*\{/
301
551
 
552
+ /** The leftmost identifier of a type name: `Course` in `Course`, `Gql` in `Gql.CourseQuery`. */
553
+ const typeRoot = (name) => (name.type === "TSQualifiedName" ? typeRoot(name.left) : name)
554
+
555
+ /** The value an identifier is initialised with when it is a `const` of this file's scope chain, else null. */
556
+ const constInit = (scope, identifier) => {
557
+ for (let current = scope; current; current = current.upper) {
558
+ const variable = current.set.get(identifier.name)
559
+ if (!variable) continue
560
+ const definition = variable.defs[0]
561
+ return definition?.type === "Variable" && definition.parent?.kind === "const" && definition.node.id.type === "Identifier" ? definition.node.init : null
562
+ }
563
+ return null
564
+ }
565
+
302
566
  /** Wire types are generated from the contract; nobody types the wire by hand. */
303
567
  export const noHandTypedWire = {
304
568
  meta: {
305
569
  type: "problem",
306
- docs: { description: "Wire types come from the contract copy via codegen; responses are not cast." },
570
+ docs: { description: "A transport response body is narrowed from `unknown` or typed by a generated wire type, never by a hand-written one." },
307
571
  schema: [],
308
572
  messages: {
309
573
  cast:
310
- "A response body is cast to a type here. A cast is a claim nobody checks: when the backend changes the shape this still compiles and fails at a reader's screen. Use the type generated from `modules/api/contract`, and validate at the client.",
311
- graphqlType:
312
- "`{{name}}` is a hand-written GraphQL result type used as a cast. The generated document type already says exactly what this operation returns; use it.",
574
+ "A response body is typed by hand here. An assertion or annotation is a claim nobody checks: when the backend changes the shape this still compiles and fails at a reader's screen. Narrow the body from `unknown` (`(await response.json()) as unknown`, then a check), or use the type generated from `modules/api/contract` (imported from `__generated__/`), and validate at the client.",
313
575
  document:
314
576
  "A GraphQL document written inline in TypeScript. Documents live in `.graphql` files so codegen can generate their types and the contract check can read them.",
315
- declared:
316
- "`{{name}}` declares a wire shape by hand in `modules/api`. Wire types are generated from the backend contract (`codegen`), so a hand-written copy is a second source of truth that drifts. Import the generated type.",
317
577
  },
318
578
  },
319
579
  create(context) {
320
580
  const filename = context.filename || context.getFilename()
321
581
  if (isSpecFile(filename)) return {}
322
- const inApi = isApiModuleFile(filename)
323
- const castCheck = (node) => {
324
- const type = node.typeAnnotation
325
- if (type && type.type === "TSTypeReference" && type.typeName.type === "Identifier") {
326
- if (/^Graph[Qq][Ll]\w*$/.test(type.typeName.name)) {
327
- context.report({ node, messageId: "graphqlType", data: { name: type.typeName.name } })
328
- return
329
- }
330
- }
331
- if (isJsonRead(node.expression)) context.report({ node, messageId: "cast" })
582
+ const source = context.sourceCode ?? context.getSourceCode()
583
+ /** Local names of the type imports that resolve into a `__generated__/` directory. */
584
+ const generated = new Set()
585
+ /** True when a type node is `unknown` or names a type imported from the generated wire module. */
586
+ const sanctioned = (type) => {
587
+ if (type.type === "TSUnknownKeyword") return true
588
+ if (type.type !== "TSTypeReference") return false
589
+ const root = typeRoot(type.typeName)
590
+ return root.type === "Identifier" && (root.name === "const" || generated.has(root.name))
591
+ }
592
+ /** Whether the value is a `.json()` read, directly or through a const initialised with one. */
593
+ const readsResponse = (node) => {
594
+ if (isJsonRead(node)) return true
595
+ let current = node
596
+ while (current && (current.type === "AwaitExpression" || current.type === "TSNonNullExpression")) current = current.argument || current.expression
597
+ if (current?.type !== "Identifier") return false
598
+ const init = constInit(source.getScope(node), current)
599
+ return Boolean(init) && isJsonRead(init)
332
600
  }
333
- const declared = (node) => {
334
- if (!inApi || !/(?:Wire|Dto|DTO|Response|Payload)$/.test(node.id.name)) return
335
- context.report({ node: node.id, messageId: "declared", data: { name: node.id.name } })
601
+ const castCheck = (node) => {
602
+ if (readsResponse(node.expression) && !sanctioned(node.typeAnnotation)) context.report({ node, messageId: "cast" })
336
603
  }
337
604
  return {
605
+ Program(program) {
606
+ for (const statement of program.body) {
607
+ if (statement.type !== "ImportDeclaration" || !String(statement.source.value).split("/").includes("__generated__")) continue
608
+ for (const specifier of statement.specifiers) generated.add(specifier.local.name)
609
+ }
610
+ },
338
611
  TSAsExpression: castCheck,
339
612
  TSTypeAssertion: castCheck,
613
+ VariableDeclarator(node) {
614
+ const annotation = node.id.type === "Identifier" ? node.id.typeAnnotation?.typeAnnotation : null
615
+ if (annotation && node.init && readsResponse(node.init) && !sanctioned(annotation)) context.report({ node, messageId: "cast" })
616
+ },
340
617
  TaggedTemplateExpression(node) {
341
618
  if (node.tag.type === "Identifier" && /^(?:gql|graphql)$/.test(node.tag.name)) {
342
619
  context.report({ node, messageId: "document" })
@@ -352,8 +629,6 @@ export const noHandTypedWire = {
352
629
  context.report({ node, messageId: "document" })
353
630
  }
354
631
  },
355
- TSInterfaceDeclaration: declared,
356
- TSTypeAliasDeclaration: declared,
357
632
  }
358
633
  },
359
634
  }
@@ -389,6 +664,78 @@ export const outcomeKindsExhaustive = {
389
664
  },
390
665
  }
391
666
 
667
+ // -- FE-OUTCOME-1 ---------------------------------------------------------------------------------
668
+
669
+ /** The `kind` values of an Outcome failure (HFS section 6.2, plus the session-accepted-but-denied `forbidden`): a `kind` union that carries one is a result union. */
670
+ const RESULT_KINDS = new Set([...OUTCOME_KINDS, "forbidden"])
671
+
672
+ const LITERAL_FLAGS = ts.TypeFlags.StringLiteral | ts.TypeFlags.BooleanLiteral
673
+
674
+ /** The literal values of a property of an object type, or null when the property is missing or not literal-typed. */
675
+ const literalsOf = (checker, type, name, location) => {
676
+ const property = type.getProperty?.(name)
677
+ if (!property) return null
678
+ const propertyType = checker.getTypeOfSymbolAtLocation(property, location)
679
+ const parts = propertyType.isUnion?.() ? propertyType.types : [propertyType]
680
+ if (!parts.every((part) => (part.flags & LITERAL_FLAGS) !== 0)) return null
681
+ return parts.map((part) => (part.flags & ts.TypeFlags.BooleanLiteral ? part.intrinsicName === "true" : part.value))
682
+ }
683
+
684
+ /**
685
+ * A result union is declared once per repository: `Outcome<T>` in the `fe.transport.outcome` / `fe.package.api.outcome` file.
686
+ *
687
+ * A union type alias is a result union when its members are object types that ALL carry the same literal-typed discriminant, in the
688
+ * result vocabulary: `ok` (both `true` and `false` among the members) or `kind` (a member of kind `"ok"` beside at least one failure
689
+ * kind of the Outcome vocabulary: refused, forbidden, invalid, not-found, unavailable). A view union that a mapper derives from an
690
+ * Outcome (`{ kind: "ready" } | { kind: "not-found" }`, no `ok` arm) is a screen state, not a second result vocabulary. The check reads the resolved members through the checker, so
691
+ * `Ok<T> | Failure` and an intersection are seen as what they are, and no name (`*Outcome`, `*Result`) decides anything.
692
+ * A UI state union (`{ status: "idle" } | { status: "saving" }`, `{ type: ... }`, a `kind` of menu items) is not result
693
+ * vocabulary and passes. An alias that only composes the one union (`type Read = Outcome<Course>`, `Extract<Outcome<T>, ...>`) is not
694
+ * a union type node and passes; `Outcome<T> | { ok: false; kind: "conflict" }` adds an arm to the one union and is refused.
695
+ */
696
+ export const oneOutcomeUnion = {
697
+ meta: {
698
+ type: "problem",
699
+ docs: { description: "A result union (`ok` / `kind` discriminant) is declared only in the outcome slot; elsewhere the code composes `Outcome<T>`." },
700
+ schema: [],
701
+ messages: {
702
+ second:
703
+ "`{{name}}` is a second result union ({{discriminant}}). The repository has one vocabulary, `Outcome<T>`, declared in `modules/api/outcome.ts` (or the api package's `src/outcome.ts`); a bespoke union here is a result shape the client, the status mapping and `outcome-kinds-exhaustive` know nothing about. Compose `Outcome<T>` (add the domain detail as its second parameter) instead of declaring another.",
704
+ },
705
+ },
706
+ create(context) {
707
+ if (isSpecFile(context.filename || context.getFilename()) || isOutcomeModule(context)) return {}
708
+ const { checker, toTs } = typed(context)
709
+ return {
710
+ TSTypeAliasDeclaration(node) {
711
+ let annotation = node.typeAnnotation
712
+ while (annotation.type === "TSParenthesizedType") annotation = annotation.typeAnnotation
713
+ if (annotation.type !== "TSUnionType") return
714
+ const tsNode = toTs(node)
715
+ if (!tsNode) return
716
+ const type = checker.getTypeAtLocation(tsNode.name)
717
+ if (!type.isUnion?.() || type.types.length < 2) return
718
+ // The members must all be object types (an object, or an intersection of them).
719
+ if (!type.types.every((member) => (member.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection)) !== 0)) return
720
+ for (const discriminant of ["ok", "kind"]) {
721
+ const values = type.types.map((member) => literalsOf(checker, member, discriminant, tsNode))
722
+ if (values.some((entry) => entry === null)) continue
723
+ const flat = values.flat()
724
+ // `ok` is a discriminant only when each member pins it to one value; `{ ok: boolean }` on every member is a flag, not a tag.
725
+ const isResult =
726
+ discriminant === "ok"
727
+ ? values.every((entry) => entry.length === 1) && flat.includes(true) && flat.includes(false)
728
+ : flat.includes("ok") && flat.some((value) => value !== "ok" && RESULT_KINDS.has(value))
729
+ if (isResult) {
730
+ context.report({ node: node.id, messageId: "second", data: { name: node.id.name, discriminant: `\`${discriminant}\` discriminant` } })
731
+ return
732
+ }
733
+ }
734
+ },
735
+ }
736
+ },
737
+ }
738
+
392
739
  /** The rules this law contributes to the plugin. */
393
740
  export const rules = {
394
741
  "fetch-only-in-api-client": fetchOnlyInApiClient,
@@ -398,6 +745,7 @@ export const rules = {
398
745
  "no-http-status-collapse": noHttpStatusCollapse,
399
746
  "no-hand-typed-wire": noHandTypedWire,
400
747
  "outcome-kinds-exhaustive": outcomeKindsExhaustive,
748
+ "one-outcome-union": oneOutcomeUnion,
401
749
  }
402
750
 
403
751
  /** Every rule is an error: a second transport or a status collapse is the defect, not a style. */