create-acrylblends 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +10 -0
  2. package/dist/index.d.ts +15 -0
  3. package/dist/index.js +287 -14
  4. package/dist/index.js.map +1 -1
  5. package/docs/framework/README.md +6 -4
  6. package/docs/framework/UPSTREAM.md +1 -1
  7. package/docs/framework/getting-started/aws-lambda.md +115 -0
  8. package/docs/framework/getting-started/bun.md +1 -3
  9. package/docs/framework/getting-started/cloudflare-pages.md +53 -0
  10. package/docs/framework/getting-started/cloudflare-workers.md +67 -0
  11. package/docs/framework/getting-started/deploy.md +5 -5
  12. package/docs/framework/getting-started/lambda-edge.md +41 -0
  13. package/docs/framework/getting-started/netlify.md +25 -0
  14. package/docs/framework/getting-started/other-runtimes.md +20 -9
  15. package/docs/framework/getting-started/service-worker.md +33 -0
  16. package/docs/framework/getting-started/vercel.md +28 -0
  17. package/docs/framework/guides/create-acrylblends.md +40 -2
  18. package/docs/framework/guides/data.md +202 -0
  19. package/docs/framework/guides/faq.md +2 -2
  20. package/docs/framework/guides/forms-and-sessions.md +34 -30
  21. package/docs/framework/helpers/conninfo.md +1 -1
  22. package/docs/framework/helpers/ssg.md +1 -1
  23. package/docs/framework/helpers/streaming.md +3 -2
  24. package/docs/framework/helpers/websocket.md +2 -2
  25. package/docs/framework/middleware/builtin/ip-restriction.md +1 -1
  26. package/docs/framework/upstream.json +3 -3
  27. package/package.json +3 -2
  28. package/templates/chat/gitignore +3 -2
  29. package/templates/chat/migrations/001-chat.sql +12 -0
  30. package/templates/chat/src/app.ts +4 -2
  31. package/templates/chat/src/chat-app.ts +22 -18
  32. package/templates/chat/src/db.ts +30 -36
  33. package/templates/chat/src/index.ts +9 -4
  34. package/templates/chat/test/chat.test.ts +21 -9
  35. package/templates/chat/test/server.test.ts +1 -1
  36. package/templates/notes/gitignore +3 -2
  37. package/templates/notes/migrations/001-notes.sql +18 -0
  38. package/templates/notes/src/app.ts +4 -3
  39. package/templates/notes/src/auth.ts +21 -19
  40. package/templates/notes/src/db.ts +40 -50
  41. package/templates/notes/src/index.ts +9 -4
  42. package/templates/notes/src/notes-app.ts +35 -29
  43. package/templates/notes/test/notes.test.ts +27 -20
  44. package/templates/notes/test/server.test.ts +1 -1
package/README.md CHANGED
@@ -74,3 +74,13 @@ MIT license.
74
74
  - a live character counter and an instant filter written as a small script in the page. When the client components of `acrylblends/jsx/dom` can be served without a bundler (planned for 0.7.2), they will replace that script here.
75
75
 
76
76
  `npx acrylblends add desktop` followed by `npm install` and `npm run desktop` runs it as a desktop window (see `docs/framework/getting-started/desktop.md`).
77
+
78
+ ## Templates from a repository or a package
79
+
80
+ ```sh
81
+ npm create acrylblends@latest my-app github:owner/repo[#ref]
82
+ npm create acrylblends@latest my-app @scope/name[@version]
83
+ npm create acrylblends@latest my-app ./template.tgz
84
+ ```
85
+
86
+ The source is downloaded as a tarball (never cloned) or packed with `npm pack --ignore-scripts`, unpacked, and read: it must hold an `acryl.template.json` (`name`, `description`, optional `plugins`), it is checked for secrets, and only then is the folder created. Nothing of the template is installed or run; if its `package.json` defines install scripts they are listed, and `--install` prints what will run before it runs. See the create-acrylblends guide in `docs/framework/guides/`.
package/dist/index.d.ts CHANGED
@@ -6,6 +6,17 @@
6
6
  export declare const PACKAGE = "acrylblends";
