@rsc-kit/core 0.42.1 → 0.43.1
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/dist/apiPrerender.js +25 -12
- package/dist/apiPrerender.js.map +1 -1
- package/dist/buildProcess.d.ts +12 -0
- package/dist/buildProcess.js +202 -0
- package/dist/buildProcess.js.map +1 -0
- package/dist/buildScope.d.ts +61 -0
- package/dist/buildScope.js +172 -0
- package/dist/buildScope.js.map +1 -0
- package/dist/conformance.d.ts +3 -0
- package/dist/conformance.js +23 -3
- package/dist/conformance.js.map +1 -1
- package/dist/conformanceBuild.d.ts +5 -0
- package/dist/conformanceBuild.js +154 -0
- package/dist/conformanceBuild.js.map +1 -0
- package/dist/csp.d.ts +11 -2
- package/dist/csp.js +55 -6
- package/dist/csp.js.map +1 -1
- package/dist/formArgs.d.ts +10 -0
- package/dist/formArgs.js +41 -0
- package/dist/formArgs.js.map +1 -0
- package/dist/headers.d.ts +2 -0
- package/dist/headers.js +2 -0
- package/dist/headers.js.map +1 -1
- package/dist/host.js +47 -29
- package/dist/host.js.map +1 -1
- package/dist/hostCalls.d.ts +17 -0
- package/dist/hostCalls.js +103 -103
- package/dist/hostCalls.js.map +1 -1
- package/dist/hostSources.d.ts +23 -0
- package/dist/hostSources.js +65 -0
- package/dist/hostSources.js.map +1 -0
- package/dist/prerender.d.ts +18 -5
- package/dist/prerender.js +95 -16
- package/dist/prerender.js.map +1 -1
- package/dist/typegen.js +11 -2
- package/dist/typegen.js.map +1 -1
- package/dist/vite.d.ts +17 -2
- package/dist/vite.js +189 -105
- package/dist/vite.js.map +1 -1
- package/package.json +5 -1
package/dist/apiPrerender.js
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
// GET only. Everything else is a method a caller may not repeat, and a stored
|
|
11
11
|
// answer to a POST is a stored answer to something that was supposed to happen
|
|
12
12
|
// once.
|
|
13
|
-
import {
|
|
13
|
+
import { buildBudget, withBuildCalls } from './buildScope.js';
|
|
14
|
+
import { pathKey, storedAnswers } from './prerender.js';
|
|
14
15
|
import { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js';
|
|
15
16
|
import { watchNondeterminism, whileRendering } from './nondeterminism.js';
|
|
16
17
|
import { allowFor } from './routing.js';
|
|
@@ -159,22 +160,27 @@ export async function prerenderApiRoutes(engine, manifest, write) {
|
|
|
159
160
|
// the cookie may already have left. Whether it went to the draft or stayed
|
|
160
161
|
// on the Response depends on what else is running in the process; the
|
|
161
162
|
// question here is only whether there was one.
|
|
162
|
-
const answered = await withResponseDraft(({ taken }) => withRequest(null, async () => {
|
|
163
|
+
const answered = await withBuildCalls((made) => withResponseDraft(({ taken }) => withRequest(null, async () => {
|
|
163
164
|
let readBy = [];
|
|
165
|
+
let budget;
|
|
164
166
|
const response = await Promise.race([
|
|
165
167
|
whileRendering(() => engine.handleApiRoute(route.name, request, {}, allowFor(route)))
|
|
166
168
|
.then(([value, reached]) => ({ value, reached }))
|
|
167
169
|
.catch((error) => ({ error })),
|
|
168
|
-
new Promise((resolve) =>
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
170
|
+
new Promise((resolve) => {
|
|
171
|
+
budget = buildBudget(BUDGET_MS, () => {
|
|
172
|
+
readBy = requestReadBy();
|
|
173
|
+
resolve(null);
|
|
174
|
+
});
|
|
175
|
+
}),
|
|
172
176
|
]);
|
|
173
|
-
|
|
174
|
-
|
|
177
|
+
budget?.stop();
|
|
178
|
+
return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken(), made: made() };
|
|
179
|
+
})));
|
|
175
180
|
if (answered.response === null) {
|
|
176
|
-
const
|
|
177
|
-
|
|
181
|
+
const called = [...answered.readBy, ...answered.made.visitors];
|
|
182
|
+
const why = called.length
|
|
183
|
+
? 'dynamic — called ' + called.join(', ')
|
|
178
184
|
: 'did not answer within the build budget';
|
|
179
185
|
said('dynamic', why);
|
|
180
186
|
continue;
|
|
@@ -183,7 +189,12 @@ export async function prerenderApiRoutes(engine, manifest, write) {
|
|
|
183
189
|
// Not a build failure. A route that throws with no request may be doing
|
|
184
190
|
// exactly the right thing — refusing a caller it cannot identify — and
|
|
185
191
|
// refusing the build over it would make that route unbuildable.
|
|
186
|
-
said('dynamic', 'threw without a request');
|
|
192
|
+
said('dynamic', answered.made.failed.length ? answered.made.failed.join('; ') : 'threw without a request');
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
// Caught by the route, whose answer is then about a backend that was down.
|
|
196
|
+
if (answered.made.failed.length) {
|
|
197
|
+
said('dynamic', answered.made.failed.join('; '));
|
|
187
198
|
continue;
|
|
188
199
|
}
|
|
189
200
|
if (touched.size > 0) {
|
|
@@ -228,7 +239,9 @@ export async function prerenderApiRoutes(engine, manifest, write) {
|
|
|
228
239
|
body,
|
|
229
240
|
varies,
|
|
230
241
|
}));
|
|
231
|
-
|
|
242
|
+
const stores = answered.made.answered.length ? storedAnswers(answered.made.answered) : null;
|
|
243
|
+
const reasons = [varies ? 'stored for the bare url — it reads the query string' : null, stores].filter(Boolean);
|
|
244
|
+
said('frozen', reasons.length ? reasons.join('; ') : null);
|
|
232
245
|
// The same warning a page gets: a stored answer keeps whatever Date.now()
|
|
233
246
|
// or Math.random() returned at build time, and a json body has no browser
|
|
234
247
|
// to move it to.
|
package/dist/apiPrerender.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["../src/apiPrerender.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,QAAQ;AAER,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cA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O,CAAC,MAAM,GAAG,CAAC,CAAE,CAAC,OAAO;oBAClC,SAAS,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,iEAAiE;wBAC3I,kGAAkG,CAAA;YACtG,CAAC;QACH,CAAC;IACD,CAAC;YAAS,CAAC;QACT,OAAO,EAAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { pathKey } from './prerender.js'\nimport { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * `url` is on the list although the path is the key the answer is stored\n * under, because nobody reads it for the path: a handler written the Next way\n * reads `new URL(request.url).searchParams`, which the probe cannot see the\n * way it sees the awaited `searchParams` — and a stored answer marked as\n * varying with nothing would then be served to every query, a webhook's\n * verification handshake included. Reading the url also puts the build\n * machine's origin within reach of the answer. A route that wants the bare\n * url stored awaits `searchParams` instead; the table says so.\n */\nconst PER_CALLER = new Set([\n 'url',\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n // The engine's own way past the probe, for the url read that resolves\n // the awaited searchParams - booked to searchParams, not to url.\n if (property === UNPROBED) return target\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0 || (route.hostMiddleware?.length ?? 0) > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) =>\n setTimeout(() => {\n readBy = requestReadBy()\n resolve(null)\n }, BUDGET_MS),\n ),\n ])\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken() }\n }),\n )\n\n if (answered.response === null) {\n const why = answered.readBy.length\n ? 'dynamic — called ' + answered.readBy.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', 'threw without a request')\n continue\n }\n\n if (touched.size > 0) {\n const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : ''\n\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint)\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A refusal is an answer to the request the build sent - none - not to\n // the ones visitors will. A route that answers 403 with nothing read is\n // usually checking something the probe cannot see, and a stored 403 was\n // once every webhook handshake's answer. Left to run, and said so.\n if (response.status >= 400) {\n said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`)\n continue\n }\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n said('frozen', varies ? 'stored for the bare url — it reads the query string' : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')}${route.source ? ' in ' + route.source : ''} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiPrerender.js","sourceRoot":"","sources":["../src/apiPrerender.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,qCAAqC;AACrC,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,QAAQ;AAER,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAC7D,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AACtF,O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AAE,CAAA;IACX,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["// Freezing an api route the way a page is frozen.\n//\n// Not as an opt-in flag, deliberately. A page is stored by default and opts\n// OUT by touching the request — connection(), cookies(), headers() all suspend\n// at build time because there is no request there, and that is what marks the\n// page dynamic. A route works the same way and for the same reason: one model\n// to learn rather than two, and the honest default in both cases is \"the build\n// tried, and here is what it found\".\n//\n// GET only. Everything else is a method a caller may not repeat, and a stored\n// answer to a POST is a stored answer to something that was supposed to happen\n// once.\n\nimport { buildBudget, withBuildCalls } from './buildScope.js'\nimport { pathKey, storedAnswers } from './prerender.js'\nimport { UNPROBED, requestReadBy, withRequest, withResponseDraft } from './request.js'\nimport { watchNondeterminism, whileRendering } from './nondeterminism.js'\nimport type { ManifestApiRoute, RouteManifest } from './manifest.js'\nimport { allowFor } from './routing.js'\n\n/**\n * How long a route gets to answer before it is called dynamic.\n *\n * A route that reads the request does not fail here — it never settles, because\n * the accessors suspend forever with no request to read. So the budget is what\n * turns \"waiting\" into an answer, and it only has to be long enough for a route\n * that was going to finish.\n */\nconst BUDGET_MS = 2_000\n\n/** What a stored answer holds. Enough to rebuild the Response exactly. */\nexport interface FrozenApiResponse {\n status: number\n headers: [string, string][]\n body: string\n /**\n * Whether the answer depends on the query string.\n *\n * False when the handler never awaited `searchParams` and declared no schema\n * for it, which means the same answer is right for `?utm_source=anything`.\n * True and the stored answer is only good for the bare url.\n */\n varies: boolean\n}\n\n/** The file a frozen route is stored as. */\nexport function apiKey(url: string): string {\n return `${pathKey(url)}.api.json`\n}\n\n/**\n * Reading anything here means the answer depends on the caller.\n *\n * `url` is on the list although the path is the key the answer is stored\n * under, because nobody reads it for the path: a handler written the Next way\n * reads `new URL(request.url).searchParams`, which the probe cannot see the\n * way it sees the awaited `searchParams` — and a stored answer marked as\n * varying with nothing would then be served to every query, a webhook's\n * verification handshake included. Reading the url also puts the build\n * machine's origin within reach of the answer. A route that wants the bare\n * url stored awaits `searchParams` instead; the table says so.\n */\nconst PER_CALLER = new Set([\n 'url',\n 'headers',\n 'body',\n 'bodyUsed',\n 'text',\n 'json',\n 'formData',\n 'arrayBuffer',\n 'blob',\n 'bytes',\n 'signal',\n 'referrer',\n 'credentials',\n])\n\n/**\n * A Request that records what was read out of it.\n *\n * A proxy rather than a subclass because the interesting properties are\n * getters on Request.prototype, and `this` has to stay the real Request or\n * every one of them throws about an illegal invocation.\n */\nfunction probeRequest(url: string, touched: Set<string>): Request {\n const real = new Request(url, { method: 'GET' })\n\n return new Proxy(real, {\n get(target, property) {\n // The engine's own way past the probe, for the url read that resolves\n // the awaited searchParams - booked to searchParams, not to url.\n if (property === UNPROBED) return target\n if (typeof property === 'string' && PER_CALLER.has(property)) touched.add(property)\n\n const value = Reflect.get(target, property, target)\n\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\n/** The url a route with no parameters answers. */\nfunction urlFor(route: ManifestApiRoute): string | null {\n // A parameterised route has as many urls as there are values, and nothing\n // here knows them. Pages solve this with generateStaticParams; until a route\n // can say the same, one is answered per request.\n if (route.segments.some((segment) => segment.type !== 'static')) return null\n\n return '/' + route.segments.map((segment) => segment.value).join('/')\n}\n\n/**\n * What the build calls a route in its output.\n *\n * The pattern for a parameterised one, spelled the way pages already spell\n * theirs, rather than the module name — a line reading\n * \"/app/api/greet/[name]/route\" names a file on disk and the rest of the table\n * names urls.\n */\nfunction labelFor(route: ManifestApiRoute): string {\n return (\n '/' +\n route.segments\n .map((segment) => (segment.type === 'static' ? segment.value : `_${segment.value}_`))\n .join('/')\n )\n}\n\n/** Whether a body is text this can store and hand back unchanged. */\nfunction asText(bytes: Uint8Array): string | null {\n try {\n const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\n return text\n } catch {\n // Binary. Storable in principle, as base64, at the cost of a third of its\n // size on disk and a decode per request — for a route that is far more\n // likely to be streaming a file it should be serving as a file.\n return null\n }\n}\n\nexport interface ApiPrerenderResult {\n url: string\n name: string\n type: 'frozen' | 'dynamic'\n reason: string | null\n /** Stored, and worth a second look - it froze a value that will not be the same tomorrow. */\n warning?: string\n}\n\n/**\n * Try to answer every api route once, at build time, and store what can be.\n *\n * Sequential rather than parallel: there are usually few of them, each is a\n * function call rather than a React render, and the ones that are going to be\n * dynamic spend the whole budget waiting — which is time, not work.\n */\nexport async function prerenderApiRoutes(\n engine: { handleApiRoute?: (n: string, r: Request, p: Record<string, string>, a: string) => Promise<Response> },\n manifest: RouteManifest,\n write: (name: string, contents: string) => Promise<void>,\n): Promise<ApiPrerenderResult[]> {\n if (!engine.handleApiRoute || !manifest.apis?.length) return []\n\n const results: ApiPrerenderResult[] = []\n\n // Date.now() and friends are watched for the length of the loop, the way\n // the page prerender watches them; whileRendering records what each route\n // reached for while it answered.\n const unwatch = watchNondeterminism()\n\n try {\n for (const route of manifest.apis) {\n const said = (type: 'frozen' | 'dynamic', reason: string | null) => {\n results.push({ url: labelFor(route), name: route.name, type, reason })\n }\n\n if (!route.methods.includes('GET')) {\n said('dynamic', 'no GET to store')\n continue\n }\n\n // A guarded route answers differently depending on who is asking, which is\n // the whole purpose of the guard. Storing one answer and serving it to\n // everyone is how a guard is silently removed.\n if (route.middleware.length > 0 || (route.hostMiddleware?.length ?? 0) > 0) {\n said('dynamic', 'guarded by middleware')\n continue\n }\n\n const url = urlFor(route)\n\n if (!url) {\n said('dynamic', 'one url per param value, and none are listed')\n continue\n }\n\n const touched = new Set<string>()\n const request = probeRequest('https://prerender.invalid' + url, touched)\n\n // No request in scope, so headers(), cookies() and connection() suspend\n // forever rather than resolving to whatever the build machine had. The\n // budget below is what turns that into an answer.\n // Inside a response draft, because that is where the engine puts a cookie\n // a route sets - a literal Set-Cookie on its Response is moved there too\n // whenever a draft is open - and a probe with no draft reads a Response\n // the cookie may already have left. Whether it went to the draft or stayed\n // on the Response depends on what else is running in the process; the\n // question here is only whether there was one.\n const answered = await withBuildCalls((made) => withResponseDraft(({ taken }) =>\n withRequest(null as never, async () => {\n let readBy: string[] = []\n let budget: { stop(): void } | undefined\n\n const response = await Promise.race([\n whileRendering(() => engine.handleApiRoute!(route.name, request, {}, allowFor(route)))\n .then(([value, reached]) => ({ value, reached }))\n .catch((error) => ({ error })),\n new Promise<null>((resolve) => {\n budget = buildBudget(BUDGET_MS, () => {\n readBy = requestReadBy()\n resolve(null)\n })\n }),\n ])\n\n budget?.stop()\n\n return { response, readBy: readBy.length ? readBy : requestReadBy(), drafted: taken(), made: made() }\n }),\n ))\n\n if (answered.response === null) {\n const called = [...answered.readBy, ...answered.made.visitors]\n const why = called.length\n ? 'dynamic — called ' + called.join(', ')\n : 'did not answer within the build budget'\n\n said('dynamic', why)\n continue\n }\n\n if ('error' in answered.response) {\n // Not a build failure. A route that throws with no request may be doing\n // exactly the right thing — refusing a caller it cannot identify — and\n // refusing the build over it would make that route unbuildable.\n said('dynamic', answered.made.failed.length ? answered.made.failed.join('; ') : 'threw without a request')\n continue\n }\n\n // Caught by the route, whose answer is then about a backend that was down.\n if (answered.made.failed.length) {\n said('dynamic', answered.made.failed.join('; '))\n continue\n }\n\n if (touched.size > 0) {\n const hint = touched.has('url') ? ' (await searchParams to read the query and keep the bare url stored)' : ''\n\n said('dynamic', 'reads the request — ' + [...touched].sort().join(', ') + hint)\n continue\n }\n\n // Awaiting the query string is not a reason to give up on the route — the\n // bare url still has one right answer. It only narrows which requests the\n // stored answer is good for.\n const varies = answered.readBy.includes('searchParams')\n\n const response = answered.response.value\n\n // A refusal is an answer to the request the build sent - none - not to\n // the ones visitors will. A route that answers 403 with nothing read is\n // usually checking something the probe cannot see, and a stored 403 was\n // once every webhook handshake's answer. Left to run, and said so.\n if (response.status >= 400) {\n said('dynamic', `answered ${response.status} to the build — a refusal is not an answer to store`)\n continue\n }\n\n // A cookie is an answer for one visitor, whatever the route read to\n // decide on it. Stored, the build's cookie would be handed to everyone.\n if (response.headers.has('set-cookie') || answered.drafted.has('set-cookie')) {\n said('dynamic', 'sets a cookie — an answer for one visitor, not one to store')\n continue\n }\n\n const body = asText(new Uint8Array(await response.arrayBuffer()))\n\n if (body === null) {\n said('dynamic', 'answers with bytes rather than text')\n continue\n }\n\n await write(\n apiKey(url),\n JSON.stringify({\n status: response.status,\n // Lower-cased and sorted, so two builds of the same route produce the\n // same bytes. Headers iteration does not promise a case or an order,\n // and a file that differs between builds for no reason defeats\n // content-addressed caching and makes a diff unreadable. Names are\n // case-insensitive, so nothing is lost by picking one.\n headers: [...response.headers]\n .map(([name, value]) => [name.toLowerCase(), value] as [string, string])\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n body,\n varies,\n } satisfies FrozenApiResponse),\n )\n\n const stores = answered.made.answered.length ? storedAnswers(answered.made.answered) : null\n const reasons = [varies ? 'stored for the bare url — it reads the query string' : null, stores].filter(Boolean)\n\n said('frozen', reasons.length ? reasons.join('; ') : null)\n\n // The same warning a page gets: a stored answer keeps whatever Date.now()\n // or Math.random() returned at build time, and a json body has no browser\n // to move it to.\n const reached = answered.response.reached\n\n if (reached.length > 0) {\n results[results.length - 1]!.warning =\n `froze ${reached.join(' and ')}${route.source ? ' in ' + route.source : ''} — a stored answer keeps whatever that returned at build time. ` +\n 'If it should differ per call, read the request (await connection()) so the route runs on demand.'\n }\n }\n } finally {\n unwatch()\n }\n\n return results\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type BuildAnswerer } from './buildScope.js';
|
|
2
|
+
export interface BuildProcessOptions {
|
|
3
|
+
command: string[];
|
|
4
|
+
cwd: string;
|
|
5
|
+
/** How long without any answer before the build gives up. */
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
/** Where what the app prints goes. */
|
|
8
|
+
print?: (text: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export declare function buildProcess(options: BuildProcessOptions): BuildAnswerer & {
|
|
11
|
+
close(): void;
|
|
12
|
+
};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// The backend's process that answers a build's rpc() calls.
|
|
2
|
+
//
|
|
3
|
+
// A command rather than the host-call endpoint: a build runs where the app is
|
|
4
|
+
// not being served - CI, a container being made - and the backend's own
|
|
5
|
+
// command is already how it is asked for its manifest there. One JSON object
|
|
6
|
+
// a line, each way:
|
|
7
|
+
//
|
|
8
|
+
// > {"id":1,"function":"Posts.all","args":[]}
|
|
9
|
+
// < {"id":1,"status":200,"result":[...]}
|
|
10
|
+
// < {"id":2,"visitor":["the session"]}
|
|
11
|
+
//
|
|
12
|
+
// In any order, matched by id. An answer with "last": true is the last this
|
|
13
|
+
// process gives - the backend's way of saying its state is no longer anyone's
|
|
14
|
+
// - and what it had not answered is asked of a new one. A line that is not an
|
|
15
|
+
// answer is something the app printed, and is passed on.
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import { saidCall } from './buildScope.js';
|
|
18
|
+
const STDERR_TAIL = 4_000;
|
|
19
|
+
export function buildProcess(options) {
|
|
20
|
+
const { command, cwd, timeoutMs = 60_000, print = (text) => process.stderr.write(text) } = options;
|
|
21
|
+
// Answers by call and arguments, so every render of a page - its shell, the
|
|
22
|
+
// whole page, each segment - holds the same one. As text, parsed for each:
|
|
23
|
+
// a render may change what it was given.
|
|
24
|
+
const answers = new Map();
|
|
25
|
+
// Functions that read the visitor, by name: what a function reads does not
|
|
26
|
+
// depend on which of five hundred posts it was asked about, and asking each
|
|
27
|
+
// would end a process each time.
|
|
28
|
+
const visitors = new Map();
|
|
29
|
+
const waiting = new Map();
|
|
30
|
+
let child = null;
|
|
31
|
+
let nextId = 1;
|
|
32
|
+
let closed = false;
|
|
33
|
+
let broken = null;
|
|
34
|
+
let timer;
|
|
35
|
+
const shown = command.join(' ');
|
|
36
|
+
/** Give up when nothing at all has been answered for too long. */
|
|
37
|
+
function watch() {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
if (waiting.size === 0)
|
|
40
|
+
return;
|
|
41
|
+
timer = setTimeout(() => {
|
|
42
|
+
const process = child;
|
|
43
|
+
child = null;
|
|
44
|
+
process?.kill();
|
|
45
|
+
failAll(`gave no answer for ${Math.round(timeoutMs / 1000)}s`, '');
|
|
46
|
+
}, timeoutMs);
|
|
47
|
+
}
|
|
48
|
+
function failAll(why, stderr) {
|
|
49
|
+
const calls = [...waiting.values()];
|
|
50
|
+
waiting.clear();
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
const names = [...new Set(calls.map((call) => saidCall(call.name)))];
|
|
53
|
+
const error = new Error(`The backend's build process ${why} while answering ${names.slice(0, 3).join(', ')}` +
|
|
54
|
+
(names.length > 3 ? ` and ${names.length - 3} more` : '') +
|
|
55
|
+
` (${shown}).` + (stderr.trim() ? `\n${stderr.trim()}` : ''));
|
|
56
|
+
for (const call of calls)
|
|
57
|
+
call.reject(error);
|
|
58
|
+
broken = error;
|
|
59
|
+
}
|
|
60
|
+
function start() {
|
|
61
|
+
const [file, ...args] = command;
|
|
62
|
+
const started = spawn(file, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
63
|
+
let stderr = '';
|
|
64
|
+
let buffered = '';
|
|
65
|
+
let answered = false;
|
|
66
|
+
const ended = (why) => {
|
|
67
|
+
if (child !== started)
|
|
68
|
+
return;
|
|
69
|
+
child = null;
|
|
70
|
+
if (closed || waiting.size === 0)
|
|
71
|
+
return;
|
|
72
|
+
failAll(why, stderr);
|
|
73
|
+
// A process that answered and then died took its calls with it. One
|
|
74
|
+
// that never answered will not the next time either.
|
|
75
|
+
if (answered)
|
|
76
|
+
broken = null;
|
|
77
|
+
};
|
|
78
|
+
started.stdout.setEncoding('utf-8');
|
|
79
|
+
started.stderr.setEncoding('utf-8');
|
|
80
|
+
started.stderr.on('data', (text) => {
|
|
81
|
+
stderr = (stderr + text).slice(-STDERR_TAIL);
|
|
82
|
+
print(text);
|
|
83
|
+
});
|
|
84
|
+
started.stdout.on('data', (text) => {
|
|
85
|
+
buffered += text;
|
|
86
|
+
let at;
|
|
87
|
+
while ((at = buffered.indexOf('\n')) !== -1) {
|
|
88
|
+
const line = buffered.slice(0, at);
|
|
89
|
+
buffered = buffered.slice(at + 1);
|
|
90
|
+
if (line.trim() !== '' && !take(line, started))
|
|
91
|
+
print(line + '\n');
|
|
92
|
+
else if (line.trim() !== '')
|
|
93
|
+
answered = true;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
// A process that went away is reported by its exit, not by the write.
|
|
97
|
+
started.stdin.on('error', () => { });
|
|
98
|
+
started.on('error', (error) => ended(`could not be started: ${error.message}`));
|
|
99
|
+
// close rather than exit: its last lines may still be in the pipe.
|
|
100
|
+
started.on('close', (code, signal) => {
|
|
101
|
+
if (buffered.trim() !== '' && take(buffered, started))
|
|
102
|
+
answered = true;
|
|
103
|
+
ended(signal ? `was stopped by ${signal}` : `ended with code ${code}`);
|
|
104
|
+
});
|
|
105
|
+
return started;
|
|
106
|
+
}
|
|
107
|
+
/** One line, if it is an answer to a call still waiting. */
|
|
108
|
+
function take(line, from) {
|
|
109
|
+
let parsed;
|
|
110
|
+
try {
|
|
111
|
+
parsed = JSON.parse(line);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
const call = typeof parsed?.id === 'number' ? waiting.get(parsed.id) : undefined;
|
|
117
|
+
// From a process already given up on: its calls were asked again.
|
|
118
|
+
if (!call || child !== from)
|
|
119
|
+
return false;
|
|
120
|
+
waiting.delete(call.id);
|
|
121
|
+
if (Array.isArray(parsed.visitor))
|
|
122
|
+
visitors.set(call.name, line);
|
|
123
|
+
call.resolve(line);
|
|
124
|
+
if (parsed.last === true) {
|
|
125
|
+
child = null;
|
|
126
|
+
from.stdin.end();
|
|
127
|
+
again();
|
|
128
|
+
}
|
|
129
|
+
watch();
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
/** Ask a new process what the last one left. */
|
|
133
|
+
function again() {
|
|
134
|
+
for (const call of [...waiting.values()]) {
|
|
135
|
+
const known = visitors.get(call.name);
|
|
136
|
+
if (known !== undefined) {
|
|
137
|
+
waiting.delete(call.id);
|
|
138
|
+
call.resolve(known);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (waiting.size === 0)
|
|
142
|
+
return;
|
|
143
|
+
child = start();
|
|
144
|
+
for (const call of waiting.values())
|
|
145
|
+
child.stdin.write(call.line);
|
|
146
|
+
}
|
|
147
|
+
function send(name, args) {
|
|
148
|
+
if (closed)
|
|
149
|
+
return Promise.reject(new Error(`${saidCall(name)} was made after the build ended.`));
|
|
150
|
+
if (broken)
|
|
151
|
+
return Promise.reject(broken);
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const id = nextId++;
|
|
154
|
+
const line = JSON.stringify({ id, function: name, args }) + '\n';
|
|
155
|
+
waiting.set(id, { id, name, line, resolve, reject });
|
|
156
|
+
child ??= start();
|
|
157
|
+
child.stdin.write(line);
|
|
158
|
+
if (waiting.size === 1)
|
|
159
|
+
watch();
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
async ask(name, args) {
|
|
164
|
+
const known = visitors.get(name);
|
|
165
|
+
if (known !== undefined)
|
|
166
|
+
return read(known);
|
|
167
|
+
const key = JSON.stringify([name, args]);
|
|
168
|
+
let answer = answers.get(key);
|
|
169
|
+
if (!answer) {
|
|
170
|
+
answer = send(name, args);
|
|
171
|
+
answers.set(key, answer);
|
|
172
|
+
}
|
|
173
|
+
return read(await answer);
|
|
174
|
+
},
|
|
175
|
+
close() {
|
|
176
|
+
closed = true;
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
const process = child;
|
|
179
|
+
child = null;
|
|
180
|
+
if (!process)
|
|
181
|
+
return;
|
|
182
|
+
// Its input ending is what ends it. A kill reaches the command and not
|
|
183
|
+
// what the command started - a wrapper's own child - which would hold
|
|
184
|
+
// these pipes, and the build with them. One still answering a call
|
|
185
|
+
// nobody is waiting for any more is stopped.
|
|
186
|
+
process.stdin.end();
|
|
187
|
+
if (waiting.size > 0)
|
|
188
|
+
process.kill();
|
|
189
|
+
process.stdout.destroy();
|
|
190
|
+
process.stderr.destroy();
|
|
191
|
+
process.unref();
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** A line, as an answer. */
|
|
196
|
+
function read(line) {
|
|
197
|
+
const { id: _, last: __, visitor, status, ...reply } = JSON.parse(line);
|
|
198
|
+
if (Array.isArray(visitor))
|
|
199
|
+
return { visitor: visitor.map(String) };
|
|
200
|
+
return { status: typeof status === 'number' ? status : 200, reply, text: JSON.stringify(reply) };
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=buildProcess.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildProcess.js","sourceRoot":"","sources":["../src/buildProcess.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,EAAE;AACF,8EAA8E;AAC9E,wEAAwE;AACxE,6EAA6E;AAC7E,oBAAoB;AACpB,EAAE;AACF,kDAAkD;AAClD,6CAA6C;AAC7C,2CAA2C;AAC3C,EAAE;AACF,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,yDAAyD;AAEzD,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAA;AAE/E,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAA;AAmBhF,MAAM,WAAW,GAAG,KAAK,CAAA;AAEzB,MAAM,UAAU,YAAY,CAAC,OAA4B;IACvD,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,GAAG,MAAM,EAAE,KAAK,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,CAAA;IAElG,4EAA4E;IAC5E,2EAA2E;IAC3E,yCAAyC;IACzC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAA;IAClD,2EAA2E;IAC3E,4EAA4E;IAC5E,iCAAiC;IACjC,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA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EAAE,CAAA;QACjB,CAAC;KACF,CAAA;AACH,CAAC;AAED,4BAA4B;AAC5B,SAAS,IAAI,CAAC,IAAY;IACxB,MAAM,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAKrE,CAAA;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;IAEnE,OAAO,EAAE,MAAM,EAAE,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAA;AAClG,CAAC","sourcesContent":["// The backend's process that answers a build's rpc() calls.\n//\n// A command rather than the host-call endpoint: a build runs where the app is\n// not being served - CI, a container being made - and the backend's own\n// command is already how it is asked for its manifest there. One JSON object\n// a line, each way:\n//\n// > {\"id\":1,\"function\":\"Posts.all\",\"args\":[]}\n// < {\"id\":1,\"status\":200,\"result\":[...]}\n// < {\"id\":2,\"visitor\":[\"the session\"]}\n//\n// In any order, matched by id. An answer with \"last\": true is the last this\n// process gives - the backend's way of saying its state is no longer anyone's\n// - and what it had not answered is asked of a new one. A line that is not an\n// answer is something the app printed, and is passed on.\n\nimport { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'\nimport type { HostCallReply } from './hostCalls.js'\nimport { saidCall, type BuildAnswer, type BuildAnswerer } from './buildScope.js'\n\nexport interface BuildProcessOptions {\n command: string[]\n cwd: string\n /** How long without any answer before the build gives up. */\n timeoutMs?: number\n /** Where what the app prints goes. */\n print?: (text: string) => void\n}\n\ninterface Waiting {\n id: number\n name: string\n line: string\n resolve: (text: string) => void\n reject: (error: Error) => void\n}\n\nconst STDERR_TAIL = 4_000\n\nexport function buildProcess(options: BuildProcessOptions): BuildAnswerer & { close(): void } {\n const { command, cwd, timeoutMs = 60_000, print = (text) => process.stderr.write(text) } = options\n\n // Answers by call and arguments, so every render of a page - its shell, the\n // whole page, each segment - holds the same one. As text, parsed for each:\n // a render may change what it was given.\n const answers = new Map<string, Promise<string>>()\n // Functions that read the visitor, by name: what a function reads does not\n // depend on which of five hundred posts it was asked about, and asking each\n // would end a process each time.\n const visitors = new Map<string, string>()\n const waiting = new Map<number, Waiting>()\n\n let child: ChildProcessWithoutNullStreams | null = null\n let nextId = 1\n let closed = false\n let broken: Error | null = null\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const shown = command.join(' ')\n\n /** Give up when nothing at all has been answered for too long. */\n function watch(): void {\n clearTimeout(timer)\n if (waiting.size === 0) return\n\n timer = setTimeout(() => {\n const process = child\n\n child = null\n process?.kill()\n failAll(`gave no answer for ${Math.round(timeoutMs / 1000)}s`, '')\n }, timeoutMs)\n }\n\n function failAll(why: string, stderr: string): void {\n const calls = [...waiting.values()]\n\n waiting.clear()\n clearTimeout(timer)\n\n const names = [...new Set(calls.map((call) => saidCall(call.name)))]\n const error = new Error(\n `The backend's build process ${why} while answering ${names.slice(0, 3).join(', ')}` +\n (names.length > 3 ? ` and ${names.length - 3} more` : '') +\n ` (${shown}).` + (stderr.trim() ? `\\n${stderr.trim()}` : ''),\n )\n\n for (const call of calls) call.reject(error)\n\n broken = error\n }\n\n function start(): ChildProcessWithoutNullStreams {\n const [file, ...args] = command\n const started = spawn(file!, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] })\n let stderr = ''\n let buffered = ''\n let answered = false\n\n const ended = (why: string) => {\n if (child !== started) return\n\n child = null\n if (closed || waiting.size === 0) return\n\n failAll(why, stderr)\n // A process that answered and then died took its calls with it. One\n // that never answered will not the next time either.\n if (answered) broken = null\n }\n\n started.stdout.setEncoding('utf-8')\n started.stderr.setEncoding('utf-8')\n\n started.stderr.on('data', (text: string) => {\n stderr = (stderr + text).slice(-STDERR_TAIL)\n print(text)\n })\n\n started.stdout.on('data', (text: string) => {\n buffered += text\n\n let at: number\n\n while ((at = buffered.indexOf('\\n')) !== -1) {\n const line = buffered.slice(0, at)\n\n buffered = buffered.slice(at + 1)\n if (line.trim() !== '' && !take(line, started)) print(line + '\\n')\n else if (line.trim() !== '') answered = true\n }\n })\n\n // A process that went away is reported by its exit, not by the write.\n started.stdin.on('error', () => {})\n started.on('error', (error) => ended(`could not be started: ${error.message}`))\n // close rather than exit: its last lines may still be in the pipe.\n started.on('close', (code, signal) => {\n if (buffered.trim() !== '' && take(buffered, started)) answered = true\n ended(signal ? `was stopped by ${signal}` : `ended with code ${code}`)\n })\n\n return started\n }\n\n /** One line, if it is an answer to a call still waiting. */\n function take(line: string, from: ChildProcessWithoutNullStreams): boolean {\n let parsed: { id?: unknown; visitor?: unknown; last?: unknown }\n\n try {\n parsed = JSON.parse(line) as typeof parsed\n } catch {\n return false\n }\n\n const call = typeof parsed?.id === 'number' ? waiting.get(parsed.id) : undefined\n\n // From a process already given up on: its calls were asked again.\n if (!call || child !== from) return false\n\n waiting.delete(call.id)\n if (Array.isArray(parsed.visitor)) visitors.set(call.name, line)\n call.resolve(line)\n\n if (parsed.last === true) {\n child = null\n from.stdin.end()\n again()\n }\n\n watch()\n\n return true\n }\n\n /** Ask a new process what the last one left. */\n function again(): void {\n for (const call of [...waiting.values()]) {\n const known = visitors.get(call.name)\n\n if (known !== undefined) {\n waiting.delete(call.id)\n call.resolve(known)\n }\n }\n\n if (waiting.size === 0) return\n\n child = start()\n\n for (const call of waiting.values()) child.stdin.write(call.line)\n }\n\n function send(name: string, args: unknown[]): Promise<string> {\n if (closed) return Promise.reject(new Error(`${saidCall(name)} was made after the build ended.`))\n if (broken) return Promise.reject(broken)\n\n return new Promise<string>((resolve, reject) => {\n const id = nextId++\n const line = JSON.stringify({ id, function: name, args }) + '\\n'\n\n waiting.set(id, { id, name, line, resolve, reject })\n child ??= start()\n child.stdin.write(line)\n if (waiting.size === 1) watch()\n })\n }\n\n return {\n async ask(name, args) {\n const known = visitors.get(name)\n\n if (known !== undefined) return read(known)\n\n const key = JSON.stringify([name, args])\n let answer = answers.get(key)\n\n if (!answer) {\n answer = send(name, args)\n answers.set(key, answer)\n }\n\n return read(await answer)\n },\n close() {\n closed = true\n clearTimeout(timer)\n\n const process = child\n\n child = null\n if (!process) return\n\n // Its input ending is what ends it. A kill reaches the command and not\n // what the command started - a wrapper's own child - which would hold\n // these pipes, and the build with them. One still answering a call\n // nobody is waiting for any more is stopped.\n process.stdin.end()\n if (waiting.size > 0) process.kill()\n process.stdout.destroy()\n process.stderr.destroy()\n process.unref()\n },\n }\n}\n\n/** A line, as an answer. */\nfunction read(line: string): BuildAnswer {\n const { id: _, last: __, visitor, status, ...reply } = JSON.parse(line) as HostCallReply & {\n id: number\n last?: boolean\n visitor?: unknown\n status?: number\n }\n\n if (Array.isArray(visitor)) return { visitor: visitor.map(String) }\n\n return { status: typeof status === 'number' ? status : 200, reply, text: JSON.stringify(reply) }\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type HostCallReply } from './hostCalls.js';
|
|
2
|
+
/** What the backend said: an answer, or what of a visitor the call read. */
|
|
3
|
+
export type BuildAnswer = {
|
|
4
|
+
visitor: string[];
|
|
5
|
+
} | {
|
|
6
|
+
status: number;
|
|
7
|
+
reply: HostCallReply | null;
|
|
8
|
+
text: string;
|
|
9
|
+
};
|
|
10
|
+
/** Whatever answers a build's calls. */
|
|
11
|
+
export interface BuildAnswerer {
|
|
12
|
+
ask(name: string, args: unknown[]): Promise<BuildAnswer>;
|
|
13
|
+
}
|
|
14
|
+
export interface BuildCallsMade {
|
|
15
|
+
answered: string[];
|
|
16
|
+
/** Each already says what it read: `rpc("Cart.items") (the session)`. */
|
|
17
|
+
visitors: string[];
|
|
18
|
+
failed: string[];
|
|
19
|
+
}
|
|
20
|
+
/** Whether this build has a backend to ask. */
|
|
21
|
+
export declare function buildAnswerer(): BuildAnswerer | null;
|
|
22
|
+
/** Have rpc() answered by this, until what is returned is called. */
|
|
23
|
+
export declare function installBuildAnswerer(answerer: BuildAnswerer): () => void;
|
|
24
|
+
/** The call as the build writes it, with what it read when that is why. */
|
|
25
|
+
export declare function saidCall(name: string, read?: string[]): string;
|
|
26
|
+
/**
|
|
27
|
+
* Run one route's renders, noting the calls they make.
|
|
28
|
+
*
|
|
29
|
+
* The notes are read while the render may still be going - a render with a
|
|
30
|
+
* hole never ends - so they are handed over as a function.
|
|
31
|
+
*/
|
|
32
|
+
export declare function withBuildCalls<T>(run: (made: () => BuildCallsMade) => Promise<T>): Promise<T>;
|
|
33
|
+
/**
|
|
34
|
+
* Answer one rpc() of a build.
|
|
35
|
+
*
|
|
36
|
+
* `needsVisitor` decides what a call that read the visitor does to the render
|
|
37
|
+
* that made it: suspend, for the probe deciding what a page's shell is.
|
|
38
|
+
* Outside any route - generateStaticParams, register() - there is no render
|
|
39
|
+
* to leave a hole in, so it is an error that says what was read.
|
|
40
|
+
*/
|
|
41
|
+
export declare function answerAtBuild(args: unknown[], needsVisitor?: (said: string) => Promise<unknown>): Promise<unknown>;
|
|
42
|
+
/**
|
|
43
|
+
* What of a visitor an answer says it read. A refusal to someone not signed
|
|
44
|
+
* in is one too: the build is not, and the visitor may be.
|
|
45
|
+
*/
|
|
46
|
+
export declare function visitorRead(answer: BuildAnswer): string[] | null;
|
|
47
|
+
/**
|
|
48
|
+
* A render's budget, not counting the time it spends waiting for the backend.
|
|
49
|
+
*
|
|
50
|
+
* The budget asks what a page cannot finish at build time, and a call being
|
|
51
|
+
* answered is not that: without this a query slower than two seconds - or
|
|
52
|
+
* just behind others in the queue - turned a page that could be stored into
|
|
53
|
+
* one that streams, depending on how busy the build machine was.
|
|
54
|
+
*/
|
|
55
|
+
export declare function buildBudget(ms: number, expire: () => void): {
|
|
56
|
+
stop(): void;
|
|
57
|
+
};
|
|
58
|
+
/** Whether the route being rendered is waiting for the backend. */
|
|
59
|
+
export declare function awaitingBuildAnswer(): boolean;
|
|
60
|
+
/** Told whenever that may have changed, until the function returned is called. */
|
|
61
|
+
export declare function onBuildAnswer(listener: () => void): () => void;
|