@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/cli.mjs ADDED
@@ -0,0 +1,340 @@
1
+ // Argument parsing and output for `kerf`. JSON on stdout with --json, human text on stderr.
2
+ // Exit codes: 0 ok, 1 diagnostics with errors (a build refused on one, or a stale AGENTS.md under --check), 2 usage or internal error.
3
+
4
+ import { fix } from './fix.mjs'
5
+ import { writeTokens } from './tokens.mjs'
6
+ import { createRequire } from 'node:module'
7
+ import { existsSync } from 'node:fs'
8
+ import { join, resolve } from 'node:path'
9
+ import { pathToFileURL } from 'node:url'
10
+ import { addCommand } from './add.mjs'
11
+ import { writeAgentsMd } from './agents-md.mjs'
12
+ import { check } from './check.mjs'
13
+ import { formatHuman, sortDiagnostics } from './diag.mjs'
14
+ import { docs } from './docs.mjs'
15
+ import { compilerLine, doctor, formatDoctor } from './doctor.mjs'
16
+ import { formatMap, writeMap } from './map.mjs'
17
+ import { serve } from './mcp.mjs'
18
+ import { explain, list, sync } from './plugins.mjs'
19
+ import { approveCommand, auditCommand, formatTrust } from './trust.mjs'
20
+ import { loadConfig } from './load-config.mjs'
21
+ import { listSurfaces } from './surface-checks.mjs'
22
+ import { runTask, tasks } from './tasks.mjs'
23
+ import { formatGate, gate } from './gate.mjs'
24
+ import { browserCommand } from './browser/cli.mjs'
25
+ import { commandCapture } from './capture.mjs'
26
+ import { metaTable } from './meta-table.mjs'
27
+ import { audit } from './audit.mjs'
28
+ import {
29
+ buildCommand,
30
+ dbCommand,
31
+ devCommand,
32
+ doctorCommand,
33
+ routesCommand,
34
+ startCommand,
35
+ unsafeAllowed,
36
+ } from './start.mjs'
37
+ import { deployCommand, formatHosts, hostsCommand, initCommand } from './deploy/index.mjs'
38
+ import {
39
+ explainTarget,
40
+ findGroups,
41
+ formatExplain,
42
+ formatFind,
43
+ styleMatrix,
44
+ writeMatrixFile,
45
+ } from './style.mjs'
46
+
47
+ import {
48
+ commandLsp,
49
+ commandTsc,
50
+ commandCheck,
51
+ commandDoctor,
52
+ commandTest,
53
+ commandBrowser,
54
+ commandDev,
55
+ commandBuild,
56
+ commandAudit,
57
+ commandDeploy,
58
+ commandStart,
59
+ commandDb,
60
+ commandRoutes,
61
+ commandSurfaces,
62
+ commandTasks,
63
+ commandRun,
64
+ commandDocs,
65
+ commandAgentsMd,
66
+ } from './cli/project.mjs'
67
+ import {
68
+ commandMap,
69
+ commandIcons,
70
+ commandAdd,
71
+ commandPlugins,
72
+ commandFix,
73
+ commandTokens,
74
+ commandStyle,
75
+ commandMcp,
76
+ } from './cli/authoring.mjs'
77
+
78
+ const usage = `usage: kerf <command> [--json] [--root <dir>]
79
+
80
+ check [files…] [--preset <p>] compile in check mode; W-, P- and D-diagnostics with fixes (--verbose: which compiler ran)
81
+ doctor [--preset <p>] which compiler this install uses, whether Rust is around (it's optional), and what live data does on the target
82
+ fix [files…] apply the safe autofixes
83
+ tokens veneer's resolved tokens as DTCG, in .kerf/tokens/
84
+ test --gate the test gate on the diff: fail-before (T010), mutants on changed lines (T011), no weakening (T020)
85
+ [--base <ref>] [--budget <sec>] [--max-mutants <n>] [--refactor] [--no-mutation]
86
+ browser <cmd> drive the running app (\`kerf browser help\`): open, snapshot, act, assert, net, time, record…
87
+ capture <cmd> stills at scroll stops, frame times, contact sheets and scene poster bakes in headless Chrome
88
+ on the GPU, from @kerf-js/capture (\`kerf capture help\`)
89
+ lsp a language server for editors on TypeScript 7: tsc --lsp with inferred props
90
+ tsc type-check the whole project with inferred props (tsc or tsgo; for CI)
91
+ dev [--port <n>] the dev server for an app with src/routes (Vite + Nitro)
92
+ build [--runtime node|bun|deno] [--preset <p>] production build to .output, and .kerf/contract.json; then the
93
+ built pages are audited (L-codes) and an error fails the build
94
+ [--unsafe-allow <codes>] go past these codes (R002, L003, a family like L, or all): forces a deploy
95
+ audit [routes…] [--url <u>] [--indexing public|private|auto] [--all] [--max <n>] the built pages, or a running site, in a clean Chrome at a phone's
96
+ and a desktop's width: axe-core's WCAG rules, console, deprecations, head, sideways scroll, shift
97
+ deploy [--prod] [--yes] [--target t] fit check, build for the target, then the host's own CLI; without --yes a dry
98
+ run that prints what would run. Netlify, Vercel, Cloudflare, Fly, Render; the live URL at the end
99
+ deploy hosts which hosts can run this app, why not, what each costs, and the one kerf suggests
100
+ deploy init [target] [--dry-run] [--force] the host's files (netlify.toml, fly.toml + Dockerfile…), a GitHub
101
+ workflow that checks and deploys on push, and \`deploy\` in the config
102
+ start [--runtime r] run .output/ on its runtime (the config's \`runtime\`, node by default)
103
+ db generate [name] a migration for the schema's changes (it applies on the next request)
104
+ db live a migration with change triggers for the tables in \`changes\`
105
+ db listen the change feed as its own process, for an app on functions
106
+ routes [--meta] the route table; --meta: every route's merged metadata, tags, card mode and H-diagnostics
107
+ surfaces the canvas and WebGL surfaces this project already defines
108
+ tasks commands and project tasks
109
+ run <task> run a project task from kerf.config.ts
110
+ docs [topic|code] docs for agents (rules, props, lists, async, testing, config, diagnostics, commands, W014…)
111
+ agents-md [--check] write AGENTS.md (--check: exit 1 when stale; --stdout: print it)
112
+ map [--stdout] write .kerf/map.md and .json: a matrix of what to call in this app
113
+ icons publish <dir> every icon and variant as static .svg files with a manifest.json, for a CDN
114
+ add <feature> install a plugin and wire it into the config; also tailwind, auth, db [engine] [--layer drizzle|prisma|native], and rust [name] [--remote] [--dry-run] [--no-install]
115
+ plugins [list] plugins, the slots they provide and bind, permissions, diagnostics
116
+ plugins explain <slot> binding chain: config → plugin → module → .kerf/slots/<id>.ts
117
+ plugins sync regenerate .kerf/slots/*, .kerf/slots.d.ts and .kerf/tokens/*
118
+ plugins audit each plugin's permissions and code against .kerf/plugins.lock.json, and what it uses undeclared
119
+ plugins approve [name…] [--all] record them in the lock; with no names, show what's waiting and write nothing
120
+ style find <query> style groups that fit what you're about to style (\`card\`, \`status badge\`): reuse before you write
121
+ style explain <group|selector> [--<axis> <value>] [--states a,b] [--accent intent:token] [--part p]
122
+ resolved CSS for one variation, and where each value came from
123
+ style matrix write .kerf/styles.json (every group: axes, parts, accents, resolved CSS, uses)
124
+ mcp MCP server on stdio: docs, check, audit, routes_meta, map, tasks, surfaces, style_find,
125
+ style_explain, test_gate, browser_*`
126
+
127
+ /** Flags that take a value (`--base main` or `--base=main`), and boolean flags, beyond the global ones. */
128
+ const valued = new Set([
129
+ 'layer',
130
+ 'base',
131
+ 'budget',
132
+ 'max-mutants',
133
+ 'concurrency',
134
+ 'url',
135
+ 'indexing',
136
+ 'tab',
137
+ 'out',
138
+ 'component',
139
+ 'from',
140
+ 'props',
141
+ 'name',
142
+ 'scope',
143
+ 'timeout',
144
+ 'preset',
145
+ 'port',
146
+ 'runtime',
147
+ 'unsafe-allow',
148
+ 'max',
149
+ 'target',
150
+ ])
151
+ /** `kerf style explain` takes the group's own axes as flags (`--status late`); these are its fixed ones. */
152
+ const styleFlags = new Set(['states', 'accent', 'part'])
153
+ const booleans = new Set([
154
+ 'dry-run',
155
+ 'no-install',
156
+ 'remote',
157
+ 'gate',
158
+ 'refactor',
159
+ 'no-mutation',
160
+ 'interactive',
161
+ 'delta',
162
+ 'graph-only',
163
+ 'no-graph',
164
+ 'headed',
165
+ 'full',
166
+ 'reload',
167
+ 'meta',
168
+ 'all',
169
+ 'verbose',
170
+ 'prod',
171
+ 'yes',
172
+ 'force',
173
+ ])
174
+
175
+ export function parse(argv) {
176
+ const out = {
177
+ command: argv[0],
178
+ positional: [],
179
+ json: false,
180
+ root: process.cwd(),
181
+ check: false,
182
+ stdout: false,
183
+ flags: {},
184
+ }
185
+ for (let i = 1; i < argv.length; i++) {
186
+ const a = argv[i]
187
+ if (a === '--json') out.json = true
188
+ else if (a === '--check') out.check = true
189
+ else if (a === '--stdout') out.stdout = true
190
+ else if (a === '--root') out.root = resolve(argv[++i] ?? '.')
191
+ else if (a.startsWith('--root=')) out.root = resolve(a.slice(7))
192
+ else if (a.startsWith('--')) {
193
+ const [name, inline] = a.slice(2).split(/=(.*)/s)
194
+ if (valued.has(name)) out.flags[name] = inline ?? argv[++i]
195
+ else if (booleans.has(name) && inline === undefined) out.flags[name] = true
196
+ else if (out.command === 'style' && styleFlags.has(name))
197
+ out.flags[name] = inline ?? argv[++i]
198
+ else if (
199
+ out.command === 'style' &&
200
+ /^[a-z][\w-]*$/i.test(name) &&
201
+ (inline ?? argv[i + 1]) !== undefined
202
+ )
203
+ (out.flags.axes ??= {})[name] = inline ?? argv[++i]
204
+ else throw Object.assign(new Error(`unknown flag ${a}`), { code: 'E_USAGE' })
205
+ } else out.positional.push(a)
206
+ }
207
+ return out
208
+ }
209
+
210
+ const dependencies = {
211
+ fix,
212
+ writeTokens,
213
+ createRequire,
214
+ existsSync,
215
+ join,
216
+ resolve,
217
+ pathToFileURL,
218
+ addCommand,
219
+ writeAgentsMd,
220
+ check,
221
+ formatHuman,
222
+ sortDiagnostics,
223
+ docs,
224
+ compilerLine,
225
+ doctor,
226
+ formatDoctor,
227
+ formatMap,
228
+ writeMap,
229
+ serve,
230
+ explain,
231
+ list,
232
+ sync,
233
+ approveCommand,
234
+ auditCommand,
235
+ formatTrust,
236
+ loadConfig,
237
+ listSurfaces,
238
+ runTask,
239
+ tasks,
240
+ formatGate,
241
+ gate,
242
+ browserCommand,
243
+ metaTable,
244
+ audit,
245
+ buildCommand,
246
+ dbCommand,
247
+ devCommand,
248
+ doctorCommand,
249
+ routesCommand,
250
+ startCommand,
251
+ unsafeAllowed,
252
+ deployCommand,
253
+ formatHosts,
254
+ hostsCommand,
255
+ initCommand,
256
+ explainTarget,
257
+ findGroups,
258
+ formatExplain,
259
+ formatFind,
260
+ styleMatrix,
261
+ writeMatrixFile,
262
+ }
263
+
264
+ export async function main(argv, io = { stdout: process.stdout, stderr: process.stderr }) {
265
+ const print = (data) => io.stdout.write(`${JSON.stringify(data, null, 2)}\n`)
266
+ const say = (text) => text && io.stderr.write(`${text}\n`)
267
+ let args
268
+ try {
269
+ if (argv[0] === 'capture') return await commandCapture(argv.slice(1), process.cwd())
270
+ args = parse(argv)
271
+ const context = { ...dependencies, args, print, say, io }
272
+ switch (args.command) {
273
+ case 'lsp':
274
+ return await commandLsp(context)
275
+ case 'tsc':
276
+ return await commandTsc(context)
277
+ case 'check':
278
+ return await commandCheck(context)
279
+ case 'doctor':
280
+ return await commandDoctor(context)
281
+ case 'test':
282
+ return await commandTest(context)
283
+ case 'browser':
284
+ return await commandBrowser(context)
285
+ case 'dev':
286
+ return await commandDev(context)
287
+ case 'build':
288
+ return await commandBuild(context)
289
+ case 'audit':
290
+ return await commandAudit(context)
291
+ case 'deploy':
292
+ return await commandDeploy(context)
293
+ case 'start':
294
+ return await commandStart(context)
295
+ case 'db':
296
+ return await commandDb(context)
297
+ case 'routes':
298
+ return await commandRoutes(context)
299
+ case 'surfaces':
300
+ return commandSurfaces(context)
301
+ case 'tasks':
302
+ return await commandTasks(context)
303
+ case 'run':
304
+ return await commandRun(context)
305
+ case 'docs':
306
+ return await commandDocs(context)
307
+ case 'agents-md':
308
+ return await commandAgentsMd(context)
309
+ case 'map':
310
+ return await commandMap(context)
311
+ case 'icons':
312
+ return await commandIcons(context)
313
+ case 'add':
314
+ return await commandAdd(context)
315
+ case 'plugins':
316
+ return await commandPlugins(context)
317
+ case 'fix':
318
+ return await commandFix(context)
319
+ case 'tokens':
320
+ return await commandTokens(context)
321
+ case 'style':
322
+ return await commandStyle(context)
323
+ case 'mcp':
324
+ return await commandMcp(context)
325
+ case undefined:
326
+ case 'help':
327
+ case '--help':
328
+ say(usage)
329
+ return args.command ? 0 : 2
330
+ default:
331
+ throw Object.assign(new Error(`unknown command ${args.command}`), { code: 'E_USAGE' })
332
+ }
333
+ } catch (error) {
334
+ const code = error.code ?? 'E_INTERNAL'
335
+ if (args?.json || argv.includes('--json'))
336
+ print({ ok: false, error: { code, message: error.message } })
337
+ say(`kerf: ${error.message}${code === 'E_USAGE' ? `\n\n${usage}` : ''}`)
338
+ return code === 'E_REFUSED' ? 1 : 2
339
+ }
340
+ }
@@ -0,0 +1 @@
1
+ export * from '@kerf-js/core/config'
package/src/config.mjs ADDED
@@ -0,0 +1,5 @@
1
+ // `defineConfig` for kerf.config.ts. Identity at runtime; the types (config.d.ts) are the point.
2
+ // Apps import it from `@kerf-js/core/config`; the CLI's loader falls back here when a project's kerf doesn't resolve.
3
+
4
+ /** @type {import('@kerf-js/core/config').defineConfig} */
5
+ export const defineConfig = (config) => config
@@ -0,0 +1,119 @@
1
+ // What each plugin's `contribute()` returned, checked against the limits. Apart from plugins.mjs because loading a config needs it and the plugin commands load configs.
2
+
3
+ export const agentsLimit = 1024
4
+ /** Rows a plugin may add to the agent map. */
5
+ const mapLimit = 5
6
+ const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
7
+
8
+ /** JSON with sorted keys and functions named, so two runs of a pure `contribute()` compare equal. */
9
+ function stable(value) {
10
+ return JSON.stringify(value, (_, v) => {
11
+ if (typeof v === 'function') return `[function ${v.name}]`
12
+ if (v && typeof v === 'object' && !Array.isArray(v))
13
+ return Object.fromEntries(
14
+ Object.keys(v)
15
+ .sort()
16
+ .map((k) => [k, v[k]]),
17
+ )
18
+ return v
19
+ })
20
+ }
21
+
22
+ /**
23
+ * Run `contribute()` for every plugin instance that has one (data-only entries are skipped), in name order.
24
+ * @param {object[]} plugins unique entries from `plugins`
25
+ * @param {(code: string, why: string, near: string, extra?: object) => void} report
26
+ * @param {{ root: string, command?: string }} env
27
+ * @returns {{ name: string, version?: string, namespace?: string, permissions?: object, manifest: object }[]}
28
+ */
29
+ export function contributions(plugins, report, env) {
30
+ const out = []
31
+ const tokenOwner = new Map()
32
+ const catalogOwner = new Map()
33
+ for (const p of [...plugins].sort(byName)) {
34
+ if (typeof p.contribute !== 'function') continue
35
+ const run = () =>
36
+ p.contribute({ command: env.command ?? 'check', mode: 'development', root: env.root })
37
+ let manifest
38
+ try {
39
+ manifest = run()
40
+ } catch (error) {
41
+ const code = typeof error?.code === 'string' ? error.code : 'P007'
42
+ report(code, `\`${p.name}\`: ${String(error?.message ?? error).split('\n')[0]}`, p.name, {
43
+ owner: code === 'P007' ? 'core' : p.name,
44
+ help: error?.help,
45
+ })
46
+ continue
47
+ }
48
+ let again
49
+ try {
50
+ again = run()
51
+ } catch {}
52
+ if (!again || stable(again) !== stable(manifest))
53
+ report(
54
+ 'P117',
55
+ `\`${p.name}\`'s contribute() returned a different manifest on a second call.`,
56
+ p.name,
57
+ )
58
+
59
+ const ns = checkManifest(p, manifest, report, tokenOwner, catalogOwner)
60
+ out.push({
61
+ name: p.name,
62
+ version: p.version,
63
+ namespace: ns,
64
+ permissions: p.permissions ?? {},
65
+ manifest,
66
+ })
67
+ }
68
+ return out
69
+ }
70
+
71
+ function checkManifest(p, manifest, report, tokenOwner, catalogOwner) {
72
+ const ns = p.namespace ?? `${p.name.replace(/^@[^/]+\//, '').replace(/^plugin-/, '')}/`
73
+ for (const d of manifest.diagnostics ?? []) {
74
+ if (!d.code.startsWith(ns))
75
+ report(
76
+ 'P111',
77
+ `\`${p.name}\` declares \`${d.code}\`, outside its namespace \`${ns}\`.`,
78
+ p.name,
79
+ )
80
+ }
81
+ const agents = manifest.agents
82
+ if (agents) {
83
+ const bytes = Buffer.byteLength(agentsSection(agents))
84
+ if (bytes > agentsLimit)
85
+ report(
86
+ 'P112',
87
+ `\`${p.name}\`'s AGENTS section is ${bytes} bytes (limit ${agentsLimit}).`,
88
+ p.name,
89
+ )
90
+ }
91
+ if ((manifest.map?.length ?? 0) > mapLimit)
92
+ report(
93
+ 'P112',
94
+ `\`${p.name}\` adds ${manifest.map.length} map rows (limit ${mapLimit}).`,
95
+ p.name,
96
+ )
97
+ const tns = manifest.tokens?.namespace
98
+ if (tns) {
99
+ if (tokenOwner.has(tns))
100
+ report(
101
+ 'P113',
102
+ `Token namespace \`${tns}\` is contributed by both \`${tokenOwner.get(tns)}\` and \`${p.name}\`.`,
103
+ p.name,
104
+ )
105
+ else tokenOwner.set(tns, p.name)
106
+ }
107
+ for (const c of manifest.catalog ?? []) {
108
+ if (catalogOwner.has(c.name))
109
+ report(
110
+ 'P113',
111
+ `Catalog entry \`${c.name}\` is contributed by both \`${catalogOwner.get(c.name)}\` and \`${p.name}\`.`,
112
+ p.name,
113
+ )
114
+ else catalogOwner.set(c.name, p.name)
115
+ }
116
+ return ns
117
+ }
118
+
119
+ export const agentsSection = (agents) => `### ${agents.title}\n\n${agents.text.trim()}\n`
@@ -0,0 +1,41 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { dirname, join } from 'node:path'
5
+ import { loadConfig } from './load-config.mjs'
6
+
7
+ /** The app's data layer: the plugin that declares one, or Drizzle, which is built in. Null with no database. */
8
+ export async function dbLayer(root, loaded) {
9
+ const { contributions = [] } = loaded ?? (await loadConfig(root))
10
+ const plugin = contributions.find((c) => c.manifest.db)?.manifest.db
11
+ if (plugin) return plugin
12
+ // Drizzle has no plugin to say so: its config file, or a client from `@kerf-js/start/db/*`, does.
13
+ const entry = join(root, 'src/db/index.server.ts')
14
+ return existsSync(join(root, 'drizzle.config.ts')) ||
15
+ (existsSync(entry) && readFileSync(entry, 'utf8').includes('@kerf-js/start/db/'))
16
+ ? DRIZZLE
17
+ : null
18
+ }
19
+
20
+ const DRIZZLE = {
21
+ layer: 'drizzle',
22
+ schema: 'src/db/schema.ts',
23
+ migrations: 'drizzle',
24
+ generate(root) {
25
+ let bin
26
+ try {
27
+ const req = createRequire(join(root, 'package.json'))
28
+ bin = join(dirname(req.resolve('drizzle-kit')), 'bin.cjs')
29
+ } catch {
30
+ throw Object.assign(new Error('drizzle-kit is not installed in this project'), {
31
+ code: 'E_USAGE',
32
+ })
33
+ }
34
+ const r = spawnSync(process.execPath, [bin, 'generate'], { cwd: root, encoding: 'utf8' })
35
+ if (r.status !== 0)
36
+ throw Object.assign(new Error(`drizzle-kit generate failed:\n${r.stdout}${r.stderr}`), {
37
+ code: 'E_INTERNAL',
38
+ })
39
+ return r.stdout.trim()
40
+ },
41
+ }
@@ -0,0 +1,142 @@
1
+ // What a half-set-up deploy looks like, without touching a provider (research 46 §8, §9): a credential written into a
2
+ // file (E008), Cloudflare in front of nothing or in front of a CDN (E010, E011), and Cloudinary without what it needs
3
+ // (E012–E014).
4
+
5
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { host } from './hosts.mjs'
8
+
9
+ /** Credentials with a shape of their own, and a value assigned to a key that names one. */
10
+ const SHAPED = [
11
+ [/\bnfp_[A-Za-z0-9]{20,}/, 'a Netlify token'],
12
+ [/\bFlyV1\s+fm\d_[A-Za-z0-9+/=_-]{20,}/, 'a Fly token'],
13
+ [
14
+ /api\.render\.com\/deploy\/srv-[\w-]+\?key=[\w-]+/,
15
+ 'a Render deploy hook (its key deploys the service)',
16
+ ],
17
+ [/cloudinary:\/\/\d+:[^@\s'"]+@/, 'a Cloudinary URL with its secret'],
18
+ ]
19
+ const KEYED =
20
+ /\b[\w-]*(token|secret|api[_-]?key|password)[\w-]*["']?\s*[:=]\s*["']([^"'\s$]{16,})["']/i
21
+
22
+ const FILES = [
23
+ 'kerf.config.ts',
24
+ 'kerf.config.mts',
25
+ 'kerf.config.js',
26
+ 'kerf.config.mjs',
27
+ 'kerf.config.json',
28
+ 'kerf.config.yaml',
29
+ 'kerf.config.yml',
30
+ 'netlify.toml',
31
+ 'vercel.json',
32
+ 'wrangler.toml',
33
+ 'fly.toml',
34
+ 'render.yaml',
35
+ 'Dockerfile',
36
+ ]
37
+
38
+ /** E008: a credential in a file that gets committed, comments included. An env var's name, or `${{ secrets.X }}`, is never one. */
39
+ export function writtenSecrets(root) {
40
+ const out = []
41
+ const wf = join(root, '.github/workflows')
42
+ const files = [
43
+ ...FILES,
44
+ ...(existsSync(wf)
45
+ ? readdirSync(wf)
46
+ .filter((f) => /\.ya?ml$/.test(f))
47
+ .map((f) => `.github/workflows/${f}`)
48
+ : []),
49
+ ]
50
+ for (const file of files) {
51
+ let text
52
+ try {
53
+ text = readFileSync(join(root, file), 'utf8')
54
+ } catch {
55
+ continue
56
+ }
57
+ text.split('\n').forEach((line, i) => {
58
+ const shaped = SHAPED.find(([re]) => re.test(line))
59
+ const keyed = !shaped && KEYED.exec(line)
60
+ if (shaped || keyed)
61
+ out.push({
62
+ file,
63
+ line: i + 1,
64
+ what: shaped ? shaped[1] : `a value for \`${keyed[0].split(/["':=\s]/)[0]}\``,
65
+ })
66
+ })
67
+ }
68
+ return out
69
+ }
70
+
71
+ /** Hosts whose own domain says the proxy isn't in front. */
72
+ const OWN = /\.(fly\.dev|onrender\.com|netlify\.app|vercel\.app|workers\.dev|pages\.dev)$/
73
+
74
+ /** E010–E014 from the config, and the environment when `env` is given (a deploy or `kerf doctor`). */
75
+ export function cdnFindings(config = {}, { env } = {}) {
76
+ const out = []
77
+ const cdn = config.deploy?.cdn ?? {}
78
+ const target = config.deploy?.target && host(config.deploy.target)
79
+ const add = (code, severity, why, fix) =>
80
+ out.push({ code, severity, file: 'kerf.config.ts', why, fix })
81
+ if (cdn.proxy === 'cloudflare') {
82
+ let url
83
+ try {
84
+ url = config.site?.url && new URL(config.site.url).hostname
85
+ } catch {}
86
+ if (url && OWN.test(url))
87
+ add(
88
+ 'E010',
89
+ 'warning',
90
+ `\`deploy.cdn.proxy\` is Cloudflare, and \`site.url\` is \`${url}\`, the host's own domain: nothing goes through the proxy, and canonical URLs point past it`,
91
+ 'Set `site.url` to the domain Cloudflare proxies, with its DNS record proxied (orange cloud) to the host',
92
+ )
93
+ if (target && target.kind !== 'server')
94
+ add(
95
+ 'E011',
96
+ 'warning',
97
+ `\`deploy.cdn.proxy\` puts Cloudflare in front of ${target.name}, which is a CDN already: two caches, and a deploy purges only its own`,
98
+ 'Drop `cdn.proxy`, or deploy to a server host (`fly`, `render`) behind it',
99
+ )
100
+ }
101
+ const images = cdn.images
102
+ if (images?.provider === 'cloudinary') {
103
+ const plugins = (config.plugins ?? []).map((p) => p?.name ?? p)
104
+ if (!plugins.some((n) => typeof n === 'string' && n.includes('@kerf-js/media')))
105
+ add(
106
+ 'E012',
107
+ 'error',
108
+ '`deploy.cdn.images` is Cloudinary, and `@kerf-js/media` is not in `plugins`: nothing would send it an image',
109
+ '`kerf add media`, or drop `cdn.images`',
110
+ )
111
+ const given = env?.CLOUDINARY_URL
112
+ const cloud = given && /@([\w-]+)\/?$/.exec(given)?.[1]
113
+ if (!images.cloud && !given)
114
+ add(
115
+ 'E013',
116
+ 'error',
117
+ '`deploy.cdn.images` names no `cloud`, and `CLOUDINARY_URL` is unset: there is no account to send images to',
118
+ "Set `cdn.images.cloud` to the cloud's name, and `CLOUDINARY_URL` in the host's environment (never in a file)",
119
+ )
120
+ else if (cloud && images.cloud && cloud !== images.cloud)
121
+ add(
122
+ 'E013',
123
+ 'error',
124
+ `\`cdn.images.cloud\` is \`${images.cloud}\`, and \`CLOUDINARY_URL\` here names \`${cloud}\`: one of them is another account`,
125
+ 'Make them name the same cloud',
126
+ )
127
+ else if (env && !given)
128
+ add(
129
+ 'E013',
130
+ 'warning',
131
+ "`CLOUDINARY_URL` is unset here: the server needs it in the host's environment",
132
+ "Set it in the host's environment settings, never in a file",
133
+ )
134
+ add(
135
+ 'E014',
136
+ 'info',
137
+ "`cdn.images` is checked, but this kerf doesn't send uploads to Cloudinary yet: they still go to `media({ server: { dir } })`",
138
+ 'Nothing yet: research 46 §9 is the plan. On a function host, uploads need a server host with a disk until then (E003)',
139
+ )
140
+ }
141
+ return out
142
+ }