7
7
  export declare const CLASS = "Acryl";
8
8
  export declare const CREATE = "create-acrylblends";
9
+ /** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */
10
+ export declare const TEMPLATE_MANIFEST = "acryl.template.json";
11
+ //#endregion
12
+ //#region src/source.d.ts
13
+ /** How the bytes of a source are obtained; real by default, replaced in tests. */
14
+ interface Fetchers {
15
+ /** The body at a URL (a GitHub tarball). */
16
+ download(url: string): Promise<Uint8Array>;
17
+ /** `npm pack <spec> --ignore-scripts` into `dest`; the path of the tarball. */
18
+ pack(spec: string, dest: string): string;
19
+ }
9
20
  //#endregion
10
21
  //#region src/index.d.ts
11
22
  export declare const TEMPLATES: readonly ["nodejs", "notes", "chat", "bun", "acryl-app"];
@@ -32,6 +43,8 @@ export interface Io {
32
43
  ask: ((question: string) => Promise<string>) | undefined;
33
44
  /** Run a program, showing its output; resolves to the exit code. */
34
45
  run(command: string, args: string[], cwd: string): Promise<number>;
46
+ /** How a template source is fetched; the real network and npm by default. */
47
+ fetchers?: Fetchers;
35
48
  }
36
49
  export declare function processIo(): Io;
