@starci/eslint-canon-fe 9.2.0 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +5 -1
  3. package/dist/brand-values.d.ts +28 -0
  4. package/dist/brand-values.js +172 -0
  5. package/dist/button-intent.d.ts +11 -0
  6. package/dist/button-intent.js +361 -0
  7. package/dist/callback-shape.d.ts +7 -0
  8. package/dist/callback-shape.js +396 -0
  9. package/dist/class-names.d.ts +19 -0
  10. package/dist/class-names.js +170 -0
  11. package/dist/client-boundary.d.ts +42 -0
  12. package/dist/client-boundary.js +404 -0
  13. package/dist/comments.d.ts +47 -0
  14. package/dist/comments.js +156 -0
  15. package/dist/control-height.d.ts +7 -0
  16. package/dist/control-height.js +83 -0
  17. package/dist/drawing.d.ts +31 -0
  18. package/dist/drawing.js +376 -0
  19. package/dist/env-owner.d.ts +22 -0
  20. package/dist/env-owner.js +291 -0
  21. package/dist/fe-stack.d.ts +10 -0
  22. package/dist/fe-stack.js +73 -0
  23. package/dist/file-layout.d.ts +71 -0
  24. package/dist/file-layout.js +465 -0
  25. package/dist/formatting.d.ts +25 -0
  26. package/dist/formatting.js +104 -0
  27. package/dist/function-budget.d.ts +9 -0
  28. package/dist/function-budget.js +48 -0
  29. package/dist/grammar-shim.d.ts +5 -0
  30. package/dist/grammar-shim.js +126 -0
  31. package/dist/hooks-folder.d.ts +34 -0
  32. package/dist/hooks-folder.js +320 -0
  33. package/dist/hygiene.d.ts +39 -0
  34. package/dist/hygiene.js +540 -0
  35. package/dist/index.d.ts +105 -0
  36. package/dist/index.js +310 -0
  37. package/{landmark.mjs → dist/landmark.d.ts} +4 -6
  38. package/dist/landmark.js +6 -0
  39. package/dist/lib/ast.d.ts +36 -0
  40. package/dist/lib/ast.js +94 -0
  41. package/dist/lib/bindings.d.ts +84 -0
  42. package/dist/lib/bindings.js +168 -0
  43. package/dist/lib/class-text.d.ts +3 -0
  44. package/dist/lib/class-text.js +30 -0
  45. package/dist/lib/config.d.ts +81 -0
  46. package/dist/lib/config.js +141 -0
  47. package/dist/lib/drawing-scope.d.ts +5 -0
  48. package/{lib/drawing-scope.mjs → dist/lib/drawing-scope.js} +6 -11
  49. package/dist/lib/eslint-boundary.d.ts +23 -0
  50. package/dist/lib/eslint-boundary.js +6 -0
  51. package/dist/lib/fe-stack.d.ts +49 -0
  52. package/dist/lib/fe-stack.js +98 -0
  53. package/dist/lib/hfs-view.d.ts +74 -0
  54. package/dist/lib/hfs-view.js +6 -0
  55. package/dist/lib/hfs.d.ts +34 -0
  56. package/dist/lib/hfs.js +72 -0
  57. package/dist/lib/next.d.ts +4 -0
  58. package/dist/lib/next.js +10 -0
  59. package/dist/lib/own-hook-origin.d.ts +17 -0
  60. package/dist/lib/own-hook-origin.js +52 -0
  61. package/dist/lib/package-root.d.ts +4 -0
  62. package/dist/lib/package-root.js +10 -0
  63. package/dist/lib/path.d.ts +2 -0
  64. package/{lib/path.mjs → dist/lib/path.js} +1 -1
  65. package/dist/lib/platform.d.ts +26 -0
  66. package/{lib/platform.mjs → dist/lib/platform.js} +38 -35
  67. package/dist/lib/program-for.d.ts +5 -0
  68. package/dist/lib/program-for.js +23 -0
  69. package/dist/lib/pure-owner-helper.d.ts +10 -0
  70. package/dist/lib/pure-owner-helper.js +156 -0
  71. package/dist/lib/react.d.ts +16 -0
  72. package/dist/lib/react.js +22 -0
  73. package/dist/lib/redux-hook-origin.d.ts +4 -0
  74. package/dist/lib/redux-hook-origin.js +50 -0
  75. package/dist/lib/rule.d.ts +28 -0
  76. package/dist/lib/rule.js +5 -0
  77. package/dist/lib/scope.d.ts +88 -0
  78. package/{lib/scope.mjs → dist/lib/scope.js} +83 -93
  79. package/dist/lib/typed-class-values.d.ts +13 -0
  80. package/dist/lib/typed-class-values.js +92 -0
  81. package/dist/lib/types.d.ts +44 -0
  82. package/dist/lib/types.js +64 -0
  83. package/dist/lib/why.d.ts +350 -0
  84. package/dist/lib/why.js +350 -0
  85. package/dist/lint-escape-hatch.d.ts +24 -0
  86. package/{lint-escape-hatch.mjs → dist/lint-escape-hatch.js} +38 -45
  87. package/dist/lists.d.ts +31 -0
  88. package/dist/lists.js +202 -0
  89. package/dist/loading.d.ts +34 -0
  90. package/dist/loading.js +157 -0
  91. package/dist/naming.d.ts +33 -0
  92. package/dist/naming.js +176 -0
  93. package/dist/native-controls.d.ts +24 -0
  94. package/dist/native-controls.js +105 -0
  95. package/dist/next-conventions.d.ts +48 -0
  96. package/dist/next-conventions.js +452 -0
  97. package/dist/project-graph.d.ts +5 -0
  98. package/{project-graph.mjs → dist/project-graph.js} +8 -12
  99. package/dist/props-and-slots.d.ts +19 -0
  100. package/dist/props-and-slots.js +320 -0
  101. package/dist/served-locale.d.ts +38 -0
  102. package/dist/served-locale.js +263 -0
  103. package/dist/shape-slot.d.ts +18 -0
  104. package/dist/shape-slot.js +324 -0
  105. package/dist/size-and-state-budget.d.ts +46 -0
  106. package/dist/size-and-state-budget.js +424 -0
  107. package/dist/size-growth.d.ts +24 -0
  108. package/dist/size-growth.js +64 -0
  109. package/dist/sonar-parity.d.ts +5 -0
  110. package/{sonar-parity.mjs → dist/sonar-parity.js} +11 -7
  111. package/dist/surface-rules.d.ts +18 -0
  112. package/dist/surface-rules.js +491 -0
  113. package/dist/swr-family.d.ts +15 -0
  114. package/dist/swr-family.js +419 -0
  115. package/dist/the-split.d.ts +27 -0
  116. package/dist/the-split.js +157 -0
  117. package/dist/tokens.d.ts +9 -0
  118. package/dist/tokens.js +35 -0
  119. package/dist/translation.d.ts +51 -0
  120. package/dist/translation.js +403 -0
  121. package/dist/transport.d.ts +73 -0
  122. package/dist/transport.js +885 -0
  123. package/dist/type-safety.d.ts +43 -0
  124. package/dist/type-safety.js +139 -0
  125. package/dist/ui-rulings.d.ts +11 -0
  126. package/dist/ui-rulings.js +121 -0
  127. package/package.json +31 -9
  128. package/runtime/knowledge/hfs/canon-pins.yaml +22 -14
  129. package/runtime/scripts/lib/package-at.mjs +5 -5
  130. package/brand-values.mjs +0 -172
  131. package/button-intent.mjs +0 -320
  132. package/callback-shape.mjs +0 -332
  133. package/class-names.mjs +0 -149
  134. package/client-boundary.mjs +0 -400
  135. package/comments.mjs +0 -159
  136. package/control-height.mjs +0 -77
  137. package/drawing.mjs +0 -315
  138. package/env-owner.mjs +0 -244
  139. package/fe-stack.mjs +0 -86
  140. package/file-layout.mjs +0 -472
  141. package/formatting.mjs +0 -110
  142. package/function-budget.mjs +0 -49
  143. package/grammar-shim.mjs +0 -123
  144. package/hooks-folder.mjs +0 -300
  145. package/hygiene.mjs +0 -513
  146. package/index.mjs +0 -317
  147. package/lib/ast.mjs +0 -97
  148. package/lib/bindings.mjs +0 -159
  149. package/lib/class-text.mjs +0 -29
  150. package/lib/config.mjs +0 -142
  151. package/lib/fe-stack.mjs +0 -77
  152. package/lib/hfs.mjs +0 -49
  153. package/lib/next.mjs +0 -6
  154. package/lib/own-hook-origin.mjs +0 -53
  155. package/lib/program-for.mjs +0 -22
  156. package/lib/pure-owner-helper.mjs +0 -148
  157. package/lib/react.mjs +0 -28
  158. package/lib/redux-hook-origin.mjs +0 -44
  159. package/lib/typed-class-values.mjs +0 -81
  160. package/lib/types.mjs +0 -63
  161. package/lib/why.mjs +0 -352
  162. package/lists.mjs +0 -193
  163. package/loading.mjs +0 -156
  164. package/naming.mjs +0 -185
  165. package/native-controls.mjs +0 -108
  166. package/next-conventions.mjs +0 -447
  167. package/props-and-slots.mjs +0 -276
  168. package/served-locale.mjs +0 -243
  169. package/size-and-state-budget.mjs +0 -376
  170. package/size-growth.mjs +0 -62
  171. package/surface-rules.mjs +0 -443
  172. package/swr-family.mjs +0 -326
  173. package/the-split.mjs +0 -155
  174. package/tokens.mjs +0 -39
  175. package/translation.mjs +0 -392
  176. package/transport.mjs +0 -830
  177. package/type-safety.mjs +0 -147
  178. package/ui-rulings.mjs +0 -134
