@opentf/afw-cli 1.31.0 → 1.33.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/package.json +4 -3
- package/src/prerender.js +14 -201
- package/src/shared.js +57 -237
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.33.0",
|
|
4
4
|
"description": "Static generation for AFW apps, run as an esdev build step.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -16,10 +16,11 @@
|
|
|
16
16
|
"esdev": ">=0.16.0"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@opentf/
|
|
19
|
+
"@opentf/afw-build": "0.1.0",
|
|
20
|
+
"@opentf/esdev-plugin-afw": "0.6.0"
|
|
20
21
|
},
|
|
21
22
|
"peerDependencies": {
|
|
22
|
-
"@opentf/afw": "0.
|
|
23
|
+
"@opentf/afw": "0.34.0"
|
|
23
24
|
},
|
|
24
25
|
"keywords": [
|
|
25
26
|
"afw",
|
package/src/prerender.js
CHANGED
|
@@ -3,218 +3,31 @@
|
|
|
3
3
|
// render each route to a static HTML file. No DOM — the SSG output is pure string
|
|
4
4
|
// concatenation, so no effects/lifecycle run.
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { join } from "runtime:path";
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import { prerender } from "@opentf/afw-build";
|
|
9
|
+
import { esdevHost } from "@opentf/esdev-plugin-afw";
|
|
9
10
|
|
|
10
|
-
import {
|
|
11
|
-
DATA_FILE,
|
|
12
|
-
buildServerBundle,
|
|
13
|
-
injectHead,
|
|
14
|
-
injectHydrationData,
|
|
15
|
-
injectMarkup,
|
|
16
|
-
injectRouteData,
|
|
17
|
-
modulepreloadTags,
|
|
18
|
-
stampRenderedPath,
|
|
19
|
-
withHtmlLang,
|
|
20
|
-
} from "./shared.js";
|
|
21
|
-
|
|
22
|
-
// "/" → dist/index.html, "/post/1" → dist/post/1/index.html, "/fr/about" → dist/fr/about/index.html.
|
|
23
|
-
function htmlPathFor(outDir, route) {
|
|
24
|
-
return route === "/" ? join(outDir, "index.html") : join(outDir, route, "index.html");
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
// Prefix a locale-agnostic route with `locale` (bare for the default) — the URL form
|
|
28
|
-
// that both selects the output file and, passed to renderRoute, pins router.locale.
|
|
29
|
-
function localizeFor(path, locale, defaultLocale) {
|
|
30
|
-
if (!locale || locale === defaultLocale) return path;
|
|
31
|
-
return path === "/" ? `/${locale}` : `/${locale}${path}`;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// `rel="alternate" hreflang` descriptors for a route across all locales (+ x-default),
|
|
35
|
-
// merged into metadata.links so renderHead emits them (docs/I18N.md §6).
|
|
36
|
-
function alternatesFor(path, locales, defaultLocale) {
|
|
37
|
-
const links = locales.map((l) => ({
|
|
38
|
-
rel: "alternate",
|
|
39
|
-
hreflang: l,
|
|
40
|
-
href: localizeFor(path, l, defaultLocale),
|
|
41
|
-
}));
|
|
42
|
-
links.push({ rel: "alternate", hreflang: "x-default", href: localizeFor(path, defaultLocale, defaultLocale) });
|
|
43
|
-
return links;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Absolute URL for sitemap/robots; "" if no base URL configured.
|
|
47
|
-
function absoluteUrl(baseUrl, path) {
|
|
48
|
-
if (!baseUrl) return "";
|
|
49
|
-
return baseUrl.replace(/\/+$/, "") + (path === "/" ? "/" : path);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Emit sitemap.xml (absolute <loc> per rendered path, with <lastmod> where the
|
|
53
|
-
// last-updated map knows the path) — requires a base URL. A project-supplied
|
|
54
|
-
// public/sitemap.xml takes precedence (it overwrites ours on copy).
|
|
55
|
-
async function writeSitemap(outDir, publicDir, baseUrl, paths, lastUpdated = {}) {
|
|
56
|
-
if (await exists(join(publicDir, "sitemap.xml"))) return false;
|
|
57
|
-
if (!baseUrl) {
|
|
58
|
-
console.warn("⚠ sitemap.xml skipped: no site URL (pass --base-url or set afw.config)");
|
|
59
|
-
return false;
|
|
60
|
-
}
|
|
61
|
-
const urls = paths
|
|
62
|
-
.map((p) => {
|
|
63
|
-
const lastmod = lastUpdated[p] ? `<lastmod>${escapeXml(lastUpdated[p])}</lastmod>` : "";
|
|
64
|
-
return ` <url><loc>${escapeXml(absoluteUrl(baseUrl, p))}</loc>${lastmod}</url>`;
|
|
65
|
-
})
|
|
66
|
-
.join("\n");
|
|
67
|
-
const xml =
|
|
68
|
-
`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
|
69
|
-
`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`;
|
|
70
|
-
await writeFile(join(outDir, "sitemap.xml"), xml);
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Emit a permissive robots.txt referencing the sitemap (honor a public/ override).
|
|
75
|
-
async function writeRobots(outDir, publicDir, baseUrl, hasSitemap) {
|
|
76
|
-
if (await exists(join(publicDir, "robots.txt"))) return false;
|
|
77
|
-
let body = "User-agent: *\nAllow: /\n";
|
|
78
|
-
if (baseUrl && hasSitemap) body += `Sitemap: ${absoluteUrl(baseUrl, "/sitemap.xml")}\n`;
|
|
79
|
-
await writeFile(join(outDir, "robots.txt"), body);
|
|
80
|
-
return true;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function escapeXml(s) {
|
|
84
|
-
return String(s).replace(/[&<>'"]/g, (c) =>
|
|
85
|
-
c === "&" ? "&" : c === "<" ? "<" : c === ">" ? ">" : c === "'" ? "'" : """,
|
|
86
|
-
);
|
|
87
|
-
}
|
|
11
|
+
import { buildServerBundle } from "./shared.js";
|
|
88
12
|
|
|
89
13
|
/**
|
|
90
14
|
* Pre-render the app to static HTML files under `outDir`. Returns
|
|
91
15
|
* `{ count, skipped, failed, siteDescription }` — `siteDescription` is the site's own
|
|
92
16
|
* `<meta name="description">` text (home route, falling back to the root layout's
|
|
93
17
|
* route-independent metadata), which `llms.txt` uses for its summary line.
|
|
18
|
+
*
|
|
19
|
+
* The rendering itself is `prerender` from `@opentf/afw-build`, shared with the Vite
|
|
20
|
+
* workflow; this builds the esdev server bundle it renders from.
|
|
94
21
|
*/
|
|
95
22
|
export async function runPrerender({ root, pages, afwEntry, afwc, shellHtml, outDir, baseUrl = "", docsPlugins = [], lastUpdated = {}, i18n = null, loaders = null, chunkManifest = null, onCompile, onRender }) {
|
|
96
23
|
const { mod, cleanup } = await buildServerBundle({ root, pages, afwEntry, afwc, docsPlugins, i18n, onCompile });
|
|
97
|
-
|
|
98
|
-
// i18n (docs/I18N.md §6): pre-render each route once per locale. The default
|
|
99
|
-
// locale is emitted bare (dist/<route>/index.html), others under their prefix
|
|
100
|
-
// (dist/<locale>/<route>/index.html). A single `[null]` means i18n is off — the
|
|
101
|
-
// loop collapses to the original one-render-per-route behavior.
|
|
102
|
-
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
103
|
-
const locales = i18nOn ? i18n.locales : [null];
|
|
104
|
-
const defaultLocale = i18nOn ? i18n.defaultLocale : null;
|
|
105
|
-
|
|
106
|
-
const { paths, skipped } = await mod.collectRoutePaths();
|
|
107
|
-
|
|
108
|
-
// `<link rel="modulepreload">` for the page + layout chunks this route will import,
|
|
109
|
-
// so the browser fetches them in parallel with `bundle.js` rather than after it.
|
|
110
|
-
const preloadFor = (route) => modulepreloadTags(chunkManifest?.routes?.[route]);
|
|
111
|
-
const failed = [];
|
|
112
|
-
const rendered = []; // concrete paths that produced an HTML file (for the sitemap)
|
|
113
|
-
let renderedCount = 0;
|
|
114
|
-
let siteDescription = ""; // the home route's resolved description (see the JSDoc above)
|
|
115
|
-
for (const { path, params, route } of paths) {
|
|
116
|
-
onRender?.(++renderedCount, paths.length);
|
|
117
|
-
for (const locale of locales) {
|
|
118
|
-
const urlPath = localizeFor(path, locale, defaultLocale);
|
|
119
|
-
try {
|
|
120
|
-
// Route loader (docs/DATA.md): run it at build time with no `request` and
|
|
121
|
-
// an empty query (a query-dependent loader needs a request server). The result
|
|
122
|
-
// is threaded into the render (`router.data`), inlined into the HTML, and
|
|
123
|
-
// written as a sibling `__data.json` — per locale, since a localized
|
|
124
|
-
// loader can return locale-dependent data.
|
|
125
|
-
const m = loaders?.match(urlPath);
|
|
126
|
-
let data;
|
|
127
|
-
let dataJson = "";
|
|
128
|
-
if (m) ({ data, json: dataJson } = await loaders.loadSerialized(m, { query: {} }));
|
|
129
|
-
|
|
130
|
-
// Passing the localized URL pins router.locale (resolveLocale) and still
|
|
131
|
-
// matches the locale-agnostic route table, so `t()` renders in `locale`.
|
|
132
|
-
const { html, metadata, hydration } =
|
|
133
|
-
(await mod.renderRoute(urlPath, params, "", { data })) ?? { html: "", metadata: {}, hydration: "" };
|
|
134
|
-
const meta = i18nOn
|
|
135
|
-
? { ...metadata, links: [...(metadata.links || []), ...alternatesFor(path, locales, defaultLocale)] }
|
|
136
|
-
: metadata;
|
|
137
|
-
if (path === "/" && (!locale || locale === defaultLocale) && typeof metadata?.description === "string") {
|
|
138
|
-
siteDescription = metadata.description;
|
|
139
|
-
}
|
|
140
|
-
let head = mod.renderHead(meta, { path: urlPath, baseUrl, managed: true });
|
|
141
|
-
const preload = preloadFor(route);
|
|
142
|
-
if (preload) head += `\n${preload}`;
|
|
143
|
-
// SEO: expose the page's last-updated time (git/frontmatter) as Open Graph's
|
|
144
|
-
// article:modified_time so crawlers see when the content actually changed,
|
|
145
|
-
// and a frontmatter `date` as article:published_time (blog posts).
|
|
146
|
-
// Article tags only on an article: `og:type` "article", or a page with a publish
|
|
147
|
-
// `date`. An index or a landing page is a website; a modified time there
|
|
148
|
-
// describes nothing.
|
|
149
|
-
const published = typeof metadata?.date === "string" ? metadata.date.trim() : "";
|
|
150
|
-
const article = metadata?.openGraph?.type === "article" || Boolean(published);
|
|
151
|
-
const iso = article ? lastUpdated[path] : null;
|
|
152
|
-
if (iso) head += `\n<meta data-afw-head="" property="article:modified_time" content="${escapeXml(iso)}">`;
|
|
153
|
-
if (published) head += `\n<meta data-afw-head="" property="article:published_time" content="${escapeXml(published)}">`;
|
|
154
|
-
// Static hosts decode requested URLs when locating files. Decode generated
|
|
155
|
-
// segments once; leave literal static folder names unchanged.
|
|
156
|
-
const outputPath = Object.keys(params).length
|
|
157
|
-
? urlPath.split("/").map(decodeURIComponent).join("/") : urlPath;
|
|
158
|
-
const file = htmlPathFor(outDir, outputPath);
|
|
159
|
-
await writeFile(
|
|
160
|
-
file,
|
|
161
|
-
injectRouteData(
|
|
162
|
-
injectHydrationData(
|
|
163
|
-
injectMarkup(injectHead(withHtmlLang(stampRenderedPath(shellHtml, urlPath), locale), head), html),
|
|
164
|
-
hydration,
|
|
165
|
-
),
|
|
166
|
-
dataJson,
|
|
167
|
-
),
|
|
168
|
-
);
|
|
169
|
-
if (m) {
|
|
170
|
-
// The static data file SPA navigation fetches on a plain static host —
|
|
171
|
-
// byte-identical to the inline payload ("null" when the loader returned
|
|
172
|
-
// undefined, so a 200 still parses as JSON).
|
|
173
|
-
const dataFile = join(dirname(file), DATA_FILE);
|
|
174
|
-
await writeFile(dataFile, dataJson || "null");
|
|
175
|
-
}
|
|
176
|
-
rendered.push(urlPath);
|
|
177
|
-
} catch (e) {
|
|
178
|
-
failed.push(urlPath);
|
|
179
|
-
const why = e?.afwNotFound ? "loader called notFound()" : (e?.message ?? e);
|
|
180
|
-
console.error(`✗ pre-render failed for ${urlPath}: ${why}`);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// 404: any unmatched path resolves to the registered 404 page. Mark noindex so
|
|
186
|
-
// crawlers don't index the error page, and keep it out of the sitemap.
|
|
187
24
|
try {
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
injectHydrationData(injectMarkup(injectHead(shellHtml, head), result.html), result.hydration),
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
} catch {
|
|
199
|
-
/* no 404 page */
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Crawl infrastructure: sitemap.xml + robots.txt (honoring public/ overrides).
|
|
203
|
-
const publicDir = join(root, "public");
|
|
204
|
-
const hasSitemap = await writeSitemap(outDir, publicDir, baseUrl, rendered, lastUpdated);
|
|
205
|
-
await writeRobots(outDir, publicDir, baseUrl, hasSitemap);
|
|
206
|
-
|
|
207
|
-
// No "/" route (or it declared no description): fall back to the layout chain's
|
|
208
|
-
// route-independent metadata — the site-wide description every route inherits.
|
|
209
|
-
if (!siteDescription) {
|
|
210
|
-
try {
|
|
211
|
-
const siteMeta = await mod.resolveMetadata({ route: "/", entry: null });
|
|
212
|
-
if (typeof siteMeta?.description === "string") siteDescription = siteMeta.description;
|
|
213
|
-
} catch {
|
|
214
|
-
/* no root layout metadata */
|
|
215
|
-
}
|
|
25
|
+
const { count, skipped, failed, siteDescription } = await prerender(esdevHost, {
|
|
26
|
+
render: mod, shellHtml, outDir, publicDir: join(root, "public"), baseUrl, lastUpdated, i18n, loaders,
|
|
27
|
+
chunkManifest, onRender,
|
|
28
|
+
});
|
|
29
|
+
return { count, skipped, failed, siteDescription };
|
|
30
|
+
} finally {
|
|
31
|
+
await cleanup();
|
|
216
32
|
}
|
|
217
|
-
|
|
218
|
-
cleanup();
|
|
219
|
-
return { count: rendered.length, skipped, failed, siteDescription };
|
|
220
33
|
}
|
package/src/shared.js
CHANGED
|
@@ -21,128 +21,19 @@ export { closeCompilers, resolveCompiler };
|
|
|
21
21
|
|
|
22
22
|
export const EXTENSIONS = [".jsx", ".tsx", ".js", ".ts", ".mdx", ".md"];
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
export
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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, "&").replace(/"/g, """);
|
|
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
|
-
}
|
|
24
|
+
// The HTML document helpers live in `@opentf/afw-build`, shared with the Vite workflow.
|
|
25
|
+
export {
|
|
26
|
+
DATA_FILE,
|
|
27
|
+
injectBeforeBody,
|
|
28
|
+
injectHead,
|
|
29
|
+
injectHydrationData,
|
|
30
|
+
injectMarkup,
|
|
31
|
+
injectRouteData,
|
|
32
|
+
modulepreloadTags,
|
|
33
|
+
stampHydrateSentinel,
|
|
34
|
+
stampRenderedPath,
|
|
35
|
+
withHtmlLang,
|
|
36
|
+
} from "@opentf/afw-build";
|
|
146
37
|
|
|
147
38
|
export { findUp };
|
|
148
39
|
|
|
@@ -239,69 +130,33 @@ export function searchProviderWarning(config) {
|
|
|
239
130
|
`use "afw" or remove it. Search is disabled for this build.`;
|
|
240
131
|
}
|
|
241
132
|
|
|
133
|
+
// The post-prerender docs steps live in `@opentf/afw-docs` (build/finish.js), shared
|
|
134
|
+
// with the Vite workflow. These wrappers keep this package's signatures and resolve the
|
|
135
|
+
// app's own `@opentf/afw-docs`.
|
|
136
|
+
async function docsBuild(root) {
|
|
137
|
+
const entry = await resolveFrom("@opentf/afw-docs/build", root);
|
|
138
|
+
const mod = await import(toFileURL(entry).href);
|
|
139
|
+
if (typeof mod.runBlogFeed !== "function") {
|
|
140
|
+
throw new Error("this @opentf/afw-docs predates the shared build steps; update @opentf/afw-docs");
|
|
141
|
+
}
|
|
142
|
+
return mod;
|
|
143
|
+
}
|
|
144
|
+
|
|
242
145
|
/** Index the completed SSG output when static search is enabled. Errors fail the build. */
|
|
243
146
|
export async function runDocsSearchIndex(root, config, siteDir, afwc) {
|
|
244
147
|
if (config?.docs?.search?.provider !== "afw") return null;
|
|
245
|
-
|
|
246
|
-
const { indexWithAfwSearch } = await import(toFileURL(entry).href);
|
|
247
|
-
return indexWithAfwSearch({ siteDir, afwc });
|
|
148
|
+
return (await docsBuild(root)).runDocsSearchIndex(config, siteDir, afwc);
|
|
248
149
|
}
|
|
249
150
|
|
|
250
151
|
/**
|
|
251
|
-
* Generate blog feeds when the project has a `blog` config and a base URL.
|
|
252
|
-
*
|
|
253
|
-
*
|
|
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`.
|
|
152
|
+
* Generate blog feeds when the project has a `blog` config and a base URL: RSS 2.0 and
|
|
153
|
+
* Atom 1.0 under `<siteDir>/<blogDir>/`, linked from every page. A
|
|
154
|
+
* `public/<blogDir>/{rss,atom}.xml` file wins. Returns `{ paths, urls, count }` or null.
|
|
257
155
|
*/
|
|
258
156
|
export async function runBlogFeed(root, appDir, config, siteDir, baseUrl, exclude = new Set()) {
|
|
259
|
-
|
|
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";
|
|
157
|
+
if (!config?.blog) return null;
|
|
266
158
|
try {
|
|
267
|
-
|
|
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 };
|
|
159
|
+
return await (await docsBuild(root)).runBlogFeed({ root, appDir, config, siteDir, baseUrl, exclude });
|
|
305
160
|
} catch (e) {
|
|
306
161
|
console.warn(`⚠ blog feeds skipped: ${e?.message ?? e}`);
|
|
307
162
|
return null;
|
|
@@ -309,65 +164,39 @@ export async function runBlogFeed(root, appDir, config, siteDir, baseUrl, exclud
|
|
|
309
164
|
}
|
|
310
165
|
|
|
311
166
|
/**
|
|
312
|
-
*
|
|
313
|
-
*
|
|
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, "&").replace(/"/g, """).replace(/</g, "<");
|
|
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.
|
|
167
|
+
* Generate `/llms.txt` and `/llms-full.txt` for docs/blog sites. Files in `public/`
|
|
168
|
+
* override each output. `siteDescription` summarizes the site.
|
|
341
169
|
*/
|
|
342
170
|
export async function runLlmsFiles(root, appDir, pages, config, siteDir, baseUrl, { siteDescription = "" } = {}) {
|
|
343
171
|
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
172
|
try {
|
|
355
|
-
|
|
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;
|
|
173
|
+
return await (await docsBuild(root)).runLlmsFiles({ root, appDir, pages, config, siteDir, baseUrl, siteDescription });
|
|
365
174
|
} catch (e) {
|
|
366
175
|
console.warn(`⚠ llms.txt skipped: ${e?.message ?? e}`);
|
|
367
176
|
return null;
|
|
368
177
|
}
|
|
369
178
|
}
|
|
370
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Resolve-aliases pinning every `@opentf/afw` import of a server bundle to the package
|
|
182
|
+
* beside `afwEntry` (its `index.js`), one entry per subpath in the package's `exports`.
|
|
183
|
+
* An alias also covers the subpaths under its key, so a lone `"@opentf/afw": index.js`
|
|
184
|
+
* turned the compiler's `@opentf/afw/signals` import into `index.js/signals`. Longer keys
|
|
185
|
+
* come first; types-only exports (`./jsx-runtime`) have no runtime file to alias.
|
|
186
|
+
*/
|
|
187
|
+
export async function afwAliases(afwEntry) {
|
|
188
|
+
const dir = dirname(afwEntry);
|
|
189
|
+
const { exports = {} } = JSON.parse(await readText(join(dir, "package.json")));
|
|
190
|
+
const aliases = {};
|
|
191
|
+
for (const [key, target] of Object.entries(exports).sort((a, b) => b[0].length - a[0].length)) {
|
|
192
|
+
if (key === "." || !key.startsWith("./")) continue;
|
|
193
|
+
const file = typeof target === "string" ? target : target?.default ?? target?.import;
|
|
194
|
+
if (typeof file === "string" && !file.endsWith(".d.ts")) aliases[`@opentf/afw/${key.slice(2)}`] = join(dir, file);
|
|
195
|
+
}
|
|
196
|
+
aliases["@opentf/afw"] = afwEntry;
|
|
197
|
+
return aliases;
|
|
198
|
+
}
|
|
199
|
+
|
|
371
200
|
/**
|
|
372
201
|
* Discover file-based routes under `app/`: every page/layout and the 404. This list is
|
|
373
202
|
* what gets prerendered, so drafts and scheduled Markdown pages (`isUnpublishedPage`)
|
|
@@ -428,12 +257,6 @@ function stripAppPrefix(filePath, appDir) {
|
|
|
428
257
|
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
429
258
|
}
|
|
430
259
|
|
|
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
260
|
/** The page URL for a `.../app/<...>/page.{mdx,md,jsx,tsx}` file (folder = URL). */
|
|
438
261
|
export function pageRouteFromPath(filePath, appDir) {
|
|
439
262
|
const r = stripAppPrefix(filePath, appDir).replace(/\/page\.(mdx|md|jsx|tsx)$/, "");
|
|
@@ -584,12 +407,11 @@ export async function emitApiBundle({ root, appDir, afwEntry, exclude, i18n, out
|
|
|
584
407
|
const entry = join(tmp, "api-entry.js");
|
|
585
408
|
await writeFile(entry, apiEntrySource(discovered, appDir, i18n));
|
|
586
409
|
|
|
587
|
-
const serverApi = join(dirname(afwEntry), "server", "index.js");
|
|
588
410
|
await mkdirp(outDir);
|
|
589
411
|
const bundle = await build({
|
|
590
412
|
input: entry,
|
|
591
413
|
platform: "node",
|
|
592
|
-
resolve: { alias:
|
|
414
|
+
resolve: { alias: await afwAliases(afwEntry), extensions: EXTENSIONS },
|
|
593
415
|
external: (id) => !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("@opentf/afw"),
|
|
594
416
|
});
|
|
595
417
|
try {
|
|
@@ -636,12 +458,11 @@ export async function emitLoaderBundle({ root, appDir, afwEntry, exclude, i18n,
|
|
|
636
458
|
const entry = join(tmp, "loaders-entry.js");
|
|
637
459
|
await writeFile(entry, loaderEntrySource(files, appDir, i18n));
|
|
638
460
|
|
|
639
|
-
const serverApi = join(dirname(afwEntry), "server", "index.js");
|
|
640
461
|
await mkdirp(outDir);
|
|
641
462
|
const bundle = await build({
|
|
642
463
|
input: entry,
|
|
643
464
|
platform: "node",
|
|
644
|
-
resolve: { alias:
|
|
465
|
+
resolve: { alias: await afwAliases(afwEntry), extensions: EXTENSIONS },
|
|
645
466
|
external: (id) => !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("@opentf/afw"),
|
|
646
467
|
});
|
|
647
468
|
try {
|
|
@@ -727,11 +548,10 @@ export async function buildServerBundle({
|
|
|
727
548
|
const entry = join(tmp, "ssg-entry.js");
|
|
728
549
|
await writeFile(entry, serverEntrySource(pages, i18n));
|
|
729
550
|
|
|
730
|
-
const serverApi = join(dirname(afwEntry), "server", "index.js");
|
|
731
551
|
const bundle = await build({
|
|
732
552
|
input: entry,
|
|
733
553
|
resolve: {
|
|
734
|
-
alias:
|
|
554
|
+
alias: await afwAliases(afwEntry),
|
|
735
555
|
extensions: EXTENSIONS,
|
|
736
556
|
},
|
|
737
557
|
// The runtime guards its dev diagnostics on `process.env.NODE_ENV`, and there is
|