@opentf/create-afw 0.1.0 → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Tech Foundation and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -3,20 +3,25 @@
3
3
  Create an [AFW](https://afw.opentechf.org) app on **Vite and Node**:
4
4
 
5
5
  ```sh
6
- npm create @opentf/afw my-app
6
+ npm create @opentf/afw@latest
7
7
  ```
8
8
 
9
- Answer the prompts, or pass the choices:
9
+ The prompts ask for a project name, a template and a language (arrow keys and Enter),
10
+ and offer to install dependencies and start the dev server.
11
+
12
+ Or pass the choices:
10
13
 
11
14
  ```sh
12
- npm create @opentf/afw my-app -- --template=fullstack --language=ts
15
+ npm create @opentf/afw@latest my-app -- --template fullstack-ts
13
16
  ```
14
17
 
15
18
  | Option | Values |
16
19
  | --- | --- |
17
- | `--template` | `spa` (default), `fullstack`, `ssr`, `ssg` |
18
- | `--language` | `ts` (default), `js` (`--ts` / `--js` also work) |
19
- | `--yes`, `-y` | Use the defaults instead of asking |
20
+ | `-t`, `--template` | `spa`, `fullstack`, `ssr`, `ssg`; add `-ts` or `-js` for the language (`fullstack-js`) |
21
+ | `-l`, `--language` | `ts` (default) or `js` |
22
+ | `--overwrite` | Remove the files in a non-empty target directory first |
23
+ | `-i`, `--immediate` | Install dependencies and start the dev server |
24
+ | `--no-interactive` | Never ask; use defaults for anything not given (also the default without a terminal) |
20
25
 
21
26
  | Template | What you get |
22
27
  | --- | --- |
@@ -25,8 +30,11 @@ npm create @opentf/afw my-app -- --template=fullstack --language=ts
25
30
  | `ssr` | Server-rendered pages on a Node server, hydrated in the browser |
26
31
  | `ssg` | Every page prerendered to static HTML at build time |
27
32
 
28
- Every project comes with `dev`, `build` and `test` (Vitest) scripts, and either
29
- `start` (the built Node server) or `preview`. TypeScript projects add `typecheck`.
33
+ - A non-empty target directory: choose to cancel, remove its files, or ignore them.
34
+ - A folder name that is not a valid package name: you are asked for one (`My App` → `my-app`).
35
+ - Every project has `dev`, `build` and `test` (Vitest) scripts, and either `start` (the
36
+ built Node server) or `preview`. TypeScript projects add `typecheck`.
37
+ - New projects depend on the current AFW release from the npm registry.
30
38
 
31
39
  For the esdev + ES-Runtime workflow, use `esdev create` instead.
32
40
 
package/index.js CHANGED
@@ -1,133 +1,280 @@
1
1
  #!/usr/bin/env node
2
2
  // `npm create @opentf/afw` — scaffold an AFW app on Vite and Node.
3
3
  //
4
- // npm create @opentf/afw my-app
5
- // npm create @opentf/afw my-app -- --template=fullstack --language=ts
4
+ // npm create @opentf/afw@latest
5
+ // npm create @opentf/afw@latest my-app -- --template fullstack-ts
6
6
  //
7
7
  // For the esdev + ES-Runtime workflow, use `esdev create` instead.
8
8
 
9
- import { access, mkdir, readdir, writeFile } from "node:fs/promises";
9
+ import { spawn } from "node:child_process";
10
+ import { mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
10
11
  import { basename, dirname, join, relative, resolve } from "node:path";
11
- import { createInterface } from "node:readline/promises";
12
- import { stdin, stdout } from "node:process";
12
+ import { argv, cwd, env, exit, stdin, stdout } from "node:process";
13
+ import { fileURLToPath } from "node:url";
14
+ import { styleText } from "node:util";
15
+
16
+ import * as prompts from "@clack/prompts";
17
+ import { slugify } from "@opentf/std";
13
18
 
14
19
  import { TEMPLATES, projectFiles } from "./templates.js";
15
20
  import { afwVersions } from "./versions.js";
16
21
 
17
- const HELP = `Create an AFW app on Vite and Node.
22
+ const DEFAULT_DIRECTORY = "afw-app";
23
+ const LANGUAGES = { ts: "TypeScript", js: "JavaScript" };
24
+ const TEMPLATE_NAMES = Object.keys(TEMPLATES);
25
+ const VALID_NAME = /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/;
26
+
27
+ const HELP = `Usage: npm create @opentf/afw [directory] -- [options]
18
28
 
19
- Usage: npm create @opentf/afw [directory] -- [options]
29
+ Create an AFW app on Vite and Node. With no options, you are asked for each choice.
20
30
 
21
31
  Options:
22
- --template=<name> ${Object.keys(TEMPLATES).join(" | ")} (default: spa)
23
- ${Object.entries(TEMPLATES).map(([n, d]) => ` ${n.padEnd(10)} ${d}`).join("\n")}
24
- --language=<lang> js | ts (default: ts)
25
- --yes, -y Use the defaults instead of asking
26
- --help, -h Show this help
32
+ -t, --template <name> ${TEMPLATE_NAMES.map((t) => `${t}`).join(", ")}; add -ts or -js to pick the language
33
+ (e.g. fullstack-ts). TypeScript is the default.
34
+ -l, --language <lang> ts or js
35
+ --overwrite Remove the files in a non-empty target directory first
36
+ -i, --immediate Install dependencies and start the dev server
37
+ --no-interactive Never ask; use the defaults for anything not given
38
+ -h, --help Show this help
39
+
40
+ Templates:
41
+ ${TEMPLATE_NAMES.map((t) => ` ${t.padEnd(10)} ${TEMPLATES[t]}`).join("\n")}
27
42
 
28
43
  For the esdev + ES-Runtime workflow, use \`esdev create\`.`;
29
44
 
30
- const VALID_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
31
-
32
- export function parseArgs(argv) {
33
- const options = { directory: undefined, template: undefined, language: undefined, yes: false, help: false };
34
- for (const arg of argv) {
35
- if (arg === "--help" || arg === "-h") options.help = true;
36
- else if (arg === "--yes" || arg === "-y") options.yes = true;
37
- else if (arg.startsWith("--template=")) options.template = arg.slice(11);
38
- else if (arg.startsWith("--language=")) options.language = arg.slice(11);
39
- else if (arg === "--ts" || arg === "--typescript") options.language = "ts";
40
- else if (arg === "--js") options.language = "js";
41
- else if (arg.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
45
+ /** Parse the command line. Throws on an unknown option or value. */
46
+ export function parseArgs(args) {
47
+ const options = { directory: undefined, template: undefined, language: undefined, overwrite: false, immediate: false, interactive: undefined, help: false };
48
+ const value = (i, flag) => {
49
+ const next = args[i + 1];
50
+ if (next === undefined || next.startsWith("-")) throw new Error(`${flag} needs a value`);
51
+ return next;
52
+ };
53
+ for (let i = 0; i < args.length; i++) {
54
+ const arg = args[i];
55
+ const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, undefined];
56
+ if (flag === "-h" || flag === "--help") options.help = true;
57
+ else if (flag === "-t" || flag === "--template") options.template = inline ?? value(i++, flag);
58
+ else if (flag === "-l" || flag === "--language") options.language = inline ?? value(i++, flag);
59
+ else if (flag === "--ts" || flag === "--typescript") options.language = "ts";
60
+ else if (flag === "--js") options.language = "js";
61
+ else if (flag === "--overwrite") options.overwrite = true;
62
+ else if (flag === "-i" || flag === "--immediate") options.immediate = true;
63
+ else if (flag === "--no-interactive" || flag === "-y" || flag === "--yes") options.interactive = false;
64
+ else if (flag === "--interactive") options.interactive = true;
65
+ else if (flag.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
42
66
  else if (options.directory === undefined) options.directory = arg;
43
67
  else throw new Error(`Unexpected argument: ${arg}`);
44
68
  }
45
- if (options.template !== undefined && !TEMPLATES[options.template]) {
46
- throw new Error(`Unknown template "${options.template}". Choose one of: ${Object.keys(TEMPLATES).join(", ")}`);
69
+ if (options.template !== undefined) {
70
+ const match = options.template.match(/^(.*?)(?:-(ts|js))?$/);
71
+ if (!TEMPLATES[match[1]]) {
72
+ throw new Error(`Unknown template "${options.template}". Choose one of: ${TEMPLATE_NAMES.join(", ")} (optionally with -ts or -js).`);
73
+ }
74
+ options.template = match[1];
75
+ if (match[2]) {
76
+ if (options.language && options.language !== match[2]) throw new Error(`--template ${match[1]}-${match[2]} conflicts with --language ${options.language}`);
77
+ options.language = match[2];
78
+ }
47
79
  }
48
- if (options.language !== undefined && !["js", "ts"].includes(options.language)) {
49
- throw new Error(`Unknown language "${options.language}". Choose js or ts.`);
80
+ if (options.language !== undefined && !LANGUAGES[options.language]) {
81
+ throw new Error(`Unknown language "${options.language}". Choose ts or js.`);
50
82
  }
51
83
  return options;
52
84
  }
53
85
 
54
86
  /** The package manager that ran us (`npm create`, `pnpm create`, …). */
55
- export function packageManager(userAgent = process.env.npm_config_user_agent ?? "") {
56
- const name = userAgent.split("/")[0];
57
- return ["pnpm", "yarn", "bun"].includes(name) ? name : "npm";
87
+ export function packageManager(userAgent = env.npm_config_user_agent ?? "") {
88
+ const name = userAgent.split(" ")[0]?.split("/")[0];
89
+ return ["pnpm", "yarn", "bun", "deno"].includes(name) ? name : "npm";
58
90
  }
59
91
 
60
- async function isEmptyDir(dir) {
92
+ /** Whether `name` can be an npm package name. */
93
+ export const isValidPackageName = (name) => VALID_NAME.test(name);
94
+
95
+ /** A valid package name derived from a folder name (`My App` → `my-app`). */
96
+ export const toValidPackageName = (name) => slugify(name) || "afw-app";
97
+
98
+ async function isEmpty(dir) {
61
99
  try {
62
- return (await readdir(dir)).filter((f) => f !== ".git").length === 0;
100
+ return (await readdir(dir)).every((entry) => entry === ".git");
63
101
  } catch {
64
102
  return true;
65
103
  }
66
104
  }
67
105
 
68
- async function ask(rl, question, fallback) {
69
- const answer = (await rl.question(`${question} (${fallback}): `)).trim();
70
- return answer || fallback;
71
- }
72
-
73
- async function choose(rl, question, choices, fallback) {
74
- const keys = Object.keys(choices);
75
- stdout.write(`${question}\n${keys.map((k, i) => ` ${i + 1}. ${k.padEnd(10)} ${choices[k]}`).join("\n")}\n`);
76
- for (;;) {
77
- const answer = (await rl.question(`Choose 1-${keys.length} (${fallback}): `)).trim();
78
- if (!answer) return fallback;
79
- const picked = keys[Number(answer) - 1] ?? (choices[answer] ? answer : undefined);
80
- if (picked) return picked;
106
+ async function emptyDir(dir) {
107
+ for (const entry of await readdir(dir)) {
108
+ if (entry !== ".git") await rm(join(dir, entry), { recursive: true, force: true });
81
109
  }
82
110
  }
83
111
 
84
- /** Scaffold a project. Returns the directory and the files written. */
85
- export async function create({ directory, template = "spa", language = "ts", cwd = process.cwd() }) {
86
- const target = resolve(cwd, directory);
87
- const name = basename(target);
88
- if (!VALID_NAME.test(name)) throw new Error(`"${name}" is not a valid package name: use lowercase letters, digits, "-", "_" or ".".`);
89
- if (!(await isEmptyDir(target))) throw new Error(`${target} is not empty.`);
112
+ /**
113
+ * Scaffold a project. `existing`: what to do with a non-empty target — `"error"`
114
+ * (default), `"remove"` its files first, or `"ignore"` and write beside them.
115
+ */
116
+ export async function create({
117
+ directory = DEFAULT_DIRECTORY, template = "spa", language = "ts", packageName, existing = "error", cwd: base = cwd(),
118
+ } = {}) {
119
+ const target = resolve(base, directory);
120
+ const name = packageName ?? basename(target);
121
+ if (!isValidPackageName(name)) throw new Error(`"${name}" is not a valid package name: use lowercase letters, digits, "-", "_" or ".".`);
122
+ if (!(await isEmpty(target))) {
123
+ if (existing === "remove") await emptyDir(target);
124
+ else if (existing !== "ignore") throw new Error(`${target} is not empty. Use --overwrite to remove its files.`);
125
+ }
90
126
  const files = projectFiles({ name, template, typescript: language === "ts", versions: await afwVersions() });
91
127
  for (const [path, contents] of Object.entries(files)) {
92
128
  const file = join(target, path);
93
129
  await mkdir(dirname(file), { recursive: true });
94
130
  await writeFile(file, contents);
95
131
  }
96
- return { target, files: Object.keys(files) };
132
+ return { target, name, files: Object.keys(files) };
133
+ }
134
+
135
+ /** The commands to run next, for the package manager in use. */
136
+ export function nextSteps({ directory, pm }) {
137
+ const run = (script) => (pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`);
138
+ return [...(directory === "." ? [] : [`cd ${/\s/.test(directory) ? JSON.stringify(directory) : directory}`]), `${pm} install`, run("dev")];
139
+ }
140
+
141
+ // Exit on Ctrl+C or Escape, as create-vite does.
142
+ function cancelled() {
143
+ prompts.cancel("Operation cancelled.");
144
+ exit(0);
97
145
  }
98
146
 
99
- async function main(argv) {
100
- const options = parseArgs(argv);
147
+ const ask = async (prompt) => {
148
+ const answer = await prompt;
149
+ if (prompts.isCancel(answer)) cancelled();
150
+ return answer;
151
+ };
152
+
153
+ function run(command, args, options) {
154
+ return new Promise((done, fail) => {
155
+ const child = spawn(command, args, { stdio: "inherit", shell: process.platform === "win32", ...options });
156
+ child.once("error", fail);
157
+ child.once("close", (code) => (code === 0 ? done() : fail(new Error(`${command} ${args.join(" ")} exited with ${code}`))));
158
+ });
159
+ }
160
+
161
+ export async function main(args = argv.slice(2)) {
162
+ let options;
163
+ try {
164
+ options = parseArgs(args);
165
+ } catch (error) {
166
+ console.error(`${styleText("red", "✖")} ${error.message}\n\nRun with --help for usage.`);
167
+ exit(1);
168
+ }
101
169
  if (options.help) {
102
170
  console.log(HELP);
103
171
  return;
104
172
  }
105
- const interactive = stdin.isTTY && stdout.isTTY && !options.yes;
106
- if (interactive && (!options.directory || !options.template || !options.language)) {
107
- const rl = createInterface({ input: stdin, output: stdout });
108
- try {
109
- options.directory ??= await ask(rl, "Project name", "afw-app");
110
- options.template ??= await choose(rl, "Template:", TEMPLATES, "spa");
111
- options.language ??= await choose(rl, "Language:", { ts: "TypeScript", js: "JavaScript" }, "ts");
112
- } finally {
113
- rl.close();
173
+ const interactive = options.interactive ?? (stdin.isTTY && stdout.isTTY && !prompts.isCI());
174
+ const pm = packageManager();
175
+
176
+ prompts.intro(styleText(["bgCyan", "black"], " create-afw "));
177
+
178
+ // Project name → target directory.
179
+ let directory = options.directory;
180
+ if (!directory && interactive) {
181
+ directory = await ask(prompts.text({
182
+ message: "Project name:",
183
+ placeholder: DEFAULT_DIRECTORY,
184
+ defaultValue: DEFAULT_DIRECTORY,
185
+ }));
186
+ }
187
+ directory = (directory || DEFAULT_DIRECTORY).trim().replace(/\/+$/, "") || DEFAULT_DIRECTORY;
188
+ const target = resolve(cwd(), directory);
189
+
190
+ // A target that already has files.
191
+ let existing = options.overwrite ? "remove" : "error";
192
+ if (!options.overwrite && !(await isEmpty(target))) {
193
+ if (!interactive) {
194
+ prompts.cancel(`Target directory "${directory}" is not empty. Use --overwrite to remove its files.`);
195
+ exit(1);
114
196
  }
197
+ existing = await ask(prompts.select({
198
+ message: `${directory === "." ? "Current directory" : `Target directory "${directory}"`} is not empty. How do you want to continue?`,
199
+ options: [
200
+ { value: "cancel", label: "Cancel" },
201
+ { value: "remove", label: "Remove existing files and continue" },
202
+ { value: "ignore", label: "Ignore files and continue" },
203
+ ],
204
+ }));
205
+ if (existing === "cancel") cancelled();
206
+ }
207
+
208
+ // The package name, when the folder name cannot be one.
209
+ let packageName = basename(target);
210
+ if (!isValidPackageName(packageName)) {
211
+ packageName = interactive
212
+ ? await ask(prompts.text({
213
+ message: "Package name:",
214
+ defaultValue: toValidPackageName(packageName),
215
+ placeholder: toValidPackageName(packageName),
216
+ validate: (value) => (value === "" || isValidPackageName(value) ? undefined : "Invalid package.json name"),
217
+ }))
218
+ : toValidPackageName(packageName);
219
+ packageName ||= toValidPackageName(basename(target));
220
+ }
221
+
222
+ const template = options.template ?? (interactive
223
+ ? await ask(prompts.select({
224
+ message: "Select a template:",
225
+ options: TEMPLATE_NAMES.map((value) => ({ value, label: value, hint: TEMPLATES[value] })),
226
+ }))
227
+ : "spa");
228
+
229
+ const language = options.language ?? (interactive
230
+ ? await ask(prompts.select({
231
+ message: "Select a language:",
232
+ options: Object.entries(LANGUAGES).map(([value, label]) => ({ value, label })),
233
+ }))
234
+ : "ts");
235
+
236
+ const immediate = options.immediate ||
237
+ (interactive && await ask(prompts.confirm({ message: `Install with ${pm} and start now?`, initialValue: false })));
238
+
239
+ const where = relative(cwd(), target) || ".";
240
+ prompts.log.step(`Scaffolding ${template} (${LANGUAGES[language]}) in ${styleText("cyan", target)}`);
241
+ try {
242
+ await create({ directory: target, template, language, packageName, existing });
243
+ } catch (error) {
244
+ prompts.cancel(error.message);
245
+ exit(1);
246
+ }
247
+
248
+ if (!immediate) {
249
+ const steps = nextSteps({ directory: where, pm }).map((s) => ` ${styleText("cyan", s)}`).join("\n");
250
+ prompts.outro(`Done. Now run:\n\n${steps}\n`);
251
+ return;
252
+ }
253
+ prompts.log.step(`Installing dependencies with ${pm}…`);
254
+ try {
255
+ await run(pm, ["install"], { cwd: target });
256
+ } catch (error) {
257
+ prompts.cancel(`${error.message}. Run "${pm} install" in ${where} to retry.`);
258
+ exit(1);
259
+ }
260
+ prompts.outro("Starting the dev server…");
261
+ await run(pm, pm === "npm" || pm === "bun" ? ["run", "dev"] : ["dev"], { cwd: target });
262
+ }
263
+
264
+ // Run as a CLI, not when imported (tests). The bin is a symlink under npm, so both
265
+ // paths are resolved before comparing.
266
+ async function invokedDirectly() {
267
+ if (!argv[1]) return false;
268
+ try {
269
+ return (await realpath(argv[1])) === (await realpath(fileURLToPath(import.meta.url)));
270
+ } catch {
271
+ return false;
115
272
  }
116
- options.directory ??= "afw-app";
117
- const { target } = await create(options);
118
- const pm = packageManager();
119
- const run = (script) => (pm === "npm" ? `npm run ${script}` : `${pm} ${script}`);
120
- const dir = relative(process.cwd(), target) || ".";
121
- console.log(`\nCreated ${options.template ?? "spa"} app in ${dir}\n\nNext:\n${dir === "." ? "" : ` cd ${dir}\n`} ${pm} install\n ${run("dev")}\n`);
122
273
  }
123
274
 
124
- // Run as a CLI (not when imported by the tests).
125
- const invoked = process.argv[1] && (await access(process.argv[1]).then(() => true, () => false))
126
- ? (await import("node:fs")).realpathSync(process.argv[1]) === (await import("node:url")).fileURLToPath(import.meta.url)
127
- : false;
128
- if (invoked) {
129
- main(process.argv.slice(2)).catch((error) => {
130
- console.error(`✗ ${error.message}`);
131
- process.exit(1);
275
+ if (await invokedDirectly()) {
276
+ main().catch((error) => {
277
+ console.error(`${styleText("red", "✖")} ${error?.message ?? error}`);
278
+ exit(1);
132
279
  });
133
280
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/create-afw",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Create an AFW app on Vite and Node: npm create @opentf/afw.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "devDependencies": {
25
25
  "@opentf/afw": "0.34.0",
26
26
  "@opentf/afw-test": "1.29.0",
27
- "@opentf/vite-plugin-afw": "0.1.0",
27
+ "@opentf/vite-plugin-afw": "0.2.0",
28
28
  "happy-dom": "21.0.4",
29
29
  "vite": "8.3.5",
30
30
  "vitest": "5.0.5"
@@ -47,5 +47,9 @@
47
47
  "license": "MIT",
48
48
  "publishConfig": {
49
49
  "access": "public"
50
+ },
51
+ "dependencies": {
52
+ "@clack/prompts": "1.8.1",
53
+ "@opentf/std": "0.20.0"
50
54
  }
51
55
  }
package/templates.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // The Vite + Node project templates. Each template is generated from one source for
2
2
  // both JavaScript and TypeScript, so the two never drift apart.
3
3
 
4
+ import { escapeHTML } from "@opentf/std";
5
+
4
6
  export const TEMPLATES = {
5
7
  spa: "Single-page app, rendered in the browser",
6
8
  fullstack: "SPA plus API routes, middleware and loaders on a Node server",
@@ -89,7 +91,7 @@ ${ts ? "export default defineConfig(" : "export default "}{
89
91
  <head>
90
92
  <meta charset="utf-8" />
91
93
  <meta name="viewport" content="width=device-width, initial-scale=1" />
92
- <title>${escapeHtml(name)}</title>
94
+ <title>${escapeHTML(name)}</title>
93
95
  <link rel="stylesheet" href="/app/global.css" />
94
96
  </head>
95
97
  <body>
@@ -145,7 +147,7 @@ export const metadata = { title: "${escapeJs(name)}" };
145
147
  export default function Home() {
146
148
  return (
147
149
  <section>
148
- <h1>${escapeHtml(name)}</h1>
150
+ <h1>${escapeHTML(name)}</h1>
149
151
  <p>Edit <code>app/page.${jsx}</code> and save: the page updates in place.</p>
150
152
  <Counter start={0} />
151
153
  </section>
@@ -247,10 +249,6 @@ function json(value) {
247
249
  return `${JSON.stringify(value, null, 2)}\n`;
248
250
  }
249
251
 
250
- function escapeHtml(text) {
251
- return String(text).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
252
- }
253
-
254
252
  function escapeJs(text) {
255
253
  return String(text).replace(/[\\"]/g, "\\$&");
256
254
  }
package/versions.js CHANGED
@@ -1,20 +1,53 @@
1
- // The AFW package versions a new project depends on: the ones this scaffolder was
2
- // released with (`versions.json`, written by `npm run build`), or — in the AFW
3
- // repository itself — the workspace packages' current versions.
1
+ // The AFW package versions a new project depends on, resolved so the scaffolder works
2
+ // however it was installed:
3
+ //
4
+ // 1. `versions.json` beside this file, when a release build wrote one;
5
+ // 2. the sibling workspace packages, inside the AFW repository;
6
+ // 3. the npm registry's `latest` for each package (`npm create` has just reached it);
7
+ // 4. the `latest` dist-tag, so scaffolding never fails on a lookup.
4
8
 
5
9
  import { readFile } from "node:fs/promises";
6
10
 
11
+ import { timeoutRun } from "@opentf/std";
12
+
7
13
  export const AFW_PACKAGES = { "@opentf/afw": "afw", "@opentf/afw-test": "afw-test", "@opentf/vite-plugin-afw": "vite-plugin-afw" };
8
14
 
9
- export async function afwVersions() {
10
- try {
11
- return JSON.parse(await readFile(new URL("./versions.json", import.meta.url), "utf8"));
12
- } catch {
13
- const versions = {};
14
- for (const [name, folder] of Object.entries(AFW_PACKAGES)) {
15
- const manifest = JSON.parse(await readFile(new URL(`../${folder}/package.json`, import.meta.url), "utf8"));
16
- versions[name] = `^${manifest.version}`;
15
+ const REGISTRY_TIMEOUT_MS = 5000;
16
+
17
+ async function fromFile() {
18
+ return JSON.parse(await readFile(new URL("./versions.json", import.meta.url), "utf8"));
19
+ }
20
+
21
+ async function fromWorkspace() {
22
+ const versions = {};
23
+ for (const [name, folder] of Object.entries(AFW_PACKAGES)) {
24
+ const manifest = JSON.parse(await readFile(new URL(`../${folder}/package.json`, import.meta.url), "utf8"));
25
+ if (manifest.name !== name) throw new Error(`not the ${name} workspace package`);
26
+ versions[name] = `^${manifest.version}`;
27
+ }
28
+ return versions;
29
+ }
30
+
31
+ /** `^<latest>` for each package from the npm registry (`npm_config_registry` honoured). */
32
+ export async function fromRegistry({ registry = process.env.npm_config_registry || "https://registry.npmjs.org/", fetch = globalThis.fetch } = {}) {
33
+ const base = registry.endsWith("/") ? registry : `${registry}/`;
34
+ const entries = await Promise.all(Object.keys(AFW_PACKAGES).map(async (name) => {
35
+ const res = await timeoutRun(() => fetch(`${base}${name}/latest`, { headers: { accept: "application/json" } }), REGISTRY_TIMEOUT_MS);
36
+ if (!res.ok) throw new Error(`${name}: registry answered ${res.status}`);
37
+ const { version } = await res.json();
38
+ if (typeof version !== "string") throw new Error(`${name}: no version in the registry answer`);
39
+ return [name, `^${version}`];
40
+ }));
41
+ return Object.fromEntries(entries);
42
+ }
43
+
44
+ export async function afwVersions(options = {}) {
45
+ for (const source of [fromFile, fromWorkspace, () => fromRegistry(options)]) {
46
+ try {
47
+ return await source();
48
+ } catch {
49
+ // try the next source
17
50
  }
18
- return versions;
19
51
  }
52
+ return Object.fromEntries(Object.keys(AFW_PACKAGES).map((name) => [name, "latest"]));
20
53
  }
package/versions.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "@opentf/afw": "^0.34.0",
3
+ "@opentf/afw-test": "^1.29.0",
4
+ "@opentf/vite-plugin-afw": "^0.2.0"
5
+ }