@acryldev/create-blends 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +104 -2
  2. package/bin/create-acrylblends.js +12 -0
  3. package/dist/index.d.ts +94 -0
  4. package/dist/index.js +1069 -0
  5. package/dist/index.js.map +1 -0
  6. package/docs/framework/LICENSE +23 -0
  7. package/docs/framework/README.md +70 -0
  8. package/docs/framework/agents/index.md +59 -0
  9. package/docs/framework/api/acryl.md +247 -0
  10. package/docs/framework/api/context.md +478 -0
  11. package/docs/framework/api/exception.md +80 -0
  12. package/docs/framework/api/index.md +12 -0
  13. package/docs/framework/api/presets.md +62 -0
  14. package/docs/framework/api/request.md +396 -0
  15. package/docs/framework/api/routing.md +303 -0
  16. package/docs/framework/api/summary.md +143 -0
  17. package/docs/framework/concepts/benchmarks.md +26 -0
  18. package/docs/framework/concepts/developer-experience.md +5 -0
  19. package/docs/framework/concepts/middleware.md +21 -0
  20. package/docs/framework/concepts/motivation.md +14 -0
  21. package/docs/framework/concepts/routers.md +63 -0
  22. package/docs/framework/concepts/stacks.md +235 -0
  23. package/docs/framework/concepts/web-standard.md +27 -0
  24. package/docs/framework/cordis/acryl-in-a-cordis-app.md +160 -0
  25. package/docs/framework/cordis/concepts.md +105 -0
  26. package/docs/framework/cordis/middleware.md +8 -0
  27. package/docs/framework/cordis/migration-from-0-3.md +111 -0
  28. package/docs/framework/cordis/migration-from-0-4.md +14 -0
  29. package/docs/framework/cordis/migration-from-dsh-webserver.md +109 -0
  30. package/docs/framework/cordis/migration-to-1-0.md +46 -0
  31. package/docs/framework/cordis/mounting.md +85 -0
  32. package/docs/framework/cordis/node-server.md +100 -0
  33. package/docs/framework/cordis/plugin-lifecycle.md +111 -0
  34. package/docs/framework/cordis/surfaces.md +71 -0
  35. package/docs/framework/cordis/transport-and-cancellation.md +57 -0
  36. package/docs/framework/cordis/validation.md +135 -0
  37. package/docs/framework/getting-started/basic.md +201 -0
  38. package/docs/framework/getting-started/bun.md +219 -0
  39. package/docs/framework/getting-started/deploy.md +133 -0
  40. package/docs/framework/getting-started/desktop.md +80 -0
  41. package/docs/framework/getting-started/nodejs.md +365 -0
  42. package/docs/framework/getting-started/other-runtimes.md +30 -0
  43. package/docs/framework/guides/best-practices.md +231 -0
  44. package/docs/framework/guides/bring-your-own-tool.md +218 -0
  45. package/docs/framework/guides/client-modules.md +210 -0
  46. package/docs/framework/guides/create-acrylblends.md +143 -0
  47. package/docs/framework/guides/data.md +314 -0
  48. package/docs/framework/guides/examples.md +3 -0
  49. package/docs/framework/guides/faq.md +19 -0
  50. package/docs/framework/guides/forms-and-sessions.md +235 -0
  51. package/docs/framework/guides/helpers.md +33 -0
  52. package/docs/framework/guides/jsx-dom.md +301 -0
  53. package/docs/framework/guides/jsx.md +487 -0
  54. package/docs/framework/guides/middleware.md +253 -0
  55. package/docs/framework/guides/production.md +80 -0
  56. package/docs/framework/guides/rpc.md +878 -0
  57. package/docs/framework/guides/testing.md +133 -0
  58. package/docs/framework/guides/validation.md +470 -0
  59. package/docs/framework/helpers/accepts.md +60 -0
  60. package/docs/framework/helpers/adapter.md +57 -0
  61. package/docs/framework/helpers/conninfo.md +77 -0
  62. package/docs/framework/helpers/cookie.md +232 -0
  63. package/docs/framework/helpers/css.md +282 -0
  64. package/docs/framework/helpers/dev.md +64 -0
  65. package/docs/framework/helpers/factory.md +180 -0
  66. package/docs/framework/helpers/html.md +123 -0
  67. package/docs/framework/helpers/jwt.md +184 -0
  68. package/docs/framework/helpers/proxy.md +115 -0
  69. package/docs/framework/helpers/route.md +143 -0
  70. package/docs/framework/helpers/ssg.md +390 -0
  71. package/docs/framework/helpers/streaming.md +224 -0
  72. package/docs/framework/helpers/testing.md +118 -0
  73. package/docs/framework/helpers/websocket.md +208 -0
  74. package/docs/framework/middleware/builtin/basic-auth.md +165 -0
  75. package/docs/framework/middleware/builtin/bearer-auth.md +138 -0
  76. package/docs/framework/middleware/builtin/body-limit.md +71 -0
  77. package/docs/framework/middleware/builtin/cache.md +99 -0
  78. package/docs/framework/middleware/builtin/combine.md +94 -0
  79. package/docs/framework/middleware/builtin/compress.md +59 -0
  80. package/docs/framework/middleware/builtin/context-storage.md +74 -0
  81. package/docs/framework/middleware/builtin/cors.md +134 -0
  82. package/docs/framework/middleware/builtin/csrf.md +105 -0
  83. package/docs/framework/middleware/builtin/etag.md +54 -0
  84. package/docs/framework/middleware/builtin/ip-restriction.md +69 -0
  85. package/docs/framework/middleware/builtin/jsx-renderer.md +283 -0
  86. package/docs/framework/middleware/builtin/jwk.md +192 -0
  87. package/docs/framework/middleware/builtin/jwt.md +145 -0
  88. package/docs/framework/middleware/builtin/language.md +232 -0
  89. package/docs/framework/middleware/builtin/logger.md +74 -0
  90. package/docs/framework/middleware/builtin/loopback-only.md +31 -0
  91. package/docs/framework/middleware/builtin/method-not-allowed.md +48 -0
  92. package/docs/framework/middleware/builtin/method-override.md +80 -0
  93. package/docs/framework/middleware/builtin/mount.md +103 -0
  94. package/docs/framework/middleware/builtin/pretty-json.md +53 -0
  95. package/docs/framework/middleware/builtin/request-id.md +87 -0
  96. package/docs/framework/middleware/builtin/secure-headers.md +247 -0
  97. package/docs/framework/middleware/builtin/timeout.md +98 -0
  98. package/docs/framework/middleware/builtin/timing.md +100 -0
  99. package/docs/framework/middleware/builtin/trailing-slash.md +74 -0
  100. package/docs/framework/middleware/third-party.md +4 -0
  101. package/docs/framework/workshop/README.md +294 -0
  102. package/docs/framework/workshop/facilitator.md +101 -0
  103. package/package.json +54 -3
