@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.
- package/LICENSE +16 -0
- package/README.md +554 -2
- package/bin/kerf.mjs +15 -0
- package/docs/async.md +50 -0
- package/docs/browser.md +53 -0
- package/docs/config.md +127 -0
- package/docs/core.md +30 -0
- package/docs/deploy.md +108 -0
- package/docs/design.md +106 -0
- package/docs/entrypoints.md +83 -0
- package/docs/fonts.md +118 -0
- package/docs/icons.md +108 -0
- package/docs/lists.md +25 -0
- package/docs/meta.md +92 -0
- package/docs/plugins.md +166 -0
- package/docs/props.md +88 -0
- package/docs/reactivity.md +26 -0
- package/docs/rules.md +39 -0
- package/docs/rust.md +253 -0
- package/docs/start-short.md +10 -0
- package/docs/start.md +642 -0
- package/docs/state.md +122 -0
- package/docs/style.md +82 -0
- package/docs/surface.md +158 -0
- package/docs/testing.md +81 -0
- package/docs/theme.md +263 -0
- package/docs/ui-state.md +105 -0
- package/docs/verify.md +61 -0
- package/package.json +47 -3
- package/src/add/config.mjs +93 -0
- package/src/add/errors.mjs +2 -0
- package/src/add/setup.mjs +88 -0
- package/src/add-rust.mjs +178 -0
- package/src/add.mjs +392 -0
- package/src/agents-md.mjs +240 -0
- package/src/alias.mjs +70 -0
- package/src/audit/page.mjs +313 -0
- package/src/audit/report.mjs +69 -0
- package/src/audit/utils.mjs +5 -0
- package/src/audit.mjs +319 -0
- package/src/browser/cli.mjs +53 -0
- package/src/browser/client.mjs +299 -0
- package/src/browser/commands.mjs +258 -0
- package/src/capture.mjs +21 -0
- package/src/catalog/audit.mjs +129 -0
- package/src/catalog/auth.mjs +40 -0
- package/src/catalog/compiler.mjs +337 -0
- package/src/catalog/contracts.mjs +18 -0
- package/src/catalog/database.mjs +52 -0
- package/src/catalog/deploy.mjs +117 -0
- package/src/catalog/design.mjs +159 -0
- package/src/catalog/forms.mjs +25 -0
- package/src/catalog/hydration.mjs +29 -0
- package/src/catalog/icons.mjs +24 -0
- package/src/catalog/media.mjs +163 -0
- package/src/catalog/metadata.mjs +116 -0
- package/src/catalog/plugins.mjs +228 -0
- package/src/catalog/realtime.mjs +195 -0
- package/src/catalog/rust.mjs +75 -0
- package/src/catalog/server-functions.mjs +100 -0
- package/src/catalog/state.mjs +39 -0
- package/src/catalog/style-groups.mjs +54 -0
- package/src/catalog/tests.mjs +127 -0
- package/src/catalog/text.mjs +200 -0
- package/src/catalog/ui-state.mjs +42 -0
- package/src/catalog.mjs +103 -0
- package/src/check/runtime.mjs +280 -0
- package/src/check.mjs +321 -0
- package/src/cli/authoring.mjs +213 -0
- package/src/cli/project.mjs +302 -0
- package/src/cli.mjs +340 -0
- package/src/config.d.ts +1 -0
- package/src/config.mjs +5 -0
- package/src/contributions.mjs +119 -0
- package/src/db-layer.mjs +41 -0
- package/src/deploy/cdn.mjs +142 -0
- package/src/deploy/files.mjs +266 -0
- package/src/deploy/fit.mjs +166 -0
- package/src/deploy/hosts.mjs +126 -0
- package/src/deploy/index/cli.mjs +20 -0
- package/src/deploy/index/environment.mjs +69 -0
- package/src/deploy/index/steps.mjs +87 -0
- package/src/deploy/index.mjs +387 -0
- package/src/deploy/needs.mjs +149 -0
- package/src/design-checks/accessible-names.mjs +62 -0
- package/src/design-checks/contrast.mjs +43 -0
- package/src/design-checks/csp.mjs +60 -0
- package/src/design-checks/files.mjs +59 -0
- package/src/design-checks/heading-links.mjs +61 -0
- package/src/design-checks/interaction.mjs +65 -0
- package/src/design-checks/jsx.mjs +67 -0
- package/src/design-checks/layout-values.mjs +68 -0
- package/src/design-checks/native-controls.mjs +48 -0
- package/src/design-checks/outline.mjs +39 -0
- package/src/design-checks/reporter.mjs +37 -0
- package/src/design-checks/rules.mjs +274 -0
- package/src/design-checks/values.mjs +262 -0
- package/src/design-checks.mjs +49 -0
- package/src/diag.mjs +98 -0
- package/src/docs.mjs +228 -0
- package/src/doctor.mjs +42 -0
- package/src/files.mjs +60 -0
- package/src/fix.mjs +48 -0
- package/src/gate/after.mjs +40 -0
- package/src/gate/before.mjs +54 -0
- package/src/gate/classify.mjs +72 -0
- package/src/gate/mutation.mjs +209 -0
- package/src/gate/resolve-cases.mjs +22 -0
- package/src/gate/result.mjs +63 -0
- package/src/gate/run.mjs +75 -0
- package/src/gate.mjs +178 -0
- package/src/index.mjs +9 -0
- package/src/infer/box-props.cjs +140 -0
- package/src/infer/core-boxes.cjs +46 -0
- package/src/infer/derived-writes.cjs +95 -0
- package/src/infer/engine/checks.cjs +193 -0
- package/src/infer/engine/flow.cjs +293 -0
- package/src/infer/engine/report.cjs +158 -0
- package/src/infer/engine/utils.cjs +15 -0
- package/src/infer/engine.cjs +265 -0
- package/src/infer/facts/sites.cjs +114 -0
- package/src/infer/facts.cjs +345 -0
- package/src/infer/hosts.cjs +161 -0
- package/src/infer/lsp.mjs +240 -0
- package/src/infer/session.cjs +161 -0
- package/src/infer/shadow.cjs +54 -0
- package/src/infer/worker.cjs +145 -0
- package/src/jsx-scan.mjs +128 -0
- package/src/kerf.mjs +98 -0
- package/src/load-config/schema.mjs +300 -0
- package/src/load-config.mjs +302 -0
- package/src/map.mjs +177 -0
- package/src/mcp/browser-tools.mjs +155 -0
- package/src/mcp.mjs +273 -0
- package/src/meta-table.mjs +63 -0
- package/src/mutate.mjs +224 -0
- package/src/plugin-checks.mjs +118 -0
- package/src/plugins.mjs +258 -0
- package/src/project.mjs +310 -0
- package/src/props-checks.mjs +64 -0
- package/src/props-listener.mjs +56 -0
- package/src/react-checks.mjs +67 -0
- package/src/server-state-checks.mjs +34 -0
- package/src/share-checks.mjs +158 -0
- package/src/site.mjs +46 -0
- package/src/slots.mjs +181 -0
- package/src/start/build.mjs +116 -0
- package/src/start/routes.mjs +38 -0
- package/src/start.mjs +394 -0
- package/src/state-checks/core-state.mjs +223 -0
- package/src/state-checks/modules.mjs +17 -0
- package/src/state-checks/scan.mjs +232 -0
- package/src/state-checks/server-graph.mjs +65 -0
- package/src/state-checks.mjs +189 -0
- package/src/style/find.mjs +121 -0
- package/src/style.mjs +327 -0
- package/src/surface-checks.mjs +384 -0
- package/src/tailwind.mjs +23 -0
- package/src/tasks.mjs +261 -0
- package/src/test-rules/context.mjs +109 -0
- package/src/test-rules/file-rules.mjs +279 -0
- package/src/test-rules/rule-helpers.mjs +244 -0
- package/src/test-rules/syntax.mjs +223 -0
- package/src/test-rules/test-rules.mjs +127 -0
- package/src/testdiff.mjs +219 -0
- package/src/tests.mjs +120 -0
- package/src/text-checks.mjs +332 -0
- package/src/tokens.mjs +33 -0
- package/src/trust/scan.mjs +95 -0
- package/src/trust.mjs +394 -0
- package/src/workspace.mjs +182 -0
- package/ts-plugin/context.js +57 -0
- package/ts-plugin/index.js +17 -0
- package/ts-plugin/mapping.js +65 -0
- package/ts-plugin/package.json +1 -0
- package/ts-plugin/proxy.js +144 -0
package/src/add-rust.mjs
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// `kerf add rust [name]`: a crate, its server module and one working function, so `kerf check` passes on the first run.
|
|
2
|
+
// `native()` by default (one hot function in this process); `--remote` for a sidecar, the same crate behind HTTP. The
|
|
3
|
+
// `kerf` crate isn't on crates.io: it comes with @kerf-js/start, so the app's crate and its TS can't disagree on a version.
|
|
4
|
+
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, relative } from 'node:path'
|
|
7
|
+
import { start } from './start.mjs'
|
|
8
|
+
|
|
9
|
+
const refused = (message) => Object.assign(new Error(message), { code: 'E_ADD' })
|
|
10
|
+
const usage = (message) => Object.assign(new Error(message), { code: 'E_USAGE' })
|
|
11
|
+
const TOOLCHAIN = '1.99.1'
|
|
12
|
+
|
|
13
|
+
const camel = (name) => name.replace(/[-_](.)/g, (_, c) => c.toUpperCase())
|
|
14
|
+
const pascal = (name) => {
|
|
15
|
+
const c = camel(name)
|
|
16
|
+
return c[0].toUpperCase() + c.slice(1)
|
|
17
|
+
}
|
|
18
|
+
const lib = (name) => name.replaceAll('-', '_')
|
|
19
|
+
|
|
20
|
+
const manifest = (name, crate, remote) => `[package]
|
|
21
|
+
name = "${name}"
|
|
22
|
+
version = "0.0.0"
|
|
23
|
+
edition = "2024"
|
|
24
|
+
publish = false
|
|
25
|
+
${
|
|
26
|
+
remote
|
|
27
|
+
? ''
|
|
28
|
+
: `
|
|
29
|
+
[lib]
|
|
30
|
+
crate-type = ["cdylib"]
|
|
31
|
+
`
|
|
32
|
+
}
|
|
33
|
+
[dependencies]
|
|
34
|
+
serde = { version = "1", features = ["derive"] }
|
|
35
|
+
serde_json = "1"
|
|
36
|
+
${
|
|
37
|
+
remote
|
|
38
|
+
? `tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
|
39
|
+
kerf = { path = "${crate}" }`
|
|
40
|
+
: `kerf = { path = "${crate}", default-features = false, features = ["native"] }`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
[build-dependencies]
|
|
44
|
+
kerf = { path = "${crate}", default-features = false, features = ["build"] }
|
|
45
|
+
|
|
46
|
+
# A rebuild in \`kerf dev\` should stay quick and not be a hundred times slower than the real thing.
|
|
47
|
+
[profile.dev]
|
|
48
|
+
opt-level = 1
|
|
49
|
+
|
|
50
|
+
[profile.release]
|
|
51
|
+
lto = "fat"
|
|
52
|
+
codegen-units = 1
|
|
53
|
+
|
|
54
|
+
[workspace]
|
|
55
|
+
`
|
|
56
|
+
|
|
57
|
+
const body = (
|
|
58
|
+
name,
|
|
59
|
+
remote,
|
|
60
|
+
) => `kerf::contract!(); // types and a \`Service\` trait, generated from your Zod: never hand-written
|
|
61
|
+
use contract::*;
|
|
62
|
+
|
|
63
|
+
struct ${pascal(name)};
|
|
64
|
+
|
|
65
|
+
impl Service for ${pascal(name)} {
|
|
66
|
+
async fn digest(&self, _ctx: kerf::Ctx, input: DigestInput) -> Result<DigestOutput, kerf::Error> {
|
|
67
|
+
let hash = input.text.bytes().fold(0x811c9dc5u32, |h, b| (h ^ b as u32).wrapping_mul(0x01000193));
|
|
68
|
+
Ok(DigestOutput { bytes: input.text.len() as i64, hash: format!("{hash:08x}") })
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
${
|
|
72
|
+
remote
|
|
73
|
+
? `
|
|
74
|
+
#[tokio::main]
|
|
75
|
+
async fn main() -> std::io::Result<()> {
|
|
76
|
+
kerf::serve(kerf::router(contract::functions(${pascal(name)}))).await
|
|
77
|
+
}
|
|
78
|
+
`
|
|
79
|
+
: `
|
|
80
|
+
kerf::native!(contract::functions(${pascal(name)}));
|
|
81
|
+
`
|
|
82
|
+
}`
|
|
83
|
+
|
|
84
|
+
const fn = (name, binding) => `import { query } from '@kerf-js/start/data'
|
|
85
|
+
import { z } from 'zod'
|
|
86
|
+
import { ${binding} } from './rust'
|
|
87
|
+
|
|
88
|
+
// \`crates/${name}\` is its body. Change the schema and \`kerf check\` stops at the Rust it broke.
|
|
89
|
+
export const digest = query({
|
|
90
|
+
input: z.object({ text: z.string().max(1_000_000) }),
|
|
91
|
+
output: z.object({ bytes: z.int(), hash: z.string() }),
|
|
92
|
+
impl: ${binding},
|
|
93
|
+
})
|
|
94
|
+
`
|
|
95
|
+
|
|
96
|
+
/** The path Cargo gets. `crate/` is in a packed @kerf-js/start; a linked one is in this repository, next to the crates. */
|
|
97
|
+
async function kerfCrate(root, dir) {
|
|
98
|
+
const { startDir } = await start(root, 'vite')
|
|
99
|
+
const found = [
|
|
100
|
+
join(startDir, '..', 'crate'),
|
|
101
|
+
join(startDir, '..', '..', '..', 'crates', 'kerf'),
|
|
102
|
+
].find((d) => existsSync(join(d, 'Cargo.toml')))
|
|
103
|
+
if (!found) throw refused('this @kerf-js/start has no `kerf` crate in it. Nothing was changed.')
|
|
104
|
+
return relative(dir, found).replaceAll('\\', '/')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function addRust(
|
|
108
|
+
root,
|
|
109
|
+
name = 'media',
|
|
110
|
+
{ remote = false, dryRun = false, install, installSpecs },
|
|
111
|
+
) {
|
|
112
|
+
if (!/^[a-z][a-z0-9_-]*$/.test(name))
|
|
113
|
+
throw usage(
|
|
114
|
+
`\`${name}\` isn't a service name: lower case, then letters, digits, \`-\` or \`_\``,
|
|
115
|
+
)
|
|
116
|
+
if (!existsSync(join(root, 'package.json')))
|
|
117
|
+
throw refused('`kerf add rust` needs a package.json. Nothing was changed.')
|
|
118
|
+
const dir = join(root, 'crates', name)
|
|
119
|
+
const module = join(root, 'src', 'server', `${name}.ts`)
|
|
120
|
+
const taken = [dir, module].filter(existsSync).map((f) => relative(root, f))
|
|
121
|
+
if (taken.length)
|
|
122
|
+
throw refused(
|
|
123
|
+
`${taken.join(', ')} already exist${taken.length > 1 ? '' : 's'}. Pick another name: \`kerf add rust <name>\`. Nothing was changed.`,
|
|
124
|
+
)
|
|
125
|
+
const binding = camel(name)
|
|
126
|
+
const factory = remote ? 'remote' : 'native'
|
|
127
|
+
const call = remote ? `remote('rust://${name}')` : `native('${name}')`
|
|
128
|
+
const rustFile = join(root, 'src', 'server', 'rust.ts')
|
|
129
|
+
const had = existsSync(rustFile)
|
|
130
|
+
? readFileSync(rustFile, 'utf8')
|
|
131
|
+
: '// The only place Rust targets are named.\n'
|
|
132
|
+
if (new RegExp(`\\b${binding}\\b`).test(had))
|
|
133
|
+
throw refused(`src/server/rust.ts already names \`${binding}\`. Nothing was changed.`)
|
|
134
|
+
const imported = new RegExp(
|
|
135
|
+
`import\\s*\\{[^}]*\\b${factory}\\b[^}]*\\}\\s*from\\s*['"]@kerf-js/start/rust['"]`,
|
|
136
|
+
).test(had)
|
|
137
|
+
const nextRust = `${imported ? had : had.replace(/^((?:\/\/.*\n)*)/, `$1import { ${factory} } from '@kerf-js/start/rust'\n`)}${had.endsWith('\n') ? '' : '\n'}\nexport const ${binding} = ${call}\n`
|
|
138
|
+
|
|
139
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
140
|
+
const needsZod = !pkg.dependencies?.zod && !pkg.devDependencies?.zod
|
|
141
|
+
const gitignore = join(root, '.gitignore')
|
|
142
|
+
const ignored =
|
|
143
|
+
existsSync(gitignore) &&
|
|
144
|
+
/^\/?target\/?$|^\*\*\/target\/?$/m.test(readFileSync(gitignore, 'utf8'))
|
|
145
|
+
const actions = [
|
|
146
|
+
`create crates/${name}`,
|
|
147
|
+
`create src/server/${name}.ts`,
|
|
148
|
+
`add \`${binding}\` to src/server/rust.ts`,
|
|
149
|
+
...(needsZod && install ? ['install zod'] : []),
|
|
150
|
+
...(ignored ? [] : ['ignore target/']),
|
|
151
|
+
'this crate needs Rust (`cargo`, from rustup.rs); the rest of kerf does not',
|
|
152
|
+
'next: `kerf check`, then `kerf dev`',
|
|
153
|
+
]
|
|
154
|
+
if (dryRun)
|
|
155
|
+
return { ok: true, feature: 'rust', service: name, kind: factory, actions, dryRun: true }
|
|
156
|
+
|
|
157
|
+
const crate = await kerfCrate(root, dir)
|
|
158
|
+
const write = (file, text) => {
|
|
159
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
160
|
+
writeFileSync(file, text)
|
|
161
|
+
}
|
|
162
|
+
write(join(dir, 'Cargo.toml'), manifest(name, crate, remote))
|
|
163
|
+
write(join(dir, 'build.rs'), `fn main() {\n kerf::build::generate("${name}");\n}\n`)
|
|
164
|
+
write(
|
|
165
|
+
join(dir, 'rust-toolchain.toml'),
|
|
166
|
+
`[toolchain]\nchannel = "${TOOLCHAIN}"\n${remote ? '' : 'targets = ["wasm32-unknown-unknown"]\n'}`,
|
|
167
|
+
)
|
|
168
|
+
write(join(dir, 'src', remote ? 'main.rs' : 'lib.rs'), body(lib(name), remote))
|
|
169
|
+
write(module, fn(name, binding))
|
|
170
|
+
write(rustFile, nextRust)
|
|
171
|
+
if (!ignored)
|
|
172
|
+
writeFileSync(
|
|
173
|
+
gitignore,
|
|
174
|
+
`${existsSync(gitignore) ? readFileSync(gitignore, 'utf8').replace(/\n?$/, '\n') : ''}target/\n`,
|
|
175
|
+
)
|
|
176
|
+
if (needsZod && install) installSpecs(['zod'])
|
|
177
|
+
return { ok: true, feature: 'rust', service: name, kind: factory, actions }
|
|
178
|
+
}
|
package/src/add.mjs
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// `kerf add`: what the wizard offers, on an app that already exists (research 34 §7). It installs a plugin and adds it to
|
|
2
|
+
// the config, whichever format that is. It only ever inserts, and stops rather than guess at a config it can't read.
|
|
3
|
+
|
|
4
|
+
import { execFileSync } from 'node:child_process'
|
|
5
|
+
import { randomBytes } from 'node:crypto'
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
8
|
+
import { addRust } from './add-rust.mjs'
|
|
9
|
+
import { writeAgentsMd } from './agents-md.mjs'
|
|
10
|
+
import { findConfig, loadConfig } from './load-config.mjs'
|
|
11
|
+
import { sync } from './plugins.mjs'
|
|
12
|
+
import { cssEntry, packages, viteConfig } from './tailwind.mjs'
|
|
13
|
+
import { database } from './map.mjs'
|
|
14
|
+
import { dbLayer } from './db-layer.mjs'
|
|
15
|
+
import { packageOf, trustStatus } from './trust.mjs'
|
|
16
|
+
|
|
17
|
+
import { usageError, refused } from './add/errors.mjs'
|
|
18
|
+
import { addToTs, addToData, listed, names } from './add/config.mjs'
|
|
19
|
+
import { setupOf, planSetup, applySetup, setupActions, authEdits } from './add/setup.mjs'
|
|
20
|
+
|
|
21
|
+
const ALIASES = {
|
|
22
|
+
veneer: '@kerf-js/veneer',
|
|
23
|
+
icons: '@kerf-js/veneer-icons',
|
|
24
|
+
text: '@kerf-js/text',
|
|
25
|
+
media: '@kerf-js/media',
|
|
26
|
+
'media-ffmpeg': '@kerf-js/media-ffmpeg',
|
|
27
|
+
'surface-keel': '@kerf-js/keel-pixel',
|
|
28
|
+
keel: '@kerf-js/keel',
|
|
29
|
+
redis: '@kerf-js/realtime-redis',
|
|
30
|
+
nats: '@kerf-js/realtime-nats',
|
|
31
|
+
agent: '@kerf-js/agent',
|
|
32
|
+
pay: '@kerf-js/pay',
|
|
33
|
+
'pay-stripe': '@kerf-js/pay/stripe',
|
|
34
|
+
'pay-square': '@kerf-js/pay/square',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Add-ons `kerf add` knows by the name after the scope, as `kerf add realtime-redis`. */
|
|
38
|
+
const ADDONS = new Set([
|
|
39
|
+
'@kerf-js/text',
|
|
40
|
+
'@kerf-js/agent',
|
|
41
|
+
'@kerf-js/pay',
|
|
42
|
+
'@kerf-js/media',
|
|
43
|
+
'@kerf-js/media-ffmpeg',
|
|
44
|
+
'@kerf-js/keel-pixel',
|
|
45
|
+
'@kerf-js/keel',
|
|
46
|
+
'@kerf-js/multiplayer',
|
|
47
|
+
'@kerf-js/realtime-durable-object',
|
|
48
|
+
'@kerf-js/realtime-livekit',
|
|
49
|
+
'@kerf-js/realtime-nats',
|
|
50
|
+
'@kerf-js/realtime-redis',
|
|
51
|
+
'@kerf-js/realtime-socketio',
|
|
52
|
+
'@kerf-js/realtime-webrtc',
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
const INSTALL = {
|
|
56
|
+
'pnpm-lock.yaml': ['pnpm', 'add'],
|
|
57
|
+
'bun.lock': ['bun', 'add'],
|
|
58
|
+
'yarn.lock': ['yarn', 'add'],
|
|
59
|
+
'deno.lock': ['deno', 'add'],
|
|
60
|
+
'package-lock.json': ['npm', 'install'],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function installer(root) {
|
|
64
|
+
const lock = Object.keys(INSTALL).find((f) => existsSync(join(root, f)))
|
|
65
|
+
return (
|
|
66
|
+
INSTALL[lock] ??
|
|
67
|
+
(process.versions.deno
|
|
68
|
+
? INSTALL['deno.lock']
|
|
69
|
+
: process.versions.bun
|
|
70
|
+
? INSTALL['bun.lock']
|
|
71
|
+
: INSTALL['package-lock.json'])
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What to install: for an app on local tarballs (`local.mjs`) those go straight in `package.json`, since npm refuses any
|
|
76
|
+
* spec for them that isn't spelled exactly as their override is. */
|
|
77
|
+
export function pinned(root, specs) {
|
|
78
|
+
const file = join(root, 'package.json')
|
|
79
|
+
const pkg = JSON.parse(readFileSync(file, 'utf8'))
|
|
80
|
+
const local = {}
|
|
81
|
+
const rest = specs.filter((spec) => {
|
|
82
|
+
const name = spec.replace(/(?<=.)@.*$/, '')
|
|
83
|
+
const override = pkg.overrides?.[name]
|
|
84
|
+
if (typeof override !== 'string' || !override.startsWith('file:')) return true
|
|
85
|
+
local[name] = override
|
|
86
|
+
return false
|
|
87
|
+
})
|
|
88
|
+
if (Object.keys(local).length)
|
|
89
|
+
writeFileSync(
|
|
90
|
+
file,
|
|
91
|
+
JSON.stringify({ ...pkg, dependencies: { ...pkg.dependencies, ...local } }, null, 2),
|
|
92
|
+
)
|
|
93
|
+
return rest
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function installSpecs(root, manager, verb, specs) {
|
|
97
|
+
const rest = pinned(root, specs)
|
|
98
|
+
execFileSync(
|
|
99
|
+
manager,
|
|
100
|
+
[verb, ...(manager === 'deno' ? rest.map((spec) => `npm:${spec}`) : rest)],
|
|
101
|
+
{ cwd: root, stdio: ['ignore', 'ignore', 'inherit'], shell: process.platform === 'win32' },
|
|
102
|
+
) // npm is npm.cmd there
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const VITE = ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs']
|
|
106
|
+
|
|
107
|
+
/** The app's Vite config with Tailwind in it. Stops rather than guess at one it can't place the plugin in. */
|
|
108
|
+
function viteWithTailwind(file, text) {
|
|
109
|
+
if (text.includes('@tailwindcss/vite')) return text
|
|
110
|
+
if (!/plugins:\s*\[/.test(text))
|
|
111
|
+
throw refused(
|
|
112
|
+
`${file} has no \`plugins: [\` to add Tailwind to. Add \`tailwindcss()\` from @tailwindcss/vite there, then run this again. Nothing was changed.`,
|
|
113
|
+
)
|
|
114
|
+
return `import tailwindcss from '@tailwindcss/vite'\n${text.replace(/plugins:\s*\[/, '$&tailwindcss(), ')}`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Tailwind's packages, the Vite plugin, and the top of src/app.css, imported first by the root layout. */
|
|
118
|
+
function addTailwind(root, { dryRun, install }) {
|
|
119
|
+
if (!existsSync(join(root, 'package.json')))
|
|
120
|
+
throw refused('`kerf add tailwind` needs a package.json. Nothing was changed.')
|
|
121
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
122
|
+
const cssFile = join(root, 'src/app.css')
|
|
123
|
+
const css = existsSync(cssFile) ? readFileSync(cssFile, 'utf8') : ''
|
|
124
|
+
const viteName = VITE.find((f) => existsSync(join(root, f)))
|
|
125
|
+
const vite = viteName
|
|
126
|
+
? viteWithTailwind(viteName, readFileSync(join(root, viteName), 'utf8'))
|
|
127
|
+
: viteConfig
|
|
128
|
+
const layoutFile = join(root, 'src/routes/_layout.tsx')
|
|
129
|
+
const layout = existsSync(layoutFile) ? readFileSync(layoutFile, 'utf8') : null
|
|
130
|
+
const has = /['"]tailwindcss['"]|tailwindcss\/utilities/.test(css)
|
|
131
|
+
if (has && pkg.dependencies?.tailwindcss)
|
|
132
|
+
return { ok: true, already: true, package: 'tailwindcss', actions: [] }
|
|
133
|
+
|
|
134
|
+
const actions = []
|
|
135
|
+
const [manager, verb] = installer(root)
|
|
136
|
+
const specs = Object.entries(packages).map(([name, version]) => `${name}@${version}`)
|
|
137
|
+
if (install) {
|
|
138
|
+
actions.push(`install ${specs.join(' ')} with ${manager}`)
|
|
139
|
+
if (!dryRun) installSpecs(root, manager, verb, specs)
|
|
140
|
+
}
|
|
141
|
+
const veneer = '@kerf-js/veneer' in { ...pkg.dependencies, ...pkg.devDependencies }
|
|
142
|
+
const edits = [
|
|
143
|
+
[join(root, viteName ?? 'vite.config.ts'), vite],
|
|
144
|
+
...(has ? [] : [[cssFile, `${cssEntry(veneer)}${css && '\n'}${css}`]]),
|
|
145
|
+
]
|
|
146
|
+
actions.push(
|
|
147
|
+
`add Tailwind to ${viteName ?? 'vite.config.ts'}`,
|
|
148
|
+
...(has
|
|
149
|
+
? []
|
|
150
|
+
: [
|
|
151
|
+
`add Tailwind to src/app.css${veneer ? ' (without its reset, which would override veneer)' : ''}`,
|
|
152
|
+
]),
|
|
153
|
+
)
|
|
154
|
+
if (layout === null)
|
|
155
|
+
actions.push('import src/app.css from your root layout: there is no src/routes/_layout.tsx')
|
|
156
|
+
else if (!/['"][^'"]*app\.css['"]/.test(layout)) {
|
|
157
|
+
edits.push([layoutFile, `import '../app.css'\n${layout}`])
|
|
158
|
+
actions.push('import src/app.css first in src/routes/_layout.tsx')
|
|
159
|
+
}
|
|
160
|
+
if (dryRun) return { ok: true, package: 'tailwindcss', actions, dryRun: true }
|
|
161
|
+
mkdirSync(join(root, 'src'), { recursive: true })
|
|
162
|
+
for (const [file, text] of edits) writeFileSync(file, text)
|
|
163
|
+
return { ok: true, package: 'tailwindcss', actions }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const ENGINES = ['sqlite', 'postgres', 'mysql']
|
|
167
|
+
const LAYER_PLUGIN = { prisma: '@kerf-js/db/plugin-prisma', native: '@kerf-js/db/plugin-native' }
|
|
168
|
+
|
|
169
|
+
/** A database on an app that has none: the wiring a scaffold writes, with no todo app. Never touches what's there. */
|
|
170
|
+
async function addDb(root, engine = 'sqlite', { layer = 'drizzle', dryRun, install }) {
|
|
171
|
+
if (!ENGINES.includes(engine))
|
|
172
|
+
throw usageError(`kerf add db takes ${ENGINES.join(', ')}, not \`${engine}\``)
|
|
173
|
+
if (!['drizzle', ...Object.keys(LAYER_PLUGIN)].includes(layer))
|
|
174
|
+
throw usageError(`--layer takes drizzle, prisma or native, not \`${layer}\``)
|
|
175
|
+
if (await dbLayer(root))
|
|
176
|
+
throw refused(
|
|
177
|
+
"This app already has a database. Changing engine or layer changes your queries, so it's yours to do. Nothing was changed.",
|
|
178
|
+
)
|
|
179
|
+
const { stackDeps, stackFiles } = await import('create-kerf/stack')
|
|
180
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
181
|
+
const name = String(pkg.name ?? 'app').replace(/^@.*\//, '')
|
|
182
|
+
const files = stackFiles({ db: engine, layer, auth: false, name, secret: '' })
|
|
183
|
+
delete files['src/routes/todos/index.tsx']
|
|
184
|
+
delete files['src/server/todos.ts']
|
|
185
|
+
const taken = Object.keys(files).filter(
|
|
186
|
+
(f) => f !== '.env' && f !== '.env.example' && existsSync(join(root, f)),
|
|
187
|
+
)
|
|
188
|
+
if (taken.length)
|
|
189
|
+
throw refused(
|
|
190
|
+
`${taken.join(', ')} already exist, so this can't add a database without overwriting them. Nothing was changed.`,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
const { deps, dev } = stackDeps({ db: engine, layer, auth: false })
|
|
194
|
+
const actions = []
|
|
195
|
+
const [manager, verb] = installer(root)
|
|
196
|
+
if (install) {
|
|
197
|
+
const specs = Object.entries({ ...deps, ...dev }).map(([n, v]) => `${n}@${v}`)
|
|
198
|
+
actions.push(`install ${specs.join(' ')} with ${manager}`)
|
|
199
|
+
if (!dryRun) installSpecs(root, manager, verb, specs)
|
|
200
|
+
}
|
|
201
|
+
actions.push(...Object.keys(files).map((f) => `write ${f}`))
|
|
202
|
+
if (dryRun) return { ok: true, package: `${layer} on ${engine}`, actions, dryRun: true }
|
|
203
|
+
for (const [file, text] of Object.entries(files)) {
|
|
204
|
+
const path = join(root, file)
|
|
205
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
206
|
+
if (file.startsWith('.env') && existsSync(path))
|
|
207
|
+
writeFileSync(path, `${readFileSync(path, 'utf8').trimEnd()}\n${text}`)
|
|
208
|
+
else writeFileSync(path, text)
|
|
209
|
+
}
|
|
210
|
+
if (LAYER_PLUGIN[layer])
|
|
211
|
+
actions.push(...(await addCommand(root, LAYER_PLUGIN[layer], { install: false })).actions)
|
|
212
|
+
actions.push('next: `kerf db generate`')
|
|
213
|
+
return { ok: true, package: `${layer} on ${engine}`, actions }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Better Auth on an app with a database. Its tables go beside yours, and your own routes stay as they are. */
|
|
217
|
+
async function addAuth(root, { dryRun, install }) {
|
|
218
|
+
const layer = await dbLayer(root)
|
|
219
|
+
if (!layer)
|
|
220
|
+
throw refused(
|
|
221
|
+
'Better Auth keeps users in a database: run `kerf add db` first. Nothing was changed.',
|
|
222
|
+
)
|
|
223
|
+
if (existsSync(join(root, 'src/auth.server.ts')))
|
|
224
|
+
throw refused(
|
|
225
|
+
'src/auth.server.ts already exists, so this app has an auth provider. Nothing was changed.',
|
|
226
|
+
)
|
|
227
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|
228
|
+
const db = database(root, layer).engine
|
|
229
|
+
const ui =
|
|
230
|
+
'@kerf-js/veneer' in { ...pkg.dependencies, ...pkg.devDependencies } ? 'veneer' : 'none'
|
|
231
|
+
const { authFiles, stackDeps } = await import('create-kerf/stack')
|
|
232
|
+
const { files, context, tables } = authFiles({ db, layer: layer.layer, ui })
|
|
233
|
+
const contextFile = join(root, 'src/context.server.ts')
|
|
234
|
+
if (
|
|
235
|
+
existsSync(contextFile) &&
|
|
236
|
+
!/export default \(\) => \(\{ db \}\)/.test(readFileSync(contextFile, 'utf8'))
|
|
237
|
+
)
|
|
238
|
+
throw refused(
|
|
239
|
+
'src/context.server.ts has been changed. Spread `session(auth, request)` from @kerf-js/start/auth into it, then run this again. Nothing was changed.',
|
|
240
|
+
)
|
|
241
|
+
const taken = Object.keys(files).filter((f) => existsSync(join(root, f)))
|
|
242
|
+
if (taken.length) throw refused(`${taken.join(', ')} already exist. Nothing was changed.`)
|
|
243
|
+
const envModule = join(root, 'src/env.server.ts')
|
|
244
|
+
const envText = existsSync(envModule) ? readFileSync(envModule, 'utf8') : ''
|
|
245
|
+
if (!envText.includes('BETTER_AUTH_SECRET') && !/server: \{\n/.test(envText))
|
|
246
|
+
throw refused(
|
|
247
|
+
'src/env.server.ts has no `server: {` block to add BETTER_AUTH_SECRET to. Nothing was changed.',
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
const actions = []
|
|
251
|
+
const [manager, verb] = installer(root)
|
|
252
|
+
const wanted = stackDeps({ db, layer: layer.layer, auth: true }).deps
|
|
253
|
+
const specs = Object.entries(wanted)
|
|
254
|
+
.filter(([name]) => !(name in (pkg.dependencies ?? {})))
|
|
255
|
+
.map(([n, v]) => `${n}@${v}`)
|
|
256
|
+
if (install && specs.length) {
|
|
257
|
+
actions.push(`install ${specs.join(' ')} with ${manager}`)
|
|
258
|
+
if (!dryRun) installSpecs(root, manager, verb, specs)
|
|
259
|
+
}
|
|
260
|
+
const edits = authEdits({ root, files, context, tables, envText, layer })
|
|
261
|
+
actions.push(...Object.keys(edits).map((f) => `write ${f}`))
|
|
262
|
+
if (!dryRun) {
|
|
263
|
+
for (const [file, text] of Object.entries(edits)) {
|
|
264
|
+
mkdirSync(dirname(join(root, file)), { recursive: true })
|
|
265
|
+
writeFileSync(join(root, file), text)
|
|
266
|
+
}
|
|
267
|
+
const env = join(root, '.env')
|
|
268
|
+
if (!(existsSync(env) && readFileSync(env, 'utf8').includes('BETTER_AUTH_SECRET')))
|
|
269
|
+
writeFileSync(
|
|
270
|
+
env,
|
|
271
|
+
`${existsSync(env) ? `${readFileSync(env, 'utf8').trimEnd()}\n` : ''}BETTER_AUTH_SECRET=${randomBytes(32).toString('base64')}\nBETTER_AUTH_URL=http://localhost:5173\n`,
|
|
272
|
+
)
|
|
273
|
+
}
|
|
274
|
+
actions.push(
|
|
275
|
+
'add BETTER_AUTH_SECRET to .env',
|
|
276
|
+
...(layer.schema ? ['next: `kerf db generate`'] : []),
|
|
277
|
+
'next: reload the app: the migration applies on the next request',
|
|
278
|
+
"next: add `auth: 'user'` to what needs a user, and link to /login",
|
|
279
|
+
)
|
|
280
|
+
return {
|
|
281
|
+
ok: true,
|
|
282
|
+
package: `Better Auth on ${layer.layer}`,
|
|
283
|
+
actions,
|
|
284
|
+
...(dryRun && { dryRun: true }),
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export async function addCommand(
|
|
289
|
+
root,
|
|
290
|
+
feature,
|
|
291
|
+
{ dryRun = false, install = true, engine, layer, remote = false } = {},
|
|
292
|
+
) {
|
|
293
|
+
root = resolve(root)
|
|
294
|
+
if (!feature)
|
|
295
|
+
throw usageError(
|
|
296
|
+
`kerf add needs a feature: db, auth, tailwind, rust, ${Object.keys(ALIASES).join(', ')}, or a package name`,
|
|
297
|
+
)
|
|
298
|
+
if (feature === 'rust') {
|
|
299
|
+
const [manager, verb] = installer(root)
|
|
300
|
+
return addRust(root, engine, {
|
|
301
|
+
remote,
|
|
302
|
+
dryRun,
|
|
303
|
+
install,
|
|
304
|
+
installSpecs: (specs) => installSpecs(root, manager, verb, specs),
|
|
305
|
+
})
|
|
306
|
+
}
|
|
307
|
+
if (feature === 'tailwind') return addTailwind(root, { dryRun, install })
|
|
308
|
+
if (feature === 'db') return addDb(root, engine, { layer, dryRun, install })
|
|
309
|
+
if (feature === 'auth') return addAuth(root, { dryRun, install })
|
|
310
|
+
const pkg =
|
|
311
|
+
ALIASES[feature] ?? (ADDONS.has(`@kerf-js/${feature}`) ? `@kerf-js/${feature}` : feature)
|
|
312
|
+
const file = findConfig(root) ?? join(root, 'kerf.config.ts')
|
|
313
|
+
const config = relative(root, file)
|
|
314
|
+
const text = existsSync(file)
|
|
315
|
+
? readFileSync(file, 'utf8')
|
|
316
|
+
: "import { defineConfig } from '@kerf-js/core/config'\n\nexport default defineConfig({})\n"
|
|
317
|
+
const named = names(text, pkg)
|
|
318
|
+
// A config can name a package that isn't installed yet, and importing it then would leave this process's module
|
|
319
|
+
// resolver sure the package has no `exports`, so the load after the install would fail too. Load it once it's there.
|
|
320
|
+
const present = existsSync(join(root, 'node_modules', packageOf(pkg), 'package.json'))
|
|
321
|
+
if (present && (named || listed((await loadConfig(root)).config, pkg)))
|
|
322
|
+
return { ok: true, already: true, package: pkg, config, actions: [] }
|
|
323
|
+
|
|
324
|
+
const home = packageOf(pkg)
|
|
325
|
+
|
|
326
|
+
const actions = []
|
|
327
|
+
const [manager, verb] = installer(root)
|
|
328
|
+
if (install) {
|
|
329
|
+
actions.push(`install ${home} with ${manager}`)
|
|
330
|
+
if (!dryRun) installSpecs(root, manager, verb, [home])
|
|
331
|
+
}
|
|
332
|
+
const setup = await setupOf(root, pkg)
|
|
333
|
+
const plan = setup && (await planSetup(root, setup))
|
|
334
|
+
const next = named
|
|
335
|
+
? text
|
|
336
|
+
: /\.(json|ya?ml)$/.test(file)
|
|
337
|
+
? addToData(file, text, pkg)
|
|
338
|
+
: addToTs(root, file, text, pkg)
|
|
339
|
+
if (!named) actions.push(`add ${pkg} to ${config}`)
|
|
340
|
+
if (dryRun)
|
|
341
|
+
return {
|
|
342
|
+
ok: true,
|
|
343
|
+
package: pkg,
|
|
344
|
+
config,
|
|
345
|
+
actions: [...actions, ...(plan ? setupActions(plan) : [])],
|
|
346
|
+
dryRun: true,
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return finishAdd({ root, file, next, text, config, pkg, install, actions, plan, setup })
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function finishAdd({ root, file, next, text, config, pkg, install, actions, plan, setup }) {
|
|
353
|
+
writeFileSync(file, next)
|
|
354
|
+
const after = await loadConfig(root)
|
|
355
|
+
const failed = after.diagnostics.filter((d) => d.severity === 'error')
|
|
356
|
+
if (failed.length) {
|
|
357
|
+
writeFileSync(file, text)
|
|
358
|
+
throw refused(
|
|
359
|
+
`${config} doesn't load with ${pkg} in it${install ? ', though the package installed' : ''}, so it's back as it was: ${failed[0].code} ${failed[0].why}`,
|
|
360
|
+
)
|
|
361
|
+
}
|
|
362
|
+
sync(root, after)
|
|
363
|
+
actions.push('regenerate .kerf/slots')
|
|
364
|
+
if (plan) {
|
|
365
|
+
for (const other of setup.with ?? [])
|
|
366
|
+
actions.push(...(await addCommand(root, other, { install })).actions)
|
|
367
|
+
applySetup(root, plan)
|
|
368
|
+
actions.push(...setupActions(plan))
|
|
369
|
+
}
|
|
370
|
+
// Never approved here: installing a plugin isn't having read what it asks for.
|
|
371
|
+
const trust = trustStatus(root, after).plugins.find((p) => p.name === pkg)
|
|
372
|
+
// Only the generated file: a scaffold's short one is the app's own until `kerf agents-md` is asked for.
|
|
373
|
+
if (
|
|
374
|
+
existsSync(join(root, 'AGENTS.md')) &&
|
|
375
|
+
readFileSync(join(root, 'AGENTS.md'), 'utf8').includes('Generated by `kerf agents-md`')
|
|
376
|
+
) {
|
|
377
|
+
await writeAgentsMd(root)
|
|
378
|
+
actions.push('regenerate AGENTS.md')
|
|
379
|
+
}
|
|
380
|
+
actions.push(...(after.contributions?.find((c) => c.name === pkg)?.manifest?.notes ?? []))
|
|
381
|
+
if (trust?.blocked)
|
|
382
|
+
actions.push(
|
|
383
|
+
`${pkg} asks for ${[...trust.added, ...trust.hidden.map((n) => `${n} (undeclared)`)].join(', ') || 'a code change'}; \`kerf check\` stops until you run \`kerf plugins approve ${pkg}\``,
|
|
384
|
+
)
|
|
385
|
+
return {
|
|
386
|
+
ok: true,
|
|
387
|
+
package: pkg,
|
|
388
|
+
config,
|
|
389
|
+
actions,
|
|
390
|
+
...(trust?.blocked && { approve: { added: trust.added, undeclared: trust.hidden } }),
|
|
391
|
+
}
|
|
392
|
+
}
|