@kerf-js/cli 0.0.0-stage → 0.1.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 (176) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +554 -2
  3. package/bin/kerf.mjs +15 -0
  4. package/docs/async.md +50 -0
  5. package/docs/browser.md +53 -0
  6. package/docs/config.md +127 -0
  7. package/docs/core.md +30 -0
  8. package/docs/deploy.md +108 -0
  9. package/docs/design.md +106 -0
  10. package/docs/entrypoints.md +83 -0
  11. package/docs/fonts.md +118 -0
  12. package/docs/icons.md +108 -0
  13. package/docs/lists.md +25 -0
  14. package/docs/meta.md +92 -0
  15. package/docs/plugins.md +166 -0
  16. package/docs/props.md +88 -0
  17. package/docs/reactivity.md +26 -0
  18. package/docs/rules.md +39 -0
  19. package/docs/rust.md +253 -0
  20. package/docs/start-short.md +10 -0
  21. package/docs/start.md +642 -0
  22. package/docs/state.md +122 -0
  23. package/docs/style.md +82 -0
  24. package/docs/surface.md +158 -0
  25. package/docs/testing.md +81 -0
  26. package/docs/theme.md +263 -0
  27. package/docs/ui-state.md +105 -0
  28. package/docs/verify.md +61 -0
  29. package/package.json +47 -3
  30. package/src/add/config.mjs +93 -0
  31. package/src/add/errors.mjs +2 -0
  32. package/src/add/setup.mjs +88 -0
  33. package/src/add-rust.mjs +178 -0
  34. package/src/add.mjs +392 -0
  35. package/src/agents-md.mjs +240 -0
  36. package/src/alias.mjs +70 -0
  37. package/src/audit/page.mjs +313 -0
  38. package/src/audit/report.mjs +69 -0
  39. package/src/audit/utils.mjs +5 -0
  40. package/src/audit.mjs +319 -0
  41. package/src/browser/cli.mjs +53 -0
  42. package/src/browser/client.mjs +299 -0
  43. package/src/browser/commands.mjs +258 -0
  44. package/src/capture.mjs +21 -0
  45. package/src/catalog/audit.mjs +129 -0
  46. package/src/catalog/auth.mjs +40 -0
  47. package/src/catalog/compiler.mjs +337 -0
  48. package/src/catalog/contracts.mjs +18 -0
  49. package/src/catalog/database.mjs +52 -0
  50. package/src/catalog/deploy.mjs +117 -0
  51. package/src/catalog/design.mjs +159 -0
  52. package/src/catalog/forms.mjs +25 -0
  53. package/src/catalog/hydration.mjs +29 -0
  54. package/src/catalog/icons.mjs +24 -0
  55. package/src/catalog/media.mjs +163 -0
  56. package/src/catalog/metadata.mjs +116 -0
  57. package/src/catalog/plugins.mjs +228 -0
  58. package/src/catalog/realtime.mjs +195 -0
  59. package/src/catalog/rust.mjs +75 -0
  60. package/src/catalog/server-functions.mjs +100 -0
  61. package/src/catalog/state.mjs +39 -0
  62. package/src/catalog/style-groups.mjs +54 -0
  63. package/src/catalog/tests.mjs +127 -0
  64. package/src/catalog/text.mjs +200 -0
  65. package/src/catalog/ui-state.mjs +42 -0
  66. package/src/catalog.mjs +103 -0
  67. package/src/check/runtime.mjs +280 -0
  68. package/src/check.mjs +321 -0
  69. package/src/cli/authoring.mjs +213 -0
  70. package/src/cli/project.mjs +302 -0
  71. package/src/cli.mjs +340 -0
  72. package/src/config.d.ts +1 -0
  73. package/src/config.mjs +5 -0
  74. package/src/contributions.mjs +119 -0
  75. package/src/db-layer.mjs +41 -0
  76. package/src/deploy/cdn.mjs +142 -0
  77. package/src/deploy/files.mjs +266 -0
  78. package/src/deploy/fit.mjs +166 -0
  79. package/src/deploy/hosts.mjs +126 -0
  80. package/src/deploy/index/cli.mjs +20 -0
  81. package/src/deploy/index/environment.mjs +69 -0
  82. package/src/deploy/index/steps.mjs +87 -0
  83. package/src/deploy/index.mjs +387 -0
  84. package/src/deploy/needs.mjs +149 -0
  85. package/src/design-checks/accessible-names.mjs +62 -0
  86. package/src/design-checks/contrast.mjs +43 -0
  87. package/src/design-checks/csp.mjs +60 -0
  88. package/src/design-checks/files.mjs +59 -0
  89. package/src/design-checks/heading-links.mjs +61 -0
  90. package/src/design-checks/interaction.mjs +65 -0
  91. package/src/design-checks/jsx.mjs +67 -0
  92. package/src/design-checks/layout-values.mjs +68 -0
  93. package/src/design-checks/native-controls.mjs +48 -0
  94. package/src/design-checks/outline.mjs +39 -0
  95. package/src/design-checks/reporter.mjs +37 -0
  96. package/src/design-checks/rules.mjs +274 -0
  97. package/src/design-checks/values.mjs +262 -0
  98. package/src/design-checks.mjs +49 -0
  99. package/src/diag.mjs +98 -0
  100. package/src/docs.mjs +228 -0
  101. package/src/doctor.mjs +42 -0
  102. package/src/files.mjs +60 -0
  103. package/src/fix.mjs +48 -0
  104. package/src/gate/after.mjs +40 -0
  105. package/src/gate/before.mjs +54 -0
  106. package/src/gate/classify.mjs +72 -0
  107. package/src/gate/mutation.mjs +209 -0
  108. package/src/gate/resolve-cases.mjs +22 -0
  109. package/src/gate/result.mjs +63 -0
  110. package/src/gate/run.mjs +75 -0
  111. package/src/gate.mjs +178 -0
  112. package/src/index.mjs +9 -0
  113. package/src/infer/box-props.cjs +140 -0
  114. package/src/infer/core-boxes.cjs +46 -0
  115. package/src/infer/derived-writes.cjs +95 -0
  116. package/src/infer/engine/checks.cjs +193 -0
  117. package/src/infer/engine/flow.cjs +293 -0
  118. package/src/infer/engine/report.cjs +158 -0
  119. package/src/infer/engine/utils.cjs +15 -0
  120. package/src/infer/engine.cjs +265 -0
  121. package/src/infer/facts/sites.cjs +114 -0
  122. package/src/infer/facts.cjs +345 -0
  123. package/src/infer/hosts.cjs +161 -0
  124. package/src/infer/lsp.mjs +240 -0
  125. package/src/infer/session.cjs +161 -0
  126. package/src/infer/shadow.cjs +54 -0
  127. package/src/infer/worker.cjs +145 -0
  128. package/src/jsx-scan.mjs +128 -0
  129. package/src/kerf.mjs +98 -0
  130. package/src/load-config/schema.mjs +300 -0
  131. package/src/load-config.mjs +302 -0
  132. package/src/map.mjs +177 -0
  133. package/src/mcp/browser-tools.mjs +155 -0
  134. package/src/mcp.mjs +273 -0
  135. package/src/meta-table.mjs +63 -0
  136. package/src/mutate.mjs +224 -0
  137. package/src/plugin-checks.mjs +118 -0
  138. package/src/plugins.mjs +258 -0
  139. package/src/project.mjs +310 -0
  140. package/src/props-checks.mjs +64 -0
  141. package/src/props-listener.mjs +56 -0
  142. package/src/react-checks.mjs +67 -0
  143. package/src/server-state-checks.mjs +34 -0
  144. package/src/share-checks.mjs +158 -0
  145. package/src/site.mjs +46 -0
  146. package/src/slots.mjs +181 -0
  147. package/src/start/build.mjs +116 -0
  148. package/src/start/routes.mjs +38 -0
  149. package/src/start.mjs +394 -0
  150. package/src/state-checks/core-state.mjs +223 -0
  151. package/src/state-checks/modules.mjs +17 -0
  152. package/src/state-checks/scan.mjs +232 -0
  153. package/src/state-checks/server-graph.mjs +65 -0
  154. package/src/state-checks.mjs +189 -0
  155. package/src/style/find.mjs +121 -0
  156. package/src/style.mjs +327 -0
  157. package/src/surface-checks.mjs +384 -0
  158. package/src/tailwind.mjs +23 -0
  159. package/src/tasks.mjs +261 -0
  160. package/src/test-rules/context.mjs +109 -0
  161. package/src/test-rules/file-rules.mjs +279 -0
  162. package/src/test-rules/rule-helpers.mjs +244 -0
  163. package/src/test-rules/syntax.mjs +223 -0
  164. package/src/test-rules/test-rules.mjs +127 -0
  165. package/src/testdiff.mjs +219 -0
  166. package/src/tests.mjs +120 -0
  167. package/src/text-checks.mjs +332 -0
  168. package/src/tokens.mjs +33 -0
  169. package/src/trust/scan.mjs +95 -0
  170. package/src/trust.mjs +394 -0
  171. package/src/workspace.mjs +182 -0
  172. package/ts-plugin/context.js +57 -0
  173. package/ts-plugin/index.js +17 -0
  174. package/ts-plugin/mapping.js +65 -0
  175. package/ts-plugin/package.json +1 -0
  176. package/ts-plugin/proxy.js +144 -0
