create-acrylblends 1.1.0 → 1.2.1

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/dist/index.d.ts CHANGED
@@ -77,6 +77,11 @@ export declare function nameFrom(directory: string): string;
77
77
  */
78
78
  export declare function frameworkRange(): string;
79
79
  export declare function replacePlaceholders(text: string, name: string): string;
80
+ /**
81
+ * 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
82
+ * version is the app as created. A folder that already is a repository, or a machine without git, is left alone.
83
+ */
84
+ export declare function startRepository(directory: string): void;
80
85
  /** Create the app. Returns the exit code: 0 done, 1 refused or failed, 2 a usage error. Never calls `process.exit`. */
81
86
  export declare function runCreate(argv: readonly string[], io?: Io): Promise<number>;
82
87
  //#endregion
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { createInterface } from "node:readline/promises";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { parseArgs } from "node:util";
9
9
  import { findSecrets } from "@webboxes/app-persistence";
10
+ import { createHash } from "node:crypto";
10
11
  //#region src/names.ts
11
12
  /**
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
@@ -28,10 +29,21 @@ var SourceError = class extends Error {
28
29
  name = "SourceError";
29
30
  };
30
31
  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
- const LIMITS = {
32
+ /** A template is copied whole into the person's new app, so it is held to the size of an app's source. */
33
+ const TEMPLATE_LIMITS = {
34
+ what: "template",
32
35
  files: 5e3,
33
36
  bytes: 52428800
34
37
  };
38
+ /**
39
+ * 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
40
+ * only stops a runaway download; the entry taken from it is a template and is held to the template's limits.
41
+ */
42
+ const REGISTRY_LIMITS = {
43
+ what: "registry",
44
+ files: 2e5,
45
+ bytes: 2147483648
46
+ };
35
47
  /** Recognise a source argument, or return `undefined` when it is not one (so the caller can report a usage error). */