@@ -1,276 +0,0 @@
1
- /** Rules for named React props, ordinary children, and local visual ownership. */
2
-
3
- import { declarationsOf, fileOf as declarationFile } from "./lib/types.mjs"
4
- import { fileOf, isComponentFile, isComponentPath, isProductSource, kindOfFile } from "./lib/scope.mjs"
5
-
6
- const propertyName = (node) => {
7
- const key = node?.key ?? node?.property
8
- if (!key) return null
9
- if (key.type === "Identifier") return key.name
10
- if (key.type === "Literal" && typeof key.value === "string") return key.value
11
- return null
12
- }
13
-
14
- /** Reject anonymous object types on named component parameters. */
15
- export const noInlineParameterType = {
16
- meta: {
17
- type: "suggestion",
18
- docs: { description: "A parameter uses a named props type, not an inline object shape." },
19
- schema: [],
20
- messages: { inline: "Name this parameter type in the module so the component API can be reused." },
21
- },
22
- create(context) {
23
- const check = (node) => {
24
- for (const param of node.params || []) {
25
- const type = param?.typeAnnotation?.typeAnnotation
26
- if (type?.type === "TSTypeLiteral" || type?.type === "TSIntersectionType" && type.types.some((item) => item.type === "TSTypeLiteral")) {
27
- context.report({ node: param.typeAnnotation || param, messageId: "inline" })
28
- }
29
- }
30
- }
31
- return { ArrowFunctionExpression: check, FunctionExpression: check, FunctionDeclaration: check }
32
- },
33
- }
34
-
35
- const isExported = (node) => node.parent?.type === "ExportNamedDeclaration" || node.parent?.parent?.type === "ExportNamedDeclaration"
36
- const containsJsx = (node, seen = new Set()) => {
37
- if (!node || typeof node !== "object" || seen.has(node)) return false
38
- seen.add(node)
39
- if (node.type === "JSXElement" || node.type === "JSXFragment") return true
40
- return Object.entries(node).some(([key, value]) => key !== "parent" && (Array.isArray(value) ? value.some((item) => containsJsx(item, seen)) : containsJsx(value, seen)))
41
- }
42
- const componentNameOf = (node) => {
43
- if (node.type !== "VariableDeclarator" || node.id?.type !== "Identifier" || !/^[A-Z]/.test(node.id.name) || !isExported(node)) return null
44
- return node.id.name
45
- }
46
-
47
- /** Require exported React components to take no parameter, or one named props parameter. */
48
- export const publicComponentSignature = {
49
- meta: {
50
- type: "problem",
51
- docs: { description: "Exported React components take no parameter, or one parameter named props with a matching XProps type (XBase may also take XBaseProps)." },
52
- schema: [],
53
- messages: {
54
- parameter: "Exported component {{name}} must be an arrow const with no parameter, or exactly one parameter named props.",
55
- type: "Exported component {{name}} must type props as {{expected}}.",
56
- },
57
- },
58
- create(context) {
59
- const check = (node, name, fn) => {
60
- if (!name || !fn) return
61
- const params = fn.params || []
62
- if (params.length === 0) return
63
- if (params.length !== 1 || params[0].type !== "Identifier" || params[0].name !== "props") {
64
- context.report({ node: fn, messageId: "parameter", data: { name } })
65
- return
66
- }
67
- const type = params[0].typeAnnotation?.typeAnnotation
68
- // XBase pairs with XBaseProps so the connected X keeps XProps for itself; XProps stays accepted for
69
- // existing twins.
70
- const expected = name.endsWith("Base") ? [`${name}Props`, `${name.slice(0, -4)}Props`] : [`${name}Props`]
71
- const actual = type?.type === "TSTypeReference" && type.typeName?.type === "Identifier" ? type.typeName.name : null
72
- if (!actual || !expected.includes(actual)) context.report({ node: params[0], messageId: "type", data: { name, expected: expected.join(" or ") } })
73
- }
74
- if (!isComponentFile(context)) return {}
75
- return {
76
- VariableDeclarator(node) {
77
- const name = componentNameOf(node)
78
- if (name && node.init?.type === "ArrowFunctionExpression" && containsJsx(node.init)) check(node, name, node.init)
79
- },
80
- FunctionDeclaration(node) {
81
- if (!isExported(node) || !containsJsx(node)) return
82
- context.report({ node, messageId: "parameter", data: { name: node.id?.name || "component" } })
83
- },
84
- }
85
- },
86
- }
87
-
88
- /** Prevent callers from styling internal component parts through named CSS props. */
89
- export const noPerPartClassNameProp = {
90
- meta: {
91
- type: "problem",
92
- docs: { description: "Components do not expose per-part class name props." },
93
- schema: [],
94
- messages: { perPart: "Keep internal part styling owned by the component." },
95
- },
96
- create(context) {
97
- if (!isComponentFile(context)) return {}
98
- return { TSPropertySignature(node) { const name = propertyName(node); if (name && name !== "className" && /^[a-z][A-Za-z0-9]*ClassName$/.test(name)) context.report({ node, messageId: "perPart" }) } }
99
- },
100
- }
101
-
102
- /** Keep component appearance local instead of exposing className placement doors. */
103
- export const noPublicClassNameProp = {
104
- meta: {
105
- type: "problem",
106
- docs: { description: "House components do not expose className or classNames props." },
107
- schema: [],
108
- messages: { declaration: "Component props must not expose {{prop}}.", usage: "Do not pass {{prop}} to house component {{component}}." },
109
- },
110
- create(context) {
111
- const declared = isComponentFile(context)
112
- /** A house component: the identifier resolves (through its import) to a file of a component layer. */
113
- const isHouseComponent = (identifier) => declarationsOf(context, identifier).some((declaration) => isComponentPath(context, declarationFile(declaration)))
114
- return {
115
- TSPropertySignature(node) { if (declared && ["className", "classNames"].includes(propertyName(node))) context.report({ node, messageId: "declaration", data: { prop: propertyName(node) } }) },
116
- JSXOpeningElement(node) {
117
- const identifier = node.name?.type === "JSXIdentifier" ? node.name : null
118
- if (!identifier) return
119
- const styled = (node.attributes || []).filter((attribute) => ["className", "classNames"].includes(attribute.name?.type === "JSXIdentifier" ? attribute.name.name : null))
120
- if (styled.length === 0 || !isHouseComponent(identifier)) return
121
- for (const attribute of styled) context.report({ node: attribute, messageId: "usage", data: { prop: attribute.name.name, component: identifier.name } })
122
- },
123
- }
124
- },
125
- }
126
-
127
- /** Keep layout APIs semantic rather than exposing raw CSS decisions above leaves. */
128
- export const noPublicFrameCssProps = {
129
- meta: { type: "problem", docs: { description: "Non-leaf component props do not expose CSS-shaped frame decisions." }, schema: [], messages: { css: "Move {{prop}} into component-owned layout behavior." } },
130
- create(context) {
131
- if (!isComponentFile(context) || kindOfFile(context) === "leaves") return {}
132
- const cssProps = new Set(["gap", "padding", "align", "justify", "className", "classNames", "style", "inline", "nested"])
133
- return { TSPropertySignature(node) { const name = propertyName(node); if (cssProps.has(name)) context.report({ node, messageId: "css", data: { prop: name } }) } }
134
- },
135
- }
136
-
137
- /** Prevent utility types from reintroducing public styling doors. */
138
- export const noCssDoorTypeLaundering = {
139
- meta: { type: "problem", docs: { description: "Omit, Pick, and Exclude cannot hide styling props." }, schema: [], messages: { utility: "Remove {{prop}} from the owning public type instead of hiding it with {{utility}}." } },
140
- create(context) {
141
- if (!isProductSource(context)) return {}
142
- return { TSTypeReference(node) { const utility = node.typeName?.type === "Identifier" ? node.typeName.name : null; const params = node.typeArguments?.params || node.typeParameters?.params || []; if (!utility || !["Omit", "Pick", "Exclude"].includes(utility)) return; const keys = params[1]?.type === "TSLiteralType" ? [params[1].literal?.value] : params[1]?.types?.map((item) => item.literal?.value) || []; const prop = keys.find((key) => ["className", "classNames", "style"].includes(key)); if (prop) context.report({ node, messageId: "utility", data: { utility, prop } }) } }
143
- },
144
- }
145
-
146
- /** The top-level declaration of a type name in this file (`interface X` or `type X = ...`), or null. */
147
- const localTypeDeclaration = (program, name) => {
148
- for (const statement of program.body) {
149
- const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement
150
- if ((declaration?.type === "TSInterfaceDeclaration" || declaration?.type === "TSTypeAliasDeclaration") && declaration.id.name === name) return declaration
151
- }
152
- return null
153
- }
154
-
155
- /** The type the first parameter of a function declares, or null. */
156
- const firstParameterType = (fn) => {
157
- const param = fn.params?.[0]
158
- const annotated = param?.type === "AssignmentPattern" ? param.left : param
159
- return annotated?.typeAnnotation?.typeAnnotation ?? null
160
- }
161
-
162
- /** The exported functions of a file that render (contain JSX): a component, whatever it is called. */
163
- const exportedRenderers = (program) => program.body.flatMap((statement) => {
164
- const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : null
165
- if (!declaration) return []
166
- const functions = declaration.type === "VariableDeclaration"
167
- ? declaration.declarations.map((item) => item.init).filter((init) => init?.type === "ArrowFunctionExpression" || init?.type === "FunctionExpression")
168
- : declaration.type === "FunctionDeclaration" || declaration.type === "ArrowFunctionExpression" || declaration.type === "FunctionExpression" ? [declaration] : []
169
- return functions.filter((fn) => fn.params.length === 1 && containsJsx(fn.body))
170
- })
171
-
172
- /** Props are readonly all the way down: every field, index signature, nested object and collection (FE-TYPING-2). */
173
- export const propsFieldsReadonly = {
174
- meta: {
175
- type: "problem",
176
- docs: { description: "Every field of a component's props type, nested objects and collections included, is readonly." },
177
- schema: [],
178
- messages: {
179
- field: "Props field `{{name}}` is not readonly. A component reads its props and never writes them: mark it `readonly` so a write is a type error.",
180
- index: "This props index signature is not readonly. Mark it `readonly [key: ...]` so no entry can be written through props.",
181
- collection: "This props collection is mutable. Write `readonly T[]`, `readonly [A, B]` or `ReadonlyArray<T>` so the component cannot change what it was given.",
182
- },
183
- },
184
- create(context) {
185
- if (!isProductSource(context)) return {}
186
- const sourceCode = context.sourceCode || context.getSourceCode()
187
- return {
188
- "Program:exit"(program) {
189
- const seen = new Set()
190
- /** Checks one type: object members, collections and the local declarations it names. */
191
- const checkType = (type) => {
192
- if (!type || seen.has(type)) return
193
- seen.add(type)
194
- if (type.type === "TSTypeOperator" && type.operator === "readonly") {
195
- checkElements(type.typeAnnotation)
196
- return
197
- }
198
- if (type.type === "TSArrayType" || type.type === "TSTupleType") {
199
- context.report({ node: type, messageId: "collection" })
200
- checkElements(type)
201
- return
202
- }
203
- if (type.type === "TSUnionType" || type.type === "TSIntersectionType") {
204
- for (const part of type.types) checkType(part)
205
- return
206
- }
207
- if (type.type === "TSTypeLiteral") {
208
- checkMembers(type.members)
209
- return
210
- }
211
- if (type.type !== "TSTypeReference" || type.typeName.type !== "Identifier") return
212
- const name = type.typeName.name
213
- const args = type.typeArguments?.params ?? type.typeParameters?.params ?? []
214
- // `Readonly<T>` makes the top level readonly; what T nests is still judged
215
- if (name === "Readonly" && args.length === 1 && !isShadowed(type.typeName)) {
216
- checkNested(args[0])
217
- return
218
- }
219
- if (name === "Array" && !isShadowed(type.typeName)) context.report({ node: type, messageId: "collection" })
220
- if ((name === "Array" || name === "ReadonlyArray") && !isShadowed(type.typeName)) {
221
- for (const arg of args) checkType(arg)
222
- return
223
- }
224
- const declaration = localTypeDeclaration(program, name)
225
- if (!declaration || seen.has(declaration)) return
226
- seen.add(declaration)
227
- if (declaration.type === "TSTypeAliasDeclaration") checkType(declaration.typeAnnotation)
228
- else {
229
- checkMembers(declaration.body.body)
230
- for (const heritage of declaration.extends ?? []) {
231
- if (heritage.expression.type === "Identifier") checkType({ type: "TSTypeReference", typeName: heritage.expression, typeArguments: heritage.typeArguments })
232
- }
233
- }
234
- }
235
- /** The element types of a collection, judged like any other props type. */
236
- const checkElements = (collection) => {
237
- if (collection?.type === "TSArrayType") checkType(collection.elementType)
238
- else if (collection?.type === "TSTupleType") for (const element of collection.elementTypes) checkType(element.type === "TSNamedTupleMember" ? element.elementType : element)
239
- else checkType(collection)
240
- }
241
- /** A `Readonly<T>` argument: its own fields are readonly, its nested values are judged. */
242
- const checkNested = (type) => {
243
- if (type?.type === "TSTypeLiteral") for (const member of type.members) checkType(member.typeAnnotation?.typeAnnotation)
244
- else checkType(type)
245
- }
246
- const checkMembers = (members) => {
247
- for (const member of members) {
248
- if (member.type === "TSPropertySignature") {
249
- if (!member.readonly) context.report({ node: member, messageId: "field", data: { name: sourceCode.getText(member.key) } })
250
- checkType(member.typeAnnotation?.typeAnnotation)
251
- } else if (member.type === "TSIndexSignature") {
252
- if (!member.readonly) context.report({ node: member, messageId: "index" })
253
- checkType(member.typeAnnotation?.typeAnnotation)
254
- }
255
- }
256
- }
257
- /** True when a built-in name is redeclared in this file, so it is not the built-in. */
258
- const isShadowed = (identifier) => localTypeDeclaration(program, identifier.name) !== null
259
- for (const fn of exportedRenderers(program)) checkType(firstParameterType(fn))
260
- },
261
- }
262
- },
263
- }
264
-
265
- export const rules = {
266
- "no-inline-parameter-type": noInlineParameterType,
267
- "props-fields-readonly": propsFieldsReadonly,
268
- "public-component-signature": publicComponentSignature,
269
- "no-per-part-classname-prop": noPerPartClassNameProp,
270
- "no-public-classname-prop": noPublicClassNameProp,
271
- "no-public-frame-css-props": noPublicFrameCssProps,
272
- "no-css-door-type-laundering": noCssDoorTypeLaundering,
273
- }
274
-
275
- /** All rules in this law are mechanical errors once adopted. */
276
- export const recommended = Object.fromEntries(Object.keys(rules).map((name) => [`starci-fe/${name}`, "error"]))
package/served-locale.mjs DELETED
@@ -1,243 +0,0 @@
1
- /**
2
- * Rules for the SERVED LOCALE law - `patterns/fe/served-locale/INDEX.md`.
3
- *
4
- * WHY THESE EXIST. An application obeyed the translation law completely - every label resolved in a
5
- * connected half, no literal below a block, both catalogues in step - and served a Vietnamese reader
6
- * an English course on a `/vi/` URL. The chrome came from the dictionary and the content came from an
7
- * API that was never told which language to serve, so the failure looked like a translation gap and
8
- * was looked for in the dictionary, where there was nothing wrong. The header was missing, and no
9
- * gate had anything to say about a header nobody wrote.
10
- *
11
- * WHAT THEY HOLD. That the transport chain declares a locale, and that exactly one place writes it.
12
- * Both are file-at-a-time facts: the chain is assembled in one file, and a header is written where it
13
- * is written.
14
- *
15
- * WHAT THEY CANNOT HOLD, stated rather than implied. Neither rule can tell whether the value the link
16
- * computes is CORRECT - whether it reads the address, the cookie or a constant - because that is
17
- * inside a function these rules only see the name of. A link that attaches `Accept-Language: "en"`
18
- * unconditionally satisfies both and is wrong. That case is a review question and LOCALE-2 is where
19
- * it is argued; pretending otherwise would be the rule claiming a guarantee it does not have.
20
- *
21
- * WHY THE FIRST RULE KEYS ON THE TERMINAL LINK RATHER THAN ON A FILE NAME. The clients folder (`modules/api/graphql/clients/`,
22
- * slot `fe.transport.client`) holds the clients, their options and every link, and a file-name pattern that guessed which of
23
- * them assembles the chain would either miss the real chain or fire on every helper beside it. The chain is identifiable by what it does: it builds the link
24
- * that talks to the network.
25
- *
26
- * WITH ONE EXEMPTION THAT WAS FOUND BY RUNNING IT, NOT BY THINKING ABOUT IT. "Constructs the
27
- * terminal link" is also true of the file that DEFINES that link, so the first version reported
28
- * `links/http.ts` and its spec on a repository that had done everything right. There was no correct
29
- * way to satisfy it there - a locale link inside the http link is a chain hiding in a link - and a
30
- * rule with no correct way to satisfy it is a finding about the rule. A file under `links/` is one
31
- * link; a chain is assembled elsewhere, which is where the locale belongs.
32
- */
33
-
34
- import { hfsOf } from "./lib/hfs.mjs"
35
- import { fileOf, isApiLayer, stem } from "./lib/scope.mjs"
36
-
37
- /**
38
- * The name of the file when it sits directly in a `links/` folder of the API layer, else null.
39
- *
40
- * NO SLOT NAMES A LINK. The clients slots (`fe.transport.client`, `fe.package.api.client`) own their whole folder, so the API
41
- * layer decides WHERE a link may be and the folder called `links` is the one fact left to the rule; the manifest would
42
- * carry it as a role (`locale-link: links/locale.ts`) and this function would ask for that role instead.
43
- */
44
- const linkFileName = (context) => {
45
- if (!isApiLayer(context)) return null
46
- const parts = hfsOf(context).relative(fileOf(context)).split("/")
47
- return parts.at(-2) === "links" ? parts.at(-1) : null
48
- }
49
-
50
- /**
51
- * The link file that owns the locale header.
52
- *
53
- * This is the ONE file allowed to write it: the `locale` link of a transport slot. The point of the second rule is that
54
- * the header appears in one place, so that place has to be named somewhere, and a name is what the law and the rule can
55
- * both refer to.
56
- */
57
- const isLocaleLinkFile = (context) => {
58
- const name = linkFileName(context)
59
- return name !== null && stem(name) === "locale"
60
- }
61
-
62
- /**
63
- * One link's own implementation, rather than a chain of them.
64
- *
65
- * WHY THIS EXEMPTION EXISTS, AND IT WAS MEASURED. The first version of the chain rule keyed only on
66
- * "constructs the terminal link", which is true of the file that DEFINES that link - `links/http.ts`
67
- * builds `new HttpLink(...)`, because that is its whole job. Run against real source it reported
68
- * that file and its spec, and there was no correct way to satisfy it there: attaching a locale link
69
- * inside the http link would be a chain hiding in a link.
70
- *
71
- * A file under `links/` is one link. A chain is assembled somewhere else, which is exactly where the
72
- * locale belongs.
73
- */
74
- const isLinkImplementationFile = (context) => linkFileName(context) !== null
75
-
76
- /** The header a request declares its language in; HTTP header names are case-insensitive. */
77
- export const LOCALE_HEADER = "Accept-Language"
78
-
79
- /** The retired locale header is refused everywhere, including the locale link. */
80
- const RETIRED_LOCALE_HEADER = "x-locale"
81
-
82
- /** Callee names that construct the terminal link - the one that actually reaches the network. */
83
- const TERMINAL_LINK_CALLEES = new Set(["createHttpLink", "HttpLink", "createUploadLink", "BatchHttpLink"])
84
-
85
- /** Callee names that attach the reader's locale to an operation. */
86
- const LOCALE_LINK_CALLEES = new Set(["createAttachLocaleLink", "createLocaleLink"])
87
-
88
- /** The callee name of a call or `new` expression, when it has a plain one. */
89
- const calleeName = (node) => {
90
- const callee = node && node.callee
91
- if (!callee) return null
92
- if (callee.type === "Identifier") return callee.name
93
- if (callee.type === "MemberExpression" && callee.property && callee.property.type === "Identifier") {
94
- return callee.property.name
95
- }
96
- return null
97
- }
98
-
99
- /** Literal and expression-free template spellings identify the same header. */
100
- const stringOf = (node) => {
101
- if (node?.type === "Literal" && typeof node.value === "string") return node.value
102
- if (node?.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked
103
- return null
104
- }
105
-
106
- /** Every static property spelling, without treating a computed variable as its identifier's name. */
107
- const keyOf = (node) => node?.property?.type === "Identifier" && !node.computed ? node.property.name : stringOf(node?.property)
108
-
109
- /** Every string-ish key a property can carry, so `"Accept-Language"` and `["Accept-Language"]` read the same. */
110
- const propertyKeyOf = (property) => {
111
- if (!property || property.type !== "Property") return null
112
- const key = property.key
113
- if (!key) return null
114
- if (key.type === "Identifier" && !property.computed) return key.name
115
- return stringOf(key)
116
- }
117
-
118
- /** Resolve a receiver's binding, so an unrelated local `Headers` or `set` method stays unrelated. */
119
- const variableOf = (node, sourceCode) => {
120
- for (let scope = sourceCode.getScope(node); scope; scope = scope.upper) {
121
- const variable = scope.set.get(node.name)
122
- if (variable) return variable
123
- }
124
- return null
125
- }
126
-
127
- /** Global browser constructors and globals may be qualified, but cannot be shadowed. */
128
- const isNativeName = (node, name, sourceCode) => {
129
- if (node?.type === "Identifier") return node.name === name && !variableOf(node, sourceCode)?.defs.length
130
- return node?.type === "MemberExpression" && keyOf(node) === name &&
131
- ["globalThis", "window"].some((global) => isNativeName(node.object, global, sourceCode))
132
- }
133
-
134
- /** Syntax establishes native Headers values and stable aliases; unknown or reassigned receivers are left alone. */
135
- const isNativeInstance = (node, name, sourceCode, seen = new Set()) => {
136
- if (!node || seen.has(node)) return false
137
- seen.add(node)
138
- const annotation = node.typeAnnotation?.typeAnnotation ?? node.typeAnnotation
139
- if (annotation?.type === "TSTypeReference" && isNativeName(annotation.typeName, name, sourceCode)) return true
140
- if (["TSAsExpression", "TSNonNullExpression", "ChainExpression"].includes(node.type)) return isNativeInstance(node.expression, name, sourceCode, seen)
141
- if (node.type === "NewExpression") return isNativeName(node.callee, name, sourceCode)
142
- if (name === "Headers" && node.type === "MemberExpression" && keyOf(node) === "headers") {
143
- return ["Request", "Response"].some((owner) => isNativeInstance(node.object, owner, sourceCode, new Set(seen)))
144
- }
145
- if (node.type !== "Identifier") return false
146
- const variable = variableOf(node, sourceCode)
147
- if (variable?.references.some((reference) => reference.isWrite() && !reference.init)) return false
148
- return (variable?.identifiers ?? []).some((identifier) => isNativeInstance(identifier, name, sourceCode, seen)) ||
149
- (variable?.defs ?? []).some((definition) => definition.type === "Variable" && isNativeInstance(definition.node.init, name, sourceCode, seen))
150
- }
151
-
152
- export const rules = {
153
- "api-client-attaches-the-locale": {
154
- meta: {
155
- type: "problem",
156
- docs: {
157
- description:
158
- "A transport chain that builds the terminal HTTP link must also attach the reader's locale, so every call declares the language it wants served.",
159
- },
160
- schema: [],
161
- messages: {
162
- missing:
163
- "This assembles the API transport but never attaches the reader's locale, so every call it makes is served the server's default language. Add the locale link to the chain, beside the auth link and unconditionally - a guest reads in a language too. A surface that is bilingual in its chrome and monolingual in its content reads as a translation gap, which is why it gets looked for in the dictionary rather than here.",
164
- },
165
- },
166
- create(context) {
167
- // A single link's implementation is not a chain - `links/http.ts` constructs the terminal link
168
- // because defining it IS its job, and there is no correct way to attach a locale there. A
169
- // spec asserts about a chain rather than being one.
170
- if (isLinkImplementationFile(context)) return {}
171
- let terminalNode = null
172
- let attachesLocale = false
173
- const note = (node) => {
174
- const name = calleeName(node)
175
- if (name === null) return
176
- if (TERMINAL_LINK_CALLEES.has(name)) terminalNode = terminalNode || node
177
- if (LOCALE_LINK_CALLEES.has(name)) attachesLocale = true
178
- }
179
- return {
180
- CallExpression: note,
181
- NewExpression: note,
182
- "Program:exit"() {
183
- if (terminalNode && !attachesLocale) {
184
- context.report({ node: terminalNode, messageId: "missing" })
185
- }
186
- },
187
- }
188
- },
189
- },
190
-
191
- "locale-header-belongs-to-the-link": {
192
- meta: {
193
- type: "problem",
194
- docs: {
195
- description:
196
- "The locale header is written by the locale link and nowhere else, so one place answers which language a request is in.",
197
- },
198
- schema: [],
199
- messages: {
200
- elsewhere:
201
- "Only the locale link may write `Accept-Language`. Setting it here is a second answer to which language this request is in, and the two diverge the first time one of them is updated - usually leaving a single hook correct and the rest of the surface on the server's default. Let the transport attach it.",
202
- retired:
203
- "The `x-locale` header is retired. Declare the reader's language with `Accept-Language` in the locale link, the one place that owns it.",
204
- },
205
- },
206
- create(context) {
207
- const ownsLocale = isLocaleLinkFile(context)
208
- const sourceCode = context.sourceCode ?? context.getSourceCode()
209
- const checkHeader = (node, key) => {
210
- const header = key?.toLowerCase()
211
- if (header === RETIRED_LOCALE_HEADER) {
212
- context.report({ node, messageId: "retired" })
213
- } else if (header === LOCALE_HEADER.toLowerCase() && !ownsLocale) {
214
- context.report({ node, messageId: "elsewhere" })
215
- }
216
- }
217
- return {
218
- Property(node) {
219
- checkHeader(node, propertyKeyOf(node))
220
- },
221
- AssignmentExpression(node) {
222
- if (node.left.type === "MemberExpression") checkHeader(node, keyOf(node.left))
223
- },
224
- NewExpression(node) {
225
- const initial = node.arguments[0]
226
- if (!isNativeName(node.callee, "Headers", sourceCode) || initial?.type !== "ArrayExpression") return
227
- for (const entry of initial.elements) {
228
- if (entry?.type === "ArrayExpression") checkHeader(entry, stringOf(entry.elements[0]))
229
- }
230
- },
231
- CallExpression(node) {
232
- const callee = node.callee
233
- if (callee.type === "MemberExpression" && ["set", "append"].includes(keyOf(callee)) && isNativeInstance(callee.object, "Headers", sourceCode)) {
234
- checkHeader(node, stringOf(node.arguments[0]))
235
- }
236
- },
237
- }
238
- },
239
- },
240
- }
241
-
242
- /** Every FE canon rule is an error; see `sources/fe/index.mjs` for why there is no warn tier. */
243
- export const recommended = Object.fromEntries(Object.keys(rules).map((name) => [`starci-fe/${name}`, "error"]))