37
50
  export interface CreateOptions {
@@ -40,6 +53,8 @@ export interface CreateOptions {
40
53
  install: boolean;
41
54
  pm: PackageManager | undefined;
42
55
  yes: boolean;
56
+ /** `github:owner/repo[#ref]`, `@scope/name` or a packed `.tgz`: a template from outside this package. */
57
+ source: string | undefined;
43
58
  }
44
59
  export declare function isTemplate(value: string): value is Template;
45
60
  export declare function parseCreateOptions(argv: readonly string[]): CreateOptions;
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
- import { spawn } from "node:child_process";
3
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
4
5
  import { basename, dirname, join, resolve } from "node:path";
5
6
  import { createInterface } from "node:readline/promises";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { parseArgs } from "node:util";
9
+ import { findSecrets } from "@webboxes/app-persistence";
8
10
  //#region src/names.ts
9
11
  /**
10
12
  * 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
@@ -13,6 +15,195 @@ import { parseArgs } from "node:util";
13
15
  const PACKAGE = "acrylblends";
14
16
  const CLASS = "Acryl";
15
17
  const CREATE = "create-acrylblends";
18
+ /** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */
19
+ const TEMPLATE_MANIFEST = "acryl.template.json";
20
+ //#endregion
21
+ //#region src/source.ts
22
+ /**
23
+ * Templates from outside this package: `github:owner/repo[#ref]`, a scoped npm package (`@scope/name[@version]`) or a packed tarball on disk.
24
+ * A source is only ever downloaded and unpacked: no git clone (hooks), no lifecycle script (`npm pack --ignore-scripts`), nothing of it is run.
25
+ */
26
+ /** A source that cannot be used; the message says why and is shown as it is. */
27
+ var SourceError = class extends Error {
28
+ name = "SourceError";
29
+ };
30
+ const SOURCE_FORMS = `github:owner/repo[#ref], @scope/name[@version], or a packed .tgz file`;
31
+ const LIMITS = {
32
+ files: 5e3,
33
+ bytes: 52428800
34
+ };
35
+ /** Recognise a source argument, or return `undefined` when it is not one (so the caller can report a usage error). */
36
+ function parseSource(text, cwd) {
37
+ const github = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:#([A-Za-z0-9_./-]+))?$/.exec(text);
38
+ if (github) return {
39
+ kind: "github",
40
+ owner: github[1],
41
+ repo: github[2],
42
+ ref: github[3]
43
+ };
44
+ if (text.startsWith("github:")) throw new SourceError(`"${text}" is not github:owner/repo[#ref]`);
45
+ if (/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9._-]+)?$/.test(text)) return {
46
+ kind: "npm",
47
+ spec: text
48
+ };
49
+ if (text.startsWith("@")) throw new SourceError(`"${text}" is not @scope/name[@version]`);
50
+ if (/\.(tgz|tar\.gz)$/.test(text)) {
51
+ const path = resolve(cwd, text);
52
+ if (!existsSync(path)) throw new SourceError(`${path} does not exist`);
53
+ return {
54
+ kind: "tarball",
55
+ path
56
+ };
57
+ }
58
+ }
59
+ const realFetchers = {
60
+ async download(url) {
61
+ const response = await fetch(url, { redirect: "follow" });
62
+ if (!response.ok) throw new SourceError(`${url} answered ${response.status}`);
63
+ return new Uint8Array(await response.arrayBuffer());
64
+ },
65
+ pack(spec, dest) {
66
+ const result = spawnSync("npm", [
67
+ "pack",
68
+ spec,
69
+ "--ignore-scripts",
70
+ "--json",
71
+ "--pack-destination",
72
+ dest
73
+ ], {
74
+ encoding: "utf8",
75
+ shell: false,
76
+ env: {
77
+ ...process.env,
78
+ npm_config_ignore_scripts: "true"
79
+ }
80
+ });
81
+ if (result.status !== 0) throw new SourceError(`npm could not pack ${spec}: ${(result.stderr || result.stdout).trim().split("\n").at(-1)}`);
82
+ const file = JSON.parse(result.stdout)[0]?.filename;
83
+ if (!file) throw new SourceError(`npm packed nothing for ${spec}`);
84
+ return join(dest, file);
85
+ }
86
+ };
87
+ /** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives that are too big. */
88
+ function extract(tarball, dir) {
89
+ const list = spawnSync("tar", ["-tzf", tarball], {
90
+ encoding: "utf8",
91
+ maxBuffer: 67108864
92
+ });
93
+ if (list.status !== 0) throw new SourceError(`${tarball} is not a readable tar.gz archive`);
94
+ const entries = list.stdout.split("\n").filter(Boolean);
95
+ if (entries.length > LIMITS.files) throw new SourceError(`the template has more than ${LIMITS.files} files`);
96
+ for (const entry of entries) if (entry.startsWith("/") || entry.split("/").includes("..")) throw new SourceError(`the archive holds a path that leaves its folder: ${entry}`);
97
+ mkdirSync(dir, { recursive: true });
98
+ const run = spawnSync("tar", [
99
+ "-xzf",
100
+ tarball,
101
+ "-C",
102
+ dir,
103
+ "--strip-components=1"
104
+ ], { encoding: "utf8" });
105
+ if (run.status !== 0) throw new SourceError(`could not unpack ${tarball}: ${run.stderr.trim()}`);
106
+ let bytes = 0;
107
+ const walk = (folder) => {
108
+ for (const entry of readdirSync(folder)) {
109
+ const path = join(folder, entry);
110
+ const info = lstatSync(path);
111
+ if (info.isSymbolicLink()) throw new SourceError(`the template holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`);
112
+ if (info.isDirectory()) walk(path);
113
+ else bytes += info.size;
114
+ }
115
+ };
116
+ walk(dir);
117
+ if (bytes > LIMITS.bytes) throw new SourceError(`the template is larger than ${LIMITS.bytes / 1024 / 1024} MB`);
118
+ }
119
+ /** Download or pack a source and unpack it into `dir` (which must not exist yet). Nothing in it is run. */
120
+ async function fetchSource(source, dir, scratch, fetchers) {
121
+ mkdirSync(scratch, { recursive: true });
122
+ let tarball;
123
+ if (source.kind === "tarball") tarball = source.path;
124
+ else if (source.kind === "npm") tarball = fetchers.pack(source.spec, scratch);
125
+ else {
126
+ tarball = join(scratch, "source.tar.gz");
127
+ writeFileSync(tarball, await fetchers.download(`https://codeload.github.com/${source.owner}/${source.repo}/tar.gz/${source.ref ?? "HEAD"}`));
128
+ }
129
+ extract(tarball, dir);
130
+ }
131
+ /** Read and check `acryl.template.json`; a source without it is not a template. */
132
+ function readManifest(dir) {
133
+ const file = join(dir, TEMPLATE_MANIFEST);
134
+ if (!existsSync(file)) throw new SourceError(`this source has no ${TEMPLATE_MANIFEST}, so it is not a template: add one with a name and a description (see the create-acrylblends guide)`);
135
+ let data;
136
+ try {
137
+ data = JSON.parse(readFileSync(file, "utf8"));
138
+ } catch {
139
+ throw new SourceError(`${TEMPLATE_MANIFEST} is not valid JSON`);
140
+ }
141
+ const m = data;
142
+ if (typeof m.name !== "string" || m.name.trim() === "") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "name"`);
143
+ if (typeof m.description !== "string") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "description"`);
144
+ const plugins = m.plugins ?? [];
145
+ if (!Array.isArray(plugins) || plugins.some((p) => typeof p !== "string" || !/^[a-z][a-z0-9-]*$/.test(p))) throw new SourceError(`"plugins" in ${TEMPLATE_MANIFEST} is a list of plugin names such as "desktop"`);
146
+ return {
147
+ name: m.name,
148
+ description: m.description,
149
+ plugins
150
+ };
151
+ }
152
+ const SKIP = /* @__PURE__ */ new Set([
153
+ ".git",
154
+ "node_modules",
155
+ TEMPLATE_MANIFEST
156
+ ]);
157
+ /** Lifecycle scripts npm runs on `npm install` in the app's own folder. */
158
+ const LIFECYCLE = [
159
+ "preinstall",
160
+ "install",
161
+ "postinstall",
162
+ "prepublish",
163
+ "preprepare",
164
+ "prepare",
165
+ "postprepare"
166
+ ];
167
+ const isText = (buffer) => !buffer.subarray(0, 8e3).includes(0);
168
+ /**
169
+ * Copy the unpacked template into `target`, replacing the placeholders of the built-in templates, naming the app, and pointing a dependency on the framework at
170
+ * the release this package carries. Returns the files written (relative paths) and the lifecycle scripts the app's package.json defines.
171
+ */
172
+ function writeTemplate(from, target, stamp, range, name) {
173
+ const files = [];
174
+ const walk = (src, dst, prefix) => {
175
+ mkdirSync(dst, { recursive: true });
176
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
177
+ if (SKIP.has(entry.name)) continue;
178
+ const outName = prefix === "" && entry.name === "gitignore" ? ".gitignore" : entry.name;
179
+ if (entry.isDirectory()) walk(join(src, entry.name), join(dst, outName), `${prefix}${entry.name}/`);
180
+ else {
181
+ const buffer = readFileSync(join(src, entry.name));
182
+ writeFileSync(join(dst, outName), isText(buffer) ? stamp(buffer.toString("utf8")) : buffer);
183
+ files.push(`${prefix}${outName}`);
184
+ }
185
+ }
186
+ };
187
+ walk(from, target, "");
188
+ const lifecycle = {};
189
+ const pkgFile = join(target, "package.json");
190
+ if (existsSync(pkgFile)) {
191
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
192
+ pkg.name = name;
193
+ for (const group of [pkg.dependencies, pkg.devDependencies]) if (group?.["acrylblends"] !== void 0) group[PACKAGE] = range;
194
+ writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
195
+ for (const script of LIFECYCLE) if (typeof pkg.scripts?.[script] === "string") lifecycle[script] = pkg.scripts[script];
196
+ }
197
+ return {
198
+ files,
199
+ lifecycle
200
+ };
201
+ }
202
+ /** Remove a folder tree quietly. */
203
+ const removeTree = (path) => rmSync(path, {
204
+ recursive: true,
205
+ force: true
206
+ });
16
207
  //#endregion
