@opentf/create-afw 0.2.0 → 0.4.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/README.md +27 -11
- package/index.js +99 -52
- package/package.json +8 -4
- package/templates.js +485 -118
- package/versions.js +6 -1
- package/versions.json +4 -3
package/README.md
CHANGED
|
@@ -6,34 +6,50 @@ Create an [AFW](https://afw.opentechf.org) app on **Vite and Node**:
|
|
|
6
6
|
npm create @opentf/afw@latest
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
The prompts ask for a project name
|
|
10
|
-
and
|
|
9
|
+
The prompts ask for a project name and a template, then only what that template needs
|
|
10
|
+
(arrow keys and Enter). The dependencies are installed and the command to start the
|
|
11
|
+
dev server is shown. Nothing is started for you.
|
|
12
|
+
|
|
13
|
+
| Prompt | Asked for | Choices |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| Template | every project | `app`, `docs`, `library` |
|
|
16
|
+
| Rendering | `app` | `spa` (in the browser), `ssr` (per request, hydrated), `ssg` (prerendered) |
|
|
17
|
+
| Server | `app`, unless `ssr` | API routes, middleware, loaders and server functions on Node: yes or no |
|
|
18
|
+
| Styling | `app`, `library` | CSS, or Tailwind CSS |
|
|
19
|
+
| Language | every project | TypeScript (default), JavaScript |
|
|
11
20
|
|
|
12
21
|
Or pass the choices:
|
|
13
22
|
|
|
14
23
|
```sh
|
|
15
|
-
npm create @opentf/afw@latest my-app -- --template
|
|
24
|
+
npm create @opentf/afw@latest my-app -- --template app --render ssg --server --tailwind
|
|
25
|
+
npm create @opentf/afw@latest my-docs -- --template docs-js
|
|
16
26
|
```
|
|
17
27
|
|
|
18
28
|
| Option | Values |
|
|
19
29
|
| --- | --- |
|
|
20
|
-
| `-t`, `--template` | `
|
|
30
|
+
| `-t`, `--template` | `app`, `docs`, `library`; add `-ts` or `-js` for the language (`app-js`) |
|
|
31
|
+
| `-r`, `--render` | `spa` (default), `ssr`, `ssg` — `app` only |
|
|
32
|
+
| `--server`, `--no-server` | Add a Node server, or not (default) — `app` only; `ssr` always has one |
|
|
33
|
+
| `-s`, `--styling` | `css` (default) or `tailwind`; `--tailwind` for short — `app` and `library` |
|
|
21
34
|
| `-l`, `--language` | `ts` (default) or `js` |
|
|
22
35
|
| `--overwrite` | Remove the files in a non-empty target directory first |
|
|
23
|
-
|
|
|
36
|
+
| `--no-install` | Skip installing dependencies |
|
|
24
37
|
| `--no-interactive` | Never ask; use defaults for anything not given (also the default without a terminal) |
|
|
25
38
|
|
|
26
39
|
| Template | What you get |
|
|
27
40
|
| --- | --- |
|
|
28
|
-
| `
|
|
29
|
-
| `
|
|
30
|
-
| `
|
|
31
|
-
|
|
41
|
+
| `app` | File-based pages and a component test; with a server, an API route, middleware, a loader and server functions |
|
|
42
|
+
| `docs` | An [`@opentf/afw-docs`](https://afw.opentechf.org/packages/afw-docs) site: MDX docs and a blog, prerendered, with search, RSS/Atom feeds, `sitemap.xml` and `llms.txt` |
|
|
43
|
+
| `library` | Components published as JSX source (`index.js` and `src/`), `@opentf/afw` as a peer dependency, a preview app and a test |
|
|
44
|
+
|
|
45
|
+
The names of earlier releases still work: `spa`, `fullstack` (`app --server`), `ssr`
|
|
46
|
+
and `ssg`.
|
|
32
47
|
|
|
33
48
|
- A non-empty target directory: choose to cancel, remove its files, or ignore them.
|
|
34
49
|
- A folder name that is not a valid package name: you are asked for one (`My App` → `my-app`).
|
|
35
|
-
-
|
|
36
|
-
built Node server) or `preview`.
|
|
50
|
+
- Apps and docs sites have `dev`, `build` and `test` (Vitest) scripts, and either `start`
|
|
51
|
+
(the built Node server) or `preview`. A library has `dev` (its preview) and `test`.
|
|
52
|
+
TypeScript projects add `typecheck`.
|
|
37
53
|
- New projects depend on the current AFW release from the npm registry.
|
|
38
54
|
|
|
39
55
|
For the esdev + ES-Runtime workflow, use `esdev create` instead.
|
package/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// `npm create @opentf/afw` — scaffold an AFW app on Vite and Node.
|
|
3
3
|
//
|
|
4
4
|
// npm create @opentf/afw@latest
|
|
5
|
-
// npm create @opentf/afw@latest my-app -- --template
|
|
5
|
+
// npm create @opentf/afw@latest my-app -- --template app --render ssr --styling tailwind
|
|
6
6
|
//
|
|
7
7
|
// For the esdev + ES-Runtime workflow, use `esdev create` instead.
|
|
8
8
|
|
|
@@ -16,35 +16,47 @@ import { styleText } from "node:util";
|
|
|
16
16
|
import * as prompts from "@clack/prompts";
|
|
17
17
|
import { slugify } from "@opentf/std";
|
|
18
18
|
|
|
19
|
-
import { TEMPLATES, projectFiles } from "./templates.js";
|
|
19
|
+
import { LEGACY_TEMPLATES, RENDERINGS, STYLINGS, TEMPLATES, projectFiles } from "./templates.js";
|
|
20
20
|
import { afwVersions } from "./versions.js";
|
|
21
21
|
|
|
22
22
|
const DEFAULT_DIRECTORY = "afw-app";
|
|
23
23
|
const LANGUAGES = { ts: "TypeScript", js: "JavaScript" };
|
|
24
24
|
const TEMPLATE_NAMES = Object.keys(TEMPLATES);
|
|
25
|
+
const SERVER_HINT = "API routes, middleware, loaders and server functions on Node";
|
|
25
26
|
const VALID_NAME = /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/;
|
|
26
27
|
|
|
27
28
|
const HELP = `Usage: npm create @opentf/afw [directory] -- [options]
|
|
28
29
|
|
|
29
|
-
Create an AFW
|
|
30
|
+
Create an AFW project on Vite and Node. With no options, you are asked for each choice.
|
|
30
31
|
|
|
31
32
|
Options:
|
|
32
|
-
-t, --template <name> ${TEMPLATE_NAMES.
|
|
33
|
-
|
|
33
|
+
-t, --template <name> ${TEMPLATE_NAMES.join(", ")} (add -ts or -js to pick the language)
|
|
34
|
+
-r, --render <mode> app: ${Object.keys(RENDERINGS).join(", ")}
|
|
35
|
+
--server app: add ${SERVER_HINT}
|
|
36
|
+
--no-server app: no server (not with --render ssr, which always has one)
|
|
37
|
+
-s, --styling <name> app and library: ${Object.keys(STYLINGS).join(", ")} (--tailwind for short)
|
|
34
38
|
-l, --language <lang> ts or js
|
|
35
39
|
--overwrite Remove the files in a non-empty target directory first
|
|
36
|
-
|
|
40
|
+
--no-install Skip installing dependencies
|
|
37
41
|
--no-interactive Never ask; use the defaults for anything not given
|
|
38
42
|
-h, --help Show this help
|
|
39
43
|
|
|
40
44
|
Templates:
|
|
41
45
|
${TEMPLATE_NAMES.map((t) => ` ${t.padEnd(10)} ${TEMPLATES[t]}`).join("\n")}
|
|
42
46
|
|
|
47
|
+
Renderings (app):
|
|
48
|
+
${Object.entries(RENDERINGS).map(([r, label]) => ` ${r.padEnd(10)} ${label}`).join("\n")}
|
|
49
|
+
|
|
50
|
+
Shorthands from earlier releases: ${Object.entries(LEGACY_TEMPLATES).map(([name, t]) => `${name} = app --render ${t.render}${t.server ? " --server" : ""}`).join("; ")}.
|
|
51
|
+
|
|
43
52
|
For the esdev + ES-Runtime workflow, use \`esdev create\`.`;
|
|
44
53
|
|
|
45
|
-
/** Parse the command line. Throws on an unknown option or value. */
|
|
54
|
+
/** Parse the command line. Throws on an unknown option or value, or conflicting ones. */
|
|
46
55
|
export function parseArgs(args) {
|
|
47
|
-
const options = {
|
|
56
|
+
const options = {
|
|
57
|
+
directory: undefined, template: undefined, render: undefined, server: undefined, styling: undefined,
|
|
58
|
+
language: undefined, overwrite: false, install: true, interactive: undefined, help: false,
|
|
59
|
+
};
|
|
48
60
|
const value = (i, flag) => {
|
|
49
61
|
const next = args[i + 1];
|
|
50
62
|
if (next === undefined || next.startsWith("-")) throw new Error(`${flag} needs a value`);
|
|
@@ -55,11 +67,16 @@ export function parseArgs(args) {
|
|
|
55
67
|
const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, undefined];
|
|
56
68
|
if (flag === "-h" || flag === "--help") options.help = true;
|
|
57
69
|
else if (flag === "-t" || flag === "--template") options.template = inline ?? value(i++, flag);
|
|
70
|
+
else if (flag === "-r" || flag === "--render") options.render = inline ?? value(i++, flag);
|
|
71
|
+
else if (flag === "--server") options.server = true;
|
|
72
|
+
else if (flag === "--no-server") options.server = false;
|
|
73
|
+
else if (flag === "-s" || flag === "--styling") options.styling = inline ?? value(i++, flag);
|
|
74
|
+
else if (flag === "--tailwind") options.styling = "tailwind";
|
|
58
75
|
else if (flag === "-l" || flag === "--language") options.language = inline ?? value(i++, flag);
|
|
59
76
|
else if (flag === "--ts" || flag === "--typescript") options.language = "ts";
|
|
60
77
|
else if (flag === "--js") options.language = "js";
|
|
61
78
|
else if (flag === "--overwrite") options.overwrite = true;
|
|
62
|
-
else if (flag === "-
|
|
79
|
+
else if (flag === "--no-install") options.install = false;
|
|
63
80
|
else if (flag === "--no-interactive" || flag === "-y" || flag === "--yes") options.interactive = false;
|
|
64
81
|
else if (flag === "--interactive") options.interactive = true;
|
|
65
82
|
else if (flag.startsWith("-")) throw new Error(`Unknown option: ${arg}`);
|
|
@@ -67,19 +84,43 @@ export function parseArgs(args) {
|
|
|
67
84
|
else throw new Error(`Unexpected argument: ${arg}`);
|
|
68
85
|
}
|
|
69
86
|
if (options.template !== undefined) {
|
|
70
|
-
const
|
|
71
|
-
if (!TEMPLATES[
|
|
87
|
+
const [, base, lang] = options.template.match(/^(.*?)(?:-(ts|js))?$/);
|
|
88
|
+
if (!TEMPLATES[base] && !LEGACY_TEMPLATES[base]) {
|
|
72
89
|
throw new Error(`Unknown template "${options.template}". Choose one of: ${TEMPLATE_NAMES.join(", ")} (optionally with -ts or -js).`);
|
|
73
90
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
options.language = match[2];
|
|
91
|
+
if (lang) {
|
|
92
|
+
if (options.language && options.language !== lang) throw new Error(`--template ${options.template} conflicts with --language ${options.language}`);
|
|
93
|
+
options.language = lang;
|
|
78
94
|
}
|
|
95
|
+
const legacy = LEGACY_TEMPLATES[base];
|
|
96
|
+
if (legacy) {
|
|
97
|
+
// An earlier release's name: a shorthand for app with its rendering and server.
|
|
98
|
+
if (options.render !== undefined && options.render !== legacy.render) throw new Error(`--template ${base} conflicts with --render ${options.render}`);
|
|
99
|
+
if (legacy.server && options.server === false) throw new Error(`--template ${base} conflicts with --no-server`);
|
|
100
|
+
options.template = legacy.template;
|
|
101
|
+
options.render = legacy.render;
|
|
102
|
+
options.server ??= legacy.server;
|
|
103
|
+
} else {
|
|
104
|
+
options.template = base;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (options.render !== undefined && !RENDERINGS[options.render]) {
|
|
108
|
+
throw new Error(`Unknown rendering "${options.render}". Choose one of: ${Object.keys(RENDERINGS).join(", ")}.`);
|
|
109
|
+
}
|
|
110
|
+
if (options.styling !== undefined && !STYLINGS[options.styling]) {
|
|
111
|
+
throw new Error(`Unknown styling "${options.styling}". Choose one of: ${Object.keys(STYLINGS).join(", ")}.`);
|
|
79
112
|
}
|
|
80
113
|
if (options.language !== undefined && !LANGUAGES[options.language]) {
|
|
81
114
|
throw new Error(`Unknown language "${options.language}". Choose ts or js.`);
|
|
82
115
|
}
|
|
116
|
+
if (options.render === "ssr" && options.server === false) throw new Error("--render ssr always has a server; drop --no-server");
|
|
117
|
+
if (options.template && options.template !== "app") {
|
|
118
|
+
if (options.render !== undefined) throw new Error(`--render applies to the app template, not ${options.template}`);
|
|
119
|
+
if (options.server !== undefined) throw new Error(`--server applies to the app template, not ${options.template}`);
|
|
120
|
+
}
|
|
121
|
+
if (options.template === "docs" && options.styling !== undefined) {
|
|
122
|
+
throw new Error("--styling applies to the app and library templates; the docs template uses the afw-docs theme");
|
|
123
|
+
}
|
|
83
124
|
return options;
|
|
84
125
|
}
|
|
85
126
|
|
|
@@ -114,7 +155,8 @@ async function emptyDir(dir) {
|
|
|
114
155
|
* (default), `"remove"` its files first, or `"ignore"` and write beside them.
|
|
115
156
|
*/
|
|
116
157
|
export async function create({
|
|
117
|
-
directory = DEFAULT_DIRECTORY, template = "
|
|
158
|
+
directory = DEFAULT_DIRECTORY, template = "app", render = "spa", server = false, styling = "css", language = "ts",
|
|
159
|
+
packageName, existing = "error", cwd: base = cwd(),
|
|
118
160
|
} = {}) {
|
|
119
161
|
const target = resolve(base, directory);
|
|
120
162
|
const name = packageName ?? basename(target);
|
|
@@ -123,7 +165,7 @@ export async function create({
|
|
|
123
165
|
if (existing === "remove") await emptyDir(target);
|
|
124
166
|
else if (existing !== "ignore") throw new Error(`${target} is not empty. Use --overwrite to remove its files.`);
|
|
125
167
|
}
|
|
126
|
-
const files = projectFiles({ name, template, typescript: language === "ts", versions: await afwVersions() });
|
|
168
|
+
const files = projectFiles({ name, template, render, server, styling, typescript: language === "ts", versions: await afwVersions() });
|
|
127
169
|
for (const [path, contents] of Object.entries(files)) {
|
|
128
170
|
const file = join(target, path);
|
|
129
171
|
await mkdir(dirname(file), { recursive: true });
|
|
@@ -133,9 +175,22 @@ export async function create({
|
|
|
133
175
|
}
|
|
134
176
|
|
|
135
177
|
/** The commands to run next, for the package manager in use. */
|
|
136
|
-
export function nextSteps({ directory, pm }) {
|
|
178
|
+
export function nextSteps({ directory, pm, installed = false }) {
|
|
137
179
|
const run = (script) => (pm === "npm" || pm === "bun" ? `${pm} run ${script}` : `${pm} ${script}`);
|
|
138
|
-
return [
|
|
180
|
+
return [
|
|
181
|
+
...(directory === "." ? [] : [`cd ${/\s/.test(directory) ? JSON.stringify(directory) : directory}`]),
|
|
182
|
+
...(installed ? [] : [`${pm} install`]),
|
|
183
|
+
run("dev"),
|
|
184
|
+
];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Run `pm install` in `dir`, its output shown. Resolves whether it succeeded. */
|
|
188
|
+
export function installDependencies(pm, dir) {
|
|
189
|
+
return new Promise((done) => {
|
|
190
|
+
const child = spawn(pm, ["install"], { cwd: dir, stdio: "inherit", shell: process.platform === "win32" });
|
|
191
|
+
child.once("error", () => done(false));
|
|
192
|
+
child.once("close", (code) => done(code === 0));
|
|
193
|
+
});
|
|
139
194
|
}
|
|
140
195
|
|
|
141
196
|
// Exit on Ctrl+C or Escape, as create-vite does.
|
|
@@ -150,14 +205,6 @@ const ask = async (prompt) => {
|
|
|
150
205
|
return answer;
|
|
151
206
|
};
|
|
152
207
|
|
|
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
208
|
export async function main(args = argv.slice(2)) {
|
|
162
209
|
let options;
|
|
163
210
|
try {
|
|
@@ -219,13 +266,20 @@ export async function main(args = argv.slice(2)) {
|
|
|
219
266
|
packageName ||= toValidPackageName(basename(target));
|
|
220
267
|
}
|
|
221
268
|
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
269
|
+
const choose = (message, entries) => ask(prompts.select({
|
|
270
|
+
message, options: Object.entries(entries).map(([value, hint]) => ({ value, label: value, hint })),
|
|
271
|
+
}));
|
|
272
|
+
|
|
273
|
+
const template = options.template ?? (interactive ? await choose("Select a template:", TEMPLATES) : "app");
|
|
274
|
+
const isApp = template === "app";
|
|
275
|
+
const render = isApp ? (options.render ?? (interactive ? await choose("How should pages render?", RENDERINGS) : "spa")) : undefined;
|
|
276
|
+
// Server-rendered pages need a server; the other renderings may add one.
|
|
277
|
+
const server = isApp && (render === "ssr" || (options.server ?? (interactive
|
|
278
|
+
? await ask(prompts.confirm({ message: `Add a server? (${SERVER_HINT})`, initialValue: false }))
|
|
279
|
+
: false)));
|
|
280
|
+
const styling = template === "docs" ? undefined : (options.styling ?? (interactive
|
|
281
|
+
? await ask(prompts.select({ message: "Select a styling:", options: Object.entries(STYLINGS).map(([value, label]) => ({ value, label })) }))
|
|
282
|
+
: "css"));
|
|
229
283
|
const language = options.language ?? (interactive
|
|
230
284
|
? await ask(prompts.select({
|
|
231
285
|
message: "Select a language:",
|
|
@@ -233,32 +287,25 @@ export async function main(args = argv.slice(2)) {
|
|
|
233
287
|
}))
|
|
234
288
|
: "ts");
|
|
235
289
|
|
|
236
|
-
const immediate = options.immediate ||
|
|
237
|
-
(interactive && await ask(prompts.confirm({ message: `Install with ${pm} and start now?`, initialValue: false })));
|
|
238
|
-
|
|
239
290
|
const where = relative(cwd(), target) || ".";
|
|
240
|
-
|
|
291
|
+
const summary = [isApp && render, server && "server", styling && STYLINGS[styling], LANGUAGES[language]].filter(Boolean).join(", ");
|
|
292
|
+
prompts.log.step(`Scaffolding ${template} (${summary}) in ${styleText("cyan", target)}`);
|
|
241
293
|
try {
|
|
242
|
-
await create({ directory: target, template, language, packageName, existing });
|
|
294
|
+
await create({ directory: target, template, render, server, styling, language, packageName, existing });
|
|
243
295
|
} catch (error) {
|
|
244
296
|
prompts.cancel(error.message);
|
|
245
297
|
exit(1);
|
|
246
298
|
}
|
|
247
299
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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);
|
|
300
|
+
// Install the dependencies; never start anything — the user runs the dev server.
|
|
301
|
+
let installed = false;
|
|
302
|
+
if (options.install) {
|
|
303
|
+
prompts.log.step(`Installing dependencies with ${pm}…`);
|
|
304
|
+
installed = await installDependencies(pm, target);
|
|
305
|
+
if (!installed) prompts.log.warn(`${pm} install failed; run it yourself in ${where}.`);
|
|
259
306
|
}
|
|
260
|
-
|
|
261
|
-
|
|
307
|
+
const steps = nextSteps({ directory: where, pm, installed }).map((s) => ` ${styleText("cyan", s)}`).join("\n");
|
|
308
|
+
prompts.outro(`Done. Now run:\n\n${steps}\n`);
|
|
262
309
|
}
|
|
263
310
|
|
|
264
311
|
// Run as a CLI, not when imported (tests). The bin is a symlink under npm, so both
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/create-afw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Create an AFW app on Vite and Node: npm create @opentf/afw.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -22,10 +22,14 @@
|
|
|
22
22
|
"node": ">=22"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"@opentf/afw": "0.
|
|
26
|
-
"@opentf/afw-
|
|
27
|
-
"@opentf/
|
|
25
|
+
"@opentf/afw": "0.36.0",
|
|
26
|
+
"@opentf/afw-docs": "0.34.0",
|
|
27
|
+
"@opentf/afw-form": "1.31.0",
|
|
28
|
+
"@opentf/afw-test": "1.31.0",
|
|
29
|
+
"@opentf/vite-plugin-afw": "0.4.0",
|
|
30
|
+
"@tailwindcss/vite": "4.3.3",
|
|
28
31
|
"happy-dom": "21.0.4",
|
|
32
|
+
"tailwindcss": "4.3.3",
|
|
29
33
|
"vite": "8.3.5",
|
|
30
34
|
"vitest": "5.0.5"
|
|
31
35
|
},
|
package/templates.js
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
|
-
// The Vite + Node project templates. Each
|
|
2
|
-
//
|
|
1
|
+
// The Vite + Node project templates. Each is generated from one source for both
|
|
2
|
+
// JavaScript and TypeScript, and for both stylings, so the variants never drift apart.
|
|
3
|
+
//
|
|
4
|
+
// Choices are independent where the framework allows it:
|
|
5
|
+
// app — rendering (spa / ssr / ssg) × server (API routes, middleware, loaders,
|
|
6
|
+
// server functions) × styling (css / tailwind). SSR always has a server.
|
|
7
|
+
// docs — an afw-docs site: MDX docs and a blog, prerendered, with search and feeds.
|
|
8
|
+
// library — a package of components published as JSX source, with a dev preview.
|
|
3
9
|
|
|
4
10
|
import { escapeHTML } from "@opentf/std";
|
|
5
11
|
|
|
6
12
|
export const TEMPLATES = {
|
|
13
|
+
app: "An app: choose how pages render and whether it has a server",
|
|
14
|
+
docs: "A documentation site with a blog, search and feeds (afw-docs)",
|
|
15
|
+
library: "A component library published as JSX source",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const RENDERINGS = {
|
|
7
19
|
spa: "Single-page app, rendered in the browser",
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
20
|
+
ssr: "Server-rendered per request, hydrated in the browser",
|
|
21
|
+
ssg: "Prerendered to static HTML at build time",
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const STYLINGS = { css: "CSS", tailwind: "Tailwind CSS" };
|
|
25
|
+
|
|
26
|
+
/** The template names of earlier releases, kept as shorthands. */
|
|
27
|
+
export const LEGACY_TEMPLATES = {
|
|
28
|
+
spa: { template: "app", render: "spa", server: false },
|
|
29
|
+
fullstack: { template: "app", render: "spa", server: true },
|
|
30
|
+
ssr: { template: "app", render: "ssr", server: true },
|
|
31
|
+
ssg: { template: "app", render: "ssg", server: false },
|
|
11
32
|
};
|
|
12
33
|
|
|
13
34
|
// The third-party tools a new project starts on. AFW's own packages take the
|
|
@@ -17,97 +38,130 @@ export const TOOL_VERSIONS = {
|
|
|
17
38
|
vitest: "^5.0.5",
|
|
18
39
|
"happy-dom": "^21.0.4",
|
|
19
40
|
typescript: "^6.0.3",
|
|
41
|
+
tailwindcss: "^4.3.3",
|
|
42
|
+
"@tailwindcss/vite": "^4.3.3",
|
|
20
43
|
};
|
|
21
44
|
|
|
22
|
-
const MODE = { spa: "spa", fullstack: "spa", ssr: "ssr", ssg: "ssg" };
|
|
23
|
-
const hasServer = (template) => template === "fullstack" || template === "ssr";
|
|
24
|
-
|
|
25
45
|
/**
|
|
26
46
|
* The files of a new project, as `{ relativePath: contents }`.
|
|
27
47
|
*
|
|
28
|
-
* @param {{ name: string, template: keyof TEMPLATES,
|
|
48
|
+
* @param {{ name: string, template: keyof TEMPLATES, render?: keyof RENDERINGS, server?: boolean,
|
|
49
|
+
* styling?: keyof STYLINGS, typescript: boolean, versions: Record<string, string> }} options
|
|
29
50
|
*/
|
|
30
|
-
export function projectFiles({ name, template, typescript, versions }) {
|
|
51
|
+
export function projectFiles({ name, template, render = "spa", server = false, styling = "css", typescript, versions }) {
|
|
31
52
|
if (!TEMPLATES[template]) throw new Error(`Unknown template "${template}". Choose one of: ${Object.keys(TEMPLATES).join(", ")}`);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
53
|
+
if (!RENDERINGS[render]) throw new Error(`Unknown rendering "${render}". Choose one of: ${Object.keys(RENDERINGS).join(", ")}`);
|
|
54
|
+
if (!STYLINGS[styling]) throw new Error(`Unknown styling "${styling}". Choose one of: ${Object.keys(STYLINGS).join(", ")}`);
|
|
55
|
+
const ctx = {
|
|
56
|
+
name, versions, ts: typescript, js: typescript ? "ts" : "js", jsx: typescript ? "tsx" : "jsx",
|
|
57
|
+
tailwind: styling === "tailwind",
|
|
58
|
+
};
|
|
59
|
+
if (template === "docs") return docsFiles(ctx);
|
|
60
|
+
if (template === "library") return libraryFiles(ctx);
|
|
61
|
+
return appFiles({ ...ctx, render, server: render === "ssr" || server });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------------------------------------------------------------------- shared
|
|
65
|
+
|
|
66
|
+
const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
|
67
|
+
const escapeJs = (text) => String(text).replace(/[\\"]/g, "\\$&");
|
|
68
|
+
// ` class="…"` with Tailwind, nothing with plain CSS.
|
|
69
|
+
const tw = (ctx, classes) => (ctx.tailwind ? ` class="${classes}"` : "");
|
|
38
70
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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"],
|
|
71
|
+
function devDependencies(ctx, extra = {}) {
|
|
72
|
+
return sortKeys({
|
|
73
|
+
"@opentf/afw-test": ctx.versions["@opentf/afw-test"],
|
|
74
|
+
"@opentf/vite-plugin-afw": ctx.versions["@opentf/vite-plugin-afw"],
|
|
47
75
|
"happy-dom": TOOL_VERSIONS["happy-dom"],
|
|
48
|
-
...(ts ? { typescript: TOOL_VERSIONS.typescript } : {}),
|
|
76
|
+
...(ctx.ts ? { typescript: TOOL_VERSIONS.typescript } : {}),
|
|
77
|
+
...(ctx.tailwind ? { tailwindcss: TOOL_VERSIONS.tailwindcss, "@tailwindcss/vite": TOOL_VERSIONS["@tailwindcss/vite"] } : {}),
|
|
49
78
|
vite: TOOL_VERSIONS.vite,
|
|
50
79
|
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,
|
|
80
|
+
...extra,
|
|
56
81
|
});
|
|
82
|
+
}
|
|
57
83
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
84
|
+
function sortKeys(object) {
|
|
85
|
+
return Object.fromEntries(Object.entries(object).sort(([a], [b]) => a.localeCompare(b)));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function viteConfig(ctx, { imports = [], plugins }) {
|
|
89
|
+
const lines = [
|
|
90
|
+
`import afw from "@opentf/vite-plugin-afw";`,
|
|
91
|
+
...(ctx.tailwind ? [`import tailwindcss from "@tailwindcss/vite";`] : []),
|
|
92
|
+
...imports,
|
|
93
|
+
...(ctx.ts ? [`import { defineConfig } from "vitest/config";`] : []),
|
|
94
|
+
];
|
|
95
|
+
const all = [...plugins, ...(ctx.tailwind ? ["tailwindcss()"] : [])];
|
|
96
|
+
return `${lines.join("\n")}
|
|
97
|
+
|
|
98
|
+
${ctx.ts ? "export default defineConfig(" : "export default "}{
|
|
99
|
+
plugins: [${all.join(", ")}],
|
|
62
100
|
test: {
|
|
63
101
|
environment: "happy-dom",
|
|
64
102
|
setupFiles: ["@opentf/afw-test/vitest"],
|
|
65
103
|
},
|
|
66
|
-
}${ts ? ")" : ""};
|
|
67
|
-
`;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
|
|
104
|
+
}${ctx.ts ? ")" : ""};
|
|
105
|
+
`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function tsconfig(ctx, include, { allowJs = false } = {}) {
|
|
109
|
+
return json({
|
|
110
|
+
compilerOptions: {
|
|
111
|
+
target: "ESNext",
|
|
112
|
+
module: "ESNext",
|
|
113
|
+
moduleResolution: "bundler",
|
|
114
|
+
lib: ["ESNext", "DOM", "DOM.Iterable"],
|
|
115
|
+
jsx: "preserve",
|
|
116
|
+
jsxImportSource: "@opentf/afw",
|
|
117
|
+
types: ["@opentf/vite-plugin-afw/client"],
|
|
118
|
+
strict: true,
|
|
119
|
+
noEmit: true,
|
|
120
|
+
isolatedModules: true,
|
|
121
|
+
skipLibCheck: true,
|
|
122
|
+
allowImportingTsExtensions: true,
|
|
123
|
+
...(allowJs ? { allowJs: true } : {}),
|
|
124
|
+
},
|
|
125
|
+
include,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
88
128
|
|
|
89
|
-
|
|
129
|
+
function indexHtml(ctx, { title, css = true }) {
|
|
130
|
+
return `<!doctype html>
|
|
90
131
|
<html lang="en">
|
|
91
132
|
<head>
|
|
92
133
|
<meta charset="utf-8" />
|
|
93
134
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
94
|
-
<title>${escapeHTML(
|
|
95
|
-
<link rel="stylesheet" href="/app/global.css" />
|
|
135
|
+
<title>${escapeHTML(title)}</title>${css ? `\n <link rel="stylesheet" href="/app/global.css" />` : ""}
|
|
96
136
|
</head>
|
|
97
137
|
<body>
|
|
98
138
|
<div id="app"></div>
|
|
99
|
-
<script type="module" src="/entry.${js}"></script>
|
|
139
|
+
<script type="module" src="/entry.${ctx.js}"></script>
|
|
100
140
|
</body>
|
|
101
141
|
</html>
|
|
102
142
|
`;
|
|
143
|
+
}
|
|
103
144
|
|
|
104
|
-
|
|
145
|
+
function entry(ctx, { importCss = false } = {}) {
|
|
146
|
+
return `import { mountApp } from "@opentf/afw";
|
|
105
147
|
import { guard, loaderRoutes, pages } from "@afw/routes";
|
|
106
|
-
|
|
107
|
-
mountApp({ pages, guard, loaders: loaderRoutes, target: document.getElementById("app")${ts ? "!" : ""} });
|
|
148
|
+
${importCss ? '\nimport "./app/global.css";\n' : ""}
|
|
149
|
+
mountApp({ pages, guard, loaders: loaderRoutes, target: document.getElementById("app")${ctx.ts ? "!" : ""} });
|
|
108
150
|
`;
|
|
151
|
+
}
|
|
109
152
|
|
|
110
|
-
|
|
153
|
+
function globalCss(ctx) {
|
|
154
|
+
if (ctx.tailwind) {
|
|
155
|
+
return `@import "tailwindcss";
|
|
156
|
+
|
|
157
|
+
@layer base {
|
|
158
|
+
body {
|
|
159
|
+
@apply mx-auto max-w-3xl px-4 py-8 font-sans;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
`;
|
|
163
|
+
}
|
|
164
|
+
return `:root {
|
|
111
165
|
font-family: system-ui, sans-serif;
|
|
112
166
|
color-scheme: light dark;
|
|
113
167
|
}
|
|
@@ -124,6 +178,86 @@ nav {
|
|
|
124
178
|
margin-bottom: 2rem;
|
|
125
179
|
}
|
|
126
180
|
`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function counter(ctx) {
|
|
184
|
+
return `export default function Counter({ start = 0 }${ctx.ts ? ": { start?: number }" : ""}) {
|
|
185
|
+
let count = $state(start);
|
|
186
|
+
const doubled = $derived(count * 2);
|
|
187
|
+
|
|
188
|
+
return (
|
|
189
|
+
<p>
|
|
190
|
+
<button${tw(ctx, "rounded-md bg-sky-600 px-3 py-1 text-white")} onclick={() => count++}>Count: {count}</button> Doubled: {doubled}
|
|
191
|
+
</p>
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function counterTest(ctx, from) {
|
|
198
|
+
return `import { expect, test } from "vitest";
|
|
199
|
+
import { render, userEvent } from "@opentf/afw-test";
|
|
200
|
+
import ${from.startsWith("../index") ? "{ Counter }" : "Counter"} from "${from}";
|
|
201
|
+
|
|
202
|
+
test("counts clicks", async () => {
|
|
203
|
+
const { getByRole, getByText } = render(Counter, { start: 1 });
|
|
204
|
+
await userEvent.setup().click(getByRole("button", { name: "Count: 1" }));
|
|
205
|
+
expect(getByRole("button").textContent).toBe("Count: 2");
|
|
206
|
+
expect(getByText(/Doubled: 4/)).toBeTruthy();
|
|
207
|
+
});
|
|
208
|
+
`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function readme(ctx, { summary, commands, notes = [] }) {
|
|
212
|
+
const rows = commands.map(([command, what]) => `| \`${command}\` | ${what} |`).join("\n");
|
|
213
|
+
return `# ${ctx.name}
|
|
214
|
+
|
|
215
|
+
${summary}
|
|
216
|
+
|
|
217
|
+
| Command | What it does |
|
|
218
|
+
| --- | --- |
|
|
219
|
+
${rows}
|
|
220
|
+
${notes.length ? `\n${notes.map((note) => `- ${note}`).join("\n")}\n` : ""}`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function scripts(ctx, { server }) {
|
|
224
|
+
return {
|
|
225
|
+
dev: "vite",
|
|
226
|
+
build: "vite build",
|
|
227
|
+
...(server ? { start: "node dist/server/index.js" } : { preview: "vite preview" }),
|
|
228
|
+
test: "vitest run",
|
|
229
|
+
...(ctx.ts ? { typecheck: "tsc" } : {}),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function commandRows(ctx, { server }) {
|
|
234
|
+
return [
|
|
235
|
+
["npm run dev", "Start the dev server"],
|
|
236
|
+
["npm run build", "Build for production"],
|
|
237
|
+
server ? ["npm start", "Run the built Node server (`PORT`, `HOST`)"] : ["npm run preview", "Preview the production build"],
|
|
238
|
+
["npm run test", "Run the tests with Vitest"],
|
|
239
|
+
...(ctx.ts ? [["npm run typecheck", "Check types"]] : []),
|
|
240
|
+
];
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---------------------------------------------------------------------------- app
|
|
244
|
+
|
|
245
|
+
function appFiles(ctx) {
|
|
246
|
+
const { ts, js, jsx, render, server } = ctx;
|
|
247
|
+
const files = {};
|
|
248
|
+
files["package.json"] = json({
|
|
249
|
+
name: ctx.name, private: true, type: "module", scripts: scripts(ctx, { server }),
|
|
250
|
+
dependencies: { "@opentf/afw": ctx.versions["@opentf/afw"] },
|
|
251
|
+
devDependencies: devDependencies(ctx),
|
|
252
|
+
});
|
|
253
|
+
const options = render === "ssg"
|
|
254
|
+
? `{ mode: "ssg", baseUrl: "" /* your site URL, e.g. "https://example.com", enables sitemap.xml */ }`
|
|
255
|
+
: `{ mode: "${render}" }`;
|
|
256
|
+
files[`vite.config.${js}`] = viteConfig(ctx, { plugins: [`afw(${options})`] });
|
|
257
|
+
if (ts) files["tsconfig.json"] = tsconfig(ctx, ["app", "tests", "entry.ts", "vite.config.ts"]);
|
|
258
|
+
files["index.html"] = indexHtml(ctx, { title: ctx.name });
|
|
259
|
+
files[`entry.${js}`] = entry(ctx);
|
|
260
|
+
files["app/global.css"] = globalCss(ctx);
|
|
127
261
|
|
|
128
262
|
const navLinks = [["/", "Home"], ["/about", "About"], ...(server ? [["/todos", "Todos"]] : [])];
|
|
129
263
|
files[`app/layout.${jsx}`] = `import { Link } from "@opentf/afw";
|
|
@@ -131,7 +265,7 @@ nav {
|
|
|
131
265
|
export default function Layout({ children }${ts ? ": { children: unknown }" : ""}) {
|
|
132
266
|
return (
|
|
133
267
|
<>
|
|
134
|
-
<nav>
|
|
268
|
+
<nav${tw(ctx, "mb-8 flex gap-4 text-sky-700")}>
|
|
135
269
|
${navLinks.map(([href, label]) => ` <Link href="${href}">${label}</Link>`).join("\n")}
|
|
136
270
|
</nav>
|
|
137
271
|
<main>{children}</main>
|
|
@@ -139,34 +273,21 @@ ${navLinks.map(([href, label]) => ` <Link href="${href}">${label}</Link>`
|
|
|
139
273
|
);
|
|
140
274
|
}
|
|
141
275
|
`;
|
|
142
|
-
|
|
143
276
|
files[`app/page.${jsx}`] = `import Counter from "./Counter.${jsx}";
|
|
144
277
|
|
|
145
|
-
export const metadata = { title: "${escapeJs(name)}" };
|
|
278
|
+
export const metadata = { title: "${escapeJs(ctx.name)}" };
|
|
146
279
|
|
|
147
280
|
export default function Home() {
|
|
148
281
|
return (
|
|
149
282
|
<section>
|
|
150
|
-
<h1>${escapeHTML(name)}</h1>
|
|
283
|
+
<h1${tw(ctx, "mb-4 text-3xl font-bold")}>${escapeHTML(ctx.name)}</h1>
|
|
151
284
|
<p>Edit <code>app/page.${jsx}</code> and save: the page updates in place.</p>
|
|
152
285
|
<Counter start={0} />
|
|
153
286
|
</section>
|
|
154
287
|
);
|
|
155
288
|
}
|
|
156
289
|
`;
|
|
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
|
-
|
|
290
|
+
files[`app/Counter.${jsx}`] = counter(ctx);
|
|
170
291
|
files["app/about/page.md"] = `---
|
|
171
292
|
title: About
|
|
172
293
|
---
|
|
@@ -175,14 +296,36 @@ title: About
|
|
|
175
296
|
|
|
176
297
|
This page is Markdown. The AFW compiler turns it into a page like any other.
|
|
177
298
|
`;
|
|
299
|
+
if (server) Object.assign(files, serverFiles(ctx));
|
|
300
|
+
files[`tests/Counter.test.${js}`] = counterTest(ctx, `../app/Counter.${jsx}`);
|
|
301
|
+
files[".gitignore"] = "node_modules\ndist\n";
|
|
178
302
|
|
|
179
|
-
|
|
180
|
-
|
|
303
|
+
const how = { spa: "rendered in the browser", ssr: "server-rendered on Node", ssg: "prerendered to static HTML" }[render];
|
|
304
|
+
files["README.md"] = readme(ctx, {
|
|
305
|
+
summary: `An [AFW](https://afw.opentechf.org) app on Vite${server ? " and Node" : ""}: pages ${how}${server ? ", with a Node server" : ""}.`,
|
|
306
|
+
commands: commandRows(ctx, { server }),
|
|
307
|
+
notes: [
|
|
308
|
+
`Pages live in \`app/\`: \`app/about/page.md\` is served at \`/about\`.`,
|
|
309
|
+
...(server ? [
|
|
310
|
+
`On the server: API routes (\`app/api/hello/route.${js}\`), middleware (\`app/_middleware.${js}\`), a loader (\`app/todos/loader.${js}\`) and server functions (\`app/todos/todos.server.${js}\`), which components call like async functions.`,
|
|
311
|
+
] : []),
|
|
312
|
+
...(ctx.tailwind ? ["Styled with Tailwind CSS: utility classes go straight into `class`."] : []),
|
|
313
|
+
],
|
|
314
|
+
});
|
|
315
|
+
return files;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function serverFiles(ctx) {
|
|
319
|
+
const { ts, js, jsx } = ctx;
|
|
320
|
+
const files = {};
|
|
321
|
+
files[`app/api/hello/route.${js}`] = `// GET /api/hello?name=… — API routes run on Node, so any npm package works here.
|
|
181
322
|
export function GET(request${ts ? ": Request" : ""}, { query, locals }${ts ? ": { query: Record<string, string>; locals: Record<string, unknown> }" : ""}) {
|
|
182
323
|
return Response.json({ message: \`Hello, \${query.name ?? "world"}!\`, requestId: locals.requestId });
|
|
183
324
|
}
|
|
184
325
|
`;
|
|
185
|
-
|
|
326
|
+
files[`app/_middleware.${js}`] = `// Runs for every request: pages, API routes, loader data and server functions alike.
|
|
327
|
+
// Authenticate here (set \`context.locals.user\`); each server function checks what
|
|
328
|
+
// that user may read or change.
|
|
186
329
|
export default async function middleware(request${ts ? ": Request" : ""}, context${ts ? ": { locals: Record<string, unknown> }" : ""}, next${ts ? ": () => Promise<Response>" : ""}) {
|
|
187
330
|
context.locals.requestId = crypto.randomUUID();
|
|
188
331
|
const response = await next();
|
|
@@ -190,65 +333,289 @@ export default async function middleware(request${ts ? ": Request" : ""}, contex
|
|
|
190
333
|
return response;
|
|
191
334
|
}
|
|
192
335
|
`;
|
|
193
|
-
|
|
194
|
-
|
|
336
|
+
files[`app/todos/todos.server.${js}`] = `// Server functions: this module runs only on the server. Components import the
|
|
337
|
+
// functions below and call them like async functions; the browser gets fetch stubs.
|
|
338
|
+
import { action, query } from "@opentf/afw/server";
|
|
195
339
|
|
|
196
|
-
|
|
197
|
-
|
|
340
|
+
// In memory for the example: use your database here.
|
|
341
|
+
const todos${ts ? ": string[]" : ""} = ["Try the dev server", "Add an API route", "Deploy with npm start"];
|
|
342
|
+
|
|
343
|
+
export const listTodos = query(async () => todos);
|
|
344
|
+
|
|
345
|
+
export const addTodo = action(async ({ title }${ts ? ": { title: string }" : ""}) => {
|
|
346
|
+
const text = String(title ?? "").trim();
|
|
347
|
+
if (!text) throw new Response(null, { status: 400 });
|
|
348
|
+
todos.push(text);
|
|
349
|
+
return todos;
|
|
350
|
+
});
|
|
351
|
+
`;
|
|
352
|
+
files[`app/todos/loader.${js}`] = `// Loaders run on the server and feed their page through \`router.data\`. A server
|
|
353
|
+
// function called from server code runs directly, with no HTTP request.
|
|
354
|
+
import { listTodos } from "./todos.server.${js}";
|
|
355
|
+
|
|
356
|
+
export default async function loader({ locals }${ts ? ": { locals: Record<string, unknown> }" : ""}) {
|
|
357
|
+
return { todos: await listTodos(undefined, { locals }) };
|
|
198
358
|
}
|
|
199
359
|
`;
|
|
200
|
-
|
|
360
|
+
files[`app/todos/page.${jsx}`] = `import { invalidate, router } from "@opentf/afw";
|
|
361
|
+
import { addTodo } from "./todos.server.${js}";
|
|
201
362
|
|
|
202
363
|
export const metadata = { title: "Todos" };
|
|
203
364
|
|
|
204
365
|
export default function Todos() {
|
|
366
|
+
let title = $state("");
|
|
367
|
+
const todos = $derived(${ts ? "(router.data as { todos?: string[] } | undefined)" : "router.data"}?.todos ?? []);
|
|
368
|
+
|
|
369
|
+
async function add(event${ts ? ": SubmitEvent" : ""}) {
|
|
370
|
+
event.preventDefault();
|
|
371
|
+
await addTodo({ title });
|
|
372
|
+
title = "";
|
|
373
|
+
await invalidate(); // reload this page's loader data
|
|
374
|
+
}
|
|
375
|
+
|
|
205
376
|
return (
|
|
206
377
|
<section>
|
|
207
|
-
<h1>Todos</h1>
|
|
208
|
-
<ul>
|
|
209
|
-
{
|
|
378
|
+
<h1${tw(ctx, "mb-4 text-2xl font-bold")}>Todos</h1>
|
|
379
|
+
<ul${tw(ctx, "mb-4 list-disc pl-6")}>
|
|
380
|
+
{todos.map((todo${ts ? ": string" : ""}) => <li>{todo}</li>)}
|
|
210
381
|
</ul>
|
|
382
|
+
<form onsubmit={add}>
|
|
383
|
+
<input${tw(ctx, "rounded-md border px-2 py-1")} value={title} oninput={(e${ts ? ": Event" : ""}) => (title = (e.target${ts ? " as HTMLInputElement" : ""}).value)} placeholder="New todo" />
|
|
384
|
+
<button${tw(ctx, "ml-2 rounded-md bg-sky-600 px-3 py-1 text-white")} type="submit">Add</button>
|
|
385
|
+
</form>
|
|
211
386
|
</section>
|
|
212
387
|
);
|
|
213
388
|
}
|
|
214
389
|
`;
|
|
215
|
-
|
|
390
|
+
return files;
|
|
391
|
+
}
|
|
216
392
|
|
|
217
|
-
|
|
218
|
-
import { render, userEvent } from "@opentf/afw-test";
|
|
219
|
-
import Counter from "../app/Counter.${jsx}";
|
|
393
|
+
// ---------------------------------------------------------------------------- docs
|
|
220
394
|
|
|
221
|
-
|
|
222
|
-
const {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
395
|
+
function docsFiles(ctx) {
|
|
396
|
+
const { ts, js, jsx } = ctx;
|
|
397
|
+
const files = {};
|
|
398
|
+
files["package.json"] = json({
|
|
399
|
+
name: ctx.name, private: true, type: "module", scripts: scripts(ctx, { server: false }),
|
|
400
|
+
dependencies: { "@opentf/afw": ctx.versions["@opentf/afw"], "@opentf/afw-docs": ctx.versions["@opentf/afw-docs"] },
|
|
401
|
+
devDependencies: devDependencies({ ...ctx, tailwind: false }),
|
|
402
|
+
});
|
|
403
|
+
files[`vite.config.${js}`] = viteConfig({ ...ctx, tailwind: false }, {
|
|
404
|
+
imports: [`import afwDocs from "@opentf/afw-docs/vite";`],
|
|
405
|
+
plugins: [`afw({ mode: "ssg" })`, "afwDocs()"],
|
|
406
|
+
});
|
|
407
|
+
if (ts) files["tsconfig.json"] = tsconfig(ctx, ["app", "tests", "entry.ts", "vite.config.ts", "afw.config.js"], { allowJs: true });
|
|
408
|
+
files["afw.config.js"] = `import { defineDocsConfig } from "@opentf/afw-docs/config";
|
|
409
|
+
|
|
410
|
+
export default defineDocsConfig({
|
|
411
|
+
// Your site's URL: canonical links, sitemap.xml, feeds and llms.txt use it.
|
|
412
|
+
site: { url: "https://example.com" },
|
|
413
|
+
docs: {
|
|
414
|
+
title: "${escapeJs(ctx.name)}",
|
|
415
|
+
nav: [
|
|
416
|
+
{ label: "Docs", href: "/docs" },
|
|
417
|
+
{ label: "Blog", href: "/blog" },
|
|
418
|
+
],
|
|
419
|
+
search: { provider: "afw" },
|
|
420
|
+
},
|
|
421
|
+
blog: { dir: "blog", title: "${escapeJs(ctx.name)} Blog" },
|
|
226
422
|
});
|
|
227
423
|
`;
|
|
424
|
+
files["index.html"] = indexHtml(ctx, { title: ctx.name, css: false });
|
|
425
|
+
files[`entry.${js}`] = entry(ctx, { importCss: true });
|
|
426
|
+
files["app/global.css"] = `@import "@opentf/afw-docs/theme";
|
|
427
|
+
`;
|
|
428
|
+
files[`app/layout.${jsx}`] = `export default function Root({ children }${ts ? ": { children: unknown }" : ""}) {
|
|
429
|
+
return <div>{children}</div>;
|
|
430
|
+
}
|
|
431
|
+
`;
|
|
432
|
+
files[`app/page.${jsx}`] = `import { Link } from "@opentf/afw";
|
|
228
433
|
|
|
229
|
-
|
|
434
|
+
export const metadata = { title: "${escapeJs(ctx.name)}", description: "Documentation and blog." };
|
|
435
|
+
|
|
436
|
+
export default function Home() {
|
|
437
|
+
return (
|
|
438
|
+
<main class="afwd-prose">
|
|
439
|
+
<h1>${escapeHTML(ctx.name)}</h1>
|
|
440
|
+
<p>Documentation and a blog, written in MDX.</p>
|
|
441
|
+
<p>
|
|
442
|
+
<Link href="/docs">Read the docs</Link> · <Link href="/blog">Visit the blog</Link>
|
|
443
|
+
</p>
|
|
444
|
+
</main>
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
`;
|
|
448
|
+
files[`app/docs/layout.${jsx}`] = `import { DocsLayout } from "@opentf/afw-docs";
|
|
449
|
+
import config from "../../afw.config.js";
|
|
450
|
+
|
|
451
|
+
export default function Docs({ children }${ts ? ": { children: unknown }" : ""}) {
|
|
452
|
+
return <DocsLayout config={config.docs} siteUrl={config.site.url}>{children}</DocsLayout>;
|
|
453
|
+
}
|
|
454
|
+
`;
|
|
455
|
+
files["app/docs/_meta.js"] = `// Sidebar order and labels. Folders not listed here follow, alphabetically.
|
|
456
|
+
export default {
|
|
457
|
+
"getting-started": "Getting Started",
|
|
458
|
+
guides: "Guides",
|
|
459
|
+
};
|
|
460
|
+
`;
|
|
461
|
+
files["app/docs/page.mdx"] = `---
|
|
462
|
+
title: Introduction
|
|
463
|
+
description: What this project is and where to start.
|
|
464
|
+
---
|
|
230
465
|
|
|
231
|
-
|
|
232
|
-
files["README.md"] = `# ${name}
|
|
466
|
+
import { Callout } from "@opentf/afw-docs";
|
|
233
467
|
|
|
234
|
-
|
|
468
|
+
# Introduction
|
|
235
469
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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." : ""}
|
|
470
|
+
Welcome to the ${escapeHTML(ctx.name)} docs.
|
|
471
|
+
|
|
472
|
+
<Callout type="tip">
|
|
473
|
+
Every folder under \`app/docs/\` with a \`page.mdx\` becomes a page in the sidebar.
|
|
474
|
+
</Callout>
|
|
244
475
|
`;
|
|
245
|
-
|
|
476
|
+
files["app/docs/getting-started/page.mdx"] = `---
|
|
477
|
+
title: Getting Started
|
|
478
|
+
description: Install and run the project.
|
|
479
|
+
---
|
|
480
|
+
|
|
481
|
+
# Getting Started
|
|
482
|
+
|
|
483
|
+
\`\`\`bash
|
|
484
|
+
npm install
|
|
485
|
+
npm run dev
|
|
486
|
+
\`\`\`
|
|
487
|
+
`;
|
|
488
|
+
files["app/docs/guides/writing-pages/page.mdx"] = `---
|
|
489
|
+
title: Writing Pages
|
|
490
|
+
description: MDX pages, components and code blocks.
|
|
491
|
+
---
|
|
492
|
+
|
|
493
|
+
import { Steps } from "@opentf/afw-docs";
|
|
494
|
+
|
|
495
|
+
# Writing Pages
|
|
496
|
+
|
|
497
|
+
<Steps>
|
|
498
|
+
|
|
499
|
+
### Add a folder
|
|
500
|
+
|
|
501
|
+
Create \`app/docs/my-topic/page.mdx\`.
|
|
502
|
+
|
|
503
|
+
### Write MDX
|
|
504
|
+
|
|
505
|
+
Markdown with components, like this list of steps.
|
|
506
|
+
|
|
507
|
+
</Steps>
|
|
508
|
+
`;
|
|
509
|
+
files[`app/blog/layout.${jsx}`] = `import { BlogLayout } from "@opentf/afw-docs";
|
|
510
|
+
import { posts } from "@opentf/afw-docs/posts";
|
|
511
|
+
import config from "../../afw.config.js";
|
|
512
|
+
|
|
513
|
+
export default function Blog({ children }${ts ? ": { children: unknown }" : ""}) {
|
|
514
|
+
return <BlogLayout config={config.docs} posts={posts} siteUrl={config.site.url}>{children}</BlogLayout>;
|
|
246
515
|
}
|
|
516
|
+
`;
|
|
517
|
+
files[`app/blog/page.${jsx}`] = `import { PostList } from "@opentf/afw-docs";
|
|
518
|
+
import { posts } from "@opentf/afw-docs/posts";
|
|
519
|
+
|
|
520
|
+
export const metadata = { title: "Blog" };
|
|
247
521
|
|
|
248
|
-
function
|
|
249
|
-
return
|
|
522
|
+
export default function BlogIndex() {
|
|
523
|
+
return (
|
|
524
|
+
<section>
|
|
525
|
+
<h1>Blog</h1>
|
|
526
|
+
<PostList posts={posts} />
|
|
527
|
+
</section>
|
|
528
|
+
);
|
|
250
529
|
}
|
|
530
|
+
`;
|
|
531
|
+
files["app/blog/hello-world/page.mdx"] = `---
|
|
532
|
+
title: Hello, world
|
|
533
|
+
description: The first post.
|
|
534
|
+
date: 2026-01-01
|
|
535
|
+
author: ${escapeHTML(ctx.name)}
|
|
536
|
+
---
|
|
251
537
|
|
|
252
|
-
|
|
253
|
-
|
|
538
|
+
# Hello, world
|
|
539
|
+
|
|
540
|
+
Posts live in \`app/blog/\`; each one appears in the post list and the RSS and Atom feeds.
|
|
541
|
+
`;
|
|
542
|
+
files[`tests/Home.test.${js}`] = `import { expect, test } from "vitest";
|
|
543
|
+
import { render } from "@opentf/afw-test";
|
|
544
|
+
import Home from "../app/page.${jsx}";
|
|
545
|
+
|
|
546
|
+
test("the home page links to the docs and the blog", () => {
|
|
547
|
+
const { getByRole } = render(Home);
|
|
548
|
+
expect(getByRole("heading", { level: 1 }).textContent).toBe("${escapeJs(ctx.name)}");
|
|
549
|
+
expect(getByRole("link", { name: "Read the docs" }).getAttribute("href")).toBe("/docs");
|
|
550
|
+
});
|
|
551
|
+
`;
|
|
552
|
+
files[".gitignore"] = "node_modules\ndist\n";
|
|
553
|
+
files["README.md"] = readme(ctx, {
|
|
554
|
+
summary: "A documentation site and blog built with [AFW](https://afw.opentechf.org) and `@opentf/afw-docs` on Vite.",
|
|
555
|
+
commands: commandRows(ctx, { server: false }),
|
|
556
|
+
notes: [
|
|
557
|
+
"Docs pages live in `app/docs/`, posts in `app/blog/`; `app/docs/_meta.js` orders the sidebar.",
|
|
558
|
+
"`npm run build` prerenders every page and writes the search index, `sitemap.xml`, RSS and Atom feeds and `llms.txt`.",
|
|
559
|
+
"Set your site's URL in `afw.config.js`.",
|
|
560
|
+
],
|
|
561
|
+
});
|
|
562
|
+
return files;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ---------------------------------------------------------------------------- library
|
|
566
|
+
|
|
567
|
+
function libraryFiles(ctx) {
|
|
568
|
+
const { ts, js, jsx } = ctx;
|
|
569
|
+
const files = {};
|
|
570
|
+
const afw = ctx.versions["@opentf/afw"];
|
|
571
|
+
files["package.json"] = json({
|
|
572
|
+
name: ctx.name,
|
|
573
|
+
version: "0.1.0",
|
|
574
|
+
type: "module",
|
|
575
|
+
// Published as source: the consuming app's AFW plugin compiles it.
|
|
576
|
+
exports: { ".": `./index.${js}` },
|
|
577
|
+
files: [`index.${js}`, "src"],
|
|
578
|
+
sideEffects: false,
|
|
579
|
+
scripts: { dev: "vite", test: "vitest run", ...(ts ? { typecheck: "tsc" } : {}) },
|
|
580
|
+
peerDependencies: { "@opentf/afw": afw },
|
|
581
|
+
devDependencies: devDependencies(ctx, { "@opentf/afw": afw }),
|
|
582
|
+
});
|
|
583
|
+
files[`vite.config.${js}`] = viteConfig(ctx, { plugins: ["afw()"] });
|
|
584
|
+
if (ts) files["tsconfig.json"] = tsconfig(ctx, ["index.ts", "src", "app", "tests", "entry.ts", "vite.config.ts"]);
|
|
585
|
+
files[`index.${js}`] = `// The package entry: export each component.
|
|
586
|
+
export { default as Counter } from "./src/Counter.${jsx}";
|
|
587
|
+
`;
|
|
588
|
+
files[`src/Counter.${jsx}`] = counter(ctx);
|
|
589
|
+
// The preview app (\`npm run dev\`): not published.
|
|
590
|
+
files["index.html"] = indexHtml(ctx, { title: `${ctx.name} preview` });
|
|
591
|
+
files[`entry.${js}`] = entry(ctx);
|
|
592
|
+
files["app/global.css"] = globalCss(ctx);
|
|
593
|
+
files[`app/page.${jsx}`] = `import { Counter } from "../index.${js}";
|
|
594
|
+
|
|
595
|
+
export default function Preview() {
|
|
596
|
+
return (
|
|
597
|
+
<section>
|
|
598
|
+
<h1${tw(ctx, "mb-4 text-2xl font-bold")}>${escapeHTML(ctx.name)}</h1>
|
|
599
|
+
<Counter start={1} />
|
|
600
|
+
</section>
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
`;
|
|
604
|
+
files[`tests/Counter.test.${js}`] = counterTest(ctx, `../index.${js}`);
|
|
605
|
+
files[".gitignore"] = "node_modules\ndist\n";
|
|
606
|
+
files["README.md"] = readme(ctx, {
|
|
607
|
+
summary: "A component library for [AFW](https://afw.opentechf.org), published as JSX source.",
|
|
608
|
+
commands: [
|
|
609
|
+
["npm run dev", "Preview the components (`app/page." + jsx + "`)"],
|
|
610
|
+
["npm run test", "Run the tests with Vitest"],
|
|
611
|
+
...(ts ? [["npm run typecheck", "Check types"]] : []),
|
|
612
|
+
["npm publish", "Publish `index." + js + "` and `src/`"],
|
|
613
|
+
],
|
|
614
|
+
notes: [
|
|
615
|
+
`Export each component from \`index.${js}\`.`,
|
|
616
|
+
"Apps install it next to `@opentf/afw` (a peer dependency); their AFW plugin compiles it, with Vite or esdev.",
|
|
617
|
+
...(ctx.tailwind ? ["Components use Tailwind classes: apps that use Tailwind add `@source \"../node_modules/" + ctx.name + "\";` to their stylesheet so the classes are generated."] : []),
|
|
618
|
+
],
|
|
619
|
+
});
|
|
620
|
+
return files;
|
|
254
621
|
}
|
package/versions.js
CHANGED
|
@@ -10,7 +10,12 @@ import { readFile } from "node:fs/promises";
|
|
|
10
10
|
|
|
11
11
|
import { timeoutRun } from "@opentf/std";
|
|
12
12
|
|
|
13
|
-
export const AFW_PACKAGES = {
|
|
13
|
+
export const AFW_PACKAGES = {
|
|
14
|
+
"@opentf/afw": "afw",
|
|
15
|
+
"@opentf/afw-docs": "afw-docs",
|
|
16
|
+
"@opentf/afw-test": "afw-test",
|
|
17
|
+
"@opentf/vite-plugin-afw": "vite-plugin-afw",
|
|
18
|
+
};
|
|
14
19
|
|
|
15
20
|
const REGISTRY_TIMEOUT_MS = 5000;
|
|
16
21
|
|
package/versions.json
CHANGED