package/dist/index.js ADDED
@@ -0,0 +1,1069 @@
1
+ import { createRequire } from "node:module";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { copyFileSync, cpSync, cpSync as cpSync$1, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, isAbsolute, join, resolve, win32 } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { fileURLToPath } from "node:url";
8
+ import { parseArgs } from "node:util";
9
+ import { findSecrets } from "@acryldev/app-persistence";
10
+ import { createHash } from "node:crypto";
11
+ // src/names.ts
12
+ /**
13
+ * 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
14
+ * `__PACKAGE__`, so a rename (for example to `acryl`) is a change here and in `scripts/lib/names.mjs`, which a test keeps equal.
15
+ */
16
+ const PACKAGE = "@acryldev/blends";
17
+ const CLASS = "Acryl";
18
+ const CREATE = "@acryldev/create-blends";
19
+ /** The file that makes a folder a template other people can create apps from (`${CREATE} <name> github:owner/repo`). */
20
+ const TEMPLATE_MANIFEST = "acryl.template.json";
21
+ // 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] (or the https://github.com/owner/repo address), @scope/name[@version], a packed .tgz file, or a folder (./path)`;
31
+ /**
32
+ * A template is copied whole into the person's new app, so it is held to the size of an app's source. 64 MB, the registry's own limit for an entry: a game is
33
+ * a whole app with its models, textures and sounds (the largest, acrylblends.action-rpg, is about 52 MB).
34
+ */
35
+ const TEMPLATE_LIMITS = {
36
+ what: "template",
37
+ files: 5e3,
38
+ bytes: 67108864
39
+ };
40
+ /**
41
+ * A registry is read for its index and one entry, and grows with every entry it publishes (100 blueprints are about 33,000 files and 200 MB), so its bound
42
+ * only stops a runaway download; the entry taken from it is a template and is held to the template's limits.
43
+ */
44
+ const REGISTRY_LIMITS = {
45
+ what: "registry",
46
+ files: 2e5,
47
+ bytes: 2147483648
48
+ };
49
+ /** Recognise a source argument, or return `undefined` when it is not one (so the caller can report a usage error). */
50
+ function parseSource(text, cwd) {
51
+ const github = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:#([A-Za-z0-9_./-]+))?$/.exec(text);
52
+ if (github) return {
53
+ kind: "github",
54
+ owner: github[1],
55
+ repo: github[2],
56
+ ref: github[3]
57
+ };
58
+ const pasted = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:\/tree\/([A-Za-z0-9_./-]+))?\/?$/.exec(text);
59
+ if (pasted) return {
60
+ kind: "github",
61
+ owner: pasted[1],
62
+ repo: pasted[2],
63
+ ref: pasted[3]
64
+ };
65
+ if (text.startsWith("github:")) throw new SourceError(`"${text}" is not github:owner/repo[#ref]`);
66
+ if (/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(@[A-Za-z0-9._-]+)?$/.test(text)) return {
67
+ kind: "npm",
68
+ spec: text
69
+ };
70
+ if (text.startsWith("@")) throw new SourceError(`"${text}" is not @scope/name[@version]`);
71
+ if (/\.(tgz|tar\.gz)$/.test(text)) {
72
+ const path = resolve(cwd, text);
73
+ if (!existsSync(path)) throw new SourceError(`${path} does not exist`);
74
+ return {
75
+ kind: "tarball",
76
+ path
77
+ };
78
+ }
79
+ if (/^(\.{1,2}[\\/]|[\\/]|[A-Za-z]:[\\/])/.test(text)) {
80
+ const path = resolve(cwd, text);
81
+ if (!existsSync(path) || !lstatSync(path).isDirectory()) throw new SourceError(`${path} is not a folder`);
82
+ return {
83
+ kind: "folder",
84
+ path
85
+ };
86
+ }
87
+ }
88
+ /**
89
+ * A registry, as `--registry` names it: a source, an https address, or a folder written as a bare path (`my-registry`, `run/registry`). A registry is never a template
90
+ * name, so a path that is an existing folder is taken as one without the `./` a template source needs.
91
+ */
92
+ function parseRegistrySource(text, cwd) {
93
+ const source = parseSource(text, cwd);
94
+ if (source !== void 0) return source;
95
+ if (text.startsWith("https://")) return {
96
+ kind: "hosted",
97
+ base: text.replace(/\/*$/, "/")
98
+ };
99
+ const path = resolve(cwd, text);
100
+ return existsSync(path) && lstatSync(path).isDirectory() ? {
101
+ kind: "folder",
102
+ path
103
+ } : void 0;
104
+ }
105
+ const realFetchers = {
106
+ async download(url, headers) {
107
+ const response = await fetch(url, {
108
+ redirect: "follow",
109
+ ...headers === void 0 ? {} : { headers }
110
+ }).catch((cause) => {
111
+ throw new SourceError(`could not reach ${url}: ${cause instanceof Error ? cause.message : String(cause)}`);
112
+ });
113
+ if (!response.ok) throw new SourceError(`${url} answered ${response.status}`);
114
+ return new Uint8Array(await response.arrayBuffer());
115
+ },
116
+ githubToken() {
117
+ const env = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
118
+ if (env !== void 0 && env !== "") return env;
119
+ const result = spawnSync("gh", ["auth", "token"], {
120
+ encoding: "utf8",
121
+ shell: false
122
+ });
123
+ const token = result.status === 0 ? result.stdout.trim() : "";
124
+ return token === "" ? void 0 : token;
125
+ },
126
+ pack(spec, dest) {
127
+ const result = spawnSync("npm", [
128
+ "pack",
129
+ spec,
130
+ "--ignore-scripts",
131
+ "--json",
132
+ "--pack-destination",
133
+ dest
134
+ ], {
135
+ encoding: "utf8",
136
+ shell: false,
137
+ env: {
138
+ ...process.env,
139
+ npm_config_ignore_scripts: "true"
140
+ }
141
+ });
142
+ if (result.status !== 0) throw new SourceError(`npm could not pack ${spec}: ${(result.stderr || result.stdout).trim().split("\n").at(-1)}`);
143
+ const file = JSON.parse(result.stdout)[0]?.filename;
144
+ if (!file) throw new SourceError(`npm packed nothing for ${spec}`);
145
+ return join(dest, file);
146
+ }
147
+ };
148
+ /**
149
+ * Windows' own tar (bsdtar, in every Windows 10 and 11). A bare `tar` there can be Git's GNU tar, first on PATH when Git's Unix tools are
150
+ * installed, which reads `C:\...` as host `C` and fails on every archive.
151
+ */
152
+ function tarCommand(platform = process.platform, systemRoot = process.env.SystemRoot) {
153
+ return platform === "win32" ? join(systemRoot ?? "C:\\Windows", "System32", "tar.exe") : "tar";
154
+ }
155
+ /** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives over `limits`. */
156
+ function extract(tarball, dir, limits) {
157
+ const tar = tarCommand();
158
+ const list = spawnSync(tar, ["-tzf", tarball], {
159
+ encoding: "utf8",
160
+ maxBuffer: 268435456
161
+ });
162
+ if (list.status !== 0) throw new SourceError(`${tarball} is not a readable tar.gz archive`);
163
+ const entries = list.stdout.split("\n").filter(Boolean);
164
+ if (entries.length > limits.files) throw new SourceError(`the ${limits.what} has more than ${limits.files} files`);
165
+ for (const entry of entries) if (entry.startsWith("/") || entry.split("/").includes("..")) throw new SourceError(`the archive holds a path that leaves its folder: ${entry}`);
166
+ mkdirSync(dir, { recursive: true });
167
+ const run = spawnSync(tar, [
168
+ "-xzf",
169
+ tarball,
170
+ "-C",
171
+ dir,
172
+ "--strip-components=1"
173
+ ], { encoding: "utf8" });
174
+ if (run.status !== 0) throw new SourceError(`could not unpack ${tarball}: ${run.stderr.trim()}`);
175
+ checkTree(dir, limits);
176
+ }
177
+ /** Refuse a tree that holds a link, or is larger than `limits`; the same check for an unpacked archive and a copied folder. */
178
+ function checkTree(dir, limits) {
179
+ let bytes = 0;
180
+ let count = 0;
181
+ const walk = (folder) => {
182
+ for (const entry of readdirSync(folder)) {
183
+ const path = join(folder, entry);
184
+ const info = lstatSync(path);
185
+ if (info.isSymbolicLink()) throw new SourceError(`the ${limits.what} holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`);
186
+ if (info.isDirectory()) walk(path);
187
+ else {
188
+ bytes += info.size;
189
+ count += 1;
190
+ }
191
+ }
192
+ };
193
+ walk(dir);
194
+ if (count > limits.files) throw new SourceError(`the ${limits.what} has more than ${limits.files} files`);
195
+ if (bytes > limits.bytes) throw new SourceError(`the ${limits.what} is larger than ${limits.bytes / 1024 / 1024} MB`);
196
+ }
197
+ /** Download or pack a template and unpack it into `dir` (which must not exist yet). Nothing in it is run. */
198
+ const fetchTemplate = (source, dir, scratch, fetchers) => fetchSource(source, dir, scratch, fetchers, TEMPLATE_LIMITS);
199
+ /** Download or copy a registry into `dir` (which must not exist yet), to read its index and take one entry from it. Nothing in it is run. */
200
+ const fetchRegistry = (source, dir, scratch, fetchers) => fetchSource(source, dir, scratch, fetchers, REGISTRY_LIMITS);
201
+ async function fetchSource(source, dir, scratch, fetchers, limits) {
202
+ mkdirSync(scratch, { recursive: true });
203
+ if (source.kind === "folder") {
204
+ cpSync$1(source.path, dir, {
205
+ recursive: true,
206
+ filter: (path) => !/[\\/](\.git|node_modules)([\\/]|$)/.test(path.slice(source.path.length))
207
+ });
208
+ checkTree(dir, limits);
209
+ return;
210
+ }
211
+ let tarball;
212
+ if (source.kind === "tarball") tarball = source.path;
213
+ else if (source.kind === "npm") tarball = fetchers.pack(source.spec, scratch);
214
+ else {
215
+ tarball = join(scratch, "source.tar.gz");
216
+ writeFileSync(tarball, await downloadGithub(source, fetchers));
217
+ }
218
+ extract(tarball, dir, limits);
219
+ }
220
+ /**
221
+ * A GitHub repository's tarball: anonymously first, then, when GitHub says there is none (a private repository looks absent), with the person's
222
+ * own GitHub login, so the owner and the people invited to a privately shared app can make an app from it.
223
+ */
224
+ async function downloadGithub(source, fetchers) {
225
+ const name = `github:${source.owner}/${source.repo}`;
226
+ try {
227
+ return await fetchers.download(`https://codeload.github.com/${source.owner}/${source.repo}/tar.gz/${source.ref ?? "HEAD"}`);
228
+ } catch (cause) {
229
+ if (!(cause instanceof SourceError && / answered 404$/u.test(cause.message))) throw cause;
230
+ const token = fetchers.githubToken?.();
231
+ if (token === void 0) throw new SourceError(`${name} was not found: it does not exist, or it is private. For a private one you were invited to, sign in to GitHub first (gh auth login, or set GITHUB_TOKEN) and run this again`);
232
+ try {
233
+ return await fetchers.download(`https://api.github.com/repos/${source.owner}/${source.repo}/tarball${source.ref === void 0 ? "" : `/${source.ref}`}`, {
234
+ Authorization: `Bearer ${token}`,
235
+ Accept: "application/vnd.github+json"
236
+ });
237
+ } catch (signedIn) {
238
+ if (signedIn instanceof SourceError && / answered 404$/u.test(signedIn.message)) throw new SourceError(`${name} was not found, and your GitHub account has no access to it: check the name, or ask its owner to invite you`);
239
+ throw signedIn;
240
+ }
241
+ }
242
+ }
243
+ /** Read and check `acryl.template.json`; a source without it is not a template. */
244
+ function readManifest(dir) {
245
+ const file = join(dir, TEMPLATE_MANIFEST);
246
+ 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 @acryldev/create-blends guide)`);
247
+ let data;
248
+ try {
249
+ data = JSON.parse(readFileSync(file, "utf8"));
250
+ } catch {
251
+ throw new SourceError(`${TEMPLATE_MANIFEST} is not valid JSON`);
252
+ }
253
+ const m = data;
254
+ if (typeof m.name !== "string" || m.name.trim() === "") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "name"`);
255
+ if (typeof m.description !== "string") throw new SourceError(`${TEMPLATE_MANIFEST} needs a "description"`);
256
+ const plugins = m.plugins ?? [];
257
+ 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"`);
258
+ return {
259
+ name: m.name,
260
+ description: m.description,
261
+ plugins
262
+ };
263
+ }
264
+ const SKIP = /* @__PURE__ */ new Set([
265
+ ".git",
266
+ "node_modules",
267
+ TEMPLATE_MANIFEST
268
+ ]);
269
+ const GIT_ATTRIBUTES = "# Every checkout has the same line endings, on every OS.\n* text=auto eol=lf\n";
270
+ /** Lifecycle scripts npm runs on `npm install` in the app's own folder. */
271
+ const LIFECYCLE = [
272
+ "preinstall",
273
+ "install",
274
+ "postinstall",
275
+ "prepublish",
276
+ "preprepare",
277
+ "prepare",
278
+ "postprepare"
279
+ ];
280
+ const isText = (buffer) => !buffer.subarray(0, 8e3).includes(0);
281
+ /**
282
+ * 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
283
+ * the release this package carries. Returns the files written (relative paths) and the lifecycle scripts the app's package.json defines.
284
+ */
285
+ function writeTemplate(from, target, stamp, range, name) {
286
+ const files = [];
287
+ const walk = (src, dst, prefix) => {
288
+ mkdirSync(dst, { recursive: true });
289
+ for (const entry of readdirSync(src, { withFileTypes: true })) {
290
+ if (SKIP.has(entry.name)) continue;
291
+ const outName = prefix === "" && entry.name === "gitignore" ? ".gitignore" : entry.name;
292
+ if (entry.isDirectory()) walk(join(src, entry.name), join(dst, outName), `${prefix}${entry.name}/`);
293
+ else {
294
+ const buffer = readFileSync(join(src, entry.name));
295
+ writeFileSync(join(dst, outName), isText(buffer) ? stamp(buffer.toString("utf8")) : buffer);
296
+ files.push(`${prefix}${outName}`);
297
+ }
298
+ }
299
+ };
300
+ walk(from, target, "");
301
+ if (!existsSync(join(target, ".gitattributes"))) {
302
+ writeFileSync(join(target, ".gitattributes"), GIT_ATTRIBUTES);
303
+ files.push(".gitattributes");
304
+ }
305
+ const lifecycle = {};
306
+ const pkgFile = join(target, "package.json");
307
+ if (existsSync(pkgFile)) {
308
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
309
+ pkg.name = name;
310
+ for (const group of [pkg.dependencies, pkg.devDependencies]) if (group?.["@acryldev/blends"] !== void 0) group[PACKAGE] = range;
311
+ writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`);
312
+ for (const script of LIFECYCLE) if (typeof pkg.scripts?.[script] === "string") lifecycle[script] = pkg.scripts[script];
313
+ }
314
+ return {
315
+ files,
316
+ lifecycle
317
+ };
318
+ }
319
+ /** Remove a folder tree quietly. */
320
+ const removeTree = (path) => rmSync(path, {
321
+ recursive: true,
322
+ force: true
323
+ });
324
+ // src/registry.ts
325
+ /**
326
+ * Starters from a registry: `npm create @acryldev/blends@latest my-app -- --from acryl.example`. A registry is a git repository (or a folder) with an `index.json` and one folder per
327
+ * starter under `blends/<id>/`. Its CI says in the index which runtime an entry is for: only `runtime: acrylblends` entries are apps this package can make (the folder is the
328
+ * app, with an `acryl.template.json`); the others are ACRYL app starters and are refused with one line. Nothing is run: the entry is downloaded, unpacked and copied.
329
+ *
330
+ * A registry grows with every entry and one starter is all that is wanted, so `openRegistry` reads as little as the registry allows. A folder is read in place. A static host
331
+ * serves the index and one archive per entry (`archive`, `integrity`, written when the site deploys: workshop-registry/scripts/registry-archives.mjs). A repository holds no
332
+ * archives, so it is downloaded whole. The public registry is a host with its repository behind it, for when the host cannot give the entry.
333
+ */
334
+ /** The public registry's repository (the same files the site lists). */
335
+ const DEFAULT_REGISTRY = "github:acrylblends/acrylblends.github.io";
336
+ const DEFAULT_REPOSITORY = {
337
+ kind: "github",
338
+ owner: "acrylblends",
339
+ repo: "acrylblends.github.io",
340
+ ref: void 0
341
+ };
342
+ /** The public registry as its site serves it, with an archive per entry. */
343
+ const PUBLIC_REGISTRY = "https://acrylblends.github.io/registry/";
344
+ /** Where ACRYL app starters are opened. */
345
+ const ACRYL_APP = "https://acryl.dev";
346
+ /** A registry id: dotted, lower case (`acryl.gtd`, `acrylblends.notes-desktop`, `login.thing`). */
347
+ const REGISTRY_ID = /^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;
348
+ /** A host cannot give this entry, which is not a judgement on the entry: the public registry reads its repository instead. */
349
+ var EntryUnavailable = class extends SourceError {};
350
+ /** The folder of an unpacked registry that holds `index.json`: the root, or its `registry/` folder (the public registry lives in its site's repository). */
351
+ /** @param label - the registry as the person named it (a folder's path, `github:owner/repo`), for the one line when it has no index. */
352
+ function registryRoot(unpacked, label = "this registry") {
353
+ for (const candidate of [unpacked, join(unpacked, "registry")]) if (existsSync(join(candidate, "index.json"))) return candidate;
354
+ throw new SourceError(`${label} has no index.json (a registry is a folder with index.json and blends/<id>/, or index.json in its registry/ folder)`);
355
+ }
356
+ /** An entry's archive as its index names it: both fields or neither, and a path that stays beside the entries. */
357
+ function parseArchive(item) {
358
+ if (item.archive === void 0 && item.integrity === void 0) return void 0;
359
+ const { archive, integrity } = item;
360
+ if (typeof archive !== "string" || !/^blends\/[^/\\]+\.tgz$/.test(archive) || archive.includes("..") || typeof integrity !== "string" || !/^sha512-[A-Za-z0-9+/]+=*$/.test(integrity)) throw new SourceError(`registry entry ${String(item.id)} has no valid archive`);
361
+ return {
362
+ path: archive,
363
+ integrity
364
+ };
365
+ }
366
+ /** The entries of an `index.json`, from its text. */
367
+ function parseIndex(text) {
368
+ let data;
369
+ try {
370
+ data = JSON.parse(text);
371
+ } catch {
372
+ throw new SourceError("the registry index.json is not valid JSON");
373
+ }
374
+ const list = data.entries;
375
+ if (!Array.isArray(list)) throw new SourceError("the registry index.json has no entries");
376
+ const entries = [];
377
+ for (const item of list) {
378
+ if (typeof item.id !== "string" || typeof item.path !== "string") continue;
379
+ if (!/^blends\/[^/\\]+$/.test(item.path)) throw new SourceError(`registry entry ${item.id} has no valid path`);
380
+ const archive = parseArchive(item);
381
+ entries.push({
382
+ id: item.id,
383
+ name: typeof item.name === "string" ? item.name : item.id,
384
+ version: typeof item.version === "string" ? item.version : "0.0.0",
385
+ path: item.path,
386
+ runtime: item.runtime === "acrylblends" ? "acrylblends" : "acryl",
387
+ ...typeof item.description === "string" ? { description: item.description } : {},
388
+ ...archive ? { archive } : {}
389
+ });
390
+ }
391
+ return entries;
392
+ }
393
+ /** A registry in a folder, read in place: only the entry that is taken is copied. */
394
+ function openFolder(unpacked, label, reading) {
395
+ const root = registryRoot(unpacked, label);
396
+ return {
397
+ entries: parseIndex(readFileSync(join(root, "index.json"), "utf8")),
398
+ takeEntry: (entry, dir) => fetchTemplate({
399
+ kind: "folder",
400
+ path: join(root, entry.path)
401
+ }, dir, join(reading.scratch, "download"), reading.fetchers)
402
+ };
403
+ }
404
+ /** A registry that holds no archives, downloaded whole and then read as a folder. */
405
+ async function openUnpacked(source, label, reading) {
406
+ const unpacked = join(reading.scratch, "registry");
407
+ await fetchRegistry(source, unpacked, join(reading.scratch, "download"), reading.fetchers);
408
+ return openFolder(unpacked, label, reading);
409
+ }
410
+ /** A registry on a static host: its index, then only the archive of the entry that is taken. */
411
+ async function openHosted(base, reading) {
412
+ const index = await reading.fetchers.download(`${base}index.json`);
413
+ return {
414
+ entries: parseIndex(Buffer.from(index).toString("utf8")),
415
+ async takeEntry(entry, dir) {
416
+ if (entry.archive === void 0) throw new EntryUnavailable(`${base} publishes no archive for ${entry.id}`);
417
+ const bytes = await downloadArchive(`${base}${entry.archive.path}`, entry.id, reading);
418
+ if (`sha512-${createHash("sha512").update(bytes).digest("base64")}` !== entry.archive.integrity) throw new SourceError(`the archive of ${entry.id} does not match its integrity`);
419
+ const download = join(reading.scratch, "download");
420
+ mkdirSync(download, { recursive: true });
421
+ const path = join(download, "entry.tgz");
422
+ writeFileSync(path, bytes);
423
+ await fetchTemplate({
424
+ kind: "tarball",
425
+ path
426
+ }, dir, download, reading.fetchers);
427
+ }
428
+ };
429
+ }
430
+ async function downloadArchive(url, id, reading) {
431
+ try {
432
+ return await reading.fetchers.download(url);
433
+ } catch (cause) {
434
+ throw new EntryUnavailable(`could not download the archive of ${id}: ${cause instanceof Error ? cause.message : String(cause)}`);
435
+ }
436
+ }
437
+ /** Open a registry the person named, reading as little of it as it allows. */
438
+ async function openRegistry(source, label, reading) {
439
+ if (source.kind === "folder") return openFolder(source.path, source.path, reading);
440
+ if (source.kind === "hosted") return openHosted(source.base, reading);
441
+ return openUnpacked(source, label, reading);
442
+ }
443
+ /**
444
+ * Open the public registry: its site, or its repository when the site cannot answer. An entry the site cannot give is taken from the repository too. An archive that
445
+ * came and does not match, or that breaks a template's limits, is refused: only a missing archive is a reason to look elsewhere.
446
+ */
447
+ async function openPublicRegistry(reading) {
448
+ let site;
449
+ try {
450
+ site = await openHosted(PUBLIC_REGISTRY, reading);
451
+ } catch {
452
+ return openUnpacked(DEFAULT_REPOSITORY, DEFAULT_REGISTRY, reading);
453
+ }
454
+ return {
455
+ entries: site.entries,
456
+ async takeEntry(entry, dir) {
457
+ try {
458
+ await site.takeEntry(entry, dir);
459
+ } catch (cause) {
460
+ if (!(cause instanceof EntryUnavailable)) throw cause;
461
+ await (await openUnpacked(DEFAULT_REPOSITORY, DEFAULT_REGISTRY, reading)).takeEntry(entry, dir);
462
+ }
463
+ }
464
+ };
465
+ }
466
+ /** The entry for an id. An ACRYL app starter is refused in one line; an unknown id lists the starters this package can make. */
467
+ function pickEntry(entries, id) {
468
+ const entry = entries.find((candidate) => candidate.id === id);
469
+ if (!entry) {
470
+ const mine = entries.filter((candidate) => candidate.runtime === "acrylblends").map((candidate) => candidate.id);
471
+ throw new SourceError(`no starter "${id}" in this registry${mine.length > 0 ? `; starters for @acryldev/create-blends: ${mine.join(", ")}` : ""}`);
472
+ }
473
+ if (entry.runtime !== "acrylblends") throw new SourceError(`${entry.id} is an ACRYL app starter: open it in the ACRYL app (${ACRYL_APP}). @acryldev/create-blends makes acrylblends apps.`);
474
+ return entry;
475
+ }
476
+ /**
477
+ * Give a pulled starter to its new owner: the manifest names the app (`acrylblends.<name>`, private), because the registry's id and its public visibility belong to the starter,
478
+ * not to the app made from it. Changes the `metadata` lines of `blend.yaml` (the id, the name, the visibility; the licence is dropped) and nothing else; a manifest it cannot read that way is left as it is.
479
+ */
480
+ function ownManifest(text, name) {
481
+ const lines = text.split("\n");
482
+ const start = lines.findIndex((line) => /^metadata:\s*$/.test(line));
483
+ if (start < 0) return text;
484
+ let end = start + 1;
485
+ while (end < lines.length && /^\s+\S|^\s*$/.test(lines[end] ?? "")) end += 1;
486
+ const set = (key, value) => {
487
+ for (let at = start + 1; at < end; at += 1) {
488
+ const match = new RegExp(`^(\\s+)${key}:.*$`).exec(lines[at] ?? "");
489
+ if (match) {
490
+ lines[at] = `${match[1]}${key}: ${value}`;
491
+ return;
492
+ }
493
+ }
494
+ };
495
+ set("id", `acrylblends.${name}`);
496
+ set("name", name);
497
+ set("visibility", "private");
498
+ for (let at = end - 1; at > start; at -= 1) if (/^\s+license:/.test(lines[at] ?? "")) lines.splice(at, 1);
499
+ return lines.join("\n");
500
+ }
501
+ /**
502
+ * Keep a pulled starter's `blend.lock.json` true to the app made from it: the lock's origin names the manifest it was written from (its id and the digest of its text,
503
+ * as blends-core's `manifestDigest`), and {@link ownManifest} has just changed both. The plugin folders are copied unchanged, so their digests stand. A lock it cannot
504
+ * read is left as it is (`npm run snapshot capture` writes it again).
505
+ */
506
+ function ownLock(text, manifestText, name) {
507
+ let lock;
508
+ try {
509
+ lock = JSON.parse(text);
510
+ } catch {
511
+ return text;
512
+ }
513
+ const origin = lock?.origin;
514
+ if (origin === null || typeof origin !== "object") return text;
515
+ const owned = {
516
+ ...lock,
517
+ origin: {
518
+ ...origin,
519
+ id: `acrylblends.${name}`,
520
+ digest: createHash("sha256").update(manifestText).digest("hex")
521
+ }
522
+ };
523
+ return `${JSON.stringify(owned, null, 2)}\n`;
524
+ }
525
+ /** A DSH profile name for an app, as the framework's scaffold writes it into `scripts/ide-host.mjs` (`acrylblends-<app>`). */
526
+ function profileNameFor(appName) {
527
+ const slug = appName.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-").replaceAll(/^-+|-+$/gu, "");
528
+ return `acrylblends-${slug === "" ? "app" : slug}`;
529
+ }
530
+ /**
531
+ * The name the scaffold wrote into a starter where an app names itself: its manifest's one-word `metadata.name`, or else its `package.json` name, which
532
+ * `init` set to the same name. A curated starter's manifest carries a display name ("Productivity Hub"), which the scaffold never wrote.
533
+ */
534
+ function starterName(manifestText, packageText) {
535
+ const fromManifest = manifestName(manifestText);
536
+ if (fromManifest !== void 0 || packageText === void 0) return fromManifest;
537
+ let name;
538
+ try {
539
+ name = JSON.parse(packageText).name;
540
+ } catch {
541
+ return;
542
+ }
543
+ return typeof name === "string" && name !== "" ? name : void 0;
544
+ }
545
+ /** The app's name as a starter's `blend.yaml` gives it (`metadata.name`), or undefined. */
546
+ function manifestName(text) {
547
+ const lines = text.split("\n");
548
+ const start = lines.findIndex((line) => /^metadata:\s*$/.test(line));
549
+ if (start < 0) return void 0;
550
+ for (let at = start + 1; at < lines.length && /^\s+\S|^\s*$/.test(lines[at] ?? ""); at += 1) {
551
+ const match = /^\s+name:\s*["']?([^"'#\s]+)["']?\s*(?:#.*)?$/.exec(lines[at] ?? "");
552
+ if (match) return match[1];
553
+ }
554
+ }
555
+ /**
556
+ * Where the scaffold wrote an app's name (its `__APP_NAME__`): the headings and the `description:` line of the agents' instructions and skills,
557
+ * the README's title, and the page's `APP_NAME` constant. A starter made from an app still says that app's name there; the app made from it says its own.
558
+ */
559
+ const PROSE_FILES = [
560
+ "AGENTS.md",
561
+ "CLAUDE.md",
562
+ "README.md"
563
+ ];
564
+ /** The lines of those files the scaffold put the name on. */
565
+ const NAMED_LINE = /^(?:#{1,6} |description: )/;
566
+ const SKILL_SCOPES = [".claude/skills", ".agents/skills"];
567
+ const CODE_FILES = ["src/routes.ts", "src/app.ts"];
568
+ /**
569
+ * Give a starter's scaffold files the new app's name: `from` (the starter's `metadata.name`) becomes `to` where it stands as a whole name on a
570
+ * heading or `description:` line of the agents' instructions, skills and README, and in the `APP_NAME` constant; the host script's DSH profile
571
+ * follows. Nothing else is read for the name, so one that is also a common word (`notes`) never rewrites a route, a string or a sentence. Plugins and the lock stay as the starter
572
+ * recorded them.
573
+ * @returns the files it changed, relative to `dir`.
574
+ */
575
+ function renameApp(dir, from, to) {
576
+ if (from === to || !/^[A-Za-z0-9][\w.-]*$/.test(from)) return [];
577
+ const escaped = from.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
578
+ const whole = new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`, "g");
579
+ const prose = [...PROSE_FILES];
580
+ for (const scope of SKILL_SCOPES) {
581
+ const root = join(dir, scope);
582
+ if (!existsSync(root)) continue;
583
+ for (const skill of readdirSync(root, { withFileTypes: true })) if (skill.isDirectory()) prose.push(`${scope}/${skill.name}/SKILL.md`);
584
+ }
585
+ const changed = [];
586
+ const rewrite = (file, edit) => {
587
+ const path = join(dir, file);
588
+ if (!existsSync(path)) return;
589
+ const text = readFileSync(path, "utf8");
590
+ const next = edit(text);
591
+ if (next === text) return;
592
+ writeFileSync(path, next);
593
+ changed.push(file);
594
+ };
595
+ for (const file of prose) rewrite(file, (text) => text.split("\n").map((line) => NAMED_LINE.test(line) ? line.replace(whole, to) : line).join("\n"));
596
+ const constant = new RegExp(`(\\bAPP_NAME = )(['"])${escaped}\\2`, "g");
597
+ for (const file of CODE_FILES) rewrite(file, (text) => text.replace(constant, `$1$2${to}$2`));
598
+ rewrite("package-lock.json", (text) => {
599
+ try {
600
+ const lock = JSON.parse(text);
601
+ const root = lock.packages?.[""];
602
+ if (lock.name !== from && root?.name !== from) return text;
603
+ if (lock.name === from) lock.name = to;
604
+ if (root !== void 0 && root.name === from) root.name = to;
605
+ return `${JSON.stringify(lock, null, 2)}\n`;
606
+ } catch {
607
+ return text;
608
+ }
609
+ });
610
+ const profile = profileNameFor(from);
611
+ rewrite("scripts/ide-host.mjs", (text) => text.replaceAll(`'${profile}'`, `'${profileNameFor(to)}'`));
612
+ return changed;
613
+ }
614
+ // src/spawn.ts
615
+ /**
616
+ * 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).
617
+ * Off Windows the command runs as it is, and so does a program given by its path on Windows (Node, started with `process.execPath`). On Windows npm runs as `node npm-cli.js` (the one npm is running from, else the one beside `node`); any other
618
+ * manager goes through `cmd.exe /d /s /c <name>.cmd`, whose arguments stay an array.
619
+ */
620
+ function packageManagerInvocation(command, args, platform = process.platform, env = process.env, exists = existsSync, execPath = process.execPath) {
621
+ if (platform !== "win32") return {
622
+ file: command,
623
+ args: [...args]
624
+ };
625
+ if (isAbsolute(command) || win32.isAbsolute(command)) return {
626
+ file: command,
627
+ args: [...args]
628
+ };
629
+ if (command === "npm") {
630
+ const running = env.npm_execpath;
631
+ const cli = running !== void 0 && /npm-cli\.c?js$/.test(running) ? running : join(dirname(execPath), "node_modules", "npm", "bin", "npm-cli.js");
632
+ if (exists(cli)) return {
633
+ file: execPath,
634
+ args: [cli, ...args]
635
+ };
636
+ }
637
+ return {
638
+ file: env.ComSpec ?? "cmd.exe",
639
+ args: [
640
+ "/d",
641
+ "/s",
642
+ "/c",
643
+ `${command}.cmd`,
644
+ ...args
645
+ ]
646
+ };
647
+ }
648
+ // src/index.ts
649
+ /**
650
+ * The templates: the same list as acrylblends init (the framework package makes every one of them; @acryldev/create-blends delegates). A test compares this list and its summaries with the
651
+ * framework package's, so they cannot drift.
652
+ */
653
+ const TEMPLATES = [
654
+ "blank",
655
+ "nodejs",
656
+ "notes",
657
+ "chat",
658
+ "todo",
659
+ "agent"
660
+ ];
661
+ const TEMPLATE_SUMMARY = {
662
+ blank: "the router, a server and one route: the smallest app",
663
+ nodejs: "a web app with a page and a client component",
664
+ notes: "a multi-user notes app on the db port (sign-up, log-in, sessions)",
665
+ chat: "a chat app that streams an answer over server-sent events",
666
+ todo: "a to-do list on the router and state",
667
+ agent: "the blank app with an offline agent that builds plugins into the running app"
668
+ };
669
+ /** Names that were templates once and still work. */
670
+ const TEMPLATE_ALIASES = { "acryl-app": "agent" };
671
+ const TEMPLATE_LIST = TEMPLATES.map((name) => ` ${name.padEnd(7)} ${TEMPLATE_SUMMARY[name]}`).join("\n");
672
+ const PACKAGE_MANAGERS = [
673
+ "npm",
674
+ "pnpm",
675
+ "yarn",
676
+ "bun"
677
+ ];
678
+ /** The version of this package. */
679
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
680
+ const HELP = `${CREATE} ${VERSION} - create an ${CLASS} app
681
+
682
+ Usage:
683
+ npx acryl new [name] [starter] (the same through npm create ${PACKAGE}@latest [name] [starter])
684
+
685
+ npx acryl new shop the Blank app in the ACRYL frame, installed and started
686
+ npx acryl new shop notes the same from a starter (${TEMPLATES.join(", ")})
687
+
688
+ The app is made, installed and started with the chat, the panels and Settings; nothing is asked when a name is given. Next time: cd shop && npm run dev.
689
+ Turn a step off:
690
+ --no-start make and install it, do not start it
691
+ --no-install make it only
692
+ --bare the app without the frame
693
+
694
+ A source makes the app from someone else's template (it is downloaded and unpacked, nothing in it runs unless --install):
695
+ github:owner/repo[#ref] a GitHub repository, as a tarball (no clone)
696
+ @scope/name[@version] an npm package (npm pack --ignore-scripts)
697
+ ./template.tgz a packed template on disk
698
+ ./folder a template folder on disk
699
+ A template is a folder with an ${TEMPLATE_MANIFEST} (name, description, plugins).
700
+
701
+ A starter from the registry is pulled by its id:
702
+ --from <id | source> a registry id such as acrylblends.notes-desktop, or any of the sources above
703
+ --registry <source> read the starters from this registry instead of the public one (github:owner/repo, an https:// address, or a folder)
704
+ Only starters made for ${CLASS} (runtime: ${PACKAGE}) are apps this command can make; an ACRYL app starter is refused with a line saying so.
705
+
706
+ Other options:
707
+ --template <name> the same as the word after the name (npm needs a -- before options when you use npm create)
708
+ --install install a source's dependencies (the lifecycle scripts it will run are listed first); a template always installs
709
+ --desktop the frame (already the default for a template and a registry starter); a starter from another source gets it only with this
710
+ --bare no frame, for a registry starter too
711
+ --pm <manager> ${PACKAGE_MANAGERS.join(", ")} (default: the one that ran this command, else npm)
712
+ -y, --yes ask nothing, and use the name my-app when none is given
713
+ -h, --help show this help
714
+
715
+ Templates (the same list as acrylblends init):
716
+ ${TEMPLATE_LIST}
717
+ -v, --version show the version
718
+ `;
719
+ /** A command line mistake. The command prints it with the help text and exits 2. */
720
+ var UsageError = class extends Error {
721
+ name = "UsageError";
722
+ };
723
+ function processIo() {
724
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
725
+ return {
726
+ stdout: process.stdout,
727
+ stderr: process.stderr,
728
+ cwd: process.cwd(),
729
+ env: process.env,
730
+ ask: interactive ? async (question) => {
731
+ const rl = createInterface({
732
+ input: process.stdin,
733
+ output: process.stdout
734
+ });
735
+ try {
736
+ return await rl.question(question);
737
+ } finally {
738
+ rl.close();
739
+ }
740
+ } : void 0,
741
+ run: (command, args, cwd) => new Promise((done) => {
742
+ const invocation = packageManagerInvocation(command, args);
743
+ const child = spawn(invocation.file, invocation.args, {
744
+ cwd,
745
+ stdio: "inherit"
746
+ });
747
+ child.on("error", () => done(1));
748
+ child.on("exit", (code) => done(code ?? 1));
749
+ })
750
+ };
751
+ }
752
+ function isTemplate(value) {
753
+ return TEMPLATES.includes(value);
754
+ }
755
+ /** The template a name means: itself, or what an old name stands for. */
756
+ function resolveTemplate(value) {
757
+ return isTemplate(value) ? value : TEMPLATE_ALIASES[value];
758
+ }
759
+ function parseCreateOptions(argv) {
760
+ let parsed;
761
+ try {
762
+ parsed = parse(argv);
763
+ } catch (error) {
764
+ throw new UsageError(error.message);
765
+ }
766
+ const { values, positionals } = parsed;
767
+ if (positionals.length > 2) throw new UsageError("takes a directory and at most one template source");
768
+ const bare = positionals[1] !== void 0 ? resolveTemplate(positionals[1]) : void 0;
769
+ if (positionals[1] !== void 0 && values.template !== void 0) throw new UsageError("give a template (or a template source) or --template, not both");
770
+ const named = values.template === void 0 ? void 0 : resolveTemplate(values.template);
771
+ if (values.template !== void 0 && named === void 0) throw new UsageError(`unknown template "${values.template}" (${TEMPLATES.join(", ")})`);
772
+ if (values.pm !== void 0 && !PACKAGE_MANAGERS.includes(values.pm)) throw new UsageError(`unknown package manager "${values.pm}" (${PACKAGE_MANAGERS.join(", ")})`);
773
+ const positionalSource = bare === void 0 ? positionals[1] : void 0;
774
+ if (values.from !== void 0 && positionals[1] !== void 0) throw new UsageError("give --from or a template (or a template source) after the directory, not both");
775
+ if (values.from !== void 0 && values.template !== void 0) throw new UsageError("give --from or --template, not both");
776
+ const source = values.from ?? positionalSource;
777
+ if (values.bare === true && values.desktop === true) throw new UsageError("give --bare or --desktop, not both");
778
+ if (values["no-install"] === true && values.install === true) throw new UsageError("give --no-install or --install, not both");
779
+ if (values.registry !== void 0 && !(source !== void 0 && REGISTRY_ID.test(source))) throw new UsageError("--registry goes with a registry id: --from <id> --registry <source>");
780
+ return {
781
+ directory: positionals[0],
782
+ template: bare ?? named,
783
+ install: values.install === true || source === void 0 && values["no-install"] !== true,
784
+ desktop: values.bare !== true && (values.desktop === true || source === void 0 || REGISTRY_ID.test(source)),
785
+ start: values["no-start"] !== true,
786
+ pm: values.pm,
787
+ yes: values.yes === true,
788
+ source,
789
+ registry: values.registry
790
+ };
791
+ }
792
+ const parse = (argv) => parseArgs({
793
+ args: [...argv],
794
+ allowPositionals: true,
795
+ strict: true,
796
+ options: {
797
+ template: { type: "string" },
798
+ from: { type: "string" },
799
+ registry: { type: "string" },
800
+ install: { type: "boolean" },
801
+ "no-install": { type: "boolean" },
802
+ desktop: { type: "boolean" },
803
+ bare: { type: "boolean" },
804
+ "no-start": { type: "boolean" },
805
+ pm: { type: "string" },
806
+ yes: {
807
+ type: "boolean",
808
+ short: "y"
809
+ }
810
+ }
811
+ });
812
+ /** A valid package name from a directory name: lower case letters, digits and dashes. */
813
+ function nameFrom(directory) {
814
+ const name = basename(resolve(directory)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/g, "");
815
+ return name === "" ? "acryl-app" : name;
816
+ }
817
+ function walkUp(from, test) {
818
+ let dir = from;
819
+ for (;;) {
820
+ const found = test(dir);
821
+ if (found) return found;
822
+ const parent = dirname(dir);
823
+ if (parent === dir) throw new Error(`${CREATE} cannot find its files`);
824
+ dir = parent;
825
+ }
826
+ }
827
+ const here = dirname(fileURLToPath(import.meta.url));
828
+ /** The framework docs: the copy `prepack` puts in the package, or `docs/framework` of the repository. */
829
+ const docsRoot = () => walkUp(here, (d) => existsSync(join(d, "docs", "framework", "README.md")) ? join(d, "docs", "framework") : void 0);
830
+ /**
831
+ * 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
832
+ * commands can do), never an older one. A caret range, so it also takes the newer patch releases.
833
+ */
834
+ function frameworkRange() {
835
+ const file = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`);
836
+ return `^${JSON.parse(readFileSync(file, "utf8")).version}`;
837
+ }
838
+ function replacePlaceholders(text, name) {
839
+ return text.replaceAll("__APP_NAME__", name).replaceAll("__PACKAGE__", PACKAGE).replaceAll("__CLASS__", CLASS).replaceAll("__RANGE__", frameworkRange());
840
+ }
841
+ function copyDocs(target) {
842
+ const filter = (path) => !/(upstream\.json|UPSTREAM\.md)$/.test(path);
843
+ mkdirSync(join(target, "docs"), { recursive: true });
844
+ cpSync(docsRoot(), join(target, "docs", "framework"), {
845
+ recursive: true,
846
+ filter
847
+ });
848
+ }
849
+ const isEmpty = (directory) => !existsSync(directory) || readdirSync(directory).length === 0;
850
+ /** The `acrylblends` command of the installed framework package, which creates every template. */
851
+ function acrylblendsBin() {
852
+ const pkgFile = createRequire(import.meta.url).resolve(`${PACKAGE}/package.json`);
853
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
854
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.acrylblends ?? Object.values(pkg.bin ?? {})[0];
855
+ if (!bin) throw new Error(`${PACKAGE} has no command to create an app with`);
856
+ return join(dirname(pkgFile), bin);
857
+ }
858
+ /** The lifecycle scripts a template defines and the line that says when they run. */
859
+ const describeScripts = (scripts) => Object.entries(scripts).map(([key, value]) => ` ${key}: ${value}`).join("\n");
860
+ /** Files whose text is checked for secrets: the template's own, not the framework docs copied in. */
861
+ function textFiles(root) {
862
+ const found = [];
863
+ const walk = (dir, prefix) => {
864
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
865
+ if (entry.name === "node_modules" || entry.name === ".git" || prefix === "" && entry.name === "docs") continue;
866
+ if (entry.isDirectory()) walk(join(dir, entry.name), `${prefix}${entry.name}/`);
867
+ else {
868
+ const buffer = readFileSync(join(dir, entry.name));
869
+ if (!buffer.subarray(0, 8e3).includes(0)) found.push({
870
+ path: `${prefix}${entry.name}`,
871
+ text: buffer.toString("utf8")
872
+ });
873
+ }
874
+ }
875
+ };
876
+ walk(root, "");
877
+ return found;
878
+ }
879
+ /**
880
+ * A new app is a git repository from the start, as `acrylblends init` makes it: the frame's versions, Files and Changes work on it, and its first
881
+ * version is the app as created. A folder that already is a repository, or a machine without git, is left alone.
882
+ */
883
+ function startRepository(directory) {
884
+ if (existsSync(join(directory, ".git"))) return;
885
+ const run = (args) => spawnSync("git", args, {
886
+ cwd: directory,
887
+ stdio: "ignore",
888
+ windowsHide: true
889
+ }).status === 0;
890
+ if (!run(["init", "-q"])) return;
891
+ if (!run(["add", "-A"])) return;
892
+ run([
893
+ ...run(["config", "user.email"]) ? [] : [
894
+ "-c",
895
+ "user.name=acrylblends",
896
+ "-c",
897
+ "user.email=scaffold@acryldev.invalid"
898
+ ],
899
+ "commit",
900
+ "-q",
901
+ "-m",
902
+ "Initial commit from acrylblends"
903
+ ]);
904
+ }
905
+ /** An app with the extensions row (what plugin-share installs through) and no plugin-share row: a starter older than sharing. */
906
+ function lacksPluginShare(directory) {
907
+ const file = join(directory, "blend.yaml");
908
+ if (!existsSync(file)) return false;
909
+ const names = [...readFileSync(file, "utf8").matchAll(/^ *name: ?(\S+)\r?$/gmu)].map((match) => match[1]);
910
+ return names.includes("extensions") && !names.includes("plugin-share");
911
+ }
912
+ /** The registry `--registry` names. */
913
+ function openNamedRegistry(name, cwd, reading) {
914
+ const source = parseRegistrySource(name, cwd);
915
+ if (!source) throw new UsageError(`unknown registry "${name}" (${SOURCE_FORMS})`);
916
+ return openRegistry(source, name, reading);
917
+ }
918
+ /**
919
+ * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked
920
+ * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.
921
+ */
922
+ async function createFromSource(options, target, directory, io) {
923
+ if (!isEmpty(target)) {
924
+ io.stderr.write(`error: ${target} is not empty; nothing was changed\n`);
925
+ return 1;
926
+ }
927
+ const scratch = mkdtempSync(join(tmpdir(), "acryl-create-blends-"));
928
+ try {
929
+ const name = nameFrom(target);
930
+ const fetchers = io.fetchers ?? realFetchers;
931
+ let entry;
932
+ if (REGISTRY_ID.test(options.source)) {
933
+ const reading = {
934
+ scratch,
935
+ fetchers
936
+ };
937
+ const registry = options.registry === void 0 ? await openPublicRegistry(reading) : await openNamedRegistry(options.registry, io.cwd, reading);
938
+ entry = pickEntry(registry.entries, options.source);
939
+ await registry.takeEntry(entry, join(scratch, "source"));
940
+ } else {
941
+ const source = parseSource(options.source, io.cwd);
942
+ if (!source) throw new UsageError(`unknown template source "${options.source}" (${SOURCE_FORMS})`);
943
+ await fetchTemplate(source, join(scratch, "source"), join(scratch, "download"), fetchers);
944
+ }
945
+ const manifest = readManifest(join(scratch, "source"));
946
+ const staged = join(scratch, "app");
947
+ const { files, lifecycle } = writeTemplate(join(scratch, "source"), staged, (text) => replacePlaceholders(text, name), frameworkRange(), name);
948
+ for (const file of [
949
+ "LICENSE",
950
+ "LICENSE.md",
951
+ "LICENSE.txt"
952
+ ]) if (existsSync(join(staged, "blend.yaml")) && existsSync(join(staged, file))) renameSync(join(staged, file), join(staged, `STARTER-${file}`));
953
+ if (existsSync(join(staged, "blend.yaml"))) {
954
+ const starterText = readFileSync(join(staged, "blend.yaml"), "utf8");
955
+ const sourcePackage = join(scratch, "source", "package.json");
956
+ const starter = starterName(starterText, existsSync(sourcePackage) ? readFileSync(sourcePackage, "utf8") : void 0);
957
+ if (starter !== void 0) renameApp(staged, starter, name);
958
+ const manifestText = ownManifest(starterText, name);
959
+ writeFileSync(join(staged, "blend.yaml"), manifestText);
960
+ if (existsSync(join(staged, "blend.lock.json"))) writeFileSync(join(staged, "blend.lock.json"), ownLock(readFileSync(join(staged, "blend.lock.json"), "utf8"), manifestText, name));
961
+ }
962
+ 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`);
963
+ if (!existsSync(join(staged, "CLAUDE.md"))) copyFileSync(join(staged, "AGENTS.md"), join(staged, "CLAUDE.md"));
964
+ const found = findSecrets(textFiles(staged));
965
+ if (found.length > 0) {
966
+ 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`);
967
+ return 1;
968
+ }
969
+ copyDocs(staged);
970
+ cpSync(staged, target, { recursive: true });
971
+ if (options.desktop) {
972
+ const framework = (args) => io.run(process.execPath, [
973
+ acrylblendsBin(),
974
+ ...args,
975
+ "--dir",
976
+ target
977
+ ], io.cwd);
978
+ if (!existsSync(join(target, "plugins", "desktop-shell")) && await framework(["add", "desktop-shell"]) !== 0 || await framework(["upgrade"]) !== 0 || lacksPluginShare(target) && await framework(["add", "plugin-share"]) !== 0) {
979
+ io.stderr.write(`error: ${directory} was made, but putting it in the ACRYL frame failed (see above); it runs on its own with \`npm start\`\n`);
980
+ startRepository(target);
981
+ return 1;
982
+ }
983
+ }
984
+ startRepository(target);
985
+ io.stdout.write(`created ${name} from ${entry ? `${entry.id} ${entry.version}` : manifest.name} (${manifest.description}) in ${target}: ${files.length} files, ${CLASS} docs in docs/framework\n`);
986
+ 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`);
987
+ const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
988
+ const hasScripts = Object.keys(lifecycle).length > 0;
989
+ if (options.install) {
990
+ const pkg = JSON.parse(readFileSync(join(target, "package.json"), "utf8"));
991
+ 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`);
992
+ if (await io.run(pm, ["install"], target) !== 0) {
993
+ io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\n`);
994
+ return 1;
995
+ }
996
+ } 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`);
997
+ io.stdout.write(`\nNext:\n cd ${directory}\n${options.install ? "" : ` ${pm} install\n`}${options.desktop ? ` ${pm} run dev in the ACRYL frame, in the browser\n ${pm} run desktop in the ACRYL frame, in its own window\n ${pm} start the app on its own\n` : ` ${existsSync(join(target, "README.md")) ? "see README.md or the package.json scripts" : "see the package.json scripts"}\n`}`);
998
+ return 0;
999
+ } catch (error) {
1000
+ if (error instanceof SourceError) {
1001
+ io.stderr.write(`error: ${error.message}\nnothing was changed\n`);
1002
+ return 1;
1003
+ }
1004
+ throw error;
1005
+ } finally {
1006
+ removeTree(scratch);
1007
+ }
1008
+ }
1009
+ /** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */
1010
+ async function runCreate(argv, io = processIo()) {
1011
+ try {
1012
+ if (argv.includes("-h") || argv.includes("--help")) {
1013
+ io.stdout.write(HELP);
1014
+ return 0;
1015
+ }
1016
+ if (argv.includes("-v") || argv.includes("--version")) {
1017
+ io.stdout.write(`${VERSION}\n`);
1018
+ return 0;
1019
+ }
1020
+ const options = parseCreateOptions(argv);
1021
+ const askedName = options.directory === void 0 && !options.yes && io.ask !== void 0;
1022
+ const directory = options.directory ?? (askedName ? (await io.ask("What is your app called? (my-app): ")).trim() || "my-app" : "my-app");
1023
+ const target = resolve(io.cwd, directory);
1024
+ if (options.source !== void 0) return await createFromSource(options, target, directory, io);
1025
+ const template = options.template ?? "blank";
1026
+ if (!isEmpty(target)) {
1027
+ io.stderr.write(`error: ${target} is not empty; nothing was changed\n`);
1028
+ return 1;
1029
+ }
1030
+ const name = nameFrom(target);
1031
+ if (await io.run(process.execPath, [
1032
+ acrylblendsBin(),
1033
+ "init",
1034
+ target,
1035
+ "--template",
1036
+ template,
1037
+ "--name",
1038
+ name,
1039
+ "--yes",
1040
+ "--no-next",
1041
+ ...options.desktop ? ["--desktop"] : ["--bare"]
1042
+ ], io.cwd) !== 0) return 1;
1043
+ const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
1044
+ if (options.install) {
1045
+ if (await io.run(pm, ["install"], target) !== 0) {
1046
+ io.stderr.write(`error: ${pm} install failed; run it yourself in ${directory}\n`);
1047
+ return 1;
1048
+ }
1049
+ }
1050
+ const start = `${pm} run dev`;
1051
+ if (options.start && options.desktop && options.install && io.ask !== void 0) {
1052
+ io.stdout.write(`\n${name} is ready. Starting it (Ctrl+C stops it). Next time: cd ${directory} && ${start}\n\n`);
1053
+ await io.run(pm, ["run", "dev"], target);
1054
+ return 0;
1055
+ }
1056
+ io.stdout.write(`\nNext:\n cd ${directory}\n${options.install ? "" : ` ${pm} install\n`} ${start}\n`);
1057
+ return 0;
1058
+ } catch (error) {
1059
+ if (error instanceof UsageError) {
1060
+ io.stderr.write(`error: ${error.message}\n\n${HELP}`);
1061
+ return 2;
1062
+ }
1063
+ io.stderr.write(`error: ${error.message}\n`);
1064
+ return 1;
1065
+ }
1066
+ }
1067
+ export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_ALIASES, TEMPLATE_MANIFEST, TEMPLATE_SUMMARY, UsageError, VERSION, frameworkRange, isTemplate, lacksPluginShare, nameFrom, parseCreateOptions, processIo, replacePlaceholders, resolveTemplate, runCreate, startRepository };
1068
+
1069
+ //# sourceMappingURL=index.js.map