create-acrylblends 0.2.2 → 0.2.3
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/README.md +2 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +22 -5
- package/dist/index.js.map +1 -1
- package/docs/framework/UPSTREAM.md +1 -1
- package/docs/framework/guides/client-modules.md +34 -0
- package/docs/framework/helpers/streaming.md +119 -0
- package/docs/framework/upstream.json +2 -2
- package/package.json +2 -2
- package/templates/chat/gitignore +5 -0
- package/templates/chat/package.json +23 -0
- package/templates/chat/src/app.ts +6 -0
- package/templates/chat/src/chat-app.ts +96 -0
- package/templates/chat/src/client/chat.tsx +115 -0
- package/templates/chat/src/client/tsconfig.json +15 -0
- package/templates/chat/src/db.ts +59 -0
- package/templates/chat/src/index.ts +22 -0
- package/templates/chat/src/llm.ts +42 -0
- package/templates/chat/src/page.tsx +38 -0
- package/templates/chat/test/chat.test.ts +153 -0
- package/templates/chat/test/server.test.ts +59 -0
- package/templates/chat/tsconfig.json +19 -0
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ It asks which template you want, creates `my-app`, and prints what to run next.
|
|
|
15
15
|
| `nodejs` | an Acryl app served with `serve()` from `acrylblends/node-server`, with a test; run with Node.js 22.19 or newer |
|
|
16
16
|
| `bun` (experimental) | the same app for Bun, with `export default app` |
|
|
17
17
|
| `notes` | a full-stack starter: accounts (scrypt, cookie session), notes in SQLite (`node:sqlite`), validated forms, search, a JSON API with a typed test client, csrf on, a test for every route |
|
|
18
|
+
| `chat` | an AI chat starter: the answer streams token by token (Server-Sent Events) from an OpenAI-compatible API (DeepSeek by default, key only from `DEEPSEEK_API_KEY`), a client component with a Stop button that also stops the request to the model, history in SQLite, tests with a mock model |
|
|
18
19
|
| `acryl-app` | a Cordis app built from plugins, with an agent that can extend it while it runs (the same app `npx acrylblends init --template agent` creates) |
|
|
19
20
|
|
|
20
21
|
Every template includes `AGENTS.md`, `CLAUDE.md` and a copy of the framework documentation in `docs/framework/`, so a coding agent working in the folder reads the API from the folder.
|
|
@@ -29,7 +30,7 @@ npm create acrylblends@latest my-app -- --template nodejs --install --pm npm
|
|
|
29
30
|
|
|
30
31
|
| Option | |
|
|
31
32
|
| --- | --- |
|
|
32
|
-
| `--template <name>` | `nodejs`, `notes`, `bun` or `acryl-app` |
|
|
33
|
+
| `--template <name>` | `nodejs`, `notes`, `chat`, `bun` or `acryl-app` |
|
|
33
34
|
| `--install` | install the dependencies after creating the app |
|
|
34
35
|
| `--pm <manager>` | `npm`, `pnpm`, `yarn` or `bun` (default: the one that ran the command) |
|
|
35
36
|
| `-y`, `--yes` | ask nothing: template `nodejs`, directory `acrylblends-app` unless given |
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const CLASS = "Acryl";
|
|
|
8
8
|
export declare const CREATE = "create-acrylblends";
|
|
9
9
|
//#endregion
|
|
10
10
|
//#region src/index.d.ts
|
|
11
|
-
export declare const TEMPLATES: readonly ["nodejs", "notes", "bun", "acryl-app"];
|
|
11
|
+
export declare const TEMPLATES: readonly ["nodejs", "notes", "chat", "bun", "acryl-app"];
|
|
12
12
|
export type Template = (typeof TEMPLATES)[number];
|
|
13
13
|
export declare const PACKAGE_MANAGERS: readonly ["npm", "pnpm", "yarn", "bun"];
|
|
14
14
|
export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
|
package/dist/index.js
CHANGED
|
@@ -49,6 +49,7 @@ function packageManagerInvocation(command, args, platform = process.platform, en
|
|
|
49
49
|
const TEMPLATES = [
|
|
50
50
|
"nodejs",
|
|
51
51
|
"notes",
|
|
52
|
+
"chat",
|
|
52
53
|
"bun",
|
|
53
54
|
"acryl-app"
|
|
54
55
|
];
|
|
@@ -66,7 +67,7 @@ Usage:
|
|
|
66
67
|
npm create ${PACKAGE}@latest [directory] [-- options]
|
|
67
68
|
|
|
68
69
|
Options:
|
|
69
|
-
--template <name> nodejs, notes, bun (experimental), acryl-app (asked when not given)
|
|
70
|
+
--template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)
|
|
70
71
|
--install install the dependencies after creating the app
|
|
71
72
|
--pm <manager> ${PACKAGE_MANAGERS.join(", ")} (default: the one that ran this command, else npm)
|
|
72
73
|
-y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app
|
|
@@ -177,12 +178,14 @@ function agentsText(template, name) {
|
|
|
177
178
|
const run = {
|
|
178
179
|
nodejs: "npm run dev",
|
|
179
180
|
notes: "npm run dev",
|
|
181
|
+
chat: "npm run dev",
|
|
180
182
|
bun: "bun run dev"
|
|
181
183
|
}[template];
|
|
182
|
-
const desktopNote = template === "nodejs" || template === "notes" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
|
|
184
|
+
const desktopNote = template === "nodejs" || template === "notes" || template === "chat" ? `\nTo run it as a desktop window: \`npx ${PACKAGE} add desktop\`, \`npm install\`, then \`npm run desktop\` (see \`docs/framework/getting-started/desktop.md\`).` : "";
|
|
183
185
|
const test = {
|
|
184
186
|
nodejs: "npm test` and `npm run check",
|
|
185
187
|
notes: "npm test` and `npm run check",
|
|
188
|
+
chat: "npm test` and `npm run check",
|
|
186
189
|
bun: "bun test` and `bun run check"
|
|
187
190
|
}[template];
|
|
188
191
|
return `# ${name}
|
|
@@ -196,7 +199,7 @@ subpath (\`'${PACKAGE}/cors'\`, \`'${PACKAGE}/validator'\`, ...). Parts marked "
|
|
|
196
199
|
|
|
197
200
|
## This app
|
|
198
201
|
|
|
199
|
-
Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : template === "notes" ? "src/notes-app.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
|
|
202
|
+
Run it with \`${run}\`. The routes are in \`${template === "bun" ? "src/index.ts" : template === "notes" ? "src/notes-app.ts" : template === "chat" ? "src/chat-app.ts" : "src/app.ts"}\`; an app is a function from \`Request\` to \`Response\`,
|
|
200
203
|
so test a route with \`await app.request('/path')\` and no server.${desktopNote}
|
|
201
204
|
|
|
202
205
|
${template === "notes" ? `
|
|
@@ -221,6 +224,19 @@ Read \`docs/framework/getting-started/deploy.md\`. In short:
|
|
|
221
224
|
- Put the SQLite file outside the code folder (\`NOTES_DB=/var/lib/notes/notes.db\`) and back it up.
|
|
222
225
|
- Behind an HTTPS reverse proxy set \`TRUST_PROXY=1\` and \`PUBLIC_ORIGIN=https://your.site\`, or the cookie is not \`Secure\` and csrf refuses form posts.
|
|
223
226
|
- \`npm test\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \`src/index.ts\`.
|
|
227
|
+
` : ""}${template === "chat" ? `
|
|
228
|
+
## Structure (a chat app: a streamed answer, history in a database)
|
|
229
|
+
|
|
230
|
+
- \`src/llm.ts\`: \`Llm\`, what the app needs from a model (messages in, pieces out, an aborted signal stops the work), and \`openAiCompatible\`, which calls an OpenAI-compatible chat completions API with \`stream: true\`. The base URL is \`DEEPSEEK_BASE_URL\` (default \`https://api.deepseek.com\`), the model \`DEEPSEEK_MODEL\` (default \`deepseek-chat\`), the key **only** the environment variable \`DEEPSEEK_API_KEY\`, read at the moment of the call: never write it to a file, a response or a log.
|
|
231
|
+
- \`src/db.ts\`: \`openDb()\` (SQLite through \`node:sqlite\`; the file is \`chat.db\` or \`$CHAT_DB\`) and \`chatStore(db)\`. The routes only call \`chatStore\`; keep SQL out of them.
|
|
232
|
+
- \`src/chat-app.ts\`: \`createApp(db, llm)\`. \`POST /api/chat\` answers Server-Sent Events: \`meta\` (the conversation id), a \`token\` per piece, then \`done\` or \`error\`. The request's signal (\`c.req.raw.signal\`) goes to the model call, so a closed tab or the Stop button stops the request to the model; what had arrived is kept.
|
|
233
|
+
- \`src/client/chat.tsx\`: the client component (own \`tsconfig.json\`, browser types): sends the message with \`fetch\`, reads the events as they arrive, shows the answer growing, and aborts on Stop. \`clientModules\` compiles it when the browser asks; \`npm run build\` compiles it once into \`dist/client\`. See \`docs/framework/guides/client-modules.md\`.
|
|
234
|
+
- \`test/chat.test.ts\` tests every route with a mock \`Llm\` (never the network); keep it that way. \`test/server.test.ts\` starts the real server and stops it with a signal.
|
|
235
|
+
- To try it with a real model: \`DEEPSEEK_API_KEY=... npm run dev\`.
|
|
236
|
+
|
|
237
|
+
## Before you ship
|
|
238
|
+
|
|
239
|
+
Read \`docs/framework/getting-started/deploy.md\`. In short: \`npm ci --omit=dev\`, \`npm run build\`, \`NODE_ENV=production npm start\`; the app listens on \`127.0.0.1\` (\`HOST=0.0.0.0\` only in a container); the SQLite file goes outside the code folder (\`CHAT_DB=/var/lib/chat/chat.db\`) and is backed up; the model key is an environment variable of the service (a root-only environment file for systemd), never a file in the repository. Anyone who can reach the app can spend your key: put it behind a login or on a private network before it is public.
|
|
224
240
|
` : ""}
|
|
225
241
|
## Things that surprise people
|
|
226
242
|
|
|
@@ -228,7 +244,7 @@ Read \`docs/framework/getting-started/deploy.md\`. In short:
|
|
|
228
244
|
- A \`json\` validator target reads the body only with a JSON \`Content-Type\`; a failure answers 400 with \`{ error, issues: [{ message, path }] }\`.
|
|
229
245
|
- \`throw new HTTPException(404, { message })\` answers an error response (plain text).
|
|
230
246
|
- \`testClient(app)\` from \`'${PACKAGE}/testing'\` types only routes chained on the \`new ${CLASS}()\` expression (\`new ${CLASS}().get(...).post(...)\`); headers such as a cookie go in the second argument of each call.
|
|
231
|
-
- **JSX:** ${template === "nodejs" || template === "notes" ? "Write pages in `.tsx` (see `src/" + (template === "notes" ? "views.tsx" : "page.tsx") + "`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
|
|
247
|
+
- **JSX:** ${template === "nodejs" || template === "notes" || template === "chat" ? "Write pages in `.tsx` (see `src/" + (template === "notes" ? "views.tsx" : "page.tsx") + "`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`." : "Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`."}
|
|
232
248
|
${template === "nodejs" ? `- **Client components** (run in the browser) live in \`src/client/\`, which has its own \`tsconfig.json\` (DOM types, no Node types); \`clientModules\` in \`src/app.ts\` compiles them when the browser asks, and \`npm run build\` compiles them once for production. See \`src/client/counter.tsx\` and \`docs/framework/guides/client-modules.md\`.\n` : ""}
|
|
233
249
|
## Before you say you are done
|
|
234
250
|
|
|
@@ -287,7 +303,7 @@ async function runCreate(argv, io = processIo()) {
|
|
|
287
303
|
const directory = options.directory ?? (ask ? (await ask(`Project directory (acrylblends-app): `)).trim() || `acrylblends-app` : `acrylblends-app`);
|
|
288
304
|
const target = resolve(io.cwd, directory);
|
|
289
305
|
const template = options.template ?? (ask ? await (async () => {
|
|
290
|
-
const answer = (await ask(`Which template do you want to use? (nodejs, notes, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
|
|
306
|
+
const answer = (await ask(`Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
|
|
291
307
|
if (!isTemplate(answer)) throw new UsageError(`unknown template "${answer}" (${TEMPLATES.join(", ")})`);
|
|
292
308
|
return answer;
|
|
293
309
|
})() : "nodejs");
|
|
@@ -321,6 +337,7 @@ async function runCreate(argv, io = processIo()) {
|
|
|
321
337
|
const start = {
|
|
322
338
|
nodejs: `${pm} run dev`,
|
|
323
339
|
notes: `${pm} run dev`,
|
|
340
|
+
chat: `${pm} run dev`,
|
|
324
341
|
bun: "bun run dev",
|
|
325
342
|
"acryl-app": `${pm} run dev`
|
|
326
343
|
}[template];
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/names.ts","../src/spawn.ts","../src/index.ts"],"sourcesContent":["/**\n * The one place this package names the framework. The templates are written with `__PACKAGE__` and `__RANGE__` (the range is stamped at create time from the framework version this package carries, see `frameworkRange`), and the text of `AGENTS.md` with\n * `__PACKAGE__`, so a rename (for example to `acryl`) is a change here and in `scripts/lib/names.mjs`, which a test keeps equal.\n */\nexport const PACKAGE = 'acrylblends'\nexport const CLASS = 'Acryl'\nexport const CREATE = 'create-acrylblends'\n","import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Invocation {\n file: string\n args: string[]\n}\n\n/**\n * How to start a package manager without the shell option (Node warns about passing args to a shell, DEP0190, and a `.cmd` shim cannot be spawned directly).\n * Off Windows the command runs as it is. On Windows npm runs as `node npm-cli.js` (the one npm is running from, else the one beside `node`); any other\n * manager goes through `cmd.exe /d /s /c <name>.cmd`, whose arguments stay an array.\n */\nexport function packageManagerInvocation(\n command: string,\n args: readonly string[],\n platform: NodeJS.Platform = process.platform,\n env: NodeJS.ProcessEnv = process.env,\n exists: (path: string) => boolean = existsSync,\n execPath: string = process.execPath,\n): Invocation {\n if (platform !== 'win32') return { file: command, args: [...args] }\n if (command === 'npm') {\n const running = env.npm_execpath\n const cli =\n running !== undefined && /npm-cli\\.c?js$/.test(running)\n ? running\n : join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')\n if (exists(cli)) return { file: execPath, args: [cli, ...args] }\n }\n return { file: env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `${command}.cmd`, ...args] }\n}\n","import { spawn } from 'node:child_process'\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { createInterface } from 'node:readline/promises'\nimport { fileURLToPath } from 'node:url'\nimport { parseArgs } from 'node:util'\nimport { CLASS, CREATE, PACKAGE } from './names'\nimport { packageManagerInvocation } from './spawn'\n\nexport { CLASS, CREATE, PACKAGE }\n\nexport const TEMPLATES = ['nodejs', 'notes', 'bun', 'acryl-app'] as const\nexport type Template = (typeof TEMPLATES)[number]\nexport const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** The version of this package. */\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app\n\nUsage:\n npm create ${PACKAGE}@latest [directory] [-- options]\n\nOptions:\n --template <name> nodejs, notes, bun (experimental), acryl-app (asked when not given)\n --install install the dependencies after creating the app\n --pm <manager> ${PACKAGE_MANAGERS.join(', ')} (default: the one that ran this command, else npm)\n -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app\n -h, --help show this help\n -v, --version show the version\n`\n\n/** A command line mistake. The command prints it with the help text and exits 2. */\nexport class UsageError extends Error {\n override name = 'UsageError'\n}\n\nexport interface Io {\n stdout: { write(text: string): unknown }\n stderr: { write(text: string): unknown }\n cwd: string\n env: Record<string, string | undefined>\n /** Ask one question; `undefined` when there is no terminal to ask on. */\n ask: ((question: string) => Promise<string>) | undefined\n /** Run a program, showing its output; resolves to the exit code. */\n run(command: string, args: string[], cwd: string): Promise<number>\n}\n\nexport function processIo(): Io {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: process.cwd(),\n env: process.env,\n ask: interactive\n ? async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await rl.question(question)\n } finally {\n rl.close()\n }\n }\n : undefined,\n run: (command, args, cwd) =>\n new Promise((done) => {\n const invocation = packageManagerInvocation(command, args)\n const child = spawn(invocation.file, invocation.args, { cwd, stdio: 'inherit' })\n child.on('error', () => done(1))\n child.on('exit', (code) => done(code ?? 1))\n }),\n }\n}\n\nexport interface CreateOptions {\n directory: string | undefined\n template: Template | undefined\n install: boolean\n pm: PackageManager | undefined\n yes: boolean\n}\n\nexport function isTemplate(value: string): value is Template {\n return (TEMPLATES as readonly string[]).includes(value)\n}\n\nexport function parseCreateOptions(argv: readonly string[]): CreateOptions {\n let parsed: ReturnType<typeof parse>\n try {\n parsed = parse(argv)\n } catch (error) {\n throw new UsageError((error as Error).message)\n }\n const { values, positionals } = parsed\n if (positionals.length > 1) throw new UsageError('takes at most one directory')\n if (values.template !== undefined && !isTemplate(values.template))\n throw new UsageError(`unknown template \"${values.template}\" (${TEMPLATES.join(', ')})`)\n if (values.pm !== undefined && !(PACKAGE_MANAGERS as readonly string[]).includes(values.pm))\n throw new UsageError(`unknown package manager \"${values.pm}\" (${PACKAGE_MANAGERS.join(', ')})`)\n return {\n directory: positionals[0],\n template: values.template as Template | undefined,\n install: values.install === true,\n pm: values.pm as PackageManager | undefined,\n yes: values.yes === true,\n }\n}\n\nconst parse = (argv: readonly string[]) =>\n parseArgs({\n args: [...argv],\n allowPositionals: true,\n strict: true,\n options: {\n template: { type: 'string' },\n install: { type: 'boolean' },\n pm: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n },\n })\n\n/** A valid package name from a directory name: lower case letters, digits and dashes. */\nexport function nameFrom(directory: string): string {\n const name = basename(resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/g, '')\n return name === '' ? 'acryl-app' : name\n}\n\nfunction walkUp(from: string, test: (dir: string) => string | undefined): string {\n let dir = from\n for (;;) {\n const found = test(dir)\n if (found) return found\n const parent = dirname(dir)\n if (parent === dir) throw new Error(`${CREATE} cannot find its files`)\n dir = parent\n }\n}\nconst here = dirname(fileURLToPath(import.meta.url))\nconst templatesRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'templates', 'nodejs')) ? join(d, 'templates') : undefined,\n )\n/** The framework docs: the copy `prepack` puts in the package, or `docs/framework` of the repository. */\nconst docsRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'docs', 'framework', 'README.md'))\n ? join(d, 'docs', 'framework')\n : undefined,\n )\n\n/**\n * The range a created app asks for: the framework version this package was released with, so a new app depends on the release that made it (and gets what that release's\n * commands can do), never an older one. A caret range, so it also takes the newer patch releases.\n */\nexport function frameworkRange(): string {\n const file = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n return `^${(JSON.parse(readFileSync(file, 'utf8')) as { version: string }).version}`\n}\n\nexport function replacePlaceholders(text: string, name: string): string {\n return text\n .replaceAll('__APP_NAME__', name)\n .replaceAll('__PACKAGE__', PACKAGE)\n .replaceAll('__CLASS__', CLASS)\n .replaceAll('__RANGE__', frameworkRange())\n}\n\n/** The guide for a coding agent in a created app: where the API is, how to run it, what must pass. */\nexport function agentsText(template: Exclude<Template, 'acryl-app'>, name: string): string {\n const run = { nodejs: 'npm run dev', notes: 'npm run dev', bun: 'bun run dev' }[template]\n const desktopNote =\n template === 'nodejs' || template === 'notes'\n ? `\\nTo run it as a desktop window: \\`npx ${PACKAGE} add desktop\\`, \\`npm install\\`, then \\`npm run desktop\\` (see \\`docs/framework/getting-started/desktop.md\\`).`\n : ''\n const test = {\n nodejs: 'npm test` and `npm run check',\n notes: 'npm test` and `npm run check',\n bun: 'bun test` and `bun run check',\n }[template]\n const jsxNote =\n template === 'nodejs' || template === 'notes'\n ? 'Write pages in `.tsx` (see `src/' +\n (template === 'notes' ? 'views.tsx' : 'page.tsx') +\n \"`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`.\"\n : \"Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`.\"\n const clientNote =\n template === 'nodejs'\n ? `- **Client components** (run in the browser) live in \\`src/client/\\`, which has its own \\`tsconfig.json\\` (DOM types, no Node types); \\`clientModules\\` in \\`src/app.ts\\` compiles them when the browser asks, and \\`npm run build\\` compiles them once for production. See \\`src/client/counter.tsx\\` and \\`docs/framework/guides/client-modules.md\\`.\\n`\n : ''\n const notesStructure =\n template === 'notes'\n ? `\n## Structure (a notes app: accounts, sessions, a database)\n\n- \\`src/db.ts\\`: \\`openDb()\\` (SQLite through the built-in \\`node:sqlite\\`; the file is \\`notes.db\\` or \\`$NOTES_DB\\`) and \\`notesStore(db)\\`, the queries for notes.\n- \\`src/auth.ts\\`: scrypt password hashes (\\`node:crypto\\`) and the \\`sessions\\` table; the cookie \\`sid\\` holds a random token.\n- \\`src/schema.ts\\`: the rules for a note and for credentials. The HTML forms and the JSON API both use \\`checkNote\\`.\n- \\`src/views.tsx\\`: the pages, as JSX components rendered to strings, and the small script for the instant filter.\n- \\`src/client/\\`: client components, with their own \\`tsconfig.json\\` (browser types). \\`counter.tsx\\` is the live character counter. \\`clientModules\\` in \\`notes-app.ts\\` compiles them when the browser asks; \\`npm run build\\` compiles them once into \\`dist/client\\` for production. See \\`docs/framework/guides/client-modules.md\\`.\n- \\`src/notes-app.ts\\`: \\`createApp(db)\\` (pages and forms, csrf on) and \\`createApi(db)\\` (the JSON API under \\`/api/notes\\`, chained so \\`testClient\\` is typed). \\`src/app.ts\\` is \\`export default createApp()\\`; tests call \\`createApp(openDb(':memory:'))\\`.\n- \\`test/notes.test.ts\\`: a test for every route. A form POST in a test needs \\`origin: 'http://localhost'\\` (csrf) and the \\`sid\\` cookie from sign up.\n- Forms answer an invalid input with status 400 and the same page with the messages; a successful POST redirects with 303.\n- To add a column: change the \\`CREATE TABLE\\` in \\`openDb\\`, \\`notesStore\\`, \\`checkNote\\`, the form and the list in \\`views.tsx\\`, and the tests.\n\n## Before you ship\n\nRead \\`docs/framework/getting-started/deploy.md\\`. In short:\n\n- Install with \\`npm ci --omit=dev\\`, run \\`npm run build\\` (it compiles \\`src/client\\` once; with \\`NODE_ENV=production\\` only \\`dist/client\\` is served), and start with \\`NODE_ENV=production npm start\\` (\\`typescript\\` stays a runtime dependency: it compiles the \\`.tsx\\` pages at start).\n- The app listens on \\`127.0.0.1\\`; set \\`HOST=0.0.0.0\\` only in a container. \\`PORT\\` chooses the port.\n- Put the SQLite file outside the code folder (\\`NOTES_DB=/var/lib/notes/notes.db\\`) and back it up.\n- Behind an HTTPS reverse proxy set \\`TRUST_PROXY=1\\` and \\`PUBLIC_ORIGIN=https://your.site\\`, or the cookie is not \\`Secure\\` and csrf refuses form posts.\n- \\`npm test\\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \\`src/index.ts\\`.\n`\n : ''\n return `# ${name}\n\nAn ${CLASS} app (${template}${template === 'bun' ? ', experimental' : ''}): handlers over the Web Standard \\`Request\\` and \\`Response\\`, from the \\`${PACKAGE}\\` package.\n\n## The framework's API is in \\`docs/framework/\\`\n\nStart at \\`docs/framework/README.md\\`; \\`api/summary.md\\` is the one-page summary. Import the class from \\`'${PACKAGE}'\\` and each middleware or helper from its own\nsubpath (\\`'${PACKAGE}/cors'\\`, \\`'${PACKAGE}/validator'\\`, ...). Parts marked \"not yet available\" in the docs are not in the package yet.\n\n## This app\n\nRun it with \\`${run}\\`. The routes are in \\`${template === 'bun' ? 'src/index.ts' : template === 'notes' ? 'src/notes-app.ts' : 'src/app.ts'}\\`; an app is a function from \\`Request\\` to \\`Response\\`,\nso test a route with \\`await app.request('/path')\\` and no server.${desktopNote}\n\n${notesStructure}\n## Things that surprise people\n\n- A page mounted at \\`/x\\` answers \\`/x\\`, not \\`/x/\\` (trailing slashes are strict); \\`trimTrailingSlash()\\` redirects.\n- A \\`json\\` validator target reads the body only with a JSON \\`Content-Type\\`; a failure answers 400 with \\`{ error, issues: [{ message, path }] }\\`.\n- \\`throw new HTTPException(404, { message })\\` answers an error response (plain text).\n- \\`testClient(app)\\` from \\`'${PACKAGE}/testing'\\` types only routes chained on the \\`new ${CLASS}()\\` expression (\\`new ${CLASS}().get(...).post(...)\\`); headers such as a cookie go in the second argument of each call.\n- **JSX:** ${jsxNote}\n${clientNote}\n## Before you say you are done\n\n\\`${test}\\` pass.\n`\n}\n\nfunction copyDocs(target: string): void {\n const filter = (path: string) => !/(upstream\\.json|UPSTREAM\\.md)$/.test(path)\n mkdirSync(join(target, 'docs'), { recursive: true })\n cpSync(docsRoot(), join(target, 'docs', 'framework'), { recursive: true, filter })\n}\n\nfunction copyTemplate(\n template: Exclude<Template, 'acryl-app'>,\n target: string,\n name: string,\n): string[] {\n const written: string[] = []\n const walk = (from: string, to: string, prefix: string) => {\n mkdirSync(to, { recursive: true })\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const targetName = prefix === '' && entry.name === 'gitignore' ? '.gitignore' : entry.name\n if (entry.isDirectory())\n walk(join(from, entry.name), join(to, targetName), `${prefix}${entry.name}/`)\n else {\n writeFileSync(\n join(to, targetName),\n replacePlaceholders(readFileSync(join(from, entry.name), 'utf8'), name),\n )\n written.push(`${prefix}${targetName}`)\n }\n }\n }\n walk(join(templatesRoot(), template), target, '')\n writeFileSync(join(target, 'AGENTS.md'), agentsText(template, name))\n writeFileSync(join(target, 'CLAUDE.md'), '@AGENTS.md\\n')\n copyDocs(target)\n return written\n}\n\nconst isEmpty = (directory: string) => !existsSync(directory) || readdirSync(directory).length === 0\n\n/** The `acrylblends` command of the installed framework package, which creates the `acryl-app` template. */\nfunction acrylblendsBin(): string {\n const pkgFile = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n const pkg = JSON.parse(readFileSync(pkgFile, 'utf8')) as { bin?: string | Record<string, string> }\n const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE]\n if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`)\n return join(dirname(pkgFile), bin)\n}\n\n/** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */\nexport async function runCreate(argv: readonly string[], io: Io = processIo()): Promise<number> {\n try {\n if (argv.includes('-h') || argv.includes('--help')) {\n io.stdout.write(HELP)\n return 0\n }\n if (argv.includes('-v') || argv.includes('--version')) {\n io.stdout.write(`${VERSION}\\n`)\n return 0\n }\n const options = parseCreateOptions(argv)\n const ask = options.yes ? undefined : io.ask\n const directory =\n options.directory ??\n (ask\n ? (await ask(`Project directory (${PACKAGE}-app): `)).trim() || `${PACKAGE}-app`\n : `${PACKAGE}-app`)\n const target = resolve(io.cwd, directory)\n const template: Template =\n options.template ??\n (ask\n ? await (async () => {\n const answer =\n (\n await ask(\n `Which template do you want to use? (nodejs, notes, bun (experimental), acryl-app) [nodejs]: `,\n )\n ).trim() || 'nodejs'\n if (!isTemplate(answer))\n throw new UsageError(`unknown template \"${answer}\" (${TEMPLATES.join(', ')})`)\n return answer\n })()\n : 'nodejs')\n if (!isEmpty(target)) {\n io.stderr.write(`error: ${target} is not empty; nothing was changed\\n`)\n return 1\n }\n const name = nameFrom(target)\n if (template === 'acryl-app') {\n const code = await io.run(\n process.execPath,\n [acrylblendsBin(), 'init', target, '--template', 'agent', '--name', name, '--yes'],\n io.cwd,\n )\n if (code !== 0) return 1\n } else {\n const files = copyTemplate(template, target, name)\n io.stdout.write(\n `created ${name} (${template}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\\n`,\n )\n }\n const pm: PackageManager =\n options.pm ??\n ((PACKAGE_MANAGERS as readonly string[]).find((m) =>\n (io.env.npm_config_user_agent ?? '').startsWith(`${m}/`),\n ) as PackageManager | undefined) ??\n 'npm'\n if (options.install) {\n if ((await io.run(pm, ['install'], target)) !== 0) {\n io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\\n`)\n return 1\n }\n }\n const start = {\n nodejs: `${pm} run dev`,\n notes: `${pm} run dev`,\n bun: 'bun run dev',\n 'acryl-app': `${pm} run dev`,\n }[template]\n io.stdout.write(\n `\\nNext:\\n cd ${directory}\\n${options.install ? '' : ` ${pm} install\\n`} ${start}\\n`,\n )\n return 0\n } catch (error) {\n if (error instanceof UsageError) {\n io.stderr.write(`error: ${error.message}\\n\\n${HELP}`)\n return 2\n }\n io.stderr.write(`error: ${(error as Error).message}\\n`)\n return 1\n }\n}\n"],"mappings":";;;;;;;;;;;;AAIA,MAAa,UAAU;AACvB,MAAa,QAAQ;AACrB,MAAa,SAAS;;;;;;;;ACOtB,SAAgB,yBACd,SACA,MACA,WAA4B,QAAQ,UACpC,MAAyB,QAAQ,KACjC,SAAoC,YACpC,WAAmB,QAAQ,UACf;CACZ,IAAI,aAAa,SAAS,OAAO;EAAE,MAAM;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;CAClE,IAAI,YAAY,OAAO;EACrB,MAAM,UAAU,IAAI;EACpB,MAAM,MACJ,YAAY,KAAA,KAAa,iBAAiB,KAAK,OAAO,IAClD,UACA,KAAK,QAAQ,Q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one place this package names the framework. The templates are written with `__PACKAGE__` and `__RANGE__` (the range is stamped at create time from the framework version this package carries, see `frameworkRange`), and the text of `AGENTS.md` with\n * `__PACKAGE__`, so a rename (for example to `acryl`) is a change here and in `scripts/lib/names.mjs`, which a test keeps equal.\n */\nexport const PACKAGE = 'acrylblends'\nexport const CLASS = 'Acryl'\nexport const CREATE = 'create-acrylblends'\n","import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface Invocation {\n file: string\n args: string[]\n}\n\n/**\n * How to start a package manager without the shell option (Node warns about passing args to a shell, DEP0190, and a `.cmd` shim cannot be spawned directly).\n * Off Windows the command runs as it is. On Windows npm runs as `node npm-cli.js` (the one npm is running from, else the one beside `node`); any other\n * manager goes through `cmd.exe /d /s /c <name>.cmd`, whose arguments stay an array.\n */\nexport function packageManagerInvocation(\n command: string,\n args: readonly string[],\n platform: NodeJS.Platform = process.platform,\n env: NodeJS.ProcessEnv = process.env,\n exists: (path: string) => boolean = existsSync,\n execPath: string = process.execPath,\n): Invocation {\n if (platform !== 'win32') return { file: command, args: [...args] }\n if (command === 'npm') {\n const running = env.npm_execpath\n const cli =\n running !== undefined && /npm-cli\\.c?js$/.test(running)\n ? running\n : join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')\n if (exists(cli)) return { file: execPath, args: [cli, ...args] }\n }\n return { file: env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `${command}.cmd`, ...args] }\n}\n","import { spawn } from 'node:child_process'\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { createInterface } from 'node:readline/promises'\nimport { fileURLToPath } from 'node:url'\nimport { parseArgs } from 'node:util'\nimport { CLASS, CREATE, PACKAGE } from './names'\nimport { packageManagerInvocation } from './spawn'\n\nexport { CLASS, CREATE, PACKAGE }\n\nexport const TEMPLATES = ['nodejs', 'notes', 'chat', 'bun', 'acryl-app'] as const\nexport type Template = (typeof TEMPLATES)[number]\nexport const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number]\n\n/** The version of this package. */\nexport const VERSION: string = (\n createRequire(import.meta.url)('../package.json') as { version: string }\n).version\n\nexport const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app\n\nUsage:\n npm create ${PACKAGE}@latest [directory] [-- options]\n\nOptions:\n --template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)\n --install install the dependencies after creating the app\n --pm <manager> ${PACKAGE_MANAGERS.join(', ')} (default: the one that ran this command, else npm)\n -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app\n -h, --help show this help\n -v, --version show the version\n`\n\n/** A command line mistake. The command prints it with the help text and exits 2. */\nexport class UsageError extends Error {\n override name = 'UsageError'\n}\n\nexport interface Io {\n stdout: { write(text: string): unknown }\n stderr: { write(text: string): unknown }\n cwd: string\n env: Record<string, string | undefined>\n /** Ask one question; `undefined` when there is no terminal to ask on. */\n ask: ((question: string) => Promise<string>) | undefined\n /** Run a program, showing its output; resolves to the exit code. */\n run(command: string, args: string[], cwd: string): Promise<number>\n}\n\nexport function processIo(): Io {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY)\n return {\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: process.cwd(),\n env: process.env,\n ask: interactive\n ? async (question) => {\n const rl = createInterface({ input: process.stdin, output: process.stdout })\n try {\n return await rl.question(question)\n } finally {\n rl.close()\n }\n }\n : undefined,\n run: (command, args, cwd) =>\n new Promise((done) => {\n const invocation = packageManagerInvocation(command, args)\n const child = spawn(invocation.file, invocation.args, { cwd, stdio: 'inherit' })\n child.on('error', () => done(1))\n child.on('exit', (code) => done(code ?? 1))\n }),\n }\n}\n\nexport interface CreateOptions {\n directory: string | undefined\n template: Template | undefined\n install: boolean\n pm: PackageManager | undefined\n yes: boolean\n}\n\nexport function isTemplate(value: string): value is Template {\n return (TEMPLATES as readonly string[]).includes(value)\n}\n\nexport function parseCreateOptions(argv: readonly string[]): CreateOptions {\n let parsed: ReturnType<typeof parse>\n try {\n parsed = parse(argv)\n } catch (error) {\n throw new UsageError((error as Error).message)\n }\n const { values, positionals } = parsed\n if (positionals.length > 1) throw new UsageError('takes at most one directory')\n if (values.template !== undefined && !isTemplate(values.template))\n throw new UsageError(`unknown template \"${values.template}\" (${TEMPLATES.join(', ')})`)\n if (values.pm !== undefined && !(PACKAGE_MANAGERS as readonly string[]).includes(values.pm))\n throw new UsageError(`unknown package manager \"${values.pm}\" (${PACKAGE_MANAGERS.join(', ')})`)\n return {\n directory: positionals[0],\n template: values.template as Template | undefined,\n install: values.install === true,\n pm: values.pm as PackageManager | undefined,\n yes: values.yes === true,\n }\n}\n\nconst parse = (argv: readonly string[]) =>\n parseArgs({\n args: [...argv],\n allowPositionals: true,\n strict: true,\n options: {\n template: { type: 'string' },\n install: { type: 'boolean' },\n pm: { type: 'string' },\n yes: { type: 'boolean', short: 'y' },\n },\n })\n\n/** A valid package name from a directory name: lower case letters, digits and dashes. */\nexport function nameFrom(directory: string): string {\n const name = basename(resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/g, '')\n return name === '' ? 'acryl-app' : name\n}\n\nfunction walkUp(from: string, test: (dir: string) => string | undefined): string {\n let dir = from\n for (;;) {\n const found = test(dir)\n if (found) return found\n const parent = dirname(dir)\n if (parent === dir) throw new Error(`${CREATE} cannot find its files`)\n dir = parent\n }\n}\nconst here = dirname(fileURLToPath(import.meta.url))\nconst templatesRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'templates', 'nodejs')) ? join(d, 'templates') : undefined,\n )\n/** The framework docs: the copy `prepack` puts in the package, or `docs/framework` of the repository. */\nconst docsRoot = () =>\n walkUp(here, (d) =>\n existsSync(join(d, 'docs', 'framework', 'README.md'))\n ? join(d, 'docs', 'framework')\n : undefined,\n )\n\n/**\n * The range a created app asks for: the framework version this package was released with, so a new app depends on the release that made it (and gets what that release's\n * commands can do), never an older one. A caret range, so it also takes the newer patch releases.\n */\nexport function frameworkRange(): string {\n const file = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n return `^${(JSON.parse(readFileSync(file, 'utf8')) as { version: string }).version}`\n}\n\nexport function replacePlaceholders(text: string, name: string): string {\n return text\n .replaceAll('__APP_NAME__', name)\n .replaceAll('__PACKAGE__', PACKAGE)\n .replaceAll('__CLASS__', CLASS)\n .replaceAll('__RANGE__', frameworkRange())\n}\n\n/** The guide for a coding agent in a created app: where the API is, how to run it, what must pass. */\nexport function agentsText(template: Exclude<Template, 'acryl-app'>, name: string): string {\n const run = {\n nodejs: 'npm run dev',\n notes: 'npm run dev',\n chat: 'npm run dev',\n bun: 'bun run dev',\n }[template]\n const desktopNote =\n template === 'nodejs' || template === 'notes' || template === 'chat'\n ? `\\nTo run it as a desktop window: \\`npx ${PACKAGE} add desktop\\`, \\`npm install\\`, then \\`npm run desktop\\` (see \\`docs/framework/getting-started/desktop.md\\`).`\n : ''\n const test = {\n nodejs: 'npm test` and `npm run check',\n notes: 'npm test` and `npm run check',\n chat: 'npm test` and `npm run check',\n bun: 'bun test` and `bun run check',\n }[template]\n const jsxNote =\n template === 'nodejs' || template === 'notes' || template === 'chat'\n ? 'Write pages in `.tsx` (see `src/' +\n (template === 'notes' ? 'views.tsx' : 'page.tsx') +\n \"`): the scripts in `package.json` run Node.js with `--import acrylblends/node-server/register`, which compiles `.tsx` with this app's own `typescript`, and `tsconfig.json` sets `jsx: react-jsx` with `jsxImportSource: acrylblends/jsx`. Render a component with `.toString()` and return it with `c.html(...)`. A command that starts the app without those scripts (a bare `node src/index.ts`) cannot load a `.tsx` file. Without a build step you can write the call JSX compiles to instead: `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'`, children after the props. See `docs/framework/guides/jsx.md`.\"\n : \"Bun compiles `.tsx` itself: write pages in `.tsx`, render a component with `.toString()` and return it with `c.html(...)`. `jsx('h1', { class: 'title' }, 'Hello')` from `'acrylblends/jsx'` (children after the props) is the same thing without JSX syntax. See `docs/framework/guides/jsx.md`.\"\n const clientNote =\n template === 'nodejs'\n ? `- **Client components** (run in the browser) live in \\`src/client/\\`, which has its own \\`tsconfig.json\\` (DOM types, no Node types); \\`clientModules\\` in \\`src/app.ts\\` compiles them when the browser asks, and \\`npm run build\\` compiles them once for production. See \\`src/client/counter.tsx\\` and \\`docs/framework/guides/client-modules.md\\`.\\n`\n : ''\n const chatStructure =\n template === 'chat'\n ? `\n## Structure (a chat app: a streamed answer, history in a database)\n\n- \\`src/llm.ts\\`: \\`Llm\\`, what the app needs from a model (messages in, pieces out, an aborted signal stops the work), and \\`openAiCompatible\\`, which calls an OpenAI-compatible chat completions API with \\`stream: true\\`. The base URL is \\`DEEPSEEK_BASE_URL\\` (default \\`https://api.deepseek.com\\`), the model \\`DEEPSEEK_MODEL\\` (default \\`deepseek-chat\\`), the key **only** the environment variable \\`DEEPSEEK_API_KEY\\`, read at the moment of the call: never write it to a file, a response or a log.\n- \\`src/db.ts\\`: \\`openDb()\\` (SQLite through \\`node:sqlite\\`; the file is \\`chat.db\\` or \\`$CHAT_DB\\`) and \\`chatStore(db)\\`. The routes only call \\`chatStore\\`; keep SQL out of them.\n- \\`src/chat-app.ts\\`: \\`createApp(db, llm)\\`. \\`POST /api/chat\\` answers Server-Sent Events: \\`meta\\` (the conversation id), a \\`token\\` per piece, then \\`done\\` or \\`error\\`. The request's signal (\\`c.req.raw.signal\\`) goes to the model call, so a closed tab or the Stop button stops the request to the model; what had arrived is kept.\n- \\`src/client/chat.tsx\\`: the client component (own \\`tsconfig.json\\`, browser types): sends the message with \\`fetch\\`, reads the events as they arrive, shows the answer growing, and aborts on Stop. \\`clientModules\\` compiles it when the browser asks; \\`npm run build\\` compiles it once into \\`dist/client\\`. See \\`docs/framework/guides/client-modules.md\\`.\n- \\`test/chat.test.ts\\` tests every route with a mock \\`Llm\\` (never the network); keep it that way. \\`test/server.test.ts\\` starts the real server and stops it with a signal.\n- To try it with a real model: \\`DEEPSEEK_API_KEY=... npm run dev\\`.\n\n## Before you ship\n\nRead \\`docs/framework/getting-started/deploy.md\\`. In short: \\`npm ci --omit=dev\\`, \\`npm run build\\`, \\`NODE_ENV=production npm start\\`; the app listens on \\`127.0.0.1\\` (\\`HOST=0.0.0.0\\` only in a container); the SQLite file goes outside the code folder (\\`CHAT_DB=/var/lib/chat/chat.db\\`) and is backed up; the model key is an environment variable of the service (a root-only environment file for systemd), never a file in the repository. Anyone who can reach the app can spend your key: put it behind a login or on a private network before it is public.\n`\n : ''\n const notesStructure =\n template === 'notes'\n ? `\n## Structure (a notes app: accounts, sessions, a database)\n\n- \\`src/db.ts\\`: \\`openDb()\\` (SQLite through the built-in \\`node:sqlite\\`; the file is \\`notes.db\\` or \\`$NOTES_DB\\`) and \\`notesStore(db)\\`, the queries for notes.\n- \\`src/auth.ts\\`: scrypt password hashes (\\`node:crypto\\`) and the \\`sessions\\` table; the cookie \\`sid\\` holds a random token.\n- \\`src/schema.ts\\`: the rules for a note and for credentials. The HTML forms and the JSON API both use \\`checkNote\\`.\n- \\`src/views.tsx\\`: the pages, as JSX components rendered to strings, and the small script for the instant filter.\n- \\`src/client/\\`: client components, with their own \\`tsconfig.json\\` (browser types). \\`counter.tsx\\` is the live character counter. \\`clientModules\\` in \\`notes-app.ts\\` compiles them when the browser asks; \\`npm run build\\` compiles them once into \\`dist/client\\` for production. See \\`docs/framework/guides/client-modules.md\\`.\n- \\`src/notes-app.ts\\`: \\`createApp(db)\\` (pages and forms, csrf on) and \\`createApi(db)\\` (the JSON API under \\`/api/notes\\`, chained so \\`testClient\\` is typed). \\`src/app.ts\\` is \\`export default createApp()\\`; tests call \\`createApp(openDb(':memory:'))\\`.\n- \\`test/notes.test.ts\\`: a test for every route. A form POST in a test needs \\`origin: 'http://localhost'\\` (csrf) and the \\`sid\\` cookie from sign up.\n- Forms answer an invalid input with status 400 and the same page with the messages; a successful POST redirects with 303.\n- To add a column: change the \\`CREATE TABLE\\` in \\`openDb\\`, \\`notesStore\\`, \\`checkNote\\`, the form and the list in \\`views.tsx\\`, and the tests.\n\n## Before you ship\n\nRead \\`docs/framework/getting-started/deploy.md\\`. In short:\n\n- Install with \\`npm ci --omit=dev\\`, run \\`npm run build\\` (it compiles \\`src/client\\` once; with \\`NODE_ENV=production\\` only \\`dist/client\\` is served), and start with \\`NODE_ENV=production npm start\\` (\\`typescript\\` stays a runtime dependency: it compiles the \\`.tsx\\` pages at start).\n- The app listens on \\`127.0.0.1\\`; set \\`HOST=0.0.0.0\\` only in a container. \\`PORT\\` chooses the port.\n- Put the SQLite file outside the code folder (\\`NOTES_DB=/var/lib/notes/notes.db\\`) and back it up.\n- Behind an HTTPS reverse proxy set \\`TRUST_PROXY=1\\` and \\`PUBLIC_ORIGIN=https://your.site\\`, or the cookie is not \\`Secure\\` and csrf refuses form posts.\n- \\`npm test\\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \\`src/index.ts\\`.\n`\n : ''\n return `# ${name}\n\nAn ${CLASS} app (${template}${template === 'bun' ? ', experimental' : ''}): handlers over the Web Standard \\`Request\\` and \\`Response\\`, from the \\`${PACKAGE}\\` package.\n\n## The framework's API is in \\`docs/framework/\\`\n\nStart at \\`docs/framework/README.md\\`; \\`api/summary.md\\` is the one-page summary. Import the class from \\`'${PACKAGE}'\\` and each middleware or helper from its own\nsubpath (\\`'${PACKAGE}/cors'\\`, \\`'${PACKAGE}/validator'\\`, ...). Parts marked \"not yet available\" in the docs are not in the package yet.\n\n## This app\n\nRun it with \\`${run}\\`. The routes are in \\`${template === 'bun' ? 'src/index.ts' : template === 'notes' ? 'src/notes-app.ts' : template === 'chat' ? 'src/chat-app.ts' : 'src/app.ts'}\\`; an app is a function from \\`Request\\` to \\`Response\\`,\nso test a route with \\`await app.request('/path')\\` and no server.${desktopNote}\n\n${notesStructure}${chatStructure}\n## Things that surprise people\n\n- A page mounted at \\`/x\\` answers \\`/x\\`, not \\`/x/\\` (trailing slashes are strict); \\`trimTrailingSlash()\\` redirects.\n- A \\`json\\` validator target reads the body only with a JSON \\`Content-Type\\`; a failure answers 400 with \\`{ error, issues: [{ message, path }] }\\`.\n- \\`throw new HTTPException(404, { message })\\` answers an error response (plain text).\n- \\`testClient(app)\\` from \\`'${PACKAGE}/testing'\\` types only routes chained on the \\`new ${CLASS}()\\` expression (\\`new ${CLASS}().get(...).post(...)\\`); headers such as a cookie go in the second argument of each call.\n- **JSX:** ${jsxNote}\n${clientNote}\n## Before you say you are done\n\n\\`${test}\\` pass.\n`\n}\n\nfunction copyDocs(target: string): void {\n const filter = (path: string) => !/(upstream\\.json|UPSTREAM\\.md)$/.test(path)\n mkdirSync(join(target, 'docs'), { recursive: true })\n cpSync(docsRoot(), join(target, 'docs', 'framework'), { recursive: true, filter })\n}\n\nfunction copyTemplate(\n template: Exclude<Template, 'acryl-app'>,\n target: string,\n name: string,\n): string[] {\n const written: string[] = []\n const walk = (from: string, to: string, prefix: string) => {\n mkdirSync(to, { recursive: true })\n for (const entry of readdirSync(from, { withFileTypes: true })) {\n const targetName = prefix === '' && entry.name === 'gitignore' ? '.gitignore' : entry.name\n if (entry.isDirectory())\n walk(join(from, entry.name), join(to, targetName), `${prefix}${entry.name}/`)\n else {\n writeFileSync(\n join(to, targetName),\n replacePlaceholders(readFileSync(join(from, entry.name), 'utf8'), name),\n )\n written.push(`${prefix}${targetName}`)\n }\n }\n }\n walk(join(templatesRoot(), template), target, '')\n writeFileSync(join(target, 'AGENTS.md'), agentsText(template, name))\n writeFileSync(join(target, 'CLAUDE.md'), '@AGENTS.md\\n')\n copyDocs(target)\n return written\n}\n\nconst isEmpty = (directory: string) => !existsSync(directory) || readdirSync(directory).length === 0\n\n/** The `acrylblends` command of the installed framework package, which creates the `acryl-app` template. */\nfunction acrylblendsBin(): string {\n const pkgFile = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`)\n const pkg = JSON.parse(readFileSync(pkgFile, 'utf8')) as { bin?: string | Record<string, string> }\n const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.[PACKAGE]\n if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`)\n return join(dirname(pkgFile), bin)\n}\n\n/** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */\nexport async function runCreate(argv: readonly string[], io: Io = processIo()): Promise<number> {\n try {\n if (argv.includes('-h') || argv.includes('--help')) {\n io.stdout.write(HELP)\n return 0\n }\n if (argv.includes('-v') || argv.includes('--version')) {\n io.stdout.write(`${VERSION}\\n`)\n return 0\n }\n const options = parseCreateOptions(argv)\n const ask = options.yes ? undefined : io.ask\n const directory =\n options.directory ??\n (ask\n ? (await ask(`Project directory (${PACKAGE}-app): `)).trim() || `${PACKAGE}-app`\n : `${PACKAGE}-app`)\n const target = resolve(io.cwd, directory)\n const template: Template =\n options.template ??\n (ask\n ? await (async () => {\n const answer =\n (\n await ask(\n `Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `,\n )\n ).trim() || 'nodejs'\n if (!isTemplate(answer))\n throw new UsageError(`unknown template \"${answer}\" (${TEMPLATES.join(', ')})`)\n return answer\n })()\n : 'nodejs')\n if (!isEmpty(target)) {\n io.stderr.write(`error: ${target} is not empty; nothing was changed\\n`)\n return 1\n }\n const name = nameFrom(target)\n if (template === 'acryl-app') {\n const code = await io.run(\n process.execPath,\n [acrylblendsBin(), 'init', target, '--template', 'agent', '--name', name, '--yes'],\n io.cwd,\n )\n if (code !== 0) return 1\n } else {\n const files = copyTemplate(template, target, name)\n io.stdout.write(\n `created ${name} (${template}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\\n`,\n )\n }\n const pm: PackageManager =\n options.pm ??\n ((PACKAGE_MANAGERS as readonly string[]).find((m) =>\n (io.env.npm_config_user_agent ?? '').startsWith(`${m}/`),\n ) as PackageManager | undefined) ??\n 'npm'\n if (options.install) {\n if ((await io.run(pm, ['install'], target)) !== 0) {\n io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\\n`)\n return 1\n }\n }\n const start = {\n nodejs: `${pm} run dev`,\n notes: `${pm} run dev`,\n chat: `${pm} run dev`,\n bun: 'bun run dev',\n 'acryl-app': `${pm} run dev`,\n }[template]\n io.stdout.write(\n `\\nNext:\\n cd ${directory}\\n${options.install ? '' : ` ${pm} install\\n`} ${start}\\n`,\n )\n return 0\n } catch (error) {\n if (error instanceof UsageError) {\n io.stderr.write(`error: ${error.message}\\n\\n${HELP}`)\n return 2\n }\n io.stderr.write(`error: ${(error as Error).message}\\n`)\n return 1\n }\n}\n"],"mappings":";;;;;;;;;;;;AAIA,MAAa,UAAU;AACvB,MAAa,QAAQ;AACrB,MAAa,SAAS;;;;;;;;ACOtB,SAAgB,yBACd,SACA,MACA,WAA4B,QAAQ,UACpC,MAAyB,QAAQ,KACjC,SAAoC,YACpC,WAAmB,QAAQ,UACf;CACZ,IAAI,aAAa,SAAS,OAAO;EAAE,MAAM;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;CAClE,IAAI,YAAY,OAAO;EACrB,MAAM,UAAU,IAAI;EACpB,MAAM,MACJ,YAAY,KAAA,KAAa,iBAAiB,KAAK,OAAO,IAClD,UACA,KAAK,QAAQ,QAAQ,GAAG,gBAAgB,OAAO,OAAO,YAAY;EACxE,IAAI,OAAO,GAAG,GAAG,OAAO;GAAE,MAAM;GAAU,MAAM,CAAC,KAAK,GAAG,IAAI;EAAE;CACjE;CACA,OAAO;EAAE,MAAM,IAAI,WAAW;EAAW,MAAM;GAAC;GAAM;GAAM;GAAM,GAAG,QAAQ;GAAO,GAAG;EAAI;CAAE;AAC/F;;;ACnBA,MAAa,YAAY;CAAC;CAAU;CAAS;CAAQ;CAAO;AAAW;AAEvE,MAAa,mBAAmB;CAAC;CAAO;CAAQ;CAAQ;AAAK;;AAI7D,MAAa,UACX,cAAc,YAAY,GA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,OAAO;EAAA,OAClB;GACL,MAAM,QAAQ,aAAa,UAAU,QAAQ,IAAI;GACjD,GAAG,OAAO,MACR,WAAW,KAAK,IAAI,SAAS,OAAO,OAAO,IAAI,MAAM,OAAO,UAAU,MAAM,0BAC9E;EACF;EACA,MAAM,KACJ,QAAQ,MACN,iBAAuC,MAAM,OAC5C,GAAG,IAAI,yBAAyB,GAAA,CAAI,WAAW,GAAG,EAAE,EAAE,CACzD,KACA;EACF,IAAI,QAAQ,SACL;OAAA,MAAM,GAAG,IAAI,IAAI,CAAC,SAAS,GAAG,MAAM,MAAO,GAAG;IACjD,GAAG,OAAO,MAAM,UAAU,GAAG,sCAAsC,UAAU,GAAG;IAChF,OAAO;GACT;;EAEF,MAAM,QAAQ;GACZ,QAAQ,GAAG,GAAG;GACd,OAAO,GAAG,GAAG;GACb,MAAM,GAAG,GAAG;GACZ,KAAK;GACL,aAAa,GAAG,GAAG;EACrB,EAAE;EACF,GAAG,OAAO,MACR,iBAAiB,UAAU,IAAI,QAAQ,UAAU,KAAK,KAAK,GAAG,YAAY,IAAI,MAAM,GACtF;EACA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,iBAAiB,YAAY;GAC/B,GAAG,OAAO,MAAM,UAAU,MAAM,QAAQ,MAAM,MAAM;GACpD,OAAO;EACT;EACA,GAAG,OAAO,MAAM,UAAW,MAAgB,QAAQ,GAAG;EACtD,OAAO;CACT;AACF"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
# Generated copy
|
|
2
2
|
|
|
3
|
-
This folder is a copy of `docs/framework` of acryldev/acryl at commit `
|
|
3
|
+
This folder is a copy of `docs/framework` of acryldev/acryl at commit `e79bf3de59c700667ae617f5d367cc1fd2f8e037`, made by `scripts/sync-framework.mjs`. Do not edit it here: change the text in ACRYL and sync again. `pnpm run verify:framework` fails when a page differs from the recorded digest.
|
|
@@ -110,6 +110,40 @@ server's nodes are gone afterwards, together with anything the visitor did to th
|
|
|
110
110
|
into an input. Keep the server markup the same as the component's first render, so the swap does not show, and keep inputs out of the
|
|
111
111
|
server markup of an island, or render them only in the browser.
|
|
112
112
|
|
|
113
|
+
## A form and its state in an island
|
|
114
|
+
|
|
115
|
+
An island that owns an input keeps the text in state and writes it back to the element, so typing and clearing the box both work:
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
import { render, useState } from 'acrylblends/jsx/dom'
|
|
119
|
+
|
|
120
|
+
const Ask = () => {
|
|
121
|
+
const [text, setText] = useState('')
|
|
122
|
+
const [sent, setSent] = useState<string[]>([])
|
|
123
|
+
const submit = (event: Event) => {
|
|
124
|
+
event.preventDefault()
|
|
125
|
+
if (text.trim() === '') return
|
|
126
|
+
setSent([...sent, text.trim()])
|
|
127
|
+
setText('')
|
|
128
|
+
}
|
|
129
|
+
return (
|
|
130
|
+
<form onSubmit={submit}>
|
|
131
|
+
<textarea value={text} onInput={(e) => setText((e.target as HTMLTextAreaElement).value)} />
|
|
132
|
+
<button type="submit">Send</button>
|
|
133
|
+
<ul>
|
|
134
|
+
{sent.map((message) => (
|
|
135
|
+
<li>{message}</li>
|
|
136
|
+
))}
|
|
137
|
+
</ul>
|
|
138
|
+
</form>
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
render(<Ask />, document.getElementById('ask')!)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
For a request that streams its answer and a Stop button (an `AbortController` kept in a `useRef`), see [Streaming an answer from a model](../helpers/streaming.md#streaming-an-answer-from-a-model).
|
|
146
|
+
|
|
113
147
|
## How the imports reach the browser
|
|
114
148
|
|
|
115
149
|
- JSX in a client module always compiles for the DOM renderer (`acrylblends/jsx/dom`), whatever the server's `tsconfig.json` says. A file's
|
|
@@ -81,6 +81,125 @@ app.get('/sse', async (c) => {
|
|
|
81
81
|
})
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
+
## Cancelling work when the client leaves
|
|
85
|
+
|
|
86
|
+
A reader that closes the tab, loses the network or presses a Stop button should not leave your server working for nobody (a request to a paid model, a database scan). There are two signals, and they are not the same:
|
|
87
|
+
|
|
88
|
+
- **`c.req.raw.signal`** is the request's `AbortSignal`. It aborts when the client goes away. Pass it to anything that takes a `signal`, such as `fetch`, and the work stops with the client. This is the one to use for cancelling work.
|
|
89
|
+
- **`stream.onAbort(callback)`** and **`stream.aborted`** belong to the response stream. They report that the *reader of the response* was cancelled. Measured: when you call `app.request()` with a `signal` and abort it, `c.req.raw.signal` aborts and `stream.aborted` stays `false`; when the reader of the response body is cancelled, `stream.onAbort` fires and `c.req.raw.signal` does not. On a real connection the request signal is what fired when a browser aborted its `fetch`. Use `c.req.raw.signal` for the work, and `stream.onAbort` for cleanup of the stream itself.
|
|
90
|
+
|
|
91
|
+
An abort event that has already fired does not fire again, so check `signal.aborted` before you wait for it:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const waitForAbort = (signal: AbortSignal) =>
|
|
95
|
+
signal.aborted
|
|
96
|
+
? Promise.resolve()
|
|
97
|
+
: new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Keep what you have when the client leaves by saving it in a `finally` block: the stream callback runs to the end whether or not the client is still there.
|
|
101
|
+
|
|
102
|
+
## Streaming an answer from a model
|
|
103
|
+
|
|
104
|
+
A chat answer that arrives token by token is a `streamSSE` response that reads a streaming upstream. This server route calls an OpenAI-compatible chat completions API (`stream: true`), forwards each piece as an event, and cancels the upstream request when the client leaves. The key comes from the environment and is never written anywhere.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { Acryl } from 'acrylblends'
|
|
108
|
+
import { streamSSE } from 'acrylblends/streaming'
|
|
109
|
+
|
|
110
|
+
/** The pieces of an OpenAI-compatible streaming answer: each `data:` line holds a JSON chunk, and `[DONE]` ends it. */
|
|
111
|
+
async function* modelPieces(messages: { role: string; content: string }[], signal: AbortSignal): AsyncGenerator<string> {
|
|
112
|
+
const key = process.env.DEEPSEEK_API_KEY
|
|
113
|
+
if (!key) throw new Error('DEEPSEEK_API_KEY is not set')
|
|
114
|
+
const base = process.env.DEEPSEEK_BASE_URL ?? 'https://api.deepseek.com'
|
|
115
|
+
const response = await fetch(`${base}/chat/completions`, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
118
|
+
body: JSON.stringify({ model: process.env.DEEPSEEK_MODEL ?? 'deepseek-chat', messages, stream: true }),
|
|
119
|
+
signal,
|
|
120
|
+
})
|
|
121
|
+
if (!response.ok || !response.body) throw new Error(`the model service answered ${response.status}`)
|
|
122
|
+
const decoder = new TextDecoder()
|
|
123
|
+
let buffer = ''
|
|
124
|
+
for await (const chunk of response.body) {
|
|
125
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
126
|
+
const lines = buffer.split('\n')
|
|
127
|
+
buffer = lines.pop() ?? ''
|
|
128
|
+
for (const line of lines) {
|
|
129
|
+
if (!line.startsWith('data:')) continue
|
|
130
|
+
const data = line.slice(5).trim()
|
|
131
|
+
if (data === '[DONE]') return
|
|
132
|
+
const piece = (JSON.parse(data) as { choices?: { delta?: { content?: string } }[] }).choices?.[0]?.delta?.content
|
|
133
|
+
if (piece) yield piece
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const app = new Acryl()
|
|
139
|
+
|
|
140
|
+
app.post('/api/chat', async (c) => {
|
|
141
|
+
const { message } = await c.req.json<{ message: string }>()
|
|
142
|
+
const signal = c.req.raw.signal // aborts when the client goes away
|
|
143
|
+
return streamSSE(c, async (stream) => {
|
|
144
|
+
let answer = ''
|
|
145
|
+
try {
|
|
146
|
+
for await (const piece of modelPieces([{ role: 'user', content: message }], signal)) {
|
|
147
|
+
answer += piece
|
|
148
|
+
// JSON-encode the piece: a piece may contain a newline, which would end an SSE `data:` line.
|
|
149
|
+
await stream.writeSSE({ event: 'token', data: JSON.stringify(piece) })
|
|
150
|
+
}
|
|
151
|
+
await stream.writeSSE({ event: 'done', data: '{}' })
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!signal.aborted) await stream.writeSSE({ event: 'error', data: JSON.stringify('The model could not answer.') })
|
|
154
|
+
} finally {
|
|
155
|
+
console.log(`kept ${answer.length} characters`) // save what arrived, also when the client pressed Stop
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Reading a POST event stream in the browser
|
|
162
|
+
|
|
163
|
+
`EventSource` can only send a GET request. For a POST (a chat message), read the response body yourself; this function calls `on` for each event as it arrives:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
async function readEvents(body: ReadableStream<Uint8Array>, on: (event: string, data: string) => void): Promise<void> {
|
|
167
|
+
const reader = body.getReader()
|
|
168
|
+
const decoder = new TextDecoder()
|
|
169
|
+
let buffer = ''
|
|
170
|
+
for (;;) {
|
|
171
|
+
const { done, value } = await reader.read()
|
|
172
|
+
if (done) return
|
|
173
|
+
buffer += decoder.decode(value, { stream: true })
|
|
174
|
+
const blocks = buffer.split('\n\n')
|
|
175
|
+
buffer = blocks.pop() ?? ''
|
|
176
|
+
for (const block of blocks) {
|
|
177
|
+
let event = 'message'
|
|
178
|
+
const data: string[] = []
|
|
179
|
+
for (const line of block.split('\n')) {
|
|
180
|
+
if (line.startsWith('event:')) event = line.slice(6).trim()
|
|
181
|
+
else if (line.startsWith('data:')) data.push(line.slice(5).trimStart())
|
|
182
|
+
}
|
|
183
|
+
on(event, data.join('\n'))
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const controller = new AbortController() // controller.abort() is the Stop button
|
|
189
|
+
const response = await fetch('/api/chat', {
|
|
190
|
+
method: 'POST',
|
|
191
|
+
headers: { 'content-type': 'application/json' },
|
|
192
|
+
body: JSON.stringify({ message: 'Hello' }),
|
|
193
|
+
signal: controller.signal,
|
|
194
|
+
})
|
|
195
|
+
let answer = ''
|
|
196
|
+
await readEvents(response.body!, (event, data) => {
|
|
197
|
+
if (event === 'token') answer += JSON.parse(data) as string
|
|
198
|
+
})
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
A complete chat component built on this is in the `chat` template of `create-acrylblends` (`npm create acrylblends@latest my-chat -- --template chat`).
|
|
202
|
+
|
|
84
203
|
## Error Handling
|
|
85
204
|
|
|
86
205
|
The third argument of the streaming helper is an error handler.
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"source": {
|
|
3
3
|
"repo": "acryldev/acryl",
|
|
4
4
|
"path": "docs/framework",
|
|
5
|
-
"commit": "
|
|
5
|
+
"commit": "e79bf3de59c700667ae617f5d367cc1fd2f8e037"
|
|
6
6
|
},
|
|
7
7
|
"files": 91,
|
|
8
|
-
"digest": "sha256:
|
|
8
|
+
"digest": "sha256:ea881fe758d9d9add8a8d3837f1dddc6938c3e021cb4ea5f1ce5cfb31af7ef2c"
|
|
9
9
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-acrylblends",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "Create an Acryl app: npm create acrylblends@latest",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"scaffold"
|
|
38
38
|
],
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"acrylblends": "^0.7.
|
|
40
|
+
"acrylblends": "^0.7.3"
|
|
41
41
|
},
|
|
42
42
|
"publishConfig": {
|
|
43
43
|
"access": "public"
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "__APP_NAME__",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22.19.0"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"dev": "node --watch --import acrylblends/node-server/register src/index.ts",
|
|
11
|
+
"start": "node --import acrylblends/node-server/register src/index.ts",
|
|
12
|
+
"test": "node --import acrylblends/node-server/register --test \"test/**/*.test.{ts,tsx}\"",
|
|
13
|
+
"check": "tsc --noEmit && tsc --noEmit -p src/client",
|
|
14
|
+
"build": "acrylblends build-client"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"__PACKAGE__": "__RANGE__",
|
|
18
|
+
"typescript": "6.0.3"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^24.0.0"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { __CLASS__ } from '__PACKAGE__'
|
|
2
|
+
import { clientModules } from '__PACKAGE__/node-server'
|
|
3
|
+
import { type StandardSchema, schemaValidator } from '__PACKAGE__/schema-validator'
|
|
4
|
+
import { streamSSE } from '__PACKAGE__/streaming'
|
|
5
|
+
import type { DatabaseSync } from 'node:sqlite'
|
|
6
|
+
import { chatStore, openDb } from './db.ts'
|
|
7
|
+
import { type Llm, openAiCompatible } from './llm.ts'
|
|
8
|
+
import { chatPage } from './page.tsx'
|
|
9
|
+
|
|
10
|
+
interface ChatInput {
|
|
11
|
+
message: string
|
|
12
|
+
conversation?: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const ChatSchema: StandardSchema<ChatInput> = {
|
|
16
|
+
'~standard': {
|
|
17
|
+
validate: (value) => {
|
|
18
|
+
const input = (value ?? {}) as Record<string, unknown>
|
|
19
|
+
const message = typeof input.message === 'string' ? input.message.trim() : ''
|
|
20
|
+
const issues = []
|
|
21
|
+
if (message === '') issues.push({ message: 'Write a message.', path: ['message'] })
|
|
22
|
+
else if (message.length > 4000)
|
|
23
|
+
issues.push({ message: 'The message is at most 4000 characters.', path: ['message'] })
|
|
24
|
+
if (input.conversation !== undefined && !Number.isInteger(input.conversation))
|
|
25
|
+
issues.push({ message: 'The conversation is a number.', path: ['conversation'] })
|
|
26
|
+
return issues.length > 0
|
|
27
|
+
? { issues }
|
|
28
|
+
: { value: { message, conversation: input.conversation as number | undefined } }
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function createApp(db: DatabaseSync = openDb(), llm: Llm = openAiCompatible) {
|
|
34
|
+
const store = chatStore(db)
|
|
35
|
+
const app = new __CLASS__()
|
|
36
|
+
|
|
37
|
+
app.get('/', (c) => {
|
|
38
|
+
const id = Number(c.req.query('c'))
|
|
39
|
+
const current = Number.isInteger(id) ? store.conversation(id) : undefined
|
|
40
|
+
return c.html(
|
|
41
|
+
chatPage(store.conversations(), current, current ? store.messages(current.id) : []),
|
|
42
|
+
)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
app.get('/api/conversations', (c) => c.json({ conversations: store.conversations() }))
|
|
46
|
+
app.get('/api/conversations/:id', (c) => {
|
|
47
|
+
const id = Number(c.req.param('id'))
|
|
48
|
+
const conversation = store.conversation(id)
|
|
49
|
+
return conversation
|
|
50
|
+
? c.json({ conversation, messages: store.messages(id) })
|
|
51
|
+
: c.json({ error: 'No such conversation.' }, 404)
|
|
52
|
+
})
|
|
53
|
+
app.delete('/api/conversations/:id', (c) =>
|
|
54
|
+
store.remove(Number(c.req.param('id')))
|
|
55
|
+
? c.json({ ok: true })
|
|
56
|
+
: c.json({ error: 'No such conversation.' }, 404),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
// The answer streams as Server-Sent Events: `meta` (the conversation id), then one `token` per piece, then `done`, or `error`.
|
|
60
|
+
// The request's signal aborts when the client goes away (the Stop button, a closed tab); it is passed to the model call so the upstream request stops too.
|
|
61
|
+
app.post('/api/chat', schemaValidator('json', ChatSchema), (c) => {
|
|
62
|
+
const { message, conversation } = c.req.valid('json')
|
|
63
|
+
const known = conversation === undefined ? undefined : store.conversation(conversation)
|
|
64
|
+
if (conversation !== undefined && !known) return c.json({ error: 'No such conversation.' }, 404)
|
|
65
|
+
const id = known?.id ?? store.start(message)
|
|
66
|
+
store.add(id, 'user', message)
|
|
67
|
+
const history = store.messages(id).map(({ role, content }) => ({ role, content }))
|
|
68
|
+
const signal = c.req.raw.signal
|
|
69
|
+
return streamSSE(c, async (stream) => {
|
|
70
|
+
let answer = ''
|
|
71
|
+
await stream.writeSSE({ event: 'meta', data: JSON.stringify({ conversation: id }) })
|
|
72
|
+
try {
|
|
73
|
+
for await (const piece of llm(history, signal)) {
|
|
74
|
+
answer += piece
|
|
75
|
+
await stream.writeSSE({ event: 'token', data: JSON.stringify(piece) })
|
|
76
|
+
}
|
|
77
|
+
await stream.writeSSE({ event: 'done', data: '{}' })
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (!signal.aborted) {
|
|
80
|
+
console.error(error)
|
|
81
|
+
// The reason stays in the log; the page gets a plain message.
|
|
82
|
+
await stream.writeSSE({
|
|
83
|
+
event: 'error',
|
|
84
|
+
data: JSON.stringify('The model could not answer. Try again.'),
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
} finally {
|
|
88
|
+
// What arrived is kept, also when the reader pressed Stop.
|
|
89
|
+
if (answer !== '') store.add(id, 'assistant', answer)
|
|
90
|
+
}
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
app.route('/client', clientModules({ root: 'src/client', compiled: 'dist/client' }))
|
|
95
|
+
return app
|
|
96
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { render, useRef, useState } from '__PACKAGE__/jsx/dom'
|
|
2
|
+
|
|
3
|
+
/** Read a Server-Sent Events body: calls `on(event, data)` for each event as it arrives. (EventSource only does GET, and this is a POST.) */
|
|
4
|
+
async function readEvents(
|
|
5
|
+
body: ReadableStream<Uint8Array>,
|
|
6
|
+
on: (event: string, data: string) => void,
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
const reader = body.getReader()
|
|
9
|
+
const decoder = new TextDecoder()
|
|
10
|
+
let buffer = ''
|
|
11
|
+
for (;;) {
|
|
12
|
+
const { done, value } = await reader.read()
|
|
13
|
+
if (done) return
|
|
14
|
+
// Line endings may be CRLF; a \r at the end of a chunk is completed by the next chunk, so normalise the whole buffer.
|
|
15
|
+
buffer = (buffer + decoder.decode(value, { stream: true })).replaceAll('\r\n', '\n')
|
|
16
|
+
const blocks = buffer.split('\n\n')
|
|
17
|
+
buffer = blocks.pop() ?? ''
|
|
18
|
+
for (const block of blocks) {
|
|
19
|
+
let event = 'message'
|
|
20
|
+
const data: string[] = []
|
|
21
|
+
for (const line of block.split('\n')) {
|
|
22
|
+
if (line.startsWith('event:')) event = line.slice(6).trim()
|
|
23
|
+
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, '')) // the SSE spec strips one leading space only
|
|
24
|
+
}
|
|
25
|
+
on(event, data.join('\n'))
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const Chat = ({ start }: { start: number | undefined }) => {
|
|
31
|
+
const [text, setText] = useState('')
|
|
32
|
+
const [asked, setAsked] = useState('')
|
|
33
|
+
const [answer, setAnswer] = useState('')
|
|
34
|
+
const [error, setError] = useState('')
|
|
35
|
+
const [busy, setBusy] = useState(false)
|
|
36
|
+
const conversation = useRef<number | undefined>(start)
|
|
37
|
+
const controller = useRef<AbortController | undefined>(undefined)
|
|
38
|
+
|
|
39
|
+
const send = async (event: Event) => {
|
|
40
|
+
event.preventDefault()
|
|
41
|
+
const message = text.trim()
|
|
42
|
+
if (message === '' || busy) return
|
|
43
|
+
setAsked(message)
|
|
44
|
+
setAnswer('')
|
|
45
|
+
setError('')
|
|
46
|
+
setText('')
|
|
47
|
+
setBusy(true)
|
|
48
|
+
controller.current = new AbortController()
|
|
49
|
+
try {
|
|
50
|
+
const response = await fetch('/api/chat', {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: { 'content-type': 'application/json' },
|
|
53
|
+
body: JSON.stringify({ message, conversation: conversation.current }),
|
|
54
|
+
signal: controller.current.signal,
|
|
55
|
+
})
|
|
56
|
+
if (!response.ok || !response.body) {
|
|
57
|
+
const problem = (await response.json().catch(() => ({}))) as {
|
|
58
|
+
issues?: { message: string }[]
|
|
59
|
+
error?: string
|
|
60
|
+
}
|
|
61
|
+
setError(problem.issues?.[0]?.message ?? problem.error ?? 'The message was not accepted.')
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
let soFar = ''
|
|
65
|
+
await readEvents(response.body, (name, data) => {
|
|
66
|
+
if (name === 'meta') {
|
|
67
|
+
conversation.current = (JSON.parse(data) as { conversation: number }).conversation
|
|
68
|
+
history.replaceState(null, '', `/?c=${conversation.current}`)
|
|
69
|
+
} else if (name === 'token') {
|
|
70
|
+
soFar += JSON.parse(data) as string
|
|
71
|
+
setAnswer(soFar)
|
|
72
|
+
} else if (name === 'error') setError(JSON.parse(data) as string)
|
|
73
|
+
})
|
|
74
|
+
} catch (caught) {
|
|
75
|
+
if (!(caught instanceof DOMException && caught.name === 'AbortError'))
|
|
76
|
+
setError('The connection was lost.')
|
|
77
|
+
} finally {
|
|
78
|
+
setBusy(false)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return (
|
|
83
|
+
<div>
|
|
84
|
+
{asked !== '' && <p class="row user">{asked}</p>}
|
|
85
|
+
{answer !== '' && <p class="row">{answer}</p>}
|
|
86
|
+
{error !== '' && (
|
|
87
|
+
<p class="row error" role="alert">
|
|
88
|
+
{error}
|
|
89
|
+
</p>
|
|
90
|
+
)}
|
|
91
|
+
<form onSubmit={send}>
|
|
92
|
+
<textarea
|
|
93
|
+
rows={3}
|
|
94
|
+
value={text}
|
|
95
|
+
placeholder="Ask something"
|
|
96
|
+
onInput={(e) => setText((e.target as HTMLTextAreaElement).value)}
|
|
97
|
+
/>
|
|
98
|
+
<p>
|
|
99
|
+
<button type="submit" disabled={busy}>
|
|
100
|
+
Send
|
|
101
|
+
</button>{' '}
|
|
102
|
+
{busy && (
|
|
103
|
+
<button type="button" onClick={() => controller.current?.abort()}>
|
|
104
|
+
Stop
|
|
105
|
+
</button>
|
|
106
|
+
)}
|
|
107
|
+
</p>
|
|
108
|
+
</form>
|
|
109
|
+
</div>
|
|
110
|
+
)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const root = document.getElementById('chat')!
|
|
114
|
+
const start = root.dataset.conversation ? Number(root.dataset.conversation) : undefined
|
|
115
|
+
render(<Chat start={start} />, root)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2024",
|
|
4
|
+
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "NodeNext",
|
|
6
|
+
"moduleResolution": "NodeNext",
|
|
7
|
+
"strict": true,
|
|
8
|
+
"noEmit": true,
|
|
9
|
+
"allowImportingTsExtensions": true,
|
|
10
|
+
"jsx": "react-jsx",
|
|
11
|
+
"jsxImportSource": "__PACKAGE__/jsx/dom",
|
|
12
|
+
"types": []
|
|
13
|
+
},
|
|
14
|
+
"include": ["**/*.ts", "**/*.tsx"]
|
|
15
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
2
|
+
|
|
3
|
+
export interface Message {
|
|
4
|
+
id: number
|
|
5
|
+
conversation_id: number
|
|
6
|
+
role: 'user' | 'assistant'
|
|
7
|
+
content: string
|
|
8
|
+
}
|
|
9
|
+
export interface Conversation {
|
|
10
|
+
id: number
|
|
11
|
+
title: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function openDb(path = process.env.CHAT_DB ?? 'chat.db'): DatabaseSync {
|
|
15
|
+
const db = new DatabaseSync(path)
|
|
16
|
+
db.exec(`
|
|
17
|
+
PRAGMA foreign_keys = ON;
|
|
18
|
+
CREATE TABLE IF NOT EXISTS conversations (id INTEGER PRIMARY KEY, title TEXT NOT NULL, created_at TEXT NOT NULL);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
20
|
+
id INTEGER PRIMARY KEY,
|
|
21
|
+
conversation_id INTEGER NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
|
22
|
+
role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
|
|
23
|
+
content TEXT NOT NULL
|
|
24
|
+
);
|
|
25
|
+
`)
|
|
26
|
+
return db
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function chatStore(db: DatabaseSync) {
|
|
30
|
+
return {
|
|
31
|
+
conversations: () =>
|
|
32
|
+
db
|
|
33
|
+
.prepare('SELECT id, title FROM conversations ORDER BY id DESC')
|
|
34
|
+
.all() as unknown as Conversation[],
|
|
35
|
+
conversation: (id: number) =>
|
|
36
|
+
db.prepare('SELECT id, title FROM conversations WHERE id = ?').get(id) as unknown as
|
|
37
|
+
| Conversation
|
|
38
|
+
| undefined,
|
|
39
|
+
messages: (id: number) =>
|
|
40
|
+
db
|
|
41
|
+
.prepare('SELECT * FROM messages WHERE conversation_id = ? ORDER BY id')
|
|
42
|
+
.all(id) as unknown as Message[],
|
|
43
|
+
start(title: string): number {
|
|
44
|
+
const info = db
|
|
45
|
+
.prepare('INSERT INTO conversations (title, created_at) VALUES (?, ?)')
|
|
46
|
+
.run(title.slice(0, 60), new Date().toISOString())
|
|
47
|
+
return Number(info.lastInsertRowid)
|
|
48
|
+
},
|
|
49
|
+
add(conversationId: number, role: Message['role'], content: string) {
|
|
50
|
+
db.prepare('INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)').run(
|
|
51
|
+
conversationId,
|
|
52
|
+
role,
|
|
53
|
+
content,
|
|
54
|
+
)
|
|
55
|
+
},
|
|
56
|
+
remove: (id: number) =>
|
|
57
|
+
Number(db.prepare('DELETE FROM conversations WHERE id = ?').run(id).changes) > 0,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { serve } from '__PACKAGE__/node-server'
|
|
2
|
+
import app, { db } from './app.ts'
|
|
3
|
+
|
|
4
|
+
const port = Number(process.env.PORT || 3000)
|
|
5
|
+
// Local by default. Behind a reverse proxy on the same machine this is right; in a container set HOST=0.0.0.0.
|
|
6
|
+
const hostname = process.env.HOST || '127.0.0.1'
|
|
7
|
+
|
|
8
|
+
const server = serve({ fetch: app.fetch, port, hostname }, (info) => {
|
|
9
|
+
console.log(`listening on http://${info.address}:${info.port}`)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
// Stop taking requests, let the ones in flight finish, then exit. A connection that never ends cannot keep the process alive past 10 seconds.
|
|
13
|
+
function shutdown(): void {
|
|
14
|
+
server.close(() => {
|
|
15
|
+
db.close()
|
|
16
|
+
process.exit(0)
|
|
17
|
+
})
|
|
18
|
+
server.closeIdleConnections()
|
|
19
|
+
setTimeout(() => process.exit(1), 10_000).unref()
|
|
20
|
+
}
|
|
21
|
+
process.once('SIGINT', shutdown)
|
|
22
|
+
process.once('SIGTERM', shutdown)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** What the app needs from a language model: the conversation so far in, the answer out piece by piece. Aborting the signal must stop the work. */
|
|
2
|
+
export type Llm = (
|
|
3
|
+
messages: { role: string; content: string }[],
|
|
4
|
+
signal: AbortSignal,
|
|
5
|
+
) => AsyncIterable<string>
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* An OpenAI-compatible chat completions API with `stream: true` (DeepSeek by default). The key is read from DEEPSEEK_API_KEY at the moment of the call and
|
|
9
|
+
* is never stored; DEEPSEEK_BASE_URL and DEEPSEEK_MODEL choose the service.
|
|
10
|
+
*/
|
|
11
|
+
export const openAiCompatible: Llm = async function* (messages, signal) {
|
|
12
|
+
const key = process.env.DEEPSEEK_API_KEY
|
|
13
|
+
if (!key) throw new Error('DEEPSEEK_API_KEY is not set')
|
|
14
|
+
const base = (process.env.DEEPSEEK_BASE_URL ?? 'https://api.deepseek.com').replace(/\/$/, '')
|
|
15
|
+
const response = await fetch(`${base}/chat/completions`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
18
|
+
body: JSON.stringify({
|
|
19
|
+
model: process.env.DEEPSEEK_MODEL ?? 'deepseek-chat',
|
|
20
|
+
messages,
|
|
21
|
+
stream: true,
|
|
22
|
+
}),
|
|
23
|
+
signal,
|
|
24
|
+
})
|
|
25
|
+
if (!response.ok || !response.body)
|
|
26
|
+
throw new Error(`the model service answered ${response.status}`)
|
|
27
|
+
const decoder = new TextDecoder()
|
|
28
|
+
let buffer = ''
|
|
29
|
+
for await (const chunk of response.body) {
|
|
30
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
31
|
+
const lines = buffer.split('\n')
|
|
32
|
+
buffer = lines.pop() ?? ''
|
|
33
|
+
for (const line of lines) {
|
|
34
|
+
if (!line.startsWith('data:')) continue
|
|
35
|
+
const data = line.slice(5).trim()
|
|
36
|
+
if (data === '[DONE]') return
|
|
37
|
+
const piece = (JSON.parse(data) as { choices?: { delta?: { content?: string } }[] })
|
|
38
|
+
.choices?.[0]?.delta?.content
|
|
39
|
+
if (piece) yield piece
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Conversation, Message } from './db.ts'
|
|
2
|
+
|
|
3
|
+
export const chatPage = (
|
|
4
|
+
conversations: Conversation[],
|
|
5
|
+
current: Conversation | undefined,
|
|
6
|
+
messages: Message[],
|
|
7
|
+
): string =>
|
|
8
|
+
(
|
|
9
|
+
<html lang="en">
|
|
10
|
+
<head>
|
|
11
|
+
<meta charset="utf-8" />
|
|
12
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
13
|
+
<title>Chat</title>
|
|
14
|
+
<style
|
|
15
|
+
dangerouslySetInnerHTML={{
|
|
16
|
+
__html:
|
|
17
|
+
'body{font:16px system-ui;max-width:48rem;margin:2rem auto;padding:0 1rem}.row{white-space:pre-wrap;margin:.75rem 0}.user{font-weight:600}.error{color:#b00020}textarea{width:100%;box-sizing:border-box;padding:.5rem}nav a{margin-right:.75rem}',
|
|
18
|
+
}}
|
|
19
|
+
/>
|
|
20
|
+
</head>
|
|
21
|
+
<body>
|
|
22
|
+
<h1>Chat</h1>
|
|
23
|
+
<nav>
|
|
24
|
+
<a href="/">New chat</a>
|
|
25
|
+
{conversations.map((c) => (
|
|
26
|
+
<a href={`/?c=${c.id}`}>{c.title}</a>
|
|
27
|
+
))}
|
|
28
|
+
</nav>
|
|
29
|
+
<div id="log">
|
|
30
|
+
{messages.map((m) => (
|
|
31
|
+
<p class={`row ${m.role}`}>{m.content}</p>
|
|
32
|
+
))}
|
|
33
|
+
</div>
|
|
34
|
+
<div id="chat" data-conversation={current ? String(current.id) : ''} />
|
|
35
|
+
<script type="module" src="/client/chat.tsx" />
|
|
36
|
+
</body>
|
|
37
|
+
</html>
|
|
38
|
+
).toString()
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { test } from 'node:test'
|
|
3
|
+
import { createApp } from '../src/chat-app.ts'
|
|
4
|
+
import { openDb } from '../src/db.ts'
|
|
5
|
+
import type { Llm } from '../src/llm.ts'
|
|
6
|
+
|
|
7
|
+
/** A model that answers with fixed pieces and records what it was asked. */
|
|
8
|
+
function mock(pieces: string[]) {
|
|
9
|
+
const asked: { role: string; content: string }[][] = []
|
|
10
|
+
const llm: Llm = async function* (messages) {
|
|
11
|
+
asked.push(messages)
|
|
12
|
+
for (const piece of pieces) yield piece
|
|
13
|
+
}
|
|
14
|
+
return { llm, asked }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const post = (body: unknown): RequestInit => ({
|
|
18
|
+
method: 'POST',
|
|
19
|
+
headers: { 'content-type': 'application/json' },
|
|
20
|
+
body: JSON.stringify(body),
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
/** Parse a Server-Sent Events body into [event, data] pairs. */
|
|
24
|
+
function events(text: string): [string, string][] {
|
|
25
|
+
return text
|
|
26
|
+
.split('\n\n')
|
|
27
|
+
.filter(Boolean)
|
|
28
|
+
.map((block) => {
|
|
29
|
+
const event = /^event: (.*)$/m.exec(block)?.[1] ?? 'message'
|
|
30
|
+
const data = /^data: (.*)$/m.exec(block)?.[1] ?? ''
|
|
31
|
+
return [event, data]
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
test('the answer streams as events: meta, one token per piece, done', async () => {
|
|
36
|
+
const { llm } = mock(['Hel', 'lo ', 'there\nline'])
|
|
37
|
+
const app = createApp(openDb(':memory:'), llm)
|
|
38
|
+
const res = await app.request('/api/chat', post({ message: 'hi' }))
|
|
39
|
+
assert.equal(res.status, 200)
|
|
40
|
+
assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/)
|
|
41
|
+
const got = events(await res.text())
|
|
42
|
+
assert.deepEqual(
|
|
43
|
+
got.map(([e]) => e),
|
|
44
|
+
['meta', 'token', 'token', 'token', 'done'],
|
|
45
|
+
)
|
|
46
|
+
assert.equal(
|
|
47
|
+
got
|
|
48
|
+
.filter(([e]) => e === 'token')
|
|
49
|
+
.map(([, d]) => JSON.parse(d) as string)
|
|
50
|
+
.join(''),
|
|
51
|
+
'Hello there\nline',
|
|
52
|
+
)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('history is stored, sent back to the model, and listed', async () => {
|
|
56
|
+
const { llm, asked } = mock(['ok'])
|
|
57
|
+
const app = createApp(openDb(':memory:'), llm)
|
|
58
|
+
const first = events(
|
|
59
|
+
await (await app.request('/api/chat', post({ message: 'first question' }))).text(),
|
|
60
|
+
)
|
|
61
|
+
const id = (JSON.parse(first[0]![1]) as { conversation: number }).conversation
|
|
62
|
+
await (await app.request('/api/chat', post({ message: 'second', conversation: id }))).text()
|
|
63
|
+
assert.deepEqual(
|
|
64
|
+
asked[1]?.map((m) => m.content),
|
|
65
|
+
['first question', 'ok', 'second'],
|
|
66
|
+
)
|
|
67
|
+
const one = (await (await app.request(`/api/conversations/${id}`)).json()) as {
|
|
68
|
+
messages: { role: string }[]
|
|
69
|
+
}
|
|
70
|
+
assert.deepEqual(
|
|
71
|
+
one.messages.map((m) => m.role),
|
|
72
|
+
['user', 'assistant', 'user', 'assistant'],
|
|
73
|
+
)
|
|
74
|
+
const list = (await (await app.request('/api/conversations')).json()) as {
|
|
75
|
+
conversations: { title: string }[]
|
|
76
|
+
}
|
|
77
|
+
assert.equal(list.conversations[0]?.title, 'first question')
|
|
78
|
+
const page = await (await app.request(`/?c=${id}`)).text()
|
|
79
|
+
assert.match(page, /first question/)
|
|
80
|
+
assert.match(page, /src="\/client\/chat\.tsx"/)
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
test('a bad message answers 400 with a message, an unknown conversation 404, and nothing reaches the model', async () => {
|
|
84
|
+
const { llm, asked } = mock(['x'])
|
|
85
|
+
const app = createApp(openDb(':memory:'), llm)
|
|
86
|
+
const empty = await app.request('/api/chat', post({ message: ' ' }))
|
|
87
|
+
assert.equal(empty.status, 400)
|
|
88
|
+
assert.match(JSON.stringify(await empty.json()), /Write a message/)
|
|
89
|
+
assert.equal(
|
|
90
|
+
(await app.request('/api/chat', post({ message: 'hi', conversation: 99 }))).status,
|
|
91
|
+
404,
|
|
92
|
+
)
|
|
93
|
+
assert.equal(asked.length, 0)
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
test('a conversation can be deleted', async () => {
|
|
97
|
+
const app = createApp(openDb(':memory:'), mock(['a']).llm)
|
|
98
|
+
const first = events(await (await app.request('/api/chat', post({ message: 'hi' }))).text())
|
|
99
|
+
const id = (JSON.parse(first[0]![1]) as { conversation: number }).conversation
|
|
100
|
+
assert.equal((await app.request(`/api/conversations/${id}`, { method: 'DELETE' })).status, 200)
|
|
101
|
+
assert.equal((await app.request(`/api/conversations/${id}`)).status, 404)
|
|
102
|
+
assert.equal((await app.request(`/api/conversations/${id}`, { method: 'DELETE' })).status, 404)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('a failing model sends an error event with a plain message and no detail', async () => {
|
|
106
|
+
const llm: Llm = async function* () {
|
|
107
|
+
yield 'partial '
|
|
108
|
+
throw new Error('upstream secret detail')
|
|
109
|
+
}
|
|
110
|
+
const app = createApp(openDb(':memory:'), llm)
|
|
111
|
+
const text = await (await app.request('/api/chat', post({ message: 'hi' }))).text()
|
|
112
|
+
assert.doesNotMatch(text, /secret detail/)
|
|
113
|
+
const last = events(text).at(-1)
|
|
114
|
+
assert.equal(last?.[0], 'error')
|
|
115
|
+
assert.match(last?.[1] ?? '', /could not answer/)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
test('when the client goes away the model call is aborted and what arrived is kept', async () => {
|
|
119
|
+
let sawAbort: (value: boolean) => void = () => {}
|
|
120
|
+
const aborted = new Promise<boolean>((resolve) => {
|
|
121
|
+
sawAbort = resolve
|
|
122
|
+
})
|
|
123
|
+
const llm: Llm = async function* (_messages, signal) {
|
|
124
|
+
yield 'first '
|
|
125
|
+
// The signal may already be aborted by the time the model is asked for more: an abort event that has fired does not fire again.
|
|
126
|
+
if (!signal.aborted)
|
|
127
|
+
await new Promise<void>((resolve) =>
|
|
128
|
+
signal.addEventListener('abort', () => resolve(), { once: true }),
|
|
129
|
+
)
|
|
130
|
+
sawAbort(signal.aborted)
|
|
131
|
+
if (signal.aborted) throw new DOMException('aborted', 'AbortError')
|
|
132
|
+
yield 'never sent'
|
|
133
|
+
}
|
|
134
|
+
const db = openDb(':memory:')
|
|
135
|
+
const app = createApp(db, llm)
|
|
136
|
+
const controller = new AbortController()
|
|
137
|
+
const res = await app.request('/api/chat', {
|
|
138
|
+
...post({ message: 'hi' }),
|
|
139
|
+
signal: controller.signal,
|
|
140
|
+
})
|
|
141
|
+
const reader = res.body!.getReader()
|
|
142
|
+
const decoder = new TextDecoder()
|
|
143
|
+
let seen = ''
|
|
144
|
+
while (!seen.includes('first')) seen += decoder.decode((await reader.read()).value)
|
|
145
|
+
controller.abort()
|
|
146
|
+
assert.equal(await aborted, true)
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
148
|
+
const rows = db.prepare('SELECT role, content FROM messages ORDER BY id').all()
|
|
149
|
+
assert.deepEqual(
|
|
150
|
+
rows.map((r) => `${r.role}:${r.content}`),
|
|
151
|
+
['user:hi', 'assistant:first '],
|
|
152
|
+
)
|
|
153
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { once } from 'node:events'
|
|
4
|
+
import { mkdtempSync } from 'node:fs'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { test } from 'node:test'
|
|
8
|
+
|
|
9
|
+
/** Start `src/index.ts` the way `npm start` does, on a port the system chooses, and read the address it prints. */
|
|
10
|
+
async function start(env: Record<string, string> = {}) {
|
|
11
|
+
const child = spawn(
|
|
12
|
+
process.execPath,
|
|
13
|
+
['--import', '__PACKAGE__/node-server/register', 'src/index.ts'],
|
|
14
|
+
{
|
|
15
|
+
env: {
|
|
16
|
+
...process.env,
|
|
17
|
+
PORT: '0',
|
|
18
|
+
CHAT_DB: join(mkdtempSync(join(tmpdir(), 'chat-')), 'chat.db'),
|
|
19
|
+
...env,
|
|
20
|
+
},
|
|
21
|
+
stdio: ['ignore', 'pipe', 'inherit'],
|
|
22
|
+
},
|
|
23
|
+
)
|
|
24
|
+
let out = ''
|
|
25
|
+
const address = await new Promise<string>((resolve, reject) => {
|
|
26
|
+
child.once('exit', (code) =>
|
|
27
|
+
reject(new Error(`the server exited with ${code} before it listened`)),
|
|
28
|
+
)
|
|
29
|
+
child.stdout.on('data', (chunk) => {
|
|
30
|
+
out += chunk
|
|
31
|
+
const match = /listening on (http:\/\/\S+)/.exec(out)
|
|
32
|
+
if (match?.[1]) resolve(match[1])
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
return { child, address }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test('the server listens on 127.0.0.1 unless HOST says otherwise', async () => {
|
|
39
|
+
const { child, address } = await start()
|
|
40
|
+
try {
|
|
41
|
+
assert.match(address, /^http:\/\/127\.0\.0\.1:\d+$/)
|
|
42
|
+
} finally {
|
|
43
|
+
child.kill('SIGTERM')
|
|
44
|
+
await once(child, 'exit')
|
|
45
|
+
}
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
|
49
|
+
test(`${signal} stops the server cleanly and frees the port`, async () => {
|
|
50
|
+
const { child, address } = await start()
|
|
51
|
+
assert.equal((await fetch(`${address}/`)).status, 200)
|
|
52
|
+
const started = Date.now()
|
|
53
|
+
child.kill(signal)
|
|
54
|
+
const [code] = await once(child, 'exit')
|
|
55
|
+
assert.equal(code, 0)
|
|
56
|
+
assert.ok(Date.now() - started < 5000, 'the server took too long to stop')
|
|
57
|
+
await assert.rejects(fetch(address), 'the port should be free')
|
|
58
|
+
})
|
|
59
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2024",
|
|
4
|
+
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "NodeNext",
|
|
6
|
+
"moduleResolution": "NodeNext",
|
|
7
|
+
"strict": true,
|
|
8
|
+
"verbatimModuleSyntax": true,
|
|
9
|
+
"erasableSyntaxOnly": true,
|
|
10
|
+
"allowImportingTsExtensions": true,
|
|
11
|
+
"noEmit": true,
|
|
12
|
+
"skipLibCheck": true,
|
|
13
|
+
"types": ["node"],
|
|
14
|
+
"jsx": "react-jsx",
|
|
15
|
+
"jsxImportSource": "__PACKAGE__/jsx"
|
|
16
|
+
},
|
|
17
|
+
"include": ["src", "test"],
|
|
18
|
+
"exclude": ["src/client"]
|
|
19
|
+
}
|