@opentf/afw-cli 0.0.0-stage → 1.31.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/src/shared.js ADDED
@@ -0,0 +1,765 @@
1
+ // Shared plumbing for the SSG library (`@opentf/afw-cli/ssg`): the pre-render
2
+ // driver that a site's `then: "run"` esdev target calls, plus the release-only
3
+ // output hook. esdev owns development, bundling and serving; this module keeps
4
+ // route discovery, the server render bundle, HTML shell injection and the docs
5
+ // output generators (search, feeds, LLM files) that run after a release build.
6
+
7
+ import { build } from "runtime:build";
8
+ import { dirname, join, toFileURL } from "runtime:path";
9
+ import { exit } from "runtime:process";
10
+
11
+ import { quiet } from "./reporter.js";
12
+
13
+ import { exists, findUp, mkdirp, readEntries, readText, resolveFrom, rmrf, writeFile } from "./runtime.js";
14
+
15
+ // The afwc compiler service and the `runtime:build` transform plugin live in
16
+ // `@opentf/esdev-plugin-afw`. Imported here for the server render bundle and
17
+ // re-exported so the SSG entry keeps a single import site.
18
+ import { closeCompilers, afwPlugin, isUnpublishedPage, resolveCompiler } from "@opentf/esdev-plugin-afw";
19
+
20
+ export { closeCompilers, resolveCompiler };
21
+
22
+ export const EXTENSIONS = [".jsx", ".tsx", ".js", ".ts", ".mdx", ".md"];
23
+
24
+ /** Inject `snippet` just before `</body>` (or append when there is none). */
25
+ export function injectBeforeBody(html, snippet) {
26
+ // Function replacer so `$` in `snippet` is literal (String.replace treats `$1`,
27
+ // `$&`, … in a string replacement as back-references — e.g. a "$189.00" price).
28
+ return html.includes("</body>") ? html.replace("</body>", () => `${snippet}</body>`) : html + snippet;
29
+ }
30
+
31
+ /** Inject pre-rendered markup into the shell's empty `#app` container. */
32
+ export function injectMarkup(shellHtml, markup) {
33
+ // Function replacer: `markup` may contain `$` (currency, etc.) — keep it literal.
34
+ return shellHtml.replace(/(<div id="app"[^>]*>)\s*(<\/div>)/, (_m, open, close) => `${open}${markup}${close}`);
35
+ }
36
+
37
+ /**
38
+ * Embed the island hydration payload (`renderRoute().hydration`) as a
39
+ * `<script type="application/json" id="__afw_h">` the client reads at upgrade so
40
+ * components resume from rich JS props (compiler-driven data hydration). Placed before
41
+ * `</body>`; a deferred module bundle runs after parse, so the payload is always in the
42
+ * DOM first. `json` is already `<`-escaped by the server collector, so it can't break out
43
+ * of the script. No-op for an empty payload. Uses a function replacer so `$` in the JSON
44
+ * stays literal.
45
+ */
46
+ export function injectHydrationData(shellHtml, json) {
47
+ if (!json) return shellHtml;
48
+ return injectBeforeBody(shellHtml, `<script type="application/json" id="__afw_h">${json}</script>`);
49
+ }
50
+
51
+ /** The reserved per-route data filename/URL suffix (mirrors the runtime's
52
+ * `DATA_FILE` in `@opentf/afw` runtime/route-data.js). */
53
+ export const DATA_FILE = "__data.json";
54
+
55
+ /**
56
+ * Embed a route loader's data (docs/DATA.md) as a `<script type="application/json"
57
+ * id="__afw_data">` the client router reads on first paint (instead of fetching
58
+ * `<path>/__data.json`). A separate script from the island payload above — the two
59
+ * channels have independent shapes and readers. `json` comes `<`-escaped from
60
+ * `serializeRouteData`; no-op for an empty payload (route without a loader, or an
61
+ * undefined loader result).
62
+ */
63
+ export function injectRouteData(shellHtml, json) {
64
+ if (!json) return shellHtml;
65
+ return injectBeforeBody(shellHtml, `<script type="application/json" id="__afw_data">${json}</script>`);
66
+ }
67
+
68
+ /**
69
+ * Stamp the `data-afw-hydrate` sentinel onto the shell's `#app` container, telling
70
+ * the client to *adopt* the server-rendered DOM on first paint instead of rebuilding
71
+ * it (`runtime/router.js` `mountApp`). Used when the client bundle was built for the
72
+ * hydrate target and there is server markup to adopt (SSR, and SSG pre-render).
73
+ * Idempotent — a no-op if the sentinel is already present.
74
+ */
75
+ export function stampHydrateSentinel(shellHtml) {
76
+ return shellHtml.replace(/<div id="app"([^>]*)>/, (m, attrs) =>
77
+ /\bdata-afw-hydrate\b/.test(attrs) ? m : `<div id="app"${attrs} data-afw-hydrate>`,
78
+ );
79
+ }
80
+
81
+ /**
82
+ * Record the route a prerendered page was rendered for on its hydrate sentinel
83
+ * (`data-afw-hydrate="/docs/x"`), so the client adopts the markup only at that URL
84
+ * and builds the requested route when a host serves this file for another path.
85
+ * A no-op when the shell carries no sentinel (a CSR-only shell).
86
+ */
87
+ export function stampRenderedPath(shellHtml, path) {
88
+ const value = String(path).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
89
+ return shellHtml.replace(/(<div id="app"[^>]*?\sdata-afw-hydrate)(?:="[^"]*")?/, (_m, attr) => `${attr}="${value}"`);
90
+ }
91
+
92
+ /**
93
+ * Inject per-route `<head>` tags before `</head>`, dropping the shell's default
94
+ * `<title>` when the route supplies its own (so each page gets a unique,
95
+ * non-duplicated title). Shared by SSG pre-render and the SSR server.
96
+ */
97
+ export function injectHead(shellHtml, headHtml) {
98
+ if (!headHtml) return shellHtml;
99
+ let out = stripRouteHead(shellHtml);
100
+ if (/<title[\s>]/i.test(headHtml)) out = out.replace(/<title>[\s\S]*?<\/title>\s*/i, "");
101
+ // Function replacer so `$` in `headHtml` (e.g. a price in a meta description) is literal.
102
+ return out.replace(/<\/head>/i, () => `${headHtml}\n</head>`);
103
+ }
104
+
105
+ const ROUTE_HEAD_TAG = /<(meta|link)\b[^>]*>\s*|<script\b([^>]*)>[\s\S]*?<\/script>\s*/gi;
106
+
107
+ /** The attribute `name`'s value in an opening tag, lower-cased; "" if absent. */
108
+ function attrOf(tag, name) {
109
+ const m = tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
110
+ return (m ? (m[1] ?? m[2] ?? m[3]) : "").toLowerCase();
111
+ }
112
+
113
+ /**
114
+ * Remove the shell's route-owned SEO tags (description, robots, `og:`/`twitter:`/`article:`,
115
+ * canonical, JSON-LD, anything marked `data-afw-head`) so the page's own head replaces them.
116
+ * This is the set the client's `updateRouteHead` (runtime/head.js) removes on navigation,
117
+ * so a prerendered page and a client-navigated one end up with the same head.
118
+ */
119
+ function stripRouteHead(shellHtml) {
120
+ const head = shellHtml.match(/<head\b[^>]*>([\s\S]*?)<\/head>/i);
121
+ if (!head) return shellHtml;
122
+ const inner = head[1].replace(ROUTE_HEAD_TAG, (tag, el) => {
123
+ if (/\sdata-afw-head\b/i.test(tag)) return "";
124
+ if (el?.toLowerCase() === "meta") {
125
+ const name = attrOf(tag, "name");
126
+ const property = attrOf(tag, "property");
127
+ if (name === "description" || name === "robots" || name.startsWith("twitter:")) return "";
128
+ if (property.startsWith("og:") || property.startsWith("article:")) return "";
129
+ } else if (el?.toLowerCase() === "link") {
130
+ if (attrOf(tag, "rel") === "canonical") return "";
131
+ } else if (attrOf(tag, "type") === "application/ld+json") return "";
132
+ return tag;
133
+ });
134
+ const start = head.index + head[0].indexOf(">") + 1;
135
+ return shellHtml.slice(0, start) + inner + shellHtml.slice(start + head[1].length);
136
+ }
137
+
138
+ /** Set/replace the shell's `<html lang>` for a localized page (i18n; docs/I18N.md §6). */
139
+ export function withHtmlLang(shellHtml, locale) {
140
+ if (!locale) return shellHtml;
141
+ if (/<html[^>]*\slang=/i.test(shellHtml)) {
142
+ return shellHtml.replace(/(<html[^>]*\slang=)(["'])[^"']*\2/i, `$1$2${locale}$2`);
143
+ }
144
+ return shellHtml.replace(/<html\b/i, `<html lang="${locale}"`);
145
+ }
146
+
147
+ export { findUp };
148
+
149
+ /**
150
+ * Load the optional project config (`afw.config.{json,js,mjs}`) as a plain object.
151
+ * Read by the build for the site URL (SEO) and the `docs` block (docs generator).
152
+ */
153
+ export async function loadConfig(root) {
154
+ const json = join(root, "afw.config.json");
155
+ if (await exists(json)) {
156
+ try {
157
+ return JSON.parse(await readText(json)) ?? {};
158
+ } catch (e) {
159
+ console.warn(`⚠ could not parse afw.config.json: ${e?.message ?? e}`);
160
+ }
161
+ }
162
+ for (const name of ["afw.config.js", "afw.config.mjs"]) {
163
+ const p = join(root, name);
164
+ if (await exists(p)) {
165
+ try {
166
+ const mod = await import(toFileURL(p).href);
167
+ return mod.default ?? {};
168
+ } catch (e) {
169
+ console.warn(`⚠ could not load ${name}: ${e?.message ?? e}`);
170
+ }
171
+ }
172
+ }
173
+ return {};
174
+ }
175
+
176
+ /**
177
+ * The docs navigation bundler plugin, when the project opts into the docs
178
+ * generator (a `docs` block in afw.config). Resolved from `@opentf/afw-docs`
179
+ * (the app's own dependency); returns null when docs aren't configured or the
180
+ * package isn't installed, so the core toolchain stays untouched for normal apps.
181
+ */
182
+ export async function loadDocsPlugins(root, appDir, config, exclude = new Set()) {
183
+ const docs = config?.docs;
184
+ const blog = config?.blog;
185
+ if (!docs && !blog) return [];
186
+ try {
187
+ const entry = await resolveFrom("@opentf/afw-docs/build", root);
188
+ const { docsNavPlugin, blogPostsPlugin, lastUpdatedPlugin } = await import(toFileURL(entry).href);
189
+ const plugins = [];
190
+ // Resolves `@opentf/afw-docs/nav` to a section map — one generated tree per top-level
191
+ // folder under app/. Any folder with a DocsLayout becomes a section automatically.
192
+ if (docs) plugins.push(docsNavPlugin({ appDir, exclude }));
193
+ // Resolves `@opentf/afw-docs/posts` to the generated post list.
194
+ if (blog) plugins.push(blogPostsPlugin({ appDir, contentDir: blog.dir ?? "blog", exclude }));
195
+ // Resolves `@opentf/afw-docs/updated` to the per-page last-updated map (every route),
196
+ // when last-updated is turned on anywhere.
197
+ if (wantsLastUpdated(config)) plugins.push(lastUpdatedPlugin({ appDir, exclude, blogDir: blog ? blog.dir ?? "blog" : undefined }));
198
+ return plugins;
199
+ } catch (e) {
200
+ console.warn(
201
+ `⚠ docs/blog config present but @opentf/afw-docs could not be loaded: ${e?.message ?? e}`,
202
+ );
203
+ return [];
204
+ }
205
+ }
206
+
207
+ /** Whether "last updated" tracking is enabled anywhere (`docs`/`blog` `lastUpdated`). */
208
+ export function wantsLastUpdated(config) {
209
+ return Boolean(config?.docs?.lastUpdated || config?.blog?.lastUpdated);
210
+ }
211
+
212
+ /**
213
+ * Build the `{ [routePath]: ISO }` last-updated map for every page (the same map the
214
+ * `@opentf/afw-docs/updated` virtual module exposes). Used by the SSG step to emit
215
+ * `article:modified_time`. Returns `{}` when last-updated is off or the package can't
216
+ * be loaded.
217
+ */
218
+ export async function runLastUpdated(root, appDir, config, exclude = new Set()) {
219
+ if (!wantsLastUpdated(config)) return {};
220
+ try {
221
+ const entry = await resolveFrom("@opentf/afw-docs/build", root);
222
+ const { loadLastUpdated } = await import(toFileURL(entry).href);
223
+ const blogDir = config?.blog ? config.blog.dir ?? "blog" : undefined;
224
+ return await loadLastUpdated({ appDir, exclude, blogDir });
225
+ } catch (e) {
226
+ console.warn(`⚠ last-updated map skipped: ${e?.message ?? e}`);
227
+ return {};
228
+ }
229
+ }
230
+
231
+ /**
232
+ * The warning for a `docs.search.provider` other than `"afw"`, or null. A retired value
233
+ * (e.g. `"pagefind"`) would otherwise turn search off without a word.
234
+ */
235
+ export function searchProviderWarning(config) {
236
+ const provider = config?.docs?.search?.provider;
237
+ if (provider == null || provider === "afw") return null;
238
+ return `⚠ docs.search.provider ${JSON.stringify(provider)} is not supported; ` +
239
+ `use "afw" or remove it. Search is disabled for this build.`;
240
+ }
241
+
242
+ /** Index the completed SSG output when static search is enabled. Errors fail the build. */
243
+ export async function runDocsSearchIndex(root, config, siteDir, afwc) {
244
+ if (config?.docs?.search?.provider !== "afw") return null;
245
+ const entry = await resolveFrom("@opentf/afw-docs/build", root);
246
+ const { indexWithAfwSearch } = await import(toFileURL(entry).href);
247
+ return indexWithAfwSearch({ siteDir, afwc });
248
+ }
249
+
250
+ /**
251
+ * Generate blog feeds when the project has a `blog` config and a base URL. Scans the
252
+ * post folders, renders RSS 2.0 + Atom 1.0, and writes them under
253
+ * `<siteDir>/<blogDir>/`. Project-supplied `public/<blogDir>/{rss,atom}.xml` files
254
+ * take precedence independently. Returns `{ paths, urls, count }` or null (no blog /
255
+ * no base URL / all feeds overridden / package missing). Resolved from the app's
256
+ * `@opentf/afw-docs`.
257
+ */
258
+ export async function runBlogFeed(root, appDir, config, siteDir, baseUrl, exclude = new Set()) {
259
+ const blog = config?.blog;
260
+ if (!blog) return null;
261
+ if (!baseUrl) {
262
+ console.warn("⚠ blog feeds skipped: no site URL (pass --base-url or set afw.config)");
263
+ return null;
264
+ }
265
+ const contentDir = blog.dir ?? "blog";
266
+ try {
267
+ const entry = await resolveFrom("@opentf/afw-docs/build", root);
268
+ const { loadPosts, postContentHtml, renderAtomFeed, renderBlogFeed } = await import(toFileURL(entry).href);
269
+ const posts = await loadPosts({ appDir, contentDir, exclude });
270
+ // Full post bodies, read back from the prerendered pages this hook runs after.
271
+ for (const post of posts) {
272
+ const page = join(siteDir, post.path.replace(/^\/+/, ""), "index.html");
273
+ if (await exists(page)) post.content = postContentHtml(await readText(page), baseUrl, post.cover);
274
+ }
275
+ const title = blog.title || (config?.docs?.title ? `${config.docs.title} Blog` : "Blog");
276
+ const channel = {
277
+ title,
278
+ description: blog.description || title,
279
+ link: `/${contentDir}`,
280
+ language: blog.language || config?.i18n?.defaultLocale || "en",
281
+ };
282
+ const feeds = [
283
+ {
284
+ file: "rss.xml",
285
+ path: `/${contentDir}/rss.xml`,
286
+ render: renderBlogFeed,
287
+ },
288
+ {
289
+ file: "atom.xml",
290
+ path: `/${contentDir}/atom.xml`,
291
+ render: renderAtomFeed,
292
+ },
293
+ ];
294
+ const written = [];
295
+ for (const feed of feeds) {
296
+ if (await exists(join(root, "public", contentDir, feed.file))) continue; // honor override
297
+ const out = join(siteDir, contentDir, feed.file);
298
+ await writeFile(out, feed.render({ posts, baseUrl, feedPath: feed.path, channel }));
299
+ written.push(feed.path);
300
+ }
301
+ if (!written.length) return null;
302
+ await injectFeedLinks(siteDir, title, contentDir);
303
+ const origin = baseUrl.replace(/\/+$/, "");
304
+ return { paths: written, urls: written.map((path) => origin + path), count: posts.length };
305
+ } catch (e) {
306
+ console.warn(`⚠ blog feeds skipped: ${e?.message ?? e}`);
307
+ return null;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Advertise the blog feeds from every prerendered page: a `<link rel="alternate">` for
313
+ * RSS and Atom in each `<head>`, so a reader finds them from any URL of the site. A page
314
+ * that already declares a feed (a hand-written link in the shell) is left alone.
315
+ */
316
+ async function injectFeedLinks(siteDir, title, contentDir) {
317
+ const t = String(title).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
318
+ const links =
319
+ `<link rel="alternate" type="application/rss+xml" title="${t}" href="/${contentDir}/rss.xml">\n` +
320
+ `<link rel="alternate" type="application/atom+xml" title="${t}" href="/${contentDir}/atom.xml">\n`;
321
+ const walk = async (dir) => {
322
+ for (const entry of await readEntries(dir)) {
323
+ const full = join(dir, entry.name);
324
+ if (entry.isDir) await walk(full);
325
+ else if (entry.name.endsWith(".html")) {
326
+ const html = await readText(full);
327
+ if (/type="application\/(rss|atom)\+xml"/.test(html) || !/<\/head>/i.test(html)) continue;
328
+ await writeFile(full, html.replace(/<\/head>/i, () => `${links}</head>`));
329
+ }
330
+ }
331
+ };
332
+ await walk(siteDir);
333
+ }
334
+
335
+ /**
336
+ * Generate `/llms.txt` and `/llms-full.txt` for docs/blog sites from the same
337
+ * filesystem route list used by the app build. Project-supplied public files override
338
+ * each output independently. `siteDescription` is the site's own description (resolved
339
+ * from the app's metadata during the build) — llms.txt summarizes the site with it
340
+ * rather than with a generic line.
341
+ */
342
+ export async function runLlmsFiles(root, appDir, pages, config, siteDir, baseUrl, { siteDescription = "" } = {}) {
343
+ if (!config?.docs && !config?.blog) return null;
344
+ const candidates = [
345
+ { file: "llms.txt", render: "renderLlmsTxt" },
346
+ { file: "llms-full.txt", render: "renderLlmsFullTxt" },
347
+ ];
348
+ const outputs = [];
349
+ for (const out of candidates) {
350
+ if (!(await exists(join(root, "public", out.file)))) outputs.push(out);
351
+ }
352
+ if (!outputs.length) return null;
353
+
354
+ try {
355
+ const entry = await resolveFrom("@opentf/afw-docs/build", root);
356
+ const mod = await import(toFileURL(entry).href);
357
+ const written = [];
358
+ for (const out of outputs) {
359
+ const render = mod[out.render];
360
+ if (typeof render !== "function") continue;
361
+ await writeFile(join(siteDir, out.file), await render({ appDir, pages, baseUrl, config, siteDescription }));
362
+ written.push(`/${out.file}`);
363
+ }
364
+ return written.length ? { paths: written } : null;
365
+ } catch (e) {
366
+ console.warn(`⚠ llms.txt skipped: ${e?.message ?? e}`);
367
+ return null;
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Discover file-based routes under `app/`: every page/layout and the 404. This list is
373
+ * what gets prerendered, so drafts and scheduled Markdown pages (`isUnpublishedPage`)
374
+ * are left out: no HTML, no sitemap entry, no `llms.txt` line.
375
+ */
376
+ export async function discoverPages(dir, exclude) {
377
+ const out = [];
378
+ for (const entry of await readEntries(dir)) {
379
+ if (entry.isDir && exclude.has(entry.name)) continue;
380
+ const full = `${dir}/${entry.name}`;
381
+ if (entry.isDir) out.push(...(await discoverPages(full, exclude)));
382
+ else if (/^404\.(mdx|md)$/.test(entry.name)) {
383
+ throw new Error(`Unsupported Markdown 404 route: ${full}. Use 404.jsx or 404.tsx instead.`);
384
+ }
385
+ else if (/^(page|layout|404)\.(mdx|md|[jt]sx)$/.test(entry.name)) {
386
+ if (!(await isUnpublishedPage(full))) out.push(full);
387
+ }
388
+ }
389
+ return out;
390
+ }
391
+
392
+ /**
393
+ * Discover file-based API routes anywhere under `app/` (SPEC §11). An endpoint is a
394
+ * `route.{js,ts}` file (the API analogue of `page.{jsx,tsx}`); its folder is the URL.
395
+ * Returns `{ routes, middleware }` — absolute paths to `route.*` handler modules and
396
+ * to `_middleware.{js,ts}` files (folder middleware) respectively.
397
+ */
398
+ export async function discoverApiRoutes(appDir, exclude = new Set()) {
399
+ const routes = [];
400
+ const middleware = [];
401
+ const walk = async (dir) => {
402
+ for (const entry of await readEntries(dir)) {
403
+ if (entry.isDir) {
404
+ if (!exclude.has(entry.name)) await walk(join(dir, entry.name));
405
+ continue;
406
+ }
407
+ const name = entry.name;
408
+ const full = join(dir, name);
409
+ if (/^route\.(jsx?|tsx?)$/.test(name)) routes.push(full);
410
+ else if (/^_middleware\.(jsx?|tsx?)$/.test(name)) middleware.push(full);
411
+ }
412
+ };
413
+ await walk(appDir);
414
+ return { routes, middleware };
415
+ }
416
+
417
+ /**
418
+ * Strip the app-directory prefix from a route file path. With `appDir` the exact
419
+ * prefix is removed (unambiguous even for `app/app/...`); without it, fall back to
420
+ * the last complete `/app` path segment — the lookahead keeps folders that merely
421
+ * start with "app" (`/appointments`) intact.
422
+ */
423
+ function stripAppPrefix(filePath, appDir) {
424
+ if (appDir) {
425
+ const base = appDir.replace(/\/+$/, "");
426
+ if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
427
+ }
428
+ return filePath.replace(/^.*\/app(?=\/)/, "");
429
+ }
430
+
431
+ /** `<link rel="modulepreload">` tags for a route's chunk hrefs (`""` when there are none). */
432
+ export function modulepreloadTags(hrefs) {
433
+ if (!hrefs || hrefs.length === 0) return "";
434
+ return hrefs.map((h) => `<link rel="modulepreload" href="${h}">`).join("\n");
435
+ }
436
+
437
+ /** The page URL for a `.../app/<...>/page.{mdx,md,jsx,tsx}` file (folder = URL). */
438
+ export function pageRouteFromPath(filePath, appDir) {
439
+ const r = stripAppPrefix(filePath, appDir).replace(/\/page\.(mdx|md|jsx|tsx)$/, "");
440
+ return r === "" ? "/" : r;
441
+ }
442
+
443
+ /** The route URL for a `.../app/<...>/route.{js,ts}` file (folder = URL). */
444
+ function apiRoutePath(filePath, appDir) {
445
+ const r = stripAppPrefix(filePath, appDir).replace(/\/route\.(jsx?|tsx?)$/, "");
446
+ return r === "" ? "/" : r;
447
+ }
448
+
449
+ /**
450
+ * Discover route loaders anywhere under `app/` (docs/DATA.md). A loader is a
451
+ * `loader.{js,ts}` file sibling to a `page.*` — the data analogue of a `route.*`
452
+ * endpoint. Strictly `js|ts` (no `x` variants): loaders are plain server modules,
453
+ * never JSX. Returns absolute file paths.
454
+ */
455
+ export async function discoverLoaders(appDir, exclude = new Set()) {
456
+ const out = [];
457
+ const walk = async (dir) => {
458
+ for (const entry of await readEntries(dir)) {
459
+ if (entry.isDir) {
460
+ if (!exclude.has(entry.name)) await walk(join(dir, entry.name));
461
+ } else if (/^loader\.(js|ts)$/.test(entry.name)) out.push(join(dir, entry.name));
462
+ }
463
+ };
464
+ await walk(appDir);
465
+ return out;
466
+ }
467
+
468
+ /** The page route a `.../app/<...>/loader.{js,ts}` file feeds (folder = URL). */
469
+ export function loaderRoutePath(filePath, appDir) {
470
+ const r = stripAppPrefix(filePath, appDir).replace(/\/loader\.(js|ts)$/, "");
471
+ return r === "" ? "/" : r;
472
+ }
473
+
474
+ /**
475
+ * Detect folders that hold both a `page.*` and a `route.*` — they'd resolve to the
476
+ * same URL. Returns the conflicting `{ path, page, route }` entries (empty = none).
477
+ * A page and an endpoint cannot own the same path (as in Next.js's App Router).
478
+ */
479
+ export async function detectRouteConflicts(appDir, exclude = new Set()) {
480
+ const pageByRoute = new Map();
481
+ for (const p of await discoverPages(appDir, exclude)) {
482
+ if (/\/page\.(mdx|md|jsx|tsx)$/.test(p)) pageByRoute.set(pageRouteFromPath(p, appDir), p);
483
+ }
484
+ const conflicts = [];
485
+ for (const r of (await discoverApiRoutes(appDir, exclude)).routes) {
486
+ const path = apiRoutePath(r, appDir);
487
+ if (pageByRoute.has(path)) conflicts.push({ path, page: pageByRoute.get(path), route: r });
488
+ }
489
+ return conflicts;
490
+ }
491
+
492
+ /**
493
+ * Detect misplaced `loader.*` files (docs/DATA.md): a loader feeds the page in
494
+ * its folder, so one without a sibling `page.*` — including one placed next to a
495
+ * `route.*` endpoint — has nothing to feed. Returns `{ loader, route, reason }`.
496
+ */
497
+ export async function detectLoaderConflicts(appDir, exclude = new Set()) {
498
+ const conflicts = [];
499
+ const anyExists = async (dir, names) => {
500
+ for (const n of names) if (await exists(join(dir, n))) return true;
501
+ return false;
502
+ };
503
+ for (const loader of await discoverLoaders(appDir, exclude)) {
504
+ const dir = dirname(loader);
505
+ if (await anyExists(dir, ["page.jsx", "page.tsx", "page.mdx", "page.md"])) continue;
506
+ const hasRoute = await anyExists(dir, ["route.js", "route.ts"]);
507
+ conflicts.push({
508
+ loader,
509
+ route: loaderRoutePath(loader, appDir),
510
+ reason: hasRoute
511
+ ? "sits next to a route.* API endpoint (endpoints take a Request; loaders feed pages)"
512
+ : "has no sibling page.* to feed",
513
+ });
514
+ }
515
+ return conflicts;
516
+ }
517
+
518
+ /** Print the route/page/loader conflicts and exit the prerender step. */
519
+ export async function assertNoRouteConflicts(appDir, exclude = new Set()) {
520
+ const conflicts = await detectRouteConflicts(appDir, exclude);
521
+ if (conflicts.length > 0) {
522
+ const lines = conflicts.map((c) => ` ${c.path}\n page: ${c.page}\n route: ${c.route}`).join("\n");
523
+ fail(`a page and an API route cannot resolve to the same path:\n${lines}\n Move one to a different folder.`);
524
+ }
525
+ const loaderConflicts = await detectLoaderConflicts(appDir, exclude);
526
+ if (loaderConflicts.length > 0) {
527
+ const lines = loaderConflicts.map((c) => ` ${c.route}\n loader: ${c.loader}\n ${c.reason}`).join("\n");
528
+ fail(`a loader.* file must sit next to the page.* it feeds:\n${lines}`);
529
+ }
530
+ }
531
+
532
+ /**
533
+ * Entry source for the API/middleware server bundle: statically import every
534
+ * route + middleware module (keyed by absolute path so scopes/routes derive from
535
+ * the path), then export three composed handlers. Mirrors `serverEntrySource`
536
+ * for the page/SSG bundle.
537
+ *
538
+ * apiHandler — routes with the API-scoped middleware composed in (standalone /
539
+ * legacy adapter use, where nothing else runs the middleware);
540
+ * apiRoutes — routes only, for servers that run `middleware` themselves at
541
+ * pipeline level — middleware must not run twice;
542
+ * middleware — the `createMiddleware` runner governing the whole request
543
+ * pipeline (pages, endpoints, loader data — docs/MIDDLEWARE.md).
544
+ */
545
+ export function apiEntrySource({ routes, middleware }, appDir, i18n = null) {
546
+ const rImports = routes.map((p, i) => `import * as r${i} from ${JSON.stringify(p)};`).join("\n");
547
+ const mImports = middleware.map((p, i) => `import * as m${i} from ${JSON.stringify(p)};`).join("\n");
548
+ const rMap = routes.map((p, i) => ` [${JSON.stringify(p)}]: r${i},`).join("\n");
549
+ const mMap = middleware.map((p, i) => ` [${JSON.stringify(p)}]: m${i},`).join("\n");
550
+ // `appDir` pins the exact prefix to strip from the keys — route derivation stays
551
+ // correct for folders whose name starts with "app" and for nested app/app dirs.
552
+ // `i18n` lets middleware scope matching strip a non-default locale prefix.
553
+ const i18nOpt =
554
+ i18n && Array.isArray(i18n.locales) && i18n.locales.length
555
+ ? `, i18n: ${JSON.stringify({ locales: i18n.locales, defaultLocale: i18n.defaultLocale })}`
556
+ : "";
557
+ const opts = appDir ? `{ appDir: ${JSON.stringify(appDir)}${i18nOpt} }` : `{${i18nOpt.replace(/^,\s*/, " ")} }`;
558
+ return (
559
+ `import { createApiHandler, createMiddleware } from "@opentf/afw/server";\n` +
560
+ `${rImports}\n${mImports}\n` +
561
+ `const routeModules = {\n${rMap}\n};\n` +
562
+ `const middlewareModules = {\n${mMap}\n};\n` +
563
+ `export const apiHandler = createApiHandler(routeModules, middlewareModules, ${opts});\n` +
564
+ `export const apiRoutes = createApiHandler(routeModules, {}, ${opts});\n` +
565
+ `export const middleware = createMiddleware(middlewareModules, ${opts});\n`
566
+ );
567
+ }
568
+
569
+ /**
570
+ * Emit the API handler bundle to `outDir/api.js` for production/deploy (SPEC §13,
571
+ * `dist/server/`). This writes a persistent, self-contained ESM module that
572
+ * exports `apiHandler` / `apiRoutes` / `middleware` (see `apiEntrySource`) — the
573
+ * runtime dispatchers are bundled in; npm/node deps stay external and resolve at
574
+ * the deploy target. A deploy adapter (`server/adapters/`) imports this file and
575
+ * hands requests to the handlers. Returns `{ routes, middleware }`, or `null`
576
+ * when the project has neither API routes nor middleware.
577
+ */
578
+ export async function emitApiBundle({ root, appDir, afwEntry, exclude, i18n, outDir }) {
579
+ const discovered = await discoverApiRoutes(appDir, exclude);
580
+ if (discovered.routes.length === 0 && discovered.middleware.length === 0) return null;
581
+
582
+ const tmp = join(root, ".afw-api-build");
583
+ await mkdirp(tmp);
584
+ const entry = join(tmp, "api-entry.js");
585
+ await writeFile(entry, apiEntrySource(discovered, appDir, i18n));
586
+
587
+ const serverApi = join(dirname(afwEntry), "server", "index.js");
588
+ await mkdirp(outDir);
589
+ const bundle = await build({
590
+ input: entry,
591
+ platform: "node",
592
+ resolve: { alias: { "@opentf/afw/server": serverApi, "@opentf/afw": afwEntry }, extensions: EXTENSIONS },
593
+ external: (id) => !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("@opentf/afw"),
594
+ });
595
+ try {
596
+ await bundle.write({ dir: outDir, format: "esm", entryFileNames: "api.js" });
597
+ } finally {
598
+ await bundle.close();
599
+ }
600
+ await rmrf(tmp);
601
+ return { routes: discovered.routes, middleware: discovered.middleware };
602
+ }
603
+
604
+ /**
605
+ * Entry source for the loader bundle (docs/DATA.md): statically import every
606
+ * `loader.{js,ts}` module (keyed by absolute path so the registry derives each
607
+ * route from it) and export the composed registry. Mirrors `apiEntrySource`.
608
+ */
609
+ export function loaderEntrySource(loaderFiles, appDir, i18n = null) {
610
+ const imports = loaderFiles.map((p, i) => `import * as l${i} from ${JSON.stringify(p)};`).join("\n");
611
+ const map = loaderFiles.map((p, i) => ` [${JSON.stringify(p)}]: l${i},`).join("\n");
612
+ const i18nOpt =
613
+ i18n && Array.isArray(i18n.locales) && i18n.locales.length
614
+ ? `, i18n: ${JSON.stringify({ locales: i18n.locales, defaultLocale: i18n.defaultLocale })}`
615
+ : "";
616
+ const opts = `\n{ appDir: ${JSON.stringify(appDir ?? "")}${i18nOpt} },\n`;
617
+ return (
618
+ `import { createLoaderRegistry } from "@opentf/afw/server";\n` +
619
+ `${imports}\n` +
620
+ `export const loaders = createLoaderRegistry(\n{\n${map}\n},${opts});\n`
621
+ );
622
+ }
623
+
624
+ /**
625
+ * Emit the loader bundle to `outDir/loaders.js` for production (`dist/server/`,
626
+ * next to `api.js`). The prerender runs these loaders at build time; a deploy
627
+ * server can import the same file to serve `<path>/__data.json`. Returns `{ files }`, or `null` when
628
+ * the app has no loader files.
629
+ */
630
+ export async function emitLoaderBundle({ root, appDir, afwEntry, exclude, i18n, outDir }) {
631
+ const files = await discoverLoaders(appDir, exclude);
632
+ if (files.length === 0) return null;
633
+
634
+ const tmp = join(root, ".afw-loaders-build");
635
+ await mkdirp(tmp);
636
+ const entry = join(tmp, "loaders-entry.js");
637
+ await writeFile(entry, loaderEntrySource(files, appDir, i18n));
638
+
639
+ const serverApi = join(dirname(afwEntry), "server", "index.js");
640
+ await mkdirp(outDir);
641
+ const bundle = await build({
642
+ input: entry,
643
+ platform: "node",
644
+ resolve: { alias: { "@opentf/afw/server": serverApi, "@opentf/afw": afwEntry }, extensions: EXTENSIONS },
645
+ external: (id) => !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("@opentf/afw"),
646
+ });
647
+ try {
648
+ await bundle.write({ dir: outDir, format: "esm", entryFileNames: "loaders.js" });
649
+ } finally {
650
+ await bundle.close();
651
+ }
652
+ await rmrf(tmp);
653
+ return { files };
654
+ }
655
+
656
+ /**
657
+ * CSS plugin: `import "./x.css"` injects a <style>; `*.module.css` resolves to an
658
+ * identity class-name map (`styles.foo` → "foo"). Dev-grade CSS Modules.
659
+ */
660
+ export function cssPlugin() {
661
+ return {
662
+ name: "css",
663
+ transform: {
664
+ filter: { id: /\.css$/ },
665
+ // `pre` so this claims a stylesheet before the runtime's own CSS Modules pass
666
+ // does: that pass resolves `@import` for real, and an app stylesheet's
667
+ // `@import "tailwindcss"` is a directive for Tailwind, not a module to fetch.
668
+ order: "pre",
669
+ handler(code, id) {
670
+ const inject =
671
+ `const __s = document.createElement("style");` +
672
+ ` __s.textContent = ${JSON.stringify(code)};` +
673
+ ` document.head.appendChild(__s);`;
674
+ const out = id.endsWith(".module.css")
675
+ ? `${inject}\nexport default new Proxy({}, { get: (_, k) => k });`
676
+ : `${inject}\nexport default ${JSON.stringify(code)};`;
677
+ return { code: out, type: "js", moduleSideEffects: true };
678
+ },
679
+ },
680
+ };
681
+ }
682
+
683
+ // Generated server entry: eager-import every page module (so `registerRoutes`
684
+ // sees real namespaces, enabling `getStaticPaths`) and re-export the render API.
685
+ // Shared by the SSG pre-render and the SSR server — both render through the same
686
+ // SSG-compiled bundle (ARCHITECTURE.md §6: "SSR … shares the SSG path").
687
+ export function serverEntrySource(pages, i18n = null) {
688
+ const imports = pages.map((p, i) => `import * as p${i} from ${JSON.stringify(p)};`).join("\n");
689
+ const map = pages.map((p, i) => ` [${JSON.stringify(p)}]: p${i},`).join("\n");
690
+ // i18n: the server-side router needs the locales too — so renderRoute can strip
691
+ // a `/fr/...` prefix to match the route table and set router.locale for `t()`
692
+ // (docs/I18N.md §6). Without this the prefix wouldn't match and pages would
693
+ // render in the default locale (or 404).
694
+ const i18nOn = i18n && Array.isArray(i18n.locales) && i18n.locales.length;
695
+ const named = i18nOn ? "registerRoutes, configureI18n" : "registerRoutes";
696
+ const i18nCall = i18nOn
697
+ ? `configureI18n(${JSON.stringify({ locales: i18n.locales, defaultLocale: i18n.defaultLocale })});\n`
698
+ : "";
699
+ return (
700
+ `${imports}\n` +
701
+ `import { ${named} } from "@opentf/afw/server";\n` +
702
+ `export { renderRoute, renderHead, collectRoutePaths, resolveMetadata } from "@opentf/afw/server";\n` +
703
+ i18nCall +
704
+ `registerRoutes({\n${map}\n});\n`
705
+ );
706
+ }
707
+
708
+ /**
709
+ * Build the server render bundle (the compiler's SSG backend — HTML-string
710
+ * renderers) and import it. Returns `{ mod, cleanup }`, where `mod` exposes
711
+ * `renderRoute` / `renderHead` / `collectRoutePaths` and `cleanup()` removes the
712
+ * temp build dir. The SSG pre-render calls `cleanup()` immediately after rendering
713
+ * every route; the SSR server keeps the module live and cleans up on shutdown.
714
+ */
715
+ export async function buildServerBundle({
716
+ root,
717
+ pages,
718
+ afwEntry,
719
+ afwc,
720
+ docsPlugins = [],
721
+ i18n = null,
722
+ onCompile,
723
+ tmpName = ".afw-ssg",
724
+ }) {
725
+ const tmp = join(root, tmpName);
726
+ await mkdirp(tmp);
727
+ const entry = join(tmp, "ssg-entry.js");
728
+ await writeFile(entry, serverEntrySource(pages, i18n));
729
+
730
+ const serverApi = join(dirname(afwEntry), "server", "index.js");
731
+ const bundle = await build({
732
+ input: entry,
733
+ resolve: {
734
+ alias: { "@opentf/afw/server": serverApi, "@opentf/afw": afwEntry },
735
+ extensions: EXTENSIONS,
736
+ },
737
+ // The runtime guards its dev diagnostics on `process.env.NODE_ENV`, and there is
738
+ // no `process` global here to read it at runtime — so it has to be folded away at
739
+ // bundle time. Server render is a production render.
740
+ define: { "process.env.NODE_ENV": '"production"' },
741
+ plugins: [
742
+ ...docsPlugins,
743
+ afwPlugin(afwc, { failOnError: true, target: "ssg", quiet, onResult: (id) => onCompile?.(id) }),
744
+ cssPlugin(),
745
+ ],
746
+ });
747
+ try {
748
+ await bundle.write({ dir: join(tmp, "out"), format: "esm", entryFileNames: "server.js" });
749
+ } finally {
750
+ await bundle.close();
751
+ }
752
+
753
+ // The runtime defines `class … extends HTMLElement` at load (for CSR custom
754
+ // elements). Server render never instantiates them, but the base class must
755
+ // exist so the class definitions evaluate. A bare stub suffices — no DOM
756
+ // (customElements stays undefined, so elements self-register only in the browser).
757
+ globalThis.HTMLElement ??= class {};
758
+ const mod = await import(toFileURL(join(tmp, "out", "server.js")).href);
759
+ return { mod, cleanup: () => rmrf(tmp) };
760
+ }
761
+
762
+ function fail(msg) {
763
+ console.error(`✗ ${msg}`);
764
+ exit(1);
765
+ }