@opentf/afw-build 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@opentf/afw-build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The toolchain-neutral core of AFW's build: compiler client, compile targets and file-based routing.",
5
+ "type": "module",
6
+ "scripts": {
7
+ "build": "cp ../../LICENSE LICENSE"
8
+ },
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./document": "./document.js"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "host.js",
16
+ "compiler-client.js",
17
+ "compile.js",
18
+ "resolve-compiler.js",
19
+ "routes.js",
20
+ "server.js",
21
+ "document.js",
22
+ "prerender.js",
23
+ "server-functions.js"
24
+ ],
25
+ "keywords": [
26
+ "afw",
27
+ "opentf",
28
+ "build",
29
+ "compiler",
30
+ "routing"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/Open-Tech-Foundation/afw.git",
35
+ "directory": "packages/afw-build"
36
+ },
37
+ "homepage": "https://afw.opentechf.org/docs",
38
+ "bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
39
+ "license": "MIT",
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }
package/prerender.js ADDED
@@ -0,0 +1,124 @@
1
+ // Static generation, shared by every toolchain: render each route of a built server
2
+ // bundle to `index.html` files (plus `__data.json` for loader routes), a `404.html`,
3
+ // and `sitemap.xml` / `robots.txt`. Each page is rendered by `renderDocument`, the
4
+ // same function a request server uses.
5
+
6
+ import { DATA_FILE, escapeXml, i18nSettings, localizePath, modulepreloadTags, renderDocument, renderNotFound } from "./document.js";
7
+
8
+ // "/" → <out>/index.html, "/post/1" → <out>/post/1/index.html.
9
+ function htmlPathFor(host, outDir, route) {
10
+ return route === "/" ? host.path.join(outDir, "index.html") : host.path.join(outDir, route, "index.html");
11
+ }
12
+
13
+ function absoluteUrl(baseUrl, path) {
14
+ if (!baseUrl) return "";
15
+ return baseUrl.replace(/\/+$/, "") + (path === "/" ? "/" : path);
16
+ }
17
+
18
+ /** `sitemap.xml` for the rendered paths, with `<lastmod>` where known. */
19
+ export function sitemapXml(baseUrl, paths, lastUpdated = {}) {
20
+ const urls = paths
21
+ .map((p) => {
22
+ const lastmod = lastUpdated[p] ? `<lastmod>${escapeXml(lastUpdated[p])}</lastmod>` : "";
23
+ return ` <url><loc>${escapeXml(absoluteUrl(baseUrl, p))}</loc>${lastmod}</url>`;
24
+ })
25
+ .join("\n");
26
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`;
27
+ }
28
+
29
+ /** A permissive `robots.txt`, pointing at the sitemap when there is one. */
30
+ export function robotsTxt(baseUrl, hasSitemap) {
31
+ let body = "User-agent: *\nAllow: /\n";
32
+ if (baseUrl && hasSitemap) body += `Sitemap: ${absoluteUrl(baseUrl, "/sitemap.xml")}\n`;
33
+ return body;
34
+ }
35
+
36
+ /**
37
+ * Pre-render the app into `outDir`.
38
+ *
39
+ * `render` is the server bundle's render API (`renderRoute`, `renderHead`,
40
+ * `collectRoutePaths`, `resolveMetadata`). `shellHtml` is the client's `index.html`
41
+ * (marked for hydration by the caller when the client hydrates). `loaders` is the
42
+ * loader registry, run at build time with no request and an empty query. A
43
+ * `public/sitemap.xml` or `public/robots.txt` in `publicDir` wins over the generated one.
44
+ *
45
+ * @returns {Promise<{ count: number, skipped: string[], failed: string[], siteDescription: string, paths: string[] }>}
46
+ * `siteDescription` is the site's own description (home route, else the root
47
+ * layout's metadata) for summaries such as `llms.txt`.
48
+ */
49
+ export async function prerender(host, {
50
+ render, shellHtml, outDir, publicDir, baseUrl = "", lastUpdated = {}, i18n = null, loaders = null,
51
+ chunkManifest = null, onRender,
52
+ }) {
53
+ const settings = i18nSettings(i18n);
54
+ const locales = settings ? settings.locales : [null];
55
+ const defaultLocale = settings?.defaultLocale ?? null;
56
+ const { paths, skipped } = await render.collectRoutePaths();
57
+ const preloadFor = (route) => modulepreloadTags(chunkManifest?.routes?.[route]);
58
+
59
+ const failed = [];
60
+ const rendered = [];
61
+ let count = 0;
62
+ let siteDescription = "";
63
+ for (const { path, params, route } of paths) {
64
+ onRender?.(++count, paths.length);
65
+ for (const locale of locales) {
66
+ const url = localizePath(path, locale, defaultLocale);
67
+ try {
68
+ const doc = await renderDocument(render, {
69
+ shell: shellHtml, url, params, loaders, baseUrl, i18n, notFound: "throw",
70
+ preload: preloadFor(route), modifiedTime: lastUpdated[path] ?? null,
71
+ });
72
+ if (path === "/" && (!locale || locale === defaultLocale) && typeof doc?.metadata?.description === "string") {
73
+ siteDescription = doc.metadata.description;
74
+ }
75
+ // Static hosts decode requested URLs when locating files. Decode generated
76
+ // segments once; leave literal static folder names unchanged.
77
+ const outputPath = Object.keys(params ?? {}).length ? url.split("/").map(decodeURIComponent).join("/") : url;
78
+ const file = htmlPathFor(host, outDir, outputPath);
79
+ await host.writeText(file, doc?.html ?? shellHtml);
80
+ // The static data file SPA navigation fetches on a plain static host —
81
+ // byte-identical to the inline payload ("null" for an undefined result).
82
+ if (doc?.loaded) await host.writeText(host.path.join(host.path.dirname(file), DATA_FILE), doc.dataJson || "null");
83
+ rendered.push(url);
84
+ } catch (e) {
85
+ failed.push(url);
86
+ const why = e?.afwNotFound ? "loader called notFound()" : (e?.message ?? e);
87
+ console.error(`✗ pre-render failed for ${url}: ${why}`);
88
+ }
89
+ }
90
+ }
91
+
92
+ // Any unmatched path is served the 404 page by static hosts.
93
+ try {
94
+ const notFound = await renderNotFound(render, { shell: shellHtml, baseUrl, preload: modulepreloadTags(chunkManifest?.notFound) });
95
+ if (notFound) await host.writeText(host.path.join(outDir, "404.html"), notFound.html);
96
+ } catch {
97
+ /* no 404 page */
98
+ }
99
+
100
+ let hasSitemap = false;
101
+ if (!(await host.kind(host.path.join(publicDir, "sitemap.xml")))) {
102
+ if (baseUrl) {
103
+ await host.writeText(host.path.join(outDir, "sitemap.xml"), sitemapXml(baseUrl, rendered, lastUpdated));
104
+ hasSitemap = true;
105
+ } else {
106
+ console.warn("⚠ sitemap.xml skipped: no site URL (set a base URL)");
107
+ }
108
+ }
109
+ if (!(await host.kind(host.path.join(publicDir, "robots.txt")))) {
110
+ await host.writeText(host.path.join(outDir, "robots.txt"), robotsTxt(baseUrl, hasSitemap));
111
+ }
112
+
113
+ // No "/" route (or it declared no description): fall back to the layout chain's
114
+ // route-independent metadata — the site-wide description every route inherits.
115
+ if (!siteDescription) {
116
+ try {
117
+ const siteMeta = await render.resolveMetadata({ route: "/", entry: null });
118
+ if (typeof siteMeta?.description === "string") siteDescription = siteMeta.description;
119
+ } catch {
120
+ /* no root layout metadata */
121
+ }
122
+ }
123
+ return { count: rendered.length, skipped, failed, siteDescription, paths: rendered };
124
+ }
@@ -0,0 +1,75 @@
1
+ // Locate the `afwc` binary: `AFWC_BIN`, else the prebuilt binary from
2
+ // `@opentf/afw-compiler`, else — in a source checkout of this repository — the cargo
3
+ // build, compiled on demand. Failures throw; the toolchain decides how to report them.
4
+
5
+ /** Nearest ancestor directory of `from` (inclusive) that contains `name`. */
6
+ export async function findUp(host, name, from) {
7
+ let dir = from;
8
+ for (;;) {
9
+ if (await host.kind(host.path.join(dir, name))) return dir;
10
+ const parent = host.path.dirname(dir);
11
+ if (parent === dir) return null;
12
+ dir = parent;
13
+ }
14
+ }
15
+
16
+ async function hasLocalCompilerWorkspace(host, workspace) {
17
+ return !!workspace && (await host.kind(host.path.join(workspace, "crates", "afw_cli", "Cargo.toml"))) === "file";
18
+ }
19
+
20
+ /** Build `afwc` from the source checkout at `workspace` unless it already exists. */
21
+ export async function ensureCompiler(host, afwc, workspace) {
22
+ if (await host.kind(afwc)) return;
23
+ if (!workspace) throw new Error(`afwc compiler not found at ${afwc}`);
24
+ console.log("building compiler (cargo build -p afw_cli)…");
25
+ const cargo = await host.run("cargo", ["--version"], { cwd: workspace });
26
+ if (!cargo.ok) {
27
+ throw new Error(
28
+ `cannot build afwc because cargo is not available.\n` +
29
+ ` This source checkout needs Rust/Cargo to build ${afwc}.\n` +
30
+ ` Install Rust in the build environment, set AFWC_BIN to an existing afwc binary,\n` +
31
+ ` or install the published packages so @opentf/afw-compiler can use its prebuilt binary.`,
32
+ );
33
+ }
34
+ const built = await host.run("cargo", ["build", "-p", "afw_cli"], { cwd: workspace, inherit: true });
35
+ if (!built.ok) throw new Error(`cargo build -p afw_cli failed (exit ${built.code ?? "unknown"})`);
36
+ }
37
+
38
+ /**
39
+ * Resolve the compiler binary. `cliDir` is the calling package's directory: a copy
40
+ * installed under `node_modules` never builds from source, a workspace checkout may.
41
+ * `resolvePackagedCompiler` is the platform's `afwcPath` from `@opentf/afw-compiler`.
42
+ * `findWorkspace` and `ensure` are injectable for tests.
43
+ *
44
+ * @returns {Promise<{ afwc: string, workspace: string | null }>}
45
+ */
46
+ export async function resolveCompiler(host, {
47
+ cliDir,
48
+ env = host.env,
49
+ resolvePackagedCompiler,
50
+ findWorkspace = (name, from) => findUp(host, name, from),
51
+ ensure = (afwc, workspace) => ensureCompiler(host, afwc, workspace),
52
+ } = {}) {
53
+ if (env.AFWC_BIN) return { afwc: env.AFWC_BIN, workspace: null };
54
+
55
+ let packagedError = null;
56
+ try {
57
+ if (typeof resolvePackagedCompiler !== "function") throw new Error("no packaged compiler resolver");
58
+ return { afwc: await resolvePackagedCompiler(), workspace: null };
59
+ } catch (e) {
60
+ packagedError = e;
61
+ }
62
+
63
+ const installedPackage = !!cliDir && cliDir.split(/[\\/]/).includes("node_modules");
64
+ const workspace = installedPackage || !cliDir ? null : await findWorkspace("Cargo.toml", cliDir);
65
+ if (await hasLocalCompilerWorkspace(host, workspace)) {
66
+ const afwc = host.path.join(workspace, "target", "debug", "afwc");
67
+ await ensure(afwc, workspace);
68
+ return { afwc, workspace };
69
+ }
70
+
71
+ throw new Error(
72
+ `${packagedError?.message ?? "cannot resolve @opentf/afw-compiler prebuilt binary"}\n` +
73
+ ` No local afwc compiler workspace was found to build from source.`,
74
+ );
75
+ }
package/routes.js ADDED
@@ -0,0 +1,176 @@
1
+ // File-convention routing shared by every toolchain: crawl `app/` for page, layout,
2
+ // 404 and loader files and generate the `@afw/routes` module an entry imports:
3
+ //
4
+ // import { mountApp } from "@opentf/afw";
5
+ // import { guard, pages, loaderRoutes } from "@afw/routes";
6
+ //
7
+ // Route keys keep their `/app/...` shape because the runtime's `routeFromPath`
8
+ // anchors on it; layouts compose by path (`layout.jsx` wraps its directory).
9
+
10
+ /** The specifier entries import. */
11
+ export const ROUTES_ID = "@afw/routes";
12
+
13
+ const PAGE_FILE = /^(page|layout|404)\.(mdx|md|jsx|tsx)$/;
14
+ const LOADER_FILE = /^loader\.(js|ts)$/;
15
+
16
+ /**
17
+ * Whether Markdown source is unpublished: frontmatter `draft: true`, or a `date`
18
+ * later than `now` (scheduled). Production builds leave such pages out of the route
19
+ * table, so their text never reaches a bundle; dev servers keep them. The same rule
20
+ * as `@opentf/afw-docs` publish.js, which drives the post list, feeds and docs nav.
21
+ */
22
+ export function isUnpublishedSource(source, now = Date.now()) {
23
+ const block = source.match(/^?---\r?\n([\s\S]*?)\r?\n---/)?.[1];
24
+ if (!block) return false;
25
+ const field = (key) => {
26
+ const m = block.match(new RegExp(`^\\s*${key}\\s*:\\s*(.*?)\\s*$`, "m"));
27
+ return m ? m[1].replace(/^(["'])(.*)\1$/, "$2") : null;
28
+ };
29
+ if (field("draft") === "true") return true;
30
+ const date = field("date");
31
+ if (!date) return false;
32
+ const at = new Date(date).getTime();
33
+ return !Number.isNaN(at) && at > now;
34
+ }
35
+
36
+ /** {@link isUnpublishedSource} for a file; non-Markdown and unreadable files are published. */
37
+ export async function isUnpublishedPage(host, path, now = Date.now()) {
38
+ if (!/\.(mdx|md)$/.test(path)) return false;
39
+ let source;
40
+ try {
41
+ source = await host.readText(path);
42
+ } catch {
43
+ return false;
44
+ }
45
+ return isUnpublishedSource(source, now);
46
+ }
47
+
48
+ /**
49
+ * Every file under `dir` whose name matches `pattern`, as `/`-separated paths
50
+ * relative to `dir`, sorted. Dot directories and `node_modules` are skipped, and
51
+ * so are excluded subtrees (`exclude` holds paths relative to `dir`).
52
+ */
53
+ async function walk(host, dir, pattern, exclude) {
54
+ const found = [];
55
+ async function visit(abs, rel) {
56
+ let entries;
57
+ try {
58
+ entries = await host.readDir(abs);
59
+ } catch {
60
+ return;
61
+ }
62
+ for (const entry of entries) {
63
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
64
+ if ([...exclude].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
65
+ const childAbs = host.path.join(abs, entry.name);
66
+ let isDir = entry.isDir;
67
+ let isFile = entry.isFile;
68
+ if (entry.isSymlink) {
69
+ const kind = await host.kind(childAbs);
70
+ isDir = kind === "dir";
71
+ isFile = kind === "file";
72
+ }
73
+ if (isDir) {
74
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
75
+ await visit(childAbs, childRel);
76
+ } else if (isFile && pattern.test(entry.name)) {
77
+ found.push(childRel);
78
+ }
79
+ }
80
+ }
81
+ await visit(dir, "");
82
+ return found.sort();
83
+ }
84
+
85
+ /**
86
+ * Page, layout and 404 files under `dir`, as absolute paths. A Markdown 404 is an
87
+ * error (the runtime has no Markdown fallback route). Without `drafts`,
88
+ * unpublished Markdown pages are left out.
89
+ */
90
+ export async function discoverPages(host, dir, { exclude = [], drafts = true } = {}) {
91
+ const out = [];
92
+ for (const rel of await walk(host, dir, PAGE_FILE, new Set(exclude))) {
93
+ const abs = host.path.join(dir, rel);
94
+ if (/(^|\/)404\.(mdx|md)$/.test(rel)) {
95
+ throw new Error(`Unsupported Markdown 404 route: ${abs}. Use 404.jsx or 404.tsx instead.`);
96
+ }
97
+ if (!drafts && (await isUnpublishedPage(host, abs))) continue;
98
+ out.push(abs);
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /** Loader files under `dir` as `[route, absPath]` pairs, sorted by route. A route
104
+ * with both `loader.js` and `loader.ts` is an error. */
105
+ export async function discoverLoaders(host, dir, { exclude = [] } = {}) {
106
+ const routes = new Map();
107
+ for (const rel of await walk(host, dir, LOADER_FILE, new Set(exclude))) {
108
+ const pattern = rel.replace(/(^|\/)loader\.(js|ts)$/, "") || "/";
109
+ const route = pattern.startsWith("/") ? pattern : `/${pattern}`;
110
+ const abs = host.path.join(dir, rel);
111
+ if (routes.has(route)) throw new Error(`Conflicting loaders for ${route}: ${routes.get(route)} and ${abs}`);
112
+ routes.set(route, abs);
113
+ }
114
+ return [...routes].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
115
+ }
116
+
117
+ function stripAppPrefix(filePath, appDir) {
118
+ if (appDir) {
119
+ const base = appDir.replace(/\/+$/, "");
120
+ if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
121
+ }
122
+ return filePath.replace(/^.*\/app(?=\/)/, "");
123
+ }
124
+
125
+ /** The route-table key for a route file — keeps `/app` so `routeFromPath` resolves it. */
126
+ export function routeKey(filePath, appDir) {
127
+ return `/app${stripAppPrefix(filePath, appDir)}`;
128
+ }
129
+
130
+ /** The optional `app/routeGuard.{js,ts}`, or null. */
131
+ export async function findGuard(host, appDir) {
132
+ for (const name of ["routeGuard.js", "routeGuard.ts"]) {
133
+ const path = host.path.join(appDir, name);
134
+ if ((await host.kind(path)) === "file") return path;
135
+ }
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * The app directory for an entry. A leaf `appDir` ("app") anchors at the importing
141
+ * entry's site root — the nearest ancestor holding that folder — so one option value
142
+ * serves every app in a repository. A nested path ("website/app") resolves against
143
+ * the working directory.
144
+ */
145
+ export async function resolveAppRoot(host, appDir, importer) {
146
+ if (appDir.includes("/") || !importer) return host.path.resolve(host.cwd(), appDir);
147
+ let dir = host.path.dirname(importer);
148
+ for (;;) {
149
+ if ((await host.kind(host.path.join(dir, appDir))) === "dir") return host.path.join(dir, appDir);
150
+ const up = host.path.dirname(dir);
151
+ if (up === dir) return host.path.resolve(host.cwd(), appDir);
152
+ dir = up;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Generate the `@afw/routes` module for the app at `root`: lazy page imports, the
158
+ * loader route patterns (never the loader modules — they are server-only), and the
159
+ * optional route guard. `files` lists every file the module was derived from, so a
160
+ * toolchain can rebuild it when one changes.
161
+ *
162
+ * @returns {Promise<{ code: string, files: string[] }>}
163
+ */
164
+ export async function routesModule(host, root, { exclude = [], drafts = true } = {}) {
165
+ const pages = await discoverPages(host, root, { exclude, drafts });
166
+ const loaders = await discoverLoaders(host, root, { exclude });
167
+ const guard = await findGuard(host, root);
168
+ const map = pages
169
+ .map((p) => ` [${JSON.stringify(routeKey(p, root))}]: () => import(${JSON.stringify(p)}),`)
170
+ .join("\n");
171
+ const code =
172
+ `export const pages = {\n${map}\n};\n` +
173
+ `export const loaderRoutes = ${JSON.stringify(loaders.map(([route]) => route))};\n` +
174
+ (guard ? `export { default as guard } from ${JSON.stringify(guard)};\n` : `export const guard = undefined;\n`);
175
+ return { code, files: [...pages, ...loaders.map(([, file]) => file), ...(guard ? [guard] : [])] };
176
+ }
@@ -0,0 +1,107 @@
1
+ // Server functions at build time (docs/SERVER_FUNCTIONS.md), shared by every toolchain:
2
+ // find the app's `*.server.{js,ts}` modules, give each `query()` / `action()` export a
3
+ // stable endpoint under its folder, and generate the browser stub that calls it.
4
+ //
5
+ // Endpoints are computed here and nowhere else: the browser stub and the server's
6
+ // endpoint table both come from `serverFunctionEndpoint`, so they cannot disagree.
7
+
8
+ /** A server module's file name. */
9
+ export const SERVER_MODULE_FILE = /\.server\.(?:[cm]?js|[cm]?ts)$/;
10
+
11
+ // FNV-1a, 64-bit: a stable, short id that does not reveal the file path.
12
+ function fnv1a64(text) {
13
+ let hash = 0xcbf29ce484222325n;
14
+ for (const byte of new TextEncoder().encode(text)) {
15
+ hash ^= BigInt(byte);
16
+ hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;
17
+ }
18
+ return hash.toString(16).padStart(16, "0");
19
+ }
20
+
21
+ const relativeTo = (root, file) => (file.startsWith(`${root}/`) ? file.slice(root.length + 1) : null);
22
+
23
+ /**
24
+ * The endpoint of export `name` of the server module `file` under the app at `root`:
25
+ * `<folder>/__fn/<id>`, so the folder's `_middleware` governs it.
26
+ */
27
+ export function serverFunctionEndpoint(root, file, name) {
28
+ const rel = relativeTo(root, file);
29
+ if (rel === null) throw new Error(`${file}: server modules must be inside the app directory (${root})`);
30
+ const folder = rel.includes("/") ? `/${rel.slice(0, rel.lastIndexOf("/"))}` : "";
31
+ return `${folder}/__fn/${fnv1a64(`${rel}#${name}`)}`;
32
+ }
33
+
34
+ /** Every `*.server` module under `dir`, sorted, skipping dot folders, node_modules and `exclude`. */
35
+ export async function discoverServerModules(host, dir, { exclude = [] } = {}) {
36
+ const skip = new Set(exclude);
37
+ const found = [];
38
+ async function visit(abs, rel) {
39
+ let entries;
40
+ try {
41
+ entries = await host.readDir(abs);
42
+ } catch {
43
+ return;
44
+ }
45
+ for (const entry of entries) {
46
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
47
+ if ([...skip].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
48
+ const childAbs = host.path.join(abs, entry.name);
49
+ if (entry.isDir) {
50
+ if (!entry.name.startsWith(".") && entry.name !== "node_modules") await visit(childAbs, childRel);
51
+ } else if (entry.isFile && SERVER_MODULE_FILE.test(entry.name)) {
52
+ found.push(childAbs);
53
+ }
54
+ }
55
+ }
56
+ await visit(dir, "");
57
+ return found.sort();
58
+ }
59
+
60
+ /**
61
+ * The exports of a server module, from the compiler (`afwc serve`'s `server-exports`):
62
+ * `[{ name, kind: "query" | "action" | null }]`. Rejects with the compiler's diagnostic
63
+ * for shapes it cannot read statically.
64
+ */
65
+ export async function serverExports(compiler, file, source) {
66
+ const out = await compiler.compile(file, source, false, "server-exports");
67
+ return JSON.parse(typeof out === "string" ? out : out.code).exports;
68
+ }
69
+
70
+ /**
71
+ * The browser module that replaces a server module: one fetch stub per server function.
72
+ * Plain exports are left out, so importing a server-only helper from browser code fails
73
+ * the build instead of shipping it.
74
+ */
75
+ export function serverFunctionStub(root, file, exports) {
76
+ const lines = [`import { serverFunction } from "@opentf/afw";`];
77
+ for (const { name, kind } of exports) {
78
+ if (!kind) continue;
79
+ const endpoint = JSON.stringify(serverFunctionEndpoint(root, file, name));
80
+ lines.push(name === "default"
81
+ ? `export default serverFunction(${endpoint}, ${JSON.stringify(kind)});`
82
+ : `export const ${name} = serverFunction(${endpoint}, ${JSON.stringify(kind)});`);
83
+ }
84
+ return `${lines.join("\n")}\n`;
85
+ }
86
+
87
+ /**
88
+ * The server side: for each server module, its import and the endpoint table entries.
89
+ * `listExports(file)` returns the module's exports (see `serverExports`).
90
+ *
91
+ * @returns {Promise<{ imports: string, table: string, files: string[] }>}
92
+ */
93
+ export async function serverFunctionTable(host, root, { exclude = [], listExports }) {
94
+ const files = await discoverServerModules(host, root, { exclude });
95
+ const imports = [];
96
+ const entries = [];
97
+ for (const [i, file] of files.entries()) {
98
+ const exports = await listExports(file);
99
+ const fns = exports.filter((e) => e.kind);
100
+ if (!fns.length) continue;
101
+ imports.push(`import * as sf${i} from ${JSON.stringify(file)};`);
102
+ for (const { name } of fns) {
103
+ entries.push(` [${JSON.stringify(serverFunctionEndpoint(root, file, name))}]: sf${i}[${JSON.stringify(name)}],`);
104
+ }
105
+ }
106
+ return { imports: imports.join("\n"), table: entries.join("\n"), files };
107
+ }