@rsc-kit/core 0.30.37 → 0.30.39
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/flash.d.ts +18 -0
- package/dist/flash.js +29 -0
- package/dist/flash.js.map +1 -0
- package/dist/flashCookie.d.ts +17 -0
- package/dist/flashCookie.js +36 -0
- package/dist/flashCookie.js.map +1 -0
- package/dist/host.js +15 -2
- package/dist/host.js.map +1 -1
- package/dist/js/ActivityRouter.js +3 -3
- package/dist/js/ActivityRouter.js.map +1 -1
- package/dist/js/Changes.js +1 -1
- package/dist/js/Changes.js.map +1 -1
- package/dist/js/DefaultRouteError.d.ts +1 -1
- package/dist/js/DefaultRouteError.js.map +1 -1
- package/dist/js/Form.d.ts +2 -2
- package/dist/js/Form.js +5 -5
- package/dist/js/Form.js.map +1 -1
- package/dist/js/Link.js +2 -2
- package/dist/js/Link.js.map +1 -1
- package/dist/js/RedirectBoundary.js +2 -2
- package/dist/js/RedirectBoundary.js.map +1 -1
- package/dist/js/SegmentBoundary.js +5 -5
- package/dist/js/SegmentBoundary.js.map +1 -1
- package/dist/js/SlotBoundary.js +3 -3
- package/dist/js/SlotBoundary.js.map +1 -1
- package/dist/js/changesStore.js +1 -1
- package/dist/js/changesStore.js.map +1 -1
- package/dist/js/createViteRscApp.js +14 -14
- package/dist/js/createViteRscApp.js.map +1 -1
- package/dist/js/navigate.d.ts +1 -1
- package/dist/js/navigate.js +8 -8
- package/dist/js/navigate.js.map +1 -1
- package/dist/js/nuqs.js +2 -2
- package/dist/js/nuqs.js.map +1 -1
- package/dist/js/pagePayload.js +2 -2
- package/dist/js/pagePayload.js.map +1 -1
- package/dist/js/refreshOn.js +3 -3
- package/dist/js/refreshOn.js.map +1 -1
- package/dist/js/section.d.ts +4 -4
- package/dist/js/section.js +2 -2
- package/dist/js/section.js.map +1 -1
- package/dist/js/useAppUpdate.js +1 -1
- package/dist/js/useAppUpdate.js.map +1 -1
- package/dist/js/useFlash.d.ts +16 -0
- package/dist/js/useFlash.js +56 -0
- package/dist/js/useFlash.js.map +1 -0
- package/dist/js/useOnline.js +1 -1
- package/dist/js/useOnline.js.map +1 -1
- package/dist/js/usePathname.js +1 -1
- package/dist/js/usePathname.js.map +1 -1
- package/dist/testing.d.ts +9 -0
- package/dist/testing.js +14 -2
- package/dist/testing.js.map +1 -1
- package/dist/vite.js +1 -0
- package/dist/vite.js.map +1 -1
- package/package.json +9 -1
package/dist/js/refreshOn.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refreshOn.js","sourceRoot":"","sources":["../../src/js/refreshOn.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAEhD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAgClD;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,SAAS,CAAI,EAC3B,MAAM,EACN,SAAS,EACT,KAAK,GAKN;IACC,OAAO,aAAa,CAClB,QAAQ,EACR,EAAE,QAAQ,EAAE,IAAI,EAAE,EAClB,aAAa,CAAC,OAAgB,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAC9D,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;AAE1D,MAAM,MAAM,GAAG,IAAI,GAAG,EAAU,CAAC;AACjC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAC;AAEtC;;;;;GAKG;AACH,KAAK,UAAU,OAAO,CAAI,EACxB,MAAM,EACN,SAAS,E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E,QAAQ,KAAK,YAAY;YAC7B,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EACxB,CAAC;YACD,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACxB,OAAO,CAAC,IAAI,CACV,aAAa,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,0DAA0D;gBAC3F,gEAAgE,CACnE,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Suspense, createElement } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { connection, currentPageProps } from \"../request\";\nimport { sign, versionSource } from \"../changed\";\nimport type { SignedName } from \"../changed\";\nimport { Changes } from \"./Changes\";\nimport { isNotFoundSignal } from \"../notFound.js\";\n\n/** A prop as it arrives awaited: a page's `params` is a promise of them. */\ntype Awaited_<T, Else> = [T] extends [never]\n ? Else\n : unknown extends T\n ? Else // props that do not say: a section's own, with no params among them\n : T extends Promise<infer V>\n ? V\n : T extends undefined\n ? Else\n : T;\n\n/**\n * What a refreshOn function is given: the page's params and search params,\n * already awaited, beside whatever props the section was rendered with.\n *\n * Typed from P when it says what they are - a page's `PageProps<typeof\n * params>` - so `params.team` is the schema's type, not a string by hand.\n */\nexport type RefreshOnInput<P> = Omit<P, \"params\" | \"searchParams\"> & {\n params: Awaited_<P extends { params?: infer A } ? A : never, Record<string, string>>;\n searchParams: Awaited_<\n P extends { searchParams?: infer S } ? S : never,\n URLSearchParams | Record<string, unknown>\n >;\n};\n\n/** What a section or page refreshes on: names, or a function of its props that makes them. */\nexport type RefreshOnList<P> =\n string[] | ((input: RefreshOnInput<P>) => string[] | Promise<string[]>);\n\n/**\n * The names a region refreshes on, read for this render and signed for the tab.\n *\n * A server component, rendered beside the region: it works out the names\n * from the props, asks the source what version each is at, and hands them to\n * the client as `Changes`. Under its own Suspense boundary, so the ask never\n * holds up the region's paint - the data is what the visitor is waiting on,\n * not the version numbers behind it.\n *\n * Renders nothing when the source cannot answer - a backend that is down\n * for this one call. The region still renders; it just does not refresh on\n * its names until the next time it is rendered.\n */\nexport function RefreshOn<P>({\n target,\n refreshOn,\n props,\n}: {\n target: string;\n refreshOn: RefreshOnList<P>;\n props: P;\n}): ReactNode {\n return createElement(\n Suspense,\n { fallback: null },\n createElement(Resolve as never, { target, refreshOn, props }),\n );\n}\n\n/** Where createTestApp's watched() collects what a render's regions refresh on. */\nexport const WATCHED = Symbol.for(\"rsc-kit.test-watched\");\n\nconst warned = new Set<string>();\nconst emptyWarned = new Set<string>();\n\n/**\n * Never throws. An error here would become an error row inside the region's\n * payload, and the browser decodes that as the region failing - a blank\n * document for a version lookup that did not go through. Said once per\n * region instead, and the region renders without refreshing on anything.\n */\nasync function Resolve<P>({\n target,\n refreshOn,\n props,\n}: {\n target: string;\n refreshOn: RefreshOnList<P>;\n props: P;\n}): Promise<ReactNode> {\n try {\n // Per request, never at build. A version read at build is stale by the\n // time anyone loads the page, and a name signed at build is signed with\n // whatever key the build machine had. At build this suspends and the\n // names become a hole in the stored shell, filled per request.\n await connection();\n\n // The page's params and searchParams, under whatever the page passed: a\n // section rendered by its page is given nothing, and alone is given these.\n const given = { ...currentPageProps(), ...(props as object) } as Record<\n string,\n unknown\n >;\n\n // Awaited here, so `({ params }) => [\\`team:${params.team}\\`]` - the way\n // anyone writes it - means the team. A page's params and search params\n // are promises, and read without awaiting they made `team:undefined`:\n // one name for every team, so each refreshed on all the others' changes.\n // Awaiting costs nothing here; the names are made per request anyway.\n const input = {\n ...given,\n params: ((await given.params) ?? {}) as Record<string, string>,\n searchParams: ((await given.searchParams) ??\n new URLSearchParams()) as URLSearchParams,\n } as RefreshOnInput<P>;\n const unique = await namesFor(target, refreshOn, input);\n\n // A test asking what this page watches - createTestApp's watched() - is\n // told here, rather than left to dig the signed names out of the payload.\n const recording = (globalThis as { [WATCHED]?: Record<string, string[]> })[WATCHED];\n\n if (recording) recording[target] = unique;\n\n if (unique.length === 0) return null;\n\n // -1 is a version nothing is at, so every name comes back with its current version.\n const versions = await versionSource().changed(\n Object.fromEntries(unique.map((name) => [name, -1])),\n 0,\n );\n const signed: Record<string, SignedName> = {};\n\n for (const name of unique)\n signed[name] = [versions[name] ?? 0, await sign(name)];\n\n return createElement(Changes, { target, names: signed });\n } catch (error) {\n // A page that does not exist is not a page that cannot say what it\n // refreshes on: the same read that found no team is what the page says\n // notFound() about, and that is the answer. Warning for it was a line in the\n // log for every missing record.\n if (isNotFoundSignal(error)) return null;\n\n if (!warned.has(target)) {\n warned.add(target);\n console.warn(\n `[rsc-kit] what ${JSON.stringify(target)} refreshes on could not be read, so it will not: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n\n return null;\n }\n}\n\n/**\n * The names a region refreshes on, for this render: its list, or what its\n * function made of the input - unique, and only non-empty strings. Warns in\n * development when that is none at all.\n */\nexport async function namesFor<P>(\n target: string,\n refreshOn: RefreshOnList<P>,\n input: RefreshOnInput<P>,\n): Promise<string[]> {\n const named =\n typeof refreshOn === \"function\" ? await refreshOn(input) : refreshOn;\n const unique = [...new Set(named)].filter(\n (name) => typeof name === \"string\" && name !== \"\",\n );\n\n if (unique.length === 0) {\n // Usually a mistake that looks like working code - a param read under\n // the wrong name, a list built from an empty query - and the region\n // then refreshes on nothing. Said in development, once per region; a\n // region that means to watch nothing for some visitors can ignore it.\n if (\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n ?.NODE_ENV !== \"production\" &&\n !emptyWarned.has(target)\n ) {\n emptyWarned.add(target);\n console.warn(\n `[rsc-kit] ${JSON.stringify(target)}'s refreshOn gave no names, so it refreshes on nothing. ` +\n \"Check what it reads - a param under another name is undefined.\",\n );\n }\n\n return [];\n }\n\n return unique;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"refreshOn.js","sourceRoot":"","sources":["../../src/js/refreshOn.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AA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mDAAmD;gBACzF,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAC3D,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,MAAc,EACd,SAA2B,EAC3B,KAAwB;IAExB,MAAM,KAAK,GACT,OAAO,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CACvC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,EAAE,CAClD,CAAC;IAEF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxB,sEAAsE;QACtE,oEAAoE;QACpE,qEAAqE;QACrE,sEAAsE;QACtE,IACG,UAAyE,CAAC,OAAO,EAAE,GAAG;YACrF,EAAE,QAAQ,KAAK,YAAY;YAC7B,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EACxB,CAAC;YACD,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACxB,OAAO,CAAC,IAAI,CACV,aAAa,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,0DAA0D;gBAC3F,gEAAgE,CACnE,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Suspense, createElement } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { connection, currentPageProps } from \"../request.js\";\nimport { sign, versionSource } from \"../changed.js\";\nimport type { SignedName } from \"../changed.js\";\nimport { Changes } from \"./Changes.js\";\nimport { isNotFoundSignal } from \"../notFound.js\";\n\n/** A prop as it arrives awaited: a page's `params` is a promise of them. */\ntype Awaited_<T, Else> = [T] extends [never]\n ? Else\n : unknown extends T\n ? Else // props that do not say: a section's own, with no params among them\n : T extends Promise<infer V>\n ? V\n : T extends undefined\n ? Else\n : T;\n\n/**\n * What a refreshOn function is given: the page's params and search params,\n * already awaited, beside whatever props the section was rendered with.\n *\n * Typed from P when it says what they are - a page's `PageProps<typeof\n * params>` - so `params.team` is the schema's type, not a string by hand.\n */\nexport type RefreshOnInput<P> = Omit<P, \"params\" | \"searchParams\"> & {\n params: Awaited_<P extends { params?: infer A } ? A : never, Record<string, string>>;\n searchParams: Awaited_<\n P extends { searchParams?: infer S } ? S : never,\n URLSearchParams | Record<string, unknown>\n >;\n};\n\n/** What a section or page refreshes on: names, or a function of its props that makes them. */\nexport type RefreshOnList<P> =\n string[] | ((input: RefreshOnInput<P>) => string[] | Promise<string[]>);\n\n/**\n * The names a region refreshes on, read for this render and signed for the tab.\n *\n * A server component, rendered beside the region: it works out the names\n * from the props, asks the source what version each is at, and hands them to\n * the client as `Changes`. Under its own Suspense boundary, so the ask never\n * holds up the region's paint - the data is what the visitor is waiting on,\n * not the version numbers behind it.\n *\n * Renders nothing when the source cannot answer - a backend that is down\n * for this one call. The region still renders; it just does not refresh on\n * its names until the next time it is rendered.\n */\nexport function RefreshOn<P>({\n target,\n refreshOn,\n props,\n}: {\n target: string;\n refreshOn: RefreshOnList<P>;\n props: P;\n}): ReactNode {\n return createElement(\n Suspense,\n { fallback: null },\n createElement(Resolve as never, { target, refreshOn, props }),\n );\n}\n\n/** Where createTestApp's watched() collects what a render's regions refresh on. */\nexport const WATCHED = Symbol.for(\"rsc-kit.test-watched\");\n\nconst warned = new Set<string>();\nconst emptyWarned = new Set<string>();\n\n/**\n * Never throws. An error here would become an error row inside the region's\n * payload, and the browser decodes that as the region failing - a blank\n * document for a version lookup that did not go through. Said once per\n * region instead, and the region renders without refreshing on anything.\n */\nasync function Resolve<P>({\n target,\n refreshOn,\n props,\n}: {\n target: string;\n refreshOn: RefreshOnList<P>;\n props: P;\n}): Promise<ReactNode> {\n try {\n // Per request, never at build. A version read at build is stale by the\n // time anyone loads the page, and a name signed at build is signed with\n // whatever key the build machine had. At build this suspends and the\n // names become a hole in the stored shell, filled per request.\n await connection();\n\n // The page's params and searchParams, under whatever the page passed: a\n // section rendered by its page is given nothing, and alone is given these.\n const given = { ...currentPageProps(), ...(props as object) } as Record<\n string,\n unknown\n >;\n\n // Awaited here, so `({ params }) => [\\`team:${params.team}\\`]` - the way\n // anyone writes it - means the team. A page's params and search params\n // are promises, and read without awaiting they made `team:undefined`:\n // one name for every team, so each refreshed on all the others' changes.\n // Awaiting costs nothing here; the names are made per request anyway.\n const input = {\n ...given,\n params: ((await given.params) ?? {}) as Record<string, string>,\n searchParams: ((await given.searchParams) ??\n new URLSearchParams()) as URLSearchParams,\n } as RefreshOnInput<P>;\n const unique = await namesFor(target, refreshOn, input);\n\n // A test asking what this page watches - createTestApp's watched() - is\n // told here, rather than left to dig the signed names out of the payload.\n const recording = (globalThis as { [WATCHED]?: Record<string, string[]> })[WATCHED];\n\n if (recording) recording[target] = unique;\n\n if (unique.length === 0) return null;\n\n // -1 is a version nothing is at, so every name comes back with its current version.\n const versions = await versionSource().changed(\n Object.fromEntries(unique.map((name) => [name, -1])),\n 0,\n );\n const signed: Record<string, SignedName> = {};\n\n for (const name of unique)\n signed[name] = [versions[name] ?? 0, await sign(name)];\n\n return createElement(Changes, { target, names: signed });\n } catch (error) {\n // A page that does not exist is not a page that cannot say what it\n // refreshes on: the same read that found no team is what the page says\n // notFound() about, and that is the answer. Warning for it was a line in the\n // log for every missing record.\n if (isNotFoundSignal(error)) return null;\n\n if (!warned.has(target)) {\n warned.add(target);\n console.warn(\n `[rsc-kit] what ${JSON.stringify(target)} refreshes on could not be read, so it will not: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n\n return null;\n }\n}\n\n/**\n * The names a region refreshes on, for this render: its list, or what its\n * function made of the input - unique, and only non-empty strings. Warns in\n * development when that is none at all.\n */\nexport async function namesFor<P>(\n target: string,\n refreshOn: RefreshOnList<P>,\n input: RefreshOnInput<P>,\n): Promise<string[]> {\n const named =\n typeof refreshOn === \"function\" ? await refreshOn(input) : refreshOn;\n const unique = [...new Set(named)].filter(\n (name) => typeof name === \"string\" && name !== \"\",\n );\n\n if (unique.length === 0) {\n // Usually a mistake that looks like working code - a param read under\n // the wrong name, a list built from an empty query - and the region\n // then refreshes on nothing. Said in development, once per region; a\n // region that means to watch nothing for some visitors can ignore it.\n if (\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n ?.NODE_ENV !== \"production\" &&\n !emptyWarned.has(target)\n ) {\n emptyWarned.add(target);\n console.warn(\n `[rsc-kit] ${JSON.stringify(target)}'s refreshOn gave no names, so it refreshes on nothing. ` +\n \"Check what it reads - a param under another name is undefined.\",\n );\n }\n\n return [];\n }\n\n return unique;\n}\n"]}
|
package/dist/js/section.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { ComponentType } from "react";
|
|
2
|
-
import type { RefreshOnList } from "./refreshOn";
|
|
3
|
-
import type { ApiParams, PageProps } from "../routeSchema";
|
|
4
|
-
import type { RoutePattern } from "../routes";
|
|
5
|
-
export type { RefreshOnInput, RefreshOnList } from "./refreshOn";
|
|
2
|
+
import type { RefreshOnList } from "./refreshOn.js";
|
|
3
|
+
import type { ApiParams, PageProps } from "../routeSchema.js";
|
|
4
|
+
import type { RoutePattern } from "../routes.js";
|
|
5
|
+
export type { RefreshOnInput, RefreshOnList } from "./refreshOn.js";
|
|
6
6
|
/**
|
|
7
7
|
* A page's `export const refreshOn`, typed from its own url schema or from
|
|
8
8
|
* its route's pattern:
|
package/dist/js/section.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Fragment, createElement } from "react";
|
|
2
|
-
import { SlotBoundary } from "./SlotBoundary";
|
|
3
|
-
import { RefreshOn } from "./refreshOn";
|
|
2
|
+
import { SlotBoundary } from "./SlotBoundary.js";
|
|
3
|
+
import { RefreshOn } from "./refreshOn.js";
|
|
4
4
|
/**
|
|
5
5
|
* Mark a region of a page as separately refreshable.
|
|
6
6
|
*
|
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,OAAO,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"section.js","sourceRoot":"","sources":["../../src/js/section.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA2B3C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,6EAA6E;AAC7E,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;AAE5D,yDAAyD;AACzD,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;AAoB1D,MAAM,UAAU,OAAO,CACrB,IAAY,EACZ,SAA2B,EAC3B,OAAO,GAAsB,EAAE;IAE/B,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC;IAE9B,2EAA2E;IAC3E,gEAAgE;IAChE,MAAM,KAAK,GAAqB,SAAS;QACvC,CAAC,CAAC,SAAS,gBAAgB,CAAC,KAAQ;YAChC,OAAO,aAAa,CAClB,QAAQ,EACR,IAAI,EACJ,aAAa,CACX,SAAiC,EACjC,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAW,CAC9D,EACD,aAAa,CACX,SAAiC,EACjC,EAAE,GAAG,EAAE,SAAS,EAAE,GAAI,KAAgB,EAAW,CAClD,CACF,CAAC;QACJ,CAAC;QACH,CAAC,CAAC,SAAS,CAAC;IAEd,2EAA2E;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.js\";\nimport { RefreshOn } from \"./refreshOn.js\";\nimport type { RefreshOnList } from \"./refreshOn.js\";\nimport type { ApiParams, PageProps } from \"../routeSchema.js\";\nimport type { RoutePattern } from \"../routes.js\";\n\nexport type { RefreshOnInput, RefreshOnList } from \"./refreshOn.js\";\n\n/**\n * A page's `export const refreshOn`, typed from its own url schema or from\n * its route's pattern:\n *\n * export const params = z.object({ team: z.string() })\n * export const refreshOn: PageRefreshOn<typeof params> = ({ params }) => [`team:${params.team}:repos`]\n *\n * // no schema: the pattern names the params, each a string\n * export const refreshOn: PageRefreshOn<'/[team]/[app]/[env]'> = ({ params }) => [`app:${params.app}`]\n *\n * The pattern is checked against the routes the build found, so one that is\n * not a page - or a param it does not have, `params.ap` - fails the\n * typecheck. `params` arrives awaited; with neither, a record of strings.\n */\nexport type PageRefreshOn<P extends RoutePattern | object = never, S = never> = [P] extends [never]\n ? RefreshOnList<PageProps<never, S>>\n : [P] extends [string]\n ? RefreshOnList<{ params: Promise<ApiParams<P>>; searchParams: Promise<URLSearchParams> }>\n : RefreshOnList<PageProps<P, S>>;\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/js/useAppUpdate.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* knows a new version activated.
|
|
13
13
|
*/
|
|
14
14
|
import { useSyncExternalStore } from "react";
|
|
15
|
-
import { isUpdated, subscribeToUpdates, updatedOnServer } from "./updateStore";
|
|
15
|
+
import { isUpdated, subscribeToUpdates, updatedOnServer } from "./updateStore.js";
|
|
16
16
|
export function useAppUpdate() {
|
|
17
17
|
const updated = useSyncExternalStore(subscribeToUpdates, isUpdated, updatedOnServer);
|
|
18
18
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAppUpdate.js","sourceRoot":"","sources":["../../src/js/useAppUpdate.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"useAppUpdate.js","sourceRoot":"","sources":["../../src/js/useAppUpdate.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAElF,MAAM,UAAU,YAAY;IAC1B,MAAM,OAAO,GAAG,oBAAoB,CAAC,kBAAkB,EAAE,SAAS,EAAE,eAAe,CAAC,CAAC;IAErF,OAAO;QACL,OAAO;QACP,qEAAqE;QACrE,oEAAoE;QACpE,6BAA6B;QAC7B,MAAM,EAAE,GAAG,EAAE;YACX,IAAI,OAAO,MAAM,KAAK,WAAW;gBAAE,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC9D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n/**\n * Whether a newer build is live, and how to get it.\n *\n * const { updated, reload } = useAppUpdate()\n *\n * if (updated) return <button onClick={reload}>A new version is ready</button>\n *\n * Reported rather than acted on. Reloading out from under someone mid-form is\n * worse than the staleness it fixes, so this package will not do it for you —\n * what it will do is tell you, which nothing else can, because only the worker\n * knows a new version activated.\n */\n\nimport { useSyncExternalStore } from \"react\";\nimport { isUpdated, subscribeToUpdates, updatedOnServer } from \"./updateStore.js\";\n\nexport function useAppUpdate(): { updated: boolean; reload: () => void } {\n const updated = useSyncExternalStore(subscribeToUpdates, isUpdated, updatedOnServer);\n\n return {\n updated,\n // location.reload() rather than a router navigation: the point is to\n // re-fetch the document and its javascript, and a client navigation\n // deliberately does neither.\n reload: () => {\n if (typeof window !== \"undefined\") window.location.reload();\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type FlashMessage } from "../flashCookie.js";
|
|
2
|
+
export type { FlashKind, FlashMessage } from "../flashCookie.js";
|
|
3
|
+
/**
|
|
4
|
+
* Hands each message flash() queued to `onMessage`, once, and clears it.
|
|
5
|
+
*
|
|
6
|
+
* useFlash(({ message, kind }) => (kind === 'error' ? toast.error : toast.success)(message))
|
|
7
|
+
*
|
|
8
|
+
* Put it in a client component in the root layout: it looks on mount, after
|
|
9
|
+
* every navigation (an action's redirect is one), and whenever the cookie
|
|
10
|
+
* changes where the browser can say so - an action that stays on the page.
|
|
11
|
+
* Render the message as text; it is a cookie, and a cookie can be set by
|
|
12
|
+
* anything on the domain.
|
|
13
|
+
*/
|
|
14
|
+
export declare function useFlash(onMessage: (message: FlashMessage) => void): void;
|
|
15
|
+
/** The queued messages, taken: read, then cleared, so each is shown once. */
|
|
16
|
+
export declare function takeFlash(): FlashMessage[];
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { FLASH_COOKIE, readFlash } from "../flashCookie.js";
|
|
4
|
+
/**
|
|
5
|
+
* Hands each message flash() queued to `onMessage`, once, and clears it.
|
|
6
|
+
*
|
|
7
|
+
* useFlash(({ message, kind }) => (kind === 'error' ? toast.error : toast.success)(message))
|
|
8
|
+
*
|
|
9
|
+
* Put it in a client component in the root layout: it looks on mount, after
|
|
10
|
+
* every navigation (an action's redirect is one), and whenever the cookie
|
|
11
|
+
* changes where the browser can say so - an action that stays on the page.
|
|
12
|
+
* Render the message as text; it is a cookie, and a cookie can be set by
|
|
13
|
+
* anything on the domain.
|
|
14
|
+
*/
|
|
15
|
+
export function useFlash(onMessage) {
|
|
16
|
+
const latest = useRef(onMessage);
|
|
17
|
+
latest.current = onMessage;
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
const take = () => {
|
|
20
|
+
for (const message of takeFlash())
|
|
21
|
+
latest.current(message);
|
|
22
|
+
};
|
|
23
|
+
take();
|
|
24
|
+
// CookieStore says when a response set the cookie, even with no
|
|
25
|
+
// navigation. Where it is missing (or the page is not a secure context),
|
|
26
|
+
// a navigation is still the moment that matters.
|
|
27
|
+
const store = globalThis.cookieStore;
|
|
28
|
+
window.addEventListener("rsc-navigate", take);
|
|
29
|
+
window.addEventListener("popstate", take);
|
|
30
|
+
store?.addEventListener("change", take);
|
|
31
|
+
return () => {
|
|
32
|
+
window.removeEventListener("rsc-navigate", take);
|
|
33
|
+
window.removeEventListener("popstate", take);
|
|
34
|
+
store?.removeEventListener("change", take);
|
|
35
|
+
};
|
|
36
|
+
}, []);
|
|
37
|
+
}
|
|
38
|
+
/** The queued messages, taken: read, then cleared, so each is shown once. */
|
|
39
|
+
export function takeFlash() {
|
|
40
|
+
if (typeof document === "undefined")
|
|
41
|
+
return [];
|
|
42
|
+
const prefix = `${FLASH_COOKIE}=`;
|
|
43
|
+
const raw = document.cookie.split("; ").find((part) => part.startsWith(prefix));
|
|
44
|
+
if (!raw)
|
|
45
|
+
return [];
|
|
46
|
+
document.cookie = `${FLASH_COOKIE}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/; SameSite=Lax`;
|
|
47
|
+
let value;
|
|
48
|
+
try {
|
|
49
|
+
value = decodeURIComponent(raw.slice(prefix.length));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
return readFlash(value);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=useFlash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useFlash.js","sourceRoot":"","sources":["../../src/js/useFlash.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAqB,MAAM,mBAAmB,CAAC;AAI/E;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ,CAAC,SAA0C;IACjE,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;IAEjC,MAAM,CAAC,OAAO,GAAG,SAAS,CAAC;IAE3B,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,IAAI,GAAG,GAAG,EAAE;YAChB,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE;gBAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAC7D,CAAC,CAAC;QAEF,IAAI,EAAE,CAAC;QAEP,gEAAgE;QAChE,yEAAyE;QACzE,iDAAiD;QACjD,MAAM,KAAK,GAAI,UAA4C,CAAC,WAAW,CAAC;QAExE,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;QAC9C,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAC1C,KAAK,EAAE,gBAAgB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAExC,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,mBAAmB,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;YACjD,MAAM,CAAC,mBAAmB,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;YAC7C,KAAK,EAAE,mBAAmB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC7C,CAAC,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,SAAS;IACvB,IAAI,OAAO,QAAQ,KAAK,WAAW;QAAE,OAAO,EAAE,CAAC;IAE/C,MAAM,MAAM,GAAG,GAAG,YAAY,GAAG,CAAC;IAClC,MAAM,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;IAEhF,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IAEpB,QAAQ,CAAC,MAAM,GAAG,GAAG,YAAY,2EAA2E,CAAC;IAE7G,IAAI,KAAa,CAAC;IAElB,IAAI,CAAC;QACH,KAAK,GAAG,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IACvD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,SAAS,CAAC,KAAK,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { FLASH_COOKIE, readFlash, type FlashMessage } from \"../flashCookie.js\";\n\nexport type { FlashKind, FlashMessage } from \"../flashCookie.js\";\n\n/**\n * Hands each message flash() queued to `onMessage`, once, and clears it.\n *\n * useFlash(({ message, kind }) => (kind === 'error' ? toast.error : toast.success)(message))\n *\n * Put it in a client component in the root layout: it looks on mount, after\n * every navigation (an action's redirect is one), and whenever the cookie\n * changes where the browser can say so - an action that stays on the page.\n * Render the message as text; it is a cookie, and a cookie can be set by\n * anything on the domain.\n */\nexport function useFlash(onMessage: (message: FlashMessage) => void): void {\n const latest = useRef(onMessage);\n\n latest.current = onMessage;\n\n useEffect(() => {\n const take = () => {\n for (const message of takeFlash()) latest.current(message);\n };\n\n take();\n\n // CookieStore says when a response set the cookie, even with no\n // navigation. Where it is missing (or the page is not a secure context),\n // a navigation is still the moment that matters.\n const store = (globalThis as { cookieStore?: EventTarget }).cookieStore;\n\n window.addEventListener(\"rsc-navigate\", take);\n window.addEventListener(\"popstate\", take);\n store?.addEventListener(\"change\", take);\n\n return () => {\n window.removeEventListener(\"rsc-navigate\", take);\n window.removeEventListener(\"popstate\", take);\n store?.removeEventListener(\"change\", take);\n };\n }, []);\n}\n\n/** The queued messages, taken: read, then cleared, so each is shown once. */\nexport function takeFlash(): FlashMessage[] {\n if (typeof document === \"undefined\") return [];\n\n const prefix = `${FLASH_COOKIE}=`;\n const raw = document.cookie.split(\"; \").find((part) => part.startsWith(prefix));\n\n if (!raw) return [];\n\n document.cookie = `${FLASH_COOKIE}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/; SameSite=Lax`;\n\n let value: string;\n\n try {\n value = decodeURIComponent(raw.slice(prefix.length));\n } catch {\n return [];\n }\n\n return readFlash(value);\n}\n"]}
|
package/dist/js/useOnline.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useSyncExternalStore } from "react";
|
|
3
|
-
import { isReachable, subscribeReachable } from "./onlineStore";
|
|
3
|
+
import { isReachable, subscribeReachable } from "./onlineStore.js";
|
|
4
4
|
/** The server is reachable from itself; assuming otherwise would render an
|
|
5
5
|
* offline state into the HTML and mismatch on hydration. */
|
|
6
6
|
function getServerSnapshot() {
|
package/dist/js/useOnline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOnline.js","sourceRoot":"","sources":["../../src/js/useOnline.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"useOnline.js","sourceRoot":"","sources":["../../src/js/useOnline.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEnE;4DAC4D;AAC5D,SAAS,iBAAiB;IACxB,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,SAAS;IACvB,OAAO,oBAAoB,CAAC,kBAAkB,EAAE,WAAW,EAAE,iBAAiB,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,UAAU,UAAU;IACxB,OAAO,CAAC,SAAS,EAAE,CAAC;AACtB,CAAC","sourcesContent":["\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { isReachable, subscribeReachable } from \"./onlineStore.js\";\n\n/** The server is reachable from itself; assuming otherwise would render an\n * offline state into the HTML and mismatch on hydration. */\nfunction getServerSnapshot(): boolean {\n return true;\n}\n\n/**\n * Whether the app can reach the server, as the router last observed it.\n *\n * See onlineStore.ts for why this is not `navigator.onLine`.\n */\nexport function useOnline(): boolean {\n return useSyncExternalStore(subscribeReachable, isReachable, getServerSnapshot);\n}\n\nexport function useOffline(): boolean {\n return !useOnline();\n}\n"]}
|
package/dist/js/usePathname.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useSyncExternalStore } from "react";
|
|
3
|
-
import { useRenderedPathname } from "./PathnameProvider";
|
|
3
|
+
import { useRenderedPathname } from "./PathnameProvider.js";
|
|
4
4
|
let currentPathname = typeof window !== "undefined" ? window.location.pathname : "/";
|
|
5
5
|
const listeners = new Set();
|
|
6
6
|
function notify() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usePathname.js","sourceRoot":"","sources":["../../src/js/usePathname.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"usePathname.js","sourceRoot":"","sources":["../../src/js/usePathname.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,IAAI,eAAe,GAAG,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC;AACrF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;AAExC,SAAS,MAAM;IACb,eAAe,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;IAC3C,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC;AAED,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;IAClC,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;IAChD,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC;AAED,SAAS,SAAS,CAAC,QAAoB;IACrC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACxB,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC1C,CAAC;AAED,SAAS,WAAW;IAClB,OAAO,eAAe,CAAC;AACzB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;IAEvC,OAAO,oBAAoB,CAAC,SAAS,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC","sourcesContent":["\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { useRenderedPathname } from \"./PathnameProvider.js\";\n\nlet currentPathname = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\nconst listeners = new Set<() => void>();\n\nfunction notify(): void {\n currentPathname = window.location.pathname;\n listeners.forEach((fn) => fn());\n}\n\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"rsc-navigate\", notify);\n window.addEventListener(\"popstate\", notify);\n}\n\nfunction subscribe(callback: () => void): () => void {\n listeners.add(callback);\n return () => listeners.delete(callback);\n}\n\nfunction getSnapshot(): string {\n return currentPathname;\n}\n\n/**\n * The current pathname, live across navigations.\n *\n * The server snapshot comes from the url being rendered rather than a\n * constant. It used to be \"/\" — so a nav bar on any other page rendered with\n * the wrong link marked active, and only hydration put it right.\n */\nexport function usePathname(): string {\n const rendered = useRenderedPathname();\n\n return useSyncExternalStore(subscribe, getSnapshot, () => rendered);\n}\n"]}
|
package/dist/testing.d.ts
CHANGED
|
@@ -84,4 +84,13 @@ export declare function staticFile(root: string, request: Request): Response | n
|
|
|
84
84
|
*/
|
|
85
85
|
/** @internal Exported for its test. */
|
|
86
86
|
export declare function buildCommand(root: string): [string, string[]];
|
|
87
|
+
/**
|
|
88
|
+
* Whether the last build can be tested as it is: newer than everything it is
|
|
89
|
+
* made from, and whole. A Nitro build is two places - the server bundle under
|
|
90
|
+
* node_modules/.nitro, and .output, which holds the browser's assets and what
|
|
91
|
+
* staticFile() answers from. Deleting .output (a clean, a deploy step, a
|
|
92
|
+
* `git clean`) left the bundle newer than the source, so the check passed and
|
|
93
|
+
* every asset a test asked for was a 404, far from the cause.
|
|
94
|
+
*/
|
|
95
|
+
export declare function buildIsFresh(root: string, bundle: string): boolean;
|
|
87
96
|
export declare function createTestApp(options?: TestAppOptions): Promise<TestApp>;
|
package/dist/testing.js
CHANGED
|
@@ -150,6 +150,19 @@ export function buildCommand(root) {
|
|
|
150
150
|
}
|
|
151
151
|
return onBun ? ['bun', ['--bun', 'vite', 'build']] : ['npx', ['vite', 'build']];
|
|
152
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* Whether the last build can be tested as it is: newer than everything it is
|
|
155
|
+
* made from, and whole. A Nitro build is two places - the server bundle under
|
|
156
|
+
* node_modules/.nitro, and .output, which holds the browser's assets and what
|
|
157
|
+
* staticFile() answers from. Deleting .output (a clean, a deploy step, a
|
|
158
|
+
* `git clean`) left the bundle newer than the source, so the check passed and
|
|
159
|
+
* every asset a test asked for was a 404, far from the cause.
|
|
160
|
+
*/
|
|
161
|
+
export function buildIsFresh(root, bundle) {
|
|
162
|
+
if (bundle.replaceAll('\\', '/').includes('/node_modules/.nitro/') && !existsSync(join(root, '.output/public')))
|
|
163
|
+
return false;
|
|
164
|
+
return statSync(bundle).mtimeMs > newestInput(root);
|
|
165
|
+
}
|
|
153
166
|
async function ensureBuilt(root, build) {
|
|
154
167
|
const existing = findBundle(root);
|
|
155
168
|
if (!build) {
|
|
@@ -158,8 +171,7 @@ async function ensureBuilt(root, build) {
|
|
|
158
171
|
}
|
|
159
172
|
return existing;
|
|
160
173
|
}
|
|
161
|
-
|
|
162
|
-
if (fresh)
|
|
174
|
+
if (existing && buildIsFresh(root, existing))
|
|
163
175
|
return existing;
|
|
164
176
|
// The user's own build command, so what is tested is what ships. A test
|
|
165
177
|
// that built some other way would pass against a bundle nobody deploys -
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,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AAE;YAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;YAEnD,sEAAsE;YACtE,kDAAkD;YAClD,OAAO,IAAI,CAAC,OAAO,CAAC,qCAAqC,EAAE,EAAE,CAAC,CAAA;QAChE,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;YAC5B,qEAAqE;YACrE,qEAAqE;YACrE,MAAM,SAAS,GAA6B,EAAE,CAAA;YAC9C,MAAM,IAAI,GAAG,UAAsD,CAAA;YAEnE,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,CAAA;YAEzB,IAAI,CAAC;gBACH,kEAAkE;gBAClE,+CAA+C;gBAC/C,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;YACxC,CAAC;oBAAS,CAAC;gBACT,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;YACtB,CAAC;YAED,OAAO,SAAS,CAAA;QAClB,CAAC;KACF,CAAA;AACH,CAAC;AAED,+FAA+F;AAC/F,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAA","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 { 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 /**\n * What each region of the page at `path` refreshes on, rendered for this\n * request: `{ page: ['ledger'], repos: ['team:1:repos'] }` - `page` for the\n * page's own `refreshOn`, a section's name for each section's. A region\n * whose refreshOn gave no names is there with `[]`; one with no refreshOn\n * is not there at all.\n *\n * expect(await app.watched('/teams/1')).toMatchObject({ repos: ['team:1:repos'] })\n *\n * The names a tab would be handed, without reading them out of the payload.\n */\n watched(path: string, init?: RequestInit): Promise<Record<string, string[]>>\n /**\n * The page at `path` as markup: the whole streamed document, with every\n * `<script>` taken out.\n *\n * The document carries the page's payload for the browser to hydrate from,\n * and the payload holds everything the page was given - a client\n * component's props included, shown or not. A test asserting that something\n * is NOT on the page reads this, not `fetch`:\n *\n * expect(await app.markup('/teams/1')).not.toContain('internal note')\n *\n * Regions that streamed in later are included where they arrived; a\n * Suspense fallback they replaced is still in the markup too, as the\n * server sent it.\n */\n markup(path: string, init?: RequestInit): Promise<string>\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 // The default outDir since 0.29.8; .rsc before it.\n join(root, '.rsc-kit/dist/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/**\n * When anything a build is made from last changed: the app's source, its\n * Vite config, its dependencies - package.json, the lockfile, and the\n * installed engine itself. Only src/ used to count, so an app that upgraded\n * @rsc-kit/core kept testing the build the old one made, and passed.\n */\nfunction newestInput(root: string): number {\n const files = [\n 'vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs',\n 'package.json', 'bun.lock', 'bun.lockb', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock',\n ]\n let latest = newest(join(root, 'src'))\n\n for (const file of files) {\n const path = join(root, file)\n\n if (existsSync(path)) latest = Math.max(latest, statSync(path).mtimeMs)\n }\n\n // The engine as installed: a workspace link changes without the lockfile.\n const engine = join(root, 'node_modules/@rsc-kit/core/dist')\n\n return Math.max(latest, newest(engine))\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 > newestInput(root)\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 */\n/**\n * Whether Request is the runtime's, told apart from a browser's by behaviour.\n *\n * A browser forbids a script from setting Cookie, so happy-dom's Request drops\n * it from an init - and every signed-in request a test makes arrives with no\n * session, bounces to sign-in, and fails far from the cause. Behaviour rather\n * than identity, because identity depends on which file loaded first.\n */\nfunction runtimeRequest(): boolean {\n try {\n return new Request('http://probe.test/', { headers: { cookie: 'probe=1' } }).headers.has('cookie')\n } catch {\n return false\n }\n}\n\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n if (!runtimeRequest()) {\n throw new Error(\n \"[rsc-kit] createTestApp is running against a browser's Request: a DOM is registered globally \" +\n '(happy-dom, in a preload or an earlier test file), and it replaces Request, Response, Headers and fetch. ' +\n 'A browser cannot set Cookie, so every signed-in request would arrive with no session. ' +\n 'Register the DOM only in the component test file and `GlobalRegistrator.unregister()` after it, ' +\n 'and run the suites isolated (`bun test --isolate`). See the testing guide, \"Components\".',\n )\n }\n\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 const fetch: TestApp['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 return {\n bundle,\n fetch,\n markup: async (path, init) => {\n const html = await (await fetch(path, init)).text()\n\n // A script's body never holds its own closing tag: the payload writes\n // \"<\" as \\u003c, and React's scripts are its own.\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, '')\n },\n watched: async (path, init) => {\n // The render records what each region resolves to while this is set:\n // the app's bundle runs in this process, so it sees the same global.\n const recording: Record<string, string[]> = {}\n const into = globalThis as { [WATCHED]?: Record<string, string[]> }\n\n into[WATCHED] = recording\n\n try {\n // Read to the end: the names resolve under their own Suspense, so\n // they are in the stream's tail, not its head.\n await (await fetch(path, init)).text()\n } finally {\n delete into[WATCHED]\n }\n\n return recording\n },\n }\n}\n\n/** Where a render records what its regions refresh on, while watched() asks (js/refreshOn). */\nconst WATCHED = Symbol.for('rsc-kit.test-watched')\n"]}
|
|
1
|
+
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,EAAE;AACF,0DAA0D;AAC1D,EAAE;AACF,sCAAsC;AACtC,oFAAoF;AACpF,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,6EAA6E;AAC7E,+EAA+E;AAC/E,gBAAgB;AAChB,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,4EAA4E;AAC5E,gEAAgE;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAC9C,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AACzE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,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nD,sEAAsE;YACtE,kDAAkD;YAClD,OAAO,IAAI,CAAC,OAAO,CAAC,qCAAqC,EAAE,EAAE,CAAC,CAAA;QAChE,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;YAC5B,qEAAqE;YACrE,qEAAqE;YACrE,MAAM,SAAS,GAA6B,EAAE,CAAA;YAC9C,MAAM,IAAI,GAAG,UAAsD,CAAA;YAEnE,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,CAAA;YAEzB,IAAI,CAAC;gBACH,kEAAkE;gBAClE,+CAA+C;gBAC/C,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;YACxC,CAAC;oBAAS,CAAC;gBACT,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;YACtB,CAAC;YAED,OAAO,SAAS,CAAA;QAClB,CAAC;KACF,CAAA;AACH,CAAC;AAED,+FAA+F;AAC/F,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAA","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 { 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 /**\n * What each region of the page at `path` refreshes on, rendered for this\n * request: `{ page: ['ledger'], repos: ['team:1:repos'] }` - `page` for the\n * page's own `refreshOn`, a section's name for each section's. A region\n * whose refreshOn gave no names is there with `[]`; one with no refreshOn\n * is not there at all.\n *\n * expect(await app.watched('/teams/1')).toMatchObject({ repos: ['team:1:repos'] })\n *\n * The names a tab would be handed, without reading them out of the payload.\n */\n watched(path: string, init?: RequestInit): Promise<Record<string, string[]>>\n /**\n * The page at `path` as markup: the whole streamed document, with every\n * `<script>` taken out.\n *\n * The document carries the page's payload for the browser to hydrate from,\n * and the payload holds everything the page was given - a client\n * component's props included, shown or not. A test asserting that something\n * is NOT on the page reads this, not `fetch`:\n *\n * expect(await app.markup('/teams/1')).not.toContain('internal note')\n *\n * Regions that streamed in later are included where they arrived; a\n * Suspense fallback they replaced is still in the markup too, as the\n * server sent it.\n */\n markup(path: string, init?: RequestInit): Promise<string>\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 // The default outDir since 0.29.8; .rsc before it.\n join(root, '.rsc-kit/dist/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/**\n * When anything a build is made from last changed: the app's source, its\n * Vite config, its dependencies - package.json, the lockfile, and the\n * installed engine itself. Only src/ used to count, so an app that upgraded\n * @rsc-kit/core kept testing the build the old one made, and passed.\n */\nfunction newestInput(root: string): number {\n const files = [\n 'vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs',\n 'package.json', 'bun.lock', 'bun.lockb', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock',\n ]\n let latest = newest(join(root, 'src'))\n\n for (const file of files) {\n const path = join(root, file)\n\n if (existsSync(path)) latest = Math.max(latest, statSync(path).mtimeMs)\n }\n\n // The engine as installed: a workspace link changes without the lockfile.\n const engine = join(root, 'node_modules/@rsc-kit/core/dist')\n\n return Math.max(latest, newest(engine))\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\n/**\n * Whether the last build can be tested as it is: newer than everything it is\n * made from, and whole. A Nitro build is two places - the server bundle under\n * node_modules/.nitro, and .output, which holds the browser's assets and what\n * staticFile() answers from. Deleting .output (a clean, a deploy step, a\n * `git clean`) left the bundle newer than the source, so the check passed and\n * every asset a test asked for was a 404, far from the cause.\n */\nexport function buildIsFresh(root: string, bundle: string): boolean {\n if (bundle.replaceAll('\\\\', '/').includes('/node_modules/.nitro/') && !existsSync(join(root, '.output/public'))) return false\n\n return statSync(bundle).mtimeMs > newestInput(root)\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 if (existing && buildIsFresh(root, existing)) 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 */\n/**\n * Whether Request is the runtime's, told apart from a browser's by behaviour.\n *\n * A browser forbids a script from setting Cookie, so happy-dom's Request drops\n * it from an init - and every signed-in request a test makes arrives with no\n * session, bounces to sign-in, and fails far from the cause. Behaviour rather\n * than identity, because identity depends on which file loaded first.\n */\nfunction runtimeRequest(): boolean {\n try {\n return new Request('http://probe.test/', { headers: { cookie: 'probe=1' } }).headers.has('cookie')\n } catch {\n return false\n }\n}\n\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n if (!runtimeRequest()) {\n throw new Error(\n \"[rsc-kit] createTestApp is running against a browser's Request: a DOM is registered globally \" +\n '(happy-dom, in a preload or an earlier test file), and it replaces Request, Response, Headers and fetch. ' +\n 'A browser cannot set Cookie, so every signed-in request would arrive with no session. ' +\n 'Register the DOM only in the component test file and `GlobalRegistrator.unregister()` after it, ' +\n 'and run the suites isolated (`bun test --isolate`). See the testing guide, \"Components\".',\n )\n }\n\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 const fetch: TestApp['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 return {\n bundle,\n fetch,\n markup: async (path, init) => {\n const html = await (await fetch(path, init)).text()\n\n // A script's body never holds its own closing tag: the payload writes\n // \"<\" as \\u003c, and React's scripts are its own.\n return html.replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, '')\n },\n watched: async (path, init) => {\n // The render records what each region resolves to while this is set:\n // the app's bundle runs in this process, so it sees the same global.\n const recording: Record<string, string[]> = {}\n const into = globalThis as { [WATCHED]?: Record<string, string[]> }\n\n into[WATCHED] = recording\n\n try {\n // Read to the end: the names resolve under their own Suspense, so\n // they are in the stream's tail, not its head.\n await (await fetch(path, init)).text()\n } finally {\n delete into[WATCHED]\n }\n\n return recording\n },\n }\n}\n\n/** Where a render records what its regions refresh on, while watched() asks (js/refreshOn). */\nconst WATCHED = Symbol.for('rsc-kit.test-watched')\n"]}
|