@@ -0,0 +1,258 @@
1
+ // Plugins (PLAN §7c, research 13 §2.6–2.8): run each plugin's pure `contribute()`, check what it declares, generate
2
+ // `.kerf/slots/<id>.ts` + `.kerf/slots.d.ts` + `.kerf/tokens/<ns>.css`, and serve `kerf plugins list|explain|sync`.
3
+
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { isAbsolute, join, relative, resolve } from 'node:path'
6
+ import { loadConfig } from './load-config.mjs'
7
+ import { slotDef } from './slots.mjs'
8
+
9
+ const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
10
+ const header =
11
+ '// Generated from kerf.config.ts. Do not edit: change kerf.config.ts and run `kerf plugins sync`.'
12
+
13
+ const posix = (p) => p.split('\\').join('/')
14
+ const slotFile = (id) => `.kerf/slots/${id}.ts`
15
+
16
+ /** The ProviderRef a bound plugin declared for `slot` (and `key`). */
17
+ function providerRef(loaded, plugin, slot, key = '') {
18
+ const c = loaded.contributions.find((x) => x.name === plugin)
19
+ return c?.manifest.provides?.find((p) => p.slot.id === slot && (p.key ?? '') === key) ?? null
20
+ }
21
+
22
+ /** `module` relative to `.kerf/slots/` when the plugin gave a relative path from the project root. */
23
+ function specifier(root, module) {
24
+ if (!module.startsWith('.') && !isAbsolute(module)) return module
25
+ const abs = isAbsolute(module) ? module : resolve(root, module)
26
+ const rel = posix(relative(join(root, '.kerf', 'slots'), abs))
27
+ return rel.startsWith('.') ? rel : `./${rel}`
28
+ }
29
+
30
+ function loader(root, ref) {
31
+ const side = ref.sides.client ?? ref.sides[Object.keys(ref.sides).sort()[0]]
32
+ if (!side)
33
+ return {
34
+ comment: 'no sides',
35
+ code: `() => Promise.reject(new Error('provider declares no module'))`,
36
+ }
37
+ const call =
38
+ side.options === undefined
39
+ ? `m[${JSON.stringify(side.export)}]`
40
+ : `m[${JSON.stringify(side.export)}](${JSON.stringify(side.options)})`
41
+ return {
42
+ comment: Object.keys(ref.sides).sort().join(', '),
43
+ code: `() => import(${JSON.stringify(specifier(root, side.module))}).then(m => ${call})`,
44
+ }
45
+ }
46
+
47
+ const unbound = (id) =>
48
+ `export const provider = null\nexport const load = (): never => {\n throw Object.assign(new Error(${JSON.stringify(`P101 ${id}: nothing provides this slot. Add a plugin that provides it to \`plugins\` in kerf.config.ts.`)}), { code: 'P101' })\n}\n`
49
+ const builtin = (id, name) =>
50
+ `export const provider = ${JSON.stringify(name)}\nexport const load = (): never => {\n throw new Error(${JSON.stringify(`${id}: built in, provided by kerf (${name}).`)})\n}\n`
51
+
52
+ function addCssEntries(files, c) {
53
+ const t = c.manifest.tokens
54
+ if (t?.cssEntries === undefined) return
55
+ if (!t.cssEntries || typeof t.cssEntries !== 'object' || Array.isArray(t.cssEntries))
56
+ throw new TypeError('tokens.cssEntries must be an object')
57
+ for (const [name, css] of Object.entries(t.cssEntries)) {
58
+ if (!/^[a-z][a-z0-9-]*$/.test(name) || typeof css !== 'string')
59
+ throw new TypeError(`Invalid tokens.cssEntries entry: ${name}`)
60
+ files[`.kerf/tokens/${t.namespace}.${name}.css`] =
61
+ `/* Generated from kerf.config.ts (${c.name}). Do not edit. */\n${css}`
62
+ }
63
+ }
64
+
65
+ /** File contents for every slot module, the slots.d.ts and token CSS, keyed by path relative to the root. */
66
+ export function generated(root, loaded) {
67
+ const files = {}
68
+ const typed = []
69
+ for (const [id, binding] of Object.entries(loaded.slots).sort(([a], [b]) => (a < b ? -1 : 1))) {
70
+ const def = slotDef(id) ?? {
71
+ version: 1,
72
+ cardinality: typeof binding === 'object' && binding ? 'keyed' : 'one',
73
+ }
74
+ let body
75
+ if (def.cardinality === 'one') {
76
+ const ref =
77
+ binding && !binding.startsWith('kerf:default') ? providerRef(loaded, binding, id) : null
78
+ if (ref) {
79
+ const l = loader(root, ref)
80
+ const plugin = loaded.contributions.find((x) => x.name === binding)
81
+ body = `// provider: ${binding}@${plugin.version} · implements ${id}@${ref.versions.join(',')} · sides: ${l.comment}\nexport const provider = ${JSON.stringify({ plugin: binding, version: plugin.version, interface: Math.max(...ref.versions) })} as const\nexport const load = ${l.code}\n`
82
+ typed.push(id)
83
+ } else if (binding?.startsWith('kerf:default')) body = builtin(id, binding)
84
+ else body = unbound(id)
85
+ } else {
86
+ const lines = []
87
+ const providers = {}
88
+ for (const [key, name] of Object.entries(binding ?? {})) {
89
+ const ref =
90
+ name && !name.startsWith('kerf:default') ? providerRef(loaded, name, id, key) : null
91
+ providers[key] = ref ? name : (name ?? null)
92
+ if (ref) lines.push(` ${JSON.stringify(key)}: ${loader(root, ref).code},`)
93
+ }
94
+ body = `export const providers = ${JSON.stringify(providers)} as const\nconst loaders: Record<string, () => Promise<unknown>> = {\n${lines.join('\n')}${lines.length ? '\n' : ''}}\nexport const load = (key: string): Promise<unknown> => {\n const l = loaders[key]\n if (l) return l()\n throw Object.assign(new Error(\`P101 ${id} key \${key}: \${providers[key as keyof typeof providers] ? 'built in, provided by kerf' : 'nothing provides it'}.\`), { code: 'P101' })\n}\n`
95
+ if (lines.length) typed.push(id)
96
+ }
97
+ files[slotFile(id)] = `${header}\n${body}`
98
+ }
99
+ // Build-side providers, for @kerf-js/core/vite to import in Node (it can't load the generated .ts): research 26 §3.1.
100
+ for (const [id, binding] of Object.entries(loaded.slots)) {
101
+ if (binding && typeof binding === 'object') {
102
+ const keys = {}
103
+ for (const [key, name] of Object.entries(binding)) {
104
+ const side =
105
+ name && !name.startsWith('kerf:default')
106
+ ? providerRef(loaded, name, id, key)?.sides.build
107
+ : null
108
+ if (side)
109
+ keys[key] = {
110
+ plugin: name,
111
+ module: side.module,
112
+ export: side.export,
113
+ options: side.options,
114
+ }
115
+ }
116
+ if (Object.keys(keys).length)
117
+ files[`.kerf/slots/${id}.build.json`] = `${JSON.stringify({ keys }, null, 2)}\n`
118
+ continue
119
+ }
120
+ if (typeof binding !== 'string' || binding.startsWith('kerf:default')) continue
121
+ const side = providerRef(loaded, binding, id)?.sides.build
122
+ if (!side) continue
123
+ const plugin = loaded.contributions.find((x) => x.name === binding)
124
+ const module = side.module.startsWith('.') ? posix(resolve(root, side.module)) : side.module
125
+ files[`.kerf/slots/${id}.build.json`] =
126
+ `${JSON.stringify({ plugin: binding, version: plugin.version, module, export: side.export, ...(side.options === undefined ? {} : { options: side.options }) }, null, 2)}\n`
127
+ }
128
+ files['.kerf/slots.d.ts'] =
129
+ `${header}\n// Only bound slots are declared: importing an unbound one is a type error (P101).\n${typed
130
+ .map(
131
+ (id) =>
132
+ `declare module 'kerf:slot/${id}' {\n export const provider: unknown\n export const providers: Record<string, unknown>\n export const load: (key?: string) => Promise<any>\n}\n`,
133
+ )
134
+ .join('')}`
135
+ for (const c of loaded.contributions) {
136
+ const t = c.manifest.tokens
137
+ if (t?.css)
138
+ files[`.kerf/tokens/${t.namespace}.css`] =
139
+ `/* Generated from kerf.config.ts (${c.name}). Do not edit. */\n${t.css}`
140
+ addCssEntries(files, c)
141
+ if (t?.alias)
142
+ files[`.kerf/tokens/${t.namespace}.alias.json`] = `${JSON.stringify(t.alias, null, 2)}\n`
143
+ }
144
+ return files
145
+ }
146
+
147
+ /** Write generated files whose content changed; remove stale slot/token files. Returns written paths. */
148
+ export function sync(root, loaded) {
149
+ const files = generated(root, loaded)
150
+ const written = []
151
+ for (const [rel, text] of Object.entries(files)) {
152
+ const abs = join(root, rel)
153
+ if (existsSync(abs) && readFileSync(abs, 'utf8') === text) continue
154
+ mkdirSync(join(abs, '..'), { recursive: true })
155
+ writeFileSync(abs, text)
156
+ written.push(rel)
157
+ }
158
+ for (const dir of ['.kerf/slots', '.kerf/tokens']) {
159
+ if (!existsSync(join(root, dir))) continue
160
+ for (const f of readdirSync(join(root, dir))) {
161
+ if (!(`${dir}/${f}` in files)) rmSync(join(root, dir, f))
162
+ }
163
+ }
164
+ return written
165
+ }
166
+
167
+ /** `kerf plugins list --json`. */
168
+ export async function list(root) {
169
+ root = resolve(root)
170
+ const loaded = await loadConfig(root)
171
+ const unique = (loaded.config.plugins ?? []).filter(
172
+ (p, i, all) => all.findIndex((q) => q.name === p.name) === i,
173
+ )
174
+ const plugins = [...unique].sort(byName).map((p) => {
175
+ const c = loaded.contributions.find((x) => x.name === p.name)
176
+ const provides = (p.provides ?? []).map((item) => {
177
+ const { slot, key } = typeof item === 'string' ? { slot: item } : item
178
+ const binding = loaded.slots[slot]
179
+ const bound = key ? binding?.[key] === p.name : binding === p.name
180
+ return {
181
+ slot,
182
+ ...(key ? { key } : {}),
183
+ interface: providerRef(loaded, p.name, slot, key)?.versions ?? null,
184
+ bound,
185
+ }
186
+ })
187
+ return {
188
+ name: p.name,
189
+ version: p.version ?? null,
190
+ provides,
191
+ permissions: c?.permissions ?? {},
192
+ namespace: c?.namespace ?? null,
193
+ diagnostics: (c?.manifest.diagnostics ?? []).map((d) => d.code),
194
+ tokens: c?.manifest.tokens?.namespace ?? null,
195
+ catalog: (c?.manifest.catalog ?? []).map((e) => e.name),
196
+ agents: c?.manifest.agents?.title ?? null,
197
+ }
198
+ })
199
+ return {
200
+ ok: !loaded.diagnostics.some((d) => d.severity === 'error'),
201
+ plugins,
202
+ slots: loaded.slots,
203
+ diagnostics: loaded.diagnostics,
204
+ }
205
+ }
206
+
207
+ /** `kerf plugins explain <slot> --json`: config entry → plugin → module → generated file. */
208
+ export async function explain(root, id) {
209
+ root = resolve(root)
210
+ const loaded = await loadConfig(root)
211
+ if (!id || !(id in loaded.slots))
212
+ throw Object.assign(
213
+ new Error(`unknown slot ${id ?? '(none)'}; known: ${Object.keys(loaded.slots).join(', ')}`),
214
+ { code: 'E_USAGE' },
215
+ )
216
+ const binding = loaded.slots[id]
217
+ const def = slotDef(id) ?? null
218
+ const chain = (key) => {
219
+ const name = key === undefined ? binding : binding?.[key]
220
+ if (!name) return { provider: null, why: 'nothing provides it (P101 for consumers)' }
221
+ if (name.startsWith('kerf:default'))
222
+ return { provider: name, why: 'built in, provided by kerf' }
223
+ const ref = providerRef(loaded, name, id, key ?? '')
224
+ const side = ref && (ref.sides.client ?? ref.sides[Object.keys(ref.sides).sort()[0]])
225
+ return {
226
+ config: loaded.file ? posix(relative(root, loaded.file)) : null,
227
+ chosenBy: loaded.config.slots?.[id] ? 'slots' : 'only provider',
228
+ plugin: name,
229
+ version: loaded.contributions.find((c) => c.name === name)?.version ?? null,
230
+ interface: ref?.versions ?? null,
231
+ sides: ref ? Object.keys(ref.sides).sort() : [],
232
+ module: side
233
+ ? {
234
+ module: side.module,
235
+ export: side.export,
236
+ ...(side.options === undefined ? {} : { options: side.options }),
237
+ }
238
+ : null,
239
+ }
240
+ }
241
+ const bindings =
242
+ def?.cardinality === 'keyed' || (binding && typeof binding === 'object')
243
+ ? Object.fromEntries(
244
+ Object.keys(binding ?? {})
245
+ .sort()
246
+ .map((k) => [k, chain(k)]),
247
+ )
248
+ : chain()
249
+ return {
250
+ slot: id,
251
+ version: def?.version ?? null,
252
+ cardinality: def?.cardinality ?? 'one',
253
+ sides: def?.sides ?? [],
254
+ binding: bindings,
255
+ file: slotFile(id),
256
+ import: `kerf:slot/${id}`,
257
+ }
258
+ }
@@ -0,0 +1,310 @@
1
+ // Project view for `kerf check`: what one file can't see. Today that is cross-file W014.
2
+ //
3
+ // The compiler reports W014 as a warning when `xs.value = xs.value.map(p => ({ ...p, … }))` feeds a box that leaves
4
+ // the file. Here we follow that box through JSX props (`<List items={xs.value} />`), into the component's props,
5
+ // through `derived` and further JSX props, until a JSX `.map` renders it as a keyed list. Found: the warning becomes
6
+ // an error with the list's location in `related`. The parse is syntax only (TypeScript's parser, no type checker).
7
+
8
+ import { relative } from 'node:path'
9
+ import ts from 'typescript'
10
+ import { local } from './alias.mjs'
11
+
12
+ const exts = [
13
+ '',
14
+ '.tsx',
15
+ '.ts',
16
+ '.jsx',
17
+ '.js',
18
+ '/index.tsx',
19
+ '/index.ts',
20
+ '/index.jsx',
21
+ '/index.js',
22
+ ]
23
+ const isComponentName = (name) => /^[A-Z]/.test(name)
24
+
25
+ /** `a.b.c(…).d` → ['a', 'b']: the root identifier and the first member after it. */
26
+ function chainRoot(expr) {
27
+ let node = expr
28
+ let member
29
+ for (;;) {
30
+ if (
31
+ ts.isParenthesizedExpression(node) ||
32
+ ts.isNonNullExpression(node) ||
33
+ ts.isAsExpression(node)
34
+ )
35
+ node = node.expression
36
+ else if (ts.isPropertyAccessExpression(node)) {
37
+ member = node.name.text
38
+ node = node.expression
39
+ } else if (ts.isElementAccessExpression(node) || ts.isCallExpression(node)) {
40
+ member = undefined
41
+ node = node.expression
42
+ } else break
43
+ }
44
+ return ts.isIdentifier(node) ? [node.text, member] : null
45
+ }
46
+
47
+ function isInJsx(node, stop) {
48
+ for (let n = node.parent; n && n !== stop; n = n.parent) if (ts.isJsxExpression(n)) return true
49
+ return false
50
+ }
51
+
52
+ /** Identifiers an expression reads (not property names); `props.x` is kept as 'props.x'. */
53
+ function identifiersIn(node) {
54
+ const names = new Set()
55
+ const visit = (n) => {
56
+ if (ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression))
57
+ names.add(`${n.expression.text}.${n.name.text}`)
58
+ if (ts.isIdentifier(n) && !(ts.isPropertyAccessExpression(n.parent) && n.parent.name === n))
59
+ names.add(n.text)
60
+ ts.forEachChild(n, visit)
61
+ }
62
+ visit(node)
63
+ return names
64
+ }
65
+
66
+ function componentsOf(sf) {
67
+ const comps = []
68
+ const add = (name, fn) => {
69
+ const param = fn.parameters[0]
70
+ const props = new Map()
71
+ let propsIdent = null
72
+ if (param && ts.isObjectBindingPattern(param.name)) {
73
+ for (const el of param.name.elements) {
74
+ if (el.dotDotDotToken || !ts.isIdentifier(el.name)) continue
75
+ const key =
76
+ el.propertyName && ts.isIdentifier(el.propertyName) ? el.propertyName.text : el.name.text
77
+ props.set(el.name.text, key)
78
+ }
79
+ } else if (param && ts.isIdentifier(param.name)) propsIdent = param.name.text
80
+ comps.push({ name, fn, props, propsIdent, derives: new Map(), lists: [], edges: [] })
81
+ }
82
+ for (const st of sf.statements) {
83
+ if (ts.isFunctionDeclaration(st) && st.name && isComponentName(st.name.text))
84
+ add(st.name.text, st)
85
+ if (
86
+ ts.isFunctionDeclaration(st) &&
87
+ !st.name &&
88
+ st.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)
89
+ )
90
+ add('default', st)
91
+ if (ts.isVariableStatement(st)) {
92
+ for (const d of st.declarationList.declarations) {
93
+ if (
94
+ ts.isIdentifier(d.name) &&
95
+ isComponentName(d.name.text) &&
96
+ d.initializer &&
97
+ (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer))
98
+ )
99
+ add(d.name.text, d.initializer)
100
+ }
101
+ }
102
+ }
103
+ for (const c of comps) analyzeComponent(c)
104
+ return comps
105
+ }
106
+
107
+ function analyzeComponent(c) {
108
+ const visit = (n) => {
109
+ if (
110
+ ts.isVariableDeclaration(n) &&
111
+ ts.isIdentifier(n.name) &&
112
+ n.initializer &&
113
+ ts.isCallExpression(n.initializer)
114
+ ) {
115
+ const callee = n.initializer.expression.getText()
116
+ if (callee === 'derived' || callee === 'state.linked')
117
+ c.derives.set(n.name.text, identifiersIn(n.initializer))
118
+ }
119
+ if (
120
+ ts.isCallExpression(n) &&
121
+ ts.isPropertyAccessExpression(n.expression) &&
122
+ n.expression.name.text === 'map' &&
123
+ isInJsx(n, c.fn)
124
+ ) {
125
+ const cb = n.arguments[0]
126
+ const root = chainRoot(n.expression.expression)
127
+ if (root && cb && (ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)))
128
+ c.lists.push({ root, at: n.getStart() })
129
+ }
130
+ if (
131
+ (ts.isJsxSelfClosingElement(n) || ts.isJsxOpeningElement(n)) &&
132
+ ts.isIdentifier(n.tagName) &&
133
+ isComponentName(n.tagName.text)
134
+ ) {
135
+ for (const attr of n.attributes.properties) {
136
+ if (
137
+ !ts.isJsxAttribute(attr) ||
138
+ !attr.initializer ||
139
+ !ts.isJsxExpression(attr.initializer) ||
140
+ !attr.initializer.expression
141
+ )
142
+ continue
143
+ const root = chainRoot(attr.initializer.expression)
144
+ if (root)
145
+ c.edges.push({
146
+ tag: n.tagName.text,
147
+ prop: attr.name.getText(),
148
+ root,
149
+ at: attr.getStart(),
150
+ })
151
+ }
152
+ }
153
+ ts.forEachChild(n, visit)
154
+ }
155
+ visit(c.fn.body ?? c.fn)
156
+ }
157
+
158
+ /**
159
+ * @param {Array<{ abs: string, rel: string, text: string, diagnostics: object[] }>} files
160
+ * @param {(file: string) => { span(start: number, end: number): number[] }} pos
161
+ */
162
+ export function projectView(files, pos) {
163
+ // Only a W014 warning needs the project view, so most runs parse nothing here.
164
+ if (!files.some((f) => f.diagnostics.some((d) => d.code === 'W014' && d.severity === 'warning')))
165
+ return
166
+ const byAbs = new Map(files.map((f) => [f.abs, f]))
167
+ parseProject(files, byAbs)
168
+
169
+ const lookup = (file, tag) => {
170
+ const own = file.comps.find((c) => c.name === tag)
171
+ if (own) return { file, comp: own }
172
+ const imp = file.imports.get(tag)
173
+ const target = imp && byAbs.get(imp.file)
174
+ const comp = target?.comps.find((c) => c.name === imp.name)
175
+ return comp ? { file: target, comp } : null
176
+ }
177
+
178
+ /** Prop names (of `comp`) that an expression rooted at `root` reads, following `derived` locals. */
179
+ const propsRead = (comp, [name, member], seen = new Set()) => {
180
+ if (seen.has(name)) return new Set()
181
+ seen.add(name)
182
+ if (comp.props.has(name)) return new Set([comp.props.get(name)])
183
+ if (name === comp.propsIdent && member) return new Set([member])
184
+ const out = new Set()
185
+ for (const dep of comp.derives.get(name) ?? [])
186
+ for (const p of propsRead(comp, dep.split('.'), seen)) out.add(p)
187
+ return out
188
+ }
189
+
190
+ /** Where `comp` (transitively) renders prop `prop` as a JSX `.map`, with the JSX path that gets there. */
191
+ const reachesList = (file, comp, prop, seen = new Set()) => {
192
+ const id = `${file.abs}#${comp.name}#${prop}`
193
+ if (seen.has(id)) return null
194
+ seen.add(id)
195
+ for (const list of comp.lists)
196
+ if (propsRead(comp, list.root).has(prop)) return { file, at: list.at, via: [] }
197
+ for (const edge of comp.edges) {
198
+ if (!propsRead(comp, edge.root).has(prop)) continue
199
+ const next = lookup(file, edge.tag)
200
+ const hit = next && reachesList(next.file, next.comp, edge.prop, seen)
201
+ if (hit)
202
+ return { ...hit, via: [{ file, at: edge.at, tag: edge.tag, prop: edge.prop }, ...hit.via] }
203
+ }
204
+ return null
205
+ }
206
+
207
+ /** Locals of `comp` that read `box`, following `derived`. */
208
+ const readsBox = (comp, [name], box, seen = new Set()) => {
209
+ if (name === box) return true
210
+ if (seen.has(name)) return false
211
+ seen.add(name)
212
+ return [...(comp?.derives.get(name) ?? [])].some((dep) =>
213
+ readsBox(comp, dep.split('.'), box, seen),
214
+ )
215
+ }
216
+
217
+ promoteFindings(files, pos, readsBox, lookup, reachesList)
218
+ }
219
+
220
+ /** The box a flagged `.map` call writes: `box.value = …map(…)` or `const box = …map(…)`. */
221
+ function boxOf(sf, offset) {
222
+ let found
223
+ const visit = (n) => {
224
+ if (found) return
225
+ if (ts.isCallExpression(n) && n.getStart() === offset) found = n
226
+ else if (n.pos <= offset && offset < n.end) ts.forEachChild(n, visit)
227
+ }
228
+ visit(sf)
229
+ for (let n = found; n; n = n.parent) {
230
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
231
+ const left = n.left
232
+ if (
233
+ ts.isPropertyAccessExpression(left) &&
234
+ left.name.text === 'value' &&
235
+ ts.isIdentifier(left.expression)
236
+ )
237
+ return left.expression.text
238
+ return null
239
+ }
240
+ if (ts.isVariableDeclaration(n)) return ts.isIdentifier(n.name) ? n.name.text : null
241
+ }
242
+ return null
243
+ }
244
+
245
+ export const relPath = (root, abs) => relative(root, abs).split('\\').join('/')
246
+
247
+ function parseProject(files, byAbs) {
248
+ for (const f of files) {
249
+ f.sf = ts.createSourceFile(f.abs, f.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
250
+ f.comps = componentsOf(f.sf)
251
+ f.imports = new Map()
252
+ for (const st of f.sf.statements) {
253
+ if (
254
+ !ts.isImportDeclaration(st) ||
255
+ !st.importClause ||
256
+ !ts.isStringLiteral(st.moduleSpecifier)
257
+ )
258
+ continue
259
+ const spec = st.moduleSpecifier.text
260
+ const base = local(f.abs, spec)
261
+ if (!base) continue
262
+ const target = exts.map((e) => base + e).find((p) => byAbs.has(p))
263
+ if (!target) continue
264
+ if (st.importClause.name)
265
+ f.imports.set(st.importClause.name.text, { file: target, name: 'default' })
266
+ const named = st.importClause.namedBindings
267
+ if (named && ts.isNamedImports(named))
268
+ for (const el of named.elements)
269
+ f.imports.set(el.name.text, { file: target, name: (el.propertyName ?? el.name).text })
270
+ }
271
+ }
272
+ }
273
+
274
+ function promoteFindings(files, pos, readsBox, lookup, reachesList) {
275
+ for (const f of files) {
276
+ for (const d of f.diagnostics) {
277
+ if (d.code !== 'W014' || d.severity !== 'warning' || !d.offset) continue
278
+ const box = boxOf(f.sf, d.offset[0])
279
+ if (!box) continue
280
+ const owners = f.comps.filter((c) => c.fn.pos <= d.offset[0] && d.offset[0] < c.fn.end)
281
+ for (const comp of owners.length ? owners : f.comps) {
282
+ let hit = null
283
+ let edge
284
+ for (edge of comp.edges) {
285
+ if (!readsBox(comp, edge.root, box)) continue
286
+ const next = lookup(f, edge.tag)
287
+ hit = next && reachesList(next.file, next.comp, edge.prop)
288
+ if (hit) break
289
+ }
290
+ if (!hit) continue
291
+ const listPos = pos(hit.file).span(hit.at, hit.at)
292
+ const path = [{ file: f, at: edge.at, tag: edge.tag, prop: edge.prop }, ...hit.via]
293
+ d.severity = 'error'
294
+ d.project = true
295
+ d.why =
296
+ `\`.map(p => ({ ...p, … }))\` gives every item a new identity on each update, and \`${box}\` reaches a keyed list in ` +
297
+ `${hit.file.rel}:${listPos[0]} through ${path.map((p) => `<${p.tag} ${p.prop}>`).join(' → ')}: every row re-runs on every change.`
298
+ d.related = [
299
+ ...path.map((p) => ({
300
+ file: p.file.rel,
301
+ span: pos(p.file).span(p.at, p.at),
302
+ why: `passed as \`<${p.tag} ${p.prop}>\``,
303
+ })),
304
+ { file: hit.file.rel, span: listPos, why: 'rendered here as a keyed list' },
305
+ ]
306
+ break
307
+ }
308
+ }
309
+ }
310
+ }
@@ -0,0 +1,64 @@
1
+ // Prop inference in `kerf check` and `kerf tsc` (research 44). `W080`–`W085` come from the engine; a `TS` code is the
2
+ // compiler's own error, reported at the source position with the inferred types applied.
3
+ // W007/W008 map proven core box errors.
4
+
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import { join, relative } from 'node:path'
8
+ import ts from 'typescript'
9
+ import { diagnostic, positions } from './diag.mjs'
10
+
11
+ const require = createRequire(import.meta.url)
12
+ const { Session } = require('./infer/session.cjs')
13
+
14
+ const posix = (p) => p.split('\\').join('/')
15
+
16
+ export function toDiagnostics(root, list, file) {
17
+ const rel = posix(relative(root, file))
18
+ const text = readFileSync(file, 'utf8')
19
+ const pos = positions(text)
20
+ return list.map((f) =>
21
+ diagnostic({
22
+ code: f.code,
23
+ severity: f.severity,
24
+ file: rel,
25
+ span: pos.span(f.start, f.end),
26
+ offset: [f.start, f.end],
27
+ why: f.why,
28
+ help: f.help,
29
+ fix: f.edits && {
30
+ description: f.help,
31
+ safe: f.safe,
32
+ edits: f.edits.map((e) => ({
33
+ file: rel,
34
+ span: pos.span(e.start, e.end),
35
+ offset: [e.start, e.end],
36
+ text: e.text,
37
+ })),
38
+ },
39
+ }),
40
+ )
41
+ }
42
+
43
+ /** Prop inference and core box diagnostics; a project with no relevant source starts no checker. */
44
+ export async function propChecks(root, config) {
45
+ if (config.check?.props === false || !existsSync(join(root, 'tsconfig.json'))) return []
46
+ const session = new Session(ts, root)
47
+ try {
48
+ const { findings, errors } = await session.analyze()
49
+ return [...findings, ...errors].flatMap(([file, list]) => toDiagnostics(root, list, file))
50
+ } finally {
51
+ session.close()
52
+ }
53
+ }
54
+
55
+ /** `kerf tsc`: the whole project, as `tsc --noEmit` sees it with inference applied. */
56
+ export async function propTsc(root) {
57
+ const session = new Session(ts, root)
58
+ try {
59
+ const { findings, errors } = await session.all()
60
+ return [...findings, ...errors].flatMap(([file, list]) => toDiagnostics(root, list, file))
61
+ } finally {
62
+ session.close()
63
+ }
64
+ }
@@ -0,0 +1,56 @@
1
+ // Prop inference while `kerf dev` runs. A listener of its own, hooked at file-change: it posts the changed name to a
2
+ // worker and goes back to serving, so nothing here is on the HMR or request path (research 44 §7).
3
+
4
+ import { Worker } from 'node:worker_threads'
5
+
6
+ const SOURCE = /\.tsx?$/
7
+ const SKIP = /[\\/](node_modules|\.kerf|\.output|dist)[\\/]/
8
+
9
+ /** @param {{ watcher: any, ws: any, config: any, close: () => Promise<void> }} server */
10
+ export function attachProps(server, root, config) {
11
+ const setting = config?.check?.props
12
+ if (setting === false || process.env.KERF_PROPS === 'off') return null
13
+ const worker = new Worker(new URL('./infer/worker.cjs', import.meta.url), {
14
+ workerData: { root, write: setting !== 'manual' },
15
+ stdout: false,
16
+ })
17
+ worker.unref()
18
+ const stats = { saves: 0, ms: [] }
19
+ const post = (file) => {
20
+ if (SOURCE.test(file) && !SKIP.test(file)) worker.postMessage(file)
21
+ }
22
+ for (const event of ['change', 'add', 'unlink']) server.watcher.on(event, post)
23
+
24
+ const logger = server.config?.logger ?? console
25
+ worker.on('message', (msg) => {
26
+ if (msg.type === 'failed') return logger.warn?.(`kerf props: ${msg.message}`)
27
+ if (msg.type === 'wrote')
28
+ return logger.info?.(`kerf props: wrote the inferred type in ${msg.file}`)
29
+ if (msg.type !== 'done') return
30
+ stats.saves++
31
+ stats.ms.push(msg.ms)
32
+ if (!msg.changed) return
33
+ const errors = msg.diagnostics.filter((d) => d.severity === 'error')
34
+ for (const d of msg.diagnostics)
35
+ logger.warn?.(`${d.file}:${d.line} ${d.code} ${d.severity} ${d.why}\n fix: ${d.help}`)
36
+ server.ws.send({ type: 'custom', event: 'kerf:props', data: msg.diagnostics })
37
+ // A save's HMR update has cleared any earlier overlay already, so this only ever shows the current errors.
38
+ if (errors.length)
39
+ server.ws.send({
40
+ type: 'error',
41
+ err: {
42
+ message: errors.map((d) => `${d.file}:${d.line} ${d.code}: ${d.why}`).join('\n'),
43
+ stack: '',
44
+ plugin: 'kerf:props',
45
+ },
46
+ })
47
+ })
48
+ worker.on('error', (e) => logger.warn?.(`kerf props stopped: ${e.message}`))
49
+
50
+ const close = server.close.bind(server)
51
+ server.close = async () => {
52
+ worker.postMessage('close')
53
+ return close()
54
+ }
55
+ return { worker, stats }
56
+ }