vinext 0.0.39 → 0.0.40
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/build/standalone.js +7 -0
- package/dist/build/standalone.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +2 -1
- package/dist/entries/app-rsc-entry.js +131 -245
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/index.d.ts +32 -1
- package/dist/index.js +80 -6
- package/dist/index.js.map +1 -1
- package/dist/plugins/server-externals-manifest.d.ts +11 -1
- package/dist/plugins/server-externals-manifest.js +10 -3
- package/dist/plugins/server-externals-manifest.js.map +1 -1
- package/dist/routing/app-router.d.ts +10 -2
- package/dist/routing/app-router.js +37 -22
- package/dist/routing/app-router.js.map +1 -1
- package/dist/server/app-page-response.d.ts +12 -1
- package/dist/server/app-page-response.js +26 -7
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +79 -0
- package/dist/server/app-page-route-wiring.js +165 -0
- package/dist/server/app-page-route-wiring.js.map +1 -0
- package/dist/server/app-page-stream.js +3 -0
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-route-handler-response.js +4 -1
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-router-entry.d.ts +6 -1
- package/dist/server/app-router-entry.js +9 -2
- package/dist/server/app-router-entry.js.map +1 -1
- package/dist/server/prod-server.d.ts +1 -1
- package/dist/server/prod-server.js +37 -11
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/worker-utils.d.ts +4 -1
- package/dist/server/worker-utils.js +31 -1
- package/dist/server/worker-utils.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +13 -4
- package/dist/shims/error-boundary.js +23 -3
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/navigation.d.ts +16 -1
- package/dist/shims/navigation.js +18 -3
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/router.js +127 -38
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.d.ts +17 -4
- package/dist/shims/server.js +91 -73
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/slot.d.ts +28 -0
- package/dist/shims/slot.js +49 -0
- package/dist/shims/slot.js.map +1 -0
- package/package.json +1 -2
|
@@ -8,10 +8,23 @@ import { jsx } from "react/jsx-runtime";
|
|
|
8
8
|
* This must be a client component since error boundaries use
|
|
9
9
|
* componentDidCatch / getDerivedStateFromError.
|
|
10
10
|
*/
|
|
11
|
-
var
|
|
11
|
+
var ErrorBoundaryInner = class extends React.Component {
|
|
12
12
|
constructor(props) {
|
|
13
13
|
super(props);
|
|
14
|
-
this.state = {
|
|
14
|
+
this.state = {
|
|
15
|
+
error: null,
|
|
16
|
+
previousPathname: props.pathname
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
static getDerivedStateFromProps(props, state) {
|
|
20
|
+
if (props.pathname !== state.previousPathname && state.error) return {
|
|
21
|
+
error: null,
|
|
22
|
+
previousPathname: props.pathname
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
error: state.error,
|
|
26
|
+
previousPathname: props.pathname
|
|
27
|
+
};
|
|
15
28
|
}
|
|
16
29
|
static getDerivedStateFromError(error) {
|
|
17
30
|
if (error && typeof error === "object" && "digest" in error) {
|
|
@@ -34,6 +47,13 @@ var ErrorBoundary = class extends React.Component {
|
|
|
34
47
|
return this.props.children;
|
|
35
48
|
}
|
|
36
49
|
};
|
|
50
|
+
function ErrorBoundary({ fallback, children }) {
|
|
51
|
+
return /* @__PURE__ */ jsx(ErrorBoundaryInner, {
|
|
52
|
+
pathname: usePathname(),
|
|
53
|
+
fallback,
|
|
54
|
+
children
|
|
55
|
+
});
|
|
56
|
+
}
|
|
37
57
|
/**
|
|
38
58
|
* Inner class component that catches notFound() errors and renders the
|
|
39
59
|
* not-found.tsx fallback. Resets when the pathname changes (client navigation)
|
|
@@ -84,6 +104,6 @@ function NotFoundBoundary({ fallback, children }) {
|
|
|
84
104
|
});
|
|
85
105
|
}
|
|
86
106
|
//#endregion
|
|
87
|
-
export { ErrorBoundary, NotFoundBoundary };
|
|
107
|
+
export { ErrorBoundary, ErrorBoundaryInner, NotFoundBoundary };
|
|
88
108
|
|
|
89
109
|
//# sourceMappingURL=error-boundary.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-boundary.js","names":[],"sources":["../../src/shims/error-boundary.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\n// oxlint-disable-next-line @typescript-eslint/no-require-imports -- next/navigation is shimmed\nimport { usePathname } from \"next/navigation\";\n\nexport type ErrorBoundaryProps = {\n fallback: React.ComponentType<{ error: Error; reset: () => void }>;\n children: React.ReactNode;\n};\n\nexport type ErrorBoundaryState = {\n error: Error | null;\n};\n\n/**\n * Generic ErrorBoundary used to wrap route segments with error.tsx.\n * This must be a client component since error boundaries use\n * componentDidCatch / getDerivedStateFromError.\n */\nexport class
|
|
1
|
+
{"version":3,"file":"error-boundary.js","names":[],"sources":["../../src/shims/error-boundary.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\n// oxlint-disable-next-line @typescript-eslint/no-require-imports -- next/navigation is shimmed\nimport { usePathname } from \"next/navigation\";\n\nexport type ErrorBoundaryProps = {\n fallback: React.ComponentType<{ error: Error; reset: () => void }>;\n children: React.ReactNode;\n};\n\ntype ErrorBoundaryInnerProps = {\n pathname: string;\n} & ErrorBoundaryProps;\n\nexport type ErrorBoundaryState = {\n error: Error | null;\n previousPathname: string;\n};\n\n/**\n * Generic ErrorBoundary used to wrap route segments with error.tsx.\n * This must be a client component since error boundaries use\n * componentDidCatch / getDerivedStateFromError.\n */\nexport class ErrorBoundaryInner extends React.Component<\n ErrorBoundaryInnerProps,\n ErrorBoundaryState\n> {\n constructor(props: ErrorBoundaryInnerProps) {\n super(props);\n this.state = { error: null, previousPathname: props.pathname };\n }\n\n static getDerivedStateFromProps(\n props: ErrorBoundaryInnerProps,\n state: ErrorBoundaryState,\n ): ErrorBoundaryState | null {\n if (props.pathname !== state.previousPathname && state.error) {\n return { error: null, previousPathname: props.pathname };\n }\n return { error: state.error, previousPathname: props.pathname };\n }\n\n static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {\n // notFound(), forbidden(), unauthorized(), and redirect() must propagate\n // past error boundaries. Re-throw them so they bubble up to the\n // framework's HTTP access fallback / redirect handler.\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String(error.digest);\n if (\n digest === \"NEXT_NOT_FOUND\" || // legacy compat\n digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;\") ||\n digest.startsWith(\"NEXT_REDIRECT;\")\n ) {\n throw error;\n }\n }\n return { error };\n }\n\n reset = () => {\n this.setState({ error: null });\n };\n\n render() {\n if (this.state.error) {\n const FallbackComponent = this.props.fallback;\n return <FallbackComponent error={this.state.error} reset={this.reset} />;\n }\n return this.props.children;\n }\n}\n\nexport function ErrorBoundary({ fallback, children }: ErrorBoundaryProps) {\n const pathname = usePathname();\n return (\n <ErrorBoundaryInner pathname={pathname} fallback={fallback}>\n {children}\n </ErrorBoundaryInner>\n );\n}\n\n// ---------------------------------------------------------------------------\n// NotFoundBoundary — catches notFound() on the client and renders not-found.tsx\n// ---------------------------------------------------------------------------\n\ntype NotFoundBoundaryProps = {\n fallback: React.ReactNode;\n children: React.ReactNode;\n};\n\ntype NotFoundBoundaryInnerProps = {\n pathname: string;\n} & NotFoundBoundaryProps;\n\ntype NotFoundBoundaryState = {\n notFound: boolean;\n previousPathname: string;\n};\n\n/**\n * Inner class component that catches notFound() errors and renders the\n * not-found.tsx fallback. Resets when the pathname changes (client navigation)\n * so a previous notFound() doesn't permanently stick.\n *\n * The ErrorBoundary above re-throws notFound errors so they propagate up to this\n * boundary. This must be placed above the ErrorBoundary in the component tree.\n */\nclass NotFoundBoundaryInner extends React.Component<\n NotFoundBoundaryInnerProps,\n NotFoundBoundaryState\n> {\n constructor(props: NotFoundBoundaryInnerProps) {\n super(props);\n this.state = { notFound: false, previousPathname: props.pathname };\n }\n\n static getDerivedStateFromProps(\n props: NotFoundBoundaryInnerProps,\n state: NotFoundBoundaryState,\n ): NotFoundBoundaryState | null {\n // Reset the boundary when the route changes so a previous notFound()\n // doesn't permanently stick after client-side navigation.\n if (props.pathname !== state.previousPathname && state.notFound) {\n return { notFound: false, previousPathname: props.pathname };\n }\n return { notFound: state.notFound, previousPathname: props.pathname };\n }\n\n static getDerivedStateFromError(error: Error): Partial<NotFoundBoundaryState> {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String(error.digest);\n if (digest === \"NEXT_NOT_FOUND\" || digest.startsWith(\"NEXT_HTTP_ERROR_FALLBACK;404\")) {\n return { notFound: true };\n }\n }\n // Not a notFound error — re-throw so it reaches an ErrorBoundary or propagates\n throw error;\n }\n\n render() {\n if (this.state.notFound) {\n return this.props.fallback;\n }\n return this.props.children;\n }\n}\n\n/**\n * Wrapper that reads the current pathname and passes it to the inner class\n * component. This enables automatic reset on client-side navigation.\n */\nexport function NotFoundBoundary({ fallback, children }: NotFoundBoundaryProps) {\n const pathname = usePathname();\n return (\n <NotFoundBoundaryInner pathname={pathname} fallback={fallback}>\n {children}\n </NotFoundBoundaryInner>\n );\n}\n"],"mappings":";;;;;;;;;;AAyBA,IAAa,qBAAb,cAAwC,MAAM,UAG5C;CACA,YAAY,OAAgC;AAC1C,QAAM,MAAM;AACZ,OAAK,QAAQ;GAAE,OAAO;GAAM,kBAAkB,MAAM;GAAU;;CAGhE,OAAO,yBACL,OACA,OAC2B;AAC3B,MAAI,MAAM,aAAa,MAAM,oBAAoB,MAAM,MACrD,QAAO;GAAE,OAAO;GAAM,kBAAkB,MAAM;GAAU;AAE1D,SAAO;GAAE,OAAO,MAAM;GAAO,kBAAkB,MAAM;GAAU;;CAGjE,OAAO,yBAAyB,OAA2C;AAIzE,MAAI,SAAS,OAAO,UAAU,YAAY,YAAY,OAAO;GAC3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qB,CAAA"}
|
package/dist/shims/head.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"head.js","names":[],"sources":["../../src/shims/head.ts"],"sourcesContent":["/**\n * next/head shim\n *\n * In the Pages Router, <Head> manages document <head> elements.\n * - On the server: collects elements into a module-level array that the\n * dev-server reads after render and injects into the HTML <head>.\n * - On the client: reduces all mounted <Head> instances into one deduped\n * document.head projection and applies it with DOM manipulation.\n */\nimport React, { useEffect, useRef, Children, isValidElement } from \"react\";\n\ntype HeadProps = {\n children?: React.ReactNode;\n};\n\n// --- SSR head collection ---\n// State uses a registration pattern so this module can be bundled for the\n// browser. The ALS-backed implementation lives in head-state.ts (server-only).\n\nlet _ssrHeadChildren: React.ReactNode[] = [];\nconst _clientHeadChildren = new Map<symbol, React.ReactNode>();\n\nlet _getSSRHeadChildren = (): React.ReactNode[] => _ssrHeadChildren;\nlet _resetSSRHeadImpl = (): void => {\n _ssrHeadChildren = [];\n};\n\n/**\n * Register ALS-backed state accessors. Called by head-state.ts on import.\n * @internal\n */\nexport function _registerHeadStateAccessors(accessors: {\n getSSRHeadChildren: () => React.ReactNode[];\n resetSSRHead: () => void;\n}): void {\n _getSSRHeadChildren = accessors.getSSRHeadChildren;\n _resetSSRHeadImpl = accessors.resetSSRHead;\n}\n\n/** Reset the SSR head collector. Call before render. */\nexport function resetSSRHead(): void {\n _resetSSRHeadImpl();\n}\n\n/** Get collected head HTML. Call after render. */\nexport function getSSRHeadHTML(): string {\n return reduceHeadChildren(_getSSRHeadChildren())\n .map((child) => headChildToHTML(child.type as string, child.props as Record<string, unknown>))\n .filter(Boolean)\n .join(\"\\n \");\n}\n\n/**\n * Tags allowed inside <head>. Anything else is silently dropped.\n * This prevents injection of dangerous elements like <iframe>, <object>, etc.\n */\nconst ALLOWED_HEAD_TAGS = new Set([\"title\", \"meta\", \"link\", \"style\", \"script\", \"base\", \"noscript\"]);\nconst ALLOWED_HEAD_TAGS_LIST = Array.from(ALLOWED_HEAD_TAGS).join(\", \");\nconst META_TYPES = [\"name\", \"httpEquiv\", \"charSet\", \"itemProp\"] as const;\n\n/** Self-closing tags: no inner content, emit as <tag ... /> */\nconst SELF_CLOSING_HEAD_TAGS = new Set([\"meta\", \"link\", \"base\"]);\n\n/** Tags whose content is raw text — closing-tag sequences must be escaped during SSR. */\nconst RAW_CONTENT_TAGS = new Set([\"script\", \"style\"]);\n\nfunction warnDisallowedHeadTag(tag: string): void {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[vinext] <Head> ignoring disallowed tag <${tag}>. ` +\n `Only ${ALLOWED_HEAD_TAGS_LIST} are allowed.`,\n );\n }\n}\n\nfunction collectHeadElements(\n list: React.ReactElement[],\n child: React.ReactNode,\n): React.ReactElement[] {\n if (\n child == null ||\n typeof child === \"boolean\" ||\n typeof child === \"string\" ||\n typeof child === \"number\"\n ) {\n return list;\n }\n if (!isValidElement(child)) {\n return list;\n }\n if (child.type === React.Fragment) {\n return Children.toArray((child.props as { children?: React.ReactNode }).children).reduce(\n collectHeadElements,\n list,\n );\n }\n if (typeof child.type !== \"string\") {\n return list;\n }\n if (!ALLOWED_HEAD_TAGS.has(child.type)) {\n warnDisallowedHeadTag(child.type);\n return list;\n }\n return list.concat(child);\n}\n\nfunction normalizeHeadKey(key: React.Key | null): string | null {\n if (key == null || typeof key === \"number\") return null;\n const normalizedKey = String(key);\n const separatorIndex = normalizedKey.indexOf(\"$\");\n return separatorIndex > 0 ? normalizedKey.slice(separatorIndex + 1) : null;\n}\n\nfunction createUniqueHeadFilter(): (child: React.ReactElement) => boolean {\n const keys = new Set<string>();\n const tags = new Set<string>();\n const metaTypes = new Set<string>();\n const metaCategories = new Map<string, Set<string>>();\n\n return (child) => {\n let isUnique = true;\n const normalizedKey = normalizeHeadKey(child.key);\n const hasKey = normalizedKey !== null;\n if (normalizedKey) {\n if (keys.has(normalizedKey)) {\n isUnique = false;\n } else {\n keys.add(normalizedKey);\n }\n }\n\n switch (child.type) {\n case \"title\":\n case \"base\":\n if (tags.has(child.type)) {\n isUnique = false;\n } else {\n tags.add(child.type);\n }\n break;\n case \"meta\": {\n const props = child.props as Record<string, unknown>;\n for (const metaType of META_TYPES) {\n if (!Object.prototype.hasOwnProperty.call(props, metaType)) continue;\n if (metaType === \"charSet\") {\n if (metaTypes.has(metaType)) {\n isUnique = false;\n } else {\n metaTypes.add(metaType);\n }\n continue;\n }\n\n const category = props[metaType];\n if (typeof category !== \"string\") continue;\n\n let categories = metaCategories.get(metaType);\n if (!categories) {\n categories = new Set<string>();\n metaCategories.set(metaType, categories);\n }\n\n if ((metaType !== \"name\" || !hasKey) && categories.has(category)) {\n isUnique = false;\n } else {\n categories.add(category);\n }\n }\n break;\n }\n default:\n break;\n }\n\n return isUnique;\n };\n}\n\nexport function reduceHeadChildren(headChildren: React.ReactNode[]): React.ReactElement[] {\n return headChildren\n .reduce<React.ReactNode[]>(\n (flattenedChildren, child) => flattenedChildren.concat(Children.toArray(child)),\n [],\n )\n .reduce(collectHeadElements, [])\n .reverse()\n .filter(createUniqueHeadFilter())\n .reverse();\n}\n\n/**\n * Validate an HTML attribute name. Rejects names that could break out of\n * the attribute context during SSR serialization, or that represent inline\n * event handlers (on*). Only allows alphanumeric characters, hyphens, and\n * common data-attribute patterns.\n */\nconst SAFE_ATTR_NAME_RE = /^[a-zA-Z][a-zA-Z0-9\\-:.]*$/;\n\nexport function isSafeAttrName(name: string): boolean {\n if (!SAFE_ATTR_NAME_RE.test(name)) return false;\n // Block inline event handlers (onclick, onerror, etc.)\n if (name.length > 2 && name[0] === \"o\" && name[1] === \"n\" && name[2] >= \"A\" && name[2] <= \"z\")\n return false;\n return true;\n}\n\n/**\n * Convert props + tag to an HTML string for SSR head injection.\n * Callers must only pass tags that have already been validated against\n * ALLOWED_HEAD_TAGS (e.g. via reduceHeadChildren / collectHeadElements).\n */\nfunction headChildToHTML(tag: string, props: Record<string, unknown>): string {\n const attrs: string[] = [];\n let innerHTML = \"\";\n\n for (const [key, value] of Object.entries(props)) {\n if (key === \"children\") {\n if (typeof value === \"string\") innerHTML = escapeHTML(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n // Intentionally raw — developer explicitly opted in.\n // SECURITY NOTE: This injects raw HTML during SSR. The client-side\n // path skips dangerouslySetInnerHTML for safety. Developers must never\n // pass unsanitized user input here — it is a stored XSS vector.\n const html = value as { __html?: string };\n if (html?.__html) innerHTML = html.__html;\n } else if (key === \"className\") {\n attrs.push(`class=\"${escapeAttr(String(value))}\"`);\n } else if (typeof value === \"string\") {\n if (!isSafeAttrName(key)) continue;\n attrs.push(`${key}=\"${escapeAttr(value)}\"`);\n } else if (typeof value === \"boolean\" && value) {\n if (!isSafeAttrName(key)) continue;\n attrs.push(key);\n }\n }\n\n const attrStr = attrs.length ? \" \" + attrs.join(\" \") : \"\";\n\n if (SELF_CLOSING_HEAD_TAGS.has(tag)) {\n return `<${tag}${attrStr} data-vinext-head=\"true\" />`;\n }\n\n // For raw-content tags (script, style), escape closing-tag sequences so the\n // HTML parser doesn't prematurely terminate the element.\n if (RAW_CONTENT_TAGS.has(tag) && innerHTML) {\n innerHTML = escapeInlineContent(innerHTML, tag);\n }\n\n return `<${tag}${attrStr} data-vinext-head=\"true\">${innerHTML}</${tag}>`;\n}\n\nfunction escapeHTML(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n\nexport function escapeAttr(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\n/**\n * Escape content that will be placed inside a raw <script> or <style> tag\n * during SSR. The HTML parser treats `</script>` (or `</style>`) as the end\n * of the block regardless of JavaScript string context, so any occurrence\n * of `</` followed by the tag name must be escaped.\n *\n * We replace `</script` and `</style` (case-insensitive) with `<\\/script`\n * and `<\\/style` respectively. The `<\\/` form is harmless in JS/CSS string\n * context but prevents the HTML parser from seeing a closing tag.\n */\nexport function escapeInlineContent(content: string, tag: string): string {\n // Build a pattern like `<\\/script` or `<\\/style`, case-insensitive\n const pattern = new RegExp(`<\\\\/(${tag})`, \"gi\");\n return content.replace(pattern, \"<\\\\/$1\");\n}\n\nfunction syncClientHead(): void {\n document.querySelectorAll(\"[data-vinext-head]\").forEach((el) => el.remove());\n\n for (const child of reduceHeadChildren([..._clientHeadChildren.values()])) {\n if (typeof child.type !== \"string\") continue;\n\n const domEl = document.createElement(child.type);\n const props = child.props as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(props)) {\n if (key === \"children\" && typeof value === \"string\") {\n domEl.textContent = value;\n } else if (key === \"dangerouslySetInnerHTML\") {\n // skip for safety\n } else if (key === \"className\") {\n domEl.setAttribute(\"class\", String(value));\n } else if (typeof value === \"boolean\" && value) {\n if (!isSafeAttrName(key)) continue;\n domEl.setAttribute(key, \"\");\n } else if (key !== \"children\" && typeof value === \"string\") {\n if (!isSafeAttrName(key)) continue;\n domEl.setAttribute(key, value);\n }\n }\n\n domEl.setAttribute(\"data-vinext-head\", \"true\");\n document.head.appendChild(domEl);\n }\n}\n\n// --- Component ---\n\nfunction Head({ children }: HeadProps): null {\n const headInstanceIdRef = useRef<symbol | null>(null);\n if (headInstanceIdRef.current === null) {\n headInstanceIdRef.current = Symbol(\"vinext-head\");\n }\n\n // SSR path: collect elements for later injection\n if (typeof window === \"undefined\") {\n _getSSRHeadChildren().push(children);\n return null;\n }\n\n // Client path: update the shared head projection after hydration.\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n const instanceId = headInstanceIdRef.current!;\n _clientHeadChildren.set(instanceId, children);\n syncClientHead();\n\n return () => {\n _clientHeadChildren.delete(instanceId);\n syncClientHead();\n };\n }, [children]);\n\n return null;\n}\n\nexport default Head;\n"],"mappings":";;;;;;;;;;;AAmBA,IAAI,mBAAsC,EAAE;AAC5C,MAAM,sCAAsB,IAAI,KAA8B;AAE9D,IAAI,4BAA+C;AACnD,IAAI,0BAAgC;AAClC,oBAAmB,EAAE;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K,SAAS;AACpC,SAAO;;AAKT,iBAAgB;EACd,MAAM,aAAa,kBAAkB;AACrC,sBAAoB,IAAI,YAAY,SAAS;AAC7C,kBAAgB;AAEhB,eAAa;AACX,uBAAoB,OAAO,WAAW;AACtC,mBAAgB;;IAEjB,CAAC,SAAS,CAAC;AAEd,QAAO"}
|
|
1
|
+
{"version":3,"file":"head.js","names":[],"sources":["../../src/shims/head.ts"],"sourcesContent":["/**\n * next/head shim\n *\n * In the Pages Router, <Head> manages document <head> elements.\n * - On the server: collects elements into a module-level array that the\n * dev-server reads after render and injects into the HTML <head>.\n * - On the client: reduces all mounted <Head> instances into one deduped\n * document.head projection and applies it with DOM manipulation.\n */\nimport React, { useEffect, useRef, Children, isValidElement } from \"react\";\n\ntype HeadProps = {\n children?: React.ReactNode;\n};\n\n// --- SSR head collection ---\n// State uses a registration pattern so this module can be bundled for the\n// browser. The ALS-backed implementation lives in head-state.ts (server-only).\n\nlet _ssrHeadChildren: React.ReactNode[] = [];\nconst _clientHeadChildren = new Map<symbol, React.ReactNode>();\n\nlet _getSSRHeadChildren = (): React.ReactNode[] => _ssrHeadChildren;\nlet _resetSSRHeadImpl = (): void => {\n _ssrHeadChildren = [];\n};\n\n/**\n * Register ALS-backed state accessors. Called by head-state.ts on import.\n * @internal\n */\nexport function _registerHeadStateAccessors(accessors: {\n getSSRHeadChildren: () => React.ReactNode[];\n resetSSRHead: () => void;\n}): void {\n _getSSRHeadChildren = accessors.getSSRHeadChildren;\n _resetSSRHeadImpl = accessors.resetSSRHead;\n}\n\n/** Reset the SSR head collector. Call before render. */\nexport function resetSSRHead(): void {\n _resetSSRHeadImpl();\n}\n\n/** Get collected head HTML. Call after render. */\nexport function getSSRHeadHTML(): string {\n return reduceHeadChildren(_getSSRHeadChildren())\n .map((child) => headChildToHTML(child.type as string, child.props as Record<string, unknown>))\n .filter(Boolean)\n .join(\"\\n \");\n}\n\n/**\n * Tags allowed inside <head>. Anything else is silently dropped.\n * This prevents injection of dangerous elements like <iframe>, <object>, etc.\n */\nconst ALLOWED_HEAD_TAGS = new Set([\"title\", \"meta\", \"link\", \"style\", \"script\", \"base\", \"noscript\"]);\nconst ALLOWED_HEAD_TAGS_LIST = Array.from(ALLOWED_HEAD_TAGS).join(\", \");\nconst META_TYPES = [\"name\", \"httpEquiv\", \"charSet\", \"itemProp\"] as const;\n\n/** Self-closing tags: no inner content, emit as <tag ... /> */\nconst SELF_CLOSING_HEAD_TAGS = new Set([\"meta\", \"link\", \"base\"]);\n\n/** Tags whose content is raw text — closing-tag sequences must be escaped during SSR. */\nconst RAW_CONTENT_TAGS = new Set([\"script\", \"style\"]);\n\nfunction warnDisallowedHeadTag(tag: string): void {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[vinext] <Head> ignoring disallowed tag <${tag}>. ` +\n `Only ${ALLOWED_HEAD_TAGS_LIST} are allowed.`,\n );\n }\n}\n\nfunction collectHeadElements(\n list: React.ReactElement[],\n child: React.ReactNode,\n): React.ReactElement[] {\n if (\n child == null ||\n typeof child === \"boolean\" ||\n typeof child === \"string\" ||\n typeof child === \"number\"\n ) {\n return list;\n }\n if (!isValidElement(child)) {\n return list;\n }\n if (child.type === React.Fragment) {\n return Children.toArray((child.props as { children?: React.ReactNode }).children).reduce(\n collectHeadElements,\n list,\n );\n }\n if (typeof child.type !== \"string\") {\n return list;\n }\n if (!ALLOWED_HEAD_TAGS.has(child.type)) {\n warnDisallowedHeadTag(child.type);\n return list;\n }\n return list.concat(child);\n}\n\nfunction normalizeHeadKey(key: React.Key | null): string | null {\n if (key == null || typeof key === \"number\") return null;\n const normalizedKey = String(key);\n const separatorIndex = normalizedKey.indexOf(\"$\");\n return separatorIndex > 0 ? normalizedKey.slice(separatorIndex + 1) : null;\n}\n\nfunction createUniqueHeadFilter(): (child: React.ReactElement) => boolean {\n const keys = new Set<string>();\n const tags = new Set<string>();\n const metaTypes = new Set<string>();\n const metaCategories = new Map<string, Set<string>>();\n\n return (child) => {\n let isUnique = true;\n const normalizedKey = normalizeHeadKey(child.key);\n const hasKey = normalizedKey !== null;\n if (normalizedKey) {\n if (keys.has(normalizedKey)) {\n isUnique = false;\n } else {\n keys.add(normalizedKey);\n }\n }\n\n switch (child.type) {\n case \"title\":\n case \"base\":\n if (tags.has(child.type)) {\n isUnique = false;\n } else {\n tags.add(child.type);\n }\n break;\n case \"meta\": {\n const props = child.props as Record<string, unknown>;\n for (const metaType of META_TYPES) {\n if (!Object.prototype.hasOwnProperty.call(props, metaType)) continue;\n if (metaType === \"charSet\") {\n if (metaTypes.has(metaType)) {\n isUnique = false;\n } else {\n metaTypes.add(metaType);\n }\n continue;\n }\n\n const category = props[metaType];\n if (typeof category !== \"string\") continue;\n\n let categories = metaCategories.get(metaType);\n if (!categories) {\n categories = new Set<string>();\n metaCategories.set(metaType, categories);\n }\n\n if ((metaType !== \"name\" || !hasKey) && categories.has(category)) {\n isUnique = false;\n } else {\n categories.add(category);\n }\n }\n break;\n }\n default:\n break;\n }\n\n return isUnique;\n };\n}\n\nexport function reduceHeadChildren(headChildren: React.ReactNode[]): React.ReactElement[] {\n return headChildren\n .reduce<React.ReactNode[]>(\n (flattenedChildren, child) => flattenedChildren.concat(Children.toArray(child)),\n [],\n )\n .reduce(collectHeadElements, [])\n .reverse()\n .filter(createUniqueHeadFilter())\n .reverse();\n}\n\n/**\n * Validate an HTML attribute name. Rejects names that could break out of\n * the attribute context during SSR serialization, or that represent inline\n * event handlers (on*). Only allows alphanumeric characters, hyphens, and\n * common data-attribute patterns.\n */\nconst SAFE_ATTR_NAME_RE = /^[a-zA-Z][a-zA-Z0-9\\-:.]*$/;\n\nexport function isSafeAttrName(name: string): boolean {\n if (!SAFE_ATTR_NAME_RE.test(name)) return false;\n // Block inline event handlers (onclick, onerror, etc.)\n if (name.length > 2 && name[0] === \"o\" && name[1] === \"n\" && name[2] >= \"A\" && name[2] <= \"z\")\n return false;\n return true;\n}\n\n/**\n * Convert props + tag to an HTML string for SSR head injection.\n * Callers must only pass tags that have already been validated against\n * ALLOWED_HEAD_TAGS (e.g. via reduceHeadChildren / collectHeadElements).\n */\nfunction headChildToHTML(tag: string, props: Record<string, unknown>): string {\n const attrs: string[] = [];\n let innerHTML = \"\";\n\n for (const [key, value] of Object.entries(props)) {\n if (key === \"children\") {\n if (typeof value === \"string\") innerHTML = escapeHTML(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n // Intentionally raw — developer explicitly opted in.\n // SECURITY NOTE: This injects raw HTML during SSR. The client-side\n // path skips dangerouslySetInnerHTML for safety. Developers must never\n // pass unsanitized user input here — it is a stored XSS vector.\n const html = value as { __html?: string };\n if (html?.__html) innerHTML = html.__html;\n } else if (key === \"className\") {\n attrs.push(`class=\"${escapeAttr(String(value))}\"`);\n } else if (typeof value === \"string\") {\n if (!isSafeAttrName(key)) continue;\n attrs.push(`${key}=\"${escapeAttr(value)}\"`);\n } else if (typeof value === \"boolean\" && value) {\n if (!isSafeAttrName(key)) continue;\n attrs.push(key);\n }\n }\n\n const attrStr = attrs.length ? \" \" + attrs.join(\" \") : \"\";\n\n if (SELF_CLOSING_HEAD_TAGS.has(tag)) {\n return `<${tag}${attrStr} data-vinext-head=\"true\" />`;\n }\n\n // For raw-content tags (script, style), escape closing-tag sequences so the\n // HTML parser doesn't prematurely terminate the element.\n if (RAW_CONTENT_TAGS.has(tag) && innerHTML) {\n innerHTML = escapeInlineContent(innerHTML, tag);\n }\n\n return `<${tag}${attrStr} data-vinext-head=\"true\">${innerHTML}</${tag}>`;\n}\n\nfunction escapeHTML(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n}\n\nexport function escapeAttr(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\n/**\n * Escape content that will be placed inside a raw <script> or <style> tag\n * during SSR. The HTML parser treats `</script>` (or `</style>`) as the end\n * of the block regardless of JavaScript string context, so any occurrence\n * of `</` followed by the tag name must be escaped.\n *\n * We replace `</script` and `</style` (case-insensitive) with `<\\/script`\n * and `<\\/style` respectively. The `<\\/` form is harmless in JS/CSS string\n * context but prevents the HTML parser from seeing a closing tag.\n */\nexport function escapeInlineContent(content: string, tag: string): string {\n // Build a pattern like `<\\/script` or `<\\/style`, case-insensitive.\n // `tag` is always a literal developer-controlled value (\"script\" or \"style\")\n // guarded by the RAW_CONTENT_TAGS.has(tag) check at all call sites — never user input.\n const pattern = new RegExp(`<\\\\/(${tag})`, \"gi\");\n return content.replace(pattern, \"<\\\\/$1\");\n}\n\nfunction syncClientHead(): void {\n document.querySelectorAll(\"[data-vinext-head]\").forEach((el) => el.remove());\n\n for (const child of reduceHeadChildren([..._clientHeadChildren.values()])) {\n if (typeof child.type !== \"string\") continue;\n\n const domEl = document.createElement(child.type);\n const props = child.props as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(props)) {\n if (key === \"children\" && typeof value === \"string\") {\n domEl.textContent = value;\n } else if (key === \"dangerouslySetInnerHTML\") {\n // skip for safety\n } else if (key === \"className\") {\n domEl.setAttribute(\"class\", String(value));\n } else if (typeof value === \"boolean\" && value) {\n if (!isSafeAttrName(key)) continue;\n domEl.setAttribute(key, \"\");\n } else if (key !== \"children\" && typeof value === \"string\") {\n if (!isSafeAttrName(key)) continue;\n domEl.setAttribute(key, value);\n }\n }\n\n domEl.setAttribute(\"data-vinext-head\", \"true\");\n document.head.appendChild(domEl);\n }\n}\n\n// --- Component ---\n\nfunction Head({ children }: HeadProps): null {\n const headInstanceIdRef = useRef<symbol | null>(null);\n if (headInstanceIdRef.current === null) {\n headInstanceIdRef.current = Symbol(\"vinext-head\");\n }\n\n // SSR path: collect elements for later injection\n if (typeof window === \"undefined\") {\n _getSSRHeadChildren().push(children);\n return null;\n }\n\n // Client path: update the shared head projection after hydration.\n // oxlint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n const instanceId = headInstanceIdRef.current!;\n _clientHeadChildren.set(instanceId, children);\n syncClientHead();\n\n return () => {\n _clientHeadChildren.delete(instanceId);\n syncClientHead();\n };\n }, [children]);\n\n return null;\n}\n\nexport default Head;\n"],"mappings":";;;;;;;;;;;AAmBA,IAAI,mBAAsC,EAAE;AAC5C,MAAM,sCAAsB,IAAI,KAA8B;AAE9D,IAAI,4BAA+C;AACnD,IAAI,0BAAgC;AAClC,oBAAmB,EAAE;;;;;;AAOvB,SAAgB,4BAA4B,WAGnC;AACP,uBAAsB,UAAU;AAChC,qBAAoB,UAAU;;;AAIhC,SAAgB,eAAqB;AACnC,oBAAmB;;;AAIrB,SAAgB,iBAAyB;AACvC,QAAO,mBAAmB,qBAAqB,CAAC,CAC7C,KAAK,UAAU,gBAAgB,MAAM,MAAgB,MAAM,MAAiC,CAAC,CAC7F,OAAO,QAAQ,CACf,KAAK,OAAO;;;;;;AAOjB,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAQ;CAAS;CAAU;CAAQ;CAAW,CAAC;AACnG,MAAM,yBAAyB,MAAM,KAAK,kBAAkB,CAAC,KAAK,KAAK;AACvE,MAAM,aAAa;CAAC;CAAQ;CAAa;CAAW;CAAW;;AAG/D,MAAM,yBAAyB,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAO,CAAC;;AAGhE,MAAM,mBAAmB,IAAI,IAAI,CAAC,UAAU,QAAQ,CAAC;AAErD,SAAS,sBAAsB,KAAmB;AAChD,KAAI,QAAQ,IAAI,aAAa,aAC3B,SAAQ,KACN,4CAA4C,IAAI,UACtC,uBAAuB,eAClC;;AAIL,SAAS,oBACP,MACA,OACsB;AACtB,KACE,SAAS,QACT,OAAO,UAAU,aACjB,OAAO,UAAU,YACjB,OAAO,UAAU,SAEjB,QAAO;AAET,KAAI,CAAC,eAAe,MAAM,CACxB,QAAO;AAET,KAAI,MAAM,SAAS,MAAM,SACvB,QAAO,SAAS,QAAS,MAAM,MAAyC,SAAS,CAAC,OAChF,qBACA,KACD;AAEH,KAAI,OAAO,MAAM,SAAS,SACx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Aa,oBAAoB,OAAO;AAC9C,WAAS,KAAK,YAAY,MAAM;;;AAMpC,SAAS,KAAK,EAAE,YAA6B;CAC3C,MAAM,oBAAoB,OAAsB,KAAK;AACrD,KAAI,kBAAkB,YAAY,KAChC,mBAAkB,UAAU,OAAO,cAAc;AAInD,KAAI,OAAO,WAAW,aAAa;AACjC,uBAAqB,CAAC,KAAK,SAAS;AACpC,SAAO;;AAKT,iBAAgB;EACd,MAAM,aAAa,kBAAkB;AACrC,sBAAoB,IAAI,YAAY,SAAS;AAC7C,kBAAgB;AAEhB,eAAa;AACX,uBAAoB,OAAO,WAAW;AACtC,mBAAgB;;IAEjB,CAAC,SAAS,CAAC;AAEd,QAAO"}
|
|
@@ -259,12 +259,27 @@ declare enum RedirectType {
|
|
|
259
259
|
}
|
|
260
260
|
/**
|
|
261
261
|
* Throw a redirect. Caught by the framework to send a redirect response.
|
|
262
|
+
*
|
|
263
|
+
* When `type` is omitted, the digest carries an empty sentinel so the
|
|
264
|
+
* catch site can resolve the default based on context:
|
|
265
|
+
* - Server Action context → "push" (Back button works after form submission)
|
|
266
|
+
* - SSR render context → "replace"
|
|
267
|
+
*
|
|
268
|
+
* This matches Next.js behavior where `redirect()` checks
|
|
269
|
+
* `actionAsyncStorage.getStore()?.isAction` at call time.
|
|
270
|
+
*
|
|
271
|
+
* @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts
|
|
262
272
|
*/
|
|
263
273
|
declare function redirect(url: string, type?: "replace" | "push" | RedirectType): never;
|
|
264
274
|
/**
|
|
265
275
|
* Trigger a permanent redirect (308).
|
|
276
|
+
*
|
|
277
|
+
* Accepts an optional `type` parameter matching Next.js's signature.
|
|
278
|
+
* Defaults to "replace" (not context-dependent like `redirect()`).
|
|
279
|
+
*
|
|
280
|
+
* @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts
|
|
266
281
|
*/
|
|
267
|
-
declare function permanentRedirect(url: string): never;
|
|
282
|
+
declare function permanentRedirect(url: string, type?: "replace" | "push" | RedirectType): never;
|
|
268
283
|
/**
|
|
269
284
|
* Trigger a not-found response (404). Caught by the framework.
|
|
270
285
|
*/
|
package/dist/shims/navigation.js
CHANGED
|
@@ -770,15 +770,30 @@ var VinextNavigationError = class extends Error {
|
|
|
770
770
|
};
|
|
771
771
|
/**
|
|
772
772
|
* Throw a redirect. Caught by the framework to send a redirect response.
|
|
773
|
+
*
|
|
774
|
+
* When `type` is omitted, the digest carries an empty sentinel so the
|
|
775
|
+
* catch site can resolve the default based on context:
|
|
776
|
+
* - Server Action context → "push" (Back button works after form submission)
|
|
777
|
+
* - SSR render context → "replace"
|
|
778
|
+
*
|
|
779
|
+
* This matches Next.js behavior where `redirect()` checks
|
|
780
|
+
* `actionAsyncStorage.getStore()?.isAction` at call time.
|
|
781
|
+
*
|
|
782
|
+
* @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts
|
|
773
783
|
*/
|
|
774
784
|
function redirect(url, type) {
|
|
775
|
-
throw new VinextNavigationError(`NEXT_REDIRECT:${url}`, `NEXT_REDIRECT;${type ?? "
|
|
785
|
+
throw new VinextNavigationError(`NEXT_REDIRECT:${url}`, `NEXT_REDIRECT;${type ?? ""};${encodeURIComponent(url)}`);
|
|
776
786
|
}
|
|
777
787
|
/**
|
|
778
788
|
* Trigger a permanent redirect (308).
|
|
789
|
+
*
|
|
790
|
+
* Accepts an optional `type` parameter matching Next.js's signature.
|
|
791
|
+
* Defaults to "replace" (not context-dependent like `redirect()`).
|
|
792
|
+
*
|
|
793
|
+
* @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts
|
|
779
794
|
*/
|
|
780
|
-
function permanentRedirect(url) {
|
|
781
|
-
throw new VinextNavigationError(`NEXT_REDIRECT:${url}`, `NEXT_REDIRECT
|
|
795
|
+
function permanentRedirect(url, type = "replace") {
|
|
796
|
+
throw new VinextNavigationError(`NEXT_REDIRECT:${url}`, `NEXT_REDIRECT;${type};${encodeURIComponent(url)};308`);
|
|
782
797
|
}
|
|
783
798
|
/**
|
|
784
799
|
* Trigger a not-found response (404). Caught by the framework.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation.js","names":["React"],"sources":["../../src/shims/navigation.ts"],"sourcesContent":["/**\n * next/navigation shim\n *\n * App Router navigation hooks. These work on both server (RSC) and client.\n * Server-side: reads from a request context set by the RSC handler.\n * Client-side: reads from browser Location API and provides navigation.\n */\n\n// Use namespace import for RSC safety: the react-server condition doesn't export\n// createContext/useContext/useSyncExternalStore as named exports, and strict ESM\n// would throw at link time for missing bindings. With `import * as React`, the\n// bindings are just `undefined` on the namespace object and we can guard at runtime.\nimport * as React from \"react\";\nimport { notifyAppRouterTransitionStart } from \"../client/instrumentation-client-state.js\";\nimport { toBrowserNavigationHref, toSameOriginAppPath } from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { ReadonlyURLSearchParams } from \"./readonly-url-search-params.js\";\n\n// ─── Layout segment context ───────────────────────────────────────────────────\n// Stores the child segments below the current layout. Each layout wraps its\n// children with a provider whose value is the remaining route tree segments\n// (including route groups, with dynamic params resolved to actual values).\n// Created lazily because `React.createContext` is NOT available in the\n// react-server condition of React. In the RSC environment, this remains null.\n// The shared context lives behind a global singleton so provider/hook pairs\n// still line up if Vite loads this shim through multiple resolved module IDs.\nconst _LAYOUT_SEGMENT_CTX_KEY = Symbol.for(\"vinext.layoutSegmentContext\");\nconst _SERVER_INSERTED_HTML_CTX_KEY = Symbol.for(\"vinext.serverInsertedHTMLContext\");\n\n/**\n * Map of parallel route key → child segments below the current layout.\n * The \"children\" key is always present (the default parallel route).\n * Named parallel routes add their own keys (e.g., \"team\", \"analytics\").\n *\n * Arrays are mutable (`string[]`) to match Next.js's public API return type\n * without requiring `as` casts. The map itself is Readonly — no key addition.\n */\nexport type SegmentMap = Readonly<Record<string, string[]>> & { readonly children: string[] };\n\ntype _LayoutSegmentGlobal = typeof globalThis & {\n [_LAYOUT_SEGMENT_CTX_KEY]?: React.Context<SegmentMap> | null;\n [_SERVER_INSERTED_HTML_CTX_KEY]?: React.Context<\n ((callback: () => unknown) => void) | null\n > | null;\n};\n\n// ─── ServerInsertedHTML context ────────────────────────────────────────────────\n// Used by CSS-in-JS libraries (Apollo Client, styled-components, emotion) to\n// register HTML injection callbacks during SSR via useContext().\n// The SSR entry wraps the rendered tree with a Provider whose value is a\n// callback registration function (useServerInsertedHTML).\n//\n// In Next.js, ServerInsertedHTMLContext holds a function:\n// (callback: () => React.ReactNode) => void\n// Libraries call useContext(ServerInsertedHTMLContext) to get this function,\n// then call it to register callbacks that inject HTML during SSR.\n//\n// Created eagerly at module load time. In the RSC environment (react-server\n// condition), createContext isn't available so this will be null.\n\nfunction getServerInsertedHTMLContext(): React.Context<\n ((callback: () => unknown) => void) | null\n> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _LayoutSegmentGlobal;\n if (!globalState[_SERVER_INSERTED_HTML_CTX_KEY]) {\n globalState[_SERVER_INSERTED_HTML_CTX_KEY] = React.createContext<\n ((callback: () => unknown) => void) | null\n >(null);\n }\n\n return globalState[_SERVER_INSERTED_HTML_CTX_KEY] ?? null;\n}\n\nexport const ServerInsertedHTMLContext: React.Context<\n ((callback: () => unknown) => void) | null\n> | null = getServerInsertedHTMLContext();\n\n/**\n * Get or create the layout segment context.\n * Returns null in the RSC environment (createContext unavailable).\n */\nexport function getLayoutSegmentContext(): React.Context<SegmentMap> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _LayoutSegmentGlobal;\n if (!globalState[_LAYOUT_SEGMENT_CTX_KEY]) {\n globalState[_LAYOUT_SEGMENT_CTX_KEY] = React.createContext<SegmentMap>({ children: [] });\n }\n\n return globalState[_LAYOUT_SEGMENT_CTX_KEY] ?? null;\n}\n\n/**\n * Read the child segments for a parallel route below the current layout.\n * Returns [] if no context is available (RSC environment, outside React tree)\n * or if the requested key is not present in the segment map.\n */\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\nfunction useChildSegments(parallelRoutesKey: string = \"children\"): string[] {\n const ctx = getLayoutSegmentContext();\n if (!ctx) return [];\n // useContext is safe here because if createContext exists, useContext does too.\n // This branch is only taken in SSR/Browser, never in RSC.\n // Try/catch for unit tests that call this hook outside a React render tree.\n try {\n const segmentMap = React.useContext(ctx);\n return segmentMap[parallelRoutesKey] ?? [];\n } catch {\n return [];\n }\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n// ---------------------------------------------------------------------------\n// Server-side request context (set by the RSC entry before rendering)\n// ---------------------------------------------------------------------------\n\nexport type NavigationContext = {\n pathname: string;\n searchParams: URLSearchParams;\n params: Record<string, string | string[]>;\n};\n\nconst _READONLY_SEARCH_PARAMS = Symbol(\"vinext.navigation.readonlySearchParams\");\nconst _READONLY_SEARCH_PARAMS_SOURCE = Symbol(\"vinext.navigation.readonlySearchParamsSource\");\n\ntype NavigationContextWithReadonlyCache = NavigationContext & {\n [_READONLY_SEARCH_PARAMS]?: ReadonlyURLSearchParams;\n [_READONLY_SEARCH_PARAMS_SOURCE]?: URLSearchParams;\n};\n\n// ---------------------------------------------------------------------------\n// Server-side navigation state lives in a separate server-only module\n// (navigation-state.ts) that uses AsyncLocalStorage for request isolation.\n// This module is bundled for the browser, so it can't import node:async_hooks.\n//\n// On the server: state functions are set by navigation-state.ts at import time.\n// On the client: _serverContext falls back to null (hooks use window instead).\n//\n// Global accessor pattern (issue #688):\n// Vite's multi-environment dev mode can create separate module instances of\n// this file for the SSR entry vs \"use client\" components. When that happens,\n// _registerStateAccessors only updates the SSR entry's instance, leaving the\n// \"use client\" instance with the default (null) fallbacks.\n//\n// To fix this, navigation-state.ts also stores the accessors on globalThis\n// via Symbol.for, and the defaults here check for that global before falling\n// back to module-level state. This ensures all module instances can reach the\n// ALS-backed state regardless of which instance was registered.\n// ---------------------------------------------------------------------------\n\ntype _StateAccessors = {\n getServerContext: () => NavigationContext | null;\n setServerContext: (ctx: NavigationContext | null) => void;\n getInsertedHTMLCallbacks: () => Array<() => unknown>;\n clearInsertedHTMLCallbacks: () => void;\n};\n\nexport const GLOBAL_ACCESSORS_KEY = Symbol.for(\"vinext.navigation.globalAccessors\");\nconst _GLOBAL_ACCESSORS_KEY = GLOBAL_ACCESSORS_KEY;\ntype _GlobalWithAccessors = typeof globalThis & { [_GLOBAL_ACCESSORS_KEY]?: _StateAccessors };\n\nfunction _getGlobalAccessors(): _StateAccessors | undefined {\n return (globalThis as _GlobalWithAccessors)[_GLOBAL_ACCESSORS_KEY];\n}\n\nlet _serverContext: NavigationContext | null = null;\nlet _serverInsertedHTMLCallbacks: Array<() => unknown> = [];\n\n// These are overridden by navigation-state.ts on the server to use ALS.\n// The defaults check globalThis for cross-module-instance access (issue #688).\nlet _getServerContext = (): NavigationContext | null => {\n const g = _getGlobalAccessors();\n return g ? g.getServerContext() : _serverContext;\n};\nlet _setServerContext = (ctx: NavigationContext | null): void => {\n const g = _getGlobalAccessors();\n if (g) {\n g.setServerContext(ctx);\n } else {\n _serverContext = ctx;\n }\n};\nlet _getInsertedHTMLCallbacks = (): Array<() => unknown> => {\n const g = _getGlobalAccessors();\n return g ? g.getInsertedHTMLCallbacks() : _serverInsertedHTMLCallbacks;\n};\nlet _clearInsertedHTMLCallbacks = (): void => {\n const g = _getGlobalAccessors();\n if (g) {\n g.clearInsertedHTMLCallbacks();\n } else {\n _serverInsertedHTMLCallbacks = [];\n }\n};\n\n/**\n * Register ALS-backed state accessors. Called by navigation-state.ts on import.\n * @internal\n */\nexport function _registerStateAccessors(accessors: _StateAccessors): void {\n _getServerContext = accessors.getServerContext;\n _setServerContext = accessors.setServerContext;\n _getInsertedHTMLCallbacks = accessors.getInsertedHTMLCallbacks;\n _clearInsertedHTMLCallbacks = accessors.clearInsertedHTMLCallbacks;\n}\n\n/**\n * Get the navigation context for the current SSR/RSC render.\n * Reads from AsyncLocalStorage when available (concurrent-safe),\n * otherwise falls back to module-level state.\n */\nexport function getNavigationContext(): NavigationContext | null {\n return _getServerContext();\n}\n\n/**\n * Set the navigation context for the current SSR/RSC render.\n * Called by the framework entry before rendering each request.\n */\nexport function setNavigationContext(ctx: NavigationContext | null): void {\n _setServerContext(ctx);\n}\n\n// ---------------------------------------------------------------------------\n// Client-side state\n// ---------------------------------------------------------------------------\n\nconst isServer = typeof window === \"undefined\";\n\n/** basePath from next.config.js, injected by the plugin at build time */\nexport const __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\n// ---------------------------------------------------------------------------\n// RSC prefetch cache utilities (shared between link.tsx and browser entry)\n// ---------------------------------------------------------------------------\n\n/** Maximum number of entries in the RSC prefetch cache. */\nexport const MAX_PREFETCH_CACHE_SIZE = 50;\n\n/** TTL for prefetch cache entries in ms (matches Next.js static prefetch TTL). */\nexport const PREFETCH_CACHE_TTL = 30_000;\n\n/** A buffered RSC response stored as an ArrayBuffer for replay. */\nexport type CachedRscResponse = {\n buffer: ArrayBuffer;\n contentType: string;\n paramsHeader: string | null;\n url: string;\n};\n\nexport type PrefetchCacheEntry = {\n snapshot?: CachedRscResponse;\n pending?: Promise<void>;\n timestamp: number;\n};\n\n/**\n * Convert a pathname (with optional query/hash) to its .rsc URL.\n * Strips trailing slashes before appending `.rsc` so that cache keys\n * are consistent regardless of the `trailingSlash` config setting.\n */\nexport function toRscUrl(href: string): string {\n const [beforeHash] = href.split(\"#\");\n const qIdx = beforeHash.indexOf(\"?\");\n const pathname = qIdx === -1 ? beforeHash : beforeHash.slice(0, qIdx);\n const query = qIdx === -1 ? \"\" : beforeHash.slice(qIdx);\n // Strip trailing slash (but preserve \"/\" root) for consistent cache keys\n const normalizedPath =\n pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n return normalizedPath + \".rsc\" + query;\n}\n\n/** Get or create the shared in-memory RSC prefetch cache on window. */\nexport function getPrefetchCache(): Map<string, PrefetchCacheEntry> {\n if (isServer) return new Map();\n if (!window.__VINEXT_RSC_PREFETCH_CACHE__) {\n window.__VINEXT_RSC_PREFETCH_CACHE__ = new Map<string, PrefetchCacheEntry>();\n }\n return window.__VINEXT_RSC_PREFETCH_CACHE__;\n}\n\n/**\n * Get or create the shared set of already-prefetched RSC URLs on window.\n * Keyed by rscUrl so that the browser entry can clear entries when consumed.\n */\nexport function getPrefetchedUrls(): Set<string> {\n if (isServer) return new Set();\n if (!window.__VINEXT_RSC_PREFETCHED_URLS__) {\n window.__VINEXT_RSC_PREFETCHED_URLS__ = new Set<string>();\n }\n return window.__VINEXT_RSC_PREFETCHED_URLS__;\n}\n\n/**\n * Evict prefetch cache entries if at capacity.\n * First sweeps expired entries, then falls back to FIFO eviction.\n */\nfunction evictPrefetchCacheIfNeeded(): void {\n const cache = getPrefetchCache();\n if (cache.size < MAX_PREFETCH_CACHE_SIZE) return;\n\n const now = Date.now();\n const prefetched = getPrefetchedUrls();\n\n for (const [key, entry] of cache) {\n if (now - entry.timestamp >= PREFETCH_CACHE_TTL) {\n cache.delete(key);\n prefetched.delete(key);\n }\n }\n\n while (cache.size >= MAX_PREFETCH_CACHE_SIZE) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) {\n cache.delete(oldest);\n prefetched.delete(oldest);\n } else {\n break;\n }\n }\n}\n\n/**\n * Store a prefetched RSC response in the cache by snapshotting it to an\n * ArrayBuffer. The snapshot completes asynchronously; during that window\n * the entry is marked `pending` so consumePrefetchResponse() will skip it\n * (the caller falls back to a fresh fetch, which is acceptable).\n *\n * Prefer prefetchRscResponse() for new call-sites — it handles the full\n * prefetch lifecycle including dedup. storePrefetchResponse() is kept for\n * backward compatibility and test helpers.\n *\n * NB: Caller is responsible for managing getPrefetchedUrls() — this\n * function only stores the response in the prefetch cache.\n */\nexport function storePrefetchResponse(rscUrl: string, response: Response): void {\n evictPrefetchCacheIfNeeded();\n const entry: PrefetchCacheEntry = { timestamp: Date.now() };\n entry.pending = snapshotRscResponse(response)\n .then((snapshot) => {\n entry.snapshot = snapshot;\n })\n .catch(() => {\n getPrefetchCache().delete(rscUrl);\n })\n .finally(() => {\n entry.pending = undefined;\n });\n getPrefetchCache().set(rscUrl, entry);\n}\n\n/**\n * Snapshot an RSC response to an ArrayBuffer for caching and replay.\n * Consumes the response body and stores it with content-type and URL metadata.\n */\nexport async function snapshotRscResponse(response: Response): Promise<CachedRscResponse> {\n const buffer = await response.arrayBuffer();\n return {\n buffer,\n contentType: response.headers.get(\"content-type\") ?? \"text/x-component\",\n paramsHeader: response.headers.get(\"X-Vinext-Params\"),\n url: response.url,\n };\n}\n\n/**\n * Reconstruct a Response from a cached RSC snapshot.\n * Creates a new Response with the original ArrayBuffer so createFromFetch\n * can consume the stream from scratch.\n *\n * NOTE: The reconstructed Response always has `url === \"\"` — the Response\n * constructor does not accept a `url` option, and `response.url` is read-only\n * set by the fetch infrastructure. Callers that need the original URL should\n * read it from `cached.url` directly rather than from the restored Response.\n *\n * @param copy - When true (default), copies the ArrayBuffer so the cached\n * snapshot remains replayable (needed for the visited-response cache).\n * Pass false for single-consumption paths (e.g. prefetch cache entries\n * that are deleted after consumption) to avoid the extra allocation.\n */\nexport function restoreRscResponse(cached: CachedRscResponse, copy = true): Response {\n const headers = new Headers({ \"content-type\": cached.contentType });\n if (cached.paramsHeader != null) {\n headers.set(\"X-Vinext-Params\", cached.paramsHeader);\n }\n\n return new Response(copy ? cached.buffer.slice(0) : cached.buffer, {\n status: 200,\n headers,\n });\n}\n\n/**\n * Prefetch an RSC response and snapshot it for later consumption.\n * Stores the in-flight promise so immediate clicks can await it instead\n * of firing a duplicate fetch.\n * Enforces a maximum cache size to prevent unbounded memory growth on\n * link-heavy pages.\n */\nexport function prefetchRscResponse(rscUrl: string, fetchPromise: Promise<Response>): void {\n const cache = getPrefetchCache();\n const prefetched = getPrefetchedUrls();\n const now = Date.now();\n\n const entry: PrefetchCacheEntry = { timestamp: now };\n\n entry.pending = fetchPromise\n .then(async (response) => {\n if (response.ok) {\n entry.snapshot = await snapshotRscResponse(response);\n } else {\n prefetched.delete(rscUrl);\n cache.delete(rscUrl);\n }\n })\n .catch(() => {\n prefetched.delete(rscUrl);\n cache.delete(rscUrl);\n })\n .finally(() => {\n entry.pending = undefined;\n });\n\n // Insert the new entry before evicting. FIFO evicts from the front of the\n // Map (oldest insertion order), so the just-appended entry is safe — only\n // entries inserted before it are candidates for removal.\n cache.set(rscUrl, entry);\n evictPrefetchCacheIfNeeded();\n}\n\n/**\n * Consume a prefetched response for a given rscUrl.\n * Only returns settled (non-pending) snapshots synchronously.\n * Returns null if the entry is still in flight or doesn't exist.\n */\nexport function consumePrefetchResponse(rscUrl: string): CachedRscResponse | null {\n const cache = getPrefetchCache();\n const entry = cache.get(rscUrl);\n if (!entry) return null;\n\n // Don't consume pending entries — let the navigation fetch independently.\n if (entry.pending) return null;\n\n cache.delete(rscUrl);\n getPrefetchedUrls().delete(rscUrl);\n\n if (entry.snapshot) {\n if (Date.now() - entry.timestamp >= PREFETCH_CACHE_TTL) {\n return null;\n }\n return entry.snapshot;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Client navigation state — stored on a Symbol.for global to survive\n// multiple Vite module instances loading this file through different IDs.\n// ---------------------------------------------------------------------------\n\ntype NavigationListener = () => void;\nconst _CLIENT_NAV_STATE_KEY = Symbol.for(\"vinext.clientNavigationState\");\n\ntype ClientNavigationState = {\n listeners: Set<NavigationListener>;\n cachedSearch: string;\n cachedReadonlySearchParams: ReadonlyURLSearchParams;\n cachedPathname: string;\n clientParams: Record<string, string | string[]>;\n clientParamsJson: string;\n pendingClientParams: Record<string, string | string[]> | null;\n pendingClientParamsJson: string | null;\n originalPushState: typeof window.history.pushState;\n originalReplaceState: typeof window.history.replaceState;\n patchInstalled: boolean;\n hasPendingNavigationUpdate: boolean;\n suppressUrlNotifyCount: number;\n navigationSnapshotActiveCount: number;\n};\n\ntype ClientNavigationGlobal = typeof globalThis & {\n [_CLIENT_NAV_STATE_KEY]?: ClientNavigationState;\n};\n\nfunction getClientNavigationState(): ClientNavigationState | null {\n if (isServer) return null;\n\n const globalState = window as ClientNavigationGlobal;\n globalState[_CLIENT_NAV_STATE_KEY] ??= {\n listeners: new Set<NavigationListener>(),\n cachedSearch: window.location.search,\n cachedReadonlySearchParams: new ReadonlyURLSearchParams(window.location.search),\n cachedPathname: stripBasePath(window.location.pathname, __basePath),\n clientParams: {},\n clientParamsJson: \"{}\",\n pendingClientParams: null,\n pendingClientParamsJson: null,\n // NB: These capture the currently installed history methods, not guaranteed\n // native ones. If a third-party library (analytics, router) has already patched\n // history methods before this module loads, we intentionally preserve that\n // wrapper. With Symbol.for global state, the first module instance to load wins.\n originalPushState: window.history.pushState.bind(window.history),\n originalReplaceState: window.history.replaceState.bind(window.history),\n patchInstalled: false,\n hasPendingNavigationUpdate: false,\n suppressUrlNotifyCount: 0,\n navigationSnapshotActiveCount: 0,\n };\n\n return globalState[_CLIENT_NAV_STATE_KEY]!;\n}\n\nfunction notifyNavigationListeners(): void {\n const state = getClientNavigationState();\n if (!state) return;\n for (const fn of state.listeners) fn();\n}\n\n// Cached URLSearchParams, pathname, etc. for referential stability\n// useSyncExternalStore compares snapshots with Object.is — avoid creating\n// new instances on every render (infinite re-renders).\nlet _cachedEmptyServerSearchParams: ReadonlyURLSearchParams | null = null;\n\n/**\n * Get cached pathname snapshot for useSyncExternalStore.\n * Note: Returns cached value from ClientNavigationState, not live window.location.\n * The cache is updated by syncCommittedUrlStateFromLocation() after navigation commits.\n * This ensures referential stability and prevents infinite re-renders.\n * External pushState/replaceState while URL notifications are suppressed won't\n * be visible until the next commit.\n */\nfunction getPathnameSnapshot(): string {\n return getClientNavigationState()?.cachedPathname ?? \"/\";\n}\n\nlet _cachedEmptyClientSearchParams: ReadonlyURLSearchParams | null = null;\n\n/**\n * Get cached search params snapshot for useSyncExternalStore.\n * Note: Returns cached value from ClientNavigationState, not live window.location.search.\n * The cache is updated by syncCommittedUrlStateFromLocation() after navigation commits.\n * This ensures referential stability and prevents infinite re-renders.\n * External pushState/replaceState while URL notifications are suppressed won't\n * be visible until the next commit.\n */\nfunction getSearchParamsSnapshot(): ReadonlyURLSearchParams {\n const cached = getClientNavigationState()?.cachedReadonlySearchParams;\n if (cached) return cached;\n if (_cachedEmptyClientSearchParams === null) {\n _cachedEmptyClientSearchParams = new ReadonlyURLSearchParams();\n }\n return _cachedEmptyClientSearchParams;\n}\n\nfunction syncCommittedUrlStateFromLocation(): boolean {\n const state = getClientNavigationState();\n if (!state) return false;\n\n let changed = false;\n\n const pathname = stripBasePath(window.location.pathname, __basePath);\n if (pathname !== state.cachedPathname) {\n state.cachedPathname = pathname;\n changed = true;\n }\n\n const search = window.location.search;\n if (search !== state.cachedSearch) {\n state.cachedSearch = search;\n state.cachedReadonlySearchParams = new ReadonlyURLSearchParams(search);\n changed = true;\n }\n\n return changed;\n}\n\nfunction getServerSearchParamsSnapshot(): ReadonlyURLSearchParams {\n const ctx = _getServerContext() as NavigationContextWithReadonlyCache | null;\n\n if (!ctx) {\n // No server context available - return cached empty instance\n if (_cachedEmptyServerSearchParams === null) {\n _cachedEmptyServerSearchParams = new ReadonlyURLSearchParams();\n }\n return _cachedEmptyServerSearchParams;\n }\n\n const source = ctx.searchParams;\n const cached = ctx[_READONLY_SEARCH_PARAMS];\n const cachedSource = ctx[_READONLY_SEARCH_PARAMS_SOURCE];\n\n // Return cached wrapper if source hasn't changed\n if (cached && cachedSource === source) {\n return cached;\n }\n\n // Create and cache new wrapper\n const readonly = new ReadonlyURLSearchParams(source);\n ctx[_READONLY_SEARCH_PARAMS] = readonly;\n ctx[_READONLY_SEARCH_PARAMS_SOURCE] = source;\n\n return readonly;\n}\n\n// ---------------------------------------------------------------------------\n// Navigation snapshot activation flag\n//\n// The render snapshot context provides pending URL values during transitions.\n// After the transition commits, the snapshot becomes stale and must NOT shadow\n// subsequent external URL changes (user pushState/replaceState). This flag\n// tracks whether a navigation transition is in progress — hooks only prefer\n// the snapshot while it's active.\n// ---------------------------------------------------------------------------\n\n/**\n * Mark a navigation snapshot as active. Called before startTransition\n * in renderNavigationPayload. While active, hooks prefer the snapshot\n * context value over useSyncExternalStore. Uses a counter (not boolean)\n * to handle overlapping navigations — rapid clicks can interleave\n * activate/deactivate if multiple transitions are in flight.\n */\nexport function activateNavigationSnapshot(): void {\n const state = getClientNavigationState();\n if (state) state.navigationSnapshotActiveCount++;\n}\n\n// Track client-side params (set during RSC hydration/navigation)\n// We cache the params object for referential stability — only create a new\n// object when the params actually change (shallow key/value comparison).\nconst _EMPTY_PARAMS: Record<string, string | string[]> = {};\n\n// ---------------------------------------------------------------------------\n// Client navigation render snapshot — provides pending URL values to hooks\n// during a startTransition so they see the destination, not the stale URL.\n// ---------------------------------------------------------------------------\n\nexport type ClientNavigationRenderSnapshot = {\n pathname: string;\n searchParams: ReadonlyURLSearchParams;\n params: Record<string, string | string[]>;\n};\n\nconst _CLIENT_NAV_RENDER_CTX_KEY = Symbol.for(\"vinext.clientNavigationRenderContext\");\ntype _ClientNavRenderGlobal = typeof globalThis & {\n [_CLIENT_NAV_RENDER_CTX_KEY]?: React.Context<ClientNavigationRenderSnapshot | null> | null;\n};\n\nexport function getClientNavigationRenderContext(): React.Context<ClientNavigationRenderSnapshot | null> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _ClientNavRenderGlobal;\n if (!globalState[_CLIENT_NAV_RENDER_CTX_KEY]) {\n globalState[_CLIENT_NAV_RENDER_CTX_KEY] =\n React.createContext<ClientNavigationRenderSnapshot | null>(null);\n }\n\n return globalState[_CLIENT_NAV_RENDER_CTX_KEY] ?? null;\n}\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\nfunction useClientNavigationRenderSnapshot(): ClientNavigationRenderSnapshot | null {\n const ctx = getClientNavigationRenderContext();\n if (!ctx || typeof React.useContext !== \"function\") return null;\n try {\n return React.useContext(ctx);\n } catch {\n return null;\n }\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\nexport function createClientNavigationRenderSnapshot(\n href: string,\n params: Record<string, string | string[]>,\n): ClientNavigationRenderSnapshot {\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n const url = new URL(href, origin);\n\n return {\n pathname: stripBasePath(url.pathname, __basePath),\n searchParams: new ReadonlyURLSearchParams(url.search),\n params,\n };\n}\n\n// Module-level fallback for environments without window (tests, SSR).\nlet _fallbackClientParams: Record<string, string | string[]> = _EMPTY_PARAMS;\nlet _fallbackClientParamsJson = \"{}\";\n\nexport function setClientParams(params: Record<string, string | string[]>): void {\n const state = getClientNavigationState();\n if (!state) {\n const json = JSON.stringify(params);\n if (json !== _fallbackClientParamsJson) {\n _fallbackClientParams = params;\n _fallbackClientParamsJson = json;\n }\n return;\n }\n\n const json = JSON.stringify(params);\n if (json !== state.clientParamsJson) {\n state.clientParams = params;\n state.clientParamsJson = json;\n state.pendingClientParams = null;\n state.pendingClientParamsJson = null;\n notifyNavigationListeners();\n }\n}\n\nexport function replaceClientParamsWithoutNotify(params: Record<string, string | string[]>): void {\n const state = getClientNavigationState();\n if (!state) return;\n\n const json = JSON.stringify(params);\n if (json !== state.clientParamsJson && json !== state.pendingClientParamsJson) {\n state.pendingClientParams = params;\n state.pendingClientParamsJson = json;\n state.hasPendingNavigationUpdate = true;\n }\n}\n\n/** Get the current client params (for testing referential stability). */\nexport function getClientParams(): Record<string, string | string[]> {\n return getClientNavigationState()?.clientParams ?? _fallbackClientParams;\n}\n\nfunction getClientParamsSnapshot(): Record<string, string | string[]> {\n return getClientNavigationState()?.clientParams ?? _EMPTY_PARAMS;\n}\n\nfunction getServerParamsSnapshot(): Record<string, string | string[]> {\n return _getServerContext()?.params ?? _EMPTY_PARAMS;\n}\n\nfunction subscribeToNavigation(cb: () => void): () => void {\n const state = getClientNavigationState();\n if (!state) return () => {};\n\n state.listeners.add(cb);\n return () => {\n state.listeners.delete(cb);\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hooks\n// ---------------------------------------------------------------------------\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the current pathname.\n * Server: from request context. Client: from window.location.\n */\nexport function usePathname(): string {\n if (isServer) {\n // During SSR of \"use client\" components, the navigation context may not be set.\n // Return a safe fallback — the client will hydrate with the real value.\n return _getServerContext()?.pathname ?? \"/\";\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n // Client-side: use the hook system for reactivity\n const pathname = React.useSyncExternalStore(\n subscribeToNavigation,\n getPathnameSnapshot,\n () => _getServerContext()?.pathname ?? \"/\",\n );\n // Prefer the render snapshot during an active navigation transition so\n // hooks return the pending URL, not the stale committed one. After commit,\n // fall through to useSyncExternalStore so user pushState/replaceState\n // calls are immediately reflected.\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.pathname;\n }\n return pathname;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the current search params as a read-only URLSearchParams.\n */\nexport function useSearchParams(): ReadonlyURLSearchParams {\n if (isServer) {\n // During SSR for \"use client\" components, the navigation context may not be set.\n // Return a safe fallback — the client will hydrate with the real value.\n return getServerSearchParamsSnapshot();\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n const searchParams = React.useSyncExternalStore(\n subscribeToNavigation,\n getSearchParamsSnapshot,\n getServerSearchParamsSnapshot,\n );\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.searchParams;\n }\n return searchParams;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the dynamic params for the current route.\n */\nexport function useParams<\n T extends Record<string, string | string[]> = Record<string, string | string[]>,\n>(): T {\n if (isServer) {\n // During SSR for \"use client\" components, the navigation context may not be set.\n return (_getServerContext()?.params ?? _EMPTY_PARAMS) as T;\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n const params = React.useSyncExternalStore(\n subscribeToNavigation,\n getClientParamsSnapshot as () => T,\n getServerParamsSnapshot as () => T,\n );\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.params as T;\n }\n return params;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/**\n * Check if a href is an external URL (any URL scheme per RFC 3986, or protocol-relative).\n */\nfunction isExternalUrl(href: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith(\"//\");\n}\n\n/**\n * Check if a href is only a hash change relative to the current URL.\n */\nfunction isHashOnlyChange(href: string): boolean {\n if (typeof window === \"undefined\") return false;\n if (href.startsWith(\"#\")) return true;\n try {\n const current = new URL(window.location.href);\n const next = new URL(href, window.location.href);\n // Strip basePath from both pathnames for consistent comparison\n // (matches how isSameRoute handles basePath in app-browser-entry.ts)\n const strippedCurrentPath = stripBasePath(current.pathname, __basePath);\n const strippedNextPath = stripBasePath(next.pathname, __basePath);\n return (\n strippedCurrentPath === strippedNextPath && current.search === next.search && next.hash !== \"\"\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Scroll to a hash target element, or to the top if no hash.\n */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const id = hash.slice(1);\n const element = document.getElementById(id);\n if (element) {\n element.scrollIntoView({ behavior: \"auto\" });\n }\n}\n\n// ---------------------------------------------------------------------------\n// History method wrappers — suppress notifications for internal updates\n// ---------------------------------------------------------------------------\n\nfunction withSuppressedUrlNotifications<T>(fn: () => T): T {\n const state = getClientNavigationState();\n if (!state) {\n return fn();\n }\n\n state.suppressUrlNotifyCount += 1;\n try {\n return fn();\n } finally {\n state.suppressUrlNotifyCount -= 1;\n }\n}\n\nexport function commitClientNavigationState(): void {\n if (isServer) return;\n const state = getClientNavigationState();\n if (!state) return;\n\n // Only decrement the snapshot counter if a snapshot was previously activated.\n // Several code paths call commit without a prior activateNavigationSnapshot()\n // — hash-only changes (navigateClientSide), Pages Router popstate, and\n // patched history.pushState/replaceState — which legitimately have count == 0.\n if (state.navigationSnapshotActiveCount > 0) {\n state.navigationSnapshotActiveCount -= 1;\n }\n\n const urlChanged = syncCommittedUrlStateFromLocation();\n if (state.pendingClientParams !== null && state.pendingClientParamsJson !== null) {\n state.clientParams = state.pendingClientParams;\n state.clientParamsJson = state.pendingClientParamsJson;\n state.pendingClientParams = null;\n state.pendingClientParamsJson = null;\n }\n const shouldNotify = urlChanged || state.hasPendingNavigationUpdate;\n state.hasPendingNavigationUpdate = false;\n\n if (shouldNotify) {\n notifyNavigationListeners();\n }\n}\n\nexport function pushHistoryStateWithoutNotify(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n): void {\n withSuppressedUrlNotifications(() => {\n const state = getClientNavigationState();\n state?.originalPushState.call(window.history, data, unused, url);\n });\n}\n\nexport function replaceHistoryStateWithoutNotify(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n): void {\n withSuppressedUrlNotifications(() => {\n const state = getClientNavigationState();\n state?.originalReplaceState.call(window.history, data, unused, url);\n });\n}\n\n/**\n * Save the current scroll position into the current history state.\n * Called before every navigation to enable scroll restoration on back/forward.\n *\n * Uses replaceHistoryStateWithoutNotify to avoid triggering the patched\n * history.replaceState interception (which would cause spurious re-renders).\n */\nfunction saveScrollPosition(): void {\n const state = window.history.state ?? {};\n replaceHistoryStateWithoutNotify(\n { ...state, __vinext_scrollX: window.scrollX, __vinext_scrollY: window.scrollY },\n \"\",\n );\n}\n\n/**\n * Restore scroll position from a history state object (used on popstate).\n *\n * When an RSC navigation is in flight (back/forward triggers both this\n * handler and the browser entry's popstate handler which calls\n * __VINEXT_RSC_NAVIGATE__), we must wait for the new content to render\n * before scrolling. Otherwise the user sees old content flash at the\n * restored scroll position.\n *\n * This handler fires before the browser entry's popstate handler (because\n * navigation.ts is loaded before hydration completes), so we defer via a\n * microtask to give the browser entry handler a chance to set\n * __VINEXT_RSC_PENDING__. Promise.resolve() schedules a microtask\n * that runs after all synchronous event listeners have completed.\n */\nfunction restoreScrollPosition(state: unknown): void {\n if (state && typeof state === \"object\" && \"__vinext_scrollY\" in state) {\n const { __vinext_scrollX: x, __vinext_scrollY: y } = state as {\n __vinext_scrollX: number;\n __vinext_scrollY: number;\n };\n\n // Defer to allow other popstate listeners (browser entry) to run first\n // and set __VINEXT_RSC_PENDING__. Promise.resolve() schedules a microtask\n // that runs after all synchronous event listeners have completed.\n void Promise.resolve().then(() => {\n const pending: Promise<void> | null = window.__VINEXT_RSC_PENDING__ ?? null;\n\n if (pending) {\n // Wait for the RSC navigation to finish rendering, then scroll.\n void pending.then(() => {\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n });\n } else {\n // No RSC navigation in flight (Pages Router or already settled).\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n }\n });\n }\n}\n\n/**\n * Navigate to a URL, handling external URLs, hash-only changes, and RSC navigation.\n */\nexport async function navigateClientSide(\n href: string,\n mode: \"push\" | \"replace\",\n scroll: boolean,\n): Promise<void> {\n // Normalize same-origin absolute URLs to local paths for SPA navigation\n let normalizedHref = href;\n if (isExternalUrl(href)) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) {\n // Truly external: use full page navigation\n if (mode === \"replace\") {\n window.location.replace(href);\n } else {\n window.location.assign(href);\n }\n return;\n }\n normalizedHref = localPath;\n }\n\n const fullHref = toBrowserNavigationHref(normalizedHref, window.location.href, __basePath);\n // Match Next.js: App Router reports navigation start before dispatching,\n // including hash-only navigations that short-circuit after URL update.\n notifyAppRouterTransitionStart(fullHref, mode);\n\n // Save scroll position before navigating (for back/forward restoration)\n if (mode === \"push\") {\n saveScrollPosition();\n }\n\n // Hash-only change: update URL and scroll to target, skip RSC fetch\n if (isHashOnlyChange(fullHref)) {\n const hash = fullHref.includes(\"#\") ? fullHref.slice(fullHref.indexOf(\"#\")) : \"\";\n if (mode === \"replace\") {\n replaceHistoryStateWithoutNotify(null, \"\", fullHref);\n } else {\n pushHistoryStateWithoutNotify(null, \"\", fullHref);\n }\n commitClientNavigationState();\n if (scroll) {\n scrollToHash(hash);\n }\n return;\n }\n\n // Extract hash for post-navigation scrolling\n const hashIdx = fullHref.indexOf(\"#\");\n const hash = hashIdx !== -1 ? fullHref.slice(hashIdx) : \"\";\n\n // Trigger RSC re-fetch if available, and wait for the new content to render\n // before scrolling. This prevents the old page from visibly jumping to the\n // top before the new content paints.\n //\n // History is NOT pushed here for RSC navigations — the commit effect inside\n // navigateRsc owns the push/replace exclusively. This avoids a fragile\n // double-push and ensures window.location still reflects the *current* URL\n // when navigateRsc computes isSameRoute (cross-route vs same-route).\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n await window.__VINEXT_RSC_NAVIGATE__(fullHref, 0, \"navigate\", mode);\n } else {\n if (mode === \"replace\") {\n replaceHistoryStateWithoutNotify(null, \"\", fullHref);\n } else {\n pushHistoryStateWithoutNotify(null, \"\", fullHref);\n }\n commitClientNavigationState();\n }\n\n if (scroll) {\n if (hash) {\n scrollToHash(hash);\n } else {\n window.scrollTo(0, 0);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// App Router router singleton\n//\n// All methods close over module-level state (navigateClientSide, withBasePath, etc.)\n// and carry no per-render data, so the object can be created once and reused.\n// Next.js returns the same router reference on every call to useRouter(), which\n// matters for components that rely on referential equality (e.g. useMemo /\n// useEffect dependency arrays, React.memo bailouts).\n// ---------------------------------------------------------------------------\n\nconst _appRouter = {\n push(href: string, options?: { scroll?: boolean }): void {\n if (isServer) return;\n void navigateClientSide(href, \"push\", options?.scroll !== false);\n },\n replace(href: string, options?: { scroll?: boolean }): void {\n if (isServer) return;\n void navigateClientSide(href, \"replace\", options?.scroll !== false);\n },\n back(): void {\n if (isServer) return;\n window.history.back();\n },\n forward(): void {\n if (isServer) return;\n window.history.forward();\n },\n refresh(): void {\n if (isServer) return;\n // Re-fetch the current page's RSC stream\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n void window.__VINEXT_RSC_NAVIGATE__(window.location.href, 0, \"refresh\");\n }\n },\n prefetch(href: string): void {\n if (isServer) return;\n // Prefetch the RSC payload for the target route and store in cache.\n // We must add to prefetchedUrls manually for deduplication.\n // prefetchRscResponse only manages the cache Map, not the URL set.\n const fullHref = toBrowserNavigationHref(href, window.location.href, __basePath);\n const rscUrl = toRscUrl(fullHref);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(rscUrl)) return;\n prefetched.add(rscUrl);\n prefetchRscResponse(\n rscUrl,\n fetch(rscUrl, {\n headers: { Accept: \"text/x-component\" },\n credentials: \"include\",\n priority: \"low\" as RequestInit[\"priority\"],\n }),\n );\n },\n};\n\n/**\n * App Router's useRouter — returns push/replace/back/forward/refresh.\n * Different from Pages Router's useRouter (next/router).\n *\n * Returns a stable singleton: the same object reference on every call,\n * matching Next.js behavior so components using referential equality\n * (e.g. useMemo / useEffect deps, React.memo) don't re-render unnecessarily.\n */\nexport function useRouter() {\n return _appRouter;\n}\n\n/**\n * Returns the active child segment one level below the layout where it's called.\n *\n * Returns the first segment from the route tree below this layout, including\n * route groups (e.g., \"(marketing)\") and resolved dynamic params. Returns null\n * if at the leaf (no child segments).\n *\n * @param parallelRoutesKey - Which parallel route to read (default: \"children\")\n */\nexport function useSelectedLayoutSegment(parallelRoutesKey?: string): string | null {\n const segments = useSelectedLayoutSegments(parallelRoutesKey);\n return segments.length > 0 ? segments[0] : null;\n}\n\n/**\n * Returns all active segments below the layout where it's called.\n *\n * Each layout in the App Router tree wraps its children with a\n * LayoutSegmentProvider whose value is a map of parallel route key to\n * segment arrays. The \"children\" key is the default parallel route.\n *\n * @param parallelRoutesKey - Which parallel route to read (default: \"children\")\n */\nexport function useSelectedLayoutSegments(parallelRoutesKey?: string): string[] {\n return useChildSegments(parallelRoutesKey);\n}\n\nexport { ReadonlyURLSearchParams };\n\n/**\n * useServerInsertedHTML — inject HTML during SSR from client components.\n *\n * Used by CSS-in-JS libraries (styled-components, emotion, StyleX) to inject\n * <style> tags during SSR so styles appear in the initial HTML (no FOUC).\n *\n * The callback is called once after each SSR render pass. The returned JSX/HTML\n * is serialized and injected into the HTML stream.\n *\n * Usage (in a \"use client\" component wrapping children):\n * useServerInsertedHTML(() => {\n * const styles = sheet.getStyleElement();\n * sheet.instance.clearTag();\n * return <>{styles}</>;\n * });\n */\n\nexport function useServerInsertedHTML(callback: () => unknown): void {\n if (typeof document !== \"undefined\") {\n // Client-side: no-op (styles are already in the DOM)\n return;\n }\n _getInsertedHTMLCallbacks().push(callback);\n}\n\n/**\n * Flush all collected useServerInsertedHTML callbacks.\n * Returns an array of results (React elements or strings).\n * Clears the callback list so the next render starts fresh.\n *\n * Called by the SSR entry after renderToReadableStream completes.\n */\nexport function flushServerInsertedHTML(): unknown[] {\n const callbacks = _getInsertedHTMLCallbacks();\n const results: unknown[] = [];\n for (const cb of callbacks) {\n try {\n const result = cb();\n if (result != null) results.push(result);\n } catch {\n // Ignore errors from individual callbacks\n }\n }\n callbacks.length = 0;\n return results;\n}\n\n/**\n * Clear all collected useServerInsertedHTML callbacks without flushing.\n * Used for cleanup between requests.\n */\nexport function clearServerInsertedHTML(): void {\n _clearInsertedHTMLCallbacks();\n}\n\n// ---------------------------------------------------------------------------\n// Non-hook utilities (can be called from Server Components)\n// ---------------------------------------------------------------------------\n\n/**\n * HTTP Access Fallback error code — shared prefix for notFound/forbidden/unauthorized.\n * Matches Next.js 16's unified error handling approach.\n */\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = \"NEXT_HTTP_ERROR_FALLBACK\";\n\n/**\n * Check if an error is an HTTP Access Fallback error (notFound, forbidden, unauthorized).\n */\nexport function isHTTPAccessFallbackError(error: unknown): boolean {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String((error as { digest: unknown }).digest);\n return (\n digest === \"NEXT_NOT_FOUND\" || // legacy compat\n digest.startsWith(`${HTTP_ERROR_FALLBACK_ERROR_CODE};`)\n );\n }\n return false;\n}\n\n/**\n * Extract the HTTP status code from an HTTP Access Fallback error.\n * Returns 404 for legacy NEXT_NOT_FOUND errors.\n */\nexport function getAccessFallbackHTTPStatus(error: unknown): number {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String((error as { digest: unknown }).digest);\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(`${HTTP_ERROR_FALLBACK_ERROR_CODE};`)) {\n return parseInt(digest.split(\";\")[1], 10);\n }\n }\n return 404;\n}\n\n/**\n * Enum matching Next.js RedirectType for type-safe redirect calls.\n */\nexport enum RedirectType {\n push = \"push\",\n replace = \"replace\",\n}\n\n/**\n * Internal error class used by redirect/notFound/forbidden/unauthorized.\n * The `digest` field is the serialised control-flow signal read by the\n * framework's error boundary and server-side request handlers.\n */\nclass VinextNavigationError extends Error {\n readonly digest: string;\n constructor(message: string, digest: string) {\n super(message);\n this.digest = digest;\n }\n}\n\n/**\n * Throw a redirect. Caught by the framework to send a redirect response.\n */\nexport function redirect(url: string, type?: \"replace\" | \"push\" | RedirectType): never {\n throw new VinextNavigationError(\n `NEXT_REDIRECT:${url}`,\n `NEXT_REDIRECT;${type ?? \"replace\"};${encodeURIComponent(url)}`,\n );\n}\n\n/**\n * Trigger a permanent redirect (308).\n */\nexport function permanentRedirect(url: string): never {\n throw new VinextNavigationError(\n `NEXT_REDIRECT:${url}`,\n `NEXT_REDIRECT;replace;${encodeURIComponent(url)};308`,\n );\n}\n\n/**\n * Trigger a not-found response (404). Caught by the framework.\n */\nexport function notFound(): never {\n throw new VinextNavigationError(\"NEXT_NOT_FOUND\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`);\n}\n\n/**\n * Trigger a forbidden response (403). Caught by the framework.\n * In Next.js, this is gated behind experimental.authInterrupts — we\n * support it unconditionally for maximum compatibility.\n */\nexport function forbidden(): never {\n throw new VinextNavigationError(\"NEXT_FORBIDDEN\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`);\n}\n\n/**\n * Trigger an unauthorized response (401). Caught by the framework.\n * In Next.js, this is gated behind experimental.authInterrupts — we\n * support it unconditionally for maximum compatibility.\n */\nexport function unauthorized(): never {\n throw new VinextNavigationError(\"NEXT_UNAUTHORIZED\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n// Listen for popstate on the client\nif (!isServer) {\n const state = getClientNavigationState();\n if (state && !state.patchInstalled) {\n state.patchInstalled = true;\n\n // Listen for popstate on the client.\n // Note: This handler runs for Pages Router only (when __VINEXT_RSC_NAVIGATE__\n // is not available). It restores scroll position with microtask-based deferral.\n // App Router scroll restoration is handled in server/app-browser-entry.ts:697\n // with RSC navigation coordination (waits for pending navigation to settle).\n window.addEventListener(\"popstate\", (event) => {\n if (typeof window.__VINEXT_RSC_NAVIGATE__ !== \"function\") {\n commitClientNavigationState();\n restoreScrollPosition(event.state);\n }\n });\n\n window.history.pushState = function patchedPushState(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n ): void {\n state.originalPushState.call(window.history, data, unused, url);\n if (state.suppressUrlNotifyCount === 0) {\n commitClientNavigationState();\n }\n };\n\n window.history.replaceState = function patchedReplaceState(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n ): void {\n state.originalReplaceState.call(window.history, data, unused, url);\n if (state.suppressUrlNotifyCount === 0) {\n commitClientNavigationState();\n }\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAM,0BAA0B,OAAO,IAAI,8BAA8B;AACzE,MAAM,gCAAgC,OAAO,IAAI,mCAAmC;AAiCpF,SAAS,+BAEA;AACP,KAAI,OAAOA,QAAM,kBAAkB,WAAY,QAAO;CAEtD,MAAM,cAAc;AACpB,KAAI,CAAC,YAAY,+BACf,aAAY,iCAAiCA,QAAM,cAEjD,KAAK;AAGT,QAAO,YAAY,kCAAkC;;AAGvD,MAAa,4BAEF,8BAA8B;;;;;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SAAS,CAAC,MAAM,gBAAgB;AAClC,QAAM,iBAAiB;AAOvB,SAAO,iBAAiB,aAAa,UAAU;AAC7C,OAAI,OAAO,OAAO,4BAA4B,YAAY;AACxD,iCAA6B;AAC7B,0BAAsB,MAAM,MAAM;;IAEpC;AAEF,SAAO,QAAQ,YAAY,SAAS,iBAClC,MACA,QACA,KACM;AACN,SAAM,kBAAkB,KAAK,OAAO,SAAS,MAAM,QAAQ,IAAI;AAC/D,OAAI,MAAM,2BAA2B,EACnC,8BAA6B;;AAIjC,SAAO,QAAQ,eAAe,SAAS,oBACrC,MACA,QACA,KACM;AACN,SAAM,qBAAqB,KAAK,OAAO,SAAS,MAAM,QAAQ,IAAI;AAClE,OAAI,MAAM,2BAA2B,EACnC,8BAA6B"}
|
|
1
|
+
{"version":3,"file":"navigation.js","names":["React"],"sources":["../../src/shims/navigation.ts"],"sourcesContent":["/**\n * next/navigation shim\n *\n * App Router navigation hooks. These work on both server (RSC) and client.\n * Server-side: reads from a request context set by the RSC handler.\n * Client-side: reads from browser Location API and provides navigation.\n */\n\n// Use namespace import for RSC safety: the react-server condition doesn't export\n// createContext/useContext/useSyncExternalStore as named exports, and strict ESM\n// would throw at link time for missing bindings. With `import * as React`, the\n// bindings are just `undefined` on the namespace object and we can guard at runtime.\nimport * as React from \"react\";\nimport { notifyAppRouterTransitionStart } from \"../client/instrumentation-client-state.js\";\nimport { toBrowserNavigationHref, toSameOriginAppPath } from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { ReadonlyURLSearchParams } from \"./readonly-url-search-params.js\";\n\n// ─── Layout segment context ───────────────────────────────────────────────────\n// Stores the child segments below the current layout. Each layout wraps its\n// children with a provider whose value is the remaining route tree segments\n// (including route groups, with dynamic params resolved to actual values).\n// Created lazily because `React.createContext` is NOT available in the\n// react-server condition of React. In the RSC environment, this remains null.\n// The shared context lives behind a global singleton so provider/hook pairs\n// still line up if Vite loads this shim through multiple resolved module IDs.\nconst _LAYOUT_SEGMENT_CTX_KEY = Symbol.for(\"vinext.layoutSegmentContext\");\nconst _SERVER_INSERTED_HTML_CTX_KEY = Symbol.for(\"vinext.serverInsertedHTMLContext\");\n\n/**\n * Map of parallel route key → child segments below the current layout.\n * The \"children\" key is always present (the default parallel route).\n * Named parallel routes add their own keys (e.g., \"team\", \"analytics\").\n *\n * Arrays are mutable (`string[]`) to match Next.js's public API return type\n * without requiring `as` casts. The map itself is Readonly — no key addition.\n */\nexport type SegmentMap = Readonly<Record<string, string[]>> & { readonly children: string[] };\n\ntype _LayoutSegmentGlobal = typeof globalThis & {\n [_LAYOUT_SEGMENT_CTX_KEY]?: React.Context<SegmentMap> | null;\n [_SERVER_INSERTED_HTML_CTX_KEY]?: React.Context<\n ((callback: () => unknown) => void) | null\n > | null;\n};\n\n// ─── ServerInsertedHTML context ────────────────────────────────────────────────\n// Used by CSS-in-JS libraries (Apollo Client, styled-components, emotion) to\n// register HTML injection callbacks during SSR via useContext().\n// The SSR entry wraps the rendered tree with a Provider whose value is a\n// callback registration function (useServerInsertedHTML).\n//\n// In Next.js, ServerInsertedHTMLContext holds a function:\n// (callback: () => React.ReactNode) => void\n// Libraries call useContext(ServerInsertedHTMLContext) to get this function,\n// then call it to register callbacks that inject HTML during SSR.\n//\n// Created eagerly at module load time. In the RSC environment (react-server\n// condition), createContext isn't available so this will be null.\n\nfunction getServerInsertedHTMLContext(): React.Context<\n ((callback: () => unknown) => void) | null\n> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _LayoutSegmentGlobal;\n if (!globalState[_SERVER_INSERTED_HTML_CTX_KEY]) {\n globalState[_SERVER_INSERTED_HTML_CTX_KEY] = React.createContext<\n ((callback: () => unknown) => void) | null\n >(null);\n }\n\n return globalState[_SERVER_INSERTED_HTML_CTX_KEY] ?? null;\n}\n\nexport const ServerInsertedHTMLContext: React.Context<\n ((callback: () => unknown) => void) | null\n> | null = getServerInsertedHTMLContext();\n\n/**\n * Get or create the layout segment context.\n * Returns null in the RSC environment (createContext unavailable).\n */\nexport function getLayoutSegmentContext(): React.Context<SegmentMap> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _LayoutSegmentGlobal;\n if (!globalState[_LAYOUT_SEGMENT_CTX_KEY]) {\n globalState[_LAYOUT_SEGMENT_CTX_KEY] = React.createContext<SegmentMap>({ children: [] });\n }\n\n return globalState[_LAYOUT_SEGMENT_CTX_KEY] ?? null;\n}\n\n/**\n * Read the child segments for a parallel route below the current layout.\n * Returns [] if no context is available (RSC environment, outside React tree)\n * or if the requested key is not present in the segment map.\n */\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\nfunction useChildSegments(parallelRoutesKey: string = \"children\"): string[] {\n const ctx = getLayoutSegmentContext();\n if (!ctx) return [];\n // useContext is safe here because if createContext exists, useContext does too.\n // This branch is only taken in SSR/Browser, never in RSC.\n // Try/catch for unit tests that call this hook outside a React render tree.\n try {\n const segmentMap = React.useContext(ctx);\n return segmentMap[parallelRoutesKey] ?? [];\n } catch {\n return [];\n }\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n// ---------------------------------------------------------------------------\n// Server-side request context (set by the RSC entry before rendering)\n// ---------------------------------------------------------------------------\n\nexport type NavigationContext = {\n pathname: string;\n searchParams: URLSearchParams;\n params: Record<string, string | string[]>;\n};\n\nconst _READONLY_SEARCH_PARAMS = Symbol(\"vinext.navigation.readonlySearchParams\");\nconst _READONLY_SEARCH_PARAMS_SOURCE = Symbol(\"vinext.navigation.readonlySearchParamsSource\");\n\ntype NavigationContextWithReadonlyCache = NavigationContext & {\n [_READONLY_SEARCH_PARAMS]?: ReadonlyURLSearchParams;\n [_READONLY_SEARCH_PARAMS_SOURCE]?: URLSearchParams;\n};\n\n// ---------------------------------------------------------------------------\n// Server-side navigation state lives in a separate server-only module\n// (navigation-state.ts) that uses AsyncLocalStorage for request isolation.\n// This module is bundled for the browser, so it can't import node:async_hooks.\n//\n// On the server: state functions are set by navigation-state.ts at import time.\n// On the client: _serverContext falls back to null (hooks use window instead).\n//\n// Global accessor pattern (issue #688):\n// Vite's multi-environment dev mode can create separate module instances of\n// this file for the SSR entry vs \"use client\" components. When that happens,\n// _registerStateAccessors only updates the SSR entry's instance, leaving the\n// \"use client\" instance with the default (null) fallbacks.\n//\n// To fix this, navigation-state.ts also stores the accessors on globalThis\n// via Symbol.for, and the defaults here check for that global before falling\n// back to module-level state. This ensures all module instances can reach the\n// ALS-backed state regardless of which instance was registered.\n// ---------------------------------------------------------------------------\n\ntype _StateAccessors = {\n getServerContext: () => NavigationContext | null;\n setServerContext: (ctx: NavigationContext | null) => void;\n getInsertedHTMLCallbacks: () => Array<() => unknown>;\n clearInsertedHTMLCallbacks: () => void;\n};\n\nexport const GLOBAL_ACCESSORS_KEY = Symbol.for(\"vinext.navigation.globalAccessors\");\nconst _GLOBAL_ACCESSORS_KEY = GLOBAL_ACCESSORS_KEY;\ntype _GlobalWithAccessors = typeof globalThis & { [_GLOBAL_ACCESSORS_KEY]?: _StateAccessors };\n\nfunction _getGlobalAccessors(): _StateAccessors | undefined {\n return (globalThis as _GlobalWithAccessors)[_GLOBAL_ACCESSORS_KEY];\n}\n\nlet _serverContext: NavigationContext | null = null;\nlet _serverInsertedHTMLCallbacks: Array<() => unknown> = [];\n\n// These are overridden by navigation-state.ts on the server to use ALS.\n// The defaults check globalThis for cross-module-instance access (issue #688).\nlet _getServerContext = (): NavigationContext | null => {\n const g = _getGlobalAccessors();\n return g ? g.getServerContext() : _serverContext;\n};\nlet _setServerContext = (ctx: NavigationContext | null): void => {\n const g = _getGlobalAccessors();\n if (g) {\n g.setServerContext(ctx);\n } else {\n _serverContext = ctx;\n }\n};\nlet _getInsertedHTMLCallbacks = (): Array<() => unknown> => {\n const g = _getGlobalAccessors();\n return g ? g.getInsertedHTMLCallbacks() : _serverInsertedHTMLCallbacks;\n};\nlet _clearInsertedHTMLCallbacks = (): void => {\n const g = _getGlobalAccessors();\n if (g) {\n g.clearInsertedHTMLCallbacks();\n } else {\n _serverInsertedHTMLCallbacks = [];\n }\n};\n\n/**\n * Register ALS-backed state accessors. Called by navigation-state.ts on import.\n * @internal\n */\nexport function _registerStateAccessors(accessors: _StateAccessors): void {\n _getServerContext = accessors.getServerContext;\n _setServerContext = accessors.setServerContext;\n _getInsertedHTMLCallbacks = accessors.getInsertedHTMLCallbacks;\n _clearInsertedHTMLCallbacks = accessors.clearInsertedHTMLCallbacks;\n}\n\n/**\n * Get the navigation context for the current SSR/RSC render.\n * Reads from AsyncLocalStorage when available (concurrent-safe),\n * otherwise falls back to module-level state.\n */\nexport function getNavigationContext(): NavigationContext | null {\n return _getServerContext();\n}\n\n/**\n * Set the navigation context for the current SSR/RSC render.\n * Called by the framework entry before rendering each request.\n */\nexport function setNavigationContext(ctx: NavigationContext | null): void {\n _setServerContext(ctx);\n}\n\n// ---------------------------------------------------------------------------\n// Client-side state\n// ---------------------------------------------------------------------------\n\nconst isServer = typeof window === \"undefined\";\n\n/** basePath from next.config.js, injected by the plugin at build time */\nexport const __basePath: string = process.env.__NEXT_ROUTER_BASEPATH ?? \"\";\n\n// ---------------------------------------------------------------------------\n// RSC prefetch cache utilities (shared between link.tsx and browser entry)\n// ---------------------------------------------------------------------------\n\n/** Maximum number of entries in the RSC prefetch cache. */\nexport const MAX_PREFETCH_CACHE_SIZE = 50;\n\n/** TTL for prefetch cache entries in ms (matches Next.js static prefetch TTL). */\nexport const PREFETCH_CACHE_TTL = 30_000;\n\n/** A buffered RSC response stored as an ArrayBuffer for replay. */\nexport type CachedRscResponse = {\n buffer: ArrayBuffer;\n contentType: string;\n paramsHeader: string | null;\n url: string;\n};\n\nexport type PrefetchCacheEntry = {\n snapshot?: CachedRscResponse;\n pending?: Promise<void>;\n timestamp: number;\n};\n\n/**\n * Convert a pathname (with optional query/hash) to its .rsc URL.\n * Strips trailing slashes before appending `.rsc` so that cache keys\n * are consistent regardless of the `trailingSlash` config setting.\n */\nexport function toRscUrl(href: string): string {\n const [beforeHash] = href.split(\"#\");\n const qIdx = beforeHash.indexOf(\"?\");\n const pathname = qIdx === -1 ? beforeHash : beforeHash.slice(0, qIdx);\n const query = qIdx === -1 ? \"\" : beforeHash.slice(qIdx);\n // Strip trailing slash (but preserve \"/\" root) for consistent cache keys\n const normalizedPath =\n pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n return normalizedPath + \".rsc\" + query;\n}\n\n/** Get or create the shared in-memory RSC prefetch cache on window. */\nexport function getPrefetchCache(): Map<string, PrefetchCacheEntry> {\n if (isServer) return new Map();\n if (!window.__VINEXT_RSC_PREFETCH_CACHE__) {\n window.__VINEXT_RSC_PREFETCH_CACHE__ = new Map<string, PrefetchCacheEntry>();\n }\n return window.__VINEXT_RSC_PREFETCH_CACHE__;\n}\n\n/**\n * Get or create the shared set of already-prefetched RSC URLs on window.\n * Keyed by rscUrl so that the browser entry can clear entries when consumed.\n */\nexport function getPrefetchedUrls(): Set<string> {\n if (isServer) return new Set();\n if (!window.__VINEXT_RSC_PREFETCHED_URLS__) {\n window.__VINEXT_RSC_PREFETCHED_URLS__ = new Set<string>();\n }\n return window.__VINEXT_RSC_PREFETCHED_URLS__;\n}\n\n/**\n * Evict prefetch cache entries if at capacity.\n * First sweeps expired entries, then falls back to FIFO eviction.\n */\nfunction evictPrefetchCacheIfNeeded(): void {\n const cache = getPrefetchCache();\n if (cache.size < MAX_PREFETCH_CACHE_SIZE) return;\n\n const now = Date.now();\n const prefetched = getPrefetchedUrls();\n\n for (const [key, entry] of cache) {\n if (now - entry.timestamp >= PREFETCH_CACHE_TTL) {\n cache.delete(key);\n prefetched.delete(key);\n }\n }\n\n while (cache.size >= MAX_PREFETCH_CACHE_SIZE) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) {\n cache.delete(oldest);\n prefetched.delete(oldest);\n } else {\n break;\n }\n }\n}\n\n/**\n * Store a prefetched RSC response in the cache by snapshotting it to an\n * ArrayBuffer. The snapshot completes asynchronously; during that window\n * the entry is marked `pending` so consumePrefetchResponse() will skip it\n * (the caller falls back to a fresh fetch, which is acceptable).\n *\n * Prefer prefetchRscResponse() for new call-sites — it handles the full\n * prefetch lifecycle including dedup. storePrefetchResponse() is kept for\n * backward compatibility and test helpers.\n *\n * NB: Caller is responsible for managing getPrefetchedUrls() — this\n * function only stores the response in the prefetch cache.\n */\nexport function storePrefetchResponse(rscUrl: string, response: Response): void {\n evictPrefetchCacheIfNeeded();\n const entry: PrefetchCacheEntry = { timestamp: Date.now() };\n entry.pending = snapshotRscResponse(response)\n .then((snapshot) => {\n entry.snapshot = snapshot;\n })\n .catch(() => {\n getPrefetchCache().delete(rscUrl);\n })\n .finally(() => {\n entry.pending = undefined;\n });\n getPrefetchCache().set(rscUrl, entry);\n}\n\n/**\n * Snapshot an RSC response to an ArrayBuffer for caching and replay.\n * Consumes the response body and stores it with content-type and URL metadata.\n */\nexport async function snapshotRscResponse(response: Response): Promise<CachedRscResponse> {\n const buffer = await response.arrayBuffer();\n return {\n buffer,\n contentType: response.headers.get(\"content-type\") ?? \"text/x-component\",\n paramsHeader: response.headers.get(\"X-Vinext-Params\"),\n url: response.url,\n };\n}\n\n/**\n * Reconstruct a Response from a cached RSC snapshot.\n * Creates a new Response with the original ArrayBuffer so createFromFetch\n * can consume the stream from scratch.\n *\n * NOTE: The reconstructed Response always has `url === \"\"` — the Response\n * constructor does not accept a `url` option, and `response.url` is read-only\n * set by the fetch infrastructure. Callers that need the original URL should\n * read it from `cached.url` directly rather than from the restored Response.\n *\n * @param copy - When true (default), copies the ArrayBuffer so the cached\n * snapshot remains replayable (needed for the visited-response cache).\n * Pass false for single-consumption paths (e.g. prefetch cache entries\n * that are deleted after consumption) to avoid the extra allocation.\n */\nexport function restoreRscResponse(cached: CachedRscResponse, copy = true): Response {\n const headers = new Headers({ \"content-type\": cached.contentType });\n if (cached.paramsHeader != null) {\n headers.set(\"X-Vinext-Params\", cached.paramsHeader);\n }\n\n return new Response(copy ? cached.buffer.slice(0) : cached.buffer, {\n status: 200,\n headers,\n });\n}\n\n/**\n * Prefetch an RSC response and snapshot it for later consumption.\n * Stores the in-flight promise so immediate clicks can await it instead\n * of firing a duplicate fetch.\n * Enforces a maximum cache size to prevent unbounded memory growth on\n * link-heavy pages.\n */\nexport function prefetchRscResponse(rscUrl: string, fetchPromise: Promise<Response>): void {\n const cache = getPrefetchCache();\n const prefetched = getPrefetchedUrls();\n const now = Date.now();\n\n const entry: PrefetchCacheEntry = { timestamp: now };\n\n entry.pending = fetchPromise\n .then(async (response) => {\n if (response.ok) {\n entry.snapshot = await snapshotRscResponse(response);\n } else {\n prefetched.delete(rscUrl);\n cache.delete(rscUrl);\n }\n })\n .catch(() => {\n prefetched.delete(rscUrl);\n cache.delete(rscUrl);\n })\n .finally(() => {\n entry.pending = undefined;\n });\n\n // Insert the new entry before evicting. FIFO evicts from the front of the\n // Map (oldest insertion order), so the just-appended entry is safe — only\n // entries inserted before it are candidates for removal.\n cache.set(rscUrl, entry);\n evictPrefetchCacheIfNeeded();\n}\n\n/**\n * Consume a prefetched response for a given rscUrl.\n * Only returns settled (non-pending) snapshots synchronously.\n * Returns null if the entry is still in flight or doesn't exist.\n */\nexport function consumePrefetchResponse(rscUrl: string): CachedRscResponse | null {\n const cache = getPrefetchCache();\n const entry = cache.get(rscUrl);\n if (!entry) return null;\n\n // Don't consume pending entries — let the navigation fetch independently.\n if (entry.pending) return null;\n\n cache.delete(rscUrl);\n getPrefetchedUrls().delete(rscUrl);\n\n if (entry.snapshot) {\n if (Date.now() - entry.timestamp >= PREFETCH_CACHE_TTL) {\n return null;\n }\n return entry.snapshot;\n }\n\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Client navigation state — stored on a Symbol.for global to survive\n// multiple Vite module instances loading this file through different IDs.\n// ---------------------------------------------------------------------------\n\ntype NavigationListener = () => void;\nconst _CLIENT_NAV_STATE_KEY = Symbol.for(\"vinext.clientNavigationState\");\n\ntype ClientNavigationState = {\n listeners: Set<NavigationListener>;\n cachedSearch: string;\n cachedReadonlySearchParams: ReadonlyURLSearchParams;\n cachedPathname: string;\n clientParams: Record<string, string | string[]>;\n clientParamsJson: string;\n pendingClientParams: Record<string, string | string[]> | null;\n pendingClientParamsJson: string | null;\n originalPushState: typeof window.history.pushState;\n originalReplaceState: typeof window.history.replaceState;\n patchInstalled: boolean;\n hasPendingNavigationUpdate: boolean;\n suppressUrlNotifyCount: number;\n navigationSnapshotActiveCount: number;\n};\n\ntype ClientNavigationGlobal = typeof globalThis & {\n [_CLIENT_NAV_STATE_KEY]?: ClientNavigationState;\n};\n\nfunction getClientNavigationState(): ClientNavigationState | null {\n if (isServer) return null;\n\n const globalState = window as ClientNavigationGlobal;\n globalState[_CLIENT_NAV_STATE_KEY] ??= {\n listeners: new Set<NavigationListener>(),\n cachedSearch: window.location.search,\n cachedReadonlySearchParams: new ReadonlyURLSearchParams(window.location.search),\n cachedPathname: stripBasePath(window.location.pathname, __basePath),\n clientParams: {},\n clientParamsJson: \"{}\",\n pendingClientParams: null,\n pendingClientParamsJson: null,\n // NB: These capture the currently installed history methods, not guaranteed\n // native ones. If a third-party library (analytics, router) has already patched\n // history methods before this module loads, we intentionally preserve that\n // wrapper. With Symbol.for global state, the first module instance to load wins.\n originalPushState: window.history.pushState.bind(window.history),\n originalReplaceState: window.history.replaceState.bind(window.history),\n patchInstalled: false,\n hasPendingNavigationUpdate: false,\n suppressUrlNotifyCount: 0,\n navigationSnapshotActiveCount: 0,\n };\n\n return globalState[_CLIENT_NAV_STATE_KEY]!;\n}\n\nfunction notifyNavigationListeners(): void {\n const state = getClientNavigationState();\n if (!state) return;\n for (const fn of state.listeners) fn();\n}\n\n// Cached URLSearchParams, pathname, etc. for referential stability\n// useSyncExternalStore compares snapshots with Object.is — avoid creating\n// new instances on every render (infinite re-renders).\nlet _cachedEmptyServerSearchParams: ReadonlyURLSearchParams | null = null;\n\n/**\n * Get cached pathname snapshot for useSyncExternalStore.\n * Note: Returns cached value from ClientNavigationState, not live window.location.\n * The cache is updated by syncCommittedUrlStateFromLocation() after navigation commits.\n * This ensures referential stability and prevents infinite re-renders.\n * External pushState/replaceState while URL notifications are suppressed won't\n * be visible until the next commit.\n */\nfunction getPathnameSnapshot(): string {\n return getClientNavigationState()?.cachedPathname ?? \"/\";\n}\n\nlet _cachedEmptyClientSearchParams: ReadonlyURLSearchParams | null = null;\n\n/**\n * Get cached search params snapshot for useSyncExternalStore.\n * Note: Returns cached value from ClientNavigationState, not live window.location.search.\n * The cache is updated by syncCommittedUrlStateFromLocation() after navigation commits.\n * This ensures referential stability and prevents infinite re-renders.\n * External pushState/replaceState while URL notifications are suppressed won't\n * be visible until the next commit.\n */\nfunction getSearchParamsSnapshot(): ReadonlyURLSearchParams {\n const cached = getClientNavigationState()?.cachedReadonlySearchParams;\n if (cached) return cached;\n if (_cachedEmptyClientSearchParams === null) {\n _cachedEmptyClientSearchParams = new ReadonlyURLSearchParams();\n }\n return _cachedEmptyClientSearchParams;\n}\n\nfunction syncCommittedUrlStateFromLocation(): boolean {\n const state = getClientNavigationState();\n if (!state) return false;\n\n let changed = false;\n\n const pathname = stripBasePath(window.location.pathname, __basePath);\n if (pathname !== state.cachedPathname) {\n state.cachedPathname = pathname;\n changed = true;\n }\n\n const search = window.location.search;\n if (search !== state.cachedSearch) {\n state.cachedSearch = search;\n state.cachedReadonlySearchParams = new ReadonlyURLSearchParams(search);\n changed = true;\n }\n\n return changed;\n}\n\nfunction getServerSearchParamsSnapshot(): ReadonlyURLSearchParams {\n const ctx = _getServerContext() as NavigationContextWithReadonlyCache | null;\n\n if (!ctx) {\n // No server context available - return cached empty instance\n if (_cachedEmptyServerSearchParams === null) {\n _cachedEmptyServerSearchParams = new ReadonlyURLSearchParams();\n }\n return _cachedEmptyServerSearchParams;\n }\n\n const source = ctx.searchParams;\n const cached = ctx[_READONLY_SEARCH_PARAMS];\n const cachedSource = ctx[_READONLY_SEARCH_PARAMS_SOURCE];\n\n // Return cached wrapper if source hasn't changed\n if (cached && cachedSource === source) {\n return cached;\n }\n\n // Create and cache new wrapper\n const readonly = new ReadonlyURLSearchParams(source);\n ctx[_READONLY_SEARCH_PARAMS] = readonly;\n ctx[_READONLY_SEARCH_PARAMS_SOURCE] = source;\n\n return readonly;\n}\n\n// ---------------------------------------------------------------------------\n// Navigation snapshot activation flag\n//\n// The render snapshot context provides pending URL values during transitions.\n// After the transition commits, the snapshot becomes stale and must NOT shadow\n// subsequent external URL changes (user pushState/replaceState). This flag\n// tracks whether a navigation transition is in progress — hooks only prefer\n// the snapshot while it's active.\n// ---------------------------------------------------------------------------\n\n/**\n * Mark a navigation snapshot as active. Called before startTransition\n * in renderNavigationPayload. While active, hooks prefer the snapshot\n * context value over useSyncExternalStore. Uses a counter (not boolean)\n * to handle overlapping navigations — rapid clicks can interleave\n * activate/deactivate if multiple transitions are in flight.\n */\nexport function activateNavigationSnapshot(): void {\n const state = getClientNavigationState();\n if (state) state.navigationSnapshotActiveCount++;\n}\n\n// Track client-side params (set during RSC hydration/navigation)\n// We cache the params object for referential stability — only create a new\n// object when the params actually change (shallow key/value comparison).\nconst _EMPTY_PARAMS: Record<string, string | string[]> = {};\n\n// ---------------------------------------------------------------------------\n// Client navigation render snapshot — provides pending URL values to hooks\n// during a startTransition so they see the destination, not the stale URL.\n// ---------------------------------------------------------------------------\n\nexport type ClientNavigationRenderSnapshot = {\n pathname: string;\n searchParams: ReadonlyURLSearchParams;\n params: Record<string, string | string[]>;\n};\n\nconst _CLIENT_NAV_RENDER_CTX_KEY = Symbol.for(\"vinext.clientNavigationRenderContext\");\ntype _ClientNavRenderGlobal = typeof globalThis & {\n [_CLIENT_NAV_RENDER_CTX_KEY]?: React.Context<ClientNavigationRenderSnapshot | null> | null;\n};\n\nexport function getClientNavigationRenderContext(): React.Context<ClientNavigationRenderSnapshot | null> | null {\n if (typeof React.createContext !== \"function\") return null;\n\n const globalState = globalThis as _ClientNavRenderGlobal;\n if (!globalState[_CLIENT_NAV_RENDER_CTX_KEY]) {\n globalState[_CLIENT_NAV_RENDER_CTX_KEY] =\n React.createContext<ClientNavigationRenderSnapshot | null>(null);\n }\n\n return globalState[_CLIENT_NAV_RENDER_CTX_KEY] ?? null;\n}\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\nfunction useClientNavigationRenderSnapshot(): ClientNavigationRenderSnapshot | null {\n const ctx = getClientNavigationRenderContext();\n if (!ctx || typeof React.useContext !== \"function\") return null;\n try {\n return React.useContext(ctx);\n } catch {\n return null;\n }\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\nexport function createClientNavigationRenderSnapshot(\n href: string,\n params: Record<string, string | string[]>,\n): ClientNavigationRenderSnapshot {\n const origin = typeof window !== \"undefined\" ? window.location.origin : \"http://localhost\";\n const url = new URL(href, origin);\n\n return {\n pathname: stripBasePath(url.pathname, __basePath),\n searchParams: new ReadonlyURLSearchParams(url.search),\n params,\n };\n}\n\n// Module-level fallback for environments without window (tests, SSR).\nlet _fallbackClientParams: Record<string, string | string[]> = _EMPTY_PARAMS;\nlet _fallbackClientParamsJson = \"{}\";\n\nexport function setClientParams(params: Record<string, string | string[]>): void {\n const state = getClientNavigationState();\n if (!state) {\n const json = JSON.stringify(params);\n if (json !== _fallbackClientParamsJson) {\n _fallbackClientParams = params;\n _fallbackClientParamsJson = json;\n }\n return;\n }\n\n const json = JSON.stringify(params);\n if (json !== state.clientParamsJson) {\n state.clientParams = params;\n state.clientParamsJson = json;\n state.pendingClientParams = null;\n state.pendingClientParamsJson = null;\n notifyNavigationListeners();\n }\n}\n\nexport function replaceClientParamsWithoutNotify(params: Record<string, string | string[]>): void {\n const state = getClientNavigationState();\n if (!state) return;\n\n const json = JSON.stringify(params);\n if (json !== state.clientParamsJson && json !== state.pendingClientParamsJson) {\n state.pendingClientParams = params;\n state.pendingClientParamsJson = json;\n state.hasPendingNavigationUpdate = true;\n }\n}\n\n/** Get the current client params (for testing referential stability). */\nexport function getClientParams(): Record<string, string | string[]> {\n return getClientNavigationState()?.clientParams ?? _fallbackClientParams;\n}\n\nfunction getClientParamsSnapshot(): Record<string, string | string[]> {\n return getClientNavigationState()?.clientParams ?? _EMPTY_PARAMS;\n}\n\nfunction getServerParamsSnapshot(): Record<string, string | string[]> {\n return _getServerContext()?.params ?? _EMPTY_PARAMS;\n}\n\nfunction subscribeToNavigation(cb: () => void): () => void {\n const state = getClientNavigationState();\n if (!state) return () => {};\n\n state.listeners.add(cb);\n return () => {\n state.listeners.delete(cb);\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hooks\n// ---------------------------------------------------------------------------\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the current pathname.\n * Server: from request context. Client: from window.location.\n */\nexport function usePathname(): string {\n if (isServer) {\n // During SSR of \"use client\" components, the navigation context may not be set.\n // Return a safe fallback — the client will hydrate with the real value.\n return _getServerContext()?.pathname ?? \"/\";\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n // Client-side: use the hook system for reactivity\n const pathname = React.useSyncExternalStore(\n subscribeToNavigation,\n getPathnameSnapshot,\n () => _getServerContext()?.pathname ?? \"/\",\n );\n // Prefer the render snapshot during an active navigation transition so\n // hooks return the pending URL, not the stale committed one. After commit,\n // fall through to useSyncExternalStore so user pushState/replaceState\n // calls are immediately reflected.\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.pathname;\n }\n return pathname;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the current search params as a read-only URLSearchParams.\n */\nexport function useSearchParams(): ReadonlyURLSearchParams {\n if (isServer) {\n // During SSR for \"use client\" components, the navigation context may not be set.\n // Return a safe fallback — the client will hydrate with the real value.\n return getServerSearchParamsSnapshot();\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n const searchParams = React.useSyncExternalStore(\n subscribeToNavigation,\n getSearchParamsSnapshot,\n getServerSearchParamsSnapshot,\n );\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.searchParams;\n }\n return searchParams;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/* oxlint-disable eslint-plugin-react-hooks/rules-of-hooks */\n/**\n * Returns the dynamic params for the current route.\n */\nexport function useParams<\n T extends Record<string, string | string[]> = Record<string, string | string[]>,\n>(): T {\n if (isServer) {\n // During SSR for \"use client\" components, the navigation context may not be set.\n return (_getServerContext()?.params ?? _EMPTY_PARAMS) as T;\n }\n const renderSnapshot = useClientNavigationRenderSnapshot();\n const params = React.useSyncExternalStore(\n subscribeToNavigation,\n getClientParamsSnapshot as () => T,\n getServerParamsSnapshot as () => T,\n );\n if (renderSnapshot && (getClientNavigationState()?.navigationSnapshotActiveCount ?? 0) > 0) {\n return renderSnapshot.params as T;\n }\n return params;\n}\n/* oxlint-enable eslint-plugin-react-hooks/rules-of-hooks */\n\n/**\n * Check if a href is an external URL (any URL scheme per RFC 3986, or protocol-relative).\n */\nfunction isExternalUrl(href: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith(\"//\");\n}\n\n/**\n * Check if a href is only a hash change relative to the current URL.\n */\nfunction isHashOnlyChange(href: string): boolean {\n if (typeof window === \"undefined\") return false;\n if (href.startsWith(\"#\")) return true;\n try {\n const current = new URL(window.location.href);\n const next = new URL(href, window.location.href);\n // Strip basePath from both pathnames for consistent comparison\n // (matches how isSameRoute handles basePath in app-browser-entry.ts)\n const strippedCurrentPath = stripBasePath(current.pathname, __basePath);\n const strippedNextPath = stripBasePath(next.pathname, __basePath);\n return (\n strippedCurrentPath === strippedNextPath && current.search === next.search && next.hash !== \"\"\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Scroll to a hash target element, or to the top if no hash.\n */\nfunction scrollToHash(hash: string): void {\n if (!hash || hash === \"#\") {\n window.scrollTo(0, 0);\n return;\n }\n const id = hash.slice(1);\n const element = document.getElementById(id);\n if (element) {\n element.scrollIntoView({ behavior: \"auto\" });\n }\n}\n\n// ---------------------------------------------------------------------------\n// History method wrappers — suppress notifications for internal updates\n// ---------------------------------------------------------------------------\n\nfunction withSuppressedUrlNotifications<T>(fn: () => T): T {\n const state = getClientNavigationState();\n if (!state) {\n return fn();\n }\n\n state.suppressUrlNotifyCount += 1;\n try {\n return fn();\n } finally {\n state.suppressUrlNotifyCount -= 1;\n }\n}\n\nexport function commitClientNavigationState(): void {\n if (isServer) return;\n const state = getClientNavigationState();\n if (!state) return;\n\n // Only decrement the snapshot counter if a snapshot was previously activated.\n // Several code paths call commit without a prior activateNavigationSnapshot()\n // — hash-only changes (navigateClientSide), Pages Router popstate, and\n // patched history.pushState/replaceState — which legitimately have count == 0.\n if (state.navigationSnapshotActiveCount > 0) {\n state.navigationSnapshotActiveCount -= 1;\n }\n\n const urlChanged = syncCommittedUrlStateFromLocation();\n if (state.pendingClientParams !== null && state.pendingClientParamsJson !== null) {\n state.clientParams = state.pendingClientParams;\n state.clientParamsJson = state.pendingClientParamsJson;\n state.pendingClientParams = null;\n state.pendingClientParamsJson = null;\n }\n const shouldNotify = urlChanged || state.hasPendingNavigationUpdate;\n state.hasPendingNavigationUpdate = false;\n\n if (shouldNotify) {\n notifyNavigationListeners();\n }\n}\n\nexport function pushHistoryStateWithoutNotify(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n): void {\n withSuppressedUrlNotifications(() => {\n const state = getClientNavigationState();\n state?.originalPushState.call(window.history, data, unused, url);\n });\n}\n\nexport function replaceHistoryStateWithoutNotify(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n): void {\n withSuppressedUrlNotifications(() => {\n const state = getClientNavigationState();\n state?.originalReplaceState.call(window.history, data, unused, url);\n });\n}\n\n/**\n * Save the current scroll position into the current history state.\n * Called before every navigation to enable scroll restoration on back/forward.\n *\n * Uses replaceHistoryStateWithoutNotify to avoid triggering the patched\n * history.replaceState interception (which would cause spurious re-renders).\n */\nfunction saveScrollPosition(): void {\n const state = window.history.state ?? {};\n replaceHistoryStateWithoutNotify(\n { ...state, __vinext_scrollX: window.scrollX, __vinext_scrollY: window.scrollY },\n \"\",\n );\n}\n\n/**\n * Restore scroll position from a history state object (used on popstate).\n *\n * When an RSC navigation is in flight (back/forward triggers both this\n * handler and the browser entry's popstate handler which calls\n * __VINEXT_RSC_NAVIGATE__), we must wait for the new content to render\n * before scrolling. Otherwise the user sees old content flash at the\n * restored scroll position.\n *\n * This handler fires before the browser entry's popstate handler (because\n * navigation.ts is loaded before hydration completes), so we defer via a\n * microtask to give the browser entry handler a chance to set\n * __VINEXT_RSC_PENDING__. Promise.resolve() schedules a microtask\n * that runs after all synchronous event listeners have completed.\n */\nfunction restoreScrollPosition(state: unknown): void {\n if (state && typeof state === \"object\" && \"__vinext_scrollY\" in state) {\n const { __vinext_scrollX: x, __vinext_scrollY: y } = state as {\n __vinext_scrollX: number;\n __vinext_scrollY: number;\n };\n\n // Defer to allow other popstate listeners (browser entry) to run first\n // and set __VINEXT_RSC_PENDING__. Promise.resolve() schedules a microtask\n // that runs after all synchronous event listeners have completed.\n void Promise.resolve().then(() => {\n const pending: Promise<void> | null = window.__VINEXT_RSC_PENDING__ ?? null;\n\n if (pending) {\n // Wait for the RSC navigation to finish rendering, then scroll.\n void pending.then(() => {\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n });\n } else {\n // No RSC navigation in flight (Pages Router or already settled).\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n }\n });\n }\n}\n\n/**\n * Navigate to a URL, handling external URLs, hash-only changes, and RSC navigation.\n */\nexport async function navigateClientSide(\n href: string,\n mode: \"push\" | \"replace\",\n scroll: boolean,\n): Promise<void> {\n // Normalize same-origin absolute URLs to local paths for SPA navigation\n let normalizedHref = href;\n if (isExternalUrl(href)) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) {\n // Truly external: use full page navigation\n if (mode === \"replace\") {\n window.location.replace(href);\n } else {\n window.location.assign(href);\n }\n return;\n }\n normalizedHref = localPath;\n }\n\n const fullHref = toBrowserNavigationHref(normalizedHref, window.location.href, __basePath);\n // Match Next.js: App Router reports navigation start before dispatching,\n // including hash-only navigations that short-circuit after URL update.\n notifyAppRouterTransitionStart(fullHref, mode);\n\n // Save scroll position before navigating (for back/forward restoration)\n if (mode === \"push\") {\n saveScrollPosition();\n }\n\n // Hash-only change: update URL and scroll to target, skip RSC fetch\n if (isHashOnlyChange(fullHref)) {\n const hash = fullHref.includes(\"#\") ? fullHref.slice(fullHref.indexOf(\"#\")) : \"\";\n if (mode === \"replace\") {\n replaceHistoryStateWithoutNotify(null, \"\", fullHref);\n } else {\n pushHistoryStateWithoutNotify(null, \"\", fullHref);\n }\n commitClientNavigationState();\n if (scroll) {\n scrollToHash(hash);\n }\n return;\n }\n\n // Extract hash for post-navigation scrolling\n const hashIdx = fullHref.indexOf(\"#\");\n const hash = hashIdx !== -1 ? fullHref.slice(hashIdx) : \"\";\n\n // Trigger RSC re-fetch if available, and wait for the new content to render\n // before scrolling. This prevents the old page from visibly jumping to the\n // top before the new content paints.\n //\n // History is NOT pushed here for RSC navigations — the commit effect inside\n // navigateRsc owns the push/replace exclusively. This avoids a fragile\n // double-push and ensures window.location still reflects the *current* URL\n // when navigateRsc computes isSameRoute (cross-route vs same-route).\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n await window.__VINEXT_RSC_NAVIGATE__(fullHref, 0, \"navigate\", mode);\n } else {\n if (mode === \"replace\") {\n replaceHistoryStateWithoutNotify(null, \"\", fullHref);\n } else {\n pushHistoryStateWithoutNotify(null, \"\", fullHref);\n }\n commitClientNavigationState();\n }\n\n if (scroll) {\n if (hash) {\n scrollToHash(hash);\n } else {\n window.scrollTo(0, 0);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// App Router router singleton\n//\n// All methods close over module-level state (navigateClientSide, withBasePath, etc.)\n// and carry no per-render data, so the object can be created once and reused.\n// Next.js returns the same router reference on every call to useRouter(), which\n// matters for components that rely on referential equality (e.g. useMemo /\n// useEffect dependency arrays, React.memo bailouts).\n// ---------------------------------------------------------------------------\n\nconst _appRouter = {\n push(href: string, options?: { scroll?: boolean }): void {\n if (isServer) return;\n void navigateClientSide(href, \"push\", options?.scroll !== false);\n },\n replace(href: string, options?: { scroll?: boolean }): void {\n if (isServer) return;\n void navigateClientSide(href, \"replace\", options?.scroll !== false);\n },\n back(): void {\n if (isServer) return;\n window.history.back();\n },\n forward(): void {\n if (isServer) return;\n window.history.forward();\n },\n refresh(): void {\n if (isServer) return;\n // Re-fetch the current page's RSC stream\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n void window.__VINEXT_RSC_NAVIGATE__(window.location.href, 0, \"refresh\");\n }\n },\n prefetch(href: string): void {\n if (isServer) return;\n // Prefetch the RSC payload for the target route and store in cache.\n // We must add to prefetchedUrls manually for deduplication.\n // prefetchRscResponse only manages the cache Map, not the URL set.\n const fullHref = toBrowserNavigationHref(href, window.location.href, __basePath);\n const rscUrl = toRscUrl(fullHref);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(rscUrl)) return;\n prefetched.add(rscUrl);\n prefetchRscResponse(\n rscUrl,\n fetch(rscUrl, {\n headers: { Accept: \"text/x-component\" },\n credentials: \"include\",\n priority: \"low\" as RequestInit[\"priority\"],\n }),\n );\n },\n};\n\n/**\n * App Router's useRouter — returns push/replace/back/forward/refresh.\n * Different from Pages Router's useRouter (next/router).\n *\n * Returns a stable singleton: the same object reference on every call,\n * matching Next.js behavior so components using referential equality\n * (e.g. useMemo / useEffect deps, React.memo) don't re-render unnecessarily.\n */\nexport function useRouter() {\n return _appRouter;\n}\n\n/**\n * Returns the active child segment one level below the layout where it's called.\n *\n * Returns the first segment from the route tree below this layout, including\n * route groups (e.g., \"(marketing)\") and resolved dynamic params. Returns null\n * if at the leaf (no child segments).\n *\n * @param parallelRoutesKey - Which parallel route to read (default: \"children\")\n */\nexport function useSelectedLayoutSegment(parallelRoutesKey?: string): string | null {\n const segments = useSelectedLayoutSegments(parallelRoutesKey);\n return segments.length > 0 ? segments[0] : null;\n}\n\n/**\n * Returns all active segments below the layout where it's called.\n *\n * Each layout in the App Router tree wraps its children with a\n * LayoutSegmentProvider whose value is a map of parallel route key to\n * segment arrays. The \"children\" key is the default parallel route.\n *\n * @param parallelRoutesKey - Which parallel route to read (default: \"children\")\n */\nexport function useSelectedLayoutSegments(parallelRoutesKey?: string): string[] {\n return useChildSegments(parallelRoutesKey);\n}\n\nexport { ReadonlyURLSearchParams };\n\n/**\n * useServerInsertedHTML — inject HTML during SSR from client components.\n *\n * Used by CSS-in-JS libraries (styled-components, emotion, StyleX) to inject\n * <style> tags during SSR so styles appear in the initial HTML (no FOUC).\n *\n * The callback is called once after each SSR render pass. The returned JSX/HTML\n * is serialized and injected into the HTML stream.\n *\n * Usage (in a \"use client\" component wrapping children):\n * useServerInsertedHTML(() => {\n * const styles = sheet.getStyleElement();\n * sheet.instance.clearTag();\n * return <>{styles}</>;\n * });\n */\n\nexport function useServerInsertedHTML(callback: () => unknown): void {\n if (typeof document !== \"undefined\") {\n // Client-side: no-op (styles are already in the DOM)\n return;\n }\n _getInsertedHTMLCallbacks().push(callback);\n}\n\n/**\n * Flush all collected useServerInsertedHTML callbacks.\n * Returns an array of results (React elements or strings).\n * Clears the callback list so the next render starts fresh.\n *\n * Called by the SSR entry after renderToReadableStream completes.\n */\nexport function flushServerInsertedHTML(): unknown[] {\n const callbacks = _getInsertedHTMLCallbacks();\n const results: unknown[] = [];\n for (const cb of callbacks) {\n try {\n const result = cb();\n if (result != null) results.push(result);\n } catch {\n // Ignore errors from individual callbacks\n }\n }\n callbacks.length = 0;\n return results;\n}\n\n/**\n * Clear all collected useServerInsertedHTML callbacks without flushing.\n * Used for cleanup between requests.\n */\nexport function clearServerInsertedHTML(): void {\n _clearInsertedHTMLCallbacks();\n}\n\n// ---------------------------------------------------------------------------\n// Non-hook utilities (can be called from Server Components)\n// ---------------------------------------------------------------------------\n\n/**\n * HTTP Access Fallback error code — shared prefix for notFound/forbidden/unauthorized.\n * Matches Next.js 16's unified error handling approach.\n */\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = \"NEXT_HTTP_ERROR_FALLBACK\";\n\n/**\n * Check if an error is an HTTP Access Fallback error (notFound, forbidden, unauthorized).\n */\nexport function isHTTPAccessFallbackError(error: unknown): boolean {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String((error as { digest: unknown }).digest);\n return (\n digest === \"NEXT_NOT_FOUND\" || // legacy compat\n digest.startsWith(`${HTTP_ERROR_FALLBACK_ERROR_CODE};`)\n );\n }\n return false;\n}\n\n/**\n * Extract the HTTP status code from an HTTP Access Fallback error.\n * Returns 404 for legacy NEXT_NOT_FOUND errors.\n */\nexport function getAccessFallbackHTTPStatus(error: unknown): number {\n if (error && typeof error === \"object\" && \"digest\" in error) {\n const digest = String((error as { digest: unknown }).digest);\n if (digest === \"NEXT_NOT_FOUND\") return 404;\n if (digest.startsWith(`${HTTP_ERROR_FALLBACK_ERROR_CODE};`)) {\n return parseInt(digest.split(\";\")[1], 10);\n }\n }\n return 404;\n}\n\n/**\n * Enum matching Next.js RedirectType for type-safe redirect calls.\n */\nexport enum RedirectType {\n push = \"push\",\n replace = \"replace\",\n}\n\n/**\n * Internal error class used by redirect/notFound/forbidden/unauthorized.\n * The `digest` field is the serialised control-flow signal read by the\n * framework's error boundary and server-side request handlers.\n */\nclass VinextNavigationError extends Error {\n readonly digest: string;\n constructor(message: string, digest: string) {\n super(message);\n this.digest = digest;\n }\n}\n\n/**\n * Throw a redirect. Caught by the framework to send a redirect response.\n *\n * When `type` is omitted, the digest carries an empty sentinel so the\n * catch site can resolve the default based on context:\n * - Server Action context → \"push\" (Back button works after form submission)\n * - SSR render context → \"replace\"\n *\n * This matches Next.js behavior where `redirect()` checks\n * `actionAsyncStorage.getStore()?.isAction` at call time.\n *\n * @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts\n */\nexport function redirect(url: string, type?: \"replace\" | \"push\" | RedirectType): never {\n throw new VinextNavigationError(\n `NEXT_REDIRECT:${url}`,\n `NEXT_REDIRECT;${type ?? \"\"};${encodeURIComponent(url)}`,\n );\n}\n\n/**\n * Trigger a permanent redirect (308).\n *\n * Accepts an optional `type` parameter matching Next.js's signature.\n * Defaults to \"replace\" (not context-dependent like `redirect()`).\n *\n * @see https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts\n */\nexport function permanentRedirect(\n url: string,\n type: \"replace\" | \"push\" | RedirectType = \"replace\",\n): never {\n throw new VinextNavigationError(\n `NEXT_REDIRECT:${url}`,\n `NEXT_REDIRECT;${type};${encodeURIComponent(url)};308`,\n );\n}\n\n/**\n * Trigger a not-found response (404). Caught by the framework.\n */\nexport function notFound(): never {\n throw new VinextNavigationError(\"NEXT_NOT_FOUND\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`);\n}\n\n/**\n * Trigger a forbidden response (403). Caught by the framework.\n * In Next.js, this is gated behind experimental.authInterrupts — we\n * support it unconditionally for maximum compatibility.\n */\nexport function forbidden(): never {\n throw new VinextNavigationError(\"NEXT_FORBIDDEN\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`);\n}\n\n/**\n * Trigger an unauthorized response (401). Caught by the framework.\n * In Next.js, this is gated behind experimental.authInterrupts — we\n * support it unconditionally for maximum compatibility.\n */\nexport function unauthorized(): never {\n throw new VinextNavigationError(\"NEXT_UNAUTHORIZED\", `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n// Listen for popstate on the client\nif (!isServer) {\n const state = getClientNavigationState();\n if (state && !state.patchInstalled) {\n state.patchInstalled = true;\n\n // Listen for popstate on the client.\n // Note: This handler runs for Pages Router only (when __VINEXT_RSC_NAVIGATE__\n // is not available). It restores scroll position with microtask-based deferral.\n // App Router scroll restoration is handled in server/app-browser-entry.ts:697\n // with RSC navigation coordination (waits for pending navigation to settle).\n window.addEventListener(\"popstate\", (event) => {\n if (typeof window.__VINEXT_RSC_NAVIGATE__ !== \"function\") {\n commitClientNavigationState();\n restoreScrollPosition(event.state);\n }\n });\n\n window.history.pushState = function patchedPushState(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n ): void {\n state.originalPushState.call(window.history, data, unused, url);\n if (state.suppressUrlNotifyCount === 0) {\n commitClientNavigationState();\n }\n };\n\n window.history.replaceState = function patchedReplaceState(\n data: unknown,\n unused: string,\n url?: string | URL | null,\n ): void {\n state.originalReplaceState.call(window.history, data, unused, url);\n if (state.suppressUrlNotifyCount === 0) {\n commitClientNavigationState();\n }\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAM,0BAA0B,OAAO,IAAI,8BAA8B;AACzE,MAAM,gCAAgC,OAAO,IAAI,mCAAmC;AAiCpF,SAAS,+BAEA;AACP,KAAI,OAAOA,QAAM,kBAAkB,WAAY,QAAO;CAEtD,MAAM,cAAc;AACpB,KAAI,CAAC,YAAY,+BACf,aAAY,iCAAiCA,QAAM,cAEjD,KAAK;AAGT,QAAO,YAAY,kCAAkC;;AAGvD,MAAa,4BAEF,8BAA8B;;;;;AAMzC,SAAgB,0BAA4D;AAC1E,KAAI,OAAOA,QAAM,kBAAkB,WAAY,QAAO;CAEtD,MAAM,cAAc;AACpB,KAAI,CAAC,YAAY,yBACf,aAAY,2BAA2BA,QAAM,cAA0B,EAAE,UAAU,EAAE,EAAE,CAAC;AAG1F,QAAO,YAAY,4BAA4B;;;;;;;AASjD,SAAS,iBAAiB,oBAA4B,YAAsB;CAC1E,MAAM,MAAM,yBAAyB;AACrC,KAAI,CAAC,IAAK,QAAO,EAAE;AAInB,KAAI;AAEF,SADmBA,QAAM,WAAW,IAAI,CACtB,sBAAsB,EAAE;SACpC;AACN,SAAO,EAAE;;;AAeb,MAAM,0BAA0B,OAAO,yCAAyC;AAChF,MAAM,iCAAiC,OAAO,+CAA+C;A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