create-acrylblends 0.2.3 → 0.2.4

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 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({
@@ -287,6 +486,78 @@ function acrylblendsBin() {
287
486
  if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`);
288
487
  return join(dirname(pkgFile), bin);
289
488
  }
489
+ /** The lifecycle scripts a template defines and the line that says when they run. */
490
+ const describeScripts = (scripts) => Object.entries(scripts).map(([key, value]) => ` ${key}: ${value}`).join("\n");
491
+ /** Files whose text is checked for secrets: the template's own, not the framework docs copied in. */
492
+ function textFiles(root) {
493
+ const found = [];
494
+ const walk = (dir, prefix) => {
495
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
496
+ if (entry.name === "node_modules" || entry.name === ".git" || prefix === "" && entry.name === "docs") continue;
497
+ if (entry.isDirectory()) walk(join(dir, entry.name), `${prefix}${entry.name}/`);
498
+ else {
499
+ const buffer = readFileSync(join(dir, entry.name));
500
+ if (!buffer.subarray(0, 8e3).includes(0)) found.push({
501
+ path: `${prefix}${entry.name}`,
502
+ text: buffer.toString("utf8")
503
+ });
504
+ }
505
+ }
506
+ };
507
+ walk(root, "");
508
+ return found;
509
+ }
510
+ /**
511
+ * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked
512
+ * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.
513
+ */
514
+ async function createFromSource(options, target, directory, io) {
515
+ if (!isEmpty(target)) {
516
+ io.stderr.write(`error: ${target} is not empty; nothing was changed\n`);
517
+ return 1;
518
+ }
519
+ const scratch = mkdtempSync(join(tmpdir(), "create-acrylblends-"));
520
+ try {
521
+ const source = parseSource(options.source, io.cwd);
522
+ if (!source) throw new UsageError(`unknown template source "${options.source}" (${SOURCE_FORMS})`);
523
+ const name = nameFrom(target);
524
+ await fetchSource(source, join(scratch, "source"), join(scratch, "download"), io.fetchers ?? realFetchers);
525
+ const manifest = readManifest(join(scratch, "source"));
526
+ const staged = join(scratch, "app");
527
+ const { files, lifecycle } = writeTemplate(join(scratch, "source"), staged, (text) => replacePlaceholders(text, name), frameworkRange(), name);
528
+ 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`);
529
+ if (!existsSync(join(staged, "CLAUDE.md"))) writeFileSync(join(staged, "CLAUDE.md"), "@AGENTS.md\n");
530
+ const found = findSecrets(textFiles(staged));
531
+ if (found.length > 0) {
532
+ 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`);
533
+ return 1;
534
+ }
535
+ copyDocs(staged);
536
+ cpSync(staged, target, { recursive: true });
537
+ io.stdout.write(`created ${name} from ${manifest.name} (${manifest.description}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\n`);
538
+ 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`);
539
+ const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
540
+ const hasScripts = Object.keys(lifecycle).length > 0;
541
+ if (options.install) {
542
+ const pkg = JSON.parse(readFileSync(join(target, "package.json"), "utf8"));
543
+ 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`);
544
+ if (await io.run(pm, ["install"], target) !== 0) {
545
+ io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\n`);
546
+ return 1;
547
+ }
548
+ } 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`);
549
+ io.stdout.write(`\nNext:\n cd ${directory}\n${options.install ? "" : ` ${pm} install\n`} see the template's README or package.json scripts\n`);
550
+ return 0;
551
+ } catch (error) {
552
+ if (error instanceof SourceError) {
553
+ io.stderr.write(`error: ${error.message}\nnothing was changed\n`);
554
+ return 1;
555
+ }
556
+ throw error;
557
+ } finally {
558
+ removeTree(scratch);
559
+ }
560
+ }
290
561
  /** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */
