@txco/web-abi 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/README.md +109 -2
- package/dist/bridge.d.ts +25 -0
- package/dist/bridge.js +103 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +67 -0
- package/dist/envelope.d.ts +57 -0
- package/dist/envelope.js +3 -0
- package/dist/harness.d.ts +32 -0
- package/dist/harness.js +144 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/manifest.d.ts +36 -0
- package/dist/manifest.js +116 -0
- package/dist/producer.d.ts +100 -0
- package/dist/producer.js +204 -0
- package/package.json +55 -4
- package/src/bridge.ts +115 -0
- package/src/cli.ts +71 -0
- package/src/envelope.ts +49 -0
- package/src/harness.ts +149 -0
- package/src/index.ts +4 -0
- package/src/manifest.ts +127 -0
- package/src/producer.ts +269 -0
- package/txco-web.schema.json +44 -0
package/dist/manifest.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// The Web ABI manifest (txco-web.json): what a build is, never its routing.
|
|
2
|
+
// This validator mirrors txco-web.schema.json plus the rules a schema can't
|
|
3
|
+
// express, and is held to the same fixture corpus as the Go validator
|
|
4
|
+
// (chassis/webabi), so the two agree.
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
/** The manifest's file name at the root of an ABI directory. */
|
|
8
|
+
export const MANIFEST_NAME = "txco-web.json";
|
|
9
|
+
/** The manifest's abi value this kit reads. */
|
|
10
|
+
export const ABI_VERSION = 1;
|
|
11
|
+
/** Producers' ops live in the band starting here, after every author op. */
|
|
12
|
+
export const PRODUCER_SCOPE = 900000;
|
|
13
|
+
const ENTRY_RE = /^server\/[^/\\][^\\]*\.m?js$/;
|
|
14
|
+
const PREFIX_RE = /^[^/\\][^\\]*\/$/;
|
|
15
|
+
function cleanPath(p) {
|
|
16
|
+
if (p === "" || p.startsWith("/") || p.endsWith("/"))
|
|
17
|
+
return false;
|
|
18
|
+
return p.split("/").every((seg) => seg !== "" && !seg.startsWith("."));
|
|
19
|
+
}
|
|
20
|
+
/** Validates a parsed manifest. */
|
|
21
|
+
export function validateManifest(doc) {
|
|
22
|
+
const errors = [];
|
|
23
|
+
if (typeof doc !== "object" || doc === null || Array.isArray(doc)) {
|
|
24
|
+
return { ok: false, errors: [{ pointer: "", message: "the manifest must be a JSON object" }] };
|
|
25
|
+
}
|
|
26
|
+
const m = doc;
|
|
27
|
+
for (const key of Object.keys(m)) {
|
|
28
|
+
if (!["$schema", "abi", "server", "immutable"].includes(key) && !key.startsWith("x-")) {
|
|
29
|
+
errors.push({ pointer: "", message: `unknown property "${key}" (a manifest describes the build, never its routing; extensions start with x-)` });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (!("abi" in m)) {
|
|
33
|
+
errors.push({ pointer: "", message: 'missing required property "abi"' });
|
|
34
|
+
}
|
|
35
|
+
else if (m.abi !== ABI_VERSION) {
|
|
36
|
+
errors.push({ pointer: "/abi", message: `abi must be ${ABI_VERSION}` });
|
|
37
|
+
}
|
|
38
|
+
if ("$schema" in m && typeof m.$schema !== "string") {
|
|
39
|
+
errors.push({ pointer: "/$schema", message: "must be a string" });
|
|
40
|
+
}
|
|
41
|
+
if ("server" in m) {
|
|
42
|
+
const s = m.server;
|
|
43
|
+
if (typeof s !== "object" || s === null || Array.isArray(s)) {
|
|
44
|
+
errors.push({ pointer: "/server", message: "must be an object" });
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
const so = s;
|
|
48
|
+
for (const key of Object.keys(so)) {
|
|
49
|
+
if (key !== "entry")
|
|
50
|
+
errors.push({ pointer: "/server", message: `unknown property "${key}"` });
|
|
51
|
+
}
|
|
52
|
+
if (typeof so.entry !== "string") {
|
|
53
|
+
errors.push({ pointer: "/server", message: 'missing required property "entry"' });
|
|
54
|
+
}
|
|
55
|
+
else if (!ENTRY_RE.test(so.entry) || so.entry.length > 512) {
|
|
56
|
+
errors.push({ pointer: "/server/entry", message: "must be a .js or .mjs module under server/" });
|
|
57
|
+
}
|
|
58
|
+
else if (!cleanPath(so.entry)) {
|
|
59
|
+
errors.push({ pointer: "/server/entry", message: "the entry must be a clean path under server/" });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if ("immutable" in m) {
|
|
64
|
+
const im = m.immutable;
|
|
65
|
+
if (!Array.isArray(im)) {
|
|
66
|
+
errors.push({ pointer: "/immutable", message: "must be an array of prefixes" });
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
if (new Set(im).size !== im.length) {
|
|
70
|
+
errors.push({ pointer: "/immutable", message: "items must be unique" });
|
|
71
|
+
}
|
|
72
|
+
im.forEach((p, i) => {
|
|
73
|
+
const ptr = `/immutable/${i}`;
|
|
74
|
+
if (typeof p !== "string" || p.length < 2 || p.length > 512 || !PREFIX_RE.test(p)) {
|
|
75
|
+
errors.push({ pointer: ptr, message: "a prefix is a relative path ending in '/'" });
|
|
76
|
+
}
|
|
77
|
+
else if (!cleanPath(p.replace(/\/$/, ""))) {
|
|
78
|
+
errors.push({ pointer: ptr, message: "a prefix must be a clean path, with no '.' or '..' segment" });
|
|
79
|
+
}
|
|
80
|
+
else if (p.split("/")[0] === "_txco") {
|
|
81
|
+
errors.push({ pointer: ptr, message: "_txco/ is reserved for the installer" });
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return errors.length > 0 ? { ok: false, errors } : { ok: true, manifest: m };
|
|
87
|
+
}
|
|
88
|
+
/** Reads and validates <dir>/txco-web.json. Throws on an unreadable or invalid manifest. */
|
|
89
|
+
export async function readManifest(dir) {
|
|
90
|
+
const raw = await readFile(join(dir, MANIFEST_NAME), "utf8");
|
|
91
|
+
let doc;
|
|
92
|
+
try {
|
|
93
|
+
doc = JSON.parse(raw);
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
throw new Error(`${MANIFEST_NAME}: not valid JSON: ${e.message}`);
|
|
97
|
+
}
|
|
98
|
+
const r = validateManifest(doc);
|
|
99
|
+
if (!r.ok) {
|
|
100
|
+
throw new Error(`${MANIFEST_NAME}: ` + r.errors.map((p) => `${p.pointer || "/"}: ${p.message}`).join("; "));
|
|
101
|
+
}
|
|
102
|
+
return r.manifest;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The private root of a public/ path: cut at the end of its first "_"
|
|
106
|
+
* segment ("" when it has none). The installer writes one public marker per
|
|
107
|
+
* root, so `_app/x.js` → `_app`, `assets/_Dk3.js` → itself.
|
|
108
|
+
*/
|
|
109
|
+
export function publicRoot(rel) {
|
|
110
|
+
const segs = rel.split("/");
|
|
111
|
+
for (let i = 0; i < segs.length; i++) {
|
|
112
|
+
if (segs[i].startsWith("_"))
|
|
113
|
+
return segs.slice(0, i + 1).join("/");
|
|
114
|
+
}
|
|
115
|
+
return "";
|
|
116
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Where the catch-all sits: after the navigation op, since ops in one scope run concurrently. */
|
|
2
|
+
export declare const catchAllScope: (scope: number) => number;
|
|
3
|
+
/**
|
|
4
|
+
* A navigation: an HTTP GET or HEAD of a path whose last segment has no
|
|
5
|
+
* extension. Everything else (an asset miss, a POST) is the catch-all's.
|
|
6
|
+
*/
|
|
7
|
+
export declare const NAV_GUARD: string;
|
|
8
|
+
/** The page a 404 op serves when the build has no 404.html. */
|
|
9
|
+
export declare const BUILTIN_404: string;
|
|
10
|
+
/** An HTML page from public/, embedded in an op. */
|
|
11
|
+
export interface Page {
|
|
12
|
+
/** Its file name in public/, for the comments. */
|
|
13
|
+
name: string;
|
|
14
|
+
html: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* How a page navigation nothing else answered is handled:
|
|
18
|
+
*
|
|
19
|
+
* - "spa": the app routes in the browser: 200, with the app shell;
|
|
20
|
+
* - "routes": the same, but only for a path the framework's route table
|
|
21
|
+
* knows (`routes`); any other navigation gets the shell with 404;
|
|
22
|
+
* - "404": every page is a file in public/, so a path that reached the ops
|
|
23
|
+
* has no page: 404, with the 404 page;
|
|
24
|
+
* - "none": no navigation op, only the catch-all.
|
|
25
|
+
*/
|
|
26
|
+
export type NavMode = "spa" | "routes" | "404" | "none";
|
|
27
|
+
export interface RenderOptions {
|
|
28
|
+
mode: NavMode;
|
|
29
|
+
/** The navigation op's scope; the catch-all goes 900 above it. Default 900000. */
|
|
30
|
+
scope?: number;
|
|
31
|
+
/** The generated-file header's producer name. */
|
|
32
|
+
producer: string;
|
|
33
|
+
/**
|
|
34
|
+
* The shell ("spa" and "routes": required), the 404 page ("404": null
|
|
35
|
+
* writes a built-in one), or null ("none").
|
|
36
|
+
*/
|
|
37
|
+
page: Page | null;
|
|
38
|
+
/**
|
|
39
|
+
* For "routes": an RE2 regex source, anchored, matching exactly the app's
|
|
40
|
+
* page paths, with "/" escaped for txcl's /…/ literal.
|
|
41
|
+
*/
|
|
42
|
+
routes?: string;
|
|
43
|
+
/** The producer's own comment lines, added to the navigation op's header. */
|
|
44
|
+
notes?: readonly string[];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Renders the build's ops, as path (relative to ops/) → file text: one
|
|
48
|
+
* navigation op for the mode, and the catch-all, a plain 404 for every other
|
|
49
|
+
* HTTP request, so every request reaching the end of the stack is answered.
|
|
50
|
+
*/
|
|
51
|
+
export declare function renderOps(o: RenderOptions): Record<string, string>;
|
|
52
|
+
/** The EMIT tail for a page answer: the page as a readable b64"…" literal, and halt. */
|
|
53
|
+
export declare function emitPage(status: number, html: string): string;
|
|
54
|
+
/** What may already be in an output dir: a previous build, and nothing else. */
|
|
55
|
+
export declare const ABI_ENTRIES: ReadonlySet<string>;
|
|
56
|
+
export interface OutDirCheck {
|
|
57
|
+
/** The output dir the build is about to wipe and rewrite. */
|
|
58
|
+
dir: string;
|
|
59
|
+
/** Paths the wipe must not reach: the project root, the sources, another build's output. */
|
|
60
|
+
protect?: readonly string[];
|
|
61
|
+
/** Paths the output dir must not sit inside (a bundler's own outDir, which it empties). */
|
|
62
|
+
notInside?: readonly string[];
|
|
63
|
+
/** The dir's current entries, or null when it doesn't exist. */
|
|
64
|
+
entries: readonly string[] | null;
|
|
65
|
+
/** Entries a producer's own previous build leaves, besides ABI_ENTRIES. */
|
|
66
|
+
allow?: readonly string[];
|
|
67
|
+
}
|
|
68
|
+
/** Every reason a build mustn't wipe and rewrite the output dir. Empty when it may. */
|
|
69
|
+
export declare function checkOutDir(c: OutDirCheck): string[];
|
|
70
|
+
/** Replaces <out>/ops/ with the given ops (path relative to ops/ → text). */
|
|
71
|
+
export declare function writeOps(out: string, ops: Record<string, string>): Promise<void>;
|
|
72
|
+
/** Validates the manifest, then writes <out>/txco-web.json. Throws on an invalid one. */
|
|
73
|
+
export declare function writeManifest(out: string, manifest: Record<string, unknown>): Promise<void>;
|
|
74
|
+
/** Every file under root, as "/"-separated paths relative to it, sorted. */
|
|
75
|
+
export declare function listFiles(root: string): Promise<string[]>;
|
|
76
|
+
/**
|
|
77
|
+
* Whether a file name carries a content hash: Vite's `main-BxYz12Ab.js`,
|
|
78
|
+
* Nuxt's `entry.CdEf34Gh.css`. A heuristic, for warnings only.
|
|
79
|
+
*/
|
|
80
|
+
export declare function looksHashed(name: string): boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Where a build lands under public/, from its base path: "/app/" serves the
|
|
83
|
+
* site under /app/, so its files go under public/app/. A relative or root
|
|
84
|
+
* base serves it at the root. A full URL (a CDN) loads the assets from
|
|
85
|
+
* elsewhere: the files still go to the root, and the producer should warn.
|
|
86
|
+
*/
|
|
87
|
+
export declare function publicPrefix(base: string): {
|
|
88
|
+
prefix: string;
|
|
89
|
+
external: boolean;
|
|
90
|
+
};
|
|
91
|
+
/** Whether a "/"-separated relative path is one a Web ABI build never deploys: a dot segment. */
|
|
92
|
+
export declare function isDotPath(rel: string): boolean;
|
|
93
|
+
/**
|
|
94
|
+
* Copies a framework's static output dir into <out>/public/<prefix>,
|
|
95
|
+
* leaving out every dot path (they never deploy). Returns the ones it left
|
|
96
|
+
* out, other than .vite/ (build metadata), for the producer to warn about.
|
|
97
|
+
*/
|
|
98
|
+
export declare function copyPublic(from: string, out: string, prefix?: string): Promise<{
|
|
99
|
+
skipped: string[];
|
|
100
|
+
}>;
|
package/dist/producer.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// What every Web ABI producer writes beside public/: the ops that answer a
|
|
2
|
+
// request no file did, the manifest, and the guard that runs before a build
|
|
3
|
+
// overwrites its output dir. The producers (a framework adapter, a Nitro
|
|
4
|
+
// preset, a Vite plugin) share it, so their ops stay the same rules
|
|
5
|
+
// (chassis/webabi checks that they agree).
|
|
6
|
+
import { cp, mkdir, readdir, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
|
+
import { MANIFEST_NAME, PRODUCER_SCOPE, validateManifest } from "./manifest.js";
|
|
9
|
+
/** Where the catch-all sits: after the navigation op, since ops in one scope run concurrently. */
|
|
10
|
+
export const catchAllScope = (scope) => scope + 900;
|
|
11
|
+
/**
|
|
12
|
+
* A navigation: an HTTP GET or HEAD of a path whose last segment has no
|
|
13
|
+
* extension. Everything else (an asset miss, a POST) is the catch-all's.
|
|
14
|
+
*/
|
|
15
|
+
export const NAV_GUARD = '@src == "http" && (@web.req.method == "GET" || @web.req.method == "HEAD")\n' +
|
|
16
|
+
" && @web.req.url.path !~ /(?i)\\.[a-z0-9]+$/";
|
|
17
|
+
/** The page a 404 op serves when the build has no 404.html. */
|
|
18
|
+
export const BUILTIN_404 = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><title>404 Not Found</title></head>' +
|
|
19
|
+
"<body><h1>404 Not Found</h1></body></html>\n";
|
|
20
|
+
/**
|
|
21
|
+
* Renders the build's ops, as path (relative to ops/) → file text: one
|
|
22
|
+
* navigation op for the mode, and the catch-all, a plain 404 for every other
|
|
23
|
+
* HTTP request, so every request reaching the end of the stack is answered.
|
|
24
|
+
*/
|
|
25
|
+
export function renderOps(o) {
|
|
26
|
+
const scope = o.scope ?? PRODUCER_SCOPE;
|
|
27
|
+
const notes = (o.notes ?? []).map((l) => (l ? `# ${l}` : "#")).join("\n");
|
|
28
|
+
const extra = notes ? `${notes}\n` : "";
|
|
29
|
+
const out = {};
|
|
30
|
+
if (o.mode === "routes") {
|
|
31
|
+
if (o.page === null)
|
|
32
|
+
throw new Error("renderOps: a routes build needs its shell");
|
|
33
|
+
if (!o.routes)
|
|
34
|
+
throw new Error("renderOps: a routes build needs its route matcher");
|
|
35
|
+
out[`${scope}/spa-fallback.txcl`] = `# ${o.producer} — SPA fallback: known routes (generated; do not edit by hand).
|
|
36
|
+
#
|
|
37
|
+
# Serves the app shell (${o.page.name}) with 200 for a navigation to a known
|
|
38
|
+
# page route that no file or earlier op answered. Paired with spa-404.txcl.
|
|
39
|
+
${extra}# Regenerated on every build — the shell embeds content-hashed asset URLs.
|
|
40
|
+
WHEN ${NAV_GUARD}
|
|
41
|
+
&& @web.req.url.path =~ /${o.routes}/
|
|
42
|
+
${emitPage(200, o.page.html)}`;
|
|
43
|
+
out[`${scope}/spa-404.txcl`] = `# ${o.producer} — SPA 404 (generated; do not edit by hand).
|
|
44
|
+
#
|
|
45
|
+
# A navigation matching no known page route is a real miss: 404, with the
|
|
46
|
+
# shell as the body so the client renders its error page.
|
|
47
|
+
WHEN ${NAV_GUARD}
|
|
48
|
+
&& @web.req.url.path !~ /${o.routes}/
|
|
49
|
+
${emitPage(404, o.page.html)}`;
|
|
50
|
+
}
|
|
51
|
+
else if (o.mode === "spa") {
|
|
52
|
+
if (o.page === null)
|
|
53
|
+
throw new Error("renderOps: an spa build needs its shell");
|
|
54
|
+
out[`${scope}/spa-fallback.txcl`] = `# ${o.producer} — SPA fallback (generated; do not edit by hand).
|
|
55
|
+
#
|
|
56
|
+
# Serves the app shell (${o.page.name}) with 200 for any page navigation
|
|
57
|
+
# nothing else answered: the app routes in the browser, so unknown pages get
|
|
58
|
+
# 200 too and the client renders its not-found view.
|
|
59
|
+
${extra}# Regenerated on every build — the shell embeds content-hashed asset URLs.
|
|
60
|
+
WHEN ${NAV_GUARD}
|
|
61
|
+
${emitPage(200, o.page.html)}`;
|
|
62
|
+
}
|
|
63
|
+
else if (o.mode === "404") {
|
|
64
|
+
const what = o.page
|
|
65
|
+
? `Serves ${o.page.name} with 404`
|
|
66
|
+
: "Serves a plain 404 page (the build has no 404.html)";
|
|
67
|
+
out[`${scope}/page-404.txcl`] = `# ${o.producer} — 404 page (generated; do not edit by hand).
|
|
68
|
+
#
|
|
69
|
+
# ${what} for any page navigation nothing else answered:
|
|
70
|
+
# no file in public/ and no op of the stack had a page for it.
|
|
71
|
+
${extra}# Regenerated on every build — the page embeds content-hashed asset URLs.
|
|
72
|
+
WHEN ${NAV_GUARD}
|
|
73
|
+
${emitPage(404, o.page ? o.page.html : BUILTIN_404)}`;
|
|
74
|
+
}
|
|
75
|
+
out[`${catchAllScope(scope)}/not-found.txcl`] = `# ${o.producer} — not found (generated; do not edit by hand).
|
|
76
|
+
#
|
|
77
|
+
# Every other HTTP request that reached the end of the stack: an asset that
|
|
78
|
+
# doesn't exist, a method nothing handles. Without it the request would get
|
|
79
|
+
# the envelope back as JSON. It sits after the navigation ops on purpose: ops
|
|
80
|
+
# in one scope run concurrently.
|
|
81
|
+
WHEN @src == "http"
|
|
82
|
+
EMIT @web.res.status = 404,
|
|
83
|
+
@web.res.headers.content-type.0 = "text/plain; charset=utf-8",
|
|
84
|
+
@web.res.body = b64"404 not found\\n",
|
|
85
|
+
@halt = true
|
|
86
|
+
`;
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
/** The EMIT tail for a page answer: the page as a readable b64"…" literal, and halt. */
|
|
90
|
+
export function emitPage(status, html) {
|
|
91
|
+
// The lexer base64-encodes a b64"…" literal at parse time, so the file stays
|
|
92
|
+
// readable HTML. Only backslash and double-quote need escaping.
|
|
93
|
+
const escaped = html.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
94
|
+
return ` EMIT @web.res.status = ${status},
|
|
95
|
+
@web.res.headers.content-type.0 = "text/html; charset=utf-8",
|
|
96
|
+
@web.res.headers.cache-control.0 = "no-cache",
|
|
97
|
+
@web.res.body = b64"${escaped}",
|
|
98
|
+
@halt = true
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
/** What may already be in an output dir: a previous build, and nothing else. */
|
|
102
|
+
export const ABI_ENTRIES = new Set([MANIFEST_NAME, "public", "server", "ops", ".gitignore", ".DS_Store"]);
|
|
103
|
+
const within = (child, parent) => {
|
|
104
|
+
const rel = relative(parent, child);
|
|
105
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
106
|
+
};
|
|
107
|
+
/** Every reason a build mustn't wipe and rewrite the output dir. Empty when it may. */
|
|
108
|
+
export function checkOutDir(c) {
|
|
109
|
+
const dir = resolve(c.dir);
|
|
110
|
+
const problems = [];
|
|
111
|
+
if (dir.split(sep).includes("OPS")) {
|
|
112
|
+
problems.push(`the output dir ${dir} is inside OPS/. A Web ABI build lives outside the stack tree; txco.yaml binds it to a stack (stacks: <name>: abi: <dir>).`);
|
|
113
|
+
}
|
|
114
|
+
for (const p of c.protect ?? []) {
|
|
115
|
+
if (p && within(resolve(p), dir)) {
|
|
116
|
+
problems.push(`the output dir ${dir} holds ${resolve(p)}, and the build wipes the output dir. Point it at a directory of its own.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
for (const p of c.notInside ?? []) {
|
|
120
|
+
if (p && within(dir, resolve(p))) {
|
|
121
|
+
problems.push(`the output dir ${dir} is inside ${resolve(p)}, another build's output. Point it at a directory of its own.`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const allowed = new Set([...ABI_ENTRIES, ...(c.allow ?? [])]);
|
|
125
|
+
const foreign = (c.entries ?? []).filter((e) => !allowed.has(e));
|
|
126
|
+
if (foreign.length > 0) {
|
|
127
|
+
problems.push(`the output dir ${dir} holds ${foreign.map((e) => `"${e}"`).join(", ")}, which isn't part of a Web ABI build, and the build wipes it. Point the output somewhere else, or empty it.`);
|
|
128
|
+
}
|
|
129
|
+
return problems;
|
|
130
|
+
}
|
|
131
|
+
/** Replaces <out>/ops/ with the given ops (path relative to ops/ → text). */
|
|
132
|
+
export async function writeOps(out, ops) {
|
|
133
|
+
await rm(join(out, "ops"), { recursive: true, force: true });
|
|
134
|
+
for (const [rel, text] of Object.entries(ops)) {
|
|
135
|
+
const file = join(out, "ops", rel);
|
|
136
|
+
await mkdir(dirname(file), { recursive: true });
|
|
137
|
+
await writeFile(file, text);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** Validates the manifest, then writes <out>/txco-web.json. Throws on an invalid one. */
|
|
141
|
+
export async function writeManifest(out, manifest) {
|
|
142
|
+
const r = validateManifest(manifest);
|
|
143
|
+
if (!r.ok) {
|
|
144
|
+
throw new Error(`${MANIFEST_NAME}: ` + r.errors.map((p) => `${p.pointer || "/"}: ${p.message}`).join("; "));
|
|
145
|
+
}
|
|
146
|
+
await mkdir(out, { recursive: true });
|
|
147
|
+
await writeFile(join(out, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
|
|
148
|
+
}
|
|
149
|
+
/** Every file under root, as "/"-separated paths relative to it, sorted. */
|
|
150
|
+
export async function listFiles(root) {
|
|
151
|
+
const out = [];
|
|
152
|
+
for (const e of await readdir(root, { recursive: true, withFileTypes: true })) {
|
|
153
|
+
// parentPath is Node ≥ 20.12; earlier 20.x calls it path.
|
|
154
|
+
const parent = e.parentPath ?? e.path ?? root;
|
|
155
|
+
if (e.isFile())
|
|
156
|
+
out.push(relative(root, join(parent, e.name)).split(sep).join("/"));
|
|
157
|
+
}
|
|
158
|
+
return out.sort();
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Whether a file name carries a content hash: Vite's `main-BxYz12Ab.js`,
|
|
162
|
+
* Nuxt's `entry.CdEf34Gh.css`. A heuristic, for warnings only.
|
|
163
|
+
*/
|
|
164
|
+
export function looksHashed(name) {
|
|
165
|
+
const stem = name.replace(/\.[^.]+$/, "");
|
|
166
|
+
const run = stem.match(/[A-Za-z0-9_-]{8,}/);
|
|
167
|
+
return run !== null && /[0-9A-Z]/.test(run[0]);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Where a build lands under public/, from its base path: "/app/" serves the
|
|
171
|
+
* site under /app/, so its files go under public/app/. A relative or root
|
|
172
|
+
* base serves it at the root. A full URL (a CDN) loads the assets from
|
|
173
|
+
* elsewhere: the files still go to the root, and the producer should warn.
|
|
174
|
+
*/
|
|
175
|
+
export function publicPrefix(base) {
|
|
176
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(base) || base.startsWith("//"))
|
|
177
|
+
return { prefix: "", external: true };
|
|
178
|
+
const path = base.replace(/^\.?\/+|\/+$/g, "");
|
|
179
|
+
return { prefix: path && path !== "." ? `${path}/` : "", external: false };
|
|
180
|
+
}
|
|
181
|
+
/** Whether a "/"-separated relative path is one a Web ABI build never deploys: a dot segment. */
|
|
182
|
+
export function isDotPath(rel) {
|
|
183
|
+
return rel.split("/").some((s) => s.startsWith("."));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Copies a framework's static output dir into <out>/public/<prefix>,
|
|
187
|
+
* leaving out every dot path (they never deploy). Returns the ones it left
|
|
188
|
+
* out, other than .vite/ (build metadata), for the producer to warn about.
|
|
189
|
+
*/
|
|
190
|
+
export async function copyPublic(from, out, prefix = "") {
|
|
191
|
+
const skipped = [];
|
|
192
|
+
await cp(from, join(out, "public", prefix), {
|
|
193
|
+
recursive: true,
|
|
194
|
+
filter: (src) => {
|
|
195
|
+
const rel = relative(from, src).split(sep).join("/");
|
|
196
|
+
if (rel === "" || !isDotPath(rel))
|
|
197
|
+
return true;
|
|
198
|
+
if (rel !== ".vite" && !rel.startsWith(".vite/"))
|
|
199
|
+
skipped.push(rel);
|
|
200
|
+
return false;
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
return { skipped };
|
|
204
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@txco/web-abi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The TxCo Web ABI kit: the txco-web.json schema and validator, the envelope ↔ Fetch bridge every runner uses, a harness that checks a build's server/ Fetch handler, and the ops and manifest writer producers share.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"keywords": ["txco", "thanks-computer", "web-abi", "fetch", "conformance"],
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/LoremLabs/thanks-computer.git",
|
|
12
|
+
"directory": "sdk/web-abi"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"files": ["dist", "src", "txco-web.schema.json", "README.md"],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./manifest": {
|
|
24
|
+
"types": "./dist/manifest.d.ts",
|
|
25
|
+
"default": "./dist/manifest.js"
|
|
26
|
+
},
|
|
27
|
+
"./bridge": {
|
|
28
|
+
"types": "./dist/bridge.d.ts",
|
|
29
|
+
"default": "./dist/bridge.js"
|
|
30
|
+
},
|
|
31
|
+
"./harness": {
|
|
32
|
+
"types": "./dist/harness.d.ts",
|
|
33
|
+
"default": "./dist/harness.js"
|
|
34
|
+
},
|
|
35
|
+
"./producer": {
|
|
36
|
+
"types": "./dist/producer.d.ts",
|
|
37
|
+
"default": "./dist/producer.js"
|
|
38
|
+
},
|
|
39
|
+
"./schema.json": "./txco-web.schema.json"
|
|
40
|
+
},
|
|
41
|
+
"bin": {
|
|
42
|
+
"txco-web-abi": "./dist/cli.js"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"clean": "rm -rf dist",
|
|
46
|
+
"build": "tsc -p tsconfig.json",
|
|
47
|
+
"test": "npm run build && node --test test/*.test.mjs",
|
|
48
|
+
"prepublishOnly": "npm run clean && npm run build"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "^20.0.0",
|
|
52
|
+
"typescript": "^5.4.0"
|
|
53
|
+
},
|
|
54
|
+
"publishConfig": {
|
|
55
|
+
"access": "public"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// The envelope ↔ Fetch bridge. A runner hands it the chassis's request
|
|
2
|
+
// envelope; it builds a Fetch Request, calls the server entry, and turns the
|
|
3
|
+
// Response into the delta the chassis merges. Every runner uses this one
|
|
4
|
+
// mapping, so a handler sees the same Request wherever it runs.
|
|
5
|
+
|
|
6
|
+
import type { FetchHandler, TxcContext, TxcDelta, TxcEnvelope } from "./envelope.js";
|
|
7
|
+
|
|
8
|
+
/** An op answer is capped at 4 MiB (--op-payload-max); the body is base64 inside it. */
|
|
9
|
+
export const DEFAULT_MAX_ANSWER_BYTES = 3 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
// Hop-by-hop headers (RFC 9110 §7.6.1) and those the Request computes.
|
|
12
|
+
const DROPPED_HEADERS = new Set([
|
|
13
|
+
"connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer",
|
|
14
|
+
"upgrade", "content-length", "host",
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
export interface RequestOptions {
|
|
18
|
+
/** Refuse a request body larger than this (bytes). Default: no limit. */
|
|
19
|
+
maxBodyBytes?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Builds the Fetch Request an envelope describes. */
|
|
23
|
+
export function envelopeToRequest(env: TxcEnvelope, opts: RequestOptions = {}): Request {
|
|
24
|
+
const req = env._txc?.web?.req ?? {};
|
|
25
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
26
|
+
let url = req.url?.full;
|
|
27
|
+
if (!url) {
|
|
28
|
+
const host = req.host ?? "localhost";
|
|
29
|
+
const raw = req.url?.query?.raw;
|
|
30
|
+
url = `http://${host}${req.url?.path ?? "/"}${raw ? "?" + raw : ""}`;
|
|
31
|
+
}
|
|
32
|
+
const headers = new Headers();
|
|
33
|
+
for (const [name, value] of Object.entries(req.headers ?? {})) {
|
|
34
|
+
if (DROPPED_HEADERS.has(name.toLowerCase())) continue;
|
|
35
|
+
for (const v of Array.isArray(value) ? value : [value]) headers.append(name, v);
|
|
36
|
+
}
|
|
37
|
+
let body: ArrayBuffer | undefined;
|
|
38
|
+
if (req.body && method !== "GET" && method !== "HEAD") {
|
|
39
|
+
const bytes = Buffer.from(req.body, "base64");
|
|
40
|
+
if (opts.maxBodyBytes !== undefined && bytes.byteLength > opts.maxBodyBytes) {
|
|
41
|
+
throw new Error(`request body is ${bytes.byteLength} bytes, over ${opts.maxBodyBytes}`);
|
|
42
|
+
}
|
|
43
|
+
body = new ArrayBuffer(bytes.byteLength);
|
|
44
|
+
new Uint8Array(body).set(bytes);
|
|
45
|
+
}
|
|
46
|
+
return new Request(url, { method, headers, body });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The handler's context: only what the contract defines. */
|
|
50
|
+
export function contextFrom(env: TxcEnvelope): TxcContext {
|
|
51
|
+
return Object.freeze({ client: Object.freeze({ ip: env._txc?.client?.ip ?? "" }) });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface DeltaOptions {
|
|
55
|
+
/** The request's method: a HEAD answer carries no body. */
|
|
56
|
+
method?: string;
|
|
57
|
+
/** Refuse a body larger than this (bytes). */
|
|
58
|
+
maxAnswerBytes?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Turns a Response into the chassis delta. */
|
|
62
|
+
export async function responseToDelta(res: Response, opts: DeltaOptions = {}): Promise<TxcDelta> {
|
|
63
|
+
const headers: Record<string, string[]> = {};
|
|
64
|
+
res.headers.forEach((value, name) => {
|
|
65
|
+
if (name === "set-cookie") return; // each cookie on its own line, below
|
|
66
|
+
(headers[name] ??= []).push(value);
|
|
67
|
+
});
|
|
68
|
+
const cookies = res.headers.getSetCookie();
|
|
69
|
+
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
70
|
+
|
|
71
|
+
const delta: TxcDelta = { _txc: { web: { res: { status: res.status, headers } }, halt: true } };
|
|
72
|
+
const noBody = (opts.method ?? "GET").toUpperCase() === "HEAD" || res.status === 204 || res.status === 304;
|
|
73
|
+
if (!noBody) {
|
|
74
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
75
|
+
const max = opts.maxAnswerBytes ?? DEFAULT_MAX_ANSWER_BYTES;
|
|
76
|
+
if (bytes.byteLength > max) {
|
|
77
|
+
throw new Error(`response body is ${bytes.byteLength} bytes, over the ${max}-byte answer limit`);
|
|
78
|
+
}
|
|
79
|
+
if (bytes.byteLength > 0) delta._txc.web.res.body = bytes.toString("base64");
|
|
80
|
+
}
|
|
81
|
+
return delta;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function errorDelta(status: number, message: string, method: string): TxcDelta {
|
|
85
|
+
const res: TxcDelta["_txc"]["web"]["res"] = { status, headers: { "content-type": ["text/plain; charset=utf-8"] } };
|
|
86
|
+
if (method.toUpperCase() !== "HEAD") res.body = Buffer.from(message + "\n").toString("base64");
|
|
87
|
+
return { _txc: { web: { res }, halt: true } };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Runs one request through a handler, end to end. A handler that throws, or
|
|
92
|
+
* returns something other than a Response, answers 500; the error is never
|
|
93
|
+
* shown to the client.
|
|
94
|
+
*/
|
|
95
|
+
export async function dispatch(handler: FetchHandler, env: TxcEnvelope, opts: RequestOptions & DeltaOptions = {}): Promise<TxcDelta> {
|
|
96
|
+
const method = env._txc?.web?.req?.method ?? "GET";
|
|
97
|
+
let request: Request;
|
|
98
|
+
try {
|
|
99
|
+
request = envelopeToRequest(env, opts);
|
|
100
|
+
} catch {
|
|
101
|
+
return errorDelta(413, "request body too large", method);
|
|
102
|
+
}
|
|
103
|
+
let res: unknown;
|
|
104
|
+
try {
|
|
105
|
+
res = await handler.fetch(request, contextFrom(env));
|
|
106
|
+
} catch {
|
|
107
|
+
return errorDelta(500, "internal error", method);
|
|
108
|
+
}
|
|
109
|
+
if (!(res instanceof Response)) return errorDelta(500, "internal error", method);
|
|
110
|
+
try {
|
|
111
|
+
return await responseToDelta(res, { ...opts, method: request.method });
|
|
112
|
+
} catch {
|
|
113
|
+
return errorDelta(502, "response too large", method);
|
|
114
|
+
}
|
|
115
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// txco-web-abi: validate a manifest, check a build's server/, or serve a
|
|
3
|
+
// build locally.
|
|
4
|
+
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
import { checkServer, serve } from "./harness.js";
|
|
9
|
+
import { MANIFEST_NAME, validateManifest } from "./manifest.js";
|
|
10
|
+
|
|
11
|
+
const USAGE = `Usage: txco-web-abi <command> <abi-dir>
|
|
12
|
+
|
|
13
|
+
Commands:
|
|
14
|
+
validate <abi-dir> check txco-web.json against the Web ABI schema
|
|
15
|
+
check-server <abi-dir> [--json] drive the build's server/ entry through the bridge
|
|
16
|
+
serve <abi-dir> [--port N] serve public/ and server/ locally
|
|
17
|
+
`;
|
|
18
|
+
|
|
19
|
+
async function main(argv: string[]): Promise<number> {
|
|
20
|
+
const [cmd, dir, ...rest] = argv;
|
|
21
|
+
if (!cmd || !dir) {
|
|
22
|
+
process.stderr.write(USAGE);
|
|
23
|
+
return 2;
|
|
24
|
+
}
|
|
25
|
+
switch (cmd) {
|
|
26
|
+
case "validate": {
|
|
27
|
+
let doc: unknown;
|
|
28
|
+
try {
|
|
29
|
+
doc = JSON.parse(await readFile(join(dir, MANIFEST_NAME), "utf8"));
|
|
30
|
+
} catch (e) {
|
|
31
|
+
process.stderr.write(`${MANIFEST_NAME}: ${(e as Error).message}\n`);
|
|
32
|
+
return 1;
|
|
33
|
+
}
|
|
34
|
+
const r = validateManifest(doc);
|
|
35
|
+
if (r.ok) {
|
|
36
|
+
process.stdout.write(`${MANIFEST_NAME}: ok\n`);
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
for (const p of r.errors) process.stdout.write(`${p.pointer || "/"}: ${p.message}\n`);
|
|
40
|
+
return 1;
|
|
41
|
+
}
|
|
42
|
+
case "check-server": {
|
|
43
|
+
const results = await checkServer(dir);
|
|
44
|
+
if (rest.includes("--json")) {
|
|
45
|
+
process.stdout.write(JSON.stringify({ ok: results.every((r) => r.ok), results }, null, 2) + "\n");
|
|
46
|
+
} else {
|
|
47
|
+
for (const r of results) process.stdout.write(`${r.ok ? "✓" : "✗"} ${r.name}${r.detail ? " " + r.detail : ""}\n`);
|
|
48
|
+
}
|
|
49
|
+
return results.every((r) => r.ok) ? 0 : 1;
|
|
50
|
+
}
|
|
51
|
+
case "serve": {
|
|
52
|
+
const i = rest.indexOf("--port");
|
|
53
|
+
const port = i >= 0 ? Number(rest[i + 1]) : 8787;
|
|
54
|
+
const server = await serve(dir, { port });
|
|
55
|
+
const addr = server.address();
|
|
56
|
+
process.stdout.write(`serving ${dir} on http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : port}\n`);
|
|
57
|
+
return await new Promise<number>(() => {}); // until interrupted
|
|
58
|
+
}
|
|
59
|
+
default:
|
|
60
|
+
process.stderr.write(USAGE);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
main(process.argv.slice(2)).then(
|
|
66
|
+
(code) => process.exit(code),
|
|
67
|
+
(e) => {
|
|
68
|
+
process.stderr.write(`txco-web-abi: ${(e as Error).message}\n`);
|
|
69
|
+
process.exit(1);
|
|
70
|
+
},
|
|
71
|
+
);
|