@opentf/create-afw 0.0.0-stage → 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
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @opentf/create-afw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create an [AFW](https://afw.opentechf.org) app on **Vite and Node**:
4
+
5
+ ```sh
6
+ npm create @opentf/afw@latest
7
+ ```
8
+
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:
13
+
14
+ ```sh
15
+ npm create @opentf/afw@latest my-app -- --template fullstack-ts
16
+ ```
17
+
18
+ | Option | Values |
19
+ | --- | --- |
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) |
25
+
26
+ | Template | What you get |
27
+ | --- | --- |
28
+ | `spa` | Single-page app, rendered in the browser |
29
+ | `fullstack` | SPA plus API routes, middleware and loaders on a Node server |
30
+ | `ssr` | Server-rendered pages on a Node server, hydrated in the browser |
31
+ | `ssg` | Every page prerendered to static HTML at build time |
32
+
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.
38
+
39
+ For the esdev + ES-Runtime workflow, use `esdev create` instead.
40
+
41
+ ## License
42
+
43
+ MIT
package/index.js ADDED
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ // `npm create @opentf/afw` — scaffold an AFW app on Vite and Node.
3
+ //
4
+ // npm create @opentf/afw@latest
5
+ // npm create @opentf/afw@latest my-app -- --template fullstack-ts
6
+ //
7
+ // For the esdev + ES-Runtime workflow, use `esdev create` instead.
8
+
9
+ import { spawn } from "node:child_process";
10
+ import { mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
11
+ import { basename, dirname, join, relative, resolve } from "node:path";
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";
18
+
19
+ import { TEMPLATES, projectFiles } from "./templates.js";
20
+ import { afwVersions } from "./versions.js";
21
+
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]
28
+
29
+ Create an AFW app on Vite and Node. With no options, you are asked for each choice.
30
+
31
+ Options:
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")}
42
+
43
+ For the esdev + ES-Runtime workflow, use \`esdev create\`.`;
44
+
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}`);
66
+ else if (options.directory === undefined) options.directory = arg;
67
+ else throw new Error(`Unexpected argument: ${arg}`);
68
+ }
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
+ }
79
+ }
80
+ if (options.language !== undefined && !LANGUAGES[options.language]) {
81
+ throw new Error(`Unknown language "${options.language}". Choose ts or js.`);
82
+ }
83
+ return options;
84
+ }
85
+
86
+ /** The package manager that ran us (`npm create`, `pnpm create`, …). */
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";
90
+ }
91
+
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) {
99
+ try {
100
+ return (await readdir(dir)).every((entry) => entry === ".git");
101
+ } catch {
102
+ return true;
103
+ }
104
+ }
105
+
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 });
109
+ }
110
+ }
111
+
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
+ }
126
+ const files = projectFiles({ name, template, typescript: language === "ts", versions: await afwVersions() });
127
+ for (const [path, contents] of Object.entries(files)) {
128
+ const file = join(target, path);
129
+ await mkdir(dirname(file), { recursive: true });
130
+ await writeFile(file, contents);
131
+ }
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);
145
+ }
146
+
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
+ }
169
+ if (options.help) {
170
+ console.log(HELP);
171
+ return;
172
+ }
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);
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;
272
+ }
273
+ }
274
+
275
+ if (await invokedDirectly()) {
276
+ main().catch((error) => {
277
+ console.error(`${styleText("red", "✖")} ${error?.message ?? error}`);
278
+ exit(1);
279
+ });
280
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@opentf/create-afw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Create an AFW app on Vite and Node: npm create @opentf/afw.",
5
+ "type": "module",
6
+ "bin": {
7
+ "create-afw": "./index.js"
8
+ },
9
+ "scripts": {
10
+ "build": "cp ../../LICENSE LICENSE && node scripts/write-versions.mjs"
11
+ },
12
+ "exports": {
13
+ ".": "./index.js"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "templates.js",
18
+ "versions.js",
19
+ "versions.json"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "devDependencies": {
25
+ "@opentf/afw": "0.34.0",
26
+ "@opentf/afw-test": "1.29.0",
27
+ "@opentf/vite-plugin-afw": "0.2.0",
28
+ "happy-dom": "21.0.4",
29
+ "vite": "8.3.5",
30
+ "vitest": "5.0.5"
31
+ },
32
+ "keywords": [
33
+ "afw",
34
+ "opentf",
35
+ "create",
36
+ "scaffold",
37
+ "vite",
38
+ "starter"
39
+ ],
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/Open-Tech-Foundation/afw.git",
43
+ "directory": "packages/create-afw"
44
+ },
45
+ "homepage": "https://afw.opentechf.org/docs",
46
+ "bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
47
+ "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "dependencies": {
52
+ "@clack/prompts": "1.8.1",
53
+ "@opentf/std": "0.20.0"
54
+ }
55
+ }
package/templates.js ADDED
@@ -0,0 +1,254 @@
1
+ // The Vite + Node project templates. Each template is generated from one source for
2
+ // both JavaScript and TypeScript, so the two never drift apart.
3
+
4
+ import { escapeHTML } from "@opentf/std";
5
+
6
+ export const TEMPLATES = {
7
+ spa: "Single-page app, rendered in the browser",
8
+ fullstack: "SPA plus API routes, middleware and loaders on a Node server",
9
+ ssr: "Server-rendered pages on a Node server, hydrated in the browser",
10
+ ssg: "Every page prerendered to static HTML at build time",
11
+ };
12
+
13
+ // The third-party tools a new project starts on. AFW's own packages take the
14
+ // versions this scaffolder was released with (versions.js).
15
+ export const TOOL_VERSIONS = {
16
+ vite: "^8.3.5",
17
+ vitest: "^5.0.5",
18
+ "happy-dom": "^21.0.4",
19
+ typescript: "^6.0.3",
20
+ };
21
+
22
+ const MODE = { spa: "spa", fullstack: "spa", ssr: "ssr", ssg: "ssg" };
23
+ const hasServer = (template) => template === "fullstack" || template === "ssr";
24
+
25
+ /**
26
+ * The files of a new project, as `{ relativePath: contents }`.
27
+ *
28
+ * @param {{ name: string, template: keyof TEMPLATES, typescript: boolean, versions: Record<string, string> }} options
29
+ */
30
+ export function projectFiles({ name, template, typescript, versions }) {
31
+ if (!TEMPLATES[template]) throw new Error(`Unknown template "${template}". Choose one of: ${Object.keys(TEMPLATES).join(", ")}`);
32
+ const ts = typescript;
33
+ const js = ts ? "ts" : "js";
34
+ const jsx = ts ? "tsx" : "jsx";
35
+ const server = hasServer(template);
36
+ const mode = MODE[template];
37
+ const files = {};
38
+
39
+ const scripts = { dev: "vite", build: "vite build" };
40
+ if (server) scripts.start = "node dist/server/index.js";
41
+ else scripts.preview = "vite preview";
42
+ scripts.test = "vitest run";
43
+ if (ts) scripts.typecheck = "tsc";
44
+ const devDependencies = {
45
+ "@opentf/afw-test": versions["@opentf/afw-test"],
46
+ "@opentf/vite-plugin-afw": versions["@opentf/vite-plugin-afw"],
47
+ "happy-dom": TOOL_VERSIONS["happy-dom"],
48
+ ...(ts ? { typescript: TOOL_VERSIONS.typescript } : {}),
49
+ vite: TOOL_VERSIONS.vite,
50
+ vitest: TOOL_VERSIONS.vitest,
51
+ };
52
+ files["package.json"] = json({
53
+ name, private: true, type: "module", scripts,
54
+ dependencies: { "@opentf/afw": versions["@opentf/afw"] },
55
+ devDependencies,
56
+ });
57
+
58
+ files[`vite.config.${js}`] = `import afw from "@opentf/vite-plugin-afw";
59
+ ${ts ? 'import { defineConfig } from "vitest/config";\n' : ""}
60
+ ${ts ? "export default defineConfig(" : "export default "}{
61
+ plugins: [afw({ mode: "${mode}"${mode === "ssg" ? ', baseUrl: "" /* your site URL, e.g. "https://example.com", enables sitemap.xml */' : ""} })],
62
+ test: {
63
+ environment: "happy-dom",
64
+ setupFiles: ["@opentf/afw-test/vitest"],
65
+ },
66
+ }${ts ? ")" : ""};
67
+ `;
68
+
69
+ if (ts) {
70
+ files["tsconfig.json"] = json({
71
+ compilerOptions: {
72
+ target: "ESNext",
73
+ module: "ESNext",
74
+ moduleResolution: "bundler",
75
+ lib: ["ESNext", "DOM", "DOM.Iterable"],
76
+ jsx: "preserve",
77
+ jsxImportSource: "@opentf/afw",
78
+ types: ["@opentf/vite-plugin-afw/client"],
79
+ strict: true,
80
+ noEmit: true,
81
+ isolatedModules: true,
82
+ skipLibCheck: true,
83
+ allowImportingTsExtensions: true,
84
+ },
85
+ include: ["app", "tests", "entry.ts", "vite.config.ts"],
86
+ });
87
+ }
88
+
89
+ files["index.html"] = `<!doctype html>
90
+ <html lang="en">
91
+ <head>
92
+ <meta charset="utf-8" />
93
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
94
+ <title>${escapeHTML(name)}</title>
95
+ <link rel="stylesheet" href="/app/global.css" />
96
+ </head>
97
+ <body>
98
+ <div id="app"></div>
99
+ <script type="module" src="/entry.${js}"></script>
100
+ </body>
101
+ </html>
102
+ `;
103
+
104
+ files[`entry.${js}`] = `import { mountApp } from "@opentf/afw";
105
+ import { guard, loaderRoutes, pages } from "@afw/routes";
106
+
107
+ mountApp({ pages, guard, loaders: loaderRoutes, target: document.getElementById("app")${ts ? "!" : ""} });
108
+ `;
109
+
110
+ files["app/global.css"] = `:root {
111
+ font-family: system-ui, sans-serif;
112
+ color-scheme: light dark;
113
+ }
114
+
115
+ body {
116
+ margin: 0 auto;
117
+ max-width: 48rem;
118
+ padding: 2rem 1rem;
119
+ }
120
+
121
+ nav {
122
+ display: flex;
123
+ gap: 1rem;
124
+ margin-bottom: 2rem;
125
+ }
126
+ `;
127
+
128
+ const navLinks = [["/", "Home"], ["/about", "About"], ...(server ? [["/todos", "Todos"]] : [])];
129
+ files[`app/layout.${jsx}`] = `import { Link } from "@opentf/afw";
130
+
131
+ export default function Layout({ children }${ts ? ": { children: unknown }" : ""}) {
132
+ return (
133
+ <>
134
+ <nav>
135
+ ${navLinks.map(([href, label]) => ` <Link href="${href}">${label}</Link>`).join("\n")}
136
+ </nav>
137
+ <main>{children}</main>
138
+ </>
139
+ );
140
+ }
141
+ `;
142
+
143
+ files[`app/page.${jsx}`] = `import Counter from "./Counter.${jsx}";
144
+
145
+ export const metadata = { title: "${escapeJs(name)}" };
146
+
147
+ export default function Home() {
148
+ return (
149
+ <section>
150
+ <h1>${escapeHTML(name)}</h1>
151
+ <p>Edit <code>app/page.${jsx}</code> and save: the page updates in place.</p>
152
+ <Counter start={0} />
153
+ </section>
154
+ );
155
+ }
156
+ `;
157
+
158
+ files[`app/Counter.${jsx}`] = `export default function Counter({ start = 0 }${ts ? ": { start?: number }" : ""}) {
159
+ let count = $state(start);
160
+ const doubled = $derived(count * 2);
161
+
162
+ return (
163
+ <p>
164
+ <button onclick={() => count++}>Count: {count}</button> Doubled: {doubled}
165
+ </p>
166
+ );
167
+ }
168
+ `;
169
+
170
+ files["app/about/page.md"] = `---
171
+ title: About
172
+ ---
173
+
174
+ # About
175
+
176
+ This page is Markdown. The AFW compiler turns it into a page like any other.
177
+ `;
178
+
179
+ if (server) {
180
+ files[`app/api/hello/route.${js}`] = `// GET /api/hello?name=… — API routes run on Node, so any npm package works here.
181
+ export function GET(request${ts ? ": Request" : ""}, { query, locals }${ts ? ": { query: Record<string, string>; locals: Record<string, unknown> }" : ""}) {
182
+ return Response.json({ message: \`Hello, \${query.name ?? "world"}!\`, requestId: locals.requestId });
183
+ }
184
+ `;
185
+ files[`app/_middleware.${js}`] = `// Runs for every request: pages, API routes and loader data alike.
186
+ export default async function middleware(request${ts ? ": Request" : ""}, context${ts ? ": { locals: Record<string, unknown> }" : ""}, next${ts ? ": () => Promise<Response>" : ""}) {
187
+ context.locals.requestId = crypto.randomUUID();
188
+ const response = await next();
189
+ response.headers.set("x-request-id", String(context.locals.requestId));
190
+ return response;
191
+ }
192
+ `;
193
+ files[`app/todos/loader.${js}`] = `// Loaders run on the server and feed their page through \`router.data\`.
194
+ const todos = ["Try the dev server", "Add an API route", "Deploy with npm start"];
195
+
196
+ export default async function loader() {
197
+ return { todos };
198
+ }
199
+ `;
200
+ files[`app/todos/page.${jsx}`] = `import { router } from "@opentf/afw";
201
+
202
+ export const metadata = { title: "Todos" };
203
+
204
+ export default function Todos() {
205
+ return (
206
+ <section>
207
+ <h1>Todos</h1>
208
+ <ul>
209
+ {(${ts ? "(router.data as { todos?: string[] } | undefined)" : "router.data"}?.todos ?? []).map((todo${ts ? ": string" : ""}) => <li>{todo}</li>)}
210
+ </ul>
211
+ </section>
212
+ );
213
+ }
214
+ `;
215
+ }
216
+
217
+ files[`tests/Counter.test.${js}`] = `import { expect, test } from "vitest";
218
+ import { render, userEvent } from "@opentf/afw-test";
219
+ import Counter from "../app/Counter.${jsx}";
220
+
221
+ test("counts clicks", async () => {
222
+ const { getByRole, getByText } = render(Counter, { start: 1 });
223
+ await userEvent.setup().click(getByRole("button", { name: "Count: 1" }));
224
+ expect(getByRole("button").textContent).toBe("Count: 2");
225
+ expect(getByText(/Doubled: 4/)).toBeTruthy();
226
+ });
227
+ `;
228
+
229
+ files[".gitignore"] = "node_modules\ndist\n";
230
+
231
+ const run = (script) => `npm run ${script}`;
232
+ files["README.md"] = `# ${name}
233
+
234
+ An [AFW](https://afw.opentechf.org) app on Vite and Node (${TEMPLATES[template].toLowerCase()}).
235
+
236
+ | Command | What it does |
237
+ | --- | --- |
238
+ | \`${run("dev")}\` | Start the dev server |
239
+ | \`${run("build")}\` | Build for production |
240
+ | ${server ? `\`npm start\` | Run the built Node server (\`PORT\`, \`HOST\`)` : `\`${run("preview")}\` | Preview the production build`} |
241
+ | \`${run("test")}\` | Run the tests with Vitest |
242
+ ${ts ? `| \`${run("typecheck")}\` | Check types |\n` : ""}
243
+ Pages live in \`app/\`: \`app/about/page.md\` is served at \`/about\`.${server ? " API routes (`route." + js + "`), middleware (`_middleware." + js + "`) and loaders (`loader." + js + "`) run on Node." : ""}
244
+ `;
245
+ return files;
246
+ }
247
+
248
+ function json(value) {
249
+ return `${JSON.stringify(value, null, 2)}\n`;
250
+ }
251
+
252
+ function escapeJs(text) {
253
+ return String(text).replace(/[\\"]/g, "\\$&");
254
+ }
package/versions.js ADDED
@@ -0,0 +1,53 @@
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.
8
+
9
+ import { readFile } from "node:fs/promises";
10
+
11
+ import { timeoutRun } from "@opentf/std";
12
+
13
+ export const AFW_PACKAGES = { "@opentf/afw": "afw", "@opentf/afw-test": "afw-test", "@opentf/vite-plugin-afw": "vite-plugin-afw" };
14
+
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
50
+ }
51
+ }
52
+ return Object.fromEntries(Object.keys(AFW_PACKAGES).map((name) => [name, "latest"]));
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
+ }