@rsc-kit/core 0.26.0 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/changed.d.ts +152 -5
- package/dist/changed.js +260 -20
- package/dist/changed.js.map +1 -1
- package/dist/compress.js +8 -1
- package/dist/compress.js.map +1 -1
- package/dist/events.d.ts +21 -3
- package/dist/events.js +31 -6
- package/dist/events.js.map +1 -1
- package/dist/headers.d.ts +6 -0
- package/dist/headers.js +6 -0
- package/dist/headers.js.map +1 -1
- package/dist/host.d.ts +3 -1
- package/dist/host.js +15 -2
- package/dist/host.js.map +1 -1
- package/dist/js/changesStore.js +40 -7
- package/dist/js/changesStore.js.map +1 -1
- package/dist/js/navigate.d.ts +1 -1
- package/dist/js/navigate.js +4 -1
- package/dist/js/navigate.js.map +1 -1
- package/dist/js/refreshOn.js +6 -1
- package/dist/js/refreshOn.js.map +1 -1
- package/dist/js/router.d.ts +2 -0
- package/dist/js/router.js +7 -0
- package/dist/js/router.js.map +1 -1
- package/dist/js/section.d.ts +11 -0
- package/dist/js/section.js +12 -3
- package/dist/js/section.js.map +1 -1
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js.map +1 -1
- package/dist/sharedRenders.d.ts +9 -0
- package/dist/sharedRenders.js +41 -0
- package/dist/sharedRenders.js.map +1 -0
- package/dist/testing.js +6 -0
- package/dist/testing.js.map +1 -1
- package/dist/vite.js +45 -7
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/js/section.js
CHANGED
|
@@ -29,14 +29,16 @@ import { RefreshOn } from "./refreshOn";
|
|
|
29
29
|
* Two pages may both call theirs 'stats'.
|
|
30
30
|
*/
|
|
31
31
|
/** Where the unwrapped component hangs off the wrapper section() returns. */
|
|
32
|
-
const INNER = Symbol.for(
|
|
32
|
+
const INNER = Symbol.for("@rsc-kit/core.section-component");
|
|
33
|
+
/** Set on the wrapper of a section declared `shared`. */
|
|
34
|
+
const SHARED = Symbol.for("@rsc-kit/core.section-shared");
|
|
33
35
|
export function section(name, Component, options = {}) {
|
|
34
36
|
const { refreshOn } = options;
|
|
35
37
|
// The names render inside the boundary, with the component, so a refresh -
|
|
36
38
|
// which renders the inside alone - carries the versions it saw.
|
|
37
39
|
const Inner = refreshOn
|
|
38
40
|
? function RefreshOnSection(props) {
|
|
39
|
-
return createElement(Fragment, null, createElement(RefreshOn, { key:
|
|
41
|
+
return createElement(Fragment, null, createElement(RefreshOn, { key: "refreshOn", target: name, refreshOn, props }), createElement(Component, { key: "section", ...props }));
|
|
40
42
|
}
|
|
41
43
|
: Component;
|
|
42
44
|
// The boundary wraps the component here rather than at the call site, so a
|
|
@@ -49,6 +51,8 @@ export function section(name, Component, options = {}) {
|
|
|
49
51
|
Section.displayName = `Section(${name})`;
|
|
50
52
|
// Reached through the route's own module, never through a shared map.
|
|
51
53
|
Section[INNER] = Inner;
|
|
54
|
+
if (options.shared)
|
|
55
|
+
Section[SHARED] = true;
|
|
52
56
|
return Section;
|
|
53
57
|
}
|
|
54
58
|
/**
|
|
@@ -64,8 +68,13 @@ export function section(name, Component, options = {}) {
|
|
|
64
68
|
* any url, bounded only by whatever guard happened to sit on the url asked for.
|
|
65
69
|
*/
|
|
66
70
|
export function sectionComponent(exported) {
|
|
67
|
-
if (typeof exported !==
|
|
71
|
+
if (typeof exported !== "function")
|
|
68
72
|
return undefined;
|
|
69
73
|
return exported[INNER];
|
|
70
74
|
}
|
|
75
|
+
/** Whether a section module's export was declared `shared`. */
|
|
76
|
+
export function isSharedSection(exported) {
|
|
77
|
+
return (typeof exported === "function" &&
|
|
78
|
+
exported[SHARED] === true);
|
|
79
|
+
}
|
|
71
80
|
//# sourceMappingURL=section.js.map
|
package/dist/js/section.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"section.js","sourceRoot":"","sources":["../../src/js/section.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OA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;IAC3E,qDAAqD;IACrD,SAAS,OAAO,CAAC,KAAQ;QACvB,sEAAsE;QACtE,oDAAoD;QACpD,OAAO,aAAa,CAClB,YAA+C,EAC/C,EAAE,IAAI,EAAE,EACR,aAAa,CAAC,KAA6B,EAAE,KAAc,CAAC,CAC7D,CAAC;IACJ,CAAC;IAED,OAAO,CAAC,WAAW,GAAG,WAAW,IAAI,GAAG,CAAC;IACzC,sEAAsE;IACrE,OAA8C,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;IAC/D,IAAI,OAAO,CAAC,MAAM;QACf,OAA8C,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAEjE,OAAO,OAA2B,CAAC;AACrC,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,gBAAgB,CAC9B,QAAiB;IAEjB,IAAI,OAAO,QAAQ,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IAErD,OAAQ,QAA+C,CAAC,KAAK,CACT,CAAC;AACvD,CAAC;AAED,+DAA+D;AAC/D,MAAM,UAAU,eAAe,CAAC,QAAiB;IAC/C,OAAO,CACL,OAAO,QAAQ,KAAK,UAAU;QAC7B,QAA+C,CAAC,MAAM,CAAC,KAAK,IAAI,CAClE,CAAC;AACJ,CAAC","sourcesContent":["import { Fragment, createElement } from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport { SlotBoundary } from \"./SlotBoundary\";\nimport { RefreshOn } from \"./refreshOn\";\nimport type { RefreshOnList } from \"./refreshOn\";\n\n/**\n * Mark a region of a page as separately refreshable.\n *\n * Deliberately not a client module. The boundary it wraps things in is one,\n * but the things it wraps are server components — an async component that\n * fetches its own data. Marking this file \"use client\" would turn every one of\n * them into a client reference, which async components cannot be.\n *\n * export default section('orders', async function Orders() { ... })\n *\n * The page renders it like any component. What it buys is a name the server\n * can address: `Rsc::revalidate('orders')` re-renders this and nothing else,\n * and the answer replaces it in place.\n *\n * With `refreshOn`, it also says what it depends on, and refreshes itself when\n * that changes - from a webhook, a job, another visitor - with nothing polling:\n *\n * export default section('repos', Repos, {\n * refreshOn: ({ params }) => [`team:${params.team}:repos`],\n * })\n *\n * The name has to be unique within the page. It does not have to be unique in\n * the app: the component is carried on the wrapper it returns, so the server\n * resolves a section through the module the route declares rather than by\n * looking the name up in a registry every section in the app also writes to.\n * Two pages may both call theirs 'stats'.\n */\n\n/** Where the unwrapped component hangs off the wrapper section() returns. */\nconst INNER = Symbol.for(\"@rsc-kit/core.section-component\");\n\n/** Set on the wrapper of a section declared `shared`. */\nconst SHARED = Symbol.for(\"@rsc-kit/core.section-shared\");\n\nexport interface SectionOptions<P> {\n /**\n * What this section refreshes on: names for the data it shows, or a\n * function of the section's props - the page's params and searchParams -\n * that makes them. When one is said to have changed, the section refreshes.\n */\n refreshOn?: RefreshOnList<P>;\n /**\n * The section renders the same for everyone allowed to see the page, so\n * when a change makes many tabs ask for it, one render answers them all.\n * Each tab's guards still run on its own request; only the render is\n * shared. Never set it on a section that shows anything per visitor - their\n * name, their data, what they may do: the first tab's render is what every\n * other tab is shown.\n */\n shared?: boolean;\n}\n\nexport function section<P extends Record<string, unknown>>(\n name: string,\n Component: ComponentType<P>,\n options: SectionOptions<P> = {},\n): ComponentType<P> {\n const { refreshOn } = options;\n\n // The names render inside the boundary, with the component, so a refresh -\n // which renders the inside alone - carries the versions it saw.\n const Inner: ComponentType<P> = refreshOn\n ? function RefreshOnSection(props: P): ReactNode {\n return createElement(\n Fragment,\n null,\n createElement(\n RefreshOn as ComponentType<never>,\n { key: \"refreshOn\", target: name, refreshOn, props } as never,\n ),\n createElement(\n Component as ComponentType<never>,\n { key: \"section\", ...(props as object) } as never,\n ),\n );\n }\n : Component;\n\n // The boundary wraps the component here rather than at the call site, so a\n // page renders a section exactly like anything else.\n function Section(props: P): ReactNode {\n // createElement cannot line its overloads up with a component generic\n // over its own props. The call is the ordinary one.\n return createElement(\n SlotBoundary as ComponentType<{ name: string }>,\n { name },\n createElement(Inner as ComponentType<never>, props as never),\n );\n }\n\n Section.displayName = `Section(${name})`;\n // Reached through the route's own module, never through a shared map.\n (Section as unknown as Record<symbol, unknown>)[INNER] = Inner;\n if (options.shared)\n (Section as unknown as Record<symbol, unknown>)[SHARED] = true;\n\n return Section as ComponentType<P>;\n}\n\n/**\n * The component inside a section module, without its boundary.\n *\n * Revalidation renders this rather than the wrapper: the client swaps what is\n * inside the boundary, so returning the wrapper would nest a new boundary\n * inside the old one on every refresh.\n *\n * Takes the module's own export rather than a name. A name-keyed registry is\n * written to by every section in the app at bundle load — the generated entry\n * imports them all eagerly — so a lookup by name reached any page's region from\n * any url, bounded only by whatever guard happened to sit on the url asked for.\n */\nexport function sectionComponent(\n exported: unknown,\n): ComponentType<Record<string, unknown>> | undefined {\n if (typeof exported !== \"function\") return undefined;\n\n return (exported as unknown as Record<symbol, unknown>)[INNER] as\n ComponentType<Record<string, unknown>> | undefined;\n}\n\n/** Whether a section module's export was declared `shared`. */\nexport function isSharedSection(exported: unknown): boolean {\n return (\n typeof exported === \"function\" &&\n (exported as unknown as Record<symbol, unknown>)[SHARED] === true\n );\n}\n"]}
|
package/dist/manifest.d.ts
CHANGED
|
@@ -121,6 +121,12 @@ export interface RouteManifest {
|
|
|
121
121
|
* `X-RSC-Kit` (how a response was served) is sent regardless.
|
|
122
122
|
*/
|
|
123
123
|
identify?: boolean;
|
|
124
|
+
/**
|
|
125
|
+
* Whether any page or section declares `refreshOn`, so the server signs
|
|
126
|
+
* names - and must refuse to serve, in production, without a key every
|
|
127
|
+
* instance shares.
|
|
128
|
+
*/
|
|
129
|
+
refreshOn?: boolean;
|
|
124
130
|
};
|
|
125
131
|
routes: ManifestRoute[];
|
|
126
132
|
intercepts: ManifestIntercept[];
|
package/dist/manifest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,uCAAuC;AACvC,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,oBAAoB","sourcesContent":["// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,uCAAuC;AACvC,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,oBAAoB","sourcesContent":["// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n /**\n * Whether any page or section declares `refreshOn`, so the server signs\n * names - and must refuse to serve, in production, without a key every\n * instance shares.\n */\n refreshOn?: boolean;\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** How long one change's render is kept for tabs still arriving. */
|
|
2
|
+
export declare const SHARED_RENDER_MS = 10000;
|
|
3
|
+
/**
|
|
4
|
+
* The render for `key`: the one already done or under way, or `render`'s.
|
|
5
|
+
* A render that fails is not kept - the next tab tries again.
|
|
6
|
+
*/
|
|
7
|
+
export declare function shareRender(key: string, render: () => Promise<string>): Promise<string>;
|
|
8
|
+
/** For tests. */
|
|
9
|
+
export declare function resetSharedRenders(): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// One render of a shared section per change, however many tabs ask for it.
|
|
2
|
+
//
|
|
3
|
+
// A name moves; every tab showing a section that refreshes on it asks for
|
|
4
|
+
// that section within a moment of each other. For a section declared
|
|
5
|
+
// `shared` - the same for everyone allowed to see the page - those asks are
|
|
6
|
+
// for the same thing, and the first one's render answers the rest. Keyed on
|
|
7
|
+
// the change that triggered the ask (`stock@5`), so an answer is never older
|
|
8
|
+
// than the change it was asked for, and a refresh that is not about a change
|
|
9
|
+
// - refresh() by hand, an action's - is never shared at all.
|
|
10
|
+
/** How long one change's render is kept for tabs still arriving. */
|
|
11
|
+
export const SHARED_RENDER_MS = 10_000;
|
|
12
|
+
/** At most this many renders are held at once; the oldest is dropped first. */
|
|
13
|
+
const MAX_HELD = 500;
|
|
14
|
+
const held = new Map();
|
|
15
|
+
/**
|
|
16
|
+
* The render for `key`: the one already done or under way, or `render`'s.
|
|
17
|
+
* A render that fails is not kept - the next tab tries again.
|
|
18
|
+
*/
|
|
19
|
+
export function shareRender(key, render) {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
const found = held.get(key);
|
|
22
|
+
if (found && now - found.at < SHARED_RENDER_MS)
|
|
23
|
+
return found.payload;
|
|
24
|
+
for (const [k, entry] of held)
|
|
25
|
+
if (now - entry.at >= SHARED_RENDER_MS)
|
|
26
|
+
held.delete(k);
|
|
27
|
+
while (held.size >= MAX_HELD)
|
|
28
|
+
held.delete(held.keys().next().value);
|
|
29
|
+
const payload = render();
|
|
30
|
+
held.set(key, { payload, at: now });
|
|
31
|
+
payload.catch(() => {
|
|
32
|
+
if (held.get(key)?.payload === payload)
|
|
33
|
+
held.delete(key);
|
|
34
|
+
});
|
|
35
|
+
return payload;
|
|
36
|
+
}
|
|
37
|
+
/** For tests. */
|
|
38
|
+
export function resetSharedRenders() {
|
|
39
|
+
held.clear();
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=sharedRenders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sharedRenders.js","sourceRoot":"","sources":["../src/sharedRenders.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,qEAAqE;AACrE,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,6DAA6D;AAE7D,oEAAoE;AACpE,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,GAAG,CAAC;AAErB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAoD,CAAC;AAEzE;;;GAGG;AACH,MAAM,UAAU,WAAW,CACzB,GAAW,EACX,MAA6B;IAE7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAE5B,IAAI,KAAK,IAAI,GAAG,GAAG,KAAK,CAAC,EAAE,GAAG,gBAAgB;QAAE,OAAO,KAAK,CAAC,OAAO,CAAC;IAErE,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,IAAI;QAC3B,IAAI,GAAG,GAAG,KAAK,CAAC,EAAE,IAAI,gBAAgB;YAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACzD,OAAO,IAAI,CAAC,IAAI,IAAI,QAAQ;QAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAe,CAAC,CAAC;IAE9E,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC;IAEzB,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;IACpC,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE;QACjB,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,OAAO;YAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,iBAAiB;AACjB,MAAM,UAAU,kBAAkB;IAChC,IAAI,CAAC,KAAK,EAAE,CAAC;AACf,CAAC","sourcesContent":["// One render of a shared section per change, however many tabs ask for it.\n//\n// A name moves; every tab showing a section that refreshes on it asks for\n// that section within a moment of each other. For a section declared\n// `shared` - the same for everyone allowed to see the page - those asks are\n// for the same thing, and the first one's render answers the rest. Keyed on\n// the change that triggered the ask (`stock@5`), so an answer is never older\n// than the change it was asked for, and a refresh that is not about a change\n// - refresh() by hand, an action's - is never shared at all.\n\n/** How long one change's render is kept for tabs still arriving. */\nexport const SHARED_RENDER_MS = 10_000;\n\n/** At most this many renders are held at once; the oldest is dropped first. */\nconst MAX_HELD = 500;\n\nconst held = new Map<string, { payload: Promise<string>; at: number }>();\n\n/**\n * The render for `key`: the one already done or under way, or `render`'s.\n * A render that fails is not kept - the next tab tries again.\n */\nexport function shareRender(\n key: string,\n render: () => Promise<string>,\n): Promise<string> {\n const now = Date.now();\n const found = held.get(key);\n\n if (found && now - found.at < SHARED_RENDER_MS) return found.payload;\n\n for (const [k, entry] of held)\n if (now - entry.at >= SHARED_RENDER_MS) held.delete(k);\n while (held.size >= MAX_HELD) held.delete(held.keys().next().value as string);\n\n const payload = render();\n\n held.set(key, { payload, at: now });\n payload.catch(() => {\n if (held.get(key)?.payload === payload) held.delete(key);\n });\n\n return payload;\n}\n\n/** For tests. */\nexport function resetSharedRenders(): void {\n held.clear();\n}\n"]}
|
package/dist/testing.js
CHANGED
|
@@ -20,6 +20,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
|
20
20
|
import { extname, join, resolve, sep } from 'node:path';
|
|
21
21
|
import { pathToFileURL } from 'node:url';
|
|
22
22
|
import { httpHostCalls } from './hostCalls.js';
|
|
23
|
+
import { configureChanged } from './changed.js';
|
|
23
24
|
import { testHostFetch } from './testHost.js';
|
|
24
25
|
export { hostReply, testChanges, HOST_MIDDLEWARE } from './testHost.js';
|
|
25
26
|
/**
|
|
@@ -167,6 +168,11 @@ export async function createTestApp(options = {}) {
|
|
|
167
168
|
const root = resolve(options.root ?? process.cwd());
|
|
168
169
|
const origin = options.origin ?? 'https://app.test';
|
|
169
170
|
built.set(root, built.get(root) ?? ensureBuilt(root, options.build ?? true));
|
|
171
|
+
// The app is built for production, which refuses to sign refreshOn names
|
|
172
|
+
// without a key. One process, one key: a fixed one, unless the test set its own.
|
|
173
|
+
if (!process.env.RSC_SIGNING_SECRET) {
|
|
174
|
+
configureChanged({ secret: 'rsc-kit-test' });
|
|
175
|
+
}
|
|
170
176
|
const bundle = await built.get(root);
|
|
171
177
|
const entry = (await import(pathToFileURL(bundle).href));
|
|
172
178
|
if (typeof entry.default !== 'function') {
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],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AAC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI;QACvB,CAAC,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,kCAAkC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACrH,CAAC,CAAC,IAAI,CAAA;IAER,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CAAC,aAAa,MAAM,iEAAiE,CAAC,CAAA;IACvG,CAAC;IAED,OAAO;QACL,MAAM;QACN,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;YAC1B,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAA;YAExD,oEAAoE;YACpE,2CAA2C;YAC3C,IAAI,IAAI;gBAAE,KAAK,CAAC,aAAc,CAAC,IAAI,CAAC,CAAA;YACpC,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,qBAAqB,EAAE,CAAC;gBACpD,MAAM,IAAI,KAAK,CAAC,aAAa,MAAM,oEAAoE,CAAC,CAAA;YAC1G,CAAC;YACD,KAAK,CAAC,qBAAqB,EAAE,CAAC,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAA;YAEtD,OAAO,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QAC5D,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["// The whole app as a function, for tests.\n//\n// import { createTestApp } from '@rsc-kit/core/testing'\n//\n// const app = await createTestApp()\n// const res = await app.fetch('/api/orders', { headers: { Cookie: 'user=ada' } })\n//\n// No port, no browser, no server process. The built entry already exports the\n// same Request → Response handler the dev server and the production server\n// both call, so a test can hand it a Request and read the Response — through\n// the real router, the real middleware, the real api routes, and the pages the\n// build stored.\n//\n// That is the tier between a unit test and a browser. An action or a route is\n// a function and can be imported and called; a browser test proves the page\n// works; this proves the app answers a url the way it is deployed, which is\n// where a route that renders fine and is served wrong shows up.\n\nimport { spawnSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { extname, join, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { httpHostCalls } from './hostCalls.js'\nimport { testHostFetch, type TestHost } from './testHost.js'\n\nexport { hostReply, testChanges, HOST_MIDDLEWARE, type HostCallInput, type HostHandler, type TestHost } from './testHost.js'\n\nexport interface TestApp {\n /** A path, not a url. The origin is whatever the app was told it is. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n /** Where the build was read from, for a test that wants to look. */\n bundle: string\n}\n\nexport interface TestAppOptions {\n /** The project. Defaults to the working directory. */\n root?: string\n /**\n * Whether to build first.\n *\n * `true` builds when the source is newer than the last build, which is what\n * a test run wants: the first run pays for it, the rest do not, and an edit\n * is picked up. `false` never builds and fails loudly if there is nothing to\n * read — for a ci step that already built.\n */\n build?: boolean\n /** The origin requests are made against. Nothing reads it; it is a url. */\n origin?: string\n /**\n * The backend, answered in the test: rpc() calls and host guards by name.\n * The app reaches it through the same client it uses against a real one,\n * so nothing listens and RSC_BACKEND is not called. See `hostReply`.\n */\n host?: TestHost\n /**\n * What answers a url this app does not own - a Go route, a Laravel page,\n * /login - in place of the backend the app forwards it to. Handed the\n * request as the backend would receive it. Without one, such a url is\n * forwarded to RSC_BACKEND, and in a test that is usually a 502.\n */\n backend?: (request: Request) => Response | Promise<Response>\n}\n\n/**\n * Where the build put the server bundle.\n *\n * Two layouts, because two ways of building. Under Nitro — every scaffolded\n * app — it is inside Nitro's own directory. On its own the plugin writes\n * <outDir>/dist/rsc. The first that exists wins.\n */\nfunction findBundle(root: string): string | null {\n const candidates = [\n join(root, 'node_modules/.nitro/vite/services/rsc/index.js'),\n join(root, '.rsc/dist/rsc/index.js'),\n join(root, 'build/dist/rsc/index.js'),\n ]\n\n return candidates.find((path) => existsSync(path)) ?? null\n}\n\n/** The newest mtime under a directory, for deciding whether a build is stale. */\nfunction newest(dir: string): number {\n if (!existsSync(dir)) return 0\n\n let latest = 0\n\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue\n\n const path = join(dir, entry.name)\n const time = entry.isDirectory() ? newest(path) : statSync(path).mtimeMs\n\n if (time > latest) latest = time\n }\n\n return latest\n}\n\n/** One build per process per root, however many test files ask. */\nconst built = new Map<string, Promise<string>>()\n\n/** The content types a test is likely to assert on; anything else is octet-stream. */\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.txt': 'text/plain; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.gif': 'image/gif',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.wasm': 'application/wasm',\n '.map': 'application/json',\n}\n\n/**\n * A file the build put in .output/public, answered the way Nitro's static\n * layer would - which the handler this harness loads does not include. The\n * handler is the rsc service: routing, pages, actions, api routes. Assets,\n * the service worker, the manifest and the icons are files Nitro serves in\n * production from .output/public, and a test that asked for /sw.js used to\n * get the router's 404 for a file the deployment serves fine - the one\n * shape this harness exists to catch, in the other direction.\n *\n * Files only, for GET and HEAD, within the directory: a path that escapes it\n * is a request for the handler, not a file.\n */\n/** @internal Exported for its test. */\nexport function staticFile(root: string, request: Request): Response | null {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n const publicDir = join(root, '.output/public')\n const pathname = decodeURIComponent(new URL(request.url).pathname)\n const file = resolve(publicDir, '.' + pathname)\n\n if (!file.startsWith(publicDir + sep) || !existsSync(file) || !statSync(file).isFile()) return null\n\n const type = CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream'\n const body = request.method === 'HEAD' ? null : readFileSync(file)\n\n return new Response(body, {\n status: 200,\n headers: { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-RSC-Kit-Test': 'static' },\n })\n}\n\n/**\n * How this project builds: its own `build` script, run by the package manager\n * this test is running under. Without a script, Vite directly - on Bun's\n * runtime when the tests are, since a bin's node shebang would otherwise\n * start it under Node.\n */\n/** @internal Exported for its test. */\nexport function buildCommand(root: string): [string, string[]] {\n const onBun = typeof process.versions.bun === 'string'\n\n let scripts: Record<string, string> = {}\n\n try {\n scripts = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')).scripts ?? {}\n } catch {\n // No package.json, or not JSON: there is no script to run.\n }\n\n if (typeof scripts.build === 'string') {\n return onBun ? ['bun', ['run', 'build']] : ['npm', ['run', 'build']]\n }\n\n return onBun ? ['bun', ['--bun', 'vite', 'build']] : ['npx', ['vite', 'build']]\n}\n\nasync function ensureBuilt(root: string, build: boolean): Promise<string> {\n const existing = findBundle(root)\n\n if (!build) {\n if (!existing) {\n throw new Error(\n `[rsc-kit] No build to test against under ${root}. Run the build first, or let createTestApp() do it by leaving \\`build\\` on.`,\n )\n }\n\n return existing\n }\n\n const fresh = existing && statSync(existing).mtimeMs > newest(join(root, 'src'))\n\n if (fresh) return existing\n\n // The user's own build command, so what is tested is what ships. A test\n // that built some other way would pass against a bundle nobody deploys -\n // and used to: this ran `npx vite build` whatever package.json said, which\n // on a Bun project built under Node and failed on the first `import 'bun'`.\n const [command, args] = buildCommand(root)\n const run = spawnSync(command, args, {\n cwd: root,\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, NODE_ENV: 'production' },\n })\n\n if (run.status !== 0) {\n throw new Error(`[rsc-kit] The build failed, so there is nothing to test:\\n${run.stderr}`)\n }\n\n const bundle = findBundle(root)\n\n if (!bundle) {\n throw new Error(\n `[rsc-kit] The build finished but no server bundle was found under ${root}. Is rscKit() in vite.config?`,\n )\n }\n\n return bundle\n}\n\n/**\n * Build the app if it needs it, load it, and hand back something to fetch from.\n *\n * Memoised per root: every test file in a run shares one build and one loaded\n * module, which is both the fast path and the correct one — two copies of the\n * server bundle in one process would be two client-reference registries.\n */\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n const root = resolve(options.root ?? process.cwd())\n const origin = options.origin ?? 'https://app.test'\n\n built.set(root, built.get(root) ?? ensureBuilt(root, options.build ?? true))\n\n const bundle = await built.get(root)!\n const entry = (await import(pathToFileURL(bundle).href)) as {\n default: (request: Request) => Promise<Response>\n installHostFn?: (fn: (name: string, ...args: unknown[]) => Promise<unknown>) => () => void\n installBackendForward?: (fn: ((request: Request) => Response | Promise<Response>) | null) => void\n }\n\n if (typeof entry.default !== 'function') {\n throw new Error(`[rsc-kit] ${bundle} does not export a request handler.`)\n }\n\n const host = options.host\n ? httpHostCalls({ endpoint: 'http://test-host/__rsc/host-call', secret: 'test', fetch: testHostFetch(options.host) })\n : null\n\n if (host && !entry.installHostFn) {\n throw new Error(`[rsc-kit] ${bundle} cannot take a host. Rebuild against the current @rsc-kit/core.`)\n }\n\n return {\n bundle,\n fetch: async (path, init) => {\n const request = new Request(new URL(path, origin), init)\n\n // Per request, not once: the loaded bundle is shared by every app a\n // run creates, and the host is this app's.\n if (host) entry.installHostFn!(host)\n if (options.backend && !entry.installBackendForward) {\n throw new Error(`[rsc-kit] ${bundle} cannot take a backend. Rebuild against the current @rsc-kit/core.`)\n }\n entry.installBackendForward?.(options.backend ?? null)\n\n return staticFile(root, request) ?? entry.default(request)\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,EAAE;AACF,0DAA0D;AAC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\n// const app = await createTestApp()\n// const res = await app.fetch('/api/orders', { headers: { Cookie: 'user=ada' } })\n//\n// No port, no browser, no server process. The built entry already exports the\n// same Request → Response handler the dev server and the production server\n// both call, so a test can hand it a Request and read the Response — through\n// the real router, the real middleware, the real api routes, and the pages the\n// build stored.\n//\n// That is the tier between a unit test and a browser. An action or a route is\n// a function and can be imported and called; a browser test proves the page\n// works; this proves the app answers a url the way it is deployed, which is\n// where a route that renders fine and is served wrong shows up.\n\nimport { spawnSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { extname, join, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { httpHostCalls } from './hostCalls.js'\nimport { configureChanged } from './changed.js'\nimport { testHostFetch, type TestHost } from './testHost.js'\n\nexport { hostReply, testChanges, HOST_MIDDLEWARE, type HostCallInput, type HostHandler, type TestHost } from './testHost.js'\n\nexport interface TestApp {\n /** A path, not a url. The origin is whatever the app was told it is. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n /** Where the build was read from, for a test that wants to look. */\n bundle: string\n}\n\nexport interface TestAppOptions {\n /** The project. Defaults to the working directory. */\n root?: string\n /**\n * Whether to build first.\n *\n * `true` builds when the source is newer than the last build, which is what\n * a test run wants: the first run pays for it, the rest do not, and an edit\n * is picked up. `false` never builds and fails loudly if there is nothing to\n * read — for a ci step that already built.\n */\n build?: boolean\n /** The origin requests are made against. Nothing reads it; it is a url. */\n origin?: string\n /**\n * The backend, answered in the test: rpc() calls and host guards by name.\n * The app reaches it through the same client it uses against a real one,\n * so nothing listens and RSC_BACKEND is not called. See `hostReply`.\n */\n host?: TestHost\n /**\n * What answers a url this app does not own - a Go route, a Laravel page,\n * /login - in place of the backend the app forwards it to. Handed the\n * request as the backend would receive it. Without one, such a url is\n * forwarded to RSC_BACKEND, and in a test that is usually a 502.\n */\n backend?: (request: Request) => Response | Promise<Response>\n}\n\n/**\n * Where the build put the server bundle.\n *\n * Two layouts, because two ways of building. Under Nitro — every scaffolded\n * app — it is inside Nitro's own directory. On its own the plugin writes\n * <outDir>/dist/rsc. The first that exists wins.\n */\nfunction findBundle(root: string): string | null {\n const candidates = [\n join(root, 'node_modules/.nitro/vite/services/rsc/index.js'),\n join(root, '.rsc/dist/rsc/index.js'),\n join(root, 'build/dist/rsc/index.js'),\n ]\n\n return candidates.find((path) => existsSync(path)) ?? null\n}\n\n/** The newest mtime under a directory, for deciding whether a build is stale. */\nfunction newest(dir: string): number {\n if (!existsSync(dir)) return 0\n\n let latest = 0\n\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue\n\n const path = join(dir, entry.name)\n const time = entry.isDirectory() ? newest(path) : statSync(path).mtimeMs\n\n if (time > latest) latest = time\n }\n\n return latest\n}\n\n/** One build per process per root, however many test files ask. */\nconst built = new Map<string, Promise<string>>()\n\n/** The content types a test is likely to assert on; anything else is octet-stream. */\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.txt': 'text/plain; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.gif': 'image/gif',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.wasm': 'application/wasm',\n '.map': 'application/json',\n}\n\n/**\n * A file the build put in .output/public, answered the way Nitro's static\n * layer would - which the handler this harness loads does not include. The\n * handler is the rsc service: routing, pages, actions, api routes. Assets,\n * the service worker, the manifest and the icons are files Nitro serves in\n * production from .output/public, and a test that asked for /sw.js used to\n * get the router's 404 for a file the deployment serves fine - the one\n * shape this harness exists to catch, in the other direction.\n *\n * Files only, for GET and HEAD, within the directory: a path that escapes it\n * is a request for the handler, not a file.\n */\n/** @internal Exported for its test. */\nexport function staticFile(root: string, request: Request): Response | null {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n const publicDir = join(root, '.output/public')\n const pathname = decodeURIComponent(new URL(request.url).pathname)\n const file = resolve(publicDir, '.' + pathname)\n\n if (!file.startsWith(publicDir + sep) || !existsSync(file) || !statSync(file).isFile()) return null\n\n const type = CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream'\n const body = request.method === 'HEAD' ? null : readFileSync(file)\n\n return new Response(body, {\n status: 200,\n headers: { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-RSC-Kit-Test': 'static' },\n })\n}\n\n/**\n * How this project builds: its own `build` script, run by the package manager\n * this test is running under. Without a script, Vite directly - on Bun's\n * runtime when the tests are, since a bin's node shebang would otherwise\n * start it under Node.\n */\n/** @internal Exported for its test. */\nexport function buildCommand(root: string): [string, string[]] {\n const onBun = typeof process.versions.bun === 'string'\n\n let scripts: Record<string, string> = {}\n\n try {\n scripts = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')).scripts ?? {}\n } catch {\n // No package.json, or not JSON: there is no script to run.\n }\n\n if (typeof scripts.build === 'string') {\n return onBun ? ['bun', ['run', 'build']] : ['npm', ['run', 'build']]\n }\n\n return onBun ? ['bun', ['--bun', 'vite', 'build']] : ['npx', ['vite', 'build']]\n}\n\nasync function ensureBuilt(root: string, build: boolean): Promise<string> {\n const existing = findBundle(root)\n\n if (!build) {\n if (!existing) {\n throw new Error(\n `[rsc-kit] No build to test against under ${root}. Run the build first, or let createTestApp() do it by leaving \\`build\\` on.`,\n )\n }\n\n return existing\n }\n\n const fresh = existing && statSync(existing).mtimeMs > newest(join(root, 'src'))\n\n if (fresh) return existing\n\n // The user's own build command, so what is tested is what ships. A test\n // that built some other way would pass against a bundle nobody deploys -\n // and used to: this ran `npx vite build` whatever package.json said, which\n // on a Bun project built under Node and failed on the first `import 'bun'`.\n const [command, args] = buildCommand(root)\n const run = spawnSync(command, args, {\n cwd: root,\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, NODE_ENV: 'production' },\n })\n\n if (run.status !== 0) {\n throw new Error(`[rsc-kit] The build failed, so there is nothing to test:\\n${run.stderr}`)\n }\n\n const bundle = findBundle(root)\n\n if (!bundle) {\n throw new Error(\n `[rsc-kit] The build finished but no server bundle was found under ${root}. Is rscKit() in vite.config?`,\n )\n }\n\n return bundle\n}\n\n/**\n * Build the app if it needs it, load it, and hand back something to fetch from.\n *\n * Memoised per root: every test file in a run shares one build and one loaded\n * module, which is both the fast path and the correct one — two copies of the\n * server bundle in one process would be two client-reference registries.\n */\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n const root = resolve(options.root ?? process.cwd())\n const origin = options.origin ?? 'https://app.test'\n\n built.set(root, built.get(root) ?? ensureBuilt(root, options.build ?? true))\n\n // The app is built for production, which refuses to sign refreshOn names\n // without a key. One process, one key: a fixed one, unless the test set its own.\n if (!process.env.RSC_SIGNING_SECRET) {\n configureChanged({ secret: 'rsc-kit-test' })\n }\n\n const bundle = await built.get(root)!\n const entry = (await import(pathToFileURL(bundle).href)) as {\n default: (request: Request) => Promise<Response>\n installHostFn?: (fn: (name: string, ...args: unknown[]) => Promise<unknown>) => () => void\n installBackendForward?: (fn: ((request: Request) => Response | Promise<Response>) | null) => void\n }\n\n if (typeof entry.default !== 'function') {\n throw new Error(`[rsc-kit] ${bundle} does not export a request handler.`)\n }\n\n const host = options.host\n ? httpHostCalls({ endpoint: 'http://test-host/__rsc/host-call', secret: 'test', fetch: testHostFetch(options.host) })\n : null\n\n if (host && !entry.installHostFn) {\n throw new Error(`[rsc-kit] ${bundle} cannot take a host. Rebuild against the current @rsc-kit/core.`)\n }\n\n return {\n bundle,\n fetch: async (path, init) => {\n const request = new Request(new URL(path, origin), init)\n\n // Per request, not once: the loaded bundle is shared by every app a\n // run creates, and the host is this app's.\n if (host) entry.installHostFn!(host)\n if (options.backend && !entry.installBackendForward) {\n throw new Error(`[rsc-kit] ${bundle} cannot take a backend. Rebuild against the current @rsc-kit/core.`)\n }\n entry.installBackendForward?.(options.backend ?? null)\n\n return staticFile(root, request) ?? entry.default(request)\n },\n }\n}\n"]}
|
package/dist/vite.js
CHANGED
|
@@ -680,6 +680,7 @@ function routeManifest() {
|
|
|
680
680
|
payloadName: staticPayloads,
|
|
681
681
|
hosts: siteHosts,
|
|
682
682
|
identify,
|
|
683
|
+
refreshOn: usesRefreshOn() || undefined,
|
|
683
684
|
},
|
|
684
685
|
routes,
|
|
685
686
|
intercepts,
|
|
@@ -2255,6 +2256,18 @@ const API_METHODS = [
|
|
|
2255
2256
|
];
|
|
2256
2257
|
/** `orders.section.tsx` — a region of a page that can be refreshed by name. */
|
|
2257
2258
|
const SECTION_FILE = /\.section\.(tsx|jsx|ts|js)$/;
|
|
2259
|
+
/**
|
|
2260
|
+
* Whether a page or a section declares refreshOn. Read from the source, as
|
|
2261
|
+
* section names are, because the manifest is written before any bundle exists.
|
|
2262
|
+
*/
|
|
2263
|
+
function usesRefreshOn() {
|
|
2264
|
+
for (const component of components.values()) {
|
|
2265
|
+
const src = readFileSync(component.absPath, "utf-8");
|
|
2266
|
+
if (SECTION_FILE.test(component.absPath) ? /\brefreshOn\s*:/.test(src) : urlSchemaExports(component.absPath).refreshOn)
|
|
2267
|
+
return true;
|
|
2268
|
+
}
|
|
2269
|
+
return false;
|
|
2270
|
+
}
|
|
2258
2271
|
const EXTS = ["tsx", "jsx", "ts", "js"];
|
|
2259
2272
|
function findRouteFile(dir, base) {
|
|
2260
2273
|
for (const ext of EXTS) {
|
|
@@ -2870,7 +2883,8 @@ import { DocumentTitle } from ${JSON.stringify(join(packageDir, "js/DocumentTitl
|
|
|
2870
2883
|
import { SlotBoundary } from ${JSON.stringify(join(packageDir, "js/SlotBoundary"))}
|
|
2871
2884
|
import { RouteErrorBoundary } from ${JSON.stringify(join(packageDir, "js/RouteErrorBoundary"))}
|
|
2872
2885
|
import __rsc_assets from 'virtual:vite-rsc/assets-manifest'
|
|
2873
|
-
import { sectionComponent } from ${JSON.stringify(join(packageDir, "js/section"))}
|
|
2886
|
+
import { isSharedSection, sectionComponent } from ${JSON.stringify(join(packageDir, "js/section"))}
|
|
2887
|
+
import { shareRender } from ${JSON.stringify(join(packageDir, "sharedRenders"))}
|
|
2874
2888
|
import { PathnameProvider } from ${JSON.stringify(join(packageDir, "js/PathnameProvider"))}
|
|
2875
2889
|
import { DefaultRouteError } from ${JSON.stringify(join(packageDir, "js/DefaultRouteError"))}
|
|
2876
2890
|
import { searchParams as requestSearchParams, withUrl } from ${JSON.stringify(join(packageDir, "request"))}
|
|
@@ -2881,7 +2895,7 @@ import { redirectDigest } from ${JSON.stringify(join(packageDir, "redirectDigest
|
|
|
2881
2895
|
import { cancelledByConsumer } from ${JSON.stringify(join(packageDir, "js/fallbackReport"))}
|
|
2882
2896
|
import { createRscHandler, pageSaidNotFound, queryAndParams } from ${JSON.stringify(join(packageDir, "host"))}
|
|
2883
2897
|
import { httpHostCalls } from ${JSON.stringify(join(packageDir, "hostCalls"))}
|
|
2884
|
-
import { backendVersions,
|
|
2898
|
+
import { backendVersions, installBackendVersionSource } from ${JSON.stringify(join(packageDir, "changed"))}
|
|
2885
2899
|
import { RefreshOn } from ${JSON.stringify(join(packageDir, "js/refreshOn"))}
|
|
2886
2900
|
import { prerenderedBeside } from ${JSON.stringify(join(packageDir, "files"))}
|
|
2887
2901
|
import { renderToReadableStream, decodeReply, decodeAction, decodeFormState, loadServerAction } from '@vitejs/plugin-rsc/rsc'
|
|
@@ -3347,11 +3361,11 @@ export function installHostFn(fn: HostFn) {
|
|
|
3347
3361
|
currentHost = fn
|
|
3348
3362
|
// The host keeps the versions a page refreshes on, read through it.
|
|
3349
3363
|
// Uninstalled, they are this process's own again.
|
|
3350
|
-
|
|
3364
|
+
installBackendVersionSource(backendVersions(fn))
|
|
3351
3365
|
return () => {
|
|
3352
3366
|
if (currentHost === fn) {
|
|
3353
3367
|
currentHost = null
|
|
3354
|
-
|
|
3368
|
+
installBackendVersionSource(null)
|
|
3355
3369
|
}
|
|
3356
3370
|
}
|
|
3357
3371
|
}
|
|
@@ -4506,10 +4520,11 @@ function regionOfSomePage(target: string): boolean {
|
|
|
4506
4520
|
)
|
|
4507
4521
|
}
|
|
4508
4522
|
|
|
4509
|
-
async function renderRevalidated(target: string, page: PageContext, skipElsewhere = false): Promise<unknown> {
|
|
4523
|
+
async function renderRevalidated(target: string, page: PageContext, skipElsewhere = false, guarded = false): Promise<unknown> {
|
|
4510
4524
|
// Every target below 'all' renders without the layout chain above it, which
|
|
4511
|
-
// is the same skip a navigation performs and needs the same guard run
|
|
4512
|
-
|
|
4525
|
+
// is the same skip a navigation performs and needs the same guard run -
|
|
4526
|
+
// unless the caller has just run it for this request.
|
|
4527
|
+
if (!guarded) await runMiddleware(page.component, page.props)
|
|
4513
4528
|
|
|
4514
4529
|
if (target === 'all' || target === 'page') {
|
|
4515
4530
|
// Keyed by the page's url, as a navigation to it is: the tree replaces
|
|
@@ -5004,15 +5019,38 @@ export function hasServerReference(payload: string): boolean {
|
|
|
5004
5019
|
export async function handleRscRevalidate(
|
|
5005
5020
|
target: string,
|
|
5006
5021
|
page: PageContext,
|
|
5022
|
+
share?: string,
|
|
5007
5023
|
): Promise<{ rscPayload: string }> {
|
|
5008
5024
|
await instrumented()
|
|
5009
5025
|
applyHost()
|
|
5010
5026
|
|
|
5027
|
+
// A shared section, asked for because of a change: this tab's guards run
|
|
5028
|
+
// on its own request, and then the render for that change - done once,
|
|
5029
|
+
// for whichever tab asked first - answers it.
|
|
5030
|
+
if (share && sharedSection(target, page)) {
|
|
5031
|
+
await runMiddleware(page.component, page.props)
|
|
5032
|
+
|
|
5033
|
+
const rscPayload = await shareRender(page.component + ' ' + target + ' ' + share, async () =>
|
|
5034
|
+
new Response(renderToReadableStream(await renderRevalidated(target, page, false, true))).text(),
|
|
5035
|
+
)
|
|
5036
|
+
|
|
5037
|
+
return { rscPayload }
|
|
5038
|
+
}
|
|
5039
|
+
|
|
5011
5040
|
const flight = renderToReadableStream(await renderRevalidated(target, page))
|
|
5012
5041
|
|
|
5013
5042
|
return { rscPayload: await new Response(flight).text() }
|
|
5014
5043
|
}
|
|
5015
5044
|
|
|
5045
|
+
/** Whether target names a section of this page declared shared. */
|
|
5046
|
+
function sharedSection(target: string, page: PageContext): boolean {
|
|
5047
|
+
const owner = manifest().routes.find((route: any) => route.component === page.component)
|
|
5048
|
+
const declared: string[] = owner?.sections ?? page.sections ?? []
|
|
5049
|
+
const path = declared.find((name: string) => name.split('/').pop() === target + '.section')
|
|
5050
|
+
|
|
5051
|
+
return path ? isSharedSection(components[path]) : false
|
|
5052
|
+
}
|
|
5053
|
+
|
|
5016
5054
|
export async function handleRscPayload(
|
|
5017
5055
|
component: string,
|
|
5018
5056
|
props: Record<string, unknown> = {},
|