create-knit 0.0.0-stage → 0.3.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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -2
  3. package/index.mjs +248 -0
  4. package/package.json +32 -3
  5. package/template/base/.claude/skills/knit-add-api/SKILL.md +41 -0
  6. package/template/base/.claude/skills/knit-add-model/SKILL.md +31 -0
  7. package/template/base/.cursor/mcp.json +24 -0
  8. package/template/base/.mcp.json +25 -0
  9. package/template/base/.vscode/mcp.json +25 -0
  10. package/template/base/AGENTS.md +76 -0
  11. package/template/base/CLAUDE.md +9 -0
  12. package/template/base/_gitignore +13 -0
  13. package/template/base/apps/web/.env.example +124 -0
  14. package/template/base/apps/web/app/app.vue +7 -0
  15. package/template/base/apps/web/app/pages/index.vue +20 -0
  16. package/template/base/apps/web/tsconfig.json +9 -0
  17. package/template/base/docker/.env.production.example +21 -0
  18. package/template/base/docker/Dockerfile +64 -0
  19. package/template/base/docker/Dockerfile.dockerignore +16 -0
  20. package/template/base/docker/dev.Dockerfile +10 -0
  21. package/template/base/docker/dev.Dockerfile.dockerignore +2 -0
  22. package/template/base/docker/docker-compose.prod.yml +44 -0
  23. package/template/base/docker-compose.yml +71 -0
  24. package/template/examples/apps/web/app/pages/platform.vue +94 -0
  25. package/template/examples/apps/web/server/api/demo/flash.post.ts +5 -0
  26. package/template/examples/layers/example-blog/admin.ts +126 -0
  27. package/template/examples/layers/example-blog/app/pages/blog/[slug].vue +169 -0
  28. package/template/examples/layers/example-blog/app/pages/blog/index.vue +73 -0
  29. package/template/examples/layers/example-blog/app/pages/blog/stats.vue +33 -0
  30. package/template/examples/layers/example-blog/commands/publishpost.ts +23 -0
  31. package/template/examples/layers/example-blog/i18n/locales/de.json +140 -0
  32. package/template/examples/layers/example-blog/i18n/locales/en.json +33 -0
  33. package/template/examples/layers/example-blog/i18n/locales/es.json +140 -0
  34. package/template/examples/layers/example-blog/nuxt.config.ts +9 -0
  35. package/template/examples/layers/example-blog/package.json +18 -0
  36. package/template/examples/layers/example-blog/server/api/blog/posts/[slug].get.ts +15 -0
  37. package/template/examples/layers/example-blog/server/api/blog/posts.get.ts +14 -0
  38. package/template/examples/layers/example-blog/server/api/blog/word-count.post.ts +23 -0
  39. package/template/examples/layers/example-blog/server/channels/comments.ts +39 -0
  40. package/template/examples/layers/example-blog/server/database/schema.ts +160 -0
  41. package/template/examples/layers/example-blog/server/database/seed.ts +24 -0
  42. package/template/examples/layers/example-blog/server/feeds/blog.ts +26 -0
  43. package/template/examples/layers/example-blog/server/resources/comments.ts +78 -0
  44. package/template/examples/layers/example-blog/server/resources/posts.ts +25 -0
  45. package/template/examples/layers/example-blog/server/routes/blog/atom.xml.ts +4 -0
  46. package/template/examples/layers/example-blog/server/routes/blog/feed.xml.ts +4 -0
  47. package/template/examples/layers/example-blog/server/sitemaps/blog.ts +14 -0
  48. package/template/examples/layers/example-blog/server/tasks/blog.ts +49 -0
  49. package/template/examples/layers/example-blog/test/blog.test.ts +46 -0
  50. package/template/examples/layers/example-blog/test/i18n.test.ts +27 -0
  51. package/template/examples/layers/example-blog/tsconfig.json +9 -0
  52. package/template/examples/layers/example-dashboard/app/pages/dashboard.vue +67 -0
  53. package/template/examples/layers/example-dashboard/i18n/locales/de.json +12 -0
  54. package/template/examples/layers/example-dashboard/i18n/locales/en.json +12 -0
  55. package/template/examples/layers/example-dashboard/i18n/locales/es.json +12 -0
  56. package/template/examples/layers/example-dashboard/nuxt.config.ts +12 -0
  57. package/template/examples/layers/example-dashboard/package.json +16 -0
  58. package/template/examples/layers/example-dashboard/tsconfig.json +9 -0
  59. package/template/versions.json +13 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Knit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # create-knit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Creates a [Knit](https://github.com/3ig/knit) project:
