@rsc-kit/core 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The backend's schema for the action a form posts to, in the browser.
3
+ *
4
+ * A backend can describe an action's input as JSON Schema - Laravel's
5
+ * FormRequest `schema()`, written to rsc-host.json with its own rendered
6
+ * messages - and `<Form action={signup}>` then checks it on blur and on
7
+ * submit with no `schema` prop: the backend's rules are the only copy.
8
+ *
9
+ * Nothing rides in a page. Most forms are in client components, which no
10
+ * server render sees, so the page could not say which action is on it. The
11
+ * build writes a chunk per action instead, and an index from action id to
12
+ * chunk; a form loads the index when a field first takes focus and its
13
+ * action's chunk, with the validator, on its first check. Immutable files,
14
+ * cached across pages, and nothing at all for a visitor who never types.
15
+ * An app whose backend declares no schema registers no loader, and this is
16
+ * never asked.
17
+ *
18
+ * A check in the browser is a courtesy: the backend validates what arrives
19
+ * either way, so a chunk that fails to load is a form without early checks,
20
+ * not a form that cannot be sent.
21
+ */
22
+ import type { StandardSchemaV1 } from './standardSchema.js';
23
+ /** What the build writes for one action. */
24
+ export interface BackendSchema {
25
+ schema: unknown;
26
+ /** Field path, then JSON Schema keyword, to the backend's own message. */
27
+ messages?: Record<string, Record<string, string>>;
28
+ }
29
+ type Load = () => Promise<{
30
+ default: BackendSchema;
31
+ }>;
32
+ /** The build's index: each action stub with a schema, beside its chunk. */
33
+ type Index = () => Promise<{
34
+ entries: ReadonlyArray<readonly [reference: unknown, load: Load]>;
35
+ }>;
36
+ /** @internal Registered by the generated browser entry, only when the backend lists a schema. */
37
+ export declare function setFormSchemas(load: Index | null): void;
38
+ /** Start loading the index, so a first check does not wait for it. */
39
+ export declare function preloadFormSchemas(): void;
40
+ /** Whether a schema is a backend's, whose blank optional fields must not be posted - see Form. */
41
+ export declare function isBackendSchema(schema: unknown): boolean;
42
+ /**
43
+ * The backend's schema for an action, or null when it declared none - or the
44
+ * action is not one of the backend's, or this app has no backend schemas.
45
+ */
46
+ export declare function backendSchemaOf(action: unknown): Promise<StandardSchemaV1 | null>;
47
+ export {};
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The backend's schema for the action a form posts to, in the browser.
3
+ *
4
+ * A backend can describe an action's input as JSON Schema - Laravel's
5
+ * FormRequest `schema()`, written to rsc-host.json with its own rendered
6
+ * messages - and `<Form action={signup}>` then checks it on blur and on
7
+ * submit with no `schema` prop: the backend's rules are the only copy.
8
+ *
9
+ * Nothing rides in a page. Most forms are in client components, which no
10
+ * server render sees, so the page could not say which action is on it. The
11
+ * build writes a chunk per action instead, and an index from action id to
12
+ * chunk; a form loads the index when a field first takes focus and its
13
+ * action's chunk, with the validator, on its first check. Immutable files,
14
+ * cached across pages, and nothing at all for a visitor who never types.
15
+ * An app whose backend declares no schema registers no loader, and this is
16
+ * never asked.
17
+ *
18
+ * A check in the browser is a courtesy: the backend validates what arrives
19
+ * either way, so a chunk that fails to load is a form without early checks,
20
+ * not a form that cannot be sent.
21
+ */
22
+ import { actionId } from './queryClient.js';
23
+ let index = null;
24
+ let byId = null;
25
+ /** @internal Registered by the generated browser entry, only when the backend lists a schema. */
26
+ export function setFormSchemas(load) {
27
+ index = load;
28
+ byId = null;
29
+ }
30
+ function table() {
31
+ byId ??= index()
32
+ .then(async ({ entries }) => {
33
+ const named = await Promise.all(entries.map(async ([reference, load]) => [await actionId(reference), load]));
34
+ return new Map(named.filter((entry) => entry[0] !== null));
35
+ })
36
+ .catch((error) => {
37
+ // Asked again next time: a network blip is not a verdict.
38
+ byId = null;
39
+ throw error;
40
+ });
41
+ return byId;
42
+ }
43
+ /** Start loading the index, so a first check does not wait for it. */
44
+ export function preloadFormSchemas() {
45
+ if (index)
46
+ table().catch(() => { });
47
+ }
48
+ const fromBackend = new WeakSet();
49
+ /** Whether a schema is a backend's, whose blank optional fields must not be posted - see Form. */
50
+ export function isBackendSchema(schema) {
51
+ return typeof schema === 'object' && schema !== null && fromBackend.has(schema);
52
+ }
53
+ const found = new WeakMap();
54
+ /**
55
+ * The backend's schema for an action, or null when it declared none - or the
56
+ * action is not one of the backend's, or this app has no backend schemas.
57
+ */
58
+ export function backendSchemaOf(action) {
59
+ if (!index || typeof action !== 'function')
60
+ return Promise.resolve(null);
61
+ let pending = found.get(action);
62
+ if (!pending) {
63
+ pending = (async () => {
64
+ const id = await actionId(action);
65
+ const load = id === null ? undefined : (await table()).get(id);
66
+ if (!load)
67
+ return null;
68
+ const [{ default: described }, { fromJsonSchema }] = await Promise.all([load(), import('json-schema-to-standard')]);
69
+ // A blank control is "", and to a form that is a field left empty - as
70
+ // it is to Laravel's `sometimes` and Go's zero value.
71
+ const schema = fromJsonSchema(described.schema, { messages: described.messages, emptyIsMissing: true });
72
+ fromBackend.add(schema);
73
+ return schema;
74
+ })().catch(() => {
75
+ found.delete(action);
76
+ return null;
77
+ });
78
+ found.set(action, pending);
79
+ }
80
+ return pending;
81
+ }
82
+ //# sourceMappingURL=formSchemas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formSchemas.js","sourceRoot":"","sources":["../../src/js/formSchemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAc3C,IAAI,KAAK,GAAiB,IAAI,CAAA;AAC9B,IAAI,IAAI,GAAsC,IAAI,CAAA;AAElD,iGAAiG;AACjG,MAAM,UAAU,cAAc,CAAC,IAAkB;IAC/C,KAAK,GAAG,IAAI,CAAA;IACZ,IAAI,GAAG,IAAI,CAAA;AACb,CAAC;AAED,SAAS,KAAK;IACZ,IAAI,KAAK,KAAM,EAAE;SACd,IAAI,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;QAC1B,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,EAAE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AI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,KAAK,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;YAE9D,IAAI,CAAC,IAAI;gBAAE,OAAO,IAAI,CAAA;YAEtB,MAAM,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAA;YACnH,uEAAuE;YACvE,sDAAsD;YACtD,MAAM,MAAM,GAAG,cAAc,CAAC,SAAS,CAAC,MAAe,EAAE,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAA;YAEhH,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YAEvB,OAAO,MAA0B,CAAA;QACnC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE;YACd,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;YAEpB,OAAO,IAAI,CAAA;QACb,CAAC,CAAC,CAAA;QAEF,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC","sourcesContent":["/**\n * The backend's schema for the action a form posts to, in the browser.\n *\n * A backend can describe an action's input as JSON Schema - Laravel's\n * FormRequest `schema()`, written to rsc-host.json with its own rendered\n * messages - and `<Form action={signup}>` then checks it on blur and on\n * submit with no `schema` prop: the backend's rules are the only copy.\n *\n * Nothing rides in a page. Most forms are in client components, which no\n * server render sees, so the page could not say which action is on it. The\n * build writes a chunk per action instead, and an index from action id to\n * chunk; a form loads the index when a field first takes focus and its\n * action's chunk, with the validator, on its first check. Immutable files,\n * cached across pages, and nothing at all for a visitor who never types.\n * An app whose backend declares no schema registers no loader, and this is\n * never asked.\n *\n * A check in the browser is a courtesy: the backend validates what arrives\n * either way, so a chunk that fails to load is a form without early checks,\n * not a form that cannot be sent.\n */\n\nimport type { StandardSchemaV1 } from './standardSchema.js'\nimport { actionId } from './queryClient.js'\n\n/** What the build writes for one action. */\nexport interface BackendSchema {\n schema: unknown\n /** Field path, then JSON Schema keyword, to the backend's own message. */\n messages?: Record<string, Record<string, string>>\n}\n\ntype Load = () => Promise<{ default: BackendSchema }>\n\n/** The build's index: each action stub with a schema, beside its chunk. */\ntype Index = () => Promise<{ entries: ReadonlyArray<readonly [reference: unknown, load: Load]> }>\n\nlet index: Index | null = null\nlet byId: Promise<Map<string, Load>> | null = null\n\n/** @internal Registered by the generated browser entry, only when the backend lists a schema. */\nexport function setFormSchemas(load: Index | null): void {\n index = load\n byId = null\n}\n\nfunction table(): Promise<Map<string, Load>> {\n byId ??= index!()\n .then(async ({ entries }) => {\n const named = await Promise.all(entries.map(async ([reference, load]) => [await actionId(reference as object), load] as const))\n\n return new Map(named.filter((entry): entry is readonly [string, Load] => entry[0] !== null))\n })\n .catch((error: unknown) => {\n // Asked again next time: a network blip is not a verdict.\n byId = null\n\n throw error\n })\n\n return byId\n}\n\n/** Start loading the index, so a first check does not wait for it. */\nexport function preloadFormSchemas(): void {\n if (index) table().catch(() => {})\n}\n\nconst fromBackend = new WeakSet<object>()\n\n/** Whether a schema is a backend's, whose blank optional fields must not be posted - see Form. */\nexport function isBackendSchema(schema: unknown): boolean {\n return typeof schema === 'object' && schema !== null && fromBackend.has(schema)\n}\n\nconst found = new WeakMap<object, Promise<StandardSchemaV1 | null>>()\n\n/**\n * The backend's schema for an action, or null when it declared none - or the\n * action is not one of the backend's, or this app has no backend schemas.\n */\nexport function backendSchemaOf(action: unknown): Promise<StandardSchemaV1 | null> {\n if (!index || typeof action !== 'function') return Promise.resolve(null)\n\n let pending = found.get(action)\n\n if (!pending) {\n pending = (async () => {\n const id = await actionId(action)\n const load = id === null ? undefined : (await table()).get(id)\n\n if (!load) return null\n\n const [{ default: described }, { fromJsonSchema }] = await Promise.all([load(), import('json-schema-to-standard')])\n // A blank control is \"\", and to a form that is a field left empty - as\n // it is to Laravel's `sometimes` and Go's zero value.\n const schema = fromJsonSchema(described.schema as never, { messages: described.messages, emptyIsMissing: true })\n\n fromBackend.add(schema)\n\n return schema as StandardSchemaV1\n })().catch(() => {\n found.delete(action)\n\n return null\n })\n\n found.set(action, pending)\n }\n\n return pending\n}\n"]}
@@ -6,6 +6,19 @@
6
6
  * `fetchQuery`.