17
208
  //#region src/spawn.ts
18
209
  /**
@@ -64,11 +255,17 @@ const VERSION = createRequire(import.meta.url)("../package.json").version;
64
255
  const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app
65
256
 
66
257
  Usage:
67
- npm create ${PACKAGE}@latest [directory] [-- options]
258
+ npm create ${PACKAGE}@latest [directory] [source] [-- options]
259
+
260
+ A source makes the app from someone else's template (it is downloaded and unpacked, nothing in it runs):
261
+ github:owner/repo[#ref] a GitHub repository, as a tarball (no clone)
262
+ @scope/name[@version] an npm package (npm pack --ignore-scripts)
263
+ ./template.tgz a packed template on disk
264
+ A template is a folder with an ${TEMPLATE_MANIFEST} (name, description, plugins).
68
265
 
69
266
  Options:
70
267
  --template <name> nodejs, notes, chat, bun (experimental), acryl-app (asked when not given)
71
- --install install the dependencies after creating the app
268
+ --install install the dependencies after creating the app (the lifecycle scripts it will run are listed first)
72
269
  --pm <manager> ${PACKAGE_MANAGERS.join(", ")} (default: the one that ran this command, else npm)
73
270
  -y, --yes ask nothing: template nodejs unless --template is given, directory ${PACKAGE}-app
74
271
  -h, --help show this help
@@ -118,7 +315,8 @@ function parseCreateOptions(argv) {
118
315
  throw new UsageError(error.message);
119
316
  }
120
317
  const { values, positionals } = parsed;
121
- if (positionals.length > 1) throw new UsageError("takes at most one directory");
318
+ if (positionals.length > 2) throw new UsageError("takes a directory and at most one template source");
319
+ if (positionals[1] !== void 0 && values.template !== void 0) throw new UsageError("give a template source or --template, not both");
122
320
  if (values.template !== void 0 && !isTemplate(values.template)) throw new UsageError(`unknown template "${values.template}" (${TEMPLATES.join(", ")})`);
123
321
  if (values.pm !== void 0 && !PACKAGE_MANAGERS.includes(values.pm)) throw new UsageError(`unknown package manager "${values.pm}" (${PACKAGE_MANAGERS.join(", ")})`);
124
322
  return {
@@ -126,7 +324,8 @@ function parseCreateOptions(argv) {
126
324
  template: values.template,
127
325
  install: values.install === true,
128
326
  pm: values.pm,
129
- yes: values.yes === true
327
+ yes: values.yes === true,
328
+ source: positionals[1]
130
329
  };
131
330
  }
132
331
  const parse = (argv) => parseArgs({
@@ -205,15 +404,16 @@ so test a route with \`await app.request('/path')\` and no server.${desktopNote}
205
404
  ${template === "notes" ? `
206
405
  ## Structure (a notes app: accounts, sessions, a database)
207
406
 
208
- - \`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.
407
+ - \`src/db.ts\`: \`openNotesDb()\` (the \`db\` port on a SQLite file, \`data/notes.sqlite\` or \`$NOTES_DB\`, with \`migrations/\` applied on start; it returns \`{ db, close }\`) and \`notesStore(db)\`, the queries for notes. Every \`db\` call returns a promise: \`await\` it. Use \`?\` bindings, never string-built SQL. See \`docs/framework/guides/data.md\`.
408
+ - \`migrations/\`: the shape of the database, one numbered file per change (\`001-notes.sql\`). A file that has run is never edited; a change is the next file (\`002-name.sql\`).
209
409
  - \`src/auth.ts\`: scrypt password hashes (\`node:crypto\`) and the \`sessions\` table; the cookie \`sid\` holds a random token.
210
410
  - \`src/schema.ts\`: the rules for a note and for credentials. The HTML forms and the JSON API both use \`checkNote\`.
211
411
  - \`src/views.tsx\`: the pages, as JSX components rendered to strings, and the small script for the instant filter.
212
412
  - \`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\`.
213
- - \`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:'))\`.
413
+ - \`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\` opens the database (top-level \`await\`) and exports the app and \`close\`; \`src/index.ts\` serves it and closes the database on SIGTERM. Tests open \`openNotesDb(':memory:')\` and pass its \`db\` to \`createApp\`.
214
414
  - \`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.
215
415
  - Forms answer an invalid input with status 400 and the same page with the messages; a successful POST redirects with 303.
216
- - To add a column: change the \`CREATE TABLE\` in \`openDb\`, \`notesStore\`, \`checkNote\`, the form and the list in \`views.tsx\`, and the tests.
416
+ - To add a column or a table: write the next migration (\`migrations/002-name.sql\`), then change \`notesStore\`, \`checkNote\`, the form and the list in \`views.tsx\`, and the tests. Do not edit \`001-notes.sql\`.
217
417
 
218
418
  ## Before you ship
219
419
 
@@ -221,22 +421,22 @@ Read \`docs/framework/getting-started/deploy.md\`. In short:
221
421
 
222
422
  - 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).
223
423
  - The app listens on \`127.0.0.1\`; set \`HOST=0.0.0.0\` only in a container. \`PORT\` chooses the port.
224
- - Put the SQLite file outside the code folder (\`NOTES_DB=/var/lib/notes/notes.db\`) and back it up.
424
+ - Put the SQLite file outside the code folder (\`NOTES_DB=/var/lib/notes/notes.sqlite\`) and back it up.
225
425
  - 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.
226
426
  - \`npm test\` includes a test that starts the server and stops it with SIGTERM; keep it passing if you change \`src/index.ts\`.
227
427
  ` : ""}${template === "chat" ? `
228
428
  ## Structure (a chat app: a streamed answer, history in a database)
229
429
 
230
430
  - \`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.
431
+ - \`src/db.ts\`: \`openChatDb()\` (the \`db\` port on a SQLite file, \`data/chat.sqlite\` or \`$CHAT_DB\`, with \`migrations/\` applied on start; it returns \`{ db, close }\`) and \`chatStore(db)\`. The routes only call \`chatStore\`; keep SQL out of them. Every \`db\` call returns a promise: \`await\` it. The shape of the database is \`migrations/NNN-name.sql\`: to change it add the next numbered file and never edit one that has run. See \`docs/framework/guides/data.md\`.
432
+ - \`src/app.ts\` opens the database (top-level \`await\`) and exports the app and \`close\`; \`src/index.ts\` serves it and closes the database on SIGTERM. \`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
433
  - \`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
434
  - \`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
435
  - To try it with a real model: \`DEEPSEEK_API_KEY=... npm run dev\`.
236
436
 
237
437
  ## Before you ship
238
438
 
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.
439
+ 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.sqlite\`) 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.
240
440
  ` : ""}
241
441
  ## Things that surprise people
242
442
 
@@ -287,6 +487,78 @@ function acrylblendsBin() {
287
487
  if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`);
288
488
  return join(dirname(pkgFile), bin);
289
489
  }
490
+ /** The lifecycle scripts a template defines and the line that says when they run. */
491
+ const describeScripts = (scripts) => Object.entries(scripts).map(([key, value]) => ` ${key}: ${value}`).join("\n");
492
+ /** Files whose text is checked for secrets: the template's own, not the framework docs copied in. */
493
+ function textFiles(root) {
494
+ const found = [];
495
+ const walk = (dir, prefix) => {
496
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
497
+ if (entry.name === "node_modules" || entry.name === ".git" || prefix === "" && entry.name === "docs") continue;
498
+ if (entry.isDirectory()) walk(join(dir, entry.name), `${prefix}${entry.name}/`);
499
+ else {
500
+ const buffer = readFileSync(join(dir, entry.name));
501
+ if (!buffer.subarray(0, 8e3).includes(0)) found.push({
502
+ path: `${prefix}${entry.name}`,
503
+ text: buffer.toString("utf8")
504
+ });
505
+ }
506
+ }
507
+ };
508
+ walk(root, "");
509
+ return found;
510
+ }
511
+ /**
512
+ * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked
513
+ * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.
514
+ */
515
+ async function createFromSource(options, target, directory, io) {
516
+ if (!isEmpty(target)) {
517
+ io.stderr.write(`error: ${target} is not empty; nothing was changed\n`);
518
+ return 1;
519
+ }
520
+ const scratch = mkdtempSync(join(tmpdir(), "create-acrylblends-"));
521
+ try {
522
+ const source = parseSource(options.source, io.cwd);
523
+ if (!source) throw new UsageError(`unknown template source "${options.source}" (${SOURCE_FORMS})`);
524
+ const name = nameFrom(target);
525
+ await fetchSource(source, join(scratch, "source"), join(scratch, "download"), io.fetchers ?? realFetchers);
526
+ const manifest = readManifest(join(scratch, "source"));
527
+ const staged = join(scratch, "app");
528
+ const { files, lifecycle } = writeTemplate(join(scratch, "source"), staged, (text) => replacePlaceholders(text, name), frameworkRange(), name);
529
+ if (!existsSync(join(staged, "AGENTS.md"))) writeFileSync(join(staged, "AGENTS.md"), `# ${name}\n\nAn ${CLASS} app made from the template "${manifest.name}": ${manifest.description}\n\nThe framework's API is in \`docs/framework/\` (start at \`docs/framework/README.md\`).\n`);
530
+ if (!existsSync(join(staged, "CLAUDE.md"))) writeFileSync(join(staged, "CLAUDE.md"), "@AGENTS.md\n");
531
+ const found = findSecrets(textFiles(staged));
532
+ if (found.length > 0) {
533
+ io.stderr.write(`error: the template holds what looks like a secret, so nothing was created:\n${found.map((f) => ` ${f.path}:${f.line} (${f.kind})`).join("\n")}\n`);
534
+ return 1;
535
+ }
536
+ copyDocs(staged);
537
+ cpSync(staged, target, { recursive: true });
538
+ io.stdout.write(`created ${name} from ${manifest.name} (${manifest.description}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\n`);
539
+ if (manifest.plugins.length > 0) io.stdout.write(`it needs these plugins: ${manifest.plugins.join(", ")}; add them with: npx ${PACKAGE} add ${manifest.plugins.join(" ")}\n`);
540
+ const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
541
+ const hasScripts = Object.keys(lifecycle).length > 0;
542
+ if (options.install) {
543
+ const pkg = JSON.parse(readFileSync(join(target, "package.json"), "utf8"));
544
+ io.stdout.write(`running ${pm} install in ${directory}. This installs: ${[...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})].join(", ") || "nothing"}${hasScripts ? `\nand runs the template's own lifecycle scripts:\n${describeScripts(lifecycle)}` : ""}\n(the dependencies' install scripts run too unless your ${pm} is set to ignore them)\n`);
545
+ if (await io.run(pm, ["install"], target) !== 0) {
546
+ io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\n`);
547
+ return 1;
548
+ }
549
+ } else if (hasScripts) io.stdout.write(`nothing was installed or run. The template defines ${LIFECYCLE.filter((k) => lifecycle[k]).join(", ")}, which ${pm} install would run:\n${describeScripts(lifecycle)}\nread them first, or pass --install to run them.\n`);
550
+ io.stdout.write(`\nNext:\n cd ${directory}\n${options.install ? "" : ` ${pm} install\n`} see the template's README or package.json scripts\n`);
551
+ return 0;
552
+ } catch (error) {
553
+ if (error instanceof SourceError) {
554
+ io.stderr.write(`error: ${error.message}\nnothing was changed\n`);
555
+ return 1;
556
+ }
557
+ throw error;
558
+ } finally {
559
+ removeTree(scratch);
560
+ }
561
+ }
290
562
  /** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */
291
563
  async function runCreate(argv, io = processIo()) {
292
564
  try {
@@ -302,6 +574,7 @@ async function runCreate(argv, io = processIo()) {
302
574
  const ask = options.yes ? void 0 : io.ask;
303
575
  const directory = options.directory ?? (ask ? (await ask(`Project directory (acrylblends-app): `)).trim() || `acrylblends-app` : `acrylblends-app`);
304
576
  const target = resolve(io.cwd, directory);
577
+ if (options.source !== void 0) return await createFromSource(options, target, directory, io);
305
578
  const template = options.template ?? (ask ? await (async () => {
306
579
  const answer = (await ask(`Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
307
580
  if (!isTemplate(answer)) throw new UsageError(`unknown template "${answer}" (${TEMPLATES.join(", ")})`);
@@ -353,6 +626,6 @@ async function runCreate(argv, io = processIo()) {
353
626
  }
354
627
  }
355
628
  //#endregion
356
- export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
629
+ export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_MANIFEST, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
357
630
 
358
631
  //# sourceMappingURL=index.js.map