4
+
5
+ ```bash
6
+ pnpm create knit my-app # asks whether to include the example apps
7
+ pnpm create knit my-app --no-examples # start empty
8
+ npm create knit@latest my-app # also works; the project itself uses pnpm
9
+ ```
10
+
11
+ It writes the project, runs `pnpm install` and creates the initial migration (`--no-install` skips both). Then:
12
+
13
+ ```bash
14
+ cd my-app
15
+ pnpm dev # open http://localhost:3000/admin
16
+ ```
17
+
18
+ License: MIT
package/index.mjs ADDED
@@ -0,0 +1,248 @@
1
+ #!/usr/bin/env node
2
+ // `pnpm create knit [dir]` (or `npm create knit@latest`): scaffolds a Knit project.
3
+ //
4
+ // pnpm create knit my-app # asks whether to include the example apps
5
+ // pnpm create knit my-app --no-examples # an empty project: core + your first app later
6
+ // pnpm create knit my-app --examples --no-install
7
+ //
8
+ // Plain Node, no dependencies, so it starts instantly.
9
+ import { spawnSync } from 'node:child_process'
10
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
+ import { basename, dirname, join, relative, resolve } from 'node:path'
12
+ import { createInterface } from 'node:readline/promises'
13
+ import { fileURLToPath } from 'node:url'
14
+
15
+ const template = join(dirname(fileURLToPath(import.meta.url)), 'template')
16
+ const versions = JSON.parse(readFileSync(join(template, 'versions.json'), 'utf8'))
17
+ const color = (code, text) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text)
18
+ const bold = text => color('1', text)
19
+ const dim = text => color('2', text)
20
+
21
+ function usage() {
22
+ return `Usage: pnpm create knit [dir] [--examples | --no-examples] [--no-install]
23
+
24
+ dir Folder to create (default: asked, or "my-knit-app")
25
+ --examples Include the example blog and dashboard apps (default when asked: yes)
26
+ --no-examples Start empty: just the core layer, ready for \`pnpm manage startapp\`
27
+ --no-install Only write the files (skip \`pnpm install\` and the initial migration)`
28
+ }
29
+
30
+ function parseArgs(argv) {
31
+ const opts = { dir: undefined, examples: undefined, install: true }
32
+ for (const arg of argv) {
33
+ if (arg === '--examples') opts.examples = true
34
+ else if (arg === '--no-examples') opts.examples = false
35
+ else if (arg === '--no-install') opts.install = false
36
+ else if (arg === '-h' || arg === '--help') {
37
+ console.log(usage())
38
+ process.exit(0)
39
+ }
40
+ else if (arg.startsWith('-')) throw new Error(`Unknown option ${arg}\n\n${usage()}`)
41
+ else if (!opts.dir) opts.dir = arg
42
+ else throw new Error(`Unexpected argument ${arg}\n\n${usage()}`)
43
+ }
44
+ return opts
45
+ }
46
+
47
+ async function ask(rl, question, fallback) {
48
+ if (!rl) return fallback
49
+ const answer = (await rl.question(`${question} ${dim(`(${fallback})`)} `)).trim()
50
+ return answer || fallback
51
+ }
52
+
53
+ /** `KNIT_CREATE_TARBALLS=<dir>`: depend on local `pnpm pack` output instead of npm (for testing). */
54
+ function localPackages() {
55
+ const dir = process.env.KNIT_CREATE_TARBALLS
56
+ if (!dir) return undefined
57
+ const files = readdirSync(dir)
58
+ const find = prefix => {
59
+ const file = files.find(f => f.startsWith(prefix) && f.endsWith('.tgz'))
60
+ if (!file) throw new Error(`KNIT_CREATE_TARBALLS: no ${prefix}*.tgz in ${dir}`)
61
+ return `file:${resolve(dir, file)}`
62
+ }
63
+ return { core: find('knit-framework-core-'), cli: find('knit-framework-cli-') }
64
+ }
65
+
66
+ const json = value => `${JSON.stringify(value, null, 2)}\n`
67
+
68
+ function writeProject(target, name, examples) {
69
+ cpSync(join(template, 'base'), target, { recursive: true })
70
+ renameSync(join(target, '_gitignore'), join(target, '.gitignore'))
71
+ if (examples) cpSync(join(template, 'examples'), target, { recursive: true })
72
+
73
+ const local = localPackages()
74
+ const knit = local ? undefined : `^${versions.knit}`
75
+ const core = local?.core ?? knit
76
+ const cli = local?.cli ?? knit
77
+
78
+ writeFileSync(join(target, 'package.json'), json({
79
+ name,
80
+ version: '0.0.1',
81
+ private: true,
82
+ type: 'module',
83
+ packageManager: versions.packageManager,
84
+ engines: { node: '>=22' },
85
+ scripts: {
86
+ manage: 'knit',
87
+ dev: 'pnpm --filter web dev',
88
+ build: 'pnpm --filter web build',
89
+ typecheck: 'pnpm -r typecheck',
90
+ check: 'knit check',
91
+ test: 'knit test',
92
+ services: 'docker compose up -d',
93
+ 'services:down': 'docker compose down',
94
+ },
95
+ devDependencies: {
96
+ '@knit-framework/cli': cli,
97
+ '@nuxt/test-utils': versions.testUtils,
98
+ '@types/node': versions.typesNode,
99
+ '@types/pg': versions.typesPg,
100
+ pg: versions.pg,
101
+ typescript: versions.typescript,
102
+ vitest: versions.vitest,
103
+ },
104
+ // Read by the `knit` CLI and the core layer (Django: settings).
105
+ framework: { app: 'apps/web', layersDir: 'layers', migrationsDir: 'server/database/migrations' },
106
+ }))
107
+
108
+ writeFileSync(join(target, 'pnpm-workspace.yaml'), [
109
+ 'packages:',
110
+ ' - layers/*',
111
+ ' - apps/*',
112
+ '',
113
+ 'allowBuilds:',
114
+ ' esbuild: true',
115
+ ' vue-demi: true',
116
+ " '@parcel/watcher': true",
117
+ " '@tailwindcss/oxide': true",
118
+ ' unrs-resolver: true',
119
+ ...(local ? ['', '# Local @knit-framework packages (KNIT_CREATE_TARBALLS)', 'overrides:', ` '@knit-framework/core': '${local.core}'`, ` '@knit-framework/cli': '${local.cli}'`] : []),
120
+ '',
121
+ ].join('\n'))
122
+
123
+ const exampleLayers = examples ? ['example-blog', 'example-dashboard'] : []
124
+ writeFileSync(join(target, 'apps/web/package.json'), json({
125
+ name: 'web',
126
+ version: '0.0.1',
127
+ private: true,
128
+ type: 'module',
129
+ scripts: { dev: 'nuxt dev', build: 'nuxt build', preview: 'nuxt preview', postinstall: 'nuxt prepare', typecheck: 'nuxt typecheck' },
130
+ dependencies: {
131
+ '@knit-framework/core': core,
132
+ ...Object.fromEntries(exampleLayers.map(l => [l, 'workspace:*'])),
133
+ nuxt: versions.nuxt,
134
+ },
135
+ devDependencies: { typescript: versions.typescript, 'vue-tsc': versions.vueTsc },
136
+ }))
137
+ writeFileSync(join(target, 'apps/web/nuxt.config.ts'), [
138
+ 'export default defineNuxtConfig({',
139
+ ' // Installed apps (Django: INSTALLED_APPS). `pnpm manage startapp <name>` adds new ones here.',
140
+ ` extends: [${['@knit-framework/core', ...exampleLayers.map(l => `../../layers/${l}`)].map(e => `'${e}'`).join(', ')}],`,
141
+ " compatibilityDate: '2026-11-01',",
142
+ ' devtools: { enabled: true },',
143
+ '})',
144
+ '',
145
+ ].join('\n'))
146
+ for (const layer of exampleLayers) {
147
+ const path = join(target, 'layers', layer, 'package.json')
148
+ const pkg = JSON.parse(readFileSync(path, 'utf8'))
149
+ pkg.dependencies['@knit-framework/core'] = core
150
+ writeFileSync(path, json(pkg))
151
+ }
152
+ mkdirSync(join(target, 'layers'), { recursive: true })
153
+ writeFileSync(join(target, 'layers/.gitkeep'), '')
154
+
155
+ writeFileSync(join(target, 'vitest.config.ts'), [
156
+ "import { defineConfig } from 'vitest/config'",
157
+ '',
158
+ '// `pnpm test` (= `knit test`): unit tests of your apps, and e2e tests that build apps/web.',
159
+ 'export default defineConfig({',
160
+ ' test: {',
161
+ ' projects: [',
162
+ " { test: { name: 'unit', environment: 'node', include: ['layers/*/test/**/*.test.ts', 'apps/*/test/unit/**/*.test.ts'] } },",
163
+ " { test: { name: 'e2e', environment: 'node', include: ['apps/*/test/e2e/**/*.test.ts'], testTimeout: 60_000, hookTimeout: 300_000, fileParallelism: false } },",
164
+ ' ],',
165
+ ' },',
166
+ '})',
167
+ '',
168
+ ].join('\n'))
169
+
170
+ writeFileSync(join(target, 'README.md'), [
171
+ `# ${name}`,
172
+ '',
173
+ `A [Knit](https://github.com/3ig/knit) project.${examples ? ' It includes the example apps in `layers/example-*` (see "Remove the examples" below).' : ''}`,
174
+ '',
175
+ '```bash',
176
+ 'pnpm dev # http://localhost:3000/admin',
177
+ 'pnpm manage startapp shop # a new app in layers/shop',
178
+ 'pnpm manage makemigrations && pnpm manage migrate',
179
+ 'pnpm manage describe # everything this project contains',
180
+ '```',
181
+ '',
182
+ '- Guides: `node_modules/@knit-framework/core/docs/` (start with `getting-started.md`), or online at https://github.com/3ig/knit/tree/main/docs',
183
+ '- Agents: see `AGENTS.md`; the `knit` MCP server is configured in `.mcp.json`.',
184
+ '- Upgrading Knit: https://github.com/3ig/knit/blob/main/docs/upgrading.md',
185
+ ...(examples
186
+ ? [
187
+ '',
188
+ '## Remove the examples',
189
+ '',
190
+ '1. Delete `layers/example-blog` and `layers/example-dashboard`, `apps/web/app/pages/platform.vue` and `apps/web/server/api/demo/`.',
191
+ '2. Remove them from `extends` in `apps/web/nuxt.config.ts` and from `dependencies` in `apps/web/package.json`.',
192
+ '3. `pnpm install`, then `pnpm manage makemigrations --name remove_examples && pnpm manage migrate` (drops their tables).',
193
+ ]
194
+ : []),
195
+ '',
196
+ ].join('\n'))
197
+ }
198
+
199
+ function run(command, args, cwd) {
200
+ console.log(dim(`$ ${command} ${args.join(' ')}`))
201
+ const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' })
202
+ return result.status === 0
203
+ }
204
+
205
+ async function main() {
206
+ const opts = parseArgs(process.argv.slice(2))
207
+ const interactive = process.stdin.isTTY && process.stdout.isTTY
208
+ const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : undefined
209
+ console.log(`\n${bold('Knit')} ${dim(`v${versions.knit}`)}: the batteries-included TypeScript framework\n`)
210
+
211
+ try {
212
+ const dir = opts.dir ?? await ask(rl, 'Project folder?', 'my-knit-app')
213
+ const target = resolve(dir)
214
+ if (existsSync(target) && readdirSync(target).length) throw new Error(`${dir} already exists and is not empty.`)
215
+ const examples = opts.examples ?? (rl ? !/^n/i.test(await ask(rl, 'Include the example apps (blog, dashboard)?', 'Y/n')) : true)
216
+ rl?.close()
217
+
218
+ const name = basename(target).toLowerCase().replace(/[^a-z0-9._-]+/g, '-') || 'knit-app'
219
+ writeProject(target, name, examples)
220
+ console.log(`Created ${bold(relative(process.cwd(), target) || '.')}${examples ? ' with the example apps' : ''}.`)
221
+
222
+ const cd = relative(process.cwd(), target)
223
+ if (opts.install) {
224
+ const hasPnpm = spawnSync('pnpm', ['--version'], { stdio: 'ignore', shell: process.platform === 'win32' }).status === 0
225
+ if (!hasPnpm) {
226
+ console.log(`\npnpm is required (Knit projects are pnpm workspaces): ${bold('npm install -g pnpm')} or ${bold('corepack enable')}, then:`)
227
+ console.log(` cd ${cd} && pnpm install && pnpm manage makemigrations --name initial`)
228
+ return
229
+ }
230
+ if (!run('pnpm', ['install'], target)) throw new Error('pnpm install failed (see above).')
231
+ if (!run('pnpm', ['manage', 'makemigrations', '--name', 'initial'], target)) throw new Error('Creating the initial migration failed (see above).')
232
+ }
233
+
234
+ console.log(`\n${bold('Next:')}`)
235
+ if (cd) console.log(` cd ${cd}`)
236
+ if (!opts.install) console.log(' pnpm install && pnpm manage makemigrations --name initial')
237
+ console.log(' pnpm dev # then open http://localhost:3000/admin to create your admin')
238
+ console.log(' pnpm manage startapp <name> # your first app\n')
239
+ }
240
+ finally {
241
+ rl?.close()
242
+ }
243
+ }
244
+
245
+ main().catch((error) => {
246
+ console.error(`\n${color('31', 'Error:')} ${error instanceof Error ? error.message : String(error)}`)
247
+ process.exit(1)
248
+ })
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "create-knit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Create a Knit project: `pnpm create knit my-app` (Django-inspired, batteries-included TypeScript framework on Nuxt).",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/3ig/knit.git",
9
+ "directory": "packages/create-knit"
10
+ },
11
+ "homepage": "https://github.com/3ig/knit#readme",
12
+ "bugs": "https://github.com/3ig/knit/issues",
13
+ "keywords": [
14
+ "knit",
15
+ "create",
16
+ "scaffold",
17
+ "nuxt",
18
+ "django",
19
+ "framework"
20
+ ],
21
+ "type": "module",
22
+ "bin": {
23
+ "create-knit": "./index.mjs"
24
+ },
25
+ "files": [
26
+ "index.mjs",
27
+ "template"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22"
31
+ },
32
+ "scripts": {
33
+ "build:template": "node build-template.mjs"
34
+ }
6
35
  }
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: knit-add-api
3
+ description: Expose a Knit model as a public REST API with permissions (defineResource) and build forms or pages on it (useResource, KnitModelForm). Use when asked for an API endpoint, a public form, a CRUD page, or "let users create/edit X" in a Knit project.
4
+ ---
5
+
6
+ # Add a public API (resource) and forms
7
+
8
+ 1. **Look first.**
9
+ - `knit_describe` with `section: "resources"` lists the existing APIs and their permission rules.
10
+ - `knit_model` with the table describes its fields.
11
+ 2. **Create `layers/<app>/server/resources/<name>.ts`** and *export* the resource:
12
+
13
+ ```ts
14
+ import { defineResource, isOwner } from '@knit-framework/core/resources'
15
+ import { product } from '../database/schema'
16
+
17
+ export default defineResource(product, {
18
+ slug: 'products',
19
+ fields: ['id', 'name', 'price', 'createdById', 'createdAt'], // always list fields for public APIs
20
+ readonlyFields: ['createdById', 'createdAt'],
21
+ searchFields: ['name'],
22
+ filterFields: ['price'],
23
+ permissions: { list: 'public', retrieve: 'public', create: 'authenticated', update: [isOwner('createdById'), 'shop.change_product'], delete: 'shop.delete_product' },
24
+ beforeCreate: (data, ctx) => ({ ...data, createdById: ctx.user!.id }), // server-set values go here
25
+ })
26
+ ```
27
+
28
+ - Writes are denied unless a rule allows them.
29
+ - `scope(ctx)` limits which rows each user can see.
30
+ - Foreign-key choices need a resource for the *target* table.
31
+ 3. **Restart `pnpm dev`** (new resource files are discovered at start).
32
+ 4. **Try it.**
33
+ - `GET /api/r/products` returns `{ items, total, page, perPage, pages }`.
34
+ - `/api/r/docs` and `/api/r/openapi.json` document it.
35
+ - With curl, cookie-carrying writes need no `Origin` header, or the server's own (CSRF guard).
36
+ 5. **UI:** `useResource<typeof product>('products').list({ … })` gives typed lists. `<KnitModelForm resource="products" :fields="['name', 'price']" @saved="refresh" />` gives a form with validation errors per field.
37
+ 6. **Verify.**
38
+ - `knit_check` / `pnpm -s manage check --json` and `pnpm typecheck`.
39
+ - An e2e test with `createTestClient` from `@knit-framework/core/testing` covering one allowed and one denied write.
40
+
41
+ Guide: `knit_docs` topic `resources` (or `node_modules/@knit-framework/core/docs/resources.md`).
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: knit-add-model
3
+ description: Add or change a model (Drizzle table) in a Knit app, end to end - schema, relations, migration, admin registration and verification. Use when asked to add a table, field or model, or to change one, in a Knit project.
4
+ ---
5
+
6
+ # Add or change a Knit model
7
+
8
+ 1. **Look first.** Call the `knit` MCP tool `knit_describe` with `section: "models"` (or run `pnpm -s manage describe --json`). Note the app's label and the existing tables, and that relations are named for `with:`.
9
+ 2. **Pick the app.**
10
+ - The layer is `layers/<app>/`.
11
+ - No suitable app yet: run `pnpm manage startapp <name>`, then restart `pnpm dev`.
12
+ - The table name must be `<label>_<model>`, the label being `knit.app` in the layer's `nuxt.config.ts` or the layer name in snake_case.
13
+ 3. **Edit `layers/<app>/server/database/schema.ts`.**
14
+ - Use explicit snake_case column names, e.g. `createdAt: timestamp('created_at', …)`.
15
+ - Give the table exactly one single-column primary key.
16
+ - Point foreign keys at imported tables (`user` from `@knit-framework/core/schema`).
17
+ - Add `relations()` for anything you'll query with `with:`.
18
+ - Model behavior goes at the bottom of the file: `defineModelMeta(table, { ordering, validators, clean })` and signal receivers. These must use the `db` they are given.
19
+ 4. **Preview, then write the migration.**
20
+ - Preview the SQL with `pnpm manage makemigrations --dry-run` (or the MCP tool `knit_pending_migration_sql`).
21
+ - Then run `pnpm manage makemigrations --name <slug>`.
22
+ - If it says drizzle-kit must ask about a rename, split the change: add the new column, migrate, then drop the old one.
23
+ 5. **Apply it** with `pnpm manage migrate`. This works while `pnpm dev` runs, and `pnpm dev` also applies migrations when it starts.
24
+ 6. **Admin:** register the table in `layers/<app>/admin.ts` with `registerAdminModel(table, { listDisplay, searchFields, listFilter, ordering, readonlyFields })`, using field *keys* (camelCase JS names). Restart `pnpm dev` if `admin.ts` is new.
25
+ 7. **Verify.**
26
+ - `pnpm -s manage check --json` (MCP: `knit_check`) has no errors. It catches unknown admin fields, missing prefixes and clashes.
27
+ - `pnpm typecheck` passes.
28
+ - Then open `/admin` and create a record, including one that fails validation.
29
+ 8. **Writes in code** go through `useModel(table)`, not raw `useDB().insert`, so validators and signals run.
30
+
31
+ Guides: `knit_docs` topics `models`, `admin`, `cli` (or `node_modules/@knit-framework/core/docs/models.md`, `node_modules/@knit-framework/core/docs/admin.md`).
@@ -0,0 +1,24 @@
1
+ {
2
+ "mcpServers": {
3
+ "knit": {
4
+ "command": "pnpm",
5
+ "args": [
6
+ "-s",
7
+ "manage",
8
+ "mcp"
9
+ ]
10
+ },
11
+ "nuxt": {
12
+ "type": "http",
13
+ "url": "https://nuxt.com/mcp"
14
+ },
15
+ "nuxt-ui": {
16
+ "type": "http",
17
+ "url": "https://ui.nuxt.com/mcp"
18
+ },
19
+ "better-auth": {
20
+ "type": "http",
21
+ "url": "https://mcp.better-auth.com/mcp"
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "mcpServers": {
3
+ "knit": {
4
+ "type": "stdio",
5
+ "command": "pnpm",
6
+ "args": [
7
+ "-s",
8
+ "manage",
9
+ "mcp"
10
+ ]
11
+ },
12
+ "nuxt": {
13
+ "type": "http",
14
+ "url": "https://nuxt.com/mcp"
15
+ },
16
+ "nuxt-ui": {
17
+ "type": "http",
18
+ "url": "https://ui.nuxt.com/mcp"
19
+ },
20
+ "better-auth": {
21
+ "type": "http",
22
+ "url": "https://mcp.better-auth.com/mcp"
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "servers": {
3
+ "knit": {
4
+ "type": "stdio",
5
+ "command": "pnpm",
6
+ "args": [
7
+ "-s",
8
+ "manage",
9
+ "mcp"
10
+ ]
11
+ },
12
+ "nuxt": {
13
+ "type": "http",
14
+ "url": "https://nuxt.com/mcp"
15
+ },
16
+ "nuxt-ui": {
17
+ "type": "http",
18
+ "url": "https://ui.nuxt.com/mcp"
19
+ },
20
+ "better-auth": {
21
+ "type": "http",
22
+ "url": "https://mcp.better-auth.com/mcp"
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,76 @@
1
+ # AGENTS.md: building an app with Knit
2
+
3
+ Knit is a Django-inspired TypeScript framework on Nuxt 4: **layers are apps**, **Drizzle tables are models**, the **admin is generated**, and **`pnpm manage`** is the CLI (Django's `manage.py`). Humans read [`README.md`](README.md) and the guides in [`node_modules/@knit-framework/core/docs/`](node_modules/@knit-framework/core/docs/README.md).
4
+
5
+ Curious how Knit works inside? Read [`node_modules/@knit-framework/core/AGENTS.md`](node_modules/@knit-framework/core/AGENTS.md).
6
+
7
+ ## 1. Learn the project first
8
+
9
+ Don't read files to find out what exists. Ask Knit:
10
+
11
+ - **MCP:** the `knit` server (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) has read-only tools:
12
+ - `knit_describe`: apps, models with columns, foreign keys and `with:` relations, admin, resources and their permission rules, tasks, channels, pages, API routes, commands, migrations. Pass `section` to get one part.
13
+ - `knit_model`: one model.
14
+ - `knit_check`: run after changes.
15
+ - `knit_migrations`, `knit_pending_migration_sql`, `knit_sqlmigrate`.
16
+ - `knit_docs`: the guides, e.g. `{ "topic": "models" }`.
17
+ - **CLI:** `pnpm -s manage describe --json` (the same document), `pnpm -s manage check --json`, `pnpm -s manage showmigrations --json`, `pnpm -s manage runtask --json`. `-s` keeps pnpm's banner out of the JSON.
18
+ - **Library docs:** the `nuxt`, `nuxt-ui` and `better-auth` MCP servers. Use them instead of guessing APIs.
19
+
20
+ ## 2. Where code goes
21
+
22
+ | You want | Put it in |
23
+ | --- | --- |
24
+ | A new app | `pnpm manage startapp <name>` → `layers/<name>/` (adds it to `apps/web/nuxt.config.ts` `extends`) |
25
+ | Models | `layers/<app>/server/database/schema.ts` (tables named `<app>_<model>`, `relations()` next to them) |
26
+ | Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })` |
27
+ | A public REST API + forms | `layers/<app>/server/resources/<name>.ts` → `export default defineResource(table, { permissions, … })`; `<KnitModelForm resource="…">` in pages |
28
+ | Pages / components | `layers/<app>/app/pages/**`, `app/components/**` (Nuxt conventions) |
29
+ | Server endpoints | `layers/<app>/server/api/**` (`useDB()`, `tables`, `useModel()` are auto-imported) |
30
+ | Background / scheduled work | `layers/<app>/server/tasks/*.ts` → `defineTask` from `@knit-framework/core/tasks` |
31
+ | Realtime | `layers/<app>/server/channels/*.ts` → `defineChannel`; `broadcastModel` in the schema |
32
+ | CLI commands / seeds | `layers/<app>/commands/<name>.ts` (`defineManageCommand`), `server/database/seed.ts` (`defineSeed`) |
33
+ | Translations | `layers/<app>/i18n/locales/{en,de,es}.json` |
34
+ | Settings | `apps/web/nuxt.config.ts`, env vars in `apps/web/.env` (see `apps/web/.env.example`) |
35
+
36
+ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component or translation with the same name in your app wins). Never edit generated files: `.nuxt/**`, `apps/web/.framework/**`, and the migrations in `apps/web/server/database/migrations/**` (regenerate them instead).
37
+
38
+ ## 3. Conventions
39
+
40
+ - **App label:** `knit: { app: 'shop' }` in the layer's `nuxt.config.ts` (default: the layer name in snake_case). Every table is `<label>_<model>`, and permissions are `<label>.<view|add|change|delete>_<model>`. Knit refuses to start (and `makemigrations` refuses to write) when a table lacks the prefix or two apps clash.
41
+ - **Writes go through `useModel(table)`** (validators, `clean()`, signals, one transaction). Raw `useDB()` is for reads and bulk work. In schema files, signal receivers and `clean()` must use the `db` they are given.
42
+ - **Cross-app references** import the table: `import { user } from '@knit-framework/core/schema'`.
43
+ - **Permissions on the server:** `requirePermission(event, 'shop.change_product')`. In the UI, `useAuth().can(perm)` is display-only.
44
+ - **Resources default to deny for writes.** List `fields` explicitly for public APIs. Server-set values (e.g. `authorId`) belong in `beforeCreate`.
45
+ - **Files outside Nitro** (tasks, commands, seeds) don't get auto-imports: import from `@knit-framework/core/*` and use the `db`/`ctx.db` you are given.
46
+ - **UI strings** go through `t()`; a literal `{`, `}`, `@` or `|` in a locale message breaks the whole language.
47
+ - **Logging:** `useLogger('scope')` in server code, never `console.*`.
48
+
49
+ ## 4. Change → verify loop
50
+
51
+ ```bash
52
+ pnpm -s manage check --json # schema, admin field names, layers, migrations (or MCP: knit_check)
53
+ pnpm manage makemigrations --name <slug> # after a schema change; --dry-run to preview
54
+ pnpm manage migrate # works while pnpm dev runs; pnpm dev also applies on start
55
+ pnpm typecheck # must pass
56
+ pnpm manage test --unit # fast; pnpm test runs e2e too (builds the app)
57
+ ```
58
+
59
+ - **Restart `pnpm dev`** after adding a new layer file it discovers: a schema, `admin.ts`, a resource, task, channel or locale file.
60
+ - **Without a terminal**, `makemigrations` can't answer drizzle-kit's "renamed or new?" question. Split the change: add the new column, migrate, then remove the old one.
61
+ - **PGlite is single-process.** `migrate`, `showmigrations`, `removemigration` and `check` go through a running `pnpm dev`. `shell`, `createsuperuser`, `loaddata` and similar need it stopped.
62
+ - **Undo an unapplied `makemigrations`** with `pnpm manage removemigration`.
63
+ - **Tests:** `createTestDatabase`, `defineFactory`, `createTestClient` from `@knit-framework/core/testing`; app tests in `layers/<app>/test/*.test.ts`. See `node_modules/@knit-framework/core/docs/testing.md`.
64
+ - **Admin or API changes:** sign in at `/admin` and try list, create (including a validation error), edit and delete.
65
+
66
+ ## 5. Gotchas
67
+
68
+ - **Relational queries need `relations()`.** `with: { author: true }` fails without a relation named `author`.
69
+ - **Resources** must be *exported*. `_choices` for a foreign key goes through the target table's resource (no resource, no choices).
70
+ - **Realtime channels are default-deny:** a channel without `authorize` needs a signed-in user. `broadcastModel` fires after commit, for `useModel` writes only.
71
+ - **CSRF:** cookie-carrying cross-site `POST`/`PUT`/`PATCH`/`DELETE` to `/api/**` get 403. With curl, send no `Origin` or the server's own origin. Webhooks go in `NUXT_KNIT_SECURITY_CSRF_EXEMPT`.
72
+ - **Vue's `useModel` shadows Knit's** in typechecking. In server files, import it explicitly from `@knit-framework/core/models`.
73
+ - **Two dev servers on `localhost`** share cookies across ports. Use `http://<name>.localhost:<port>`.
74
+ - **Drizzle renders columns unqualified inside `` sql`…` ``.** In correlated subqueries, write table-qualified names.
75
+
76
+ More: [`node_modules/@knit-framework/core/docs/troubleshooting.md`](node_modules/@knit-framework/core/docs/troubleshooting.md), and the error hints Knit logs next to common errors.
@@ -0,0 +1,9 @@
1
+ # CLAUDE.md
2
+
3
+ Read and follow [AGENTS.md](AGENTS.md); it is the single source of truth for building with Knit.
4
+
5
+ Project MCP servers (`.mcp.json`):
6
+ - `knit`: this project's models, resources, routes, checks, migrations and Knit's guides. Start with `knit_describe`.
7
+ - `nuxt`, `nuxt-ui`, `better-auth`: library APIs; use them instead of guessing.
8
+
9
+ Skills in `.claude/skills/`: `knit-add-model`, `knit-add-api`.
@@ -0,0 +1,13 @@
1
+ node_modules
2
+ .nuxt
3
+ .output
4
+ .data
5
+ dist
6
+ *.log
7
+ .env
8
+ .framework
9
+
10
+ # `manage inspectdb` output (review, then move into schema.ts)
11
+ .inspectdb
12
+ .env.production
13
+