@rsc-kit/core 0.24.1 → 0.24.3
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 +69 -62
- package/dist/conformance.d.ts +68 -0
- package/dist/conformance.js +309 -0
- package/dist/conformance.js.map +1 -0
- package/dist/hostCalls.d.ts +10 -3
- package/dist/hostCalls.js +19 -0
- package/dist/hostCalls.js.map +1 -1
- package/dist/testHost.d.ts +39 -6
- package/dist/testHost.js +2 -0
- package/dist/testHost.js.map +1 -1
- package/dist/typegen.d.ts +10 -1
- package/dist/typegen.js +44 -7
- package/dist/typegen.js.map +1 -1
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +47 -2
- package/dist/vite.js.map +1 -1
- package/package.json +8 -3
package/dist/hostCalls.d.ts
CHANGED
|
@@ -74,6 +74,16 @@ export interface HostCallReply {
|
|
|
74
74
|
* function's result.
|
|
75
75
|
*/
|
|
76
76
|
redirect?: string;
|
|
77
|
+
/**
|
|
78
|
+
* Where an unexpected failure happened in the backend, sent only in
|
|
79
|
+
* development (Laravel's app.debug, Go's CallbackHandler.Debug): the
|
|
80
|
+
* thrown type, its message, and frames newest first.
|
|
81
|
+
*/
|
|
82
|
+
debug?: {
|
|
83
|
+
type?: string;
|
|
84
|
+
message?: string;
|
|
85
|
+
trace?: string[];
|
|
86
|
+
};
|
|
77
87
|
/** The status to redirect with. Defaults to 307, which preserves the method. */
|
|
78
88
|
redirectStatus?: number;
|
|
79
89
|
/**
|
|
@@ -121,7 +131,4 @@ export type HostCallBatchLine = HostCallReply & {
|
|
|
121
131
|
index: number;
|
|
122
132
|
status?: number;
|
|
123
133
|
};
|
|
124
|
-
/**
|
|
125
|
-
* The function to hand to `installHostFn`, or to `hostCalls` on the JS host.
|
|
126
|
-
*/
|
|
127
134
|
export declare function httpHostCalls(options: HttpHostCallsOptions): (name: string, ...args: unknown[]) => Promise<unknown>;
|
package/dist/hostCalls.js
CHANGED
|
@@ -27,6 +27,23 @@ const nextTick = typeof setImmediate === 'function' ? (fn) => setImmediate(fn) :
|
|
|
27
27
|
/**
|
|
28
28
|
* The function to hand to `installHostFn`, or to `hostCalls` on the JS host.
|
|
29
29
|
*/
|
|
30
|
+
/**
|
|
31
|
+
* The backend's trace, on the error the render sees.
|
|
32
|
+
*
|
|
33
|
+
* As its cause - an Error named for the backend's type, whose stack is the
|
|
34
|
+
* backend's frames - so Node, Bun and the dev overlay print it under the
|
|
35
|
+
* renderer's own stack; and appended to that stack, for whatever prints only
|
|
36
|
+
* the one. Before this a failed rpc() pointed at a line of JavaScript, and the
|
|
37
|
+
* PHP or Go that failed was a separate search through another log.
|
|
38
|
+
*/
|
|
39
|
+
function withBackendTrace(failure, debug) {
|
|
40
|
+
const frames = (debug.trace ?? []).map((frame) => ' at ' + frame).join('\n');
|
|
41
|
+
const cause = new Error(debug.message ?? '');
|
|
42
|
+
cause.name = 'Backend ' + (debug.type ?? 'Error');
|
|
43
|
+
cause.stack = cause.name + ': ' + (debug.message ?? '') + (frames ? '\n' + frames : '');
|
|
44
|
+
failure.cause = cause;
|
|
45
|
+
failure.stack = (failure.stack ?? String(failure)) + '\nCaused in the backend by ' + cause.stack;
|
|
46
|
+
}
|
|
30
47
|
export function httpHostCalls(options) {
|
|
31
48
|
const { endpoint, secret, forwardHeaders = DEFAULT_FORWARDED, timeoutMs = 30_000, fetch: fetchImpl, onRevalidate, batch = true, } = options;
|
|
32
49
|
if (!secret) {
|
|
@@ -305,6 +322,8 @@ export function httpHostCalls(options) {
|
|
|
305
322
|
;
|
|
306
323
|
failure.refusalStatus = reply.refusalStatus;
|
|
307
324
|
}
|
|
325
|
+
if (reply.debug)
|
|
326
|
+
withBackendTrace(failure, reply.debug);
|
|
308
327
|
throw failure;
|
|
309
328
|
}
|
|
310
329
|
if (status >= 400) {
|
package/dist/hostCalls.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hostCalls.js","sourceRoot":"","sources":["../src/hostCalls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B,CAAC,CAAA;QACpF,CAAC;QAED,OAAO,KAAK,CAAC,MAAM,IAAI,IAAI,CAAA;IAC7B,CAAC;IAED,OAAO,KAAK,UAAU,QAAQ,CAAC,IAAY,EAAE,GAAG,IAAe;QAC7D,MAAM,OAAO,GAAG,MAAM,gBAAgB,EAAE,CAAA;QACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QAEjG,OAAO,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACjC,CAAC,CAAA;AACH,CAAC","sourcesContent":["// Host calls over HTTP, so a host in any language can answer them.\n//\n// A server component writing `await rpc('Orders.recent')` needs the host\n// mid-render. The Laravel path answers on a second unix socket with its own\n// framing (PROTOCOL.md, \"The callback channel\"), which every non-JS host has\n// to reimplement before it can render a single page that fetches anything.\n// This is the same conversation over an ordinary POST.\n//\n// The transport is the only thing that changes. The engine still sees one\n// function, the deferred-release ordering in streaming.ts still applies, and a\n// reply may still carry `revalidate` — a Go host that answers this endpoint\n// gets the same semantics the socket has, without the framing.\n\nimport { headers as incomingHeaders } from './request.js'\nimport { revalidate } from './revalidate.js'\nimport type { RevalidateTarget } from './routes.js'\nimport { ActionValidationError } from './action.js'\nimport { redirect } from './redirect.js'\nimport { ServerAuthenticationError, ServerAuthorizationError } from './js/errors.js'\nimport { notFound } from './notFound.js'\n\nexport interface HttpHostCallsOptions {\n /**\n * Where calls are POSTed. A loopback address or a unix socket url — see the\n * note on `secret` for why this must not be a public one.\n */\n endpoint: string\n /**\n * Sent as `X-RSC-Host-Secret`, and required rather than optional.\n *\n * This endpoint runs functions by name on behalf of a render. PROTOCOL.md\n * Part 3b draws the line at client-supplied input deciding what RUNS, and an\n * unauthenticated callback endpoint is on the wrong side of it: anyone who\n * can reach it can invoke any registered host function directly, with\n * whatever arguments they like and none of the app's routing in front. A\n * default of \"off\" would be the kind that ships.\n */\n secret: string\n /**\n * Request headers copied from the render's own request onto the call.\n *\n * This is what makes a host call run as the person browsing: the backend's\n * session middleware reads its cookie and finds the same user. Nothing else\n * is forwarded, because everything else is either meaningless to the backend\n * or actively wrong — `content-length` and `content-type` describe this POST,\n * not the page request.\n */\n forwardHeaders?: string[]\n /** Defaults to 30s. A render blocked on a host that never answers is a hung request. */\n timeoutMs?: number\n /** Injectable for tests and for a runtime whose fetch is not global. */\n fetch?: typeof fetch\n /**\n * What to do with whatever a reply reported as invalidated.\n *\n * Defaults to marking it on the engine, which is the only thing that makes\n * `Revalidate(ctx, \"orders\")` on the host side mean anything: an action's\n * answer carries the re-rendered region only if the target reached the\n * revalidation scope before the action returned. Without it a host reports\n * what it dirtied, nothing listens, and the browser is told nothing — the\n * page simply shows stale data with no error anywhere.\n */\n onRevalidate?: (targets: string[]) => void\n /**\n * Send calls issued in the same tick as one POST. On by default; a host\n * that does not understand the envelope is detected on the first batch and\n * sent single calls from then on. `false` never batches.\n */\n batch?: boolean\n}\n\nconst DEFAULT_FORWARDED = ['cookie', 'authorization']\n\nexport interface HostCallReply {\n result?: unknown\n error?: string\n revalidate?: string[]\n /**\n * Field name to messages, when the host refused the input.\n *\n * The same shape everything else here already uses: Laravel's own\n * `$e->errors()`, the socket protocol's `validation_errors`, and what\n * `issuesToErrors` turns a Standard Schema result into. Dot-joined for a\n * nested field, the empty string for a message about the form rather than\n * any one field.\n */\n validationErrors?: Record<string, string[]>\n /** The caller has no session. Becomes the engine's own authentication error. */\n unauthenticated?: boolean\n /** The caller has a session and still may not. */\n unauthorized?: boolean\n /**\n * Where the host says this request should go instead.\n *\n * Answered with a 200 and this field, never as a 3xx: fetch follows a\n * redirect transparently, so a real one would send the host call itself to\n * the destination and hand whatever came back to the render as the\n * function's result.\n */\n redirect?: string\n /** The status to redirect with. Defaults to 307, which preserves the method. */\n redirectStatus?: number\n /**\n * The status a refusal should be answered with.\n *\n * A middleware that aborted meant what it aborted with — throttle answers\n * 429, a signed-url check 403 — and collapsing those to 500 makes a\n * rate-limited visitor indistinguishable from a broken server.\n */\n refusalStatus?: number\n}\n\n/**\n * A batch on the wire: several calls in one POST, answered in order.\n *\n * Calls issued in the same tick of a render - sibling components each\n * awaiting rpc() - travel together, so a page's parallel reads cost the host\n * one request rather than one each. A host that has never heard of the\n * envelope answers it as a malformed single call, and the calls are sent one\n * at a time from then on; nothing is lost but the saving.\n */\nexport interface HostCallBatch {\n calls: { function: string; args: unknown[] }[]\n}\n\nexport interface HostCallBatchReply {\n /** One per call, in order. Each carries the status that call would have had. */\n replies: (HostCallReply & { status?: number })[]\n}\n\n/**\n * A batch answered as it goes: one line per call, each as the host finishes\n * it, in whatever order that is.\n *\n * `application/x-ndjson`, each line a reply with the call's `index` in the\n * batch. A host that answers this way lets a fast call resolve while a slow\n * sibling is still running - which is what keeps a page's boundaries\n * streaming independently when their reads travelled together. A host that\n * answers the whole batch at once, as one JSON object of `replies`, is read\n * as before; the saving of the batch stays, the independence does not.\n */\nexport type HostCallBatchLine = HostCallReply & { index: number; status?: number }\n\n/** How many calls one POST carries at most. */\nconst BATCH_LIMIT = 50\n\ntype Settled = { status: number; reply: HostCallReply | null; text: string }\n\ninterface Pending {\n name: string\n args: unknown[]\n resolve: (settled: Settled) => void\n reject: (error: unknown) => void\n}\n\ninterface Bucket {\n headers: Record<string, string>\n calls: Pending[]\n}\n\n// After the current I/O, before the next timer: what a render issued\n// synchronously - and across the microtasks between one component's awaits -\n// is in the bucket by then. setImmediate where the runtime has it, a zero\n// timer where it does not (a Worker).\nconst nextTick: (fn: () => void) => void =\n typeof setImmediate === 'function' ? (fn) => setImmediate(fn) : (fn) => setTimeout(fn, 0)\n\n/**\n * The function to hand to `installHostFn`, or to `hostCalls` on the JS host.\n */\nexport function httpHostCalls(\n options: HttpHostCallsOptions,\n): (name: string, ...args: unknown[]) => Promise<unknown> {\n const {\n endpoint,\n secret,\n forwardHeaders = DEFAULT_FORWARDED,\n timeoutMs = 30_000,\n fetch: fetchImpl,\n onRevalidate,\n batch = true,\n } = options\n\n if (!secret) {\n throw new Error('httpHostCalls requires a secret — see the note on the option.')\n }\n\n const forwarded = forwardHeaders.map((name) => name.toLowerCase())\n\n // Off for good the first time the host answers a batch as something else.\n let batching = batch\n\n // One bucket per set of forwarded headers: two visitors' renders in flight\n // at once must not share a request, because the host reads the cookie off\n // the request to know whose session a call runs under.\n const buckets = new Map<string, Bucket>()\n\n async function forwardedHeaders(): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'x-rsc-host-secret': secret,\n }\n\n // Outside a render — a prerender pass, or a host calling one directly —\n // there is no request to forward from, and that is not an error. The call\n // simply carries no session, which is exactly what a build-time render\n // should be doing.\n //\n // Only that one condition is swallowed. A blanket catch here is the wrong\n // shape: anything else going wrong while reading the request would come\n // out as a call with no session, which is not a failure the caller sees —\n // it is the visitor silently becoming anonymous, and the page rendering as\n // though they were logged out.\n try {\n const from = await incomingHeaders()\n\n for (const key of forwarded) {\n const value = from.get(key)\n if (value !== null) headers[key] = value\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n\n if (!message.startsWith('No request in scope')) throw error\n }\n\n return headers\n }\n\n /** One POST. `label` names what is being sent, for the error messages. */\n async function post(\n body: unknown,\n headers: Record<string, string>,\n label: string,\n ): Promise<{ status: number; text: string }> {\n const response = await send(body, headers, label)\n\n // Read the body before branching on status: a host that reports the error\n // in JSON with a 500 is saying something more useful than \"500\", and\n // throwing on the status alone discards it.\n return { status: response.status, text: await response.text() }\n }\n\n /** The POST itself, headers in hand, body still to read. */\n async function send(body: unknown, headers: Record<string, string>, label: string): Promise<Response> {\n const doFetch = fetchImpl ?? globalThis.fetch\n\n // AbortSignal.timeout is not on every runtime this engine targets, so the\n // controller is written out rather than assumed.\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n let response: Response\n\n try {\n response = await doFetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`Host call ${label} timed out after ${timeoutMs}ms`)\n }\n\n throw new Error(\n `Host call ${label} could not reach the host at ${endpoint}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n )\n } finally {\n clearTimeout(timer)\n }\n\n return response\n }\n\n function parse(text: string): HostCallReply | null {\n try {\n return text ? (JSON.parse(text) as HostCallReply) : null\n } catch {\n return null\n }\n }\n\n async function single(name: string, args: unknown[], headers: Record<string, string>): Promise<Settled> {\n const { status, text } = await post({ function: name, args }, headers, JSON.stringify(name))\n\n return { status, reply: parse(text), text }\n }\n\n /** Read a streamed batch, one reply per line, resolving each call as its line lands. */\n async function resolveAsLinesArrive(body: ReadableStream<Uint8Array>, calls: Pending[]): Promise<void> {\n const answered = new Set<number>()\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffered = ''\n\n const take = (line: string) => {\n const trimmed = line.trim()\n\n if (!trimmed) return\n\n let parsed: Partial<HostCallBatchLine> | null\n\n try {\n parsed = JSON.parse(trimmed) as Partial<HostCallBatchLine>\n } catch {\n return\n }\n\n const index = parsed?.index\n\n if (typeof index !== 'number' || !calls[index] || answered.has(index)) return\n\n const { index: _, status: own, ...reply } = parsed as HostCallBatchLine\n\n answered.add(index)\n calls[index]!.resolve({ status: own ?? 200, reply, text: JSON.stringify(reply) })\n }\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n\n if (done) break\n\n buffered += decoder.decode(value, { stream: true })\n\n let at: number\n\n while ((at = buffered.indexOf('\\n')) !== -1) {\n take(buffered.slice(0, at))\n buffered = buffered.slice(at + 1)\n }\n }\n\n buffered += decoder.decode()\n take(buffered)\n } catch (error) {\n for (const [i, call] of calls.entries()) {\n if (!answered.has(i)) call.reject(error)\n }\n\n return\n }\n\n // The host closed the batch with a call unanswered: a fault on its side,\n // reported to the call rather than left pending forever.\n for (const [i, call] of calls.entries()) {\n if (!answered.has(i)) {\n call.reject(new Error(`Host call ${JSON.stringify(call.name)} was not answered in its batch`))\n }\n }\n }\n\n /**\n * Send a bucket. One call goes as itself, so a host that speaks only the\n * single shape - or a request that happened to be alone - sees nothing\n * new on the wire.\n */\n async function flush(bucket: Bucket): Promise<void> {\n const { headers, calls } = bucket\n\n if (calls.length === 1) {\n const [only] = calls\n\n try {\n only.resolve(await single(only.name, only.args, headers))\n } catch (error) {\n only.reject(error)\n }\n\n return\n }\n\n const label = `batch of ${calls.length} (${calls.map((c) => c.name).join(', ')})`\n let response: Response\n\n try {\n response = await send(\n { calls: calls.map((c) => ({ function: c.name, args: c.args })) } satisfies HostCallBatch,\n headers,\n label,\n )\n } catch (error) {\n // The host could not be reached, or did not answer in time. Not\n // re-sent one by one: the calls may have run, and an action run twice\n // is worse than one reported as failed.\n for (const call of calls) call.reject(error)\n\n return\n }\n\n // Answered as it goes: each call resolves the moment its line arrives,\n // so a component waiting on a fast read paints while a slow sibling's\n // is still running. The batch saved the round trips; this keeps the\n // streaming the batch would otherwise have cost.\n if (response.status < 400 && (response.headers.get('content-type') ?? '').includes('x-ndjson') && response.body) {\n await resolveAsLinesArrive(response.body, calls)\n\n return\n }\n\n const status = response.status\n const text = await response.text()\n const parsed = parse(text) as Partial<HostCallBatchReply> | null\n const replies = parsed?.replies\n\n if (status < 400 && Array.isArray(replies) && replies.length === calls.length) {\n calls.forEach((call, i) => {\n const { status: own, ...reply } = replies[i]!\n\n call.resolve({ status: own ?? 200, reply, text: JSON.stringify(reply) })\n })\n\n return\n }\n\n // Not a batch answer: a host that does not know the envelope refused it\n // as one malformed call, before running anything. From here on, one at a\n // time - and these, now.\n batching = false\n\n await Promise.all(\n calls.map(async (call) => {\n try {\n call.resolve(await single(call.name, call.args, headers))\n } catch (error) {\n call.reject(error)\n }\n }),\n )\n }\n\n function enqueue(name: string, args: unknown[], headers: Record<string, string>): Promise<Settled> {\n return new Promise<Settled>((resolve, reject) => {\n const key = JSON.stringify(headers)\n let bucket = buckets.get(key)\n\n if (!bucket) {\n bucket = { headers, calls: [] }\n buckets.set(key, bucket)\n\n const mine = bucket\n\n nextTick(() => {\n if (buckets.get(key) === mine) buckets.delete(key)\n\n void flush(mine)\n })\n }\n\n bucket.calls.push({ name, args, resolve, reject })\n\n if (bucket.calls.length >= BATCH_LIMIT) {\n buckets.delete(key)\n\n void flush(bucket)\n }\n })\n }\n\n /**\n * What a reply means, in the caller's own async context.\n *\n * Deliberately not done where the response arrives: a batch is answered in\n * a timer, outside every caller's request scope, and `redirect()` and\n * `revalidate()` both write to that scope. Interpreting here, after the\n * caller's await resumed, puts each reply back inside the render it belongs\n * to.\n */\n function interpret(name: string, { status, reply, text }: Settled): unknown {\n // Refusing the input is not the call failing — it is the call answering.\n //\n // Thrown rather than returned, so a handler stops where it is instead of\n // carrying on with data the host rejected. createActionClient catches this\n // on the way out and returns { validationErrors }, which is the shape\n // useForm reads: React serialises a REJECTED server action opaquely, so a\n // validation error that stays thrown reaches the browser as \"an error\n // occurred\" with every field it named gone.\n //\n // Checked before `error`, so a host that sends both is read as a refusal\n // rather than as a failure with no fields.\n if (reply?.validationErrors) {\n throw new ActionValidationError(reply.validationErrors)\n }\n\n // Raised as the engine's own redirect, so it travels the path every other\n // redirect travels — a real 3xx above a Suspense boundary, the digest\n // below one — rather than becoming an error the page has to interpret.\n if (reply?.redirect) {\n redirect(reply.redirect as never, reply.redirectStatus ?? 307)\n }\n\n if (reply?.unauthenticated) {\n throw new ServerAuthenticationError(reply.error ?? 'Unauthenticated.')\n }\n\n if (reply?.unauthorized) {\n throw new ServerAuthorizationError(reply.error ?? 'This action is unauthorized.')\n }\n\n // The backend says there is no such thing - Go's Refuse(404), Laravel's\n // abort(404), a record this caller cannot see. Raised as the engine's\n // own notFound(), so the page answers with not-found.tsx and a 404,\n // exactly as a component calling notFound() would; as an error it\n // reached the page as \"something went wrong\".\n if (reply?.refusalStatus === 404) notFound()\n\n if (reply?.error !== undefined) {\n const failure = new Error(`Host call ${JSON.stringify(name)} failed: ${reply.error}`)\n\n // Carried on the error rather than thrown as another class: the host\n // chose a status and the only job here is not to lose it on the way to\n // whoever writes the response.\n if (reply.refusalStatus) {\n ;(failure as Error & { refusalStatus?: number }).refusalStatus = reply.refusalStatus\n }\n\n throw failure\n }\n\n if (status >= 400) {\n throw new Error(\n `Host call ${JSON.stringify(name)} failed: ${status}`.trim() +\n (text ? ` — ${text.slice(0, 200)}` : ''),\n )\n }\n\n if (reply === null) {\n throw new Error(\n `Host call ${JSON.stringify(name)} returned a body that is not JSON: ${text.slice(0, 200)}`,\n )\n }\n\n if (reply.revalidate?.length) {\n if (onRevalidate) onRevalidate(reply.revalidate)\n // Named by the host over the wire - Rsc::revalidate('orders') in PHP -\n // so nothing here can check it; the renderer refuses an unknown name.\n else for (const target of reply.revalidate) revalidate(target as RevalidateTarget)\n }\n\n return reply.result ?? null\n }\n\n return async function hostCall(name: string, ...args: unknown[]): Promise<unknown> {\n const headers = await forwardedHeaders()\n const settled = batching ? await enqueue(name, args, headers) : await single(name, args, headers)\n\n return interpret(name, settled)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hostCalls.js","sourceRoot":"","sources":["../src/hostCalls.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,EAAE;AACF,yEAAyE;AACzE,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,uDAAuD;AACvD,EAAE;AACF,0EAA0E;AAC1E,+EAA+E;AAC/E,4EAA4E;AAC5E,+DAA+D;AAE/D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,cAAc,CAAA;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAE5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAA;AACpF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AED,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CACb,aAAa,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,sCAAsC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAC5F,CAAA;QACH,CAAC;QAED,IAAI,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,CAAC;YAC7B,IAAI,YAAY;gBAAE,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;YAChD,uEAAuE;YACvE,sEAAsE;;gBACjE,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,UAAU;oBAAE,UAAU,CAAC,MAA0B,CAAC,CAAA;QACpF,CAAC;QAED,OAAO,KAAK,CAAC,MAAM,IAAI,IAAI,CAAA;IAC7B,CAAC;IAED,OAAO,KAAK,UAAU,QAAQ,CAAC,IAAY,EAAE,GAAG,IAAe;QAC7D,MAAM,OAAO,GAAG,MAAM,gBAAgB,EAAE,CAAA;QACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QAEjG,OAAO,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACjC,CAAC,CAAA;AACH,CAAC","sourcesContent":["// Host calls over HTTP, so a host in any language can answer them.\n//\n// A server component writing `await rpc('Orders.recent')` needs the host\n// mid-render. The Laravel path answers on a second unix socket with its own\n// framing (PROTOCOL.md, \"The callback channel\"), which every non-JS host has\n// to reimplement before it can render a single page that fetches anything.\n// This is the same conversation over an ordinary POST.\n//\n// The transport is the only thing that changes. The engine still sees one\n// function, the deferred-release ordering in streaming.ts still applies, and a\n// reply may still carry `revalidate` — a Go host that answers this endpoint\n// gets the same semantics the socket has, without the framing.\n\nimport { headers as incomingHeaders } from './request.js'\nimport { revalidate } from './revalidate.js'\nimport type { RevalidateTarget } from './routes.js'\nimport { ActionValidationError } from './action.js'\nimport { redirect } from './redirect.js'\nimport { ServerAuthenticationError, ServerAuthorizationError } from './js/errors.js'\nimport { notFound } from './notFound.js'\n\nexport interface HttpHostCallsOptions {\n /**\n * Where calls are POSTed. A loopback address or a unix socket url — see the\n * note on `secret` for why this must not be a public one.\n */\n endpoint: string\n /**\n * Sent as `X-RSC-Host-Secret`, and required rather than optional.\n *\n * This endpoint runs functions by name on behalf of a render. PROTOCOL.md\n * Part 3b draws the line at client-supplied input deciding what RUNS, and an\n * unauthenticated callback endpoint is on the wrong side of it: anyone who\n * can reach it can invoke any registered host function directly, with\n * whatever arguments they like and none of the app's routing in front. A\n * default of \"off\" would be the kind that ships.\n */\n secret: string\n /**\n * Request headers copied from the render's own request onto the call.\n *\n * This is what makes a host call run as the person browsing: the backend's\n * session middleware reads its cookie and finds the same user. Nothing else\n * is forwarded, because everything else is either meaningless to the backend\n * or actively wrong — `content-length` and `content-type` describe this POST,\n * not the page request.\n */\n forwardHeaders?: string[]\n /** Defaults to 30s. A render blocked on a host that never answers is a hung request. */\n timeoutMs?: number\n /** Injectable for tests and for a runtime whose fetch is not global. */\n fetch?: typeof fetch\n /**\n * What to do with whatever a reply reported as invalidated.\n *\n * Defaults to marking it on the engine, which is the only thing that makes\n * `Revalidate(ctx, \"orders\")` on the host side mean anything: an action's\n * answer carries the re-rendered region only if the target reached the\n * revalidation scope before the action returned. Without it a host reports\n * what it dirtied, nothing listens, and the browser is told nothing — the\n * page simply shows stale data with no error anywhere.\n */\n onRevalidate?: (targets: string[]) => void\n /**\n * Send calls issued in the same tick as one POST. On by default; a host\n * that does not understand the envelope is detected on the first batch and\n * sent single calls from then on. `false` never batches.\n */\n batch?: boolean\n}\n\nconst DEFAULT_FORWARDED = ['cookie', 'authorization']\n\nexport interface HostCallReply {\n result?: unknown\n error?: string\n revalidate?: string[]\n /**\n * Field name to messages, when the host refused the input.\n *\n * The same shape everything else here already uses: Laravel's own\n * `$e->errors()`, the socket protocol's `validation_errors`, and what\n * `issuesToErrors` turns a Standard Schema result into. Dot-joined for a\n * nested field, the empty string for a message about the form rather than\n * any one field.\n */\n validationErrors?: Record<string, string[]>\n /** The caller has no session. Becomes the engine's own authentication error. */\n unauthenticated?: boolean\n /** The caller has a session and still may not. */\n unauthorized?: boolean\n /**\n * Where the host says this request should go instead.\n *\n * Answered with a 200 and this field, never as a 3xx: fetch follows a\n * redirect transparently, so a real one would send the host call itself to\n * the destination and hand whatever came back to the render as the\n * function's result.\n */\n redirect?: string\n /**\n * Where an unexpected failure happened in the backend, sent only in\n * development (Laravel's app.debug, Go's CallbackHandler.Debug): the\n * thrown type, its message, and frames newest first.\n */\n debug?: { type?: string; message?: string; trace?: string[] }\n /** The status to redirect with. Defaults to 307, which preserves the method. */\n redirectStatus?: number\n /**\n * The status a refusal should be answered with.\n *\n * A middleware that aborted meant what it aborted with — throttle answers\n * 429, a signed-url check 403 — and collapsing those to 500 makes a\n * rate-limited visitor indistinguishable from a broken server.\n */\n refusalStatus?: number\n}\n\n/**\n * A batch on the wire: several calls in one POST, answered in order.\n *\n * Calls issued in the same tick of a render - sibling components each\n * awaiting rpc() - travel together, so a page's parallel reads cost the host\n * one request rather than one each. A host that has never heard of the\n * envelope answers it as a malformed single call, and the calls are sent one\n * at a time from then on; nothing is lost but the saving.\n */\nexport interface HostCallBatch {\n calls: { function: string; args: unknown[] }[]\n}\n\nexport interface HostCallBatchReply {\n /** One per call, in order. Each carries the status that call would have had. */\n replies: (HostCallReply & { status?: number })[]\n}\n\n/**\n * A batch answered as it goes: one line per call, each as the host finishes\n * it, in whatever order that is.\n *\n * `application/x-ndjson`, each line a reply with the call's `index` in the\n * batch. A host that answers this way lets a fast call resolve while a slow\n * sibling is still running - which is what keeps a page's boundaries\n * streaming independently when their reads travelled together. A host that\n * answers the whole batch at once, as one JSON object of `replies`, is read\n * as before; the saving of the batch stays, the independence does not.\n */\nexport type HostCallBatchLine = HostCallReply & { index: number; status?: number }\n\n/** How many calls one POST carries at most. */\nconst BATCH_LIMIT = 50\n\ntype Settled = { status: number; reply: HostCallReply | null; text: string }\n\ninterface Pending {\n name: string\n args: unknown[]\n resolve: (settled: Settled) => void\n reject: (error: unknown) => void\n}\n\ninterface Bucket {\n headers: Record<string, string>\n calls: Pending[]\n}\n\n// After the current I/O, before the next timer: what a render issued\n// synchronously - and across the microtasks between one component's awaits -\n// is in the bucket by then. setImmediate where the runtime has it, a zero\n// timer where it does not (a Worker).\nconst nextTick: (fn: () => void) => void =\n typeof setImmediate === 'function' ? (fn) => setImmediate(fn) : (fn) => setTimeout(fn, 0)\n\n/**\n * The function to hand to `installHostFn`, or to `hostCalls` on the JS host.\n */\n/**\n * The backend's trace, on the error the render sees.\n *\n * As its cause - an Error named for the backend's type, whose stack is the\n * backend's frames - so Node, Bun and the dev overlay print it under the\n * renderer's own stack; and appended to that stack, for whatever prints only\n * the one. Before this a failed rpc() pointed at a line of JavaScript, and the\n * PHP or Go that failed was a separate search through another log.\n */\nfunction withBackendTrace(failure: Error, debug: NonNullable<HostCallReply['debug']>): void {\n const frames = (debug.trace ?? []).map((frame) => ' at ' + frame).join('\\n')\n const cause = new Error(debug.message ?? '')\n\n cause.name = 'Backend ' + (debug.type ?? 'Error')\n cause.stack = cause.name + ': ' + (debug.message ?? '') + (frames ? '\\n' + frames : '')\n\n failure.cause = cause\n failure.stack = (failure.stack ?? String(failure)) + '\\nCaused in the backend by ' + cause.stack\n}\n\nexport function httpHostCalls(\n options: HttpHostCallsOptions,\n): (name: string, ...args: unknown[]) => Promise<unknown> {\n const {\n endpoint,\n secret,\n forwardHeaders = DEFAULT_FORWARDED,\n timeoutMs = 30_000,\n fetch: fetchImpl,\n onRevalidate,\n batch = true,\n } = options\n\n if (!secret) {\n throw new Error('httpHostCalls requires a secret — see the note on the option.')\n }\n\n const forwarded = forwardHeaders.map((name) => name.toLowerCase())\n\n // Off for good the first time the host answers a batch as something else.\n let batching = batch\n\n // One bucket per set of forwarded headers: two visitors' renders in flight\n // at once must not share a request, because the host reads the cookie off\n // the request to know whose session a call runs under.\n const buckets = new Map<string, Bucket>()\n\n async function forwardedHeaders(): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'x-rsc-host-secret': secret,\n }\n\n // Outside a render — a prerender pass, or a host calling one directly —\n // there is no request to forward from, and that is not an error. The call\n // simply carries no session, which is exactly what a build-time render\n // should be doing.\n //\n // Only that one condition is swallowed. A blanket catch here is the wrong\n // shape: anything else going wrong while reading the request would come\n // out as a call with no session, which is not a failure the caller sees —\n // it is the visitor silently becoming anonymous, and the page rendering as\n // though they were logged out.\n try {\n const from = await incomingHeaders()\n\n for (const key of forwarded) {\n const value = from.get(key)\n if (value !== null) headers[key] = value\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n\n if (!message.startsWith('No request in scope')) throw error\n }\n\n return headers\n }\n\n /** One POST. `label` names what is being sent, for the error messages. */\n async function post(\n body: unknown,\n headers: Record<string, string>,\n label: string,\n ): Promise<{ status: number; text: string }> {\n const response = await send(body, headers, label)\n\n // Read the body before branching on status: a host that reports the error\n // in JSON with a 500 is saying something more useful than \"500\", and\n // throwing on the status alone discards it.\n return { status: response.status, text: await response.text() }\n }\n\n /** The POST itself, headers in hand, body still to read. */\n async function send(body: unknown, headers: Record<string, string>, label: string): Promise<Response> {\n const doFetch = fetchImpl ?? globalThis.fetch\n\n // AbortSignal.timeout is not on every runtime this engine targets, so the\n // controller is written out rather than assumed.\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n let response: Response\n\n try {\n response = await doFetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`Host call ${label} timed out after ${timeoutMs}ms`)\n }\n\n throw new Error(\n `Host call ${label} could not reach the host at ${endpoint}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n )\n } finally {\n clearTimeout(timer)\n }\n\n return response\n }\n\n function parse(text: string): HostCallReply | null {\n try {\n return text ? (JSON.parse(text) as HostCallReply) : null\n } catch {\n return null\n }\n }\n\n async function single(name: string, args: unknown[], headers: Record<string, string>): Promise<Settled> {\n const { status, text } = await post({ function: name, args }, headers, JSON.stringify(name))\n\n return { status, reply: parse(text), text }\n }\n\n /** Read a streamed batch, one reply per line, resolving each call as its line lands. */\n async function resolveAsLinesArrive(body: ReadableStream<Uint8Array>, calls: Pending[]): Promise<void> {\n const answered = new Set<number>()\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffered = ''\n\n const take = (line: string) => {\n const trimmed = line.trim()\n\n if (!trimmed) return\n\n let parsed: Partial<HostCallBatchLine> | null\n\n try {\n parsed = JSON.parse(trimmed) as Partial<HostCallBatchLine>\n } catch {\n return\n }\n\n const index = parsed?.index\n\n if (typeof index !== 'number' || !calls[index] || answered.has(index)) return\n\n const { index: _, status: own, ...reply } = parsed as HostCallBatchLine\n\n answered.add(index)\n calls[index]!.resolve({ status: own ?? 200, reply, text: JSON.stringify(reply) })\n }\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n\n if (done) break\n\n buffered += decoder.decode(value, { stream: true })\n\n let at: number\n\n while ((at = buffered.indexOf('\\n')) !== -1) {\n take(buffered.slice(0, at))\n buffered = buffered.slice(at + 1)\n }\n }\n\n buffered += decoder.decode()\n take(buffered)\n } catch (error) {\n for (const [i, call] of calls.entries()) {\n if (!answered.has(i)) call.reject(error)\n }\n\n return\n }\n\n // The host closed the batch with a call unanswered: a fault on its side,\n // reported to the call rather than left pending forever.\n for (const [i, call] of calls.entries()) {\n if (!answered.has(i)) {\n call.reject(new Error(`Host call ${JSON.stringify(call.name)} was not answered in its batch`))\n }\n }\n }\n\n /**\n * Send a bucket. One call goes as itself, so a host that speaks only the\n * single shape - or a request that happened to be alone - sees nothing\n * new on the wire.\n */\n async function flush(bucket: Bucket): Promise<void> {\n const { headers, calls } = bucket\n\n if (calls.length === 1) {\n const [only] = calls\n\n try {\n only.resolve(await single(only.name, only.args, headers))\n } catch (error) {\n only.reject(error)\n }\n\n return\n }\n\n const label = `batch of ${calls.length} (${calls.map((c) => c.name).join(', ')})`\n let response: Response\n\n try {\n response = await send(\n { calls: calls.map((c) => ({ function: c.name, args: c.args })) } satisfies HostCallBatch,\n headers,\n label,\n )\n } catch (error) {\n // The host could not be reached, or did not answer in time. Not\n // re-sent one by one: the calls may have run, and an action run twice\n // is worse than one reported as failed.\n for (const call of calls) call.reject(error)\n\n return\n }\n\n // Answered as it goes: each call resolves the moment its line arrives,\n // so a component waiting on a fast read paints while a slow sibling's\n // is still running. The batch saved the round trips; this keeps the\n // streaming the batch would otherwise have cost.\n if (response.status < 400 && (response.headers.get('content-type') ?? '').includes('x-ndjson') && response.body) {\n await resolveAsLinesArrive(response.body, calls)\n\n return\n }\n\n const status = response.status\n const text = await response.text()\n const parsed = parse(text) as Partial<HostCallBatchReply> | null\n const replies = parsed?.replies\n\n if (status < 400 && Array.isArray(replies) && replies.length === calls.length) {\n calls.forEach((call, i) => {\n const { status: own, ...reply } = replies[i]!\n\n call.resolve({ status: own ?? 200, reply, text: JSON.stringify(reply) })\n })\n\n return\n }\n\n // Not a batch answer: a host that does not know the envelope refused it\n // as one malformed call, before running anything. From here on, one at a\n // time - and these, now.\n batching = false\n\n await Promise.all(\n calls.map(async (call) => {\n try {\n call.resolve(await single(call.name, call.args, headers))\n } catch (error) {\n call.reject(error)\n }\n }),\n )\n }\n\n function enqueue(name: string, args: unknown[], headers: Record<string, string>): Promise<Settled> {\n return new Promise<Settled>((resolve, reject) => {\n const key = JSON.stringify(headers)\n let bucket = buckets.get(key)\n\n if (!bucket) {\n bucket = { headers, calls: [] }\n buckets.set(key, bucket)\n\n const mine = bucket\n\n nextTick(() => {\n if (buckets.get(key) === mine) buckets.delete(key)\n\n void flush(mine)\n })\n }\n\n bucket.calls.push({ name, args, resolve, reject })\n\n if (bucket.calls.length >= BATCH_LIMIT) {\n buckets.delete(key)\n\n void flush(bucket)\n }\n })\n }\n\n /**\n * What a reply means, in the caller's own async context.\n *\n * Deliberately not done where the response arrives: a batch is answered in\n * a timer, outside every caller's request scope, and `redirect()` and\n * `revalidate()` both write to that scope. Interpreting here, after the\n * caller's await resumed, puts each reply back inside the render it belongs\n * to.\n */\n function interpret(name: string, { status, reply, text }: Settled): unknown {\n // Refusing the input is not the call failing — it is the call answering.\n //\n // Thrown rather than returned, so a handler stops where it is instead of\n // carrying on with data the host rejected. createActionClient catches this\n // on the way out and returns { validationErrors }, which is the shape\n // useForm reads: React serialises a REJECTED server action opaquely, so a\n // validation error that stays thrown reaches the browser as \"an error\n // occurred\" with every field it named gone.\n //\n // Checked before `error`, so a host that sends both is read as a refusal\n // rather than as a failure with no fields.\n if (reply?.validationErrors) {\n throw new ActionValidationError(reply.validationErrors)\n }\n\n // Raised as the engine's own redirect, so it travels the path every other\n // redirect travels — a real 3xx above a Suspense boundary, the digest\n // below one — rather than becoming an error the page has to interpret.\n if (reply?.redirect) {\n redirect(reply.redirect as never, reply.redirectStatus ?? 307)\n }\n\n if (reply?.unauthenticated) {\n throw new ServerAuthenticationError(reply.error ?? 'Unauthenticated.')\n }\n\n if (reply?.unauthorized) {\n throw new ServerAuthorizationError(reply.error ?? 'This action is unauthorized.')\n }\n\n // The backend says there is no such thing - Go's Refuse(404), Laravel's\n // abort(404), a record this caller cannot see. Raised as the engine's\n // own notFound(), so the page answers with not-found.tsx and a 404,\n // exactly as a component calling notFound() would; as an error it\n // reached the page as \"something went wrong\".\n if (reply?.refusalStatus === 404) notFound()\n\n if (reply?.error !== undefined) {\n const failure = new Error(`Host call ${JSON.stringify(name)} failed: ${reply.error}`)\n\n // Carried on the error rather than thrown as another class: the host\n // chose a status and the only job here is not to lose it on the way to\n // whoever writes the response.\n if (reply.refusalStatus) {\n ;(failure as Error & { refusalStatus?: number }).refusalStatus = reply.refusalStatus\n }\n\n if (reply.debug) withBackendTrace(failure, reply.debug)\n\n throw failure\n }\n\n if (status >= 400) {\n throw new Error(\n `Host call ${JSON.stringify(name)} failed: ${status}`.trim() +\n (text ? ` — ${text.slice(0, 200)}` : ''),\n )\n }\n\n if (reply === null) {\n throw new Error(\n `Host call ${JSON.stringify(name)} returned a body that is not JSON: ${text.slice(0, 200)}`,\n )\n }\n\n if (reply.revalidate?.length) {\n if (onRevalidate) onRevalidate(reply.revalidate)\n // Named by the host over the wire - Rsc::revalidate('orders') in PHP -\n // so nothing here can check it; the renderer refuses an unknown name.\n else for (const target of reply.revalidate) revalidate(target as RevalidateTarget)\n }\n\n return reply.result ?? null\n }\n\n return async function hostCall(name: string, ...args: unknown[]): Promise<unknown> {\n const headers = await forwardedHeaders()\n const settled = batching ? await enqueue(name, args, headers) : await single(name, args, headers)\n\n return interpret(name, settled)\n }\n}\n"]}
|
package/dist/testHost.d.ts
CHANGED
|
@@ -10,18 +10,49 @@ export interface HostCallInput {
|
|
|
10
10
|
}
|
|
11
11
|
/** Answers one function. Return a value for its result, or one of `hostReply`'s answers. */
|
|
12
12
|
export type HostHandler = (call: HostCallInput) => unknown;
|
|
13
|
+
type Reply = Omit<HostCallReply, 'result'> & {
|
|
14
|
+
[REPLY]: true;
|
|
15
|
+
};
|
|
16
|
+
/** One of the protocol's own answers, from `hostReply`. */
|
|
17
|
+
export type HostReply = Reply;
|
|
18
|
+
declare global {
|
|
19
|
+
/**
|
|
20
|
+
* The backend's functions, as the build read them from rsc-host.json:
|
|
21
|
+
* each one's arguments and result. Written into .rsc-kit/rsc-env.d.ts;
|
|
22
|
+
* empty without a manifest.
|
|
23
|
+
*/
|
|
24
|
+
interface RscHostFunctions {
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
type Answer<T> = T | HostReply | Promise<T | HostReply>;
|
|
28
|
+
type Guards = {
|
|
29
|
+
[HOST_MIDDLEWARE]?: (call: {
|
|
30
|
+
args: [names: string[]];
|
|
31
|
+
headers: Headers;
|
|
32
|
+
}) => Answer<true>;
|
|
33
|
+
};
|
|
13
34
|
/**
|
|
14
35
|
* The backend's functions, by the name rpc() calls them with.
|
|
15
36
|
*
|
|
37
|
+
* Typed from the app's rsc-host.json when it has one: a handler may only
|
|
38
|
+
* answer for a function the backend has, is given its arguments, and returns
|
|
39
|
+
* its result or one of `hostReply`'s answers - never a shape the backend
|
|
40
|
+
* would not send, which is how a fake drifts from the real thing while its
|
|
41
|
+
* tests stay green. Without a manifest, any name and any value.
|
|
42
|
+
*
|
|
16
43
|
* Route guards declared for the host are asked as `__rsc.middleware`
|
|
17
44
|
* (`HOST_MIDDLEWARE`), with the guard names as the first argument; answer
|
|
18
|
-
* `true` to let the page render.
|
|
19
|
-
* answer would.
|
|
45
|
+
* `true` to let the page render.
|
|
20
46
|
*/
|
|
21
|
-
export type TestHost = Record<string, HostHandler
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
47
|
+
export type TestHost = [keyof RscHostFunctions] extends [never] ? Record<string, HostHandler> : {
|
|
48
|
+
[K in keyof RscHostFunctions]?: RscHostFunctions[K] extends {
|
|
49
|
+
args: infer A extends unknown[];
|
|
50
|
+
result: infer R;
|
|
51
|
+
} ? (call: {
|
|
52
|
+
args: A;
|
|
53
|
+
headers: Headers;
|
|
54
|
+
}) => Answer<R> : never;
|
|
55
|
+
} & Guards;
|
|
25
56
|
/**
|
|
26
57
|
* The protocol's own answers, for a handler to return.
|
|
27
58
|
*
|
|
@@ -42,6 +73,8 @@ export declare const hostReply: {
|
|
|
42
73
|
readonly refuse: (status: number, message?: string) => Reply;
|
|
43
74
|
/** The input was refused, by field: an action returns these as validationErrors. */
|
|
44
75
|
readonly invalid: (errors: Record<string, string[]>) => Reply;
|
|
76
|
+
/** An unexpected failure, as an adapter answers a crash: an error, not a refusal. */
|
|
77
|
+
readonly fail: (message?: string) => Reply;
|
|
45
78
|
/** A result, and the regions of the page the call says it changed. */
|
|
46
79
|
readonly revalidating: (result: unknown, ...targets: string[]) => Reply;
|
|
47
80
|
};
|
package/dist/testHost.js
CHANGED
|
@@ -29,6 +29,8 @@ export const hostReply = {
|
|
|
29
29
|
refuse: (status, message = 'Refused.') => reply({ error: message, refusalStatus: status }),
|
|
30
30
|
/** The input was refused, by field: an action returns these as validationErrors. */
|
|
31
31
|
invalid: (errors) => reply({ validationErrors: errors }),
|
|
32
|
+
/** An unexpected failure, as an adapter answers a crash: an error, not a refusal. */
|
|
33
|
+
fail: (message = 'Something went wrong.') => reply({ error: message }),
|
|
32
34
|
/** A result, and the regions of the page the call says it changed. */
|
|
33
35
|
revalidating: (result, ...targets) => reply({ result, revalidate: targets }),
|
|
34
36
|
};
|
package/dist/testHost.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testHost.js","sourceRoot":"","sources":["../src/testHost.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+DAA+D;AAC/D,EAAE;AACF,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,yDAAyD;AAIzD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAA;AAEnD,4DAA4D;AAC5D,MAAM,CAAC,MAAM,eAAe,GAAG,kBAAkB,CAAA;
|
|
1
|
+
{"version":3,"file":"testHost.js","sourceRoot":"","sources":["../src/testHost.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+DAA+D;AAC/D,EAAE;AACF,yEAAyE;AACzE,2EAA2E;AAC3E,4EAA4E;AAC5E,yDAAyD;AAIzD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAA;AAEnD,4DAA4D;AAC5D,MAAM,CAAC,MAAM,eAAe,GAAG,kBAAkB,CAAA;AAsDjD,MAAM,KAAK,GAAG,CAAC,MAAiC,EAAS,EAAE,CAAC,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAA;AAE1F;;;;;;;;GAQG;AACH,MAAM,CAAC,MA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,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE,EAAE,CAAC,CAAA;QAE1F,IAAI,OAAO,IAAI,IAAI,EAAE,CAAC;YACpB,OAAO,IAAI,CAAC;gBACV,OAAO,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;aACnG,CAAC,CAAA;QACJ,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAA;IAC1E,CAAC,CAAiB,CAAA;AACpB,CAAC","sourcesContent":["// A backend for tests: answers rpc() calls and host middleware the way a Go\n// or Laravel host answers them over HTTP, without one running.\n//\n// The app under test talks to it through the real client, httpHostCalls,\n// handed a fetch that answers in-process. So a test exercises what ships -\n// batching, a redirect raised as the engine's own, an unauthenticated reply\n// becoming a 401 - and only the backend is stood in for.\n\nimport type { HostCallReply } from './hostCalls.js'\n\nconst REPLY = Symbol.for('rsc-kit.test-host-reply')\n\n/** The name the engine asks a host's route guards under. */\nexport const HOST_MIDDLEWARE = '__rsc.middleware'\n\n/** What a test handler is given: the call's arguments, and the headers the renderer forwarded. */\nexport interface HostCallInput {\n args: unknown[]\n /** The visitor's request headers the renderer passed on - the cookie, the Accept-Language. */\n headers: Headers\n}\n\n/** Answers one function. Return a value for its result, or one of `hostReply`'s answers. */\nexport type HostHandler = (call: HostCallInput) => unknown\n\ntype Reply = Omit<HostCallReply, 'result'> & { [REPLY]: true }\n\n/** One of the protocol's own answers, from `hostReply`. */\nexport type HostReply = Reply\n\ndeclare global {\n /**\n * The backend's functions, as the build read them from rsc-host.json:\n * each one's arguments and result. Written into .rsc-kit/rsc-env.d.ts;\n * empty without a manifest.\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface RscHostFunctions {}\n}\n\ntype Answer<T> = T | HostReply | Promise<T | HostReply>\n\ntype Guards = {\n [HOST_MIDDLEWARE]?: (call: { args: [names: string[]]; headers: Headers }) => Answer<true>\n}\n\n/**\n * The backend's functions, by the name rpc() calls them with.\n *\n * Typed from the app's rsc-host.json when it has one: a handler may only\n * answer for a function the backend has, is given its arguments, and returns\n * its result or one of `hostReply`'s answers - never a shape the backend\n * would not send, which is how a fake drifts from the real thing while its\n * tests stay green. Without a manifest, any name and any value.\n *\n * Route guards declared for the host are asked as `__rsc.middleware`\n * (`HOST_MIDDLEWARE`), with the guard names as the first argument; answer\n * `true` to let the page render.\n */\nexport type TestHost = [keyof RscHostFunctions] extends [never]\n ? Record<string, HostHandler>\n : {\n [K in keyof RscHostFunctions]?: RscHostFunctions[K] extends { args: infer A extends unknown[]; result: infer R }\n ? (call: { args: A; headers: Headers }) => Answer<R>\n : never\n } & Guards\n\nconst reply = (fields: Omit<Reply, typeof REPLY>): Reply => ({ ...fields, [REPLY]: true })\n\n/**\n * The protocol's own answers, for a handler to return.\n *\n * host: {\n * 'Apps.list': ({ headers }) =>\n * headers.get('cookie')?.includes('session=') ? [{ id: 1 }] : hostReply.unauthenticated(),\n * 'Apps.create': ({ args }) => hostReply.invalid({ name: ['Taken.'] }),\n * }\n */\nexport const hostReply = {\n /** No session: the page answers 401, an action its auth error. */\n unauthenticated: (message?: string): Reply => reply({ unauthenticated: true, error: message }),\n /** A session that still may not: 403. */\n unauthorized: (message?: string): Reply => reply({ unauthorized: true, error: message }),\n /** Send the visitor somewhere else, as the host's redirect does. */\n redirect: (to: string, status = 307): Reply => reply({ redirect: to, redirectStatus: status }),\n /** Refuse with a status - a 404 for a record this caller cannot see, a 429. */\n refuse: (status: number, message = 'Refused.'): Reply => reply({ error: message, refusalStatus: status }),\n /** The input was refused, by field: an action returns these as validationErrors. */\n invalid: (errors: Record<string, string[]>): Reply => reply({ validationErrors: errors }),\n /** An unexpected failure, as an adapter answers a crash: an error, not a refusal. */\n fail: (message = 'Something went wrong.'): Reply => reply({ error: message }),\n /** A result, and the regions of the page the call says it changed. */\n revalidating: (result: unknown, ...targets: string[]): Reply =>\n reply({ result, revalidate: targets } as Omit<Reply, typeof REPLY>),\n} as const\n\nfunction isReply(value: unknown): value is Reply {\n return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[REPLY] === true\n}\n\nasync function answer(host: TestHost, name: string, args: unknown[], headers: Headers): Promise<HostCallReply> {\n const handler = host[name]\n\n // Fails the call rather than answering null: a function the test forgot\n // is a test that would otherwise pass against nothing.\n if (!handler) {\n return {\n error:\n name === HOST_MIDDLEWARE\n ? `the page asked its host guards (${JSON.stringify(args[0])}) and the test host has no \"${HOST_MIDDLEWARE}\" handler`\n : `the test host has no handler for ${JSON.stringify(name)}`,\n }\n }\n\n const value = await handler({ args, headers })\n\n if (isReply(value)) {\n const { [REPLY]: _, ...fields } = value\n\n return fields\n }\n\n return { result: value === undefined ? null : value }\n}\n\n/**\n * A fetch that answers the host-call endpoint from `host`: one call as\n * itself, a batch as `{ replies }`, in order.\n */\nexport function testHostFetch(host: TestHost): typeof fetch {\n return (async (_input: RequestInfo | URL, init?: RequestInit) => {\n const headers = new Headers(init?.headers)\n const body = JSON.parse(String(init?.body ?? '{}')) as\n | { function: string; args?: unknown[] }\n | { calls: { function: string; args?: unknown[] }[] }\n\n // The renderer's own headers are not the visitor's.\n headers.delete('x-rsc-host-secret')\n headers.delete('content-type')\n\n const json = (value: unknown) =>\n new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } })\n\n if ('calls' in body) {\n return json({\n replies: await Promise.all(body.calls.map((c) => answer(host, c.function, c.args ?? [], headers))),\n })\n }\n\n return json(await answer(host, body.function, body.args ?? [], headers))\n }) as typeof fetch\n}\n"]}
|
package/dist/typegen.d.ts
CHANGED
|
@@ -1,2 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Write the types; or, with `check`, say which committed generated files are
|
|
4
|
+
* not what the backend and the route tree produce now, and change nothing.
|
|
5
|
+
*
|
|
6
|
+
* For CI: `rsc-kit-typegen --check` fails when rsc-host.json or the types were
|
|
7
|
+
* committed and the backend has moved on since. Only files that were already
|
|
8
|
+
* there are compared - one that is not committed is written fresh by every
|
|
9
|
+
* build and cannot be stale - and every one is put back as it was.
|
|
10
|
+
*/
|
|
11
|
+
export declare function typegen(root?: string, check?: boolean): Promise<string[]>;
|
package/dist/typegen.js
CHANGED
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
// The app's own vite.config is loaded, through the app's own Vite, so the
|
|
11
11
|
// plugin's options - sourceDir, outDir, a host's route file - are the ones it
|
|
12
12
|
// builds with. Only the plugin's config step runs, which is what writes them.
|
|
13
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
13
14
|
import { createRequire } from "node:module";
|
|
14
|
-
import { join } from "node:path";
|
|
15
|
+
import { join, relative } from "node:path";
|
|
15
16
|
import { cwd, exit, stderr, stdout } from "node:process";
|
|
16
17
|
import { pathToFileURL } from "node:url";
|
|
17
18
|
async function flatten(option) {
|
|
@@ -20,7 +21,16 @@ async function flatten(option) {
|
|
|
20
21
|
return (await Promise.all(value.map(flatten))).flat();
|
|
21
22
|
return value && typeof value === "object" ? [value] : [];
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
+
/**
|
|
25
|
+
* Write the types; or, with `check`, say which committed generated files are
|
|
26
|
+
* not what the backend and the route tree produce now, and change nothing.
|
|
27
|
+
*
|
|
28
|
+
* For CI: `rsc-kit-typegen --check` fails when rsc-host.json or the types were
|
|
29
|
+
* committed and the backend has moved on since. Only files that were already
|
|
30
|
+
* there are compared - one that is not committed is written fresh by every
|
|
31
|
+
* build and cannot be stale - and every one is put back as it was.
|
|
32
|
+
*/
|
|
33
|
+
export async function typegen(root = cwd(), check = false) {
|
|
24
34
|
const local = createRequire(join(root, "package.json"));
|
|
25
35
|
let vitePath;
|
|
26
36
|
try {
|
|
@@ -30,20 +40,47 @@ export async function typegen(root = cwd()) {
|
|
|
30
40
|
throw new Error("No vite installed in " + root + ". Run this from the app's directory.");
|
|
31
41
|
}
|
|
32
42
|
const vite = (await import(pathToFileURL(vitePath).href));
|
|
33
|
-
|
|
43
|
+
// As a build would: a manifest command that fails is a failure, not a
|
|
44
|
+
// warning, when the question is whether what is committed is current.
|
|
45
|
+
const env = check ? { command: "build", mode: "production" } : { command: "serve", mode: "development" };
|
|
34
46
|
const loaded = await vite.loadConfigFromFile(env, undefined, root);
|
|
35
47
|
if (!loaded)
|
|
36
48
|
throw new Error("No vite.config found in " + root + ".");
|
|
37
49
|
const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === "rsc-kit");
|
|
38
50
|
if (!plugin?.config)
|
|
39
51
|
throw new Error("The vite.config in " + root + " does not use rscKit().");
|
|
40
|
-
|
|
52
|
+
if (!check) {
|
|
53
|
+
await plugin.config({}, env);
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
const files = plugin.api?.generatedFiles?.() ?? [];
|
|
57
|
+
const before = new Map(files.filter((f) => existsSync(f)).map((f) => [f, readFileSync(f, "utf-8")]));
|
|
58
|
+
try {
|
|
59
|
+
await plugin.config({}, env);
|
|
60
|
+
return [...before].filter(([f, text]) => !existsSync(f) || readFileSync(f, "utf-8") !== text).map(([f]) => f);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
for (const [f, text] of before)
|
|
64
|
+
writeFileSync(f, text);
|
|
65
|
+
}
|
|
41
66
|
}
|
|
42
67
|
// Run as a command, not when imported.
|
|
43
68
|
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href || process.argv[1]?.endsWith("rsc-kit-typegen")) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
69
|
+
const check = process.argv.includes("--check");
|
|
70
|
+
typegen(cwd(), check)
|
|
71
|
+
.then((stale) => {
|
|
72
|
+
if (!check) {
|
|
73
|
+
stdout.write("rsc-kit: route types written\n");
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (stale.length === 0) {
|
|
77
|
+
stdout.write("rsc-kit: generated files are current\n");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
stderr.write("rsc-kit-typegen --check: these are committed and no longer what the backend and the routes produce:\n" +
|
|
81
|
+
stale.map((f) => " " + relative(cwd(), f)).join("\n") +
|
|
82
|
+
"\nRun rsc-kit-typegen and commit the result.\n");
|
|
83
|
+
exit(1);
|
|
47
84
|
})
|
|
48
85
|
.catch((error) => {
|
|
49
86
|
stderr.write("rsc-kit-typegen: " + (error instanceof Error ? error.message : String(error)) + "\n");
|
package/dist/typegen.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typegen.js","sourceRoot":"","sources":["../src/typegen.ts"],"names":[],"mappings":";AACA,gEAAgE;AAChE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,8EAA8E;AAE9E,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"typegen.js","sourceRoot":"","sources":["../src/typegen.ts"],"names":[],"mappings":";AACA,gEAAgE;AAChE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,8EAA8E;AAE9E,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,aAAa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CAAC;IACV,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,MAAM,CAAC,KAAK,CAAC,mBAAmB,GAAG,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;QACpG,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["#!/usr/bin/env node\n// rsc-kit-typegen: write the route types without starting Vite.\n//\n// The types - every url the app has, for <Link href> and redirect() - are\n// written when the dev server or a build starts, and again when a dev server\n// sees a route added. A typecheck run with neither, by an agent or in CI,\n// read the types from the last start: a route added since failed with\n// '\"/admin\"' is not assignable to type Route until something started Vite.\n//\n// The app's own vite.config is loaded, through the app's own Vite, so the\n// plugin's options - sourceDir, outDir, a host's route file - are the ones it\n// builds with. Only the plugin's config step runs, which is what writes them.\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, relative } from \"node:path\";\nimport { cwd, exit, stderr, stdout } from \"node:process\";\nimport { pathToFileURL } from \"node:url\";\n\ninterface PluginLike {\n name?: string;\n config?: (config: object, env: { command: string; mode: string }) => unknown;\n api?: { generatedFiles?: () => string[] };\n}\n\nasync function flatten(option: unknown): Promise<PluginLike[]> {\n const value = await option;\n\n if (Array.isArray(value)) return (await Promise.all(value.map(flatten))).flat();\n\n return value && typeof value === \"object\" ? [value as PluginLike] : [];\n}\n\n/**\n * Write the types; or, with `check`, say which committed generated files are\n * not what the backend and the route tree produce now, and change nothing.\n *\n * For CI: `rsc-kit-typegen --check` fails when rsc-host.json or the types were\n * committed and the backend has moved on since. Only files that were already\n * there are compared - one that is not committed is written fresh by every\n * build and cannot be stale - and every one is put back as it was.\n */\nexport async function typegen(root = cwd(), check = false): Promise<string[]> {\n const local = createRequire(join(root, \"package.json\"));\n let vitePath: string;\n\n try {\n vitePath = local.resolve(\"vite\");\n } catch {\n throw new Error(\"No vite installed in \" + root + \". Run this from the app's directory.\");\n }\n\n const vite = (await import(pathToFileURL(vitePath).href)) as {\n loadConfigFromFile: (\n env: { command: string; mode: string },\n file?: string,\n root?: string,\n ) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n\n // As a build would: a manifest command that fails is a failure, not a\n // warning, when the question is whether what is committed is current.\n const env = check ? { command: \"build\", mode: \"production\" } : { command: \"serve\", mode: \"development\" };\n const loaded = await vite.loadConfigFromFile(env, undefined, root);\n\n if (!loaded) throw new Error(\"No vite.config found in \" + root + \".\");\n\n const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n\n if (!plugin?.config) throw new Error(\"The vite.config in \" + root + \" does not use rscKit().\");\n\n if (!check) {\n await plugin.config({}, env);\n\n return [];\n }\n\n const files = plugin.api?.generatedFiles?.() ?? [];\n const before = new Map(files.filter((f) => existsSync(f)).map((f) => [f, readFileSync(f, \"utf-8\")]));\n\n try {\n await plugin.config({}, env);\n\n return [...before].filter(([f, text]) => !existsSync(f) || readFileSync(f, \"utf-8\") !== text).map(([f]) => f);\n } finally {\n for (const [f, text] of before) writeFileSync(f, text);\n }\n}\n\n// Run as a command, not when imported.\nif (import.meta.url === pathToFileURL(process.argv[1] ?? \"\").href || process.argv[1]?.endsWith(\"rsc-kit-typegen\")) {\n const check = process.argv.includes(\"--check\");\n\n typegen(cwd(), check)\n .then((stale) => {\n if (!check) {\n stdout.write(\"rsc-kit: route types written\\n\");\n\n return;\n }\n\n if (stale.length === 0) {\n stdout.write(\"rsc-kit: generated files are current\\n\");\n\n return;\n }\n\n stderr.write(\n \"rsc-kit-typegen --check: these are committed and no longer what the backend and the routes produce:\\n\" +\n stale.map((f) => \" \" + relative(cwd(), f)).join(\"\\n\") +\n \"\\nRun rsc-kit-typegen and commit the result.\\n\",\n );\n exit(1);\n })\n .catch((error: unknown) => {\n stderr.write(\"rsc-kit-typegen: \" + (error instanceof Error ? error.message : String(error)) + \"\\n\");\n exit(1);\n });\n}\n"]}
|
package/dist/vite.d.ts
CHANGED
|
@@ -288,6 +288,13 @@ export interface RscKitOptions {
|
|
|
288
288
|
hostManifest?: {
|
|
289
289
|
command: string[];
|
|
290
290
|
cwd?: string;
|
|
291
|
+
/**
|
|
292
|
+
* Where the backend's source is, relative to the project root, so the
|
|
293
|
+
* dev server runs the command again when it changes: `['backend']`, or
|
|
294
|
+
* `['app/Rsc']`. Without it the manifest is written once, as dev starts,
|
|
295
|
+
* and a function added to the backend is not typed until the next start.
|
|
296
|
+
*/
|
|
297
|
+
watch?: string[];
|
|
291
298
|
};
|
|
292
299
|
}
|
|
293
300
|
/**
|
package/dist/vite.js
CHANGED
|
@@ -421,12 +421,12 @@ function loadHostManifest(options) {
|
|
|
421
421
|
hostDefs = manifest.defs;
|
|
422
422
|
}
|
|
423
423
|
/** Run the backend's manifest command, once per process; see the option. */
|
|
424
|
-
function runHostManifest(options, isBuild) {
|
|
424
|
+
function runHostManifest(options, isBuild, again = false) {
|
|
425
425
|
const spec = options.hostManifest;
|
|
426
426
|
if (!spec)
|
|
427
427
|
return;
|
|
428
428
|
const ran = projectRoot + "\0" + spec.command.join("\0");
|
|
429
|
-
if (hostManifestRan.has(ran))
|
|
429
|
+
if (hostManifestRan.has(ran) && !again)
|
|
430
430
|
return;
|
|
431
431
|
hostManifestRan.add(ran);
|
|
432
432
|
const [command, ...args] = spec.command;
|
|
@@ -2183,6 +2183,21 @@ function renderHostSignatures() {
|
|
|
2183
2183
|
out.push("declare function " + hostGlobal + "<T = " + (sig.result ? tsOf(sig.result) : "void") + ">(name: " +
|
|
2184
2184
|
JSON.stringify(name) + (params ? ", " + params : "") + "): Promise<T>;");
|
|
2185
2185
|
}
|
|
2186
|
+
// Every function by name, its arguments and its result: what a test's fake
|
|
2187
|
+
// backend is typed against (createTestApp({ host })), so a fake cannot
|
|
2188
|
+
// answer for a function the backend does not have, or with a value it
|
|
2189
|
+
// would never send.
|
|
2190
|
+
if (hostFunctions?.length) {
|
|
2191
|
+
out.push("interface RscHostFunctions {");
|
|
2192
|
+
for (const name of hostFunctions) {
|
|
2193
|
+
const sig = hostTypes[name];
|
|
2194
|
+
out.push(" " + JSON.stringify(name) + ": " +
|
|
2195
|
+
(sig
|
|
2196
|
+
? "{ args: [" + tsParams(sig) + "]; result: " + (sig.result ? tsOf(sig.result) : "void") + " };"
|
|
2197
|
+
: "{ args: unknown[]; result: unknown };"));
|
|
2198
|
+
}
|
|
2199
|
+
out.push("}", "");
|
|
2200
|
+
}
|
|
2186
2201
|
const untyped = hostFunctions?.filter((name) => !hostTypes[name]) ?? null;
|
|
2187
2202
|
if (untyped === null) {
|
|
2188
2203
|
out.push("declare function " + hostGlobal + "<T = unknown>(name: string, ...args: unknown[]): Promise<T>;");
|
|
@@ -6415,6 +6430,17 @@ export function rscKit(options = {}) {
|
|
|
6415
6430
|
}
|
|
6416
6431
|
const routesPlugin = {
|
|
6417
6432
|
name: "rsc-kit",
|
|
6433
|
+
// For rsc-kit-typegen --check: every file the config step writes that an
|
|
6434
|
+
// app might commit, so a stale one can be named.
|
|
6435
|
+
api: {
|
|
6436
|
+
generatedFiles() {
|
|
6437
|
+
return [
|
|
6438
|
+
join(projectRoot, HOST_FILE),
|
|
6439
|
+
join(sourceDir, HOST_ACTIONS_MODULE),
|
|
6440
|
+
...(existsSync(typesDir) ? readdirSync(typesDir).map((name) => join(typesDir, name)) : []),
|
|
6441
|
+
];
|
|
6442
|
+
},
|
|
6443
|
+
},
|
|
6418
6444
|
// A Nitro module, which Nitro's Vite plugin collects from any plugin
|
|
6419
6445
|
// that carries one. Only for a built server: the dev server evaluates
|
|
6420
6446
|
// the entry through Vite's runner when it is first asked for, and there
|
|
@@ -6989,6 +7015,25 @@ export function rscKit(options = {}) {
|
|
|
6989
7015
|
void server.restart();
|
|
6990
7016
|
};
|
|
6991
7017
|
server.watcher.add(hostActionsPath);
|
|
7018
|
+
// The backend's own source, when the app says where it is: a function
|
|
7019
|
+
// added in Go or PHP is typed in the editor a moment after it is saved,
|
|
7020
|
+
// rather than at the next start. Its rewritten manifest restarts the
|
|
7021
|
+
// server through the handler above.
|
|
7022
|
+
const backendDirs = (options.hostManifest?.watch ?? []).map((dir) => resolve(projectRoot, dir));
|
|
7023
|
+
if (backendDirs.length > 0) {
|
|
7024
|
+
let timer;
|
|
7025
|
+
const backendChanged = (file) => {
|
|
7026
|
+
if (!backendDirs.some((dir) => file === dir || file.startsWith(dir + "/")))
|
|
7027
|
+
return;
|
|
7028
|
+
clearTimeout(timer);
|
|
7029
|
+
timer = setTimeout(() => runHostManifest(options, false, true), 300);
|
|
7030
|
+
};
|
|
7031
|
+
for (const dir of backendDirs)
|
|
7032
|
+
server.watcher.add(dir);
|
|
7033
|
+
server.watcher.on("add", backendChanged);
|
|
7034
|
+
server.watcher.on("change", backendChanged);
|
|
7035
|
+
server.watcher.on("unlink", backendChanged);
|
|
7036
|
+
}
|
|
6992
7037
|
server.watcher.on("add", hostActionsChanged);
|
|
6993
7038
|
server.watcher.on("change", hostActionsChanged);
|
|
6994
7039
|
server.watcher.on("unlink", hostActionsChanged);
|