@rsc-kit/core 0.30.52 → 0.30.53
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/conformance.d.ts +2 -2
- package/dist/conformance.js +4 -4
- package/dist/conformance.js.map +1 -1
- package/dist/host.d.ts +2 -2
- package/dist/host.js +5 -5
- package/dist/host.js.map +1 -1
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js.map +1 -1
- package/dist/purge.d.ts +8 -2
- package/dist/purge.js +12 -6
- package/dist/purge.js.map +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +67 -8
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/manifest.d.ts
CHANGED
|
@@ -149,6 +149,12 @@ export interface RouteManifest {
|
|
|
149
149
|
* every page it serves from its cache. Fixed for the build.
|
|
150
150
|
*/
|
|
151
151
|
headers?: Record<string, string>;
|
|
152
|
+
/**
|
|
153
|
+
* rscKit({ backendPaths }), normalised: a proxy in front sends a path equal
|
|
154
|
+
* to one, or under it, to the backend and everything else here. `[]` when
|
|
155
|
+
* none; absent from a build before 0.30.53.
|
|
156
|
+
*/
|
|
157
|
+
backendPaths?: string[];
|
|
152
158
|
};
|
|
153
159
|
routes: ManifestRoute[];
|
|
154
160
|
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 * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: 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 * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\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 * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\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 * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: 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 * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\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 * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\n /**\n * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal\n * to one, or under it, to the backend and everything else here. `[]` when\n * none; absent from a build before 0.30.53.\n */\n backendPaths?: string[];\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"]}
|
package/dist/purge.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* the names that changed - after the answer has gone, through `after()`, so a
|
|
9
9
|
* slow CDN never holds up the action that made the change.
|
|
10
10
|
*
|
|
11
|
-
* Homeport is the one installed for you: with `
|
|
11
|
+
* Homeport is the one installed for you: with `RSC_PURGE_URL` set (or Homeport's `HOMEPORT_PURGE_URL`), the
|
|
12
12
|
* hook is `homeportPurge()` unless the app installed another.
|
|
13
13
|
*
|
|
14
14
|
* A Laravel or Go backend changes its names itself (`Rsc::changed()`,
|
|
@@ -27,6 +27,12 @@ export type Purger = (purge: Purge) => Promise<void> | void;
|
|
|
27
27
|
export declare function installPurge(purger: Purger | null): void;
|
|
28
28
|
/** The purge in use: the app's, else Homeport's when its url is set, else none. */
|
|
29
29
|
export declare function installedPurge(): Purger | null;
|
|
30
|
+
/**
|
|
31
|
+
* Where an edge in front of the app takes its purges: `RSC_PURGE_URL`, or
|
|
32
|
+
* `HOMEPORT_PURGE_URL`, the name Homeport sets on the apps it runs - read so
|
|
33
|
+
* those keep purging, not as the name to set.
|
|
34
|
+
*/
|
|
35
|
+
export declare function purgeUrl(): string | undefined;
|
|
30
36
|
/**
|
|
31
37
|
* @internal For changed(): purge these tags once the answer has gone, or at
|
|
32
38
|
* once outside a request. Does nothing when no purge is installed.
|
|
@@ -42,7 +48,7 @@ export declare function purge(what: Purge): Promise<void>;
|
|
|
42
48
|
/** Homeport takes at most this many tags and paths, together, per call. */
|
|
43
49
|
export declare const HOMEPORT_PURGE_LIMIT = 100;
|
|
44
50
|
export interface HomeportPurgeOptions {
|
|
45
|
-
/** Where to post. Default `
|
|
51
|
+
/** Where to post. Default `RSC_PURGE_URL`, or the `HOMEPORT_PURGE_URL` Homeport sets. */
|
|
46
52
|
url?: string;
|
|
47
53
|
/** For tests. */
|
|
48
54
|
fetch?: typeof fetch;
|
package/dist/purge.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* the names that changed - after the answer has gone, through `after()`, so a
|
|
9
9
|
* slow CDN never holds up the action that made the change.
|
|
10
10
|
*
|
|
11
|
-
* Homeport is the one installed for you: with `
|
|
11
|
+
* Homeport is the one installed for you: with `RSC_PURGE_URL` set (or Homeport's `HOMEPORT_PURGE_URL`), the
|
|
12
12
|
* hook is `homeportPurge()` unless the app installed another.
|
|
13
13
|
*
|
|
14
14
|
* A Laravel or Go backend changes its names itself (`Rsc::changed()`,
|
|
@@ -34,11 +34,17 @@ export function installedPurge() {
|
|
|
34
34
|
const installed = globals[PURGER];
|
|
35
35
|
if (installed !== undefined)
|
|
36
36
|
return installed;
|
|
37
|
-
const url =
|
|
37
|
+
const url = purgeUrl();
|
|
38
38
|
return url ? homeportPurge({ url }) : null;
|
|
39
39
|
}
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Where an edge in front of the app takes its purges: `RSC_PURGE_URL`, or
|
|
42
|
+
* `HOMEPORT_PURGE_URL`, the name Homeport sets on the apps it runs - read so
|
|
43
|
+
* those keep purging, not as the name to set.
|
|
44
|
+
*/
|
|
45
|
+
export function purgeUrl() {
|
|
46
|
+
const env = globalThis.process?.env;
|
|
47
|
+
return env?.RSC_PURGE_URL || env?.HOMEPORT_PURGE_URL || undefined;
|
|
42
48
|
}
|
|
43
49
|
// The names an action changed go out as one purge when its answer has gone:
|
|
44
50
|
// three changed() calls send one request, not three. Gathered per request,
|
|
@@ -108,9 +114,9 @@ const HOMEPORT_TIMEOUT_MS = 5_000;
|
|
|
108
114
|
*/
|
|
109
115
|
export function homeportPurge(options = {}) {
|
|
110
116
|
return async (what) => {
|
|
111
|
-
const url = options.url ??
|
|
117
|
+
const url = options.url ?? purgeUrl();
|
|
112
118
|
if (!url)
|
|
113
|
-
throw new Error("homeportPurge() has no url:
|
|
119
|
+
throw new Error("homeportPurge() has no url: RSC_PURGE_URL is not set.");
|
|
114
120
|
const send = options.fetch ?? fetch;
|
|
115
121
|
const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= HOMEPORT_TAG_BYTES);
|
|
116
122
|
const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= HOMEPORT_PATH_BYTES);
|
package/dist/purge.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version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AAI,CAAC;QAC1B,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,mBAAmB,CAAC;KACjD,CAAC,CAAC;IAEH,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IAE9B,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;QAAE,OAAO;IAEpC,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QACxC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAE9E,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC;QAEpE,OAAO,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,qBAAqB,QAAQ,CAAC,MAAM,kBAAkB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC","sourcesContent":["/**\n * Telling a CDN that kept pages changed.\n *\n * A `revalidate` page goes out with `Cache-Tag`, and a CDN that purges by tag\n * can drop it the moment one of those tags changes, rather than waiting out\n * its `max-age` in `CDN-Cache-Control`. What calls the purge is the app's: every CDN has its own API, so\n * the engine has one hook, `installPurge()`, and `changed(tag)` calls it with\n * the names that changed - after the answer has gone, through `after()`, so a\n * slow CDN never holds up the action that made the change.\n *\n * Homeport is the one installed for you: with `HOMEPORT_PURGE_URL` set, the\n * hook is `homeportPurge()` unless the app installed another.\n *\n * A Laravel or Go backend changes its names itself (`Rsc::changed()`,\n * `reg.Changed()`), and the engine never hears of it, so each backend\n * purges for its own changes. This hook covers `changed()` called here.\n */\n\n// Not imported: @rsc-kit/core/changed reaches this file and a client component\n// may import that, so request.ts - server-only - is found through the global\n// it sets when the server loads it. Without it, there is no request to wait\n// for, and a purge goes out at once.\ntype AfterHooks = { after: (work: () => unknown) => void; requestKey: () => object | null };\n\nfunction hooks(): AfterHooks {\n return (\n ((globalThis as Record<symbol, unknown>)[Symbol.for(\"rsc-kit.after\")] as AfterHooks | undefined) ?? {\n after: (work) => void Promise.resolve().then(work),\n requestKey: () => null,\n }\n );\n}\n\n/** What a purge drops: pages carrying any of these tags, pages at these paths, or everything. */\nexport interface Purge {\n tags?: readonly string[];\n paths?: readonly string[];\n all?: boolean;\n}\n\n/** Sends a purge to a CDN. A rejection is logged; it never fails the change. */\nexport type Purger = (purge: Purge) => Promise<void> | void;\n\n// On the global, like the cache store: an app installs through its own copy\n// of the package, and the engine's copy is the one that calls it.\nconst PURGER = Symbol.for(\"rsc-kit.purger\");\nconst globals = globalThis as unknown as Record<symbol, Purger | null | undefined>;\n\n/** Install the app's purge. `null` takes it out, and Homeport's default with it. */\nexport function installPurge(purger: Purger | null): void {\n globals[PURGER] = purger;\n}\n\n/** The purge in use: the app's, else Homeport's when its url is set, else none. */\nexport function installedPurge(): Purger | null {\n const installed = globals[PURGER];\n\n if (installed !== undefined) return installed;\n\n const url = homeportPurgeUrl();\n\n return url ? homeportPurge({ url }) : null;\n}\n\nfunction homeportPurgeUrl(): string | undefined {\n return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.HOMEPORT_PURGE_URL || undefined;\n}\n\n// The names an action changed go out as one purge when its answer has gone:\n// three changed() calls send one request, not three. Gathered per request,\n// so a request whose after() work never ran cannot hold back another's.\nconst pendingFor = new WeakMap<object, Set<string>>();\n\n/**\n * @internal For changed(): purge these tags once the answer has gone, or at\n * once outside a request. Does nothing when no purge is installed.\n */\nexport function purgeLater(tags: readonly string[]): void {\n if (tags.length === 0 || !installedPurge()) return;\n\n const { after, requestKey } = hooks();\n const key = requestKey();\n\n if (!key) {\n after(() => purge({ tags }));\n\n return;\n }\n\n let pending = pendingFor.get(key);\n\n if (pending) {\n for (const tag of tags) pending.add(tag);\n\n return;\n }\n\n pending = new Set(tags);\n pendingFor.set(key, pending);\n\n const gathered = pending;\n\n after(() => {\n pendingFor.delete(key);\n\n return purge({ tags: [...gathered] });\n });\n}\n\n/**\n * Send a purge now, through the installed purge. For an app's own use - a\n * deploy step, a webhook - as well as changed()'s. Never throws: the change\n * it follows is already made, and a CDN that missed it still drops the copy\n * at its `max-age` in `CDN-Cache-Control`. A failure is logged.\n */\nexport async function purge(what: Purge): Promise<void> {\n const purger = installedPurge();\n\n if (!purger) return;\n\n try {\n await purger(what);\n } catch (error) {\n console.warn(\n \"[rsc-kit] purging the CDN failed; its copy is dropped at CDN-Cache-Control's max-age instead: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/** Homeport takes at most this many tags and paths, together, per call. */\nexport const HOMEPORT_PURGE_LIMIT = 100;\n\n/** The longest tag and path Homeport takes, in bytes. */\nconst HOMEPORT_TAG_BYTES = 1024;\nconst HOMEPORT_PATH_BYTES = 2048;\n\nconst bytes = new TextEncoder();\n\n/** How long one call may take, so a purge url that hangs leaves nothing pending. */\nconst HOMEPORT_TIMEOUT_MS = 5_000;\n\nexport interface HomeportPurgeOptions {\n /** Where to post. Default `HOMEPORT_PURGE_URL`, which Homeport sets. */\n url?: string;\n /** For tests. */\n fetch?: typeof fetch;\n}\n\n/**\n * Homeport's purge: `POST {tags, paths, all}` to the url Homeport gives the\n * app, no token - it is reachable only from inside the app's own network.\n * Split into calls of 100 tags and paths together. A tag or path too long for\n * it is left out: one would cost the whole call, and the edge keeps no page\n * with a tag it could not purge. Only a 202 is accepted. A 429 is tried once\n * more after its `Retry-After` (at most five seconds); anything else is that\n * call lost. The rest are still sent, then the purge rejects.\n */\nexport function homeportPurge(options: HomeportPurgeOptions = {}): Purger {\n return async (what) => {\n const url = options.url ?? homeportPurgeUrl();\n\n if (!url) throw new Error(\"homeportPurge() has no url: HOMEPORT_PURGE_URL is not set.\");\n\n const send = options.fetch ?? fetch;\n const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= HOMEPORT_TAG_BYTES);\n const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= HOMEPORT_PATH_BYTES);\n const bodies: Purge[] = [];\n\n if (what.all) bodies.push({ all: true });\n\n while (tags.length > 0 || paths.length > 0) {\n const body: Purge = {};\n const someTags = tags.splice(0, HOMEPORT_PURGE_LIMIT);\n const somePaths = paths.splice(0, HOMEPORT_PURGE_LIMIT - someTags.length);\n\n if (someTags.length > 0) body.tags = someTags;\n if (somePaths.length > 0) body.paths = somePaths;\n bodies.push(body);\n }\n\n const failed: string[] = [];\n\n for (const body of bodies) {\n try {\n await post(send, url, body);\n } catch (error) {\n failed.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (failed.length > 0) throw new Error(failed.join(\" \"));\n };\n}\n\nasync function post(send: typeof fetch, url: string, body: Purge, retried = false): Promise<void> {\n const response = await send(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(HOMEPORT_TIMEOUT_MS),\n });\n\n await response.body?.cancel();\n\n if (response.status === 202) return;\n\n if (response.status === 429 && !retried) {\n const seconds = Math.min(Number(response.headers.get(\"Retry-After\")) || 1, 5);\n\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000));\n\n return post(send, url, body, true);\n }\n\n throw new Error(`Homeport answered ${response.status} to a purge of ${JSON.stringify(body)}.`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"purge.js","sourceRoot":"","sources":["../src/purge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAQH,SAAS,KAAK;IACZ,OAAO,CACH,UAAsC,CAAC,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,CAA4B,IAAI;QAClG,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAA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AEpC,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QACxC,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QAE9E,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC;QAEpE,OAAO,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,qBAAqB,QAAQ,CAAC,MAAM,kBAAkB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC","sourcesContent":["/**\n * Telling a CDN that kept pages changed.\n *\n * A `revalidate` page goes out with `Cache-Tag`, and a CDN that purges by tag\n * can drop it the moment one of those tags changes, rather than waiting out\n * its `max-age` in `CDN-Cache-Control`. What calls the purge is the app's: every CDN has its own API, so\n * the engine has one hook, `installPurge()`, and `changed(tag)` calls it with\n * the names that changed - after the answer has gone, through `after()`, so a\n * slow CDN never holds up the action that made the change.\n *\n * Homeport is the one installed for you: with `RSC_PURGE_URL` set (or Homeport's `HOMEPORT_PURGE_URL`), the\n * hook is `homeportPurge()` unless the app installed another.\n *\n * A Laravel or Go backend changes its names itself (`Rsc::changed()`,\n * `reg.Changed()`), and the engine never hears of it, so each backend\n * purges for its own changes. This hook covers `changed()` called here.\n */\n\n// Not imported: @rsc-kit/core/changed reaches this file and a client component\n// may import that, so request.ts - server-only - is found through the global\n// it sets when the server loads it. Without it, there is no request to wait\n// for, and a purge goes out at once.\ntype AfterHooks = { after: (work: () => unknown) => void; requestKey: () => object | null };\n\nfunction hooks(): AfterHooks {\n return (\n ((globalThis as Record<symbol, unknown>)[Symbol.for(\"rsc-kit.after\")] as AfterHooks | undefined) ?? {\n after: (work) => void Promise.resolve().then(work),\n requestKey: () => null,\n }\n );\n}\n\n/** What a purge drops: pages carrying any of these tags, pages at these paths, or everything. */\nexport interface Purge {\n tags?: readonly string[];\n paths?: readonly string[];\n all?: boolean;\n}\n\n/** Sends a purge to a CDN. A rejection is logged; it never fails the change. */\nexport type Purger = (purge: Purge) => Promise<void> | void;\n\n// On the global, like the cache store: an app installs through its own copy\n// of the package, and the engine's copy is the one that calls it.\nconst PURGER = Symbol.for(\"rsc-kit.purger\");\nconst globals = globalThis as unknown as Record<symbol, Purger | null | undefined>;\n\n/** Install the app's purge. `null` takes it out, and Homeport's default with it. */\nexport function installPurge(purger: Purger | null): void {\n globals[PURGER] = purger;\n}\n\n/** The purge in use: the app's, else Homeport's when its url is set, else none. */\nexport function installedPurge(): Purger | null {\n const installed = globals[PURGER];\n\n if (installed !== undefined) return installed;\n\n const url = purgeUrl();\n\n return url ? homeportPurge({ url }) : null;\n}\n\n/**\n * Where an edge in front of the app takes its purges: `RSC_PURGE_URL`, or\n * `HOMEPORT_PURGE_URL`, the name Homeport sets on the apps it runs - read so\n * those keep purging, not as the name to set.\n */\nexport function purgeUrl(): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n return env?.RSC_PURGE_URL || env?.HOMEPORT_PURGE_URL || undefined;\n}\n\n// The names an action changed go out as one purge when its answer has gone:\n// three changed() calls send one request, not three. Gathered per request,\n// so a request whose after() work never ran cannot hold back another's.\nconst pendingFor = new WeakMap<object, Set<string>>();\n\n/**\n * @internal For changed(): purge these tags once the answer has gone, or at\n * once outside a request. Does nothing when no purge is installed.\n */\nexport function purgeLater(tags: readonly string[]): void {\n if (tags.length === 0 || !installedPurge()) return;\n\n const { after, requestKey } = hooks();\n const key = requestKey();\n\n if (!key) {\n after(() => purge({ tags }));\n\n return;\n }\n\n let pending = pendingFor.get(key);\n\n if (pending) {\n for (const tag of tags) pending.add(tag);\n\n return;\n }\n\n pending = new Set(tags);\n pendingFor.set(key, pending);\n\n const gathered = pending;\n\n after(() => {\n pendingFor.delete(key);\n\n return purge({ tags: [...gathered] });\n });\n}\n\n/**\n * Send a purge now, through the installed purge. For an app's own use - a\n * deploy step, a webhook - as well as changed()'s. Never throws: the change\n * it follows is already made, and a CDN that missed it still drops the copy\n * at its `max-age` in `CDN-Cache-Control`. A failure is logged.\n */\nexport async function purge(what: Purge): Promise<void> {\n const purger = installedPurge();\n\n if (!purger) return;\n\n try {\n await purger(what);\n } catch (error) {\n console.warn(\n \"[rsc-kit] purging the CDN failed; its copy is dropped at CDN-Cache-Control's max-age instead: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/** Homeport takes at most this many tags and paths, together, per call. */\nexport const HOMEPORT_PURGE_LIMIT = 100;\n\n/** The longest tag and path Homeport takes, in bytes. */\nconst HOMEPORT_TAG_BYTES = 1024;\nconst HOMEPORT_PATH_BYTES = 2048;\n\nconst bytes = new TextEncoder();\n\n/** How long one call may take, so a purge url that hangs leaves nothing pending. */\nconst HOMEPORT_TIMEOUT_MS = 5_000;\n\nexport interface HomeportPurgeOptions {\n /** Where to post. Default `RSC_PURGE_URL`, or the `HOMEPORT_PURGE_URL` Homeport sets. */\n url?: string;\n /** For tests. */\n fetch?: typeof fetch;\n}\n\n/**\n * Homeport's purge: `POST {tags, paths, all}` to the url Homeport gives the\n * app, no token - it is reachable only from inside the app's own network.\n * Split into calls of 100 tags and paths together. A tag or path too long for\n * it is left out: one would cost the whole call, and the edge keeps no page\n * with a tag it could not purge. Only a 202 is accepted. A 429 is tried once\n * more after its `Retry-After` (at most five seconds); anything else is that\n * call lost. The rest are still sent, then the purge rejects.\n */\nexport function homeportPurge(options: HomeportPurgeOptions = {}): Purger {\n return async (what) => {\n const url = options.url ?? purgeUrl();\n\n if (!url) throw new Error(\"homeportPurge() has no url: RSC_PURGE_URL is not set.\");\n\n const send = options.fetch ?? fetch;\n const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= HOMEPORT_TAG_BYTES);\n const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= HOMEPORT_PATH_BYTES);\n const bodies: Purge[] = [];\n\n if (what.all) bodies.push({ all: true });\n\n while (tags.length > 0 || paths.length > 0) {\n const body: Purge = {};\n const someTags = tags.splice(0, HOMEPORT_PURGE_LIMIT);\n const somePaths = paths.splice(0, HOMEPORT_PURGE_LIMIT - someTags.length);\n\n if (someTags.length > 0) body.tags = someTags;\n if (somePaths.length > 0) body.paths = somePaths;\n bodies.push(body);\n }\n\n const failed: string[] = [];\n\n for (const body of bodies) {\n try {\n await post(send, url, body);\n } catch (error) {\n failed.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (failed.length > 0) throw new Error(failed.join(\" \"));\n };\n}\n\nasync function post(send: typeof fetch, url: string, body: Purge, retried = false): Promise<void> {\n const response = await send(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(HOMEPORT_TIMEOUT_MS),\n });\n\n await response.body?.cancel();\n\n if (response.status === 202) return;\n\n if (response.status === 429 && !retried) {\n const seconds = Math.min(Number(response.headers.get(\"Retry-After\")) || 1, 5);\n\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000));\n\n return post(send, url, body, true);\n }\n\n throw new Error(`Homeport answered ${response.status} to a purge of ${JSON.stringify(body)}.`);\n}\n"]}
|
package/dist/vite.d.ts
CHANGED
|
@@ -346,7 +346,7 @@ export declare function normalisePageHeaders(raw: Record<string, string> | undef
|
|
|
346
346
|
* slash. Refused rather than corrected where a mistake would silently send the
|
|
347
347
|
* whole app, or its own endpoints, to the backend.
|
|
348
348
|
*/
|
|
349
|
-
export declare function normaliseBackendPaths(paths: readonly string[] | undefined): string[];
|
|
349
|
+
export declare function normaliseBackendPaths(paths: readonly string[] | undefined, hostCallPath?: string): string[];
|
|
350
350
|
/**
|
|
351
351
|
* The prefixes a backend owns, as the route patterns the browser already reads
|
|
352
352
|
* for a route.ts: the prefix, and everything under it.
|
package/dist/vite.js
CHANGED
|
@@ -446,7 +446,7 @@ export function normalisePageHeaders(raw) {
|
|
|
446
446
|
* slash. Refused rather than corrected where a mistake would silently send the
|
|
447
447
|
* whole app, or its own endpoints, to the backend.
|
|
448
448
|
*/
|
|
449
|
-
export function normaliseBackendPaths(paths) {
|
|
449
|
+
export function normaliseBackendPaths(paths, hostCallPath = DEFAULT_HOST_CALL_PATH) {
|
|
450
450
|
const out = [];
|
|
451
451
|
for (const raw of paths ?? []) {
|
|
452
452
|
const given = typeof raw === "string" ? raw.trim() : "";
|
|
@@ -461,6 +461,12 @@ export function normaliseBackendPaths(paths) {
|
|
|
461
461
|
if (path === "/_rsc" || path.startsWith("/_rsc/")) {
|
|
462
462
|
throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is this package's own endpoint, which the renderer answers.`);
|
|
463
463
|
}
|
|
464
|
+
// A proxy routes these prefixes to the backend from outside, and the
|
|
465
|
+
// host-call endpoint is for the renderer alone: named here, a proxy
|
|
466
|
+
// reading the list would open it to every browser.
|
|
467
|
+
if (hostCallPath === path || hostCallPath.startsWith(path + "/")) {
|
|
468
|
+
throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is the host-call endpoint (${hostCallPath}), which only the renderer calls. A proxy reading backendPaths would open it to browsers.`);
|
|
469
|
+
}
|
|
464
470
|
// A bracket is a dynamic segment to the client, which reads these as route patterns.
|
|
465
471
|
if (/[?#*[\]]/.test(path)) {
|
|
466
472
|
throw new Error(`[rsc-kit] backendPaths: ${JSON.stringify(raw)} is a prefix, not a pattern: no query, fragment, wildcard or bracket.`);
|
|
@@ -470,6 +476,8 @@ export function normaliseBackendPaths(paths) {
|
|
|
470
476
|
}
|
|
471
477
|
return out;
|
|
472
478
|
}
|
|
479
|
+
/** Where host calls go on the backend, unless `hostCall.path` or RSC_HOST_CALL_PATH says. */
|
|
480
|
+
const DEFAULT_HOST_CALL_PATH = "/__rsc/host-call";
|
|
473
481
|
/**
|
|
474
482
|
* The prefixes a backend owns, as the route patterns the browser already reads
|
|
475
483
|
* for a route.ts: the prefix, and everything under it.
|
|
@@ -520,7 +528,7 @@ function resolvePaths(options) {
|
|
|
520
528
|
hotFile = options.hotFile || process.env.RSC_HOT_FILE || "";
|
|
521
529
|
hostCallOptions = options.hostCall;
|
|
522
530
|
packageDir = resolve(options.packageDir || process.env.RSC_PACKAGE_DIR || thisDir());
|
|
523
|
-
backendPaths = normaliseBackendPaths(options.backendPaths);
|
|
531
|
+
backendPaths = normaliseBackendPaths(options.backendPaths, options.hostCall?.path ?? process.env.RSC_HOST_CALL_PATH ?? DEFAULT_HOST_CALL_PATH);
|
|
524
532
|
hostGlobal = options.hostGlobal || process.env.RSC_HOST_GLOBAL || "rpc";
|
|
525
533
|
interceptManifestFile = resolve(options.interceptManifestFile ||
|
|
526
534
|
process.env.RSC_INTERCEPT_MANIFEST ||
|
|
@@ -880,6 +888,9 @@ function routeManifest() {
|
|
|
880
888
|
identify,
|
|
881
889
|
refreshOn: usesRefreshOn() || undefined,
|
|
882
890
|
headers: Object.keys(pageHeaders).length ? pageHeaders : undefined,
|
|
891
|
+
// Always written, [] when none: a reader can tell "none" from a build
|
|
892
|
+
// too old to say.
|
|
893
|
+
backendPaths,
|
|
883
894
|
},
|
|
884
895
|
routes,
|
|
885
896
|
intercepts,
|
|
@@ -3128,10 +3139,22 @@ function backendPathConsts() {
|
|
|
3128
3139
|
function onBackendPath(pathname: string): boolean {
|
|
3129
3140
|
return BACKEND_PATHS.some((prefix) => pathname === prefix || pathname.startsWith(prefix + '/'))
|
|
3130
3141
|
}
|
|
3142
|
+
|
|
3143
|
+
// The backend's host-call endpoint, which only this server calls - straight to
|
|
3144
|
+
// the backend, never through here. A browser asking for it here was handed on
|
|
3145
|
+
// like any url nothing owns, so the secret was all that stood in front of it.
|
|
3146
|
+
function isHostCallPath(pathname: string): boolean {
|
|
3147
|
+
const path = (typeof process !== 'undefined' && process.env.RSC_HOST_CALL_PATH) || ${JSON.stringify(hostCallOptions?.path ?? DEFAULT_HOST_CALL_PATH)}
|
|
3148
|
+
const asked = pathname.replace(/\\/+$/, '')
|
|
3149
|
+
|
|
3150
|
+
return asked === path || asked.startsWith(path + '/')
|
|
3151
|
+
}
|
|
3131
3152
|
`;
|
|
3132
3153
|
}
|
|
3133
3154
|
/** With no backend configured: this app's not-found page, or a test's backend. */
|
|
3134
|
-
const NO_FALLBACK_BODY = `
|
|
3155
|
+
const NO_FALLBACK_BODY = ` if (isHostCallPath(new URL(request.url).pathname)) return await notFound(request)
|
|
3156
|
+
|
|
3157
|
+
// The app named this prefix as the backend's: no page is asked about it, so one
|
|
3135
3158
|
// that matches (a dynamic root route) cannot answer for it.
|
|
3136
3159
|
const toBackend = onBackendPath(new URL(request.url).pathname)
|
|
3137
3160
|
const answer = toBackend ? null : await devHandler(request)
|
|
@@ -3144,6 +3167,8 @@ const NO_FALLBACK_BODY = ` // The app named this prefix as the backend's: no pa
|
|
|
3144
3167
|
`;
|
|
3145
3168
|
const FALLBACK_BODY = ` const FALLBACK_ORIGIN = fallbackOrigin()
|
|
3146
3169
|
|
|
3170
|
+
if (isHostCallPath(new URL(request.url).pathname)) return await notFound(request)
|
|
3171
|
+
|
|
3147
3172
|
// The app named this prefix as the backend's (rscKit({ backendPaths })): no
|
|
3148
3173
|
// page is asked about it. A dynamic root route such as [team]/[app] matches
|
|
3149
3174
|
// /gitlab/connect, renders, says notFound() - and a page that said that is not
|
|
@@ -6445,7 +6470,7 @@ import { parseRedirectDigest } from ${JSON.stringify(redirectDigestModule)}
|
|
|
6445
6470
|
import { isNotFoundDigest } from ${JSON.stringify(notFoundModule)}
|
|
6446
6471
|
import { EARLY_CLICKS } from ${JSON.stringify(earlyClicks)}
|
|
6447
6472
|
import { searchSnapshotContext } from ${JSON.stringify(join(packageDir, "js/useSearchParams"))}
|
|
6448
|
-
import { createElement as h
|
|
6473
|
+
import { createElement as h } from 'react'
|
|
6449
6474
|
${webManifestOptions ? `import { INSTALL_CAPTURE } from ${JSON.stringify(installCapture)}` : ""}
|
|
6450
6475
|
|
|
6451
6476
|
// What runs ahead of the runtime: held taps, and - in an app that can be
|
|
@@ -6470,9 +6495,15 @@ const DEV_ORIGIN = ${JSON.stringify(devOrigin)}
|
|
|
6470
6495
|
*
|
|
6471
6496
|
* One component for the first render, the prerender and the resume: a shell
|
|
6472
6497
|
* and its holes must be the same tree.
|
|
6498
|
+
*
|
|
6499
|
+
* It returns the promise rather than calling use() on it - React renders a
|
|
6500
|
+
* promise as what it resolves to. A hook here would be this module's React,
|
|
6501
|
+
* and in dev, on a start with an empty dependency cache, that is not the copy
|
|
6502
|
+
* React DOM renders with: every page answered 500 with "Invalid hook call"
|
|
6503
|
+
* until the server was restarted on a warm cache.
|
|
6473
6504
|
*/
|
|
6474
6505
|
function Decoded({ from }: { from: { stream: ReadableStream; decoded?: Promise<unknown> } }) {
|
|
6475
|
-
return
|
|
6506
|
+
return (from.decoded ??= createFromReadableStream(from.stream)) as any
|
|
6476
6507
|
}
|
|
6477
6508
|
|
|
6478
6509
|
function decodedBy(stream: ReadableStream): unknown {
|
|
@@ -7502,6 +7533,16 @@ function clientImportsAudit() {
|
|
|
7502
7533
|
},
|
|
7503
7534
|
};
|
|
7504
7535
|
}
|
|
7536
|
+
/** Whether the app's Nitro exports `nitro/services`: the release candidate on. */
|
|
7537
|
+
function nitroHasPublicServices(root) {
|
|
7538
|
+
try {
|
|
7539
|
+
createRequire(join(root, "package.json")).resolve("nitro/services");
|
|
7540
|
+
return true;
|
|
7541
|
+
}
|
|
7542
|
+
catch {
|
|
7543
|
+
return false;
|
|
7544
|
+
}
|
|
7545
|
+
}
|
|
7505
7546
|
/**
|
|
7506
7547
|
* A Nitro runtime plugin, so instrumentation.ts runs when the server starts.
|
|
7507
7548
|
*
|
|
@@ -7513,15 +7554,30 @@ function clientImportsAudit() {
|
|
|
7513
7554
|
* it. Not on a Worker: there is no startup, and the first request is the
|
|
7514
7555
|
* first chance to read a binding.
|
|
7515
7556
|
*/
|
|
7516
|
-
|
|
7557
|
+
/**
|
|
7558
|
+
* How the plugin reaches the ssr service. Nitro's release candidate made
|
|
7559
|
+
* `nitro/services` public and removed the virtual module the betas had, so an
|
|
7560
|
+
* app is answered with whichever its own Nitro has: a build importing the
|
|
7561
|
+
* other failed to resolve it, and the app could not build at all.
|
|
7562
|
+
*/
|
|
7563
|
+
function startupPlugin(publicServices) {
|
|
7564
|
+
return (publicServices
|
|
7565
|
+
? `import { fetchService } from "nitro/services"
|
|
7566
|
+
|
|
7567
|
+
const ssr = { fetch: (request) => fetchService('ssr', request) }
|
|
7568
|
+
`
|
|
7569
|
+
: `import { viteServices } from "#nitro/virtual/vite-services"
|
|
7517
7570
|
|
|
7571
|
+
const ssr = viteServices.ssr
|
|
7572
|
+
`) + STARTUP_PLUGIN;
|
|
7573
|
+
}
|
|
7574
|
+
const STARTUP_PLUGIN = `
|
|
7518
7575
|
export default function rscKitStartup() {
|
|
7519
7576
|
if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return
|
|
7520
7577
|
|
|
7521
7578
|
// The ssr service is the one Nitro's renderer asks; its fetch imports the
|
|
7522
7579
|
// rsc entry and hands the request on. The rsc service's own export is the
|
|
7523
7580
|
// handler function, not a { fetch }, so it cannot be probed directly.
|
|
7524
|
-
const ssr = viteServices.ssr
|
|
7525
7581
|
if (!ssr) return
|
|
7526
7582
|
|
|
7527
7583
|
// Two ways to fail, one outcome. register() rejecting is reported by the
|
|
@@ -7925,7 +7981,7 @@ export function rscKit(options = {}) {
|
|
|
7925
7981
|
}
|
|
7926
7982
|
if (!instrumentationFile())
|
|
7927
7983
|
return;
|
|
7928
|
-
nitro.options.virtual["#rsc-kit/startup"] =
|
|
7984
|
+
nitro.options.virtual["#rsc-kit/startup"] = startupPlugin(nitroHasPublicServices(projectRoot));
|
|
7929
7985
|
nitro.options.plugins = [...(nitro.options.plugins ?? []), "#rsc-kit/startup"];
|
|
7930
7986
|
},
|
|
7931
7987
|
},
|
|
@@ -8568,6 +8624,9 @@ export function rscKit(options = {}) {
|
|
|
8568
8624
|
output: "server",
|
|
8569
8625
|
...compileStep(projectRoot),
|
|
8570
8626
|
...(buildCommands().length ? { commands: buildCommands().map((c) => c.name) } : {}),
|
|
8627
|
+
// The prefixes a proxy in front sends straight to the
|
|
8628
|
+
// backend: a path equal to one or under it. [] when none.
|
|
8629
|
+
backendPaths,
|
|
8571
8630
|
}, null, 2) + "\n");
|
|
8572
8631
|
// The edge contract's marker: the pages an edge may answer from a
|
|
8573
8632
|
// cached shell or whole, and the build both endpoints will say they
|