36
48
  function parseSource(text, cwd) {
37
49
  const github = /^github:([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:#([A-Za-z0-9_./-]+))?$/.exec(text);
@@ -71,6 +83,19 @@ function parseSource(text, cwd) {
71
83
  };
72
84
  }
73
85
  }
86
+ /**
87
+ * A registry, as `--registry` names it: a source, or a folder written as a bare path (`my-registry`, `run/registry`). A registry is never a template name, so a
88
+ * path that is an existing folder is taken as one without the `./` a template source needs.
89
+ */
90
+ function parseRegistrySource(text, cwd) {
91
+ const source = parseSource(text, cwd);
92
+ if (source !== void 0) return source;
93
+ const path = resolve(cwd, text);
94
+ return existsSync(path) && lstatSync(path).isDirectory() ? {
95
+ kind: "folder",
96
+ path
97
+ } : void 0;
98
+ }
74
99
  const realFetchers = {
75
100
  async download(url) {
76
101
  const response = await fetch(url, { redirect: "follow" });
@@ -99,15 +124,15 @@ const realFetchers = {
99
124
  return join(dest, file);
100
125
  }
101
126
  };
102
- /** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives that are too big. */
103
- function extract(tarball, dir) {
127
+ /** Unpack a tarball into `dir`, dropping its single top folder; refuses links, paths that leave the folder, and archives over `limits`. */
128
+ function extract(tarball, dir, limits) {
104
129
  const list = spawnSync("tar", ["-tzf", tarball], {
105
130
  encoding: "utf8",
106
- maxBuffer: 67108864
131
+ maxBuffer: 268435456
107
132
  });
108
133
  if (list.status !== 0) throw new SourceError(`${tarball} is not a readable tar.gz archive`);
109
134
  const entries = list.stdout.split("\n").filter(Boolean);
110
- if (entries.length > LIMITS.files) throw new SourceError(`the template has more than ${LIMITS.files} files`);
135
+ if (entries.length > limits.files) throw new SourceError(`the ${limits.what} has more than ${limits.files} files`);
111
136
  for (const entry of entries) if (entry.startsWith("/") || entry.split("/").includes("..")) throw new SourceError(`the archive holds a path that leaves its folder: ${entry}`);
112
137
  mkdirSync(dir, { recursive: true });
113
138
  const run = spawnSync("tar", [
@@ -118,17 +143,17 @@ function extract(tarball, dir) {
118
143
  "--strip-components=1"
119
144
  ], { encoding: "utf8" });
120
145
  if (run.status !== 0) throw new SourceError(`could not unpack ${tarball}: ${run.stderr.trim()}`);
121
- checkTree(dir);
146
+ checkTree(dir, limits);
122
147
  }
123
- /** Refuse a tree that holds a link, or is larger than the limits; the same check for an unpacked archive and a copied folder. */
124
- function checkTree(dir) {
148
+ /** Refuse a tree that holds a link, or is larger than `limits`; the same check for an unpacked archive and a copied folder. */
149
+ function checkTree(dir, limits) {
125
150
  let bytes = 0;
126
151
  let count = 0;
127
152
  const walk = (folder) => {
128
153
  for (const entry of readdirSync(folder)) {
129
154
  const path = join(folder, entry);
130
155
  const info = lstatSync(path);
131
- if (info.isSymbolicLink()) throw new SourceError(`the template holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`);
156
+ if (info.isSymbolicLink()) throw new SourceError(`the ${limits.what} holds a symbolic link (${path.slice(dir.length + 1)}); links are not allowed`);
132
157
  if (info.isDirectory()) walk(path);
133
158
  else {
134
159
  bytes += info.size;
@@ -137,18 +162,21 @@ function checkTree(dir) {
137
162
  }
138
163
  };
139
164
  walk(dir);
140
- if (count > LIMITS.files) throw new SourceError(`the template has more than ${LIMITS.files} files`);
141
- if (bytes > LIMITS.bytes) throw new SourceError(`the template is larger than ${LIMITS.bytes / 1024 / 1024} MB`);
165
+ if (count > limits.files) throw new SourceError(`the ${limits.what} has more than ${limits.files} files`);
166
+ if (bytes > limits.bytes) throw new SourceError(`the ${limits.what} is larger than ${limits.bytes / 1024 / 1024} MB`);
142
167
  }
143
- /** Download or pack a source and unpack it into `dir` (which must not exist yet). Nothing in it is run. */
144
- async function fetchSource(source, dir, scratch, fetchers) {
168
+ /** Download or pack a template and unpack it into `dir` (which must not exist yet). Nothing in it is run. */
169
+ const fetchTemplate = (source, dir, scratch, fetchers) => fetchSource(source, dir, scratch, fetchers, TEMPLATE_LIMITS);
170
+ /** 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. */
171
+ const fetchRegistry = (source, dir, scratch, fetchers) => fetchSource(source, dir, scratch, fetchers, REGISTRY_LIMITS);
172
+ async function fetchSource(source, dir, scratch, fetchers, limits) {
145
173
  mkdirSync(scratch, { recursive: true });
146
174
  if (source.kind === "folder") {
147
175
  cpSync$1(source.path, dir, {
148
176
  recursive: true,
149
177
  filter: (path) => !/[\\/](\.git|node_modules)([\\/]|$)/.test(path.slice(source.path.length))
150
178
  });
151
- checkTree(dir);
179
+ checkTree(dir, limits);
152
180
  return;
153
181
  }
154
182
  let tarball;
@@ -158,7 +186,7 @@ async function fetchSource(source, dir, scratch, fetchers) {
158
186
  tarball = join(scratch, "source.tar.gz");
159
187
  writeFileSync(tarball, await fetchers.download(`https://codeload.github.com/${source.owner}/${source.repo}/tar.gz/${source.ref ?? "HEAD"}`));
160
188
  }
161
- extract(tarball, dir);
189
+ extract(tarball, dir, limits);
162
190
  }
163
191
  /** Read and check `acryl.template.json`; a source without it is not a template. */
164
192
  function readManifest(dir) {
@@ -241,13 +269,14 @@ const ACRYL_APP = "https://acryl.dev";
241
269
  /** A registry id: dotted, lower case (`acryl.gtd`, `acrylblends.notes-desktop`, `login.thing`). */
242
270
  const REGISTRY_ID = /^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;
243
271
  /** 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). */
244
- function registryRoot(unpacked) {
272
+ /** @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. */
273
+ function registryRoot(unpacked, label = "this registry") {
245
274
  for (const candidate of [unpacked, join(unpacked, "registry")]) if (existsSync(join(candidate, "index.json"))) return candidate;
246
- throw new SourceError("this registry has no index.json (it is a folder with index.json and blends/<id>/)");
275
+ 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)`);
247
276
  }
248
277
  /** Read the index of an unpacked registry. */
249
- function readRegistry(unpacked) {
250
- const root = registryRoot(unpacked);
278
+ function readRegistry(unpacked, label) {
279
+ const root = registryRoot(unpacked, label);
251
280
  let data;
252
281
  try {
253
282
  data = JSON.parse(readFileSync(join(root, "index.json"), "utf8"));
@@ -309,6 +338,119 @@ function ownManifest(text, name) {
309
338
  for (let at = end - 1; at > start; at -= 1) if (/^\s+license:/.test(lines[at] ?? "")) lines.splice(at, 1);
310
339
  return lines.join("\n");
311
340
  }
341
+ /**
342
+ * 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,
343
+ * 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
344
+ * read is left as it is (`npm run snapshot capture` writes it again).
345
+ */
346
+ function ownLock(text, manifestText, name) {
347
+ let lock;
348
+ try {
349
+ lock = JSON.parse(text);
350
+ } catch {
351
+ return text;
352
+ }
353
+ const origin = lock?.origin;
354
+ if (origin === null || typeof origin !== "object") return text;
355
+ const owned = {
356
+ ...lock,
357
+ origin: {
358
+ ...origin,
359
+ id: `acrylblends.${name}`,
360
+ digest: createHash("sha256").update(manifestText).digest("hex")
361
+ }
362
+ };
363
+ return `${JSON.stringify(owned, null, 2)}\n`;
364
+ }
365
+ /** A DSH profile name for an app, as the framework's scaffold writes it into `scripts/ide-host.mjs` (`acrylblends-<app>`). */
366
+ function profileNameFor(appName) {
367
+ const slug = appName.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-").replaceAll(/^-+|-+$/gu, "");
368
+ return `acrylblends-${slug === "" ? "app" : slug}`;
369
+ }
370
+ /**
371
+ * 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
372
+ * `init` set to the same name. A curated starter's manifest carries a display name ("Productivity Hub"), which the scaffold never wrote.
373
+ */
374
+ function starterName(manifestText, packageText) {
375
+ const fromManifest = manifestName(manifestText);
376
+ if (fromManifest !== void 0 || packageText === void 0) return fromManifest;
377
+ let name;
378
+ try {
379
+ name = JSON.parse(packageText).name;
380
+ } catch {
381
+ return;
382
+ }
383
+ return typeof name === "string" && name !== "" ? name : void 0;
384
+ }
385
+ /** The app's name as a starter's `blend.yaml` gives it (`metadata.name`), or undefined. */
386
+ function manifestName(text) {
387
+ const lines = text.split("\n");
388
+ const start = lines.findIndex((line) => /^metadata:\s*$/.test(line));
389
+ if (start < 0) return void 0;
390
+ for (let at = start + 1; at < lines.length && /^\s+\S|^\s*$/.test(lines[at] ?? ""); at += 1) {
391
+ const match = /^\s+name:\s*["']?([^"'#\s]+)["']?\s*(?:#.*)?$/.exec(lines[at] ?? "");
392
+ if (match) return match[1];
393
+ }
394
+ }
395
+ /**
396
+ * Where the scaffold wrote an app's name (its `__APP_NAME__`): the headings and the `description:` line of the agents' instructions and skills,
397
+ * 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.
398
+ */
399
+ const PROSE_FILES = [
400
+ "AGENTS.md",
401
+ "CLAUDE.md",
402
+ "README.md"
403
+ ];
404
+ /** The lines of those files the scaffold put the name on. */
405
+ const NAMED_LINE = /^(?:#{1,6} |description: )/;
406
+ const SKILL_SCOPES = [".claude/skills", ".agents/skills"];
407
+ const CODE_FILES = ["src/routes.ts", "src/app.ts"];
408
+ /**
409
+ * 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
410
+ * heading or `description:` line of the agents' instructions, skills and README, and in the `APP_NAME` constant; the host script's DSH profile
411
+ * 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
412
+ * recorded them.
413
+ * @returns the files it changed, relative to `dir`.
414
+ */
415
+ function renameApp(dir, from, to) {
416
+ if (from === to || !/^[A-Za-z0-9][\w.-]*$/.test(from)) return [];
417
+ const escaped = from.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
418
+ const whole = new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`, "g");
419
+ const prose = [...PROSE_FILES];
420
+ for (const scope of SKILL_SCOPES) {
421
+ const root = join(dir, scope);
422
+ if (!existsSync(root)) continue;
423
+ for (const skill of readdirSync(root, { withFileTypes: true })) if (skill.isDirectory()) prose.push(`${scope}/${skill.name}/SKILL.md`);
424
+ }
425
+ const changed = [];
426
+ const rewrite = (file, edit) => {
427
+ const path = join(dir, file);
428
+ if (!existsSync(path)) return;
429
+ const text = readFileSync(path, "utf8");
430
+ const next = edit(text);
431
+ if (next === text) return;
432
+ writeFileSync(path, next);
433
+ changed.push(file);
434
+ };
435
+ for (const file of prose) rewrite(file, (text) => text.split("\n").map((line) => NAMED_LINE.test(line) ? line.replace(whole, to) : line).join("\n"));
436
+ const constant = new RegExp(`(\\bAPP_NAME = )(['"])${escaped}\\2`, "g");
437
+ for (const file of CODE_FILES) rewrite(file, (text) => text.replace(constant, `$1$2${to}$2`));
438
+ rewrite("package-lock.json", (text) => {
439
+ try {
440
+ const lock = JSON.parse(text);
441
+ const root = lock.packages?.[""];
442
+ if (lock.name !== from && root?.name !== from) return text;
443
+ if (lock.name === from) lock.name = to;
444
+ if (root !== void 0 && root.name === from) root.name = to;
445
+ return `${JSON.stringify(lock, null, 2)}\n`;
446
+ } catch {
447
+ return text;
448
+ }
449
+ });
450
+ const profile = profileNameFor(from);
451
+ rewrite("scripts/ide-host.mjs", (text) => text.replaceAll(`'${profile}'`, `'${profileNameFor(to)}'`));
452
+ return changed;
453
+ }
312
454
  //#endregion
313
455
  //#region src/spawn.ts
314
456
  /**
@@ -560,6 +702,32 @@ function textFiles(root) {
560
702
  return found;
561
703
  }
562
704
  /**
705
+ * 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
706
+ * version is the app as created. A folder that already is a repository, or a machine without git, is left alone.
707
+ */
708
+ function startRepository(directory) {
709
+ if (existsSync(join(directory, ".git"))) return;
710
+ const run = (args) => spawnSync("git", args, {
711
+ cwd: directory,
712
+ stdio: "ignore",
713
+ windowsHide: true
714
+ }).status === 0;
715
+ if (!run(["init", "-q"])) return;
716
+ if (!run(["add", "-A"])) return;
717
+ run([
718
+ ...run(["config", "user.email"]) ? [] : [
719
+ "-c",
720
+ "user.name=acrylblends",
721
+ "-c",
722
+ "user.email=scaffold@acrylblends.invalid"
723
+ ],
724
+ "commit",
725
+ "-q",
726
+ "-m",
727
+ "Initial commit from acrylblends"
728
+ ]);
729
+ }
730
+ /**
563
731
  * Create an app from a template source (`github:`, `@scope/name`, a packed tarball). The source is fetched and unpacked into a scratch folder, checked
564
732
  * (manifest, secrets), and only then copied to the target; nothing in it is installed or run unless `--install`, which lists the scripts first.
565
733
  */
@@ -574,24 +742,32 @@ async function createFromSource(options, target, directory, io) {
574
742
  const fetchers = io.fetchers ?? realFetchers;
575
743
  let entry;
576
744
  if (REGISTRY_ID.test(options.source)) {
577
- const registrySource = parseSource(options.registry ?? "github:acrylblends/acrylblends.github.io", io.cwd);
745
+ const registrySource = parseRegistrySource(options.registry ?? "github:acrylblends/acrylblends.github.io", io.cwd);
578
746
  if (!registrySource) throw new UsageError(`unknown registry "${options.registry}" (${SOURCE_FORMS})`);
579
- await fetchSource(registrySource, join(scratch, "registry"), join(scratch, "download"), fetchers);
580
- const registry = readRegistry(join(scratch, "registry"));
747
+ await fetchRegistry(registrySource, join(scratch, "registry"), join(scratch, "download"), fetchers);
748
+ const registry = readRegistry(join(scratch, "registry"), registrySource.kind === "folder" ? registrySource.path : options.registry ?? "github:acrylblends/acrylblends.github.io");
581
749
  entry = pickEntry(registry.entries, options.source);
582
- await fetchSource({
750
+ await fetchTemplate({
583
751
  kind: "folder",
584
752
  path: join(registry.root, entry.path)
585
753
  }, join(scratch, "source"), join(scratch, "download"), fetchers);
586
754
  } else {
587
755
  const source = parseSource(options.source, io.cwd);
588
756
  if (!source) throw new UsageError(`unknown template source "${options.source}" (${SOURCE_FORMS})`);
589
- await fetchSource(source, join(scratch, "source"), join(scratch, "download"), fetchers);
757
+ await fetchTemplate(source, join(scratch, "source"), join(scratch, "download"), fetchers);
590
758
  }
591
759
  const manifest = readManifest(join(scratch, "source"));
592
760
  const staged = join(scratch, "app");
593
761
  const { files, lifecycle } = writeTemplate(join(scratch, "source"), staged, (text) => replacePlaceholders(text, name), frameworkRange(), name);
594
- if (entry !== void 0 && existsSync(join(staged, "blend.yaml"))) writeFileSync(join(staged, "blend.yaml"), ownManifest(readFileSync(join(staged, "blend.yaml"), "utf8"), name));
762
+ if (entry !== void 0 && existsSync(join(staged, "blend.yaml"))) {
763
+ const starterText = readFileSync(join(staged, "blend.yaml"), "utf8");
764
+ const sourcePackage = join(scratch, "source", "package.json");
765
+ const starter = starterName(starterText, existsSync(sourcePackage) ? readFileSync(sourcePackage, "utf8") : void 0);
766
+ if (starter !== void 0) renameApp(staged, starter, name);
767
+ const manifestText = ownManifest(starterText, name);
768
+ writeFileSync(join(staged, "blend.yaml"), manifestText);
769
+ if (existsSync(join(staged, "blend.lock.json"))) writeFileSync(join(staged, "blend.lock.json"), ownLock(readFileSync(join(staged, "blend.lock.json"), "utf8"), manifestText, name));
770
+ }
595
771
  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`);
596
772
  if (!existsSync(join(staged, "CLAUDE.md"))) copyFileSync(join(staged, "AGENTS.md"), join(staged, "CLAUDE.md"));
597
773
  const found = findSecrets(textFiles(staged));
@@ -601,6 +777,7 @@ async function createFromSource(options, target, directory, io) {
601
777
  }
602
778
  copyDocs(staged);
603
779
  cpSync(staged, target, { recursive: true });
780
+ startRepository(target);
604
781
  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`);
605
782
  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`);
606
783
  const pm = options.pm ?? PACKAGE_MANAGERS.find((m) => (io.env.npm_config_user_agent ?? "").startsWith(`${m}/`)) ?? "npm";
@@ -683,6 +860,6 @@ async function runCreate(argv, io = processIo()) {
683
860
  }
684
861
  }
685
862
  //#endregion
686
- export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_ALIASES, TEMPLATE_MANIFEST, TEMPLATE_SUMMARY, UsageError, VERSION, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, resolveTemplate, runCreate };
863
+ export { CLASS, CREATE, HELP, PACKAGE, PACKAGE_MANAGERS, TEMPLATES, TEMPLATE_ALIASES, TEMPLATE_MANIFEST, TEMPLATE_SUMMARY, UsageError, VERSION, frameworkRange, isTemplate, nameFrom, parseCreateOptions, processIo, replacePlaceholders, resolveTemplate, runCreate, startRepository };
687
864
 
688
865
  //# sourceMappingURL=index.js.map