@sproutboat/runtime 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/CHANGELOG.md +7 -0
- package/README.md +6 -0
- package/package.json +11 -0
- package/src/index.ts +10 -0
- package/src/native-fetch-prelude.js +950 -0
- package/src/source.ts +44 -0
- package/src/transport-broker.js +299 -0
- package/src/transport-embedded.js +1574 -0
- package/src/wrap.ts +267 -0
package/src/wrap.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The build-independent half of sprout compilation: the binding/trigger wrapper
|
|
3
|
+
* that turns a user's `export default { fetch }` into a native-fetch module, plus
|
|
4
|
+
* the `Bindings` shape and the `SPROUTBOAT_*_JSON` env readers.
|
|
5
|
+
*
|
|
6
|
+
* This module has no imports on purpose — the monorepo consumes it via the
|
|
7
|
+
* `sproutboat/runtime/wrap` export to drive its own (host-native, non-musl)
|
|
8
|
+
* compile path without pulling in `toolchain.ts` / `patch-porffor.ts`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The prelude file (Web API shims + broker binding shim + trigger dispatcher).
|
|
12
|
+
* It is read as text and string-prepended before Porffor sees it, never
|
|
13
|
+
* imported — callers do `readFile(preludePath, "utf8")`. */
|
|
14
|
+
export const preludePath = new URL("./native-fetch-prelude.js", import.meta.url);
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* #15 — the two transports the prelude can be built with.
|
|
18
|
+
*
|
|
19
|
+
* Both define `__sbCall(reqJson) -> replyJson` and nothing else; every binding
|
|
20
|
+
* shim above that line is identical, which is what lets one conformance suite
|
|
21
|
+
* hold both honest. `broker` talks to the per-deployment broker over loopback
|
|
22
|
+
* (deployed, dev, phase-0 standalone); `embedded` compiles SQLite into the
|
|
23
|
+
* sprout and needs no second process at all.
|
|
24
|
+
*/
|
|
25
|
+
export type Transport = "broker" | "embedded";
|
|
26
|
+
export const transportPath = (transport: Transport): URL =>
|
|
27
|
+
new URL(transport === "embedded" ? "./transport-embedded.js" : "./transport-broker.js", import.meta.url);
|
|
28
|
+
|
|
29
|
+
/** Where the prelude expects its transport spliced in. */
|
|
30
|
+
export const TRANSPORT_MARKER =
|
|
31
|
+
"// TRANSPORT: wrap.ts splices one of transport-broker.js / transport-embedded.js here.";
|
|
32
|
+
|
|
33
|
+
// The server honours $PORT at runtime (patches/porffor-render.patch); this baked
|
|
34
|
+
// value is only a fallback for a directly-run binary.
|
|
35
|
+
const DEFAULT_PORT = 8080;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What an artifact with no `compatibilityDate` means. Artifacts built before
|
|
39
|
+
* the field existed keep the semantics of that day forever, because the binary
|
|
40
|
+
* is immutable and `rollback` can reactivate it at any time.
|
|
41
|
+
*
|
|
42
|
+
* How to use it: when a runtime behaviour has to change in a way that would
|
|
43
|
+
* break a deployed handler, don't change it unconditionally — gate it in the
|
|
44
|
+
* prelude on `__sbCompat >= "YYYY-MM-DD"` (ISO dates compare correctly as
|
|
45
|
+
* strings) and document the flip date. Old binaries carry their old date and
|
|
46
|
+
* keep the old behaviour; a project opts in by moving `compatibility_date` in
|
|
47
|
+
* its `sproutboat.jsonc` and rebuilding.
|
|
48
|
+
*/
|
|
49
|
+
export const BASELINE_COMPATIBILITY_DATE = "2026-08-26";
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Binding names a project declares. `do` maps a binding name to a Durable Object
|
|
53
|
+
* class name; `crons` are schedule expressions with no name.
|
|
54
|
+
*/
|
|
55
|
+
export type Bindings = {
|
|
56
|
+
kv: string[];
|
|
57
|
+
secrets: string[];
|
|
58
|
+
outbound: string[];
|
|
59
|
+
d1: string[];
|
|
60
|
+
r2: string[];
|
|
61
|
+
queues: string[];
|
|
62
|
+
analytics: string[];
|
|
63
|
+
do: Array<{ binding: string; className: string }>;
|
|
64
|
+
/** #48 — worker-to-worker: binding name -> the project it calls. The hostname
|
|
65
|
+
* it resolves to is a runtime input, not part of the artifact. */
|
|
66
|
+
services: Array<{ binding: string; service: string }>;
|
|
67
|
+
crons: string[];
|
|
68
|
+
/** Static-asset binding name for `env.<NAME>.fetch(request)`; `""` when assets are edge-only. */
|
|
69
|
+
assets: string;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export const EMPTY_BINDINGS: Bindings = {
|
|
73
|
+
kv: [],
|
|
74
|
+
secrets: [],
|
|
75
|
+
outbound: [],
|
|
76
|
+
d1: [],
|
|
77
|
+
r2: [],
|
|
78
|
+
queues: [],
|
|
79
|
+
analytics: [],
|
|
80
|
+
do: [],
|
|
81
|
+
services: [],
|
|
82
|
+
crons: [],
|
|
83
|
+
assets: "",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
function hasBindings(b: Bindings): boolean {
|
|
87
|
+
return (
|
|
88
|
+
b.kv.length > 0 ||
|
|
89
|
+
b.secrets.length > 0 ||
|
|
90
|
+
b.outbound.length > 0 ||
|
|
91
|
+
b.d1.length > 0 ||
|
|
92
|
+
b.r2.length > 0 ||
|
|
93
|
+
b.queues.length > 0 ||
|
|
94
|
+
b.analytics.length > 0 ||
|
|
95
|
+
b.do.length > 0 ||
|
|
96
|
+
b.services.length > 0 ||
|
|
97
|
+
b.assets !== ""
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Turn the module's exports into plain top-level declarations, so the handler
|
|
103
|
+
* object is reachable as `__sbHandlers` and Durable Object classes stay
|
|
104
|
+
* addressable by name.
|
|
105
|
+
*
|
|
106
|
+
* Two shapes reach us. A hand-written file exports inline
|
|
107
|
+
* (`export default { fetch }`), while a bundled one declares everything first
|
|
108
|
+
* and re-exports at the end (`export { src_default as default, Counter }`) —
|
|
109
|
+
* #89 made the second shape the normal case. Returns null when neither matches.
|
|
110
|
+
*/
|
|
111
|
+
export function neutraliseExports(source: string): string | null {
|
|
112
|
+
if (/\bexport\s+default\s*\{/.test(source)) {
|
|
113
|
+
return source
|
|
114
|
+
.replace(/^(\s*)export\s+default\s*/m, "$1const __sbHandlers = ")
|
|
115
|
+
.replace(/^export\s+(async\s+function|function|class|const|let|var)\b/gm, "$1");
|
|
116
|
+
}
|
|
117
|
+
// Not anchored to a line: a minified bundle puts the whole module on one
|
|
118
|
+
// line. Bundlers emit exactly one such block, at the end.
|
|
119
|
+
const blocks = [...source.matchAll(/export\s*\{([^}]*)\}\s*;?/g)];
|
|
120
|
+
const block = blocks[blocks.length - 1];
|
|
121
|
+
if (block === undefined) return null;
|
|
122
|
+
let handler: string | null = null;
|
|
123
|
+
const aliases: string[] = [];
|
|
124
|
+
for (const entry of block[1]
|
|
125
|
+
.split(",")
|
|
126
|
+
.map((part) => part.trim())
|
|
127
|
+
.filter(Boolean)) {
|
|
128
|
+
const parts = entry.match(/^(\S+)(?:\s+as\s+(\S+))?$/);
|
|
129
|
+
if (parts === null) continue;
|
|
130
|
+
const local = parts[1];
|
|
131
|
+
const exported = parts[2] ?? local;
|
|
132
|
+
if (exported === "default") handler = local;
|
|
133
|
+
// `export { Counter as Counter }` needs no alias; a renamed one does, so
|
|
134
|
+
// `durable_objects` in the config can still name the class it expects.
|
|
135
|
+
else if (exported !== local) aliases.push(`const ${exported} = ${local};`);
|
|
136
|
+
}
|
|
137
|
+
if (handler === null) return null;
|
|
138
|
+
return source.replace(block[0], [`const __sbHandlers = ${handler};`, ...aliases].join("\n"));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Build the final native-fetch module: the prelude (Web API shims + the broker
|
|
143
|
+
* binding shim + the trigger dispatcher), then `const env = {…}` with the baked
|
|
144
|
+
* `vars`, then — if any binding is declared — one `__sbInstallBindings(env, …)`
|
|
145
|
+
* line, then the user's source with its `export` keywords neutralised (so its
|
|
146
|
+
* `export default {…}` becomes a plain object we can hand to the dispatcher),
|
|
147
|
+
* then our single `export default { fetch }` that routes every request through
|
|
148
|
+
* `__sbEntry` (HTTP → `handlers.fetch`; `x-sb-trigger` → scheduled / queue / DO).
|
|
149
|
+
*
|
|
150
|
+
* With no bindings and no `scheduled`/`queue`/DO the output behaves exactly like
|
|
151
|
+
* a plain `export default { fetch }` sprout.
|
|
152
|
+
*
|
|
153
|
+
* `port` is only the baked fallback in `export default { port }`; the runtime
|
|
154
|
+
* reads `$PORT` first. The monorepo's bench path overrides it.
|
|
155
|
+
*
|
|
156
|
+
* ponytail: the sprout process is long-lived, so a handler that mutates `env`
|
|
157
|
+
* leaks that change to later requests. Freeze upstream once Porffor supports
|
|
158
|
+
* Object.freeze in native mode.
|
|
159
|
+
*/
|
|
160
|
+
export function wrapNativeFetchHandler(
|
|
161
|
+
source: string,
|
|
162
|
+
prelude: string,
|
|
163
|
+
vars: Record<string, string> = {},
|
|
164
|
+
bindings: Bindings = EMPTY_BINDINGS,
|
|
165
|
+
port: number = DEFAULT_PORT,
|
|
166
|
+
compatibilityDate: string = BASELINE_COMPATIBILITY_DATE,
|
|
167
|
+
appName: string = "app",
|
|
168
|
+
/** #15 — assets baked into the module for a binary that has no files beside it. */
|
|
169
|
+
assets?: { manifest: unknown; files: Record<string, string> },
|
|
170
|
+
): string {
|
|
171
|
+
const neutralised = neutraliseExports(source);
|
|
172
|
+
if (neutralised === null || !/\bfetch\s*\(/.test(source)) {
|
|
173
|
+
throw new Error("handler must default-export an object with a fetch(request) method");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const env = `const env = ${JSON.stringify(vars)};\nglobalThis.env = env;\n`;
|
|
177
|
+
// Baked, not a binding: the date belongs to the artifact, and a handler must
|
|
178
|
+
// not be able to change the semantics it was compiled against at runtime.
|
|
179
|
+
const compat =
|
|
180
|
+
`globalThis.__sbCompat = ${JSON.stringify(compatibilityDate)};\n` +
|
|
181
|
+
// #15 — the embedded transport derives its default data directory from this.
|
|
182
|
+
`globalThis.__sbAppName = ${JSON.stringify(appName)};\n` +
|
|
183
|
+
// #15 — and enforces the outbound allowlist itself, with no broker to do it.
|
|
184
|
+
`globalThis.__sbOutbound = ${JSON.stringify(bindings.outbound)};\n` +
|
|
185
|
+
(assets ? `globalThis.__sbAssets = ${JSON.stringify(assets)};\n` : "");
|
|
186
|
+
const wire = hasBindings(bindings) ? `__sbInstallBindings(env, ${JSON.stringify(bindings)});\n` : "";
|
|
187
|
+
const registerDO = bindings.do.length
|
|
188
|
+
? `__sbRegisterDO({ ${bindings.do.map((d) => `${d.className}: ${d.className}`).join(", ")} });\n`
|
|
189
|
+
: "";
|
|
190
|
+
// Cron / queue / alarm timers, for a transport that has no broker to deliver
|
|
191
|
+
// them. The broker transport defines this as a no-op, so the emitted module
|
|
192
|
+
// is the same either way.
|
|
193
|
+
const triggers = hasBindings(bindings) ? `__sbStartLocalTriggers(__sbHandlers, ${JSON.stringify(bindings)});\n` : "";
|
|
194
|
+
|
|
195
|
+
return (
|
|
196
|
+
`${prelude}\n${compat}${env}${wire}` +
|
|
197
|
+
`${neutralised}\n` +
|
|
198
|
+
`${registerDO}${triggers}` +
|
|
199
|
+
`export default {\n port: ${port},\n fetch(request) { return __sbEntry(__sbHandlers, request); }\n};\n`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
type VarsJson = string | number | boolean | null | { readonly [key: string]: VarsJson } | VarsJson[];
|
|
204
|
+
function isVarsObject(value: VarsJson): value is { readonly [key: string]: VarsJson } {
|
|
205
|
+
return value !== null && Object(value) === value && !Array.isArray(value);
|
|
206
|
+
}
|
|
207
|
+
function isVarsString(value: VarsJson): value is string {
|
|
208
|
+
return Object(value) !== value && value === String(value);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** `SPROUTBOAT_VARS_JSON` (set by the build) → a validated flat string map. */
|
|
212
|
+
export function readVarsFromEnv(): Record<string, string> {
|
|
213
|
+
const raw = process.env.SPROUTBOAT_VARS_JSON;
|
|
214
|
+
if (!raw) return {};
|
|
215
|
+
const parsed: VarsJson = JSON.parse(raw);
|
|
216
|
+
if (!isVarsObject(parsed)) throw new Error("SPROUTBOAT_VARS_JSON must be a JSON object");
|
|
217
|
+
return Object.fromEntries(
|
|
218
|
+
Object.entries(parsed).map(([key, value]): [string, string] => {
|
|
219
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(key) || !isVarsString(value))
|
|
220
|
+
throw new Error(`SPROUTBOAT_VARS_JSON.${key} must map an UPPER_SNAKE name to a string`);
|
|
221
|
+
return [key, value];
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* `SPROUTBOAT_BINDINGS_JSON` (the artifact's `bindings.json`, passed by the
|
|
228
|
+
* build) → a `Bindings` shape. Every field is re-validated here; unknown keys
|
|
229
|
+
* are dropped and a missing / empty payload is `EMPTY_BINDINGS`, so an old build
|
|
230
|
+
* with no bindings still compiles.
|
|
231
|
+
*/
|
|
232
|
+
export function readBindingsFromEnv(): Bindings {
|
|
233
|
+
const raw = process.env.SPROUTBOAT_BINDINGS_JSON;
|
|
234
|
+
if (!raw) return EMPTY_BINDINGS;
|
|
235
|
+
const parsed: VarsJson = JSON.parse(raw);
|
|
236
|
+
if (!isVarsObject(parsed)) throw new Error("SPROUTBOAT_BINDINGS_JSON must be a JSON object");
|
|
237
|
+
const strings = (v: VarsJson): string[] => (Array.isArray(v) ? v.filter(isVarsString) : []);
|
|
238
|
+
const services: Array<{ binding: string; service: string }> = [];
|
|
239
|
+
if (Array.isArray(parsed.services)) {
|
|
240
|
+
for (const entry of parsed.services) {
|
|
241
|
+
if (isVarsObject(entry) && isVarsString(entry.binding) && isVarsString(entry.service)) {
|
|
242
|
+
services.push({ binding: entry.binding, service: entry.service });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const dos: Array<{ binding: string; className: string }> = [];
|
|
247
|
+
if (Array.isArray(parsed.do)) {
|
|
248
|
+
for (const entry of parsed.do) {
|
|
249
|
+
if (isVarsObject(entry) && isVarsString(entry.binding) && isVarsString(entry.className)) {
|
|
250
|
+
dos.push({ binding: entry.binding, className: entry.className });
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return {
|
|
255
|
+
kv: strings(parsed.kv),
|
|
256
|
+
secrets: strings(parsed.secrets),
|
|
257
|
+
outbound: strings(parsed.outbound),
|
|
258
|
+
d1: strings(parsed.d1),
|
|
259
|
+
r2: strings(parsed.r2),
|
|
260
|
+
queues: strings(parsed.queues),
|
|
261
|
+
analytics: strings(parsed.analytics),
|
|
262
|
+
do: dos,
|
|
263
|
+
services,
|
|
264
|
+
crons: strings(parsed.crons),
|
|
265
|
+
assets: isVarsString(parsed.assets) ? parsed.assets : "",
|
|
266
|
+
};
|
|
267
|
+
}
|