@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
package/src/docs.mjs ADDED
@@ -0,0 +1,228 @@
1
+ // Docs for agents: topic files in ../docs, plus pages generated from the installed kerf (diagnostics, commands,
2
+ // AGENTS.md). One source for `kerf docs`, the MCP `docs` tool and AGENTS.md, so they can't disagree.
3
+
4
+ import { readFileSync, readdirSync } from 'node:fs'
5
+ import { resolve } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { catalog, entry, probe } from './catalog.mjs'
8
+ import { loadConfig } from './load-config.mjs'
9
+ import { tasks } from './tasks.mjs'
10
+ import { probeTests } from './tests.mjs'
11
+ import { exportsOf, loadCompiler, resolveKerf } from './kerf.mjs'
12
+
13
+ const docsDir = fileURLToPath(new URL('../docs/', import.meta.url))
14
+ const fileTopics = Object.fromEntries(
15
+ readdirSync(docsDir)
16
+ .filter((f) => f.endsWith('.md'))
17
+ .map((f) => [f.slice(0, -3), f]),
18
+ )
19
+
20
+ /** What `kerf docs` can show, with the line that says what each topic covers. */
21
+ export const topics = {
22
+ rules: 'The nine rules: boxes, derived, live JSX and props, run-once bodies (start here)',
23
+ state:
24
+ 'Every reactive function (state, derived, watch, untrack, flush, batch, context) and defineState with persist, sync and history; S001, S002, S008, S009, S012, S013',
25
+ props: 'How props stay live; W001, W005, W006',
26
+ lists: 'Keyed lists, conditionals and stable items; W010, W011, W013, W014',
27
+ async: 'resource, <Boundary pending error>, @kerf-js/core/ssr and hydrate; W012',
28
+ start:
29
+ 'full stack: routes, load, query, mutation, the database, auth, realtime, runtimes; Q001–Q016, A001–A005, C001–C002, F001–F003, R001–R024',
30
+ rust: 'Rust bodies: native() addons with a WASM fallback, remote() sidecars, kerf add rust, impl, the kerf crate, build.rs, Ctx, touch, kerf dev reload, deployment; R101–R109',
31
+ deploy:
32
+ 'Deploy: which hosts can run the app, kerf deploy hosts/init, the push workflow, Netlify, Vercel, Cloudflare, Fly, Render, CDN and Cloudinary; E001–E014',
33
+ plugins:
34
+ 'Build a plugin: slots, server extensions, check hooks, docs, `kerf add`, conformance. Walks through how @kerf-js/pay is built',
35
+ theme: 'Change the look: veneer() options, three worked looks, button tone channels, D010',
36
+ testing:
37
+ '@kerf-js/core/test: render, screen, user, flush, clock, touches and toTouchAtMost(n, { runs }); T001–T009',
38
+ browser:
39
+ '@kerf-js/core/browser: online, visible, lifecycle, media, on, interval; the net/page fakes; W050, W051, W054, W056, T012',
40
+ 'ui-state':
41
+ 'Hover, press and focus as state: interaction(), the ui prop, sharing across tabs and clients, realtime({ share }); U001–U005',
42
+ surface:
43
+ '@kerf-js/core/surface: canvas and WebGL as layout children: defineSurface, <Surface>, s.draw, s.frame, s.text, the clock; X001–X004, X009–X012',
44
+ verify:
45
+ 'Check your work: drive the running app (kerf browser / __kerf__.agent: snapshot with the live graph, act, assert, clock, network, record) and the test gate; T010, T011, T020',
46
+ icons:
47
+ '@kerf-js/veneer-icons: per-icon exports, iconSet, the three tiers, icons({ tier }), sizes',
48
+ fonts:
49
+ 'Fonts with @kerf-js/text: text({ fonts }), what the build makes, using a face in CSS, budgets; X020, X021, X022, X023',
50
+ meta: 'Page metadata and share cards: route `meta`, what is automatic, `site.url`, `.og.tsx`, `kerf routes --meta`; H001–H010, H011 (no description) to H017',
51
+ config: 'kerf.config.ts: scope, tasks, environments, reserved plugins/slots; P-codes',
52
+ design:
53
+ 'The design language: Stack, Row, Heading, Text, Link, the closed vocabulary, `kerf fix`, `kerf tokens`; D001–D007, D011, D012, D030–D041',
54
+ style:
55
+ 'Style groups (@kerf-js/core/style): group(), axes, parts, accents, kerf style find/explain, .kerf/styles.json; D020–D025, W060',
56
+ diagnostics: 'Every diagnostic code, from W to L, and which ones the installed kerf reports',
57
+ commands: "This project's commands and tasks (from `kerf tasks`)",
58
+ agents: 'The generated AGENTS.md',
59
+ }
60
+
61
+ const probes = new Map()
62
+
63
+ /** What the installed kerf offers: version, exports, and which catalog codes its compiler reports. */
64
+ export function installed(root) {
65
+ const kerf = resolveKerf(root)
66
+ if (!probes.has(kerf.compilerPath))
67
+ probes.set(kerf.compilerPath, { ...probe(loadCompiler(kerf)), ...probeTests(catalog) })
68
+ return { kerf, exports: exportsOf(kerf), status: probes.get(kerf.compilerPath) }
69
+ }
70
+
71
+ function status(code, info) {
72
+ const e = entry(code)
73
+ const st = info.status[e.code]
74
+ if (e.by === 'compiler')
75
+ return st?.implemented
76
+ ? `reported${st.autofix ? ', safe autofix' : st.suggestion ? ', suggested edit' : ''}`
77
+ : 'not reported by this kerf yet'
78
+ if (e.by === 'test') return 'reported by @kerf-js/core/test after each test'
79
+ if (e.by === 'gate') return 'reported by `kerf test --gate` on a diff'
80
+ if (e.code.startsWith('T'))
81
+ return st?.implemented
82
+ ? `reported by kerf check on test files${st.autofix ? ', safe autofix' : st.suggestion ? ', suggested edit' : ''}`
83
+ : 'not reported by this kerf yet'
84
+ if (e.by === 'start')
85
+ return 'reported by @kerf-js/start when it serves or renders the route, and by kerf check and `kerf routes --meta`'
86
+ if (e.by === 'cli' && e.code.startsWith('H'))
87
+ return 'reported by kerf check and by `kerf routes --meta`, per route, on what the routes produce'
88
+ if (e.by === 'cli')
89
+ return e.proposed
90
+ ? 'reported by kerf check (proposed code, research 17)'
91
+ : 'reported by kerf check'
92
+ if (e.by === 'runtime') return 'reported in dev by the runtime (a console warning)'
93
+ if (e.by === 'plugin') return `reported by kerf check when \`${e.owner}\` is in \`plugins\``
94
+ return 'reserved'
95
+ }
96
+
97
+ function codePage(code, info) {
98
+ const e = entry(code)
99
+ const lines = [
100
+ `# ${code} (${e.severity})`,
101
+ '',
102
+ e.catches + '.',
103
+ '',
104
+ `**Fix:** ${e.fix}.`,
105
+ '',
106
+ `**Status in kerf@${info.kerf.version}:** ${status(code, info)}.`,
107
+ ]
108
+ if (e.example) lines.push('', 'Triggers it:', '', '```tsx', e.example, '```')
109
+ if (code.startsWith('T'))
110
+ lines.push(
111
+ '',
112
+ 'A test that needs it on purpose keeps it with a reason: `// kerf-allow ' +
113
+ code +
114
+ ': <why>` in the file header (whole file) or on the line above.',
115
+ )
116
+ const topic =
117
+ Object.entries(topics).find(([, d]) => d.includes(code)) ??
118
+ (code.startsWith('T') ? ['testing'] : undefined)
119
+ if (topic) lines.push('', `More: \`kerf docs ${topic[0]}\`.`)
120
+ return lines.join('\n')
121
+ }
122
+
123
+ const contributed = async (root) => (await loadConfig(root)).contributions
124
+
125
+ /** What this app's plugins add to the docs (`docs` and `diagnostics` in their manifests). */
126
+ const pluginDocs = async (root) =>
127
+ (await contributed(root)).flatMap((c) => (c.manifest.docs ? [c.manifest.docs] : []))
128
+ const pluginCodes = async (root) =>
129
+ (await contributed(root)).flatMap((c) =>
130
+ (c.manifest.diagnostics ?? []).map((d) => ({ ...d, plugin: c.name })),
131
+ )
132
+
133
+ function diagnosticsPage(info, own = []) {
134
+ const rows = [
135
+ ...catalog.map(
136
+ (e) => `| ${e.code} | ${e.severity} | ${e.catches} | ${e.fix} | ${status(e.code, info)} |`,
137
+ ),
138
+ ...own.map(
139
+ (d) =>
140
+ `| ${d.code} | ${d.severity ?? 'error'} | ${d.catches} | ${d.fix} | from \`${d.plugin}\` |`,
141
+ ),
142
+ ]
143
+ return [
144
+ `# Diagnostics (kerf@${info.kerf.version})`,
145
+ '',
146
+ '| Code | Severity | Catches | Fix | Status |',
147
+ '|---|---|---|---|---|',
148
+ ...rows,
149
+ ].join('\n')
150
+ }
151
+
152
+ export function commandsPage(list, { planned: showPlanned = true } = {}) {
153
+ const rows = list.tasks
154
+ .filter((t) => t.available)
155
+ .map(
156
+ (t) =>
157
+ `| \`${t.command}\` | ${t.description ?? '(no description: P004)'} | ${t.sideEffects?.length ? t.sideEffects.join(', ') : 'none'} |`,
158
+ )
159
+ const planned = list.tasks.filter((t) => !t.available).map((t) => `\`${t.name}\``)
160
+ return [
161
+ '| Command | Does | Side effects |',
162
+ '|---|---|---|',
163
+ ...rows,
164
+ '',
165
+ showPlanned && planned.length ? `Planned, not shipped yet: ${planned.join(', ')}.` : '',
166
+ ]
167
+ .join('\n')
168
+ .trim()
169
+ }
170
+
171
+ /**
172
+ * @param {string} root
173
+ * @param {string} [topic] a topic name or a diagnostic code; omitted: the index
174
+ * @returns {Promise<{ topic: string, text: string, topics?: Record<string, string> }>}
175
+ */
176
+ export async function docs(root, topic) {
177
+ root = resolve(root)
178
+ const key = (topic ?? 'index').trim()
179
+ if (key === 'index') {
180
+ const all = {
181
+ ...topics,
182
+ ...Object.fromEntries((await pluginDocs(root)).map((d) => [d.topic, d.summary])),
183
+ }
184
+ const text = [
185
+ '# kerf docs',
186
+ '',
187
+ ...Object.entries(all).map(([t, d]) => `- \`${t}\`: ${d}`),
188
+ '',
189
+ 'Any diagnostic code works too: `W014`, `T003`, `P004`, `D025`, `Q001`.',
190
+ ].join('\n')
191
+ return { topic: 'index', text, topics: all }
192
+ }
193
+ const info = installed(root)
194
+ if (/^[A-Z]{1,5}\d{3}$/i.test(key)) {
195
+ const code = key.toUpperCase()
196
+ const own = !entry(code) && (await pluginCodes(root)).find((d) => d.code === code)
197
+ if (own)
198
+ return {
199
+ topic: code,
200
+ text: `# ${code} (${own.severity ?? 'error'})\n\n${own.catches}.\n\n**Fix:** ${own.fix}.\n\nReported by kerf check, from \`${own.plugin}\`.`,
201
+ }
202
+ if (!entry(code))
203
+ throw Object.assign(new Error(`unknown diagnostic code ${code}`), { code: 'E_UNKNOWN_TOPIC' })
204
+ return { topic: code, text: codePage(code, info) }
205
+ }
206
+ if (key === 'diagnostics')
207
+ return { topic: key, text: diagnosticsPage(info, await pluginCodes(root)) }
208
+ if (key === 'commands')
209
+ return { topic: key, text: `# Commands\n\n${commandsPage(await tasks(root))}` }
210
+ if (key === 'agents') {
211
+ const { agentsMd } = await import('./agents-md.mjs')
212
+ return { topic: key, text: (await agentsMd(root)).text }
213
+ }
214
+ const page = (await pluginDocs(root)).find((d) => d.topic === key)
215
+ if (page) return { topic: key, text: readFileSync(page.file, 'utf8').trim() }
216
+ if (fileTopics[key]) {
217
+ const text = readFileSync(resolve(docsDir, fileTopics[key]), 'utf8').trim()
218
+ return { topic: key, text: key === 'rules' ? `# The rules\n\n${text}` : text }
219
+ }
220
+ throw Object.assign(
221
+ new Error(
222
+ `unknown docs topic "${key}"; topics: ${Object.keys(topics).join(', ')}, or a code like W014`,
223
+ ),
224
+ { code: 'E_UNKNOWN_TOPIC' },
225
+ )
226
+ }
227
+
228
+ export const readDoc = (name) => readFileSync(resolve(docsDir, `${name}.md`), 'utf8').trim()
package/src/doctor.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // `kerf doctor`: what this install compiles with, and whether Rust is around. Everything here is information: Rust is
2
+ // optional, the WASM compiler is a full compiler, and the addon only adds speed. Nothing it reports fails the command.
3
+
4
+ import { spawnSync } from 'node:child_process'
5
+ import { loadCompiler, resolveKerf } from './kerf.mjs'
6
+
7
+ /** One line for `kerf check --verbose` and `kerf doctor`. */
8
+ export function compilerLine(backend) {
9
+ if (!backend) return 'compiler: this kerf does not say which build it uses'
10
+ if (backend.kind === 'native')
11
+ return `compiler: native addon${backend.package ? ` (${backend.package})` : ` (${backend.file})`}`
12
+ const offer = backend.wanted?.length
13
+ ? `. Optional, and faster: ${backend.wanted.join(' or ')}, which a normal install adds by itself`
14
+ : '. No prebuilt addon for this platform, and none is needed'
15
+ return `compiler: WASM, same output as the addon${offer}`
16
+ }
17
+
18
+ export function doctor(root) {
19
+ const kerf = resolveKerf(root)
20
+ const { backend } = loadCompiler(kerf)
21
+ const cargo = spawnSync('cargo', ['--version'], { encoding: 'utf8' })
22
+ const version = cargo.status === 0 ? cargo.stdout.trim() : null
23
+ const runtime = globalThis.Deno
24
+ ? `Deno ${Deno.version.deno}`
25
+ : globalThis.Bun
26
+ ? `Bun ${Bun.version}`
27
+ : `Node ${process.version}`
28
+ return {
29
+ ok: true,
30
+ kerf: kerf.version,
31
+ runtime,
32
+ compiler: backend ?? null,
33
+ rust: { cargo: version, required: false },
34
+ }
35
+ }
36
+
37
+ export const formatDoctor = (r) =>
38
+ [
39
+ `kerf ${r.kerf} on ${r.runtime}`,
40
+ compilerLine(r.compiler),
41
+ `rust: ${r.rust.cargo ?? 'no cargo on PATH'}. Not needed for kerf; only \`kerf add rust\` sidecars and native() use it`,
42
+ ].join('\n')
package/src/files.mjs ADDED
@@ -0,0 +1,60 @@
1
+ // Project file discovery with a small glob (`**`, `*`, `?`, `{a,b}`), relative to the project root.
2
+
3
+ import { readdirSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+
6
+ const skipDirs = new Set([
7
+ 'public',
8
+ 'node_modules',
9
+ '.git',
10
+ '.kerf',
11
+ '.output',
12
+ 'dist',
13
+ 'coverage',
14
+ 'target',
15
+ ])
16
+
17
+ export function globToRegExp(glob) {
18
+ let re = ''
19
+ for (let i = 0; i < glob.length; i++) {
20
+ const c = glob[i]
21
+ if (c === '*' && glob[i + 1] === '*') {
22
+ re += glob[i + 2] === '/' ? '(?:.*/)?' : '.*'
23
+ i += glob[i + 2] === '/' ? 2 : 1
24
+ } else if (c === '*') re += '[^/]*'
25
+ else if (c === '?') re += '[^/]'
26
+ else if (c === '{') {
27
+ const end = glob.indexOf('}', i)
28
+ re += `(?:${glob
29
+ .slice(i + 1, end)
30
+ .split(',')
31
+ .map((s) => s.replace(/[.+^$()|[\]\\]/g, '\\$&'))
32
+ .join('|')})`
33
+ i = end
34
+ } else re += c.replace(/[.+^$()|[\]\\]/g, '\\$&')
35
+ }
36
+ return new RegExp(`^${re}$`)
37
+ }
38
+
39
+ export const matcher = (globs) => {
40
+ const res = (globs ?? []).map(globToRegExp)
41
+ return (path) => res.some((re) => re.test(path))
42
+ }
43
+
44
+ /** Relative posix paths under `root` matching `include` and none of `exclude`. Sorted, so output is stable. */
45
+ export function discover(root, { include = ['**/*.{tsx,jsx}'], exclude = [] } = {}) {
46
+ const inc = matcher(include)
47
+ const exc = matcher(exclude)
48
+ /** @type {string[]} */
49
+ const out = []
50
+ const walk = (rel) => {
51
+ for (const ent of readdirSync(join(root, rel), { withFileTypes: true })) {
52
+ const path = rel ? `${rel}/${ent.name}` : ent.name
53
+ if (ent.isDirectory()) {
54
+ if (!skipDirs.has(ent.name) && !exc(path) && !exc(`${path}/`)) walk(path)
55
+ } else if (inc(path) && !exc(path)) out.push(path)
56
+ }
57
+ }
58
+ walk('')
59
+ return out.sort()
60
+ }
package/src/fix.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // `kerf fix`: apply every autofix `kerf check` marks safe, the same edits an agent reads in `--json`. Unsafe fixes are
2
+ // suggestions and stay with the agent. Edits are applied last first; one that overlaps an earlier one waits for the
3
+ // next pass, and passes repeat until nothing is left (a fix can only shrink what the next check reports).
4
+
5
+ import { readFileSync, writeFileSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import { check } from './check.mjs'
8
+
9
+ const PASSES = 5
10
+
11
+ export async function fix(root, options = {}) {
12
+ root = resolve(root)
13
+ const applied = []
14
+ for (let pass = 0; pass < PASSES; pass++) {
15
+ const { diagnostics } = await check(root, options)
16
+ const byFile = new Map()
17
+ for (const d of diagnostics) {
18
+ if (!d.fix?.safe || !d.fix.edits?.length) continue
19
+ const file = d.fix.edits[0].file
20
+ byFile.set(file, [...(byFile.get(file) ?? []), d])
21
+ }
22
+ if (!byFile.size) break
23
+ let changed = 0
24
+ for (const [file, list] of byFile) {
25
+ const edits = []
26
+ for (const d of list) {
27
+ if (
28
+ d.fix.edits.some(
29
+ (e) =>
30
+ e.file !== file ||
31
+ edits.some((x) => e.offset[0] < x.offset[1] && x.offset[0] < e.offset[1]),
32
+ )
33
+ )
34
+ continue
35
+ edits.push(...d.fix.edits)
36
+ applied.push({ code: d.code, file, span: d.span })
37
+ changed++
38
+ }
39
+ const abs = join(root, file)
40
+ let text = readFileSync(abs, 'utf8')
41
+ for (const e of edits.sort((a, b) => b.offset[0] - a.offset[0]))
42
+ text = text.slice(0, e.offset[0]) + e.text + text.slice(e.offset[1])
43
+ writeFileSync(abs, text)
44
+ }
45
+ if (!changed) break
46
+ }
47
+ return { ok: true, applied }
48
+ }
@@ -0,0 +1,40 @@
1
+ import { copyProject, removeCopy } from '../workspace.mjs'
2
+ import { resolver } from './resolve-cases.mjs'
3
+
4
+ export async function afterRun({ cases, testFiles, log, root, options, run, result }) {
5
+ // After: the change as it stands. Every changed test must pass.
6
+ log(
7
+ `gate: ${cases.length} new or changed tests in ${testFiles.length} files; running them on the change`,
8
+ )
9
+ const afterDir = copyProject(root, { exclude: options.exclude, id: 'after' })
10
+ let after
11
+ try {
12
+ after = await run(afterDir, testFiles)
13
+ } finally {
14
+ removeCopy(afterDir)
15
+ }
16
+ const resolveCases = resolver(testFiles, cases)
17
+ const afterStatus = resolveCases(after)
18
+ const byKey = new Map()
19
+ for (const [key, st] of afterStatus) {
20
+ const [file, name] = key.split('::')
21
+ const c =
22
+ cases.find((x) => x.file === file && x.name === name) ??
23
+ cases.find((x) => x.file === file && x.dynamic)
24
+ const t = {
25
+ file,
26
+ name,
27
+ line: c?.line ?? 1,
28
+ end: c?.end ?? c?.line ?? 1,
29
+ after: st.status,
30
+ afterMessage: st.status === 'passed' ? undefined : st.message,
31
+ before: null,
32
+ kills: 0,
33
+ }
34
+ byKey.set(key, t)
35
+ result.tests.push(t)
36
+ }
37
+ if (after.timedOut) result.notes.push('the run on the change timed out')
38
+
39
+ return { after, resolveCases, byKey }
40
+ }
@@ -0,0 +1,54 @@
1
+ import { diagnostic } from '../diag.mjs'
2
+ import { copyProject, removeCopy, writeFiles } from '../workspace.mjs'
3
+
4
+ export async function beforeRun({
5
+ source,
6
+ options,
7
+ log,
8
+ root,
9
+ run,
10
+ testFiles,
11
+ resolveCases,
12
+ byKey,
13
+ allowed,
14
+ result,
15
+ diagnostics,
16
+ }) {
17
+ // Before: source reverted, tests and their helpers as they are now. Every changed test must fail.
18
+ if (source.length && !options.refactor) {
19
+ log(`gate: reverting ${source.length} source files; the changed tests must fail`)
20
+ const beforeDir = copyProject(root, { exclude: options.exclude, id: 'before' })
21
+ let before
22
+ try {
23
+ writeFiles(beforeDir, Object.fromEntries(source.map((c) => [c.rel, c.before])))
24
+ before = await run(beforeDir, testFiles)
25
+ } finally {
26
+ removeCopy(beforeDir)
27
+ }
28
+ const beforeStatus = resolveCases(before)
29
+ for (const [key, t] of byKey) {
30
+ const st =
31
+ beforeStatus.get(key) ??
32
+ (before.loadErrors.has(t.file)
33
+ ? { status: 'failed', message: before.loadErrors.get(t.file) }
34
+ : { status: 'missing' })
35
+ t.before = st.status
36
+ t.beforeMessage = st.message
37
+ if (t.after === 'passed' && st.status === 'passed' && allowed('T010', t.file, t.line))
38
+ result.notes.push(`T010 allowed on "${t.name}"`)
39
+ else if (t.after === 'passed' && st.status === 'passed')
40
+ diagnostics.push(
41
+ diagnostic({
42
+ code: 'T010',
43
+ file: t.file,
44
+ span: [t.line, 1, t.line, 1],
45
+ why: `"${t.name}" passes on the code before this change too, so it doesn't test the change`,
46
+ help: "Assert what the change makes different (what the user sees now and didn't before); or, if this is a test for existing behavior, add it in its own change with no source edits",
47
+ }),
48
+ )
49
+ }
50
+ } else if (!options.refactor)
51
+ result.notes.push(
52
+ 'no source change: fail-before skipped; mutants come from the source the new tests import',
53
+ )
54
+ }
@@ -0,0 +1,72 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { discover } from '../files.mjs'
4
+ import { changedCases, weakened } from '../testdiff.mjs'
5
+ import { allowances, checkTestFile, isTestFile, parse } from '../tests.mjs'
6
+
7
+ export function classify(root, changes, code, configFile, importsOf) {
8
+ // Tests, test support (helpers only tests import) and source.
9
+ const tests = changes.filter((c) => isTestFile(c.rel))
10
+ const others = changes.filter((c) => !isTestFile(c.rel) && code(c.rel) && !configFile(c.rel))
11
+ const testAbs = new Set(
12
+ discover(root, {
13
+ include: ['**/*.{test,spec}.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'],
14
+ exclude: ['.kerf/**'],
15
+ }).map((r) => join(root, r)),
16
+ )
17
+ const importedBySource = new Set()
18
+ for (const rel of discover(root, {
19
+ include: ['**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'],
20
+ exclude: ['.kerf/**'],
21
+ })) {
22
+ const abs = join(root, rel)
23
+ if (testAbs.has(abs)) continue
24
+ for (const p of importsOf(abs, readFileSync(abs, 'utf8'))) importedBySource.add(p)
25
+ }
26
+ const importedByTests = new Set()
27
+ for (const abs of testAbs)
28
+ for (const p of importsOf(abs, readFileSync(abs, 'utf8'))) importedByTests.add(p)
29
+ const isSupport = (rel) =>
30
+ importedByTests.has(join(root, rel)) &&
31
+ !importedBySource.has(join(root, rel)) &&
32
+ !rel.match(/(^|\/)src\//)
33
+ const support = others.filter((c) => isSupport(c.rel))
34
+ const source = others.filter((c) => !isSupport(c.rel))
35
+
36
+ // Static: T020 on every changed test file, T001–T009 on the ones that still exist (T005 blocks here).
37
+ const diagnostics = []
38
+ for (const c of tests) diagnostics.push(...weakened(c.before, c.after, c.rel))
39
+ for (const c of tests) {
40
+ if (c.after == null) continue
41
+ for (const d of checkTestFile(c.after, c.rel, { abs: join(root, c.rel), root })) {
42
+ if (d.code === 'T005' && d.severity === 'warning') {
43
+ d.severity = 'error'
44
+ d.why += ' The gate blocks implementation queries in new and changed tests.'
45
+ }
46
+ diagnostics.push(d)
47
+ }
48
+ }
49
+
50
+ // The tests this change has to prove.
51
+ // `// kerf-allow T010: <reason>` / T011 on a test keeps it (shown in the result, for the reviewer).
52
+ const allowFns = new Map(
53
+ tests
54
+ .filter((c) => c.after != null)
55
+ .map((c) => [c.rel, allowances(c.after, parse(c.after, c.rel))]),
56
+ )
57
+ const allowed = (rule, file, line) => allowFns.get(file)?.(rule, line) ?? false
58
+ const cases = tests
59
+ .filter((c) => c.after != null)
60
+ .flatMap((c) =>
61
+ changedCases(c.before, c.after, c.rel).map((t) => ({
62
+ file: c.rel,
63
+ name: t.name,
64
+ line: t.line,
65
+ end: t.end,
66
+ dynamic: t.dynamic,
67
+ })),
68
+ )
69
+ const testFiles = [...new Set(cases.map((c) => c.file))]
70
+
71
+ return { tests, support, source, isSupport, diagnostics, allowed, cases, testFiles }
72
+ }