291
562
  async function runCreate(argv, io = processIo()) {
292
563
  try {
@@ -302,6 +573,7 @@ async function runCreate(argv, io = processIo()) {
302
573
  const ask = options.yes ? void 0 : io.ask;
303
574
  const directory = options.directory ?? (ask ? (await ask(`Project directory (acrylblends-app): `)).trim() || `acrylblends-app` : `acrylblends-app`);
304
575
  const target = resolve(io.cwd, directory);
576
+ if (options.source !== void 0) return await createFromSource(options, target, directory, io);
305
577
  const template = options.template ?? (ask ? await (async () => {
306
578
  const answer = (await ask(`Which template do you want to use? (nodejs, notes, chat, bun (experimental), acryl-app) [nodejs]: `)).trim() || "nodejs";
307
579
  if (!isTemplate(answer)) throw new UsageError(`unknown template "${answer}" (${TEMPLATES.join(", ")})`);
@@ -353,6 +625,6 @@ async function runCreate(argv, io = processIo()) {
353
625
  }
354
626
  }
355
627
  //#endregion
356
- export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
628
+ export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_MANIFEST, UsageError, VERSION, agentsText, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, runCreate };
357
629
 
358
630
  //# sourceMappingURL=index.js.map
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', '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,GAAG,CAAC,CAAC,iBAAiB,CAAC,CACjD;AA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AAa,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
+ {"version":3,"file":"index.js","names":[],"sources":["../src/names.ts","../src/source.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\n/** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */\nexport const TEMPLATE_MANIFEST = 'acryl.template.json'\n","/**\n * Templates from outside this package: `github:owner/repo[#ref]`, a scoped npm package (`@scope/name[@version]`) or a packed tarball on disk.\n * A source is only ever downloaded and unpacked: no git clone (hooks), no lifecycle script (`npm pack --ignore-scripts`), nothing of it is run.\n */\nimport { spawnSync } from 'node:child_process'\nimport {\n cpSync,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { PACKAGE, TEMPLATE_MANIFEST } from './names'\n\nexport type Source =\n | { kind: 'github'; owner: string; repo: string; ref: string | undefined }\n | { kind: 'npm'; spec: string }\n | { kind: 'tarball'; path: string }\n\n/** What a template says about itself in `acryl.template.json`. */\nexport interface Manifest {\n name: string\n description: string\n /** Library plugins the template needs, added with `acrylblends add`. */\n plugins: string[]\n}\n\n/** A source that cannot be used; the message says why and is shown as it is. */\nexport class SourceError extends Error {\n override name = 'SourceError'\n}\n\nexport const SOURCE_FORMS = `github:owner/repo[#ref], @scope/name[@version], or a packed .tgz file`\n\nconst LIMITS = { files: 5000, bytes: 50 * 1024 * 1024 }\n\n/** Recognise a source argument, or return `undefined` when it is not one (so the caller can report a usage error). */\nexport function parseSource(text: string, cwd: string): Source | undefined {\n const github = /^github:([A-Za-z0-9_.-]+)\\/([A-Za-z0-9_.-]+)(?:#([A-Za-z0-9_./-]+))?$/.exec(text)\n if (github) return { kind: 'github', owner: github[1]!, repo: github[2]!, ref: github[3] }\n if (text.startsWith('github:')) throw new SourceError(`\"${text}\" is not github:owner/repo[#ref]`)\n if (/^@[a-z0-9][a-z0-9._-]*\\/[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9._-]+)?$/.test(text))\n return { kind: 'npm', spec: text }\n if (text.startsWith('@')) throw new SourceError(`\"${text}\" is not @scope/name[@version]`)\n if (/\\.(tgz|tar\\.gz)$/.test(text)) {\n const path = resolve(cwd, text)\n if (!existsSync(path)) throw new SourceError(`${path} does not exist`)\n return { kind: 'tarball', path }\n }\n return undefined\n}\n\n/** How the bytes of a source are obtained; real by default, replaced in tests. */\nexport interface Fetchers {\n /** The body at a URL (a GitHub tarball). */\n download(url: string): Promise<Uint8Array>\n /** `npm pack <spec> --ignore-scripts` into `dest`; the path of the tarball. */\n pack(spec: string, dest: string): string\n}\n\nexport const realFetchers: Fetchers = {\n async download(url) {\n const response = await fetch(url, { redirect: 'follow' })\n if (!response.ok) throw new SourceError(`${url} answered ${response.status}`)\n return new Uint8Array(await response.arrayBuffer())\n },\n pack(spec, dest) {\n const result = spawnSync(\n 'npm',\n ['pack', spec, '--ignore-scripts', '--json', '--pack-destination', dest],\n {\n encoding: 'utf8',\n shell: false,\n env: { ...process.env, npm_config_ignore_scripts: 'true' },\n },\n )\n if (result.status !== 0)\n throw new SourceError(\n `npm could not pack ${spec}: ${(result.stderr || result.stdout).trim().split('\\n').at(-1)}`,\n )\n const file = (JSON.parse(result.stdout) as { filename: string }[])[0]?.filename\n if (!file) throw new SourceError(`npm packed nothing for ${spec}`)\n return join(dest, file)\n },\n}\n\n/** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives that are too big. */\nfunction extract(tarball: string, dir: string): void {\n const list = spawnSync('tar', ['-tzf', tarball], {\n encoding: 'utf8',\n maxBuffer: 64 * 1024 * 1024,\n })\n if (list.status !== 0) throw new SourceError(`${tarball} is not a readable tar.gz archive`)\n const entries = list.stdout.split('\\n').filter(Boolean)\n if (entries.length > LIMITS.files)\n throw new SourceError(`the template has more than ${LIMITS.files} files`)\n for (const entry of entries)\n if (entry.startsWith('/') || entry.split('/').includes('..'))\n throw new SourceError(`the archive holds a path that leaves its folder: ${entry}`)\n mkdirSync(dir, { recursive: true })\n const run = spawnSync('tar', ['-xzf', tarball, '-C', dir, '--strip-components=1'], {\n encoding: 'utf8',\n })\n if (run.status !== 0) throw new SourceError(`could not unpack ${tarball}: ${run.stderr.trim()}`)\n let bytes = 0\n const walk = (folder: string) => {\n for (const entry of readdirSync(folder)) {\n const path = join(folder, entry)\n const info = lstatSync(path)\n if (info.isSymbolicLink())\n throw new SourceError(\n `the template holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`,\n )\n if (info.isDirectory()) walk(path)\n else bytes += info.size\n }\n }\n walk(dir)\n if (bytes > LIMITS.bytes)\n throw new SourceError(`the template is larger than ${LIMITS.bytes / 1024 / 1024} MB`)\n}\n\n/** Download or pack a source and unpack it into `dir` (which must not exist yet). Nothing in it is run. */\nexport async function fetchSource(\n source: Source,\n dir: string,\n scratch: string,\n fetchers: Fetchers,\n): Promise<void> {\n mkdirSync(scratch, { recursive: true })\n let tarball: string\n if (source.kind === 'tarball') tarball = source.path\n else if (source.kind === 'npm') tarball = fetchers.pack(source.spec, scratch)\n else {\n tarball = join(scratch, 'source.tar.gz')\n writeFileSync(\n tarball,\n await fetchers.download(\n `https://codeload.github.com/${source.owner}/${source.repo}/tar.gz/${source.ref ?? 'HEAD'}`,\n ),\n )\n }\n extract(tarball, dir)\n}\n\n/** Read and check `acryl.template.json`; a source without it is not a template. */\nexport function readManifest(dir: string): Manifest {\n const file = join(dir, TEMPLATE_MANIFEST)\n if (!existsSync(file))\n throw new SourceError(\n `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)`,\n )\n let data: unknown\n try {\n data = JSON.parse(readFileSync(file, 'utf8'))\n } catch {\n throw new SourceError(`${TEMPLATE_MANIFEST} is not valid JSON`)\n }\n const m = data as Record<string, unknown>\n if (typeof m.name !== 'string' || m.name.trim() === '')\n throw new SourceError(`${TEMPLATE_MANIFEST} needs a \"name\"`)\n if (typeof m.description !== 'string')\n throw new SourceError(`${TEMPLATE_MANIFEST} needs a \"description\"`)\n const plugins = m.plugins ?? []\n if (\n !Array.isArray(plugins) ||\n plugins.some((p) => typeof p !== 'string' || !/^[a-z][a-z0-9-]*$/.test(p))\n )\n throw new SourceError(\n `\"plugins\" in ${TEMPLATE_MANIFEST} is a list of plugin names such as \"desktop\"`,\n )\n return { name: m.name, description: m.description, plugins: plugins as string[] }\n}\n\nconst SKIP = new Set(['.git', 'node_modules', TEMPLATE_MANIFEST])\n/** Lifecycle scripts npm runs on `npm install` in the app's own folder. */\nexport const LIFECYCLE = [\n 'preinstall',\n 'install',\n 'postinstall',\n 'prepublish',\n 'preprepare',\n 'prepare',\n 'postprepare',\n]\n\nconst isText = (buffer: Buffer) => !buffer.subarray(0, 8000).includes(0)\n\n/**\n * 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\n * the release this package carries. Returns the files written (relative paths) and the lifecycle scripts the app's package.json defines.\n */\nexport function writeTemplate(\n from: string,\n target: string,\n stamp: (text: string) => string,\n range: string,\n name: string,\n): { files: string[]; lifecycle: Record<string, string> } {\n const files: string[] = []\n const walk = (src: string, dst: string, prefix: string) => {\n mkdirSync(dst, { recursive: true })\n for (const entry of readdirSync(src, { withFileTypes: true })) {\n if (SKIP.has(entry.name)) continue\n const outName = prefix === '' && entry.name === 'gitignore' ? '.gitignore' : entry.name\n if (entry.isDirectory())\n walk(join(src, entry.name), join(dst, outName), `${prefix}${entry.name}/`)\n else {\n const buffer = readFileSync(join(src, entry.name))\n writeFileSync(join(dst, outName), isText(buffer) ? stamp(buffer.toString('utf8')) : buffer)\n files.push(`${prefix}${outName}`)\n }\n }\n }\n walk(from, target, '')\n const lifecycle: Record<string, string> = {}\n const pkgFile = join(target, 'package.json')\n if (existsSync(pkgFile)) {\n const pkg = JSON.parse(readFileSync(pkgFile, 'utf8')) as {\n name?: string\n scripts?: Record<string, string>\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n }\n pkg.name = name\n for (const group of [pkg.dependencies, pkg.devDependencies])\n if (group?.[PACKAGE] !== undefined) group[PACKAGE] = range\n writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\\n`)\n for (const script of LIFECYCLE)\n if (typeof pkg.scripts?.[script] === 'string') lifecycle[script] = pkg.scripts[script]\n }\n return { files, lifecycle }\n}\n\n/** Remove a folder tree quietly. */\nexport const removeTree = (path: string) => rmSync(path, { recursive: true, force: true })\nexport { cpSync }\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 {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n writeFileSync,\n} from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { tmpdir } from 'node:os'\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 { findSecrets } from '@webboxes/app-persistence'\nimport { CLASS, CREATE, PACKAGE, TEMPLATE_MANIFEST } from './names'\nimport {\n type Fetchers,\n fetchSource,\n LIFECYCLE,\n parseSource,\n readManifest,\n realFetchers,\n removeTree,\n SOURCE_FORMS,\n SourceError,\n writeTemplate,\n} from './source'\nimport { packageManagerInvocation } from './spawn'\n\nexport { CLASS, CREATE, PACKAGE, TEMPLATE_MANIFEST }\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] [source] [-- options]\n\nA source makes the app from someone else's template (it is downloaded and unpacked, nothing in it runs):\n github:owner/repo[#ref] a GitHub repository, as a tarball (no clone)\n @scope/name[@version] an npm package (npm pack --ignore-scripts)\n ./template.tgz a packed template on disk\nA template is a folder with an ${TEMPLATE_MANIFEST} (name, description, plugins).\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 (the lifecycle scripts it will run are listed first)\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 /** How a template source is fetched; the real network and npm by default. */\n fetchers?: Fetchers\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 /** `github:owner/repo[#ref]`, `@scope/name` or a packed `.tgz`: a template from outside this package. */\n source: string | undefined\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 > 2)\n throw new UsageError('takes a directory and at most one template source')\n if (positionals[1] !== undefined && values.template !== undefined)\n throw new UsageError('give a template source or --template, not both')\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 source: positionals[1],\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/** The lifecycle scripts a template defines and the line that says when they run. */\nconst describeScripts = (scripts: Record<string, string>) =>\n Object.entries(scripts)\n .map(([key, value]) => ` ${key}: ${value}`)\n .join('\\n')\n\n/** Files whose text is checked for secrets: the template's own, not the framework docs copied in. */\nfunction textFiles(root: string): { path: string; text: string }[] {\n const found: { path: string; text: string }[] = []\n const walk = (dir: string, prefix: string) => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (\n entry.name === 'node_modules' ||\n entry.name === '.git' ||\n (prefix === '' && entry.name === 'docs')\n )\n continue\n if (entry.isDirectory()) walk(join(dir, entry.name), `${prefix}${entry.name}/`)\n else {\n const buffer = readFileSync(join(dir, entry.name))\n if (!buffer.subarray(0, 8000).includes(0))\n found.push({ path: `${prefix}${entry.name}`, text: buffer.toString('utf8') })\n }\n }\n }\n walk(root, '')\n return found\n}\n\n/**\n * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked\n * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.\n */\nasync function createFromSource(\n options: CreateOptions,\n target: string,\n directory: string,\n io: Io,\n): Promise<number> {\n if (!isEmpty(target)) {\n io.stderr.write(`error: ${target} is not empty; nothing was changed\\n`)\n return 1\n }\n const scratch = mkdtempSync(join(tmpdir(), 'create-acrylblends-'))\n try {\n const source = parseSource(options.source!, io.cwd)\n if (!source)\n throw new UsageError(`unknown template source \"${options.source}\" (${SOURCE_FORMS})`)\n const name = nameFrom(target)\n await fetchSource(\n source,\n join(scratch, 'source'),\n join(scratch, 'download'),\n io.fetchers ?? realFetchers,\n )\n const manifest = readManifest(join(scratch, 'source'))\n const staged = join(scratch, 'app')\n const { files, lifecycle } = writeTemplate(\n join(scratch, 'source'),\n staged,\n (text) => replacePlaceholders(text, name),\n frameworkRange(),\n name,\n )\n if (!existsSync(join(staged, 'AGENTS.md')))\n writeFileSync(\n join(staged, 'AGENTS.md'),\n `# ${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`,\n )\n if (!existsSync(join(staged, 'CLAUDE.md')))\n writeFileSync(join(staged, 'CLAUDE.md'), '@AGENTS.md\\n')\n const found = findSecrets(textFiles(staged))\n if (found.length > 0) {\n io.stderr.write(\n `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`,\n )\n return 1\n }\n copyDocs(staged)\n cpSync(staged, target, { recursive: true })\n io.stdout.write(\n `created ${name} from ${manifest.name} (${manifest.description}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\\n`,\n )\n if (manifest.plugins.length > 0)\n io.stdout.write(\n `it needs these plugins: ${manifest.plugins.join(', ')}; add them with: npx ${PACKAGE} add ${manifest.plugins.join(' ')}\\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 const hasScripts = Object.keys(lifecycle).length > 0\n if (options.install) {\n const pkg = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')) as {\n dependencies?: object\n devDependencies?: object\n }\n io.stdout.write(\n `running ${pm} install in ${directory}. This installs: ${[...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})].join(', ') || 'nothing'}` +\n `${hasScripts ? `\\nand runs the template's own lifecycle scripts:\\n${describeScripts(lifecycle)}` : ''}\\n` +\n `(the dependencies' install scripts run too unless your ${pm} is set to ignore them)\\n`,\n )\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 } else if (hasScripts) {\n io.stdout.write(\n `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`,\n )\n }\n io.stdout.write(\n `\\nNext:\\n cd ${directory}\\n${options.install ? '' : ` ${pm} install\\n`} see the template's README or package.json scripts\\n`,\n )\n return 0\n } catch (error) {\n if (error instanceof SourceError) {\n io.stderr.write(`error: ${error.message}\\nnothing was changed\\n`)\n return 1\n }\n throw error\n } finally {\n removeTree(scratch)\n }\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 if (options.source !== undefined) return await createFromSource(options, target, directory, io)\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":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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"}
@@ -35,12 +35,12 @@ The starter asks which template you want (`nodejs`, `bun` (experimental), or `ac
35
35
 
36
36
  ## Runtimes
37
37
 
38
- Verified: Node.js. Bun is experimental. The other runtimes the framework could target are listed on [Other runtimes](getting-started/other-runtimes.md) as not yet verified.
38
+ Verified: Node.js. Bun is experimental (its adapter is checked on Bun). Adapters for AWS Lambda, Lambda@Edge, Cloudflare Workers and Pages, Vercel, Netlify and Service Workers are part of the package, with a guide each on [Other runtimes](getting-started/other-runtimes.md); they are tested with the platforms' own events and have not been deployed by the ACRYL team.
39
39
 
40
40
  ## Not yet available
41
41
 
42
- Some parts of the documented API surface are not part of the package yet, and their pages say so at the top: the adapters of the runtimes other than Node.js.
43
- They are enabled as they are ported.
42
+ Some parts of the documented API surface are not part of the package yet, and their pages say so: the Vite plugin for static site generation, a registry of third-party middleware, and benchmark results.
43
+ They are enabled as they are built.
44
44
 
45
45
  ## Where to read next
46
46
 
@@ -49,6 +49,7 @@ They are enabled as they are ported.
49
49
  | Run something in five minutes | [Getting started](getting-started/basic.md) |
50
50
  | Run the app as a desktop app | [Desktop](getting-started/desktop.md) |
51
51
  | Run it on a server | [Deploy](getting-started/deploy.md) |
52
+ | Run it on a hosting platform | [Other runtimes](getting-started/other-runtimes.md): [AWS Lambda](getting-started/aws-lambda.md), [Cloudflare Workers](getting-started/cloudflare-workers.md), [Vercel](getting-started/vercel.md), [Netlify](getting-started/netlify.md) |
52
53
  | Look up a call | [API](api/index.md), [Routing](api/routing.md), [Context](api/context.md), [Request](api/request.md), [API summary](api/summary.md) |
53
54
  | Understand the design | [Concepts](concepts/motivation.md) |
54
55
  | Copy a pattern | [Guides](guides/best-practices.md), [Validation](guides/validation.md), [Testing](guides/testing.md), [Forms, sessions and a database](guides/forms-and-sessions.md), [Client components without a bundler](guides/client-modules.md) |
@@ -1,3 +1,3 @@
1
1
  # Generated copy
2
2
 
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.
3
+ This folder is a copy of `docs/framework` of acryldev/acryl at commit `eada6fb06a5cafb6c2c92a97effeba567dbd44ba`, 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.
@@ -0,0 +1,115 @@
1
+ # AWS Lambda
2
+
3
+ An Acryl app runs on AWS Lambda behind API Gateway (REST API and HTTP API), an Application Load Balancer, a Lambda Function URL or VPC Lattice. `handle(app)` from `acrylblends/aws-lambda` turns the app into the Lambda handler: it builds a `Request` from the event, calls `app.fetch`, and returns the result in the shape the event source expects.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with API Gateway v1 and v2 and ALB events. It has not been deployed to an AWS account by the ACRYL team: try your first deploy with a test stage.
6
+
7
+ ## Install and write the handler
8
+
9
+ ```sh
10
+ npm install acrylblends
11
+ ```
12
+
13
+ ```ts
14
+ import { Acryl } from 'acrylblends'
15
+ import { handle } from 'acrylblends/aws-lambda'
16
+
17
+ const app = new Acryl()
18
+
19
+ app.get('/', (c) => c.text('Hello from Lambda'))
20
+ app.get('/json', (c) => c.json({ message: 'Hello JSON' }))
21
+
22
+ export const handler = handle(app)
23
+ ```
24
+
25
+ Bundle the file to one JavaScript file for the `nodejs22.x` (or newer) runtime with your tool of choice (esbuild is common), upload it, and set the handler to `index.handler` (the file name, a dot, the export).
26
+
27
+ ## The event and the Lambda context
28
+
29
+ Both are in the bindings of the request:
30
+
31
+ ```ts
32
+ import { Acryl } from 'acrylblends'
33
+ import type { LambdaContext, LambdaEvent } from 'acrylblends/aws-lambda'
34
+
35
+ type Bindings = {
36
+ event: LambdaEvent
37
+ lambdaContext: LambdaContext
38
+ }
39
+
40
+ const app = new Acryl<{ Bindings: Bindings }>()
41
+
42
+ app.get('/info', (c) => {
43
+ return c.json({
44
+ isBase64Encoded: c.env.event.isBase64Encoded,
45
+ awsRequestId: c.env.lambdaContext.awsRequestId,
46
+ })
47
+ })
48
+ ```
49
+
50
+ `c.env.requestContext` holds the request context of the event (API Gateway, ALB or Lattice). The client's address is available through the [ConnInfo helper](../helpers/conninfo.md): `getConnInfo(c).remote.address`.
51
+
52
+ ## Binary responses
53
+
54
+ A response is returned base64 encoded when its content type is binary (images, audio, video, PDF, archives and other non-text types) or it has a content encoding such as `gzip`. To decide differently, pass `isContentTypeBinary`:
55
+
56
+ ```ts
57
+ import { Acryl } from 'acrylblends'
58
+ import { defaultIsContentTypeBinary, handle } from 'acrylblends/aws-lambda'
59
+
60
+ const app = new Acryl()
61
+
62
+ export const handler = handle(app, {
63
+ isContentTypeBinary: (contentType) =>
64
+ defaultIsContentTypeBinary(contentType) || contentType.startsWith('application/vnd.api+octet'),
65
+ })
66
+ ```
67
+
68
+ ## Response streaming
69
+
70
+ On a Function URL with `RESPONSE_STREAM` invoke mode, use `streamHandle` instead of `handle`: the body is written to the response stream as the app produces it, so [streaming helpers](../helpers/streaming.md) (SSE, `stream`, `streamText`) reach the client as they are written. It needs the `awslambda` global, which only the Lambda runtime provides.
71
+
72
+ ```ts
73
+ import { Acryl } from 'acrylblends'
74
+ import { streamHandle } from 'acrylblends/aws-lambda'
75
+
76
+ const app = new Acryl()
77
+
78
+ export const handler = streamHandle(app)
79
+ ```
80
+
81
+ ## Try it without AWS
82
+
83
+ A handler is a function from an event to a result, so it can be called locally with a sample event:
84
+
85
+ ```ts
86
+ import { Acryl } from 'acrylblends'
87
+ import { handle } from 'acrylblends/aws-lambda'
88
+
89
+ const app = new Acryl().get('/', (c) => c.text('Hello from Lambda'))
90
+
91
+ const result = await handle(app)({
92
+ version: '2.0',
93
+ routeKey: '$default',
94
+ rawPath: '/',
95
+ rawQueryString: '',
96
+ headers: { host: 'example.execute-api.eu-west-1.amazonaws.com' },
97
+ requestContext: {
98
+ accountId: '1',
99
+ apiId: 'example',
100
+ authentication: null,
101
+ authorizer: {},
102
+ domainName: 'example.execute-api.eu-west-1.amazonaws.com',
103
+ domainPrefix: 'example',
104
+ http: { method: 'GET', path: '/', protocol: 'HTTP/1.1', sourceIp: '203.0.113.9', userAgent: 'test' },
105
+ requestId: 'r',
106
+ routeKey: '$default',
107
+ stage: '$default',
108
+ time: '25/Oct/2026:12:00:00 +0000',
109
+ timeEpoch: 0,
110
+ },
111
+ body: null,
112
+ isBase64Encoded: false,
113
+ })
114
+ console.log(result.statusCode, result.body) // 200 Hello from Lambda
115
+ ```
@@ -1,6 +1,6 @@
1
1
  # Bun
2
2
 
3
- > **Experimental.** Bun is not a verified runtime yet: the Acryl application code is the same, but the `bun` template and this guide are not covered by the release checks. Node.js is the verified runtime.
3
+ > **Experimental.** Bun is not a verified runtime yet: the Acryl application code is the same, and the Bun adapter (`acrylblends/bun`) is checked on Bun in the framework's release check (a static file, the client address, a WebSocket echo), but the `bun` template and this guide are not covered by the release checks. Node.js is the verified runtime.
4
4
 
5
5
 
6
6
  [Bun](https://bun.com) is another JavaScript runtime. It's not Node.js. Bun includes a transcompiler, so we can write the code in TypeScript or plain JavaScript.
@@ -94,8 +94,6 @@ export default {
94
94
 
95
95
  To serve static files, use `serveStatic` from `acrylblends/bun`.
96
96
 
97
- > **Not yet available.** The Bun adapter, `acrylblends/bun`, is not part of acrylblends yet. The code below shows the planned usage.
98
-
99
97
  ```ts
100
98
  import { serveStatic } from 'acrylblends/bun'
101
99
 
@@ -0,0 +1,53 @@
1
+ # Cloudflare Pages
2
+
3
+ Cloudflare Pages Functions run code next to a static site. `handle(app)` from `acrylblends/cloudflare-pages` turns an Acryl app into a Pages Function, and `handleMiddleware` turns a middleware into a Pages middleware.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with a Pages event context. It has not been deployed to Cloudflare by the ACRYL team. Cloudflare recommends Workers with static assets for new projects (see [Cloudflare Workers](cloudflare-workers.md)).
6
+
7
+ ## A catch-all function
8
+
9
+ Put the file in `functions/[[route]].ts` so it answers every path that is not a static file:
10
+
11
+ ```ts
12
+ import { Acryl } from 'acrylblends'
13
+ import { handle } from 'acrylblends/cloudflare-pages'
14
+
15
+ const app = new Acryl().basePath('/api')
16
+
17
+ app.get('/hello', (c) => c.json({ message: 'Hello from Pages Functions' }))
18
+
19
+ export const onRequest = handle(app)
20
+ ```
21
+
22
+ `basePath('/api')` is for a function at `functions/api/[[route]].ts`.
23
+
24
+ ## The event context and the bindings
25
+
26
+ The Pages event context (`env`, `params`, `data`, `waitUntil`, `next`) is `c.env.eventContext`; the environment bindings are `c.env` as in Workers:
27
+
28
+ ```ts
29
+ import { Acryl } from 'acrylblends'
30
+ import type { EventContext } from 'acrylblends/cloudflare-pages'
31
+
32
+ type Bindings = { MY_KV: unknown; eventContext: EventContext }
33
+
34
+ const app = new Acryl<{ Bindings: Bindings }>()
35
+
36
+ app.get('/params', (c) => c.json(c.env.eventContext.params))
37
+ ```
38
+
39
+ ## Middleware
40
+
41
+ ```ts
42
+ import { handleMiddleware } from 'acrylblends/cloudflare-pages'
43
+
44
+ // functions/_middleware.ts
45
+ export const onRequest = handleMiddleware(async (c, next) => {
46
+ await next()
47
+ c.res.headers.set('x-checked', 'yes')
48
+ })
49
+ ```
50
+
51
+ ## Static files
52
+
53
+ In [advanced mode](https://developers.cloudflare.com/pages/platform/functions/advanced-mode/) (a `_worker.js` that answers every request), `serveStatic()` from `acrylblends/cloudflare-pages` answers a request from the Pages `ASSETS` binding and falls through to the app's not-found handler when there is no such file. The client's address is available through the [ConnInfo helper](../helpers/conninfo.md).
@@ -0,0 +1,67 @@
1
+ # Cloudflare Workers
2
+
3
+ A Cloudflare Worker is a module that exports a `fetch` handler, which is what an Acryl app has: `export default app` is a Worker. The adapter `acrylblends/cloudflare-workers` adds the pieces that need Cloudflare: the client's address, WebSockets, and (deprecated) serving static files from Workers KV.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and a Worker with these routes (`export default app`, bindings from `vars`, `getConnInfo`, `waitUntil`) has been run in `workerd` with `wrangler dev --local`, which needs no Cloudflare account. The ACRYL team has not deployed to Cloudflare itself: run `wrangler dev` first.
6
+
7
+ ## A Worker
8
+
9
+ ```ts
10
+ import { Acryl } from 'acrylblends'
11
+
12
+ const app = new Acryl()
13
+
14
+ app.get('/', (c) => c.text('Hello Cloudflare Workers!'))
15
+
16
+ export default app
17
+ ```
18
+
19
+ With Wrangler: a `wrangler.jsonc` naming the entry file and a compatibility date (`"main": "src/index.ts"`, `"compatibility_date": "2026-01-01"`), then `npx wrangler dev` to run it locally and `npx wrangler deploy` to publish it.
20
+
21
+ ## Bindings and the execution context
22
+
23
+ Environment variables, secrets, KV namespaces, D1 databases and R2 buckets arrive as `c.env`; the `ExecutionContext` is `c.executionCtx`:
24
+
25
+ ```ts
26
+ import { Acryl } from 'acrylblends'
27
+
28
+ type Bindings = {
29
+ MY_SECRET: string
30
+ }
31
+
32
+ const app = new Acryl<{ Bindings: Bindings }>()
33
+
34
+ app.get('/', (c) => {
35
+ c.executionCtx.waitUntil(Promise.resolve()) // work that may finish after the response
36
+ return c.text(c.env.MY_SECRET ? 'configured' : 'missing')
37
+ })
38
+
39
+ export default app
40
+ ```
41
+
42
+ ## The client's address
43
+
44
+ ```ts
45
+ import { Acryl } from 'acrylblends'
46
+ import { getConnInfo } from 'acrylblends/cloudflare-workers'
47
+
48
+ const app = new Acryl()
49
+
50
+ app.get('/ip', (c) => c.text(getConnInfo(c).remote.address ?? 'unknown'))
51
+
52
+ export default app
53
+ ```
54
+
55
+ It reads the `cf-connecting-ip` header that Cloudflare sets. See the [ConnInfo helper](../helpers/conninfo.md).
56
+
57
+ ## WebSockets
58
+
59
+ `upgradeWebSocket` from `acrylblends/cloudflare-workers` accepts the upgrade with Cloudflare's `WebSocketPair`. Cloudflare does not give an `onOpen` event. See the [WebSocket helper](../helpers/websocket.md).
60
+
61
+ ## Static files
62
+
63
+ Prefer Cloudflare's static assets (the `assets` setting of Wrangler), which serve files before your code runs. `serveStatic` from `acrylblends/cloudflare-workers`, which reads files from Workers KV (`__STATIC_CONTENT`), is deprecated by Cloudflare's move to static assets and is kept for existing Workers Sites projects. Cloudflare Pages is the other option: see [Cloudflare Pages](cloudflare-pages.md).
64
+
65
+ ## Service Worker syntax
66
+
67
+ A Worker written in the old non-module syntax (`addEventListener('fetch', ...)`) uses `fire` from `acrylblends/service-worker`: see [Service Worker](service-worker.md).
@@ -0,0 +1,41 @@
1
+ # Lambda@Edge
2
+
3
+ An Acryl app can answer CloudFront requests from Lambda@Edge. `handle(app)` from `acrylblends/lambda-edge` turns the app into the edge function: it builds a `Request` from the CloudFront event, calls `app.fetch`, and returns a CloudFront response. A viewer-request or origin-request function that answers by itself (a redirect, an HTML page, a JSON answer) is the typical use.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with a CloudFront viewer-request event. It has not been deployed to AWS by the ACRYL team.
6
+
7
+ ```ts
8
+ import { Acryl } from 'acrylblends'
9
+ import { handle } from 'acrylblends/lambda-edge'
10
+
11
+ const app = new Acryl()
12
+
13
+ app.get('/', (c) => c.text('Hello from the edge'))
14
+
15
+ export const handler = handle(app)
16
+ ```
17
+
18
+ Lambda@Edge has its own limits: the function must be created in `us-east-1`, has no environment variables, and its size and time limits are lower than Lambda's; check them in the AWS documentation when you choose between this adapter and [AWS Lambda](aws-lambda.md).
19
+
20
+ ## The CloudFront event
21
+
22
+ The CloudFront request, response and config are in the bindings:
23
+
24
+ ```ts
25
+ import { Acryl } from 'acrylblends'
26
+ import type { Callback, CloudFrontEdgeEvent } from 'acrylblends/lambda-edge'
27
+
28
+ type Bindings = {
29
+ callback: Callback
30
+ event: CloudFrontEdgeEvent
31
+ }
32
+
33
+ const app = new Acryl<{ Bindings: Bindings }>()
34
+
35
+ app.get('/country', (c) => {
36
+ const request = c.env.event.Records[0].cf.request
37
+ return c.json({ uri: request.uri, clientIp: request.clientIp })
38
+ })
39
+ ```
40
+
41
+ The client's address is available through the [ConnInfo helper](../helpers/conninfo.md).
@@ -0,0 +1,25 @@
1
+ # Netlify
2
+
3
+ Netlify Functions (version 2) and Edge Functions take a `Request` and a context and return a `Response`. `handle(app)` from `acrylblends/netlify` is that function; the Netlify context is available to the app as `c.env.context`.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with a `Request`. It has not been deployed to Netlify by the ACRYL team.
6
+
7
+ ## A function
8
+
9
+ `netlify/functions/api.ts`:
10
+
11
+ ```ts
12
+ import { Acryl } from 'acrylblends'
13
+ import { handle } from 'acrylblends/netlify'
14
+ import type { Context } from '@netlify/functions'
15
+
16
+ type Bindings = { context: Context }
17
+
18
+ const app = new Acryl<{ Bindings: Bindings }>().basePath('/.netlify/functions/api')
19
+
20
+ app.get('/hello', (c) => c.json({ hello: 'world', site: c.env.context.site.id }))
21
+
22
+ export default handle(app)
23
+ ```
24
+
25
+ Run it locally with `netlify dev` and publish with `netlify deploy`. The client's address comes from `getConnInfo` of `acrylblends/netlify` (the Netlify context's `ip`); see the [ConnInfo helper](../helpers/conninfo.md).
@@ -1,23 +1,34 @@
1
1
  # Other runtimes
2
2
 
3
- Acryl is built on Web Standards, so the same application code is expected to run wherever a `fetch`-style handler can run. Only Node.js ([guide](nodejs.md)) is verified so far. Bun is experimental ([guide](bun.md)).
3
+ Acryl is built on Web Standards, so the same application code is expected to run wherever a `fetch`-style handler can run. Node.js ([guide](nodejs.md)) is the runtime the framework is verified on. Bun is experimental ([guide](bun.md)).
4
4
 
5
- The following runtimes and platforms are **not yet verified**. There are no getting-started pages for them yet, and their adapters (for example `acrylblends/cloudflare-workers`
6
- or `acrylblends/aws-lambda`) are not part of acrylblends yet:
5
+ ## Hosting platforms with an adapter
6
+
7
+ These platforms have an adapter in acrylblends, ported from the upstream adapters with their tests. Each is called with the platform's own events in the framework's release check; the ACRYL team has not deployed to these platforms, so try a first deploy on a test project.
8
+
9
+ | Platform | Guide | Import |
10
+ | --- | --- | --- |
11
+ | AWS Lambda (API Gateway, ALB, Function URLs, VPC Lattice) | [AWS Lambda](aws-lambda.md) | `acrylblends/aws-lambda` |
12
+ | Lambda@Edge (CloudFront) | [Lambda@Edge](lambda-edge.md) | `acrylblends/lambda-edge` |
13
+ | Cloudflare Workers | [Cloudflare Workers](cloudflare-workers.md) | `acrylblends/cloudflare-workers` |
14
+ | Cloudflare Pages | [Cloudflare Pages](cloudflare-pages.md) | `acrylblends/cloudflare-pages` |
15
+ | Vercel | [Vercel](vercel.md) | `acrylblends/vercel` |
16
+ | Netlify | [Netlify](netlify.md) | `acrylblends/netlify` |
17
+ | Service Worker | [Service Worker](service-worker.md) | `acrylblends/service-worker` |
18
+ | Bun | [Bun](bun.md) | `acrylblends/bun` |
19
+
20
+ ## Not yet verified
21
+
22
+ The following runtimes and platforms have no adapter and no getting-started page yet:
7
23
 
8
24
  - Deno, and Deno Deploy
9
- - Cloudflare Workers, and Cloudflare Pages
10
25
  - Fastly Compute
11
- - AWS Lambda, and Lambda@Edge
12
- - Vercel
13
- - Netlify
14
26
  - Next.js
15
27
  - Supabase Functions
16
28
  - Google Cloud Run
17
29
  - Azure Functions
18
30
  - Alibaba Cloud Function Compute
19
31
  - CloudBase
20
- - Service Worker
21
32
  - WebAssembly (WASI)
22
33
 
23
- A page is added here, with a getting-started guide, when a platform has been verified with a test that runs on it.
34
+ A page is added here, with a getting-started guide, when a platform has an adapter and a test that calls it.
@@ -0,0 +1,31 @@
1
+ # Service Worker
2
+
3
+ An Acryl app can answer `fetch` events in a Service Worker, and in any environment that uses the Service Worker syntax, such as a Cloudflare Worker written without ES modules. `fire(app)` from `acrylblends/service-worker` registers the app on the `fetch` event, and `handle(app)` returns the listener, if you want to register it yourself.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with a fetch event. It has not been run inside a browser's Service Worker by the ACRYL team.
6
+
7
+ ```ts
8
+ import { Acryl } from 'acrylblends'
9
+ import { fire } from 'acrylblends/service-worker'
10
+
11
+ const app = new Acryl()
12
+
13
+ app.get('/', (c) => c.text('Hello from a Service Worker'))
14
+
15
+ fire(app)
16
+ ```
17
+
18
+ A request the app does not answer (`404`) can be passed on to the network by giving `fetch` as an option, so a Service Worker can serve some routes and leave the others to the origin:
19
+
20
+ ```ts no-check
21
+ import { Acryl } from 'acrylblends'
22
+ import { handle } from 'acrylblends/service-worker'
23
+
24
+ const app = new Acryl()
25
+
26
+ app.get('/offline', (c) => c.text('Served by the Service Worker'))
27
+
28
+ addEventListener('fetch', handle(app, { fetch: globalThis.fetch }))
29
+ ```
30
+
31
+ `app.fire()` (a method of the app) is deprecated in favour of `fire()` from this module.
@@ -0,0 +1,28 @@
1
+ # Vercel
2
+
3
+ Vercel runs a function that takes a `Request` and returns a `Response`, which is what `app.fetch` is. `handle(app)` from `acrylblends/vercel` is that function.
4
+
5
+ > **Status.** The adapter is the upstream adapter ported with its test suite, and the framework's release check calls it with a `Request`. It has not been deployed to Vercel by the ACRYL team.
6
+
7
+ ## A function
8
+
9
+ Create `api/index.ts`:
10
+
11
+ ```ts
12
+ import { Acryl } from 'acrylblends'
13
+ import { handle } from 'acrylblends/vercel'
14
+
15
+ const app = new Acryl().basePath('/api')
16
+
17
+ app.get('/', (c) => c.text('Hello from Vercel'))
18
+ app.get('/hello', (c) => c.json({ hello: 'world' }))
19
+
20
+ export const GET = handle(app)
21
+ export const POST = handle(app)
22
+ ```
23
+
24
+ Export one handler per HTTP method the app answers. Run it locally with `vercel dev`, and publish with `vercel deploy`.
25
+
26
+ ## The client's address
27
+
28
+ The client's address comes from `getConnInfo` of `acrylblends/vercel`, which reads the `x-real-ip` header Vercel sets; see the [ConnInfo helper](../helpers/conninfo.md).
@@ -8,6 +8,8 @@
8
8
  | Template | What you get |
9
9
  | --- | --- |
10
10
  | `nodejs` | an Acryl application served with `serve()` from `acrylblends/node-server`; run with Node.js 22.19 or newer |
11
+ | `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, a test for every route, a client-component counter |
12
+ | `chat` | an AI chat starter: the answer streams token by token 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 |
11
13
  | `bun` (experimental) | an Acryl application with `export default app`, run with `bun` |
12
14
  | `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) |
13
15
 
@@ -47,14 +49,50 @@ bun create acrylblends@latest my-app --template nodejs
47
49
  | Argument | Description | Example |
48
50
  | :-- | :-- | :-- |
49
51
  | `[directory]` | The folder to create. It must not exist or must be empty. Asked for when it is missing. | `my-app` |
50
- | `--template <template>` | One of `nodejs`, `bun` (experimental), `acryl-app`. Skips the template question. | `--template bun` |
51
- | `--install` | Install the dependencies with the package manager after creating the project. | `--install` |
52
+ | `[source]` | A template from outside the package: `github:owner/repo[#ref]`, `@scope/name[@version]` or a packed `.tgz` file. See [Templates from a repository or a package](#templates-from-a-repository-or-a-package). | `github:acme/starter` |
53
+ | `--template <template>` | One of `nodejs`, `notes`, `chat`, `bun` (experimental), `acryl-app`. Skips the template question. | `--template bun` |
54
+ | `--install` | Install the dependencies with the package manager after creating the project. For a template from a source, the install scripts it will run are listed first. | `--install` |
52
55
  | `--pm <packageManager>` | The package manager for `--install`: `npm`, `pnpm`, `yarn` or `bun`. Defaults to the one that started the initializer. | `--pm pnpm` |
53
56
  | `--yes`, `-y` | Ask nothing: use `nodejs` unless `--template` is given, and the directory `acryl-app`. | `-y` |
54
57
  | `--help` | Print the arguments. | `--help` |
55
58
 
56
59
  The templates are inside the package, so creating a project needs no network except for `--install`.
57
60
 
61
+ ## Templates from a repository or a package
62
+
63
+ A second argument after the directory makes the app from someone else's template:
64
+
65
+ ```sh
66
+ npm create acrylblends@latest my-app github:acme/starter # a GitHub repository (the default branch)
67
+ npm create acrylblends@latest my-app github:acme/starter#v1.2 # a tag, branch or commit
68
+ npm create acrylblends@latest my-app @acme/starter # an npm package
69
+ npm create acrylblends@latest my-app ./acme-starter-1.0.0.tgz # a packed template on disk
70
+ ```
71
+
72
+ A template is a folder (a repository, or an npm package) with an `acryl.template.json` at its top:
73
+
74
+ ```json
75
+ {
76
+ "name": "starter",
77
+ "description": "What the app is",
78
+ "plugins": ["desktop"]
79
+ }
80
+ ```
81
+
82
+ `name` and `description` are required and shown when the app is created. `plugins` is optional: library plugins the template needs, which the command lists with the `acrylblends add` line that adds them. A source without the file is refused with a message.
83
+
84
+ What the command does, in order:
85
+
86
+ 1. **Fetches without running anything.** A GitHub source is downloaded as a tarball (never cloned, so no git hook can run). An npm source is fetched with `npm pack --ignore-scripts`. The archive is unpacked into a scratch folder; one with a path that leaves its folder, a symbolic link, more than 5,000 files or more than 50 MB is refused.
87
+ 2. **Reads `acryl.template.json`** and refuses the source if it is missing or malformed.
88
+ 3. **Fills the template in.** `__APP_NAME__`, `__PACKAGE__`, `__CLASS__` and `__RANGE__` in text files are replaced as in the built-in templates, `package.json` gets the app's name, a dependency on `acrylblends` is set to the release this command carries, a `gitignore` file becomes `.gitignore` (npm does not publish a `.gitignore`), `docs/framework/` is added, and so are `AGENTS.md` and `CLAUDE.md` when the template has none of its own.
89
+ 4. **Looks for secrets.** The result is checked with the secret scan the save step of Blend apps uses; a template that holds a key or a password is refused, and the file and line are named (never the value).
90
+ 5. **Creates the folder** only if all of that passed.
91
+
92
+ Nothing of the template is installed or run. If its `package.json` defines `preinstall`, `install`, `postinstall` or `prepare`, the command says so and prints them: `npm install` would run them. Read them first. With `--install` the command prints the list of what will be installed and which scripts will run, then runs the install.
93
+
94
+ To publish your own: put `acryl.template.json` in the repository or package, name the files with the placeholders above, keep a file named `gitignore` instead of `.gitignore`, and keep secrets out.
95
+
58
96
  ## Example flows
59
97
 
60
98
  ### Interactive
@@ -12,8 +12,8 @@ A `json` validation target reads the body only when the request has a JSON `Cont
12
12
 
13
13
  ## Which runtimes are verified?
14
14
 
15
- Node.js. Bun is experimental. The others are listed, as not yet verified, on [Other runtimes](../getting-started/other-runtimes.md).
15
+ Node.js. Bun is experimental. The hosting platforms with an adapter (AWS Lambda, Lambda@Edge, Cloudflare Workers and Pages, Vercel, Netlify, Service Worker) and the ones without are listed on [Other runtimes](../getting-started/other-runtimes.md).
16
16
 
17
17
  ## Where are the parts marked "not yet available"?
18
18
 
19
- Their pages are part of the documentation so that the structure is complete; each starts with a note saying so. They are enabled as they are ported.
19
+ Their pages are part of the documentation so that the structure is complete; each starts with a note saying so. They are enabled as they are built.
@@ -4,7 +4,7 @@ The ConnInfo Helper helps you to get the connection information. For example, yo
4
4
 
5
5
  ## Import
6
6
 
7
- Only the Node.js adapter, `acrylblends/node-server`, is available today. The adapters for the other platforms (Cloudflare Workers, Bun, Vercel, AWS Lambda, Netlify and Lambda@Edge) are **not yet available**; their imports are shown for completeness and are not checked by the docs tests.
7
+ Each adapter has its own `getConnInfo`: `acrylblends/node-server`, `acrylblends/cloudflare-workers`, `acrylblends/vercel`, `acrylblends/aws-lambda`, `acrylblends/netlify`, `acrylblends/lambda-edge` and `acrylblends/bun`. The Bun example is not type-checked by the docs tests, which run without Bun's types.
8
8
 
9
9
  **Cloudflare Workers**
10
10
 
@@ -98,7 +98,7 @@ export interface FileSystemModule {
98
98
 
99
99
  ### Using the adapter for Bun
100
100
 
101
- On Bun, a `toSSG` function is provided by `acrylblends/bun` (not yet available).
101
+ On Bun, a `toSSG` function is provided by `acrylblends/bun`; it writes the files with `Bun.write`.
102
102
 
103
103
  ### Options
104
104
 
@@ -170,7 +170,8 @@ async function readEvents(body: ReadableStream<Uint8Array>, on: (event: string,
170
170
  for (;;) {
171
171
  const { done, value } = await reader.read()
172
172
  if (done) return
173
- buffer += decoder.decode(value, { stream: true })
173
+ // Line endings may be CRLF; a \r at the end of a chunk is completed by the next chunk, so normalise the whole buffer.
174
+ buffer = (buffer + decoder.decode(value, { stream: true })).replaceAll('\r\n', '\n')
174
175
  const blocks = buffer.split('\n\n')
175
176
  buffer = blocks.pop() ?? ''
176
177
  for (const block of blocks) {
@@ -178,7 +179,7 @@ async function readEvents(body: ReadableStream<Uint8Array>, on: (event: string,
178
179
  const data: string[] = []
179
180
  for (const line of block.split('\n')) {
180
181
  if (line.startsWith('event:')) event = line.slice(6).trim()
181
- else if (line.startsWith('data:')) data.push(line.slice(5).trimStart())
182
+ else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, '')) // the SSE spec strips one leading space only
182
183
  }
183
184
  on(event, data.join('\n'))
184
185
  }
@@ -1,11 +1,11 @@
1
1
  # WebSocket Helper
2
2
 
3
3
  WebSocket Helper is a helper for server-side WebSockets in Acryl applications.
4
- The Node.js adapter is available; the others are not yet available.
4
+ The Node.js, Cloudflare Workers and Bun adapters are available.
5
5
 
6
6
  ## Import
7
7
 
8
- Only the Node.js adapter, `acrylblends/node-server`, is available today. The adapters for the other platforms (Cloudflare Workers, Bun, Vercel, AWS Lambda, Netlify and Lambda@Edge) are **not yet available**; their imports are shown for completeness and are not checked by the docs tests.
8
+ The Node.js adapter (`acrylblends/node-server`), the Cloudflare Workers adapter (`acrylblends/cloudflare-workers`) and the Bun adapter (`acrylblends/bun`) provide `upgradeWebSocket`. The other platforms have no WebSocket support in their adapters. The Bun adapter is checked on Bun in the framework's release check; its examples below are not type-checked by the docs tests, which run without Bun's types.
9
9
 
10
10
  **Cloudflare Workers**
11
11
 
@@ -31,7 +31,7 @@ app.use(
31
31
  app.get('/', (c) => c.text('Acryl!'))
32
32
  ```
33
33
 
34
- Pass the `getConninfo` from the [ConnInfo helper](../../helpers/conninfo.md) appropriate for your environment as the first argument of `ipRestriction`. For a runtime whose adapter is not yet available there is no `getConnInfo` to pass yet.
34
+ Pass the `getConninfo` from the [ConnInfo helper](../../helpers/conninfo.md) appropriate for your environment as the first argument of `ipRestriction`. Every adapter has one (`acrylblends/bun`, `acrylblends/aws-lambda`, `acrylblends/node-server` and the others).
35
35
 
36
36
  ## Rules
37
37
 
@@ -2,8 +2,8 @@
2
2
  "source": {
3
3
  "repo": "acryldev/acryl",
4
4
  "path": "docs/framework",
5
- "commit": "e79bf3de59c700667ae617f5d367cc1fd2f8e037"
5
+ "commit": "eada6fb06a5cafb6c2c92a97effeba567dbd44ba"
6
6
  },
7
- "files": 91,
8
- "digest": "sha256:ea881fe758d9d9add8a8d3837f1dddc6938c3e021cb4ea5f1ce5cfb31af7ef2c"
7
+ "files": 98,
8
+ "digest": "sha256:396f882ac7b612455edc59961c52472fadc5f95ea1a778208e7edd860e4e6727"
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-acrylblends",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Create an Acryl app: npm create acrylblends@latest",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,7 +37,8 @@
37
37
  "scaffold"
38
38
  ],
39
39
  "dependencies": {
40
- "acrylblends": "^0.7.3"
40
+ "acrylblends": "^0.7.4",
41
+ "@webboxes/app-persistence": "0.1.1"
41
42
  },
42
43
  "publishConfig": {
43
44
  "access": "public"