7
7
  */
8
8
  export declare function claimRead(id: string, args: unknown[]): Promise<unknown> | null;
9
+ /**
10
+ * A server reference's id, or null for anything else.
11
+ *
12
+ * React keeps the id private, but encoding a reference to send back writes
13
+ * it out: the reference becomes `$h<part>`, and the part is `{ id, bound }`.
14
+ * That is the reply protocol the server decodes, so it cannot drift on one
15
+ * side alone. Nothing is called - calling a bound reference to learn its id
16
+ * would reach callServer a tick later, and run the action.
17
+ *
18
+ * A bound reference answers null: what it was bound to is part of what it
19
+ * does, and the id alone does not say it.
20
+ */
21
+ export declare function actionId(fn: object): Promise<string | null>;
9
22
  /**
10
23
  * Read a query, over GET.
11
24
  *
@@ -59,6 +59,35 @@ export function claimRead(id, args) {
59
59
  slot.promise = send(id, args);
60
60
  return slot.promise;
61
61
  }
62
+ /**
63
+ * A server reference's id, or null for anything else.
64
+ *
65
+ * React keeps the id private, but encoding a reference to send back writes
66
+ * it out: the reference becomes `$h<part>`, and the part is `{ id, bound }`.
67
+ * That is the reply protocol the server decodes, so it cannot drift on one
68
+ * side alone. Nothing is called - calling a bound reference to learn its id
69
+ * would reach callServer a tick later, and run the action.
70
+ *
71
+ * A bound reference answers null: what it was bound to is part of what it
72
+ * does, and the id alone does not say it.
73
+ */
74
+ export async function actionId(fn) {
75
+ if (!(await isServerReference(fn)))
76
+ return null;
77
+ try {
78
+ const encoded = await encode([fn]);
79
+ if (typeof encoded === 'string')
80
+ return null;
81
+ const [root] = JSON.parse(String(encoded.get('0')));
82
+ if (typeof root !== 'string' || !root.startsWith('$h'))
83
+ return null;
84
+ const part = JSON.parse(String(encoded.get(String(parseInt(root.slice(2), 16)))));
85
+ return typeof part.id === 'string' && part.bound == null ? part.id : null;
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
62
91
  export function fetchQuery(reference, args = []) {
63
92
  if (typeof window === 'undefined') {
64
93
  // React's SSR runtime refuses a server-function call during the initial
@@ -1 +1 @@
1
- {"version":3,"file":"queryClient.js","sourceRoot":"","sources":["../../src/js/queryClient.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,EAAE;AACF,sEAAsE;AACtE,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,sEAAsE;AACtE,gBAAgB;AAChB,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,yDAAyD;AAEzD,2EAA2E;AAC3E,MAAM,UAAU,GAAG,aAAa,CAAA;AAEhC;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,aAAa,CAAA;AAElC;;;;;GAKG;AACH,MAAM,OAAO,GAAG,KAAK,CAAA;AAIrB;;;;;GAKG;AACH,IAAI,IAAI,GAAkE,IAAI,CAAA;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,EAAU,EAAE,IAAe;IACnD,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAA;IAEtC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;IACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IAE7B,OAAO,IAAI,CAAC,OAAO,CAAA;AACrB,CAAC;AAsBD,MAAM,UAAU,UAAU,CACxB,SAA8C,EAC9C,IAAI,GAAc,EAAE;IAEpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;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,IAAI,CACH,GAAG,EAAE,CAAC,IAAI,EACV,GAAG,EAAE,CAAC,KAAK,CACZ,CAAA;QACH,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;IAC3B,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["// The browser half of `query()`: send a read as a GET.\n//\n// That is the whole of it. There is no cache here, no batching and no\n// deduplication, because TanStack Query and SWR already do those and do them\n// better — this owns the transport and they own everything above it.\n//\n// The awkward fact it is built around: a server function's id is not readable\n// from the client. React keeps it in a module-private WeakMap and exposes no\n// getter, so there is no `ref.$$id` to build a url from. What the client *can*\n// do is call the reference and be handed the id by React itself — the stub's\n// whole body is `callServer(id, args)`, and this package already owns\n// `callServer`.\n//\n// So a read opens a one-shot slot and calls the reference; the transport claims\n// the slot and sends a GET instead of posting. The slot is also what says this\n// is a read at all: calling `getListings(kind)` directly is still a POST, and\n// `fetchQuery(getListings, [kind])` is the same call as a GET. Nothing has to\n// know a list of query ids, on either side of the build.\n\n/** Where reads are answered. Must match HEADER.queryPath on the server. */\nconst QUERY_PATH = '/_rsc/query'\n\n/**\n * Sent on every read, and required by the endpoint.\n *\n * Not decoration. A GET with no unusual header is a *simple* request, so any\n * page anywhere can trigger one with `<img src=\"…/_rsc/query?…\">` and it goes\n * out with the visitor's cookies — CORS stops the attacker reading the answer,\n * but the read still runs. This header is not CORS-safelisted, so the browser\n * preflights it, and nothing here answers a preflight.\n *\n * That restores exactly the protection a POST had: a `POST` carrying\n * `X-RSC-Action` is non-simple for the same reason.\n */\nconst QUERY_HEADER = 'X-RSC-Query'\n\n/**\n * How long a url may get before the read goes as a POST instead.\n *\n * Conservative. Proxies and CDNs start refusing somewhere between 8k and 16k,\n * and the failure is a 414 from a machine that is not ours.\n */\nconst MAX_URL = 6_000\n\ntype Reader = (...args: unknown[]) => Promise<unknown>\n\n/**\n * The slot a read opens before calling the reference.\n *\n * One-shot and synchronous: React's stub calls `callServer` in its own body\n * with nothing awaited in between, so exactly one transport call can claim it.\n */\nlet slot: { claimed: boolean; promise: Promise<unknown> | null } | null = null\n\n/**\n * Claim the open slot, if a read opened one.\n *\n * Called from the app's `callServer` before it posts. Returns null when this is\n * an ordinary action, which is every call that did not come through\n * `fetchQuery`.\n */\nexport function claimRead(id: string, args: unknown[]): Promise<unknown> | null {\n if (!slot || slot.claimed) return null\n\n slot.claimed = true\n slot.promise = send(id, args)\n\n return slot.promise\n}\n\n/**\n * Read a query, over GET.\n *\n * Hand this to a cache library and let it decide everything else:\n *\n * queryFn: () => fetchQuery(getListings, [kind])\n * useSWR(['listings', kind], () => fetchQuery(getListings, [kind]))\n *\n * Every call goes to the server, which is what a fetcher needs — staleness,\n * revalidation, retries, polling and deduplication all belong to the library\n * holding the answer, not to the thing that fetches it.\n */\nexport function fetchQuery<Data>(reference: () => Promise<Data>, args?: []): Promise<Data>\n// The query's own parameters, so a wrong key fails the typecheck rather than\n// the read. NoInfer keeps the tuple from being inferred from the call site,\n// where a wrong key would simply widen it.\nexport function fetchQuery<Args extends unknown[], Data>(\n reference: (...args: Args) => Promise<Data>,\n args: NoInfer<Args>,\n): Promise<Data>\nexport function fetchQuery<Data>(\n reference: (...args: never[]) => Promise<Data>,\n args: unknown[] = [],\n): Promise<Data> {\n if (typeof window === 'undefined') {\n // React's SSR runtime refuses a server-function call during the initial\n // render, and reaching a query's id means calling its reference — so this\n // cannot work here. Raised with the fix in it rather than left to surface\n // as React's more general message about fetch waterfalls.\n //\n // A cache library runs its fetcher in an effect, so the server render never\n // reaches this; a server component that wants the data during render should\n // await the query directly, which needs none of this.\n throw new Error(\n 'A query was read during server rendering. Read it in a server component with await, or through a cache library, whose fetcher runs after hydration.',\n )\n }\n\n const opened = { claimed: false, promise: null as Promise<unknown> | null }\n\n slot = opened\n\n try {\n // React's stub reaches callServer synchronously, so the slot is claimed by\n // the time this returns. The stub's own promise is discarded: the one the\n // transport made is the one that settles with the answer.\n ;(reference as unknown as Reader)(...(args as unknown[]))\n } finally {\n // Cleared here and nowhere else, so a reference that throws on the way in\n // does not leave the slot open for the next read to claim by accident.\n // Nothing is returned from this block: a `return` in `finally` discards\n // whatever the `try` was throwing, which would turn a reference that threw\n // synchronously into the misleading bound-reference error below.\n slot = null\n }\n\n if (!opened.claimed || !opened.promise) {\n // The only way here is a reference whose call path is asynchronous, which\n // today means one that was `.bind()`-ed. Loud, because the quiet version is\n // a read that silently went out as a POST.\n throw new Error(\n 'A query was called through a bound reference. Pass the exported query itself, unbound.',\n )\n }\n\n return opened.promise as Promise<Data>\n}\n\nasync function send(id: string, args: unknown[]): Promise<unknown> {\n const encoded = await encode(args)\n\n // encodeReply answers with FormData the moment an argument holds a File, and\n // a url cannot carry one. Rather than refuse a call that would have worked as\n // an action, the read falls back to a POST: it stops being cacheable, which\n // is the only thing it loses.\n if (typeof encoded !== 'string') return await post(id, args, 'an argument contained a File')\n\n const url = `${QUERY_PATH}?id=${encodeURIComponent(id)}&args=${encodeURIComponent(encoded)}`\n\n if (url.length > MAX_URL) return await post(id, args, 'the arguments are too large for a url')\n\n const res = await fetch(url, {\n headers: {\n [QUERY_HEADER]: '1',\n Accept: 'text/x-component',\n // Where the read came from. Same reason an action sends it: a host that\n // guards by route needs to know which page is asking.\n 'X-RSC-Referer': window.location.pathname + window.location.search,\n },\n })\n\n if (!res.ok || !res.body) {\n throw await failureFrom(res)\n }\n\n return await deserialize(res.body)\n}\n\n/**\n * What a refused read rejects with.\n *\n * A cache library reports failure by rejection, so this has to be an Error —\n * and one carrying the message the server meant, rather than a status code. A\n * validation refusal keeps its fields on `errors`, where a form can read them.\n */\nasync function failureFrom(res: Response): Promise<Error> {\n const body = await res.text().catch(() => '')\n\n try {\n const parsed = JSON.parse(body) as { message?: string; errors?: Record<string, string[]>; refusal?: unknown }\n const error = new Error(parsed.message || `Query failed: ${res.status}`) as Error & {\n errors?: unknown\n refusal?: unknown\n status?: number\n }\n\n if (parsed.errors) error.errors = parsed.errors\n // The data a refusal declared with .refusal(schema), checked on the server.\n if (parsed.refusal !== undefined) error.refusal = parsed.refusal\n error.status = res.status\n\n return error\n } catch {\n return new Error(body || `Query failed: ${res.status}`)\n }\n}\n\n/**\n * The same read, as an action.\n *\n * Reached only when the arguments cannot ride in a url. Warned about in\n * development rather than silently tolerated, because the read still works and\n * the thing that changed — it is no longer a GET, so nothing can cache it — is\n * otherwise invisible.\n */\nasync function post(id: string, args: unknown[], why: string): Promise<unknown> {\n if (import.meta.env?.DEV) {\n console.warn(`[rsc-kit] A query was sent as a POST because ${why}. It will not be cached.`)\n }\n\n return await asAction(id, args)\n}\n\n/**\n * The Flight codec and the action transport, installed by the app bootstrap.\n *\n * Injected rather than imported, and not for testing: this module is reached\n * from client components, so importing the browser runtime here would pull a\n * second copy of it into that graph — two client-reference registries, where\n * components resolve to undefined with nothing logged. The bootstrap already\n * holds the one true copy.\n */\nlet deserialize: (stream: ReadableStream) => Promise<unknown> = () => {\n throw new Error('No Flight decoder installed. createViteRscApp() sets one up.')\n}\n\nlet encode: (args: unknown[]) => Promise<string | FormData> = () => {\n throw new Error('No Flight encoder installed. createViteRscApp() sets one up.')\n}\n\nlet asAction: (id: string, args: unknown[]) => Promise<unknown> = () => {\n throw new Error('No action transport installed. createViteRscApp() sets one up.')\n}\n\nexport function setQueryCodec(codec: {\n deserialize: (stream: ReadableStream) => Promise<unknown>\n encode: (args: unknown[]) => Promise<string | FormData>\n asAction: (id: string, args: unknown[]) => Promise<unknown>\n}): void {\n deserialize = codec.deserialize\n encode = codec.encode\n asAction = codec.asAction\n}\n\nconst references = new WeakMap<object, Promise<boolean>>()\n\n/**\n * Whether `fn` is a server reference, asked of Flight before anything calls\n * it: one it can send back to the server encodes, and a function of the\n * browser's own is refused. React keeps its registry of references private,\n * and calling to find out would run a plain function.\n *\n * False wherever there is no encoder - a page with no runtime, a test.\n */\nexport function isServerReference(fn: object): Promise<boolean> {\n let known = references.get(fn)\n\n if (!known) {\n known = Promise.resolve()\n .then(() => encode([fn]))\n .then(\n () => true,\n () => false,\n )\n references.set(fn, known)\n }\n\n return known\n}\n"]}
1
+ {"version":3,"file":"queryClient.js","sourceRoot":"","sources":["../../src/js/queryClient.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,EAAE;AACF,sEAAsE;AACtE,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,sEAAsE;AACtE,gBAAgB;AAChB,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,yDAAyD;AAEzD,2EAA2E;AAC3E,MAAM,UAAU,GAAG,aAAa,CAAA;AAEhC;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,aAAa,CAAA;AAElC;;;;;GAKG;AACH,MAAM,OAAO,GAAG,KAAK,CAAA;AAIrB;;;;;GAKG;AACH,IAAI,IAAI,GAAkE,IAAI,CAAA;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,EAAU,EAAE,IAAe;IACnD,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAA;IAEtC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;IACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IAE7B,OAAO,IAAI,CAAC,OAAO,CAAA;AACrB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,EAAU;IACvC,IAAI,CAAC,CAAC,MAAM,iBAAiB,CAAC,EAAE,CAAC,CAAC;QAAE,OAAO,IAAI,CAAA;IAE/C,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;QAElC,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QAE5C,MAAM,CAAC,IAA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CAAC,CAAA;AACjF,CAAC,CAAA;AAED,IAAI,MAAM,GAAoD,GAAG,EAAE;IACjE,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAA;AACjF,CAAC,CAAA;AAED,IAAI,QAAQ,GAAsD,GAAG,EAAE;IACrE,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;AACnF,CAAC,CAAA;AAED,MAAM,UAAU,aAAa,CAAC,KAI7B;IACC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAA;IAC/B,MAAM,GAAG,KAAK,CAAC,MAAM,CAAA;IACrB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAA;AAC3B,CAAC;AAED,MAAM,UAAU,GAAG,IAAI,OAAO,EAA4B,CAAA;AAE1D;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,EAAU;IAC1C,IAAI,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IAE9B,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG,OAAO,CAAC,OAAO,EAAE;aACtB,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;aACxB,IAAI,CACH,GAAG,EAAE,CAAC,IAAI,EACV,GAAG,EAAE,CAAC,KAAK,CACZ,CAAA;QACH,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;IAC3B,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["// The browser half of `query()`: send a read as a GET.\n//\n// That is the whole of it. There is no cache here, no batching and no\n// deduplication, because TanStack Query and SWR already do those and do them\n// better — this owns the transport and they own everything above it.\n//\n// The awkward fact it is built around: a server function's id is not readable\n// from the client. React keeps it in a module-private WeakMap and exposes no\n// getter, so there is no `ref.$$id` to build a url from. What the client *can*\n// do is call the reference and be handed the id by React itself — the stub's\n// whole body is `callServer(id, args)`, and this package already owns\n// `callServer`.\n//\n// So a read opens a one-shot slot and calls the reference; the transport claims\n// the slot and sends a GET instead of posting. The slot is also what says this\n// is a read at all: calling `getListings(kind)` directly is still a POST, and\n// `fetchQuery(getListings, [kind])` is the same call as a GET. Nothing has to\n// know a list of query ids, on either side of the build.\n\n/** Where reads are answered. Must match HEADER.queryPath on the server. */\nconst QUERY_PATH = '/_rsc/query'\n\n/**\n * Sent on every read, and required by the endpoint.\n *\n * Not decoration. A GET with no unusual header is a *simple* request, so any\n * page anywhere can trigger one with `<img src=\"…/_rsc/query?…\">` and it goes\n * out with the visitor's cookies — CORS stops the attacker reading the answer,\n * but the read still runs. This header is not CORS-safelisted, so the browser\n * preflights it, and nothing here answers a preflight.\n *\n * That restores exactly the protection a POST had: a `POST` carrying\n * `X-RSC-Action` is non-simple for the same reason.\n */\nconst QUERY_HEADER = 'X-RSC-Query'\n\n/**\n * How long a url may get before the read goes as a POST instead.\n *\n * Conservative. Proxies and CDNs start refusing somewhere between 8k and 16k,\n * and the failure is a 414 from a machine that is not ours.\n */\nconst MAX_URL = 6_000\n\ntype Reader = (...args: unknown[]) => Promise<unknown>\n\n/**\n * The slot a read opens before calling the reference.\n *\n * One-shot and synchronous: React's stub calls `callServer` in its own body\n * with nothing awaited in between, so exactly one transport call can claim it.\n */\nlet slot: { claimed: boolean; promise: Promise<unknown> | null } | null = null\n\n/**\n * Claim the open slot, if a read opened one.\n *\n * Called from the app's `callServer` before it posts. Returns null when this is\n * an ordinary action, which is every call that did not come through\n * `fetchQuery`.\n */\nexport function claimRead(id: string, args: unknown[]): Promise<unknown> | null {\n if (!slot || slot.claimed) return null\n\n slot.claimed = true\n slot.promise = send(id, args)\n\n return slot.promise\n}\n\n/**\n * A server reference's id, or null for anything else.\n *\n * React keeps the id private, but encoding a reference to send back writes\n * it out: the reference becomes `$h<part>`, and the part is `{ id, bound }`.\n * That is the reply protocol the server decodes, so it cannot drift on one\n * side alone. Nothing is called - calling a bound reference to learn its id\n * would reach callServer a tick later, and run the action.\n *\n * A bound reference answers null: what it was bound to is part of what it\n * does, and the id alone does not say it.\n */\nexport async function actionId(fn: object): Promise<string | null> {\n if (!(await isServerReference(fn))) return null\n\n try {\n const encoded = await encode([fn])\n\n if (typeof encoded === 'string') return null\n\n const [root] = JSON.parse(String(encoded.get('0'))) as unknown[]\n\n if (typeof root !== 'string' || !root.startsWith('$h')) return null\n\n const part = JSON.parse(String(encoded.get(String(parseInt(root.slice(2), 16))))) as { id?: unknown; bound?: unknown }\n\n return typeof part.id === 'string' && part.bound == null ? part.id : null\n } catch {\n return null\n }\n}\n\n/**\n * Read a query, over GET.\n *\n * Hand this to a cache library and let it decide everything else:\n *\n * queryFn: () => fetchQuery(getListings, [kind])\n * useSWR(['listings', kind], () => fetchQuery(getListings, [kind]))\n *\n * Every call goes to the server, which is what a fetcher needs — staleness,\n * revalidation, retries, polling and deduplication all belong to the library\n * holding the answer, not to the thing that fetches it.\n */\nexport function fetchQuery<Data>(reference: () => Promise<Data>, args?: []): Promise<Data>\n// The query's own parameters, so a wrong key fails the typecheck rather than\n// the read. NoInfer keeps the tuple from being inferred from the call site,\n// where a wrong key would simply widen it.\nexport function fetchQuery<Args extends unknown[], Data>(\n reference: (...args: Args) => Promise<Data>,\n args: NoInfer<Args>,\n): Promise<Data>\nexport function fetchQuery<Data>(\n reference: (...args: never[]) => Promise<Data>,\n args: unknown[] = [],\n): Promise<Data> {\n if (typeof window === 'undefined') {\n // React's SSR runtime refuses a server-function call during the initial\n // render, and reaching a query's id means calling its reference — so this\n // cannot work here. Raised with the fix in it rather than left to surface\n // as React's more general message about fetch waterfalls.\n //\n // A cache library runs its fetcher in an effect, so the server render never\n // reaches this; a server component that wants the data during render should\n // await the query directly, which needs none of this.\n throw new Error(\n 'A query was read during server rendering. Read it in a server component with await, or through a cache library, whose fetcher runs after hydration.',\n )\n }\n\n const opened = { claimed: false, promise: null as Promise<unknown> | null }\n\n slot = opened\n\n try {\n // React's stub reaches callServer synchronously, so the slot is claimed by\n // the time this returns. The stub's own promise is discarded: the one the\n // transport made is the one that settles with the answer.\n ;(reference as unknown as Reader)(...(args as unknown[]))\n } finally {\n // Cleared here and nowhere else, so a reference that throws on the way in\n // does not leave the slot open for the next read to claim by accident.\n // Nothing is returned from this block: a `return` in `finally` discards\n // whatever the `try` was throwing, which would turn a reference that threw\n // synchronously into the misleading bound-reference error below.\n slot = null\n }\n\n if (!opened.claimed || !opened.promise) {\n // The only way here is a reference whose call path is asynchronous, which\n // today means one that was `.bind()`-ed. Loud, because the quiet version is\n // a read that silently went out as a POST.\n throw new Error(\n 'A query was called through a bound reference. Pass the exported query itself, unbound.',\n )\n }\n\n return opened.promise as Promise<Data>\n}\n\nasync function send(id: string, args: unknown[]): Promise<unknown> {\n const encoded = await encode(args)\n\n // encodeReply answers with FormData the moment an argument holds a File, and\n // a url cannot carry one. Rather than refuse a call that would have worked as\n // an action, the read falls back to a POST: it stops being cacheable, which\n // is the only thing it loses.\n if (typeof encoded !== 'string') return await post(id, args, 'an argument contained a File')\n\n const url = `${QUERY_PATH}?id=${encodeURIComponent(id)}&args=${encodeURIComponent(encoded)}`\n\n if (url.length > MAX_URL) return await post(id, args, 'the arguments are too large for a url')\n\n const res = await fetch(url, {\n headers: {\n [QUERY_HEADER]: '1',\n Accept: 'text/x-component',\n // Where the read came from. Same reason an action sends it: a host that\n // guards by route needs to know which page is asking.\n 'X-RSC-Referer': window.location.pathname + window.location.search,\n },\n })\n\n if (!res.ok || !res.body) {\n throw await failureFrom(res)\n }\n\n return await deserialize(res.body)\n}\n\n/**\n * What a refused read rejects with.\n *\n * A cache library reports failure by rejection, so this has to be an Error —\n * and one carrying the message the server meant, rather than a status code. A\n * validation refusal keeps its fields on `errors`, where a form can read them.\n */\nasync function failureFrom(res: Response): Promise<Error> {\n const body = await res.text().catch(() => '')\n\n try {\n const parsed = JSON.parse(body) as { message?: string; errors?: Record<string, string[]>; refusal?: unknown }\n const error = new Error(parsed.message || `Query failed: ${res.status}`) as Error & {\n errors?: unknown\n refusal?: unknown\n status?: number\n }\n\n if (parsed.errors) error.errors = parsed.errors\n // The data a refusal declared with .refusal(schema), checked on the server.\n if (parsed.refusal !== undefined) error.refusal = parsed.refusal\n error.status = res.status\n\n return error\n } catch {\n return new Error(body || `Query failed: ${res.status}`)\n }\n}\n\n/**\n * The same read, as an action.\n *\n * Reached only when the arguments cannot ride in a url. Warned about in\n * development rather than silently tolerated, because the read still works and\n * the thing that changed — it is no longer a GET, so nothing can cache it — is\n * otherwise invisible.\n */\nasync function post(id: string, args: unknown[], why: string): Promise<unknown> {\n if (import.meta.env?.DEV) {\n console.warn(`[rsc-kit] A query was sent as a POST because ${why}. It will not be cached.`)\n }\n\n return await asAction(id, args)\n}\n\n/**\n * The Flight codec and the action transport, installed by the app bootstrap.\n *\n * Injected rather than imported, and not for testing: this module is reached\n * from client components, so importing the browser runtime here would pull a\n * second copy of it into that graph — two client-reference registries, where\n * components resolve to undefined with nothing logged. The bootstrap already\n * holds the one true copy.\n */\nlet deserialize: (stream: ReadableStream) => Promise<unknown> = () => {\n throw new Error('No Flight decoder installed. createViteRscApp() sets one up.')\n}\n\nlet encode: (args: unknown[]) => Promise<string | FormData> = () => {\n throw new Error('No Flight encoder installed. createViteRscApp() sets one up.')\n}\n\nlet asAction: (id: string, args: unknown[]) => Promise<unknown> = () => {\n throw new Error('No action transport installed. createViteRscApp() sets one up.')\n}\n\nexport function setQueryCodec(codec: {\n deserialize: (stream: ReadableStream) => Promise<unknown>\n encode: (args: unknown[]) => Promise<string | FormData>\n asAction: (id: string, args: unknown[]) => Promise<unknown>\n}): void {\n deserialize = codec.deserialize\n encode = codec.encode\n asAction = codec.asAction\n}\n\nconst references = new WeakMap<object, Promise<boolean>>()\n\n/**\n * Whether `fn` is a server reference, asked of Flight before anything calls\n * it: one it can send back to the server encodes, and a function of the\n * browser's own is refused. React keeps its registry of references private,\n * and calling to find out would run a plain function.\n *\n * False wherever there is no encoder - a page with no runtime, a test.\n */\nexport function isServerReference(fn: object): Promise<boolean> {\n let known = references.get(fn)\n\n if (!known) {\n known = Promise.resolve()\n .then(() => encode([fn]))\n .then(\n () => true,\n () => false,\n )\n references.set(fn, known)\n }\n\n return known\n}\n"]}
package/dist/vite.d.ts CHANGED
@@ -393,6 +393,46 @@ declare let hostCallsCommand: {
393
393
  } | null;
394
394
  /** The backend's actions by module - its path under server-actions/ - and then by export. */
395
395
  export type HostActions = Record<string, Record<string, string>>;
396
+ /**
397
+ * What the backend offers the app, read from a file it wrote:
398
+ *
399
+ * {
400
+ * "actions": { "ordersCreate": "Orders.create" },
401
+ * "functions": ["Orders.create", "Orders.recent"]
402
+ * }
403
+ *
404
+ * `actions` are the server actions the build writes "use server" stubs for,
405
+ * by JavaScript name. `functions` are the names rpc() may be called with,
406
+ * which the build turns into a type so a misspelt one fails the typecheck.
407
+ *
408
+ * A file rather than an environment variable, because the backend no longer
409
+ * drives the build - `vite build` does. Discovery has to stay where the code
410
+ * is (reflection through Composer's autoloader finds what a class inherits; a
411
+ * regex would silently miss every inherited action), but the handoff is just
412
+ * names, and a JSON file is something any language can write:
413
+ *
414
+ * php artisan rsc:host-manifest
415
+ * go run ./backend -manifest rsc-host.json
416
+ *
417
+ * Absent is not an error: a backend-less app has no file. `hostManifest`
418
+ * runs the command as dev or a build starts.
419
+ */
420
+ /** A JSON Schema, the subset a backend describes its types with. */
421
+ type JsonSchema = Record<string, unknown>;
422
+ /** One action's entry under `schemas` in rsc-host.json. */
423
+ export interface HostFormSchema {
424
+ schema: JsonSchema;
425
+ /** Field path (`*` for any list index), then JSON Schema keyword, to a message. */
426
+ messages?: Record<string, Record<string, string>>;
427
+ }
428
+ /**
429
+ * `schemas` as the backend wrote it, or a loud refusal. A schema that is not
430
+ * an object, or messages that are not strings, would load in the browser and
431
+ * then check nothing, or say nothing - a form quietly less checked than the
432
+ * backend says it is.
433
+ */
434
+ /** @internal */
435
+ export declare function checkHostSchemas(raw: unknown, functions: string[] | null): Record<string, HostFormSchema>;
396
436
  /**
397
437
  * rscKit({ headers }), in the case the contract spells each name. Refused at
398
438
  * build, never trimmed at runtime: a header that was asked for and quietly not
package/dist/vite.js CHANGED
@@ -311,6 +311,11 @@ let hostDefs = {};
311
311
  * sent a check - a backend that has never heard of one would run the call.
312
312
  */
313
313
  let hostValidates = [];
314
+ /**
315
+ * Each action's input as JSON Schema, with the backend's own messages, by
316
+ * function: what `<Form>` checks in the browser - see js/formSchemas.ts.
317
+ */
318
+ let hostSchemas = {};
314
319
  /** Where the backend wrote each function, when it says. */
315
320
  let hostSources = {};
316
321
  /** The command a build asks what rpc() answers; see hostManifest.calls. */
@@ -445,6 +450,42 @@ function tsFilesUnder(dir) {
445
450
  .filter((f) => f.endsWith(".ts"))
446
451
  .map((f) => join(dir, f));
447
452
  }
453
+ /**
454
+ * `schemas` as the backend wrote it, or a loud refusal. A schema that is not
455
+ * an object, or messages that are not strings, would load in the browser and
456
+ * then check nothing, or say nothing - a form quietly less checked than the
457
+ * backend says it is.
458
+ */
459
+ /** @internal */
460
+ export function checkHostSchemas(raw, functions) {
461
+ // An empty map is an empty list to PHP's json_encode.
462
+ if (raw === undefined || (Array.isArray(raw) && raw.length === 0))
463
+ return {};
464
+ const fail = (why) => {
465
+ throw new Error(`[rsc-kit] ${HOST_FILE}: ${why}`);
466
+ };
467
+ const isMap = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
468
+ if (!isMap(raw))
469
+ fail('"schemas" must map a function name to { schema, messages }.');
470
+ for (const [name, entry] of Object.entries(raw)) {
471
+ if (functions && !functions.includes(name))
472
+ fail(`"schemas" names ${name}, which is not one of the backend's functions.`);
473
+ if (!isMap(entry) || !isMap(entry.schema))
474
+ fail(`"schemas"."${name}" must be { schema: <a JSON Schema object>, messages? }.`);
475
+ const messages = entry.messages;
476
+ if (messages !== undefined && !(Array.isArray(messages) && messages.length === 0)) {
477
+ const ok = isMap(messages) && Object.values(messages).every((m) => (Array.isArray(m) && m.length === 0) || (isMap(m) && Object.values(m).every((t) => typeof t === "string")));
478
+ if (!ok)
479
+ fail(`"schemas"."${name}".messages must map a field to { keyword: message }.`);
480
+ }
481
+ }
482
+ return Object.fromEntries(Object.entries(raw).map(([name, { schema, messages }]) => [
483
+ name,
484
+ isMap(messages) && Object.keys(messages).length > 0
485
+ ? { schema, messages: Object.fromEntries(Object.entries(messages).filter(([, m]) => isMap(m))) }
486
+ : { schema },
487
+ ]));
488
+ }
448
489
  function fileHostManifest(root) {
449
490
  const path = join(root, HOST_FILE);
450
491
  if (!existsSync(path)) {
@@ -452,7 +493,7 @@ function fileHostManifest(root) {
452
493
  throw new Error("[rsc-kit] rsc-host-actions.json is the old manifest. The backend now writes " +
453
494
  HOST_FILE + " - { actions, functions } - so update the adapter and run its manifest command.");
454
495
  }
455
- return { actions: {}, functions: null, types: {}, defs: {}, validates: [], sources: {}, calls: null };
496
+ return { actions: {}, functions: null, types: {}, defs: {}, validates: [], schemas: {}, sources: {}, calls: null };
456
497
  }
457
498
  let parsed;
458
499
  try {
@@ -485,6 +526,7 @@ function fileHostManifest(root) {
485
526
  // The reserved guard call is the engine's to make, not the app's.
486
527
  functions: functions ? functions.filter((n) => !n.startsWith("__rsc.")).sort() : null,
487
528
  validates: validates ?? [],
529
+ schemas: checkHostSchemas(parsed?.schemas, functions ?? null),
488
530
  // Only what a position can be read from. The editor's, and nothing the
489
531
  // app does: a malformed one is a name with nowhere to go, not a failure.
490
532
  sources: Object.fromEntries(Object.entries(isMap(parsed?.sources) ? parsed.sources : {}).filter(([, at]) => isMap(at) && typeof at.file === "string" && at.file !== "" && Number.isInteger(at.line) && at.line > 0)),
@@ -501,14 +543,7 @@ function fileHostManifest(root) {
501
543
  * two cannot drift.
502
544
  */
503
545
  function aliasEntries() {
504
- const entries = [
505
- // A library written for Next reads the request through next/headers -
506
- // Vercel's flags SDK does, through `flags/next` - and headers() and
507
- // cookies() here have the same names and shapes, with one object per
508
- // request, which is what its per-request dedupe keys on. Answered by
509
- // this package, so such a library runs unchanged and without Next.
510
- { find: /^next\/headers$/, replacement: join(packageDir, "request") },
511
- ];
546
+ const entries = [];
512
547
  if (!packageAlias)
513
548
  return entries;
514
549
  if (existsSync(join(projectRoot, "node_modules", packageAlias)))
@@ -861,13 +896,14 @@ function loadHostManifest(options, before = false) {
861
896
  // checked when it lands.
862
897
  if (!before || !options.hostManifest)
863
898
  throw error;
864
- manifest = { actions: {}, functions: null, types: {}, defs: {}, validates: [], sources: {}, calls: null };
899
+ manifest = { actions: {}, functions: null, types: {}, defs: {}, validates: [], schemas: {}, sources: {}, calls: null };
865
900
  }
866
901
  hostActions = options.hostActions ? checkHostActions(options.hostActions, "rscKit({ hostActions })") : manifest.actions;
867
902
  hostFunctions = manifest.functions;
868
903
  hostTypes = manifest.types;
869
904
  hostDefs = manifest.defs;
870
905
  hostValidates = manifest.validates;
906
+ hostSchemas = manifest.schemas;
871
907
  hostSources = manifest.sources;
872
908
  hostCallsCommand = buildCallsCommand(options.hostManifest, manifest.calls);
873
909
  }
@@ -3188,6 +3224,38 @@ function commandsPlugin() {
3188
3224
  },
3189
3225
  };
3190
3226
  }
3227
+ const FORM_SCHEMAS_ID = "virtual:rsc-kit/form-schemas";
3228
+ const FORM_SCHEMA_ID = "virtual:rsc-kit/form-schema/";
3229
+ /**
3230
+ * The browser's side of `schemas` in rsc-host.json: an index of each action
3231
+ * stub with a schema beside a loader for its chunk, and one chunk per
3232
+ * function. The index imports the stubs themselves, so in the browser they
3233
+ * are the same references a form is handed, and their ids are React's -
3234
+ * never computed here. See js/formSchemas.ts.
3235
+ */
3236
+ function formSchemasPlugin() {
3237
+ return {
3238
+ name: "rsc-kit:form-schemas",
3239
+ resolveId(id) {
3240
+ if (id === FORM_SCHEMAS_ID || id.startsWith(FORM_SCHEMA_ID))
3241
+ return "\0" + id;
3242
+ },
3243
+ load(id) {
3244
+ if (id === "\0" + FORM_SCHEMAS_ID) {
3245
+ const modules = Object.entries(hostActions);
3246
+ const imports = modules.map(([module], i) => `import * as __s${i} from ${JSON.stringify(join(sourceDir, HOST_ACTIONS_DIR, module + ".ts"))}`);
3247
+ const entries = modules.flatMap(([, exports], i) => Object.entries(exports)
3248
+ .filter(([, target]) => hostSchemas[target])
3249
+ .map(([name, target]) => ` [__s${i}[${JSON.stringify(name)}], () => import(${JSON.stringify(FORM_SCHEMA_ID + target)})]`));
3250
+ return [...imports, `export const entries = [\n${entries.join(",\n")}\n]`, ""].join("\n");
3251
+ }
3252
+ if (id.startsWith("\0" + FORM_SCHEMA_ID)) {
3253
+ const described = hostSchemas[id.slice(FORM_SCHEMA_ID.length + 1)];
3254
+ return `export default ${JSON.stringify(described ?? null)}\n`;
3255
+ }
3256
+ },
3257
+ };
3258
+ }
3191
3259
  /** The module behind the synthesised /openapi.json route. */
3192
3260
  function openApiPlugin() {
3193
3261
  return {
@@ -7462,12 +7530,18 @@ function generateEntryBrowser() {
7462
7530
  const refreshModule = join(packageDir, "js/navigate");
7463
7531
  const chunkPreload = join(packageDir, "js/chunkPreload");
7464
7532
  const devErrorOverlay = join(packageDir, "js/devErrorOverlay");
7533
+ // Only when the backend described an action's input: otherwise no form
7534
+ // looks for one, and the entry is what it was.
7535
+ const formSchemas = Object.values(hostActions).some((exports) => Object.values(exports).some((target) => hostSchemas[target]))
7536
+ ? `import { setFormSchemas } from ${JSON.stringify(join(packageDir, "js/formSchemas"))}\n` +
7537
+ `setFormSchemas(() => import(${JSON.stringify(FORM_SCHEMAS_ID)}))\n`
7538
+ : "";
7465
7539
  return `// GENERATED by rscKit() — do not edit.
7466
7540
  import { createViteRscApp } from ${JSON.stringify(clientBootstrap)}
7467
7541
  import { refresh } from ${JSON.stringify(refreshModule)}
7468
7542
  import { setChunkLoader } from ${JSON.stringify(chunkPreload)}
7469
7543
  import * as clientReferences from 'virtual:vite-rsc/client-references'
7470
-
7544
+ ${formSchemas}
7471
7545
  // How a client component's id becomes its chunk, for loading the ones a
7472
7546
  // prefetched page uses before the tap - see chunkPreload.ts. The same map the
7473
7547
  // runtime loads them through, so a chunk loaded here is the one it finds.
@@ -9713,6 +9787,7 @@ export function rscKit(options = {}) {
9713
9787
  serverRendererInRsc(),
9714
9788
  metadataRoutesPlugin(),
9715
9789
  openApiPlugin(),
9790
+ formSchemasPlugin(),
9716
9791
  commandsPlugin(),
9717
9792
  extendableClientReferences(),
9718
9793
  stableComponentNames(),