@rsc-kit/core 0.18.1 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action.d.ts +16 -2
- package/dist/action.js +21 -12
- package/dist/action.js.map +1 -1
- package/dist/apiPrerender.js +25 -7
- package/dist/apiPrerender.js.map +1 -1
- package/dist/clientPackages.d.ts +30 -0
- package/dist/clientPackages.js +234 -0
- package/dist/clientPackages.js.map +1 -0
- package/dist/compress.d.ts +12 -0
- package/dist/compress.js +134 -0
- package/dist/compress.js.map +1 -0
- package/dist/compressRuntime.d.ts +8 -0
- package/dist/compressRuntime.js +62 -0
- package/dist/compressRuntime.js.map +1 -0
- package/dist/files.d.ts +20 -0
- package/dist/files.js +38 -0
- package/dist/files.js.map +1 -1
- package/dist/formSubmit.d.ts +1 -0
- package/dist/formSubmit.js +14 -0
- package/dist/formSubmit.js.map +1 -0
- package/dist/host.d.ts +23 -0
- package/dist/host.js +175 -31
- package/dist/host.js.map +1 -1
- package/dist/hostCalls.d.ts +15 -0
- package/dist/hostCalls.js +75 -8
- package/dist/hostCalls.js.map +1 -1
- package/dist/js/Form.d.ts +21 -4
- package/dist/js/Form.js +110 -83
- package/dist/js/Form.js.map +1 -1
- package/dist/js/Link.d.ts +5 -5
- package/dist/js/Link.js.map +1 -1
- package/dist/js/RedirectBoundary.js.map +1 -1
- package/dist/js/RouteErrorBoundary.d.ts +6 -2
- package/dist/js/RouteErrorBoundary.js +10 -0
- package/dist/js/RouteErrorBoundary.js.map +1 -1
- package/dist/js/SlotBoundary.d.ts +7 -1
- package/dist/js/SlotBoundary.js +9 -1
- package/dist/js/SlotBoundary.js.map +1 -1
- package/dist/js/createViteRscApp.d.ts +1 -0
- package/dist/js/createViteRscApp.js +54 -5
- package/dist/js/createViteRscApp.js.map +1 -1
- package/dist/js/errors.d.ts +3 -1
- package/dist/js/errors.js +26 -3
- package/dist/js/errors.js.map +1 -1
- package/dist/js/formEncoding.d.ts +72 -3
- package/dist/js/formEncoding.js +284 -20
- package/dist/js/formEncoding.js.map +1 -1
- package/dist/js/navigate.d.ts +6 -3
- package/dist/js/navigate.js +57 -7
- package/dist/js/navigate.js.map +1 -1
- package/dist/js/nuqs.js.map +1 -1
- package/dist/js/router.d.ts +3 -3
- package/dist/js/router.js.map +1 -1
- package/dist/js/updateStore.js +8 -2
- package/dist/js/updateStore.js.map +1 -1
- package/dist/manifest.d.ts +6 -0
- package/dist/manifest.js.map +1 -1
- package/dist/openapi.d.ts +74 -0
- package/dist/openapi.js +172 -0
- package/dist/openapi.js.map +1 -0
- package/dist/redirect.d.ts +4 -4
- package/dist/redirect.js.map +1 -1
- package/dist/request.d.ts +56 -2
- package/dist/request.js +68 -4
- package/dist/request.js.map +1 -1
- package/dist/routes.d.ts +17 -6
- package/dist/routes.js.map +1 -1
- package/dist/testing.d.ts +14 -0
- package/dist/testing.js +56 -2
- package/dist/testing.js.map +1 -1
- package/dist/useSsr.d.ts +11 -0
- package/dist/useSsr.js +15 -0
- package/dist/useSsr.js.map +1 -1
- package/dist/vite.d.ts +69 -1
- package/dist/vite.js +481 -51
- package/dist/vite.js.map +1 -1
- package/package.json +5 -1
package/dist/request.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,EAAE;AACF,6DAA6D;AAC7D,EAAE;AACF,iDAAiD;AACjD,4FAA4F;AAC5F,mCAAmC;AACnC,MAAM;AACN,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,iBAAiB;AACjB,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,qDAAqD;AACrD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,+EAA+E;AAC/E,4EAA4E;AAC5E,yEAAyE;AACzE,0EAA0E;AAC1E,gDAAgD;A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,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAElE,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QAEnD,MAAM,KAAK,GACT,QAAQ,CAAC,MAAM,KAAK,CAAC;YACnB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC;YACxB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAEnE,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,eAAe,KAAK,EAAE,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY;IAChC,6EAA6E;IAC7E,iDAAiD;IACjD,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;IAErB,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC;QAC/D,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,GAAG,EAAE,CAAC;IAEzB,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,eAAe,EAAE,CAAC;AACnE,CAAC","sourcesContent":["// Reading the request from inside a render.\n//\n// import { headers, cookies } from '@rsc-kit/core/request'\n//\n// export default async function middleware() {\n// const locale = cookies().get('locale') ?? negotiate(headers().get('accept-language'))\n// if (!locale) redirect('/en')\n// }\n//\n// Server components have no arguments beyond their props, and middleware has\n// none at all, so without this an app on a JavaScript host cannot see a header\n// — no locale negotiation, no subdomain, no cookie. The Laravel host escaped\n// that through rpc(), because PHP has the request; this is the same thing for\n// everyone else.\n//\n// Read-only on purpose. Setting a cookie means writing a response header, and\n// by the time a component renders the shell may already have been flushed — an\n// API that appears to set one and silently does not is worse than not having\n// it. Set them in the host, which owns the response.\n//\n// Asynchronous on purpose too, and not for ergonomics. A build has no request,\n// so a read there suspends and never settles — which is the same thing the\n// prerender probe does to a host call. Anything still waiting when the probe's\n// budget expires becomes a fallback in the frozen shell, so a read inside a\n// Suspense boundary leaves the shell frozen and makes only that boundary\n// dynamic. Reading synchronously could only mark the whole route dynamic,\n// because there would be nothing to suspend on.\n//\n// Scoped to the request, on the same store cache() uses. Two requests in\n// flight cannot see each other's headers.\n\nimport { resolveScope } from \"./revalidate.js\";\n\n/** What a host can supply: a real Request, or the parts of one. */\nexport type RequestLike =\n Request | { url: string; headers: Record<string, string> } | null;\n\ninterface Slot {\n /** False during a build: there is nothing to answer with. */\n request: boolean;\n url: string | null;\n /**\n * Held as Headers rather than as a Request.\n *\n * `new Request(url, { headers })` drops Cookie: a spec-compliant Headers\n * built with the \"request\" guard refuses the forbidden header names, and\n * Cookie is one of them. `new Headers()` has no guard and keeps it. Bun\n * happens to allow both, which is why rebuilding a Request looked fine until\n * it ran anywhere stricter — and what it loses is every cookie, silently.\n */\n headers: Headers;\n original: Request | null;\n /**\n * Whether anything asked. Only for the build's report — the classification\n * comes from the suspension, not from this.\n */\n read: boolean;\n /**\n * What read it, in the order they did.\n *\n * Only the name of the accessor — `cookies()`, `headers()` — which is enough\n * for the build to say why a page could not be frozen. Without it the answer\n * is \"something in this page reached for the request\", and finding which is\n * the part that takes an afternoon.\n */\n readBy: string[];\n /**\n * The same reads with the component that made each one - `cookies() in\n * RootLayout` - taken from the stack at the moment of the read, which is\n * still the component's own call: an accessor runs synchronously up to\n * the point it suspends. Only the build reads this. \"Reads the request\" is\n * a category; this is the line to open.\n */\n readWhere: string[];\n /**\n * Reads the server could not answer and React caught at a boundary - the\n * fallback is what got stored - with the component that made each:\n * `useSearchParams() in Query`. Noted by the SSR entry, read by the build,\n * which attaches them to the route so a page stored as its own loading\n * screen says why.\n */\n fallbacks: string[];\n /**\n * For a read made inside a cache()-wrapped helper: the components that\n * awaited that helper, first caller included. The helper runs once, so\n * the stack at the read names only whoever got there first; every later\n * awaiter is a cache hit that never reaches the accessor. The one above\n * every boundary is usually one of the later ones.\n */\n awaiters: Map<unknown, string[]>;\n /** The cache()-wrapped helper whose body is running, while it runs. */\n inHelper: unknown;\n /** readWhere entry -> the helper it was read inside. */\n readVia: Map<string, unknown>;\n}\n\nconst SCOPE = Symbol.for(\"@rsc-kit/core.request-scope\");\n\n/**\n * The accessors themselves and the plumbing under them: frames to walk past\n * on the way to the component that called.\n */\nconst NOT_A_CALLER = new Set([\n \"never\",\n \"cache\",\n \"noteAwaiter\",\n \"withHelper\",\n \"noteRequestRead\",\n \"recordRead\",\n \"caller\",\n \"slot\",\n \"cookies\",\n \"headers\",\n \"connection\",\n \"searchParams\",\n \"request\",\n \"url\",\n \"parseParams\",\n \"parseSearchParams\",\n \"parseBody\",\n \"get\",\n \"set\",\n \"has\",\n]);\n\n/** The accessors a component calls by name. One calling another is plumbing, not a second read. */\nconst ACCESSORS = new Set([\n \"cookies\",\n \"headers\",\n \"connection\",\n \"searchParams\",\n \"request\",\n \"url\",\n]);\n\n/**\n * The nearest named function above the accessor on the stack, and whether\n * another accessor sits between: `cookies()` reads through `headers()`, and\n * that inner read is not a second thing the component did.\n *\n * Read from a thrown-away Error: the one thing a build cannot otherwise learn\n * is which component reached for the request, and the stack knows. Function\n * names survive a server bundle, which is not minified, so this is\n * `RootLayout` and not a line number in a chunk. Internal names are walked\n * past; an anonymous frame is skipped rather than reported as `<anonymous>`.\n */\nfunction caller(own: string): { name: string | null; nested: boolean } {\n const stack = new Error().stack ?? \"\";\n let accessors = 0;\n let helper: string | null = null;\n\n for (const line of stack.split(\"\\n\")) {\n const match = /^\\s*at (?:async )?([^\\s(]+)/.exec(line);\n\n if (!match) continue;\n\n const name = match[1]!.split(\".\").pop()!;\n\n // A frame with no function name prints its location instead - `js:6054:8`\n // - which is not a name to report.\n if (!/^[\\w$]+$/.test(name)) continue;\n\n if (ACCESSORS.has(name)) accessors++;\n if (\n NOT_A_CALLER.has(name) ||\n name === \"<anonymous>\" ||\n name === \"Object\" ||\n name === \"Promise\"\n )\n continue;\n\n const nested = accessors > (ACCESSORS.has(own) ? 1 : 0);\n\n // A function that is not a component - getCurrentUser, wrapped in\n // cache() - is the shared helper the read lives in. Named, because with\n // cache() the read runs once, on whichever component called first, and\n // every other caller of the helper is invisible to the stack. The helper\n // is what they have in common.\n if (/^[a-z_$]/.test(name) && !/^use[A-Z]/.test(name)) {\n helper ??= name;\n\n continue;\n }\n\n return {\n name: helper && helper !== name ? `${helper} (from ${name})` : name,\n nested,\n };\n }\n\n return { name: helper, nested: accessors > (ACCESSORS.has(own) ? 1 : 0) };\n}\n\nfunction recordRead(store: Slot, by: string): void {\n if (!store.readBy.includes(by)) store.readBy.push(by);\n\n // Older stores, written by a bundle built before this field existed.\n store.readWhere ??= [];\n\n const { name, nested } = caller(by.replace(/\\(.*$/, \"\"));\n\n if (nested) return;\n\n const entry = name ? `${by} in ${name}` : by;\n\n if (!store.readWhere.includes(entry)) store.readWhere.push(entry);\n if (store.inHelper) (store.readVia ??= new Map()).set(entry, store.inHelper);\n}\n\nconst globals = globalThis as Record<symbol | string, unknown>;\n\nlet ready: Promise<void> | null = null;\n\ninterface Scope {\n getStore(): Slot | undefined;\n run<T>(store: Slot, fn: () => T): T;\n}\n\nfunction scope(): Scope | null {\n return (globals[SCOPE] as Scope | undefined) ?? null;\n}\n\nfunction slot(): Slot {\n const store = scope()?.getStore();\n\n if (!store) {\n throw new Error(\n \"No request in scope. headers() and cookies() are for a render — middleware, a layout, \" +\n \"a page — and there is nothing to read outside one.\",\n );\n }\n\n store.read = true;\n\n return store;\n}\n\n/**\n * The request's headers.\n *\n * Empty during a build, where there is no request: the page is marked as\n * needing one instead, and rendered on demand rather than frozen.\n */\nexport async function headers(): Promise<Headers> {\n const store = slot();\n\n return store.request ? store.headers : never(\"headers()\");\n}\n\n/** How a cookie should be written. The names browsers use. */\nexport interface CookieOptions {\n path?: string;\n domain?: string;\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n partitioned?: boolean;\n}\n\nexport interface Cookies {\n get(name: string): string | undefined;\n has(name: string): boolean;\n getAll(): Record<string, string>;\n /**\n * Write one on the response.\n *\n * Only from a server action, which has a response of its own that has not\n * been sent. A render has already flushed its headers by the time a\n * component runs — that is what makes the first paint fast — so this throws\n * there rather than appearing to work.\n */\n set(name: string, value: string, options?: CookieOptions): void;\n /** Write one that expires immediately. Same rule about where. */\n delete(name: string, options?: CookieOptions): void;\n}\n\n/** Kept for the name it had when it could only read. */\nexport type ReadonlyCookies = Cookies;\n\n/**\n * The response being built, while it can still be changed.\n *\n * Open from the moment a request is picked up until the host constructs its\n * Response, and sealed the instant it does. Middleware runs inside that window\n * — before any rendering starts — so a header set there is on the answer. A\n * component runs after it, during streaming, where the status line and headers\n * are already on the wire; setting one there is refused rather than dropped.\n */\ninterface Draft {\n headers: Headers;\n sealed: boolean;\n}\n\nconst DRAFT = Symbol.for(\"@rsc-kit/core.response-draft\");\n\nlet draftReady: Promise<void> | null = null;\n\ninterface DraftScope {\n getStore(): Draft | undefined;\n run<T>(store: Draft, fn: () => T): T;\n}\n\nfunction draft(): DraftScope | null {\n return (globals[DRAFT] as DraftScope | undefined) ?? null;\n}\n\n/** The open draft, or an explanation of why there is not one. */\nfunction writable(what: string): Draft {\n const open = draft()?.getStore();\n\n if (!open) {\n throw new Error(\n `${what} needs a response that has not been sent. Middleware and server actions have one; ` +\n \"a script outside a request does not.\",\n );\n }\n\n if (open.sealed) {\n throw new Error(\n `${what} was called after the response had been sent. Headers go out before the render ` +\n \"starts — that is what makes the first paint fast — so set them in middleware, which \" +\n \"runs before it.\",\n );\n }\n\n return open;\n}\n\n/**\n * Headers to put on the answer.\n *\n * Mutate it as you would any Headers. `append` is the one to reach for when a\n * header may legitimately appear twice; `set` replaces.\n */\n/**\n * The draft's headers, refusing writes once the response has gone.\n *\n * A proxy rather than the Headers itself: returning the live object means code\n * that captured it before the response was built can go on mutating a thing\n * nobody will read. Nothing in this package does that — the host copies the\n * headers onto the response the instant it seals — but \"safe because of the\n * order two other functions happen to run in\" is not a property, and an app\n * holding the object across an await would find writes silently doing nothing.\n */\nfunction sealable(draft: Draft): Headers {\n const guard =\n (method: \"set\" | \"append\" | \"delete\") =>\n (...args: [string, string]) => {\n writable(\"responseHeaders()\");\n\n return (draft.headers[method] as (...a: string[]) => void)(...args);\n };\n\n const proxy: Headers = new Proxy(draft.headers, {\n get(target, property, receiver) {\n if (\n property === \"set\" ||\n property === \"append\" ||\n property === \"delete\"\n ) {\n return guard(property);\n }\n\n // A maplike forEach passes the object it was called on as the third\n // callback argument, and binding to the target makes that the raw\n // Headers — a live, unguarded reference handed out by the very method\n // meant to be read-only. Substituted for the proxy so there is no way\n // through.\n if (property === \"forEach\") {\n return (\n fn: (value: string, key: string, parent: Headers) => void,\n thisArg?: unknown,\n ) =>\n target.forEach((value, key) => fn.call(thisArg, value, key, proxy));\n }\n\n const value = Reflect.get(target, property, receiver);\n\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n\n return proxy;\n}\n\nexport function responseHeaders(): Headers {\n return sealable(writable(\"responseHeaders()\"));\n}\n\n/**\n * Run a request with a response that can still be changed, and take what was\n * put on it.\n *\n * `seal()` is called by the host the moment it builds the Response, so\n * anything set afterwards is refused instead of silently going nowhere.\n */\nexport async function withResponseDraft<T>(\n run: (draft: { taken: () => Headers; seal: () => void }) => Promise<T>,\n): Promise<T> {\n if (!globals[DRAFT]) {\n draftReady ??= resolveScope().then((resolved) => {\n globals[DRAFT] ??= resolved as unknown as DraftScope;\n });\n\n await draftReady;\n }\n\n const open: Draft = { headers: new Headers(), sealed: false };\n\n return await draft()!.run(open, () =>\n run({\n taken: () => open.headers,\n seal: () => {\n open.sealed = true;\n },\n }),\n );\n}\n\n/**\n * A cookie name, as RFC 6265 defines one: a token, so no separators at all.\n *\n * Checked rather than escaped because there is no escaping — a name is not a\n * quoted string. An app that derives one from user input (`pref_${key}`) would\n * otherwise let that input close the pair and open another: a name of\n * `session=attacker; Path=/; HttpOnly; x` serializes to a header whose *first*\n * pair is a session cookie the caller chose, and the browser reads the first.\n */\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/** No separator may appear in an attribute either, for the same reason. */\nconst COOKIE_ATTRIBUTE = /[;,\\r\\n]/;\n\n/** `name=value; Path=/; HttpOnly` — the header a browser expects. */\nexport function serializeCookie(cookie: {\n name: string;\n value: string;\n options: CookieOptions;\n}): string {\n if (!COOKIE_NAME.test(cookie.name)) {\n throw new Error(\n `Not a usable cookie name: ${JSON.stringify(cookie.name)}. ` +\n \"A name is a token — letters, digits and !#$%&'*+-.^_`|~ — with no spaces, \" +\n \"semicolons or equals signs. Nothing escapes them, so one cannot be encoded around.\",\n );\n }\n\n if (cookie.options.sameSite !== undefined) {\n const value = String(cookie.options.sameSite).toLowerCase();\n\n if (value !== \"strict\" && value !== \"lax\" && value !== \"none\") {\n throw new Error(\n `Not a SameSite value: ${JSON.stringify(cookie.options.sameSite)}. ` +\n \"It is written into the header as given, so anything else becomes further attributes.\",\n );\n }\n }\n\n for (const [attribute, value] of [\n [\"path\", cookie.options.path],\n [\"domain\", cookie.options.domain],\n // Trusted because it is typed as a Date — but a cast reaches this, and the\n // result lands in the header verbatim like the others.\n [\"expires\", cookie.options.expires?.toUTCString()],\n ] as const) {\n if (typeof value === \"string\" && COOKIE_ATTRIBUTE.test(value)) {\n throw new Error(\n `The cookie ${attribute} ${JSON.stringify(value)} contains a separator. ` +\n \"It would be read as further attributes rather than as part of this one.\",\n );\n }\n }\n\n const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];\n const o = cookie.options;\n\n if (o.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(o.maxAge)}`);\n if (o.expires) parts.push(`Expires=${o.expires.toUTCString()}`);\n // Defaulted, because a cookie without one is scoped to the path that set it\n // — a session written by POST /_rsc/action would not be sent for any page.\n parts.push(`Path=${o.path ?? \"/\"}`);\n if (o.domain) parts.push(`Domain=${o.domain}`);\n if (o.sameSite)\n parts.push(`SameSite=${o.sameSite[0].toUpperCase()}${o.sameSite.slice(1)}`);\n if (o.secure) parts.push(\"Secure\");\n if (o.httpOnly) parts.push(\"HttpOnly\");\n if (o.partitioned) parts.push(\"Partitioned\");\n\n return parts.join(\"; \");\n}\n\nexport async function cookies(): Promise<Cookies> {\n // Named before the await, because `headers()` never settles during a build —\n // nothing after this line runs there, and the reason would be recorded as\n // headers() for a call nobody wrote.\n const store = slot();\n\n if (!store.request) recordRead(store, \"cookies()\");\n\n const parsed = parseCookies((await headers()).get(\"cookie\") ?? \"\");\n\n const write = (\n name: string,\n value: string,\n options: CookieOptions = {},\n ): void => {\n // Appended, never set: several cookies on one response are several\n // Set-Cookie headers, and replacing would leave only the last.\n writable(\"cookies().set()\").headers.append(\n \"Set-Cookie\",\n serializeCookie({ name, value, options }),\n );\n };\n\n return {\n get: (name) => parsed[name],\n has: (name) => name in parsed,\n getAll: () => ({ ...parsed }),\n set: write,\n // Expired rather than removed: a browser drops a cookie when it is told\n // one has already passed, and there is no other way to say it.\n delete: (name, options = {}) => write(name, \"\", { ...options, maxAge: 0 }),\n };\n}\n\n/**\n * The whole request, for a host-specific need the accessors do not cover.\n *\n * Null on a host that forwards only the parts — the worker behind Laravel has\n * a socket, not a request. Use headers() and cookies(), which work everywhere.\n */\nexport async function request(): Promise<Request | null> {\n const store = slot();\n\n return store.request ? store.original : never(\"request()\");\n}\n\n/**\n * Mark everything below as belonging to the request, not to the build.\n *\n * export default async function Orders() {\n * await connection()\n *\n * const rows = await db.query('select * from orders')\n *\n * return <ul>{rows.map(...)}</ul>\n * }\n *\n * At build time this never resolves, so nothing after it runs: the query is not\n * made, the boundary above becomes a hole, and the rest of the page still\n * freezes. At request time it resolves immediately and the component runs\n * normally.\n *\n * **Once is enough.** It is a barrier, not a wrapper — everything after it in\n * this component belongs to the request, however many calls that is. Repeating\n * it before each query does nothing.\n *\n * It needs a boundary above it. With a <Suspense> or a loading.tsx there is a\n * fallback to store and the page becomes a shell; with neither, nothing can\n * paint and the build refuses the route rather than storing a blank.\n *\n * Reach for it when the build should not run something — a database the build\n * machine cannot see, or a value that must differ per visitor. A query the\n * build CAN run, whose answer is the same for everyone, wants none of this: it\n * should be frozen.\n *\n * The same name and behaviour as Next's `connection()`.\n */\nexport async function connection(): Promise<void> {\n const store = slot();\n\n // No request means a build. Suspend rather than continue, the same way\n // headers() and cookies() do.\n if (!store.request) return never(\"connection()\");\n}\n\n/** The url this request was made to, whichever way the host supplied it. */\nexport async function url(): Promise<string | null> {\n const store = slot();\n\n return store.request ? store.url : never(\"url()\");\n}\n\nfunction parseCookies(header: string): Record<string, string> {\n const out: Record<string, string> = {};\n\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n\n if (eq === -1) continue;\n\n const name = part.slice(0, eq).trim();\n\n if (!name) continue;\n\n // Decoded because that is how they were written. A malformed escape is\n // left as it arrived rather than throwing the render away.\n const raw = part.slice(eq + 1).trim();\n\n try {\n out[name] = decodeURIComponent(raw);\n } catch {\n out[name] = raw;\n }\n }\n\n return out;\n}\n\n/**\n * Run one request with its headers readable.\n *\n * `null` is the build: a scope with nothing in it, so a page that reads is\n * caught rather than silently frozen holding whatever the machine that built\n * it happened to send.\n */\nexport async function withRequest<T>(\n from: RequestLike,\n run: () => Promise<T>,\n): Promise<T> {\n if (!globals[SCOPE]) {\n ready ??= resolveScope().then((resolved) => {\n globals[SCOPE] ??= resolved as unknown as Scope;\n });\n\n await ready;\n }\n\n const isRequest = from instanceof Request;\n const store: Slot = {\n request: from !== null,\n url: from ? (isRequest ? from.url : from.url) : null,\n headers: from\n ? isRequest\n ? from.headers\n : new Headers(from.headers)\n : new Headers(),\n original: isRequest ? from : null,\n read: false,\n readBy: [],\n readWhere: [],\n fallbacks: [],\n awaiters: new Map(),\n inHelper: null,\n readVia: new Map(),\n };\n\n return await scope()!.run(store, run);\n}\n\n/**\n * A promise that never settles, so the caller suspends.\n *\n * What a read does during a build. React treats it exactly as it treats a host\n * call that never answers: the component suspends, its Suspense fallback goes\n * into the shell, and the probe's budget decides the rest.\n */\n/**\n * Record a read without suspending on it.\n *\n * For a reader that CAN answer during a build but whose answer would be wrong\n * to store — an api route's query string, which exists and is empty, and which\n * the build has no business freezing an answer to. `never()` is for a reader\n * with nothing to return; this is for one that has something and should still\n * be noticed.\n *\n * A no-op outside a render scope, so a handler called at request time pays a\n * property read and nothing else.\n */\nexport function noteRequestRead(by: string): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n recordRead(store, by);\n}\n\nfunction never(by: string): Promise<never> {\n const store = slot();\n\n store.read = true;\n recordRead(store, by);\n\n return new Promise(() => {});\n}\n\n/**\n * Whether anything read the request during the scope that is open.\n *\n * For the prerenderer, which opens one with no request and asks afterwards.\n */\nexport function requestWasRead(): boolean {\n return scope()?.getStore()?.read ?? false;\n}\n\n/**\n * What reached for the request during the scope that is open.\n *\n * For the build, which asks afterwards so it can say why a page is rendered per\n * visitor rather than only that it is.\n */\nexport function requestReadBy(): string[] {\n return scope()?.getStore()?.readBy ?? [];\n}\n\n/** A read React caught at a boundary during SSR: `useSearchParams() in Query`. */\nexport function noteFallback(text: string): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n store.fallbacks ??= [];\n\n if (!store.fallbacks.includes(text)) store.fallbacks.push(text);\n}\n\n/** The reads caught at a boundary during this render, with their components. */\nexport function requestFallbacks(): string[] {\n return scope()?.getStore()?.fallbacks ?? [];\n}\n\n/**\n * A component called a cache()-wrapped helper. Recorded on every call, hit\n * or miss, so a read the helper makes can name everyone who waited for it.\n */\nexport function noteAwaiter(helper: unknown): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n const { name } = caller(\"cache\");\n\n if (!name) return;\n\n store.awaiters ??= new Map();\n\n const list = store.awaiters.get(helper) ?? [];\n\n if (!list.includes(name)) list.push(name);\n\n store.awaiters.set(helper, list);\n}\n\n/** Run a cache()-wrapped helper's body, so a read inside it is filed under the helper. */\nexport function withHelper<T>(helper: unknown, run: () => T): T {\n const store = scope()?.getStore();\n\n if (!store) return run();\n\n const before = store.inHelper;\n\n store.inHelper = helper;\n\n try {\n return run();\n } finally {\n store.inHelper = before;\n }\n}\n\n/**\n * The same reads, each with the component that made it: `cookies() in\n * RootLayout`. A read inside a cached helper with more than one awaiter\n * names them all - `connection() awaited by AuthLinks, AuthDialogSlot` -\n * because the stack saw only the first, and the first is rarely the one\n * that blocks.\n */\nexport function requestReadWhere(): string[] {\n const store = scope()?.getStore();\n\n if (!store?.readWhere?.length) return store?.readBy ?? [];\n\n return store.readWhere.map((entry) => {\n const helper = store.readVia?.get(entry);\n const awaiters = helper ? store.awaiters?.get(helper) : undefined;\n\n if (!awaiters || awaiters.length < 2) return entry;\n\n const names =\n awaiters.length === 2\n ? awaiters.join(\" and \")\n : awaiters.slice(0, -1).join(\", \") + \" and \" + awaiters.at(-1);\n\n return `${entry.split(\" in \")[0]} awaited by ${names}`;\n });\n}\n\n/**\n * The query string, as a page receives it.\n *\n * Derived from the request rather than passed down the render, so no host has\n * to forward it separately — and so it suspends during a build for the same\n * reason every other read does. A frozen page cannot know the query it will be\n * asked for.\n */\nexport async function searchParams(): Promise<URLSearchParams> {\n // Named before the await, so the build reports the call someone wrote rather\n // than url(), which this happens to be built on.\n const store = slot();\n\n if (!store.request && !store.readBy.includes(\"searchParams()\")) {\n store.readBy.push(\"searchParams()\");\n }\n\n const from = await url();\n\n return from ? new URL(from).searchParams : new URLSearchParams();\n}\n"]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K,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAElE,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QAEnD,MAAM,KAAK,GACT,QAAQ,CAAC,MAAM,KAAK,CAAC;YACnB,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC;YACxB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAEnE,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,eAAe,KAAK,EAAE,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY;IAChC,6EAA6E;IAC7E,iDAAiD;IACjD,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;IAErB,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC;QAC/D,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,GAAG,EAAE,CAAC;IAEzB,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,eAAe,EAAE,CAAC;AACnE,CAAC","sourcesContent":["// Reading the request from inside a render.\n//\n// import { headers, cookies } from '@rsc-kit/core/request'\n//\n// export default async function middleware() {\n// const locale = cookies().get('locale')?.value ?? negotiate(headers().get('accept-language'))\n// if (!locale) redirect('/en')\n// }\n//\n// Server components have no arguments beyond their props, and middleware has\n// none at all, so without this an app on a JavaScript host cannot see a header\n// — no locale negotiation, no subdomain, no cookie. The Laravel host escaped\n// that through rpc(), because PHP has the request; this is the same thing for\n// everyone else.\n//\n// Read-only on purpose. Setting a cookie means writing a response header, and\n// by the time a component renders the shell may already have been flushed — an\n// API that appears to set one and silently does not is worse than not having\n// it. Set them in the host, which owns the response.\n//\n// Asynchronous on purpose too, and not for ergonomics. A build has no request,\n// so a read there suspends and never settles — which is the same thing the\n// prerender probe does to a host call. Anything still waiting when the probe's\n// budget expires becomes a fallback in the frozen shell, so a read inside a\n// Suspense boundary leaves the shell frozen and makes only that boundary\n// dynamic. Reading synchronously could only mark the whole route dynamic,\n// because there would be nothing to suspend on.\n//\n// Scoped to the request, on the same store cache() uses. Two requests in\n// flight cannot see each other's headers.\n\nimport { resolveScope } from \"./revalidate.js\";\n\n/** What a host can supply: a real Request, or the parts of one. */\nexport type RequestLike =\n Request | { url: string; headers: Record<string, string> } | null;\n\ninterface Slot {\n /** False during a build: there is nothing to answer with. */\n request: boolean;\n url: string | null;\n /**\n * Held as Headers rather than as a Request.\n *\n * `new Request(url, { headers })` drops Cookie: a spec-compliant Headers\n * built with the \"request\" guard refuses the forbidden header names, and\n * Cookie is one of them. `new Headers()` has no guard and keeps it. Bun\n * happens to allow both, which is why rebuilding a Request looked fine until\n * it ran anywhere stricter — and what it loses is every cookie, silently.\n */\n headers: Headers;\n original: Request | null;\n /**\n * Whether anything asked. Only for the build's report — the classification\n * comes from the suspension, not from this.\n */\n read: boolean;\n /**\n * What read it, in the order they did.\n *\n * Only the name of the accessor — `cookies()`, `headers()` — which is enough\n * for the build to say why a page could not be frozen. Without it the answer\n * is \"something in this page reached for the request\", and finding which is\n * the part that takes an afternoon.\n */\n readBy: string[];\n /**\n * The same reads with the component that made each one - `cookies() in\n * RootLayout` - taken from the stack at the moment of the read, which is\n * still the component's own call: an accessor runs synchronously up to\n * the point it suspends. Only the build reads this. \"Reads the request\" is\n * a category; this is the line to open.\n */\n readWhere: string[];\n /**\n * Reads the server could not answer and React caught at a boundary - the\n * fallback is what got stored - with the component that made each:\n * `useSearchParams() in Query`. Noted by the SSR entry, read by the build,\n * which attaches them to the route so a page stored as its own loading\n * screen says why.\n */\n fallbacks: string[];\n /**\n * For a read made inside a cache()-wrapped helper: the components that\n * awaited that helper, first caller included. The helper runs once, so\n * the stack at the read names only whoever got there first; every later\n * awaiter is a cache hit that never reaches the accessor. The one above\n * every boundary is usually one of the later ones.\n */\n awaiters: Map<unknown, string[]>;\n /** The cache()-wrapped helper whose body is running, while it runs. */\n inHelper: unknown;\n /** readWhere entry -> the helper it was read inside. */\n readVia: Map<string, unknown>;\n /** Work to run once the answer is on its way - see after(). */\n after: (() => unknown)[];\n}\n\nconst SCOPE = Symbol.for(\"@rsc-kit/core.request-scope\");\n\n/**\n * The accessors themselves and the plumbing under them: frames to walk past\n * on the way to the component that called.\n */\nconst NOT_A_CALLER = new Set([\n \"never\",\n \"cache\",\n \"noteAwaiter\",\n \"withHelper\",\n \"noteRequestRead\",\n \"recordRead\",\n \"caller\",\n \"slot\",\n \"cookies\",\n \"headers\",\n \"connection\",\n \"searchParams\",\n \"request\",\n \"url\",\n \"parseParams\",\n \"parseSearchParams\",\n \"parseBody\",\n \"get\",\n \"set\",\n \"has\",\n]);\n\n/** The accessors a component calls by name. One calling another is plumbing, not a second read. */\nconst ACCESSORS = new Set([\n \"cookies\",\n \"headers\",\n \"connection\",\n \"searchParams\",\n \"request\",\n \"url\",\n]);\n\n/**\n * The nearest named function above the accessor on the stack, and whether\n * another accessor sits between: `cookies()` reads through `headers()`, and\n * that inner read is not a second thing the component did.\n *\n * Read from a thrown-away Error: the one thing a build cannot otherwise learn\n * is which component reached for the request, and the stack knows. Function\n * names survive a server bundle, which is not minified, so this is\n * `RootLayout` and not a line number in a chunk. Internal names are walked\n * past; an anonymous frame is skipped rather than reported as `<anonymous>`.\n */\nfunction caller(own: string): { name: string | null; nested: boolean } {\n const stack = new Error().stack ?? \"\";\n let accessors = 0;\n let helper: string | null = null;\n\n for (const line of stack.split(\"\\n\")) {\n const match = /^\\s*at (?:async )?([^\\s(]+)/.exec(line);\n\n if (!match) continue;\n\n const name = match[1]!.split(\".\").pop()!;\n\n // A frame with no function name prints its location instead - `js:6054:8`\n // - which is not a name to report.\n if (!/^[\\w$]+$/.test(name)) continue;\n\n if (ACCESSORS.has(name)) accessors++;\n if (\n NOT_A_CALLER.has(name) ||\n name === \"<anonymous>\" ||\n name === \"Object\" ||\n name === \"Promise\"\n )\n continue;\n\n const nested = accessors > (ACCESSORS.has(own) ? 1 : 0);\n\n // A function that is not a component - getCurrentUser, wrapped in\n // cache() - is the shared helper the read lives in. Named, because with\n // cache() the read runs once, on whichever component called first, and\n // every other caller of the helper is invisible to the stack. The helper\n // is what they have in common.\n if (/^[a-z_$]/.test(name) && !/^use[A-Z]/.test(name)) {\n helper ??= name;\n\n continue;\n }\n\n return {\n name: helper && helper !== name ? `${helper} (from ${name})` : name,\n nested,\n };\n }\n\n return { name: helper, nested: accessors > (ACCESSORS.has(own) ? 1 : 0) };\n}\n\nfunction recordRead(store: Slot, by: string): void {\n if (!store.readBy.includes(by)) store.readBy.push(by);\n\n // Older stores, written by a bundle built before this field existed.\n store.readWhere ??= [];\n\n const { name, nested } = caller(by.replace(/\\(.*$/, \"\"));\n\n if (nested) return;\n\n const entry = name ? `${by} in ${name}` : by;\n\n if (!store.readWhere.includes(entry)) store.readWhere.push(entry);\n if (store.inHelper) (store.readVia ??= new Map()).set(entry, store.inHelper);\n}\n\nconst globals = globalThis as Record<symbol | string, unknown>;\n\nlet ready: Promise<void> | null = null;\n\ninterface Scope {\n getStore(): Slot | undefined;\n run<T>(store: Slot, fn: () => T): T;\n}\n\nfunction scope(): Scope | null {\n return (globals[SCOPE] as Scope | undefined) ?? null;\n}\n\nfunction slot(): Slot {\n const store = scope()?.getStore();\n\n if (!store) {\n throw new Error(\n \"No request in scope. headers() and cookies() are for a render — middleware, a layout, \" +\n \"a page — and there is nothing to read outside one.\",\n );\n }\n\n store.read = true;\n\n return store;\n}\n\n/**\n * The request's headers.\n *\n * Empty during a build, where there is no request: the page is marked as\n * needing one instead, and rendered on demand rather than frozen.\n */\nexport async function headers(): Promise<Headers> {\n const store = slot();\n\n return store.request ? store.headers : never(\"headers()\");\n}\n\n/** How a cookie should be written. The names browsers use. */\nexport interface CookieOptions {\n path?: string;\n domain?: string;\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: \"strict\" | \"lax\" | \"none\";\n partitioned?: boolean;\n}\n\n/** One cookie as the request carried it: the shape Next's `cookies().get()` returns. */\nexport interface RequestCookie {\n name: string;\n value: string;\n}\n\n/**\n * The cookie jar, in the shape Next's `cookies()` has.\n *\n * `get()` returns `{ name, value }` rather than the string, because the guide\n * says \"the same names from `@rsc-kit/core/request`\" and a name that is the\n * same with a different return shape is the worst of both: ported code\n * reading `?.value` off a string got `undefined`, silently. `getAll()` is a\n * list for the same reason, and because a list composes where a record does\n * not.\n */\nexport interface Cookies {\n get(name: string): RequestCookie | undefined;\n has(name: string): boolean;\n getAll(): RequestCookie[];\n /**\n * Write one on the response.\n *\n * Only from a server action, which has a response of its own that has not\n * been sent. A render has already flushed its headers by the time a\n * component runs — that is what makes the first paint fast — so this throws\n * there rather than appearing to work.\n *\n * Either call shape Next takes: `set(name, value, options)` or\n * `set({ name, value, ...options })`.\n */\n set(name: string, value: string, options?: CookieOptions): void;\n set(cookie: RequestCookie & CookieOptions): void;\n /** Write one that expires immediately. Same rule about where. */\n delete(name: string, options?: CookieOptions): void;\n}\n\n/** Kept for the name it had when it could only read. */\nexport type ReadonlyCookies = Cookies;\n\n/**\n * The response being built, while it can still be changed.\n *\n * Open from the moment a request is picked up until the host constructs its\n * Response, and sealed the instant it does. Middleware runs inside that window\n * — before any rendering starts — so a header set there is on the answer. A\n * component runs after it, during streaming, where the status line and headers\n * are already on the wire; setting one there is refused rather than dropped.\n */\ninterface Draft {\n headers: Headers;\n sealed: boolean;\n}\n\nconst DRAFT = Symbol.for(\"@rsc-kit/core.response-draft\");\n\nlet draftReady: Promise<void> | null = null;\n\ninterface DraftScope {\n getStore(): Draft | undefined;\n run<T>(store: Draft, fn: () => T): T;\n}\n\nfunction draft(): DraftScope | null {\n return (globals[DRAFT] as DraftScope | undefined) ?? null;\n}\n\n/** The open draft, or an explanation of why there is not one. */\nfunction writable(what: string): Draft {\n const open = draft()?.getStore();\n\n if (!open) {\n throw new Error(\n `${what} needs a response that has not been sent. Middleware and server actions have one; ` +\n \"a script outside a request does not.\",\n );\n }\n\n if (open.sealed) {\n throw new Error(\n `${what} was called after the response had been sent. Headers go out before the render ` +\n \"starts — that is what makes the first paint fast — so set them in middleware, which \" +\n \"runs before it.\",\n );\n }\n\n return open;\n}\n\n/**\n * Headers to put on the answer.\n *\n * Mutate it as you would any Headers. `append` is the one to reach for when a\n * header may legitimately appear twice; `set` replaces.\n */\n/**\n * The draft's headers, refusing writes once the response has gone.\n *\n * A proxy rather than the Headers itself: returning the live object means code\n * that captured it before the response was built can go on mutating a thing\n * nobody will read. Nothing in this package does that — the host copies the\n * headers onto the response the instant it seals — but \"safe because of the\n * order two other functions happen to run in\" is not a property, and an app\n * holding the object across an await would find writes silently doing nothing.\n */\nfunction sealable(draft: Draft): Headers {\n const guard =\n (method: \"set\" | \"append\" | \"delete\") =>\n (...args: [string, string]) => {\n writable(\"responseHeaders()\");\n\n return (draft.headers[method] as (...a: string[]) => void)(...args);\n };\n\n const proxy: Headers = new Proxy(draft.headers, {\n get(target, property, receiver) {\n if (\n property === \"set\" ||\n property === \"append\" ||\n property === \"delete\"\n ) {\n return guard(property);\n }\n\n // A maplike forEach passes the object it was called on as the third\n // callback argument, and binding to the target makes that the raw\n // Headers — a live, unguarded reference handed out by the very method\n // meant to be read-only. Substituted for the proxy so there is no way\n // through.\n if (property === \"forEach\") {\n return (\n fn: (value: string, key: string, parent: Headers) => void,\n thisArg?: unknown,\n ) =>\n target.forEach((value, key) => fn.call(thisArg, value, key, proxy));\n }\n\n const value = Reflect.get(target, property, receiver);\n\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n\n return proxy;\n}\n\nexport function responseHeaders(): Headers {\n return sealable(writable(\"responseHeaders()\"));\n}\n\n/**\n * Run a request with a response that can still be changed, and take what was\n * put on it.\n *\n * `seal()` is called by the host the moment it builds the Response, so\n * anything set afterwards is refused instead of silently going nowhere.\n */\nexport async function withResponseDraft<T>(\n run: (draft: { taken: () => Headers; seal: () => void }) => Promise<T>,\n): Promise<T> {\n if (!globals[DRAFT]) {\n draftReady ??= resolveScope().then((resolved) => {\n globals[DRAFT] ??= resolved as unknown as DraftScope;\n });\n\n await draftReady;\n }\n\n const open: Draft = { headers: new Headers(), sealed: false };\n\n return await draft()!.run(open, () =>\n run({\n taken: () => open.headers,\n seal: () => {\n open.sealed = true;\n },\n }),\n );\n}\n\n/**\n * A cookie name, as RFC 6265 defines one: a token, so no separators at all.\n *\n * Checked rather than escaped because there is no escaping — a name is not a\n * quoted string. An app that derives one from user input (`pref_${key}`) would\n * otherwise let that input close the pair and open another: a name of\n * `session=attacker; Path=/; HttpOnly; x` serializes to a header whose *first*\n * pair is a session cookie the caller chose, and the browser reads the first.\n */\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/** No separator may appear in an attribute either, for the same reason. */\nconst COOKIE_ATTRIBUTE = /[;,\\r\\n]/;\n\n/** `name=value; Path=/; HttpOnly` — the header a browser expects. */\nexport function serializeCookie(cookie: {\n name: string;\n value: string;\n options: CookieOptions;\n}): string {\n if (!COOKIE_NAME.test(cookie.name)) {\n throw new Error(\n `Not a usable cookie name: ${JSON.stringify(cookie.name)}. ` +\n \"A name is a token — letters, digits and !#$%&'*+-.^_`|~ — with no spaces, \" +\n \"semicolons or equals signs. Nothing escapes them, so one cannot be encoded around.\",\n );\n }\n\n if (cookie.options.sameSite !== undefined) {\n const value = String(cookie.options.sameSite).toLowerCase();\n\n if (value !== \"strict\" && value !== \"lax\" && value !== \"none\") {\n throw new Error(\n `Not a SameSite value: ${JSON.stringify(cookie.options.sameSite)}. ` +\n \"It is written into the header as given, so anything else becomes further attributes.\",\n );\n }\n }\n\n for (const [attribute, value] of [\n [\"path\", cookie.options.path],\n [\"domain\", cookie.options.domain],\n // Trusted because it is typed as a Date — but a cast reaches this, and the\n // result lands in the header verbatim like the others.\n [\"expires\", cookie.options.expires?.toUTCString()],\n ] as const) {\n if (typeof value === \"string\" && COOKIE_ATTRIBUTE.test(value)) {\n throw new Error(\n `The cookie ${attribute} ${JSON.stringify(value)} contains a separator. ` +\n \"It would be read as further attributes rather than as part of this one.\",\n );\n }\n }\n\n const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];\n const o = cookie.options;\n\n if (o.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(o.maxAge)}`);\n if (o.expires) parts.push(`Expires=${o.expires.toUTCString()}`);\n // Defaulted, because a cookie without one is scoped to the path that set it\n // — a session written by POST /_rsc/action would not be sent for any page.\n parts.push(`Path=${o.path ?? \"/\"}`);\n if (o.domain) parts.push(`Domain=${o.domain}`);\n if (o.sameSite)\n parts.push(`SameSite=${o.sameSite[0].toUpperCase()}${o.sameSite.slice(1)}`);\n if (o.secure) parts.push(\"Secure\");\n if (o.httpOnly) parts.push(\"HttpOnly\");\n if (o.partitioned) parts.push(\"Partitioned\");\n\n return parts.join(\"; \");\n}\n\nexport async function cookies(): Promise<Cookies> {\n // Named before the await, because `headers()` never settles during a build —\n // nothing after this line runs there, and the reason would be recorded as\n // headers() for a call nobody wrote.\n const store = slot();\n\n if (!store.request) recordRead(store, \"cookies()\");\n\n const parsed = parseCookies((await headers()).get(\"cookie\") ?? \"\");\n\n const write = (\n name: string,\n value: string,\n options: CookieOptions = {},\n ): void => {\n // Appended, never set: several cookies on one response are several\n // Set-Cookie headers, and replacing would leave only the last.\n writable(\"cookies().set()\").headers.append(\n \"Set-Cookie\",\n serializeCookie({ name, value, options }),\n );\n };\n\n return {\n get: (name) => (name in parsed ? { name, value: parsed[name] } : undefined),\n has: (name) => name in parsed,\n getAll: () => Object.entries(parsed).map(([name, value]) => ({ name, value })),\n set: (nameOrCookie: string | (RequestCookie & CookieOptions), value?: string, options?: CookieOptions) => {\n if (typeof nameOrCookie === \"string\") return write(nameOrCookie, value ?? \"\", options);\n\n const { name, value: v, ...rest } = nameOrCookie;\n\n return write(name, v, rest);\n },\n // Expired rather than removed: a browser drops a cookie when it is told\n // one has already passed, and there is no other way to say it.\n delete: (name, options = {}) => write(name, \"\", { ...options, maxAge: 0 }),\n };\n}\n\n/**\n * The whole request, for a host-specific need the accessors do not cover.\n *\n * Null on a host that forwards only the parts — the worker behind Laravel has\n * a socket, not a request. Use headers() and cookies(), which work everywhere.\n */\nexport async function request(): Promise<Request | null> {\n const store = slot();\n\n return store.request ? store.original : never(\"request()\");\n}\n\n/**\n * Mark everything below as belonging to the request, not to the build.\n *\n * export default async function Orders() {\n * await connection()\n *\n * const rows = await db.query('select * from orders')\n *\n * return <ul>{rows.map(...)}</ul>\n * }\n *\n * At build time this never resolves, so nothing after it runs: the query is not\n * made, the boundary above becomes a hole, and the rest of the page still\n * freezes. At request time it resolves immediately and the component runs\n * normally.\n *\n * **Once is enough.** It is a barrier, not a wrapper — everything after it in\n * this component belongs to the request, however many calls that is. Repeating\n * it before each query does nothing.\n *\n * It needs a boundary above it. With a <Suspense> or a loading.tsx there is a\n * fallback to store and the page becomes a shell; with neither, nothing can\n * paint and the build refuses the route rather than storing a blank.\n *\n * Reach for it when the build should not run something — a database the build\n * machine cannot see, or a value that must differ per visitor. A query the\n * build CAN run, whose answer is the same for everyone, wants none of this: it\n * should be frozen.\n *\n * The same name and behaviour as Next's `connection()`.\n */\nexport async function connection(): Promise<void> {\n const store = slot();\n\n // No request means a build. Suspend rather than continue, the same way\n // headers() and cookies() do.\n if (!store.request) return never(\"connection()\");\n}\n\n/** The url this request was made to, whichever way the host supplied it. */\nexport async function url(): Promise<string | null> {\n const store = slot();\n\n return store.request ? store.url : never(\"url()\");\n}\n\nfunction parseCookies(header: string): Record<string, string> {\n const out: Record<string, string> = {};\n\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n\n if (eq === -1) continue;\n\n const name = part.slice(0, eq).trim();\n\n if (!name) continue;\n\n // Decoded because that is how they were written. A malformed escape is\n // left as it arrived rather than throwing the render away.\n const raw = part.slice(eq + 1).trim();\n\n try {\n out[name] = decodeURIComponent(raw);\n } catch {\n out[name] = raw;\n }\n }\n\n return out;\n}\n\n/**\n * Run one request with its headers readable.\n *\n * `null` is the build: a scope with nothing in it, so a page that reads is\n * caught rather than silently frozen holding whatever the machine that built\n * it happened to send.\n */\nexport async function withRequest<T>(\n from: RequestLike,\n run: () => Promise<T>,\n): Promise<T> {\n if (!globals[SCOPE]) {\n ready ??= resolveScope().then((resolved) => {\n globals[SCOPE] ??= resolved as unknown as Scope;\n });\n\n await ready;\n }\n\n const isRequest = from instanceof Request;\n const store: Slot = {\n request: from !== null,\n url: from ? (isRequest ? from.url : from.url) : null,\n headers: from\n ? isRequest\n ? from.headers\n : new Headers(from.headers)\n : new Headers(),\n original: isRequest ? from : null,\n read: false,\n readBy: [],\n readWhere: [],\n fallbacks: [],\n awaiters: new Map(),\n inHelper: null,\n readVia: new Map(),\n after: [],\n };\n\n return await scope()!.run(store, run);\n}\n\n/**\n * A promise that never settles, so the caller suspends.\n *\n * What a read does during a build. React treats it exactly as it treats a host\n * call that never answers: the component suspends, its Suspense fallback goes\n * into the shell, and the probe's budget decides the rest.\n */\n/**\n * The build's probe hands a route a Request that records what is read out of\n * it, and a read of `url` marks the route as depending on the caller — the\n * Next way to read a query is `new URL(request.url).searchParams`, which the\n * probe cannot otherwise see. The engine itself reads the url to resolve the\n * awaited `searchParams`, and that read is accounted for by `searchParams`,\n * not by `url`; this is the door it goes through. A probe answers the real\n * Request to this key; anything else answers nothing, and the request is its\n * own.\n */\nexport const UNPROBED = Symbol.for(\"rsc-kit.unprobed\");\n\n/** The request's url, read by the engine rather than the route. */\nexport function urlOf(request: Request): string {\n return ((request as unknown as Record<symbol, Request | undefined>)[UNPROBED] ?? request).url;\n}\n\n/**\n * Record a read without suspending on it.\n *\n * For a reader that CAN answer during a build but whose answer would be wrong\n * to store — an api route's query string, which exists and is empty, and which\n * the build has no business freezing an answer to. `never()` is for a reader\n * with nothing to return; this is for one that has something and should still\n * be noticed.\n *\n * A no-op outside a render scope, so a handler called at request time pays a\n * property read and nothing else.\n */\nexport function noteRequestRead(by: string): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n recordRead(store, by);\n}\n\nfunction never(by: string): Promise<never> {\n const store = slot();\n\n store.read = true;\n recordRead(store, by);\n\n return new Promise(() => {});\n}\n\n/**\n * Whether anything read the request during the scope that is open.\n *\n * For the prerenderer, which opens one with no request and asks afterwards.\n */\nexport function requestWasRead(): boolean {\n return scope()?.getStore()?.read ?? false;\n}\n\n/**\n * What reached for the request during the scope that is open.\n *\n * For the build, which asks afterwards so it can say why a page is rendered per\n * visitor rather than only that it is.\n */\nexport function requestReadBy(): string[] {\n return scope()?.getStore()?.readBy ?? [];\n}\n\n/** A read React caught at a boundary during SSR: `useSearchParams() in Query`. */\nexport function noteFallback(text: string): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n store.fallbacks ??= [];\n\n if (!store.fallbacks.includes(text)) store.fallbacks.push(text);\n}\n\n/**\n * Run something once the answer is on its way, without making it wait.\n *\n * Logging, an audit row, an email, a cache warm: work the visitor should not\n * pay for, and that must still finish. Next's `after()`, and needed for the\n * same reason on every host: on a long-lived process a detached promise\n * happens to run to completion, but a Worker tears the isolate down when the\n * response ends unless the work is registered with the platform's\n * `waitUntil` - so a fire-and-forget promise there dies silently, some of\n * the time. The host hands these to `waitUntil` where one exists and runs\n * them detached where a process will keep them.\n *\n * From a component, a middleware, a server action or an api route. A\n * rejection is reported and never reaches the response, which has already\n * gone. Outside a request - a build - the work runs at once.\n */\nexport function after(work: () => unknown): void {\n const store = scope()?.getStore();\n\n if (!store || !store.request) {\n void Promise.resolve().then(work).catch(reportAfter);\n\n return;\n }\n\n store.after.push(work);\n}\n\nfunction reportAfter(error: unknown): void {\n console.error(\"[rsc-kit] after() work failed:\", error);\n}\n\n/**\n * @internal For the host: the work `after()` collected for this request, as\n * one promise that never rejects. Taken once; a second call has nothing.\n */\nexport function takeAfterWork(): Promise<void> | null {\n const store = scope()?.getStore();\n\n if (!store || store.after.length === 0) return null;\n\n const work = store.after.splice(0);\n\n return Promise.allSettled(\n work.map((run) => Promise.resolve().then(run)),\n ).then((results) => {\n for (const result of results) {\n if (result.status === \"rejected\") reportAfter(result.reason);\n }\n });\n}\n\n/** The reads caught at a boundary during this render, with their components. */\nexport function requestFallbacks(): string[] {\n return scope()?.getStore()?.fallbacks ?? [];\n}\n\n/**\n * A component called a cache()-wrapped helper. Recorded on every call, hit\n * or miss, so a read the helper makes can name everyone who waited for it.\n */\nexport function noteAwaiter(helper: unknown): void {\n const store = scope()?.getStore();\n\n if (!store) return;\n\n const { name } = caller(\"cache\");\n\n if (!name) return;\n\n store.awaiters ??= new Map();\n\n const list = store.awaiters.get(helper) ?? [];\n\n if (!list.includes(name)) list.push(name);\n\n store.awaiters.set(helper, list);\n}\n\n/** Run a cache()-wrapped helper's body, so a read inside it is filed under the helper. */\nexport function withHelper<T>(helper: unknown, run: () => T): T {\n const store = scope()?.getStore();\n\n if (!store) return run();\n\n const before = store.inHelper;\n\n store.inHelper = helper;\n\n try {\n return run();\n } finally {\n store.inHelper = before;\n }\n}\n\n/**\n * The same reads, each with the component that made it: `cookies() in\n * RootLayout`. A read inside a cached helper with more than one awaiter\n * names them all - `connection() awaited by AuthLinks, AuthDialogSlot` -\n * because the stack saw only the first, and the first is rarely the one\n * that blocks.\n */\nexport function requestReadWhere(): string[] {\n const store = scope()?.getStore();\n\n if (!store?.readWhere?.length) return store?.readBy ?? [];\n\n return store.readWhere.map((entry) => {\n const helper = store.readVia?.get(entry);\n const awaiters = helper ? store.awaiters?.get(helper) : undefined;\n\n if (!awaiters || awaiters.length < 2) return entry;\n\n const names =\n awaiters.length === 2\n ? awaiters.join(\" and \")\n : awaiters.slice(0, -1).join(\", \") + \" and \" + awaiters.at(-1);\n\n return `${entry.split(\" in \")[0]} awaited by ${names}`;\n });\n}\n\n/**\n * The query string, as a page receives it.\n *\n * Derived from the request rather than passed down the render, so no host has\n * to forward it separately — and so it suspends during a build for the same\n * reason every other read does. A frozen page cannot know the query it will be\n * asked for.\n */\nexport async function searchParams(): Promise<URLSearchParams> {\n // Named before the await, so the build reports the call someone wrote rather\n // than url(), which this happens to be built on.\n const store = slot();\n\n if (!store.request && !store.readBy.includes(\"searchParams()\")) {\n store.readBy.push(\"searchParams()\");\n }\n\n const from = await url();\n\n return from ? new URL(from).searchParams : new URLSearchParams();\n}\n"]}
|
package/dist/routes.d.ts
CHANGED
|
@@ -30,9 +30,20 @@ type OffRoute = `${string}://${string}` | `mailto:${string}` | `tel:${string}` |
|
|
|
30
30
|
* A url this app can answer, or one that deliberately leaves it.
|
|
31
31
|
*
|
|
32
32
|
* Cast when the destination is computed rather than written:
|
|
33
|
-
* `href={path as
|
|
33
|
+
* `href={path as Route}`.
|
|
34
34
|
*/
|
|
35
|
-
|
|
35
|
+
/**
|
|
36
|
+
* A url this app answers - a page or a route.ts - or one that deliberately
|
|
37
|
+
* leaves it. One type, as Next's `Route` is one type: what `<Link href>`,
|
|
38
|
+
* `visit()` and `redirect()` take. A route.ts is a full navigation rather
|
|
39
|
+
* than a payload fetch, and never prefetched - the client knows which urls
|
|
40
|
+
* are routes and treats a link to one as the anchor it is - so the type
|
|
41
|
+
* does not have to keep them apart to keep a hover from running one.
|
|
42
|
+
*
|
|
43
|
+
* `Route` is the same type under the name Next uses, so a port keeps the
|
|
44
|
+
* word it already has.
|
|
45
|
+
*/
|
|
46
|
+
export type Route = Unregistered extends true ? string : Filled<RoutePattern> | `${Filled<RoutePattern>}?${string}` | `${Filled<RoutePattern>}#${string}` | Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}` | OffRoute;
|
|
36
47
|
/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */
|
|
37
48
|
export interface RegisterApi {
|
|
38
49
|
}
|
|
@@ -60,7 +71,7 @@ type NoApis = string extends ApiPattern ? true : false;
|
|
|
60
71
|
* `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed
|
|
61
72
|
* because that is how a GET is parameterised.
|
|
62
73
|
*/
|
|
63
|
-
export type
|
|
74
|
+
export type ApiRoute = NoApis extends true ? string : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;
|
|
64
75
|
/**
|
|
65
76
|
* An api url, checked against the routes the build found.
|
|
66
77
|
*
|
|
@@ -73,7 +84,7 @@ export type ApiHref = NoApis extends true ? string : Filled<ApiPattern> | `${Fil
|
|
|
73
84
|
* Wrong path, and it stops compiling. Renamed the directory, and every call
|
|
74
85
|
* site says so rather than one of them 404ing in production.
|
|
75
86
|
*/
|
|
76
|
-
export declare function apiUrl(href:
|
|
87
|
+
export declare function apiUrl(href: ApiRoute): string;
|
|
77
88
|
/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */
|
|
78
89
|
export type SearchExportOf<M> = M extends {
|
|
79
90
|
searchParams: infer S;
|
|
@@ -126,7 +137,7 @@ export type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;
|
|
|
126
137
|
* The search params a link to `H` may carry.
|
|
127
138
|
*
|
|
128
139
|
* The page's schema input when `H` is one declared route with a schema;
|
|
129
|
-
* otherwise anything. "One route" matters: `path as
|
|
140
|
+
* otherwise anything. "One route" matters: `path as Route` is every route at
|
|
130
141
|
* once, and a link that could go anywhere cannot be held to one page's schema.
|
|
131
142
|
*/
|
|
132
143
|
export type SearchFor<H extends string> = Unregistered extends true ? LooseSearch : IsUnion<H> extends true ? LooseSearch : [PatternOf<H>] extends [never] ? LooseSearch : SchemaFor<PatternOf<H>> extends undefined ? LooseSearch : LinkInputOf<SchemaFor<PatternOf<H>>>;
|
|
@@ -152,5 +163,5 @@ export declare function withSearch(path: string, search: object | undefined): st
|
|
|
152
163
|
* `Link` has the same check on its own `search` prop. This is for `visit`,
|
|
153
164
|
* `prefetch`, `redirect` and anything else that wants the finished string.
|
|
154
165
|
*/
|
|
155
|
-
export declare function href<H extends
|
|
166
|
+
export declare function href<H extends Route>(path: H, ...rest: {} extends SearchFor<H> ? [search?: SearchFor<H>] : [search: SearchFor<H>]): Route;
|
|
156
167
|
export {};
|
package/dist/routes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,kBAAkB;AA+GlB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,MAAM,CAAC,IAAa;IAClC,OAAO,IAAI,CAAC;AACd,CAAC;AA0GD,uGAAuG;AACvG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IAErC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QAEpD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,MAAM,IA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C,IAAI,CAAC,GAAG,CAAC,CAAC;IAE1D,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;AAC9D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAClB,IAAO,EACP,GAAG,IAEuB;IAE1B,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAuB,CAAS,CAAC;AACjE,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Href}`.\n */\nexport type Href = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | OffRoute;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Href, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiHref = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiHref): string {\n return href;\n}\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Href` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Href>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Href {\n return withSearch(path, rest[0] as object | undefined) as Href;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,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AAM,CAAC,CAAC;IAC5D,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;IAChE,MAAM,QAAQ,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;IACjE,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE1D,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;AAC9D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAClB,IAAO,EACP,GAAG,IAEuB;IAE1B,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAuB,CAAU,CAAC;AAClE,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | OffRoute;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n"]}
|
package/dist/testing.d.ts
CHANGED
|
@@ -19,6 +19,20 @@ export interface TestAppOptions {
|
|
|
19
19
|
/** The origin requests are made against. Nothing reads it; it is a url. */
|
|
20
20
|
origin?: string;
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* A file the build put in .output/public, answered the way Nitro's static
|
|
24
|
+
* layer would - which the handler this harness loads does not include. The
|
|
25
|
+
* handler is the rsc service: routing, pages, actions, api routes. Assets,
|
|
26
|
+
* the service worker, the manifest and the icons are files Nitro serves in
|
|
27
|
+
* production from .output/public, and a test that asked for /sw.js used to
|
|
28
|
+
* get the router's 404 for a file the deployment serves fine - the one
|
|
29
|
+
* shape this harness exists to catch, in the other direction.
|
|
30
|
+
*
|
|
31
|
+
* Files only, for GET and HEAD, within the directory: a path that escapes it
|
|
32
|
+
* is a request for the handler, not a file.
|
|
33
|
+
*/
|
|
34
|
+
/** @internal Exported for its test. */
|
|
35
|
+
export declare function staticFile(root: string, request: Request): Response | null;
|
|
22
36
|
/**
|
|
23
37
|
* How this project builds: its own `build` script, run by the package manager
|
|
24
38
|
* this test is running under. Without a script, Vite directly - on Bun's
|
package/dist/testing.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
// where a route that renders fine and is served wrong shows up.
|
|
18
18
|
import { spawnSync } from 'node:child_process';
|
|
19
19
|
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
20
|
-
import { join, resolve } from 'node:path';
|
|
20
|
+
import { extname, join, resolve, sep } from 'node:path';
|
|
21
21
|
import { pathToFileURL } from 'node:url';
|
|
22
22
|
/**
|
|
23
23
|
* Where the build put the server bundle.
|
|
@@ -51,6 +51,57 @@ function newest(dir) {
|
|
|
51
51
|
}
|
|
52
52
|
/** One build per process per root, however many test files ask. */
|
|
53
53
|
const built = new Map();
|
|
54
|
+
/** The content types a test is likely to assert on; anything else is octet-stream. */
|
|
55
|
+
const CONTENT_TYPES = {
|
|
56
|
+
'.html': 'text/html; charset=utf-8',
|
|
57
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
58
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
59
|
+
'.css': 'text/css; charset=utf-8',
|
|
60
|
+
'.json': 'application/json; charset=utf-8',
|
|
61
|
+
'.webmanifest': 'application/manifest+json',
|
|
62
|
+
'.xml': 'application/xml',
|
|
63
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
64
|
+
'.svg': 'image/svg+xml',
|
|
65
|
+
'.png': 'image/png',
|
|
66
|
+
'.jpg': 'image/jpeg',
|
|
67
|
+
'.jpeg': 'image/jpeg',
|
|
68
|
+
'.webp': 'image/webp',
|
|
69
|
+
'.avif': 'image/avif',
|
|
70
|
+
'.gif': 'image/gif',
|
|
71
|
+
'.ico': 'image/x-icon',
|
|
72
|
+
'.woff': 'font/woff',
|
|
73
|
+
'.woff2': 'font/woff2',
|
|
74
|
+
'.wasm': 'application/wasm',
|
|
75
|
+
'.map': 'application/json',
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* A file the build put in .output/public, answered the way Nitro's static
|
|
79
|
+
* layer would - which the handler this harness loads does not include. The
|
|
80
|
+
* handler is the rsc service: routing, pages, actions, api routes. Assets,
|
|
81
|
+
* the service worker, the manifest and the icons are files Nitro serves in
|
|
82
|
+
* production from .output/public, and a test that asked for /sw.js used to
|
|
83
|
+
* get the router's 404 for a file the deployment serves fine - the one
|
|
84
|
+
* shape this harness exists to catch, in the other direction.
|
|
85
|
+
*
|
|
86
|
+
* Files only, for GET and HEAD, within the directory: a path that escapes it
|
|
87
|
+
* is a request for the handler, not a file.
|
|
88
|
+
*/
|
|
89
|
+
/** @internal Exported for its test. */
|
|
90
|
+
export function staticFile(root, request) {
|
|
91
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
92
|
+
return null;
|
|
93
|
+
const publicDir = join(root, '.output/public');
|
|
94
|
+
const pathname = decodeURIComponent(new URL(request.url).pathname);
|
|
95
|
+
const file = resolve(publicDir, '.' + pathname);
|
|
96
|
+
if (!file.startsWith(publicDir + sep) || !existsSync(file) || !statSync(file).isFile())
|
|
97
|
+
return null;
|
|
98
|
+
const type = CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
99
|
+
const body = request.method === 'HEAD' ? null : readFileSync(file);
|
|
100
|
+
return new Response(body, {
|
|
101
|
+
status: 200,
|
|
102
|
+
headers: { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-RSC-Kit-Test': 'static' },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
54
105
|
/**
|
|
55
106
|
* How this project builds: its own `build` script, run by the package manager
|
|
56
107
|
* this test is running under. Without a script, Vite directly - on Bun's
|
|
@@ -120,7 +171,10 @@ export async function createTestApp(options = {}) {
|
|
|
120
171
|
}
|
|
121
172
|
return {
|
|
122
173
|
bundle,
|
|
123
|
-
fetch: (path, init) =>
|
|
174
|
+
fetch: async (path, init) => {
|
|
175
|
+
const request = new Request(new URL(path, origin), init);
|
|
176
|
+
return staticFile(root, request) ?? entry.default(request);
|
|
177
|
+
},
|
|
124
178
|
};
|
|
125
179
|
}
|
|
126
180
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","source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,KAAK,UAAU,aAAa,CAAC,OAAO,GAAmB,EAAE;IAC9D,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;IACnD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,kBAAkB,CAAA;IAEnD,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAA;IAE5E,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,CAAE,CAAA;IACrC,MAAM,KAAK,GAAG,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAEtD,CAAA;IAED,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,aAAa,MAAM,qCAAqC,CAAC,CAAA;IAC3E,CAAC;IAED,OAAO;QACL,MAAM;QACN,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC;KAC/E,CAAA;AACH,CAAC","sourcesContent":["// The whole app as a function, for tests.\n//\n// import { createTestApp } from '@rsc-kit/core/testing'\n//\n// const app = await createTestApp()\n// const res = await app.fetch('/api/orders', { headers: { Cookie: 'user=ada' } })\n//\n// No port, no browser, no server process. The built entry already exports the\n// same Request → Response handler the dev server and the production server\n// both call, so a test can hand it a Request and read the Response — through\n// the real router, the real middleware, the real api routes, and the pages the\n// build stored.\n//\n// That is the tier between a unit test and a browser. An action or a route is\n// a function and can be imported and called; a browser test proves the page\n// works; this proves the app answers a url the way it is deployed, which is\n// where a route that renders fine and is served wrong shows up.\n\nimport { spawnSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nexport interface TestApp {\n /** A path, not a url. The origin is whatever the app was told it is. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n /** Where the build was read from, for a test that wants to look. */\n bundle: string\n}\n\nexport interface TestAppOptions {\n /** The project. Defaults to the working directory. */\n root?: string\n /**\n * Whether to build first.\n *\n * `true` builds when the source is newer than the last build, which is what\n * a test run wants: the first run pays for it, the rest do not, and an edit\n * is picked up. `false` never builds and fails loudly if there is nothing to\n * read — for a ci step that already built.\n */\n build?: boolean\n /** The origin requests are made against. Nothing reads it; it is a url. */\n origin?: string\n}\n\n/**\n * Where the build put the server bundle.\n *\n * Two layouts, because two ways of building. Under Nitro — every scaffolded\n * app — it is inside Nitro's own directory. On its own the plugin writes\n * <outDir>/dist/rsc. The first that exists wins.\n */\nfunction findBundle(root: string): string | null {\n const candidates = [\n join(root, 'node_modules/.nitro/vite/services/rsc/index.js'),\n join(root, '.rsc/dist/rsc/index.js'),\n join(root, 'build/dist/rsc/index.js'),\n ]\n\n return candidates.find((path) => existsSync(path)) ?? null\n}\n\n/** The newest mtime under a directory, for deciding whether a build is stale. */\nfunction newest(dir: string): number {\n if (!existsSync(dir)) return 0\n\n let latest = 0\n\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue\n\n const path = join(dir, entry.name)\n const time = entry.isDirectory() ? newest(path) : statSync(path).mtimeMs\n\n if (time > latest) latest = time\n }\n\n return latest\n}\n\n/** One build per process per root, however many test files ask. */\nconst built = new Map<string, Promise<string>>()\n\n/**\n * How this project builds: its own `build` script, run by the package manager\n * this test is running under. Without a script, Vite directly - on Bun's\n * runtime when the tests are, since a bin's node shebang would otherwise\n * start it under Node.\n */\n/** @internal Exported for its test. */\nexport function buildCommand(root: string): [string, string[]] {\n const onBun = typeof process.versions.bun === 'string'\n\n let scripts: Record<string, string> = {}\n\n try {\n scripts = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')).scripts ?? {}\n } catch {\n // No package.json, or not JSON: there is no script to run.\n }\n\n if (typeof scripts.build === 'string') {\n return onBun ? ['bun', ['run', 'build']] : ['npm', ['run', 'build']]\n }\n\n return onBun ? ['bun', ['--bun', 'vite', 'build']] : ['npx', ['vite', 'build']]\n}\n\nasync function ensureBuilt(root: string, build: boolean): Promise<string> {\n const existing = findBundle(root)\n\n if (!build) {\n if (!existing) {\n throw new Error(\n `[rsc-kit] No build to test against under ${root}. Run the build first, or let createTestApp() do it by leaving \\`build\\` on.`,\n )\n }\n\n return existing\n }\n\n const fresh = existing && statSync(existing).mtimeMs > newest(join(root, 'src'))\n\n if (fresh) return existing\n\n // The user's own build command, so what is tested is what ships. A test\n // that built some other way would pass against a bundle nobody deploys -\n // and used to: this ran `npx vite build` whatever package.json said, which\n // on a Bun project built under Node and failed on the first `import 'bun'`.\n const [command, args] = buildCommand(root)\n const run = spawnSync(command, args, {\n cwd: root,\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, NODE_ENV: 'production' },\n })\n\n if (run.status !== 0) {\n throw new Error(`[rsc-kit] The build failed, so there is nothing to test:\\n${run.stderr}`)\n }\n\n const bundle = findBundle(root)\n\n if (!bundle) {\n throw new Error(\n `[rsc-kit] The build finished but no server bundle was found under ${root}. Is rscKit() in vite.config?`,\n )\n }\n\n return bundle\n}\n\n/**\n * Build the app if it needs it, load it, and hand back something to fetch from.\n *\n * Memoised per root: every test file in a run shares one build and one loaded\n * module, which is both the fast path and the correct one — two copies of the\n * server bundle in one process would be two client-reference registries.\n */\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n const root = resolve(options.root ?? process.cwd())\n const origin = options.origin ?? 'https://app.test'\n\n built.set(root, built.get(root) ?? ensureBuilt(root, options.build ?? true))\n\n const bundle = await built.get(root)!\n const entry = (await import(pathToFileURL(bundle).href)) as {\n default: (request: Request) => Promise<Response>\n }\n\n if (typeof entry.default !== 'function') {\n throw new Error(`[rsc-kit] ${bundle} does not export a request handler.`)\n }\n\n return {\n bundle,\n fetch: (path, init) => entry.default(new Request(new URL(path, origin), init)),\n }\n}\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,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAyBxC;;;;;;GAMG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,UAAU,GAAG;QACjB,IAAI,CAAC,IAAI,EAAE,gDAAgD,CAAC;QAC5D,IAAI,CAAC,IAAI,EAAE,wBAAwB,CAAC;QACpC,IAAI,CAAC,IAAI,EAAE,yBAAyB,CAAC;KACtC,CAAA;IAED,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,CAAA;AAC5D,CAAC;AAED,iFAAiF;AACjF,SAAS,MAAM,CAAC,GAAW;IACzB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,CAAC,CAAA;IAE9B,IAAI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AM,IAAI,KAAK,CAAC,aAAa,MAAM,qCAAqC,CAAC,CAAA;IAC3E,CAAC;IAED,OAAO;QACL,MAAM;QACN,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;YAC1B,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,CAAA;YAExD,OAAO,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QAC5D,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["// The whole app as a function, for tests.\n//\n// import { createTestApp } from '@rsc-kit/core/testing'\n//\n// const app = await createTestApp()\n// const res = await app.fetch('/api/orders', { headers: { Cookie: 'user=ada' } })\n//\n// No port, no browser, no server process. The built entry already exports the\n// same Request → Response handler the dev server and the production server\n// both call, so a test can hand it a Request and read the Response — through\n// the real router, the real middleware, the real api routes, and the pages the\n// build stored.\n//\n// That is the tier between a unit test and a browser. An action or a route is\n// a function and can be imported and called; a browser test proves the page\n// works; this proves the app answers a url the way it is deployed, which is\n// where a route that renders fine and is served wrong shows up.\n\nimport { spawnSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { extname, join, resolve, sep } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nexport interface TestApp {\n /** A path, not a url. The origin is whatever the app was told it is. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n /** Where the build was read from, for a test that wants to look. */\n bundle: string\n}\n\nexport interface TestAppOptions {\n /** The project. Defaults to the working directory. */\n root?: string\n /**\n * Whether to build first.\n *\n * `true` builds when the source is newer than the last build, which is what\n * a test run wants: the first run pays for it, the rest do not, and an edit\n * is picked up. `false` never builds and fails loudly if there is nothing to\n * read — for a ci step that already built.\n */\n build?: boolean\n /** The origin requests are made against. Nothing reads it; it is a url. */\n origin?: string\n}\n\n/**\n * Where the build put the server bundle.\n *\n * Two layouts, because two ways of building. Under Nitro — every scaffolded\n * app — it is inside Nitro's own directory. On its own the plugin writes\n * <outDir>/dist/rsc. The first that exists wins.\n */\nfunction findBundle(root: string): string | null {\n const candidates = [\n join(root, 'node_modules/.nitro/vite/services/rsc/index.js'),\n join(root, '.rsc/dist/rsc/index.js'),\n join(root, 'build/dist/rsc/index.js'),\n ]\n\n return candidates.find((path) => existsSync(path)) ?? null\n}\n\n/** The newest mtime under a directory, for deciding whether a build is stale. */\nfunction newest(dir: string): number {\n if (!existsSync(dir)) return 0\n\n let latest = 0\n\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue\n\n const path = join(dir, entry.name)\n const time = entry.isDirectory() ? newest(path) : statSync(path).mtimeMs\n\n if (time > latest) latest = time\n }\n\n return latest\n}\n\n/** One build per process per root, however many test files ask. */\nconst built = new Map<string, Promise<string>>()\n\n/** The content types a test is likely to assert on; anything else is octet-stream. */\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.webmanifest': 'application/manifest+json',\n '.xml': 'application/xml',\n '.txt': 'text/plain; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.gif': 'image/gif',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.wasm': 'application/wasm',\n '.map': 'application/json',\n}\n\n/**\n * A file the build put in .output/public, answered the way Nitro's static\n * layer would - which the handler this harness loads does not include. The\n * handler is the rsc service: routing, pages, actions, api routes. Assets,\n * the service worker, the manifest and the icons are files Nitro serves in\n * production from .output/public, and a test that asked for /sw.js used to\n * get the router's 404 for a file the deployment serves fine - the one\n * shape this harness exists to catch, in the other direction.\n *\n * Files only, for GET and HEAD, within the directory: a path that escapes it\n * is a request for the handler, not a file.\n */\n/** @internal Exported for its test. */\nexport function staticFile(root: string, request: Request): Response | null {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n\n const publicDir = join(root, '.output/public')\n const pathname = decodeURIComponent(new URL(request.url).pathname)\n const file = resolve(publicDir, '.' + pathname)\n\n if (!file.startsWith(publicDir + sep) || !existsSync(file) || !statSync(file).isFile()) return null\n\n const type = CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream'\n const body = request.method === 'HEAD' ? null : readFileSync(file)\n\n return new Response(body, {\n status: 200,\n headers: { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-RSC-Kit-Test': 'static' },\n })\n}\n\n/**\n * How this project builds: its own `build` script, run by the package manager\n * this test is running under. Without a script, Vite directly - on Bun's\n * runtime when the tests are, since a bin's node shebang would otherwise\n * start it under Node.\n */\n/** @internal Exported for its test. */\nexport function buildCommand(root: string): [string, string[]] {\n const onBun = typeof process.versions.bun === 'string'\n\n let scripts: Record<string, string> = {}\n\n try {\n scripts = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')).scripts ?? {}\n } catch {\n // No package.json, or not JSON: there is no script to run.\n }\n\n if (typeof scripts.build === 'string') {\n return onBun ? ['bun', ['run', 'build']] : ['npm', ['run', 'build']]\n }\n\n return onBun ? ['bun', ['--bun', 'vite', 'build']] : ['npx', ['vite', 'build']]\n}\n\nasync function ensureBuilt(root: string, build: boolean): Promise<string> {\n const existing = findBundle(root)\n\n if (!build) {\n if (!existing) {\n throw new Error(\n `[rsc-kit] No build to test against under ${root}. Run the build first, or let createTestApp() do it by leaving \\`build\\` on.`,\n )\n }\n\n return existing\n }\n\n const fresh = existing && statSync(existing).mtimeMs > newest(join(root, 'src'))\n\n if (fresh) return existing\n\n // The user's own build command, so what is tested is what ships. A test\n // that built some other way would pass against a bundle nobody deploys -\n // and used to: this ran `npx vite build` whatever package.json said, which\n // on a Bun project built under Node and failed on the first `import 'bun'`.\n const [command, args] = buildCommand(root)\n const run = spawnSync(command, args, {\n cwd: root,\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, NODE_ENV: 'production' },\n })\n\n if (run.status !== 0) {\n throw new Error(`[rsc-kit] The build failed, so there is nothing to test:\\n${run.stderr}`)\n }\n\n const bundle = findBundle(root)\n\n if (!bundle) {\n throw new Error(\n `[rsc-kit] The build finished but no server bundle was found under ${root}. Is rscKit() in vite.config?`,\n )\n }\n\n return bundle\n}\n\n/**\n * Build the app if it needs it, load it, and hand back something to fetch from.\n *\n * Memoised per root: every test file in a run shares one build and one loaded\n * module, which is both the fast path and the correct one — two copies of the\n * server bundle in one process would be two client-reference registries.\n */\nexport async function createTestApp(options: TestAppOptions = {}): Promise<TestApp> {\n const root = resolve(options.root ?? process.cwd())\n const origin = options.origin ?? 'https://app.test'\n\n built.set(root, built.get(root) ?? ensureBuilt(root, options.build ?? true))\n\n const bundle = await built.get(root)!\n const entry = (await import(pathToFileURL(bundle).href)) as {\n default: (request: Request) => Promise<Response>\n }\n\n if (typeof entry.default !== 'function') {\n throw new Error(`[rsc-kit] ${bundle} does not export a request handler.`)\n }\n\n return {\n bundle,\n fetch: async (path, init) => {\n const request = new Request(new URL(path, origin), init)\n\n return staticFile(root, request) ?? entry.default(request)\n },\n }\n}\n"]}
|
package/dist/useSsr.d.ts
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The module with its directive taken out, for the environment it runs in.
|
|
3
|
+
*
|
|
4
|
+
* Where server components render the directive turns the module into
|
|
5
|
+
* proxies; in the ssr environment the module is the real thing and the
|
|
6
|
+
* directive is a string with no meaning left - which the bundler says so
|
|
7
|
+
* about, once per build, as MODULE_LEVEL_DIRECTIVE "may not be preserved".
|
|
8
|
+
* Nothing needed preserving. Removed, and the warning with it. Null when the
|
|
9
|
+
* code has no directive.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withoutSsrDirective(code: string): string | null;
|
|
1
12
|
export declare const SSR_GUIDE = "https://docs.rsc-kit.dev/guides/emails";
|
|
2
13
|
export declare function hasUseSsr(code: string): boolean;
|
|
3
14
|
export declare class UseSsrError extends Error {
|
package/dist/useSsr.js
CHANGED
|
@@ -21,6 +21,21 @@ import { basename, relative } from "node:path";
|
|
|
21
21
|
* export named, at build and in dev, rather than proxied into nonsense.
|
|
22
22
|
*/
|
|
23
23
|
const DIRECTIVE = /^\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*["']use ssr["']/;
|
|
24
|
+
/**
|
|
25
|
+
* The module with its directive taken out, for the environment it runs in.
|
|
26
|
+
*
|
|
27
|
+
* Where server components render the directive turns the module into
|
|
28
|
+
* proxies; in the ssr environment the module is the real thing and the
|
|
29
|
+
* directive is a string with no meaning left - which the bundler says so
|
|
30
|
+
* about, once per build, as MODULE_LEVEL_DIRECTIVE "may not be preserved".
|
|
31
|
+
* Nothing needed preserving. Removed, and the warning with it. Null when the
|
|
32
|
+
* code has no directive.
|
|
33
|
+
*/
|
|
34
|
+
export function withoutSsrDirective(code) {
|
|
35
|
+
if (!DIRECTIVE.test(code))
|
|
36
|
+
return null;
|
|
37
|
+
return code.replace(/(^\s*(?:\/\/[^\n]*\n|\/\*[\s\S]*?\*\/\s*)*)["']use ssr["'];?[ \t]*\n?/, "$1");
|
|
38
|
+
}
|
|
24
39
|
export const SSR_GUIDE = "https://docs.rsc-kit.dev/guides/emails";
|
|
25
40
|
export function hasUseSsr(code) {
|
|
26
41
|
return DIRECTIVE.test(code.slice(0, 2048));
|
package/dist/useSsr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSsr.js","sourceRoot":"","sources":["../src/useSsr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAE/C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH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;AAC3C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAC5B,IAAY,EACZ,EAAU,EACV,IAAI,GAAW,OAAO,CAAC,GAAG,EAAE;IAE5B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAElC,MAAM,IAAI,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAErD,OAAO,CACL;QACE,iBAAiB,IAAI,yFAAyF;QAC9G,oDAAoD,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,4BAA4B;QACrH,GAAG,KAAK,CAAC,GAAG,CACV,CAAC,IAAI,EAAE,EAAE,CACP,gBAAgB,IAAI,+CAA+C,IAAI,YAAY,CACtF;QACD,GAAG,CAAC,UAAU;YACZ,CAAC,CAAC;gBACE,2EAA2E;aAC5E;YACH,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CACpB,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,eAAe,GAAG,kCAAkC,CAAC;AAElE,sFAAsF;AACtF,MAAM,UAAU,qBAAqB,CAAC,QAAuB;IAC3D,OAAO,CACL,6KAA6K;QAC7K,CAAC,QAAQ,CAAC,CAAC,CAAC,gBAAgB,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,oLAAoL;QACpL,SAAS,CACV,CAAC;AACJ,CAAC","sourcesContent":["import { basename, relative } from \"node:path\";\n\n/**\n * \"use ssr\": a module that runs in the ssr environment and is called from\n * where server components render.\n *\n * react-dom/server cannot run where server components render. React's\n * server build refuses to load it, and the refusal is right: the renderer\n * needs the client build's internals, and the components it would render\n * import that same server `react` - no useState, no useContext. A template\n * and the call that renders it have to load together somewhere React DOM's\n * server renderer can: the ssr environment, which every app here already\n * has. plugin-rsc exposes that as a call to write by hand,\n * `import.meta.viteRsc.import('./render', { environment: 'ssr' })`, and\n * nobody should have to. So a directive names the module instead, the way\n * \"use client\" names one, and this rewrites it for the server-components\n * environment into proxies of its exports that call across. Everything\n * else imports it normally.\n *\n * The exports are functions and the calls are async, because the answer\n * crosses environments as a promise. Anything else is refused with the\n * export named, at build and in dev, rather than proxied into nonsense.\n */\nconst DIRECTIVE = /^\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*[\"']use ssr[\"']/;\n\nexport const SSR_GUIDE = \"https://docs.rsc-kit.dev/guides/emails\";\n\nexport function hasUseSsr(code: string): boolean {\n return DIRECTIVE.test(code.slice(0, 2048));\n}\n\nexport class UseSsrError extends Error {}\n\n/** Comments blanked, so an `export` inside one is not read as one. */\nfunction withoutComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, \" \"))\n .replace(\n /(^|[^:\\\\])\\/\\/[^\\n]*/g,\n (m, lead: string) => lead + \" \".repeat(m.length - lead.length),\n );\n}\n\nconst NAME = \"[A-Za-z_$][\\\\w$]*\";\nconst NON_FUNCTION = /^\\s*(?:new\\b|[\"'`\\d[{]|true\\b|false\\b|null\\b)/;\n\n/** The runtime exports a \"use ssr\" module can offer: named functions, and a default. */\nexport function ssrExports(\n code: string,\n file: string,\n): { named: string[]; hasDefault: boolean } {\n const src = withoutComments(code);\n const named = new Set<string>();\n let hasDefault = false;\n\n for (const m of src.matchAll(\n new RegExp(\n `^[ \\\\t]*export\\\\s+(async\\\\s+)?function\\\\s*\\\\*?\\\\s*(${NAME})`,\n \"gm\",\n ),\n )) {\n if (!m[1]) {\n throw new UseSsrError(\n `\"use ssr\": \\`${m[2]}\\` in ${file} is called from another environment, and the answer crosses as a promise. Make it an async function.`,\n );\n }\n\n named.add(m[2]);\n }\n\n for (const m of src.matchAll(\n new RegExp(\n `^[ \\\\t]*export\\\\s+(?:const|let|var)\\\\s+(${NAME})\\\\s*(?::[^=\\\\n]*)?=([^\\\\n]*)`,\n \"gm\",\n ),\n )) {\n if (NON_FUNCTION.test(m[2])) {\n throw new UseSsrError(\n `\"use ssr\": a module with the directive exports functions only; \\`${m[1]}\\` in ${file} is a value. Put it in a module without the directive.`,\n );\n }\n\n named.add(m[1]);\n }\n\n if (/^[ \\t]*export\\s+(?:const|let|var)\\s*[[{]/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": ${file} destructures an export. Export each function by its own name; that is what gets called across.`,\n );\n }\n\n if (/^[ \\t]*export\\s+(?:abstract\\s+)?(?:class|enum)\\b/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": a module with the directive exports functions only; ${file} exports a class or enum.`,\n );\n }\n\n if (/^[ \\t]*export\\s*(?:\\{|\\*)/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": ${file} re-exports. Export the functions where they are declared; \\`export { … }\\` and \\`export *\\` cannot be called across.`,\n );\n }\n\n const dflt = /^[ \\t]*export\\s+default\\s+(async\\s+)?(function\\b)?/m.exec(src);\n\n if (dflt) {\n if (dflt[2] && !dflt[1]) {\n throw new UseSsrError(\n `\"use ssr\": the default export of ${file} is called from another environment. Make it an async function.`,\n );\n }\n\n hasDefault = true;\n }\n\n return { named: [...named], hasDefault };\n}\n\n/**\n * The module the server-components environment gets in place of a \"use ssr\"\n * one: its exports, as async proxies that call the real module where it\n * runs. Null when the module carries no directive.\n */\nexport function ssrProxyModule(\n code: string,\n id: string,\n root: string = process.cwd(),\n): string | null {\n if (!hasUseSsr(code)) return null;\n\n const path = id.split(\"?\")[0];\n const file = relative(root, path);\n const { named, hasDefault } = ssrExports(code, file);\n\n return (\n [\n `// \"use ssr\": ${file} runs in the ssr environment, where React DOM's server renderer can. These call across.`,\n `const __rsc_kit_ssr = import.meta.viteRsc.import(${JSON.stringify(\"./\" + basename(path))}, { environment: 'ssr' });`,\n ...named.map(\n (name) =>\n `export const ${name} = async (...args) => (await __rsc_kit_ssr).${name}(...args);`,\n ),\n ...(hasDefault\n ? [\n \"export default async (...args) => (await __rsc_kit_ssr).default(...args);\",\n ]\n : []),\n ].join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Any of react-dom's server renderer entries. */\nexport const SERVER_RENDERER = /^react-dom\\/server(?:\\.[a-z]+)?$/;\n\n/** What a module gets in place of react-dom/server where server components render. */\nexport function serverRendererMessage(importer: string | null): string {\n return (\n \"react-dom/server cannot run where server components render: React's server build has no client internals for it, and the components it would render import that same React.\" +\n (importer ? ` Imported by ${importer}.` : \"\") +\n ' Put the rendering - the template and the call - in a module that starts with \"use ssr\": it runs in the ssr environment, and its exports are called from here as async functions. ' +\n SSR_GUIDE\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useSsr.js","sourceRoot":"","sources":["../src/useSsr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAE/C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,SAAS,GAAG,0DAA0D,CAAC;AAE7E;;;;;;;;;GASG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC9C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAEvC,OAAO,IAAI,CAAC,OAAO,CAAC,uEAAuE,EAAE,IAAI,CAAC,CAAC;AACrG,CAAC;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,wCAAwC,CAAC;AAElE,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,OAAO,WAAY,SA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,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAErD,OAAO,CACL;QACE,iBAAiB,IAAI,yFAAyF;QAC9G,oDAAoD,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,4BAA4B;QACrH,GAAG,KAAK,CAAC,GAAG,CACV,CAAC,IAAI,EAAE,EAAE,CACP,gBAAgB,IAAI,+CAA+C,IAAI,YAAY,CACtF;QACD,GAAG,CAAC,UAAU;YACZ,CAAC,CAAC;gBACE,2EAA2E;aAC5E;YACH,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CACpB,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,eAAe,GAAG,kCAAkC,CAAC;AAElE,sFAAsF;AACtF,MAAM,UAAU,qBAAqB,CAAC,QAAuB;IAC3D,OAAO,CACL,6KAA6K;QAC7K,CAAC,QAAQ,CAAC,CAAC,CAAC,gBAAgB,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,oLAAoL;QACpL,SAAS,CACV,CAAC;AACJ,CAAC","sourcesContent":["import { basename, relative } from \"node:path\";\n\n/**\n * \"use ssr\": a module that runs in the ssr environment and is called from\n * where server components render.\n *\n * react-dom/server cannot run where server components render. React's\n * server build refuses to load it, and the refusal is right: the renderer\n * needs the client build's internals, and the components it would render\n * import that same server `react` - no useState, no useContext. A template\n * and the call that renders it have to load together somewhere React DOM's\n * server renderer can: the ssr environment, which every app here already\n * has. plugin-rsc exposes that as a call to write by hand,\n * `import.meta.viteRsc.import('./render', { environment: 'ssr' })`, and\n * nobody should have to. So a directive names the module instead, the way\n * \"use client\" names one, and this rewrites it for the server-components\n * environment into proxies of its exports that call across. Everything\n * else imports it normally.\n *\n * The exports are functions and the calls are async, because the answer\n * crosses environments as a promise. Anything else is refused with the\n * export named, at build and in dev, rather than proxied into nonsense.\n */\nconst DIRECTIVE = /^\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*[\"']use ssr[\"']/;\n\n/**\n * The module with its directive taken out, for the environment it runs in.\n *\n * Where server components render the directive turns the module into\n * proxies; in the ssr environment the module is the real thing and the\n * directive is a string with no meaning left - which the bundler says so\n * about, once per build, as MODULE_LEVEL_DIRECTIVE \"may not be preserved\".\n * Nothing needed preserving. Removed, and the warning with it. Null when the\n * code has no directive.\n */\nexport function withoutSsrDirective(code: string): string | null {\n if (!DIRECTIVE.test(code)) return null;\n\n return code.replace(/(^\\s*(?:\\/\\/[^\\n]*\\n|\\/\\*[\\s\\S]*?\\*\\/\\s*)*)[\"']use ssr[\"'];?[ \\t]*\\n?/, \"$1\");\n}\n\nexport const SSR_GUIDE = \"https://docs.rsc-kit.dev/guides/emails\";\n\nexport function hasUseSsr(code: string): boolean {\n return DIRECTIVE.test(code.slice(0, 2048));\n}\n\nexport class UseSsrError extends Error {}\n\n/** Comments blanked, so an `export` inside one is not read as one. */\nfunction withoutComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, \" \"))\n .replace(\n /(^|[^:\\\\])\\/\\/[^\\n]*/g,\n (m, lead: string) => lead + \" \".repeat(m.length - lead.length),\n );\n}\n\nconst NAME = \"[A-Za-z_$][\\\\w$]*\";\nconst NON_FUNCTION = /^\\s*(?:new\\b|[\"'`\\d[{]|true\\b|false\\b|null\\b)/;\n\n/** The runtime exports a \"use ssr\" module can offer: named functions, and a default. */\nexport function ssrExports(\n code: string,\n file: string,\n): { named: string[]; hasDefault: boolean } {\n const src = withoutComments(code);\n const named = new Set<string>();\n let hasDefault = false;\n\n for (const m of src.matchAll(\n new RegExp(\n `^[ \\\\t]*export\\\\s+(async\\\\s+)?function\\\\s*\\\\*?\\\\s*(${NAME})`,\n \"gm\",\n ),\n )) {\n if (!m[1]) {\n throw new UseSsrError(\n `\"use ssr\": \\`${m[2]}\\` in ${file} is called from another environment, and the answer crosses as a promise. Make it an async function.`,\n );\n }\n\n named.add(m[2]);\n }\n\n for (const m of src.matchAll(\n new RegExp(\n `^[ \\\\t]*export\\\\s+(?:const|let|var)\\\\s+(${NAME})\\\\s*(?::[^=\\\\n]*)?=([^\\\\n]*)`,\n \"gm\",\n ),\n )) {\n if (NON_FUNCTION.test(m[2])) {\n throw new UseSsrError(\n `\"use ssr\": a module with the directive exports functions only; \\`${m[1]}\\` in ${file} is a value. Put it in a module without the directive.`,\n );\n }\n\n named.add(m[1]);\n }\n\n if (/^[ \\t]*export\\s+(?:const|let|var)\\s*[[{]/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": ${file} destructures an export. Export each function by its own name; that is what gets called across.`,\n );\n }\n\n if (/^[ \\t]*export\\s+(?:abstract\\s+)?(?:class|enum)\\b/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": a module with the directive exports functions only; ${file} exports a class or enum.`,\n );\n }\n\n if (/^[ \\t]*export\\s*(?:\\{|\\*)/m.test(src)) {\n throw new UseSsrError(\n `\"use ssr\": ${file} re-exports. Export the functions where they are declared; \\`export { … }\\` and \\`export *\\` cannot be called across.`,\n );\n }\n\n const dflt = /^[ \\t]*export\\s+default\\s+(async\\s+)?(function\\b)?/m.exec(src);\n\n if (dflt) {\n if (dflt[2] && !dflt[1]) {\n throw new UseSsrError(\n `\"use ssr\": the default export of ${file} is called from another environment. Make it an async function.`,\n );\n }\n\n hasDefault = true;\n }\n\n return { named: [...named], hasDefault };\n}\n\n/**\n * The module the server-components environment gets in place of a \"use ssr\"\n * one: its exports, as async proxies that call the real module where it\n * runs. Null when the module carries no directive.\n */\nexport function ssrProxyModule(\n code: string,\n id: string,\n root: string = process.cwd(),\n): string | null {\n if (!hasUseSsr(code)) return null;\n\n const path = id.split(\"?\")[0];\n const file = relative(root, path);\n const { named, hasDefault } = ssrExports(code, file);\n\n return (\n [\n `// \"use ssr\": ${file} runs in the ssr environment, where React DOM's server renderer can. These call across.`,\n `const __rsc_kit_ssr = import.meta.viteRsc.import(${JSON.stringify(\"./\" + basename(path))}, { environment: 'ssr' });`,\n ...named.map(\n (name) =>\n `export const ${name} = async (...args) => (await __rsc_kit_ssr).${name}(...args);`,\n ),\n ...(hasDefault\n ? [\n \"export default async (...args) => (await __rsc_kit_ssr).default(...args);\",\n ]\n : []),\n ].join(\"\\n\") + \"\\n\"\n );\n}\n\n/** Any of react-dom's server renderer entries. */\nexport const SERVER_RENDERER = /^react-dom\\/server(?:\\.[a-z]+)?$/;\n\n/** What a module gets in place of react-dom/server where server components render. */\nexport function serverRendererMessage(importer: string | null): string {\n return (\n \"react-dom/server cannot run where server components render: React's server build has no client internals for it, and the components it would render import that same React.\" +\n (importer ? ` Imported by ${importer}.` : \"\") +\n ' Put the rendering - the template and the call - in a module that starts with \"use ssr\": it runs in the ssr environment, and its exports are called from here as async functions. ' +\n SSR_GUIDE\n );\n}\n"]}
|