vinext 0.0.49 → 0.0.51
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/client-build-config.js.map +1 -1
- package/dist/build/google-fonts/build-url.js.map +1 -1
- package/dist/build/google-fonts/fallback-metrics-data.js +14031 -0
- package/dist/build/google-fonts/fallback-metrics-data.js.map +1 -0
- package/dist/build/google-fonts/fallback-metrics.d.ts +13 -0
- package/dist/build/google-fonts/fallback-metrics.js +46 -0
- package/dist/build/google-fonts/fallback-metrics.js.map +1 -0
- package/dist/build/google-fonts/get-axes.js.map +1 -1
- package/dist/build/google-fonts/sort-variants.js.map +1 -1
- package/dist/build/google-fonts/validate.js.map +1 -1
- package/dist/build/layout-classification.js.map +1 -1
- package/dist/build/nitro-route-rules.js.map +1 -1
- package/dist/build/precompress.d.ts +13 -2
- package/dist/build/precompress.js +12 -3
- package/dist/build/precompress.js.map +1 -1
- package/dist/build/prerender.d.ts +17 -1
- package/dist/build/prerender.js +114 -23
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/report.d.ts +5 -4
- package/dist/build/report.js +196 -348
- package/dist/build/report.js.map +1 -1
- package/dist/build/route-classification-injector.js.map +1 -1
- package/dist/build/route-classification-manifest.js.map +1 -1
- package/dist/build/run-prerender.js.map +1 -1
- package/dist/build/server-manifest.js.map +1 -1
- package/dist/build/ssr-manifest.js.map +1 -1
- package/dist/build/standalone.js.map +1 -1
- package/dist/build/static-export.js.map +1 -1
- package/dist/check.js +2 -1
- package/dist/check.js.map +1 -1
- package/dist/cli-args.js.map +1 -1
- package/dist/cli.js +68 -7
- package/dist/cli.js.map +1 -1
- package/dist/client/instrumentation-client-state.js.map +1 -1
- package/dist/client/validate-module-path.js.map +1 -1
- package/dist/client/vinext-next-data.d.ts +5 -1
- package/dist/client/window-next.d.ts +151 -0
- package/dist/client/window-next.js +48 -0
- package/dist/client/window-next.js.map +1 -0
- package/dist/cloudflare/kv-cache-handler.js.map +1 -1
- package/dist/cloudflare/tpr.js +2 -1
- package/dist/cloudflare/tpr.js.map +1 -1
- package/dist/config/config-matchers.d.ts +3 -1
- package/dist/config/config-matchers.js +5 -4
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/dotenv.d.ts +11 -1
- package/dist/config/dotenv.js.map +1 -1
- package/dist/config/next-config.d.ts +93 -6
- package/dist/config/next-config.js +233 -6
- package/dist/config/next-config.js.map +1 -1
- package/dist/config/tsconfig-paths.d.ts +13 -0
- package/dist/config/tsconfig-paths.js +117 -0
- package/dist/config/tsconfig-paths.js.map +1 -0
- package/dist/deploy.js +16 -7
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-browser-entry.d.ts +3 -1
- package/dist/entries/app-browser-entry.js +36 -2
- package/dist/entries/app-browser-entry.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +19 -1
- package/dist/entries/app-rsc-entry.js +49 -12
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/app-rsc-manifest.d.ts +9 -0
- package/dist/entries/app-rsc-manifest.js +8 -1
- package/dist/entries/app-rsc-manifest.js.map +1 -1
- package/dist/entries/app-ssr-entry.js.map +1 -1
- package/dist/entries/pages-client-entry.js +3 -5
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-entry-helpers.js.map +1 -1
- package/dist/entries/pages-server-entry.js +34 -1
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.js.map +1 -1
- package/dist/index.js +204 -53
- package/dist/index.js.map +1 -1
- package/dist/init.js.map +1 -1
- package/dist/plugins/async-hooks-stub.js.map +1 -1
- package/dist/plugins/client-reference-dedup.d.ts +15 -2
- package/dist/plugins/client-reference-dedup.js +138 -16
- package/dist/plugins/client-reference-dedup.js.map +1 -1
- package/dist/plugins/fonts.d.ts +2 -2
- package/dist/plugins/fonts.js +15 -6
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/plugins/instrumentation-client.js.map +1 -1
- package/dist/plugins/og-assets.js.map +1 -1
- package/dist/plugins/optimize-imports.js.map +1 -1
- package/dist/plugins/postcss.js.map +1 -1
- package/dist/plugins/rsc-client-reference-loaders.d.ts +7 -0
- package/dist/plugins/rsc-client-reference-loaders.js +48 -0
- package/dist/plugins/rsc-client-reference-loaders.js.map +1 -0
- package/dist/plugins/rsc-client-shim-excludes.js.map +1 -1
- package/dist/plugins/sass.d.ts +34 -0
- package/dist/plugins/sass.js +22 -0
- package/dist/plugins/sass.js.map +1 -0
- package/dist/plugins/server-externals-manifest.js.map +1 -1
- package/dist/plugins/strip-server-exports.js.map +1 -1
- package/dist/routing/app-route-graph.d.ts +78 -6
- package/dist/routing/app-route-graph.js +241 -25
- package/dist/routing/app-route-graph.js.map +1 -1
- package/dist/routing/app-router.js.map +1 -1
- package/dist/routing/file-matcher.js.map +1 -1
- package/dist/routing/pages-router.js.map +1 -1
- package/dist/routing/route-matching.js.map +1 -1
- package/dist/routing/route-pattern.d.ts +56 -1
- package/dist/routing/route-pattern.js +60 -1
- package/dist/routing/route-pattern.js.map +1 -1
- package/dist/routing/route-trie.js.map +1 -1
- package/dist/routing/route-validation.js.map +1 -1
- package/dist/routing/utils.js.map +1 -1
- package/dist/server/api-handler.js.map +1 -1
- package/dist/server/app-browser-action-result.d.ts +44 -0
- package/dist/server/app-browser-action-result.js +79 -0
- package/dist/server/app-browser-action-result.js.map +1 -0
- package/dist/server/app-browser-entry.js +330 -133
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-browser-error.js.map +1 -1
- package/dist/server/app-browser-hydration.d.ts +31 -0
- package/dist/server/app-browser-hydration.js +30 -0
- package/dist/server/app-browser-hydration.js.map +1 -0
- package/dist/server/app-browser-navigation-controller.d.ts +20 -4
- package/dist/server/app-browser-navigation-controller.js +90 -23
- package/dist/server/app-browser-navigation-controller.js.map +1 -1
- package/dist/server/app-browser-popstate.d.ts +16 -0
- package/dist/server/app-browser-popstate.js +17 -0
- package/dist/server/app-browser-popstate.js.map +1 -0
- package/dist/server/app-browser-rsc-redirect.d.ts +28 -0
- package/dist/server/app-browser-rsc-redirect.js +37 -0
- package/dist/server/app-browser-rsc-redirect.js.map +1 -0
- package/dist/server/app-browser-state.d.ts +27 -23
- package/dist/server/app-browser-state.js +158 -54
- package/dist/server/app-browser-state.js.map +1 -1
- package/dist/server/app-browser-stream.d.ts +9 -4
- package/dist/server/app-browser-stream.js +29 -8
- package/dist/server/app-browser-stream.js.map +1 -1
- package/dist/server/app-browser-visible-commit.d.ts +11 -1
- package/dist/server/app-browser-visible-commit.js +69 -21
- package/dist/server/app-browser-visible-commit.js.map +1 -1
- package/dist/server/app-client-reference-preloader.js.map +1 -1
- package/dist/server/app-elements-wire.d.ts +43 -6
- package/dist/server/app-elements-wire.js +121 -5
- package/dist/server/app-elements-wire.js.map +1 -1
- package/dist/server/app-elements.d.ts +2 -2
- package/dist/server/app-elements.js +2 -2
- package/dist/server/app-elements.js.map +1 -1
- package/dist/server/app-fallback-renderer.d.ts +10 -1
- package/dist/server/app-fallback-renderer.js +37 -1
- package/dist/server/app-fallback-renderer.js.map +1 -1
- package/dist/server/app-history-state.d.ts +26 -0
- package/dist/server/app-history-state.js +53 -0
- package/dist/server/app-history-state.js.map +1 -0
- package/dist/server/app-hook-warning-suppression.js.map +1 -1
- package/dist/server/app-middleware.d.ts +1 -1
- package/dist/server/app-middleware.js +4 -9
- package/dist/server/app-middleware.js.map +1 -1
- package/dist/server/app-mounted-slots-header.js.map +1 -1
- package/dist/server/app-page-boundary-render.d.ts +11 -1
- package/dist/server/app-page-boundary-render.js +27 -19
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-boundary.d.ts +1 -0
- package/dist/server/app-page-boundary.js +10 -7
- package/dist/server/app-page-boundary.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +23 -3
- package/dist/server/app-page-cache.js +63 -27
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-dispatch.d.ts +11 -1
- package/dist/server/app-page-dispatch.js +85 -14
- package/dist/server/app-page-dispatch.js.map +1 -1
- package/dist/server/app-page-element-builder.d.ts +10 -1
- package/dist/server/app-page-element-builder.js +38 -6
- package/dist/server/app-page-element-builder.js.map +1 -1
- package/dist/server/app-page-execution.js +2 -3
- package/dist/server/app-page-execution.js.map +1 -1
- package/dist/server/app-page-head.d.ts +7 -0
- package/dist/server/app-page-head.js +6 -1
- package/dist/server/app-page-head.js.map +1 -1
- package/dist/server/app-page-method.js.map +1 -1
- package/dist/server/app-page-params.js.map +1 -1
- package/dist/server/app-page-probe.d.ts +23 -1
- package/dist/server/app-page-probe.js +29 -1
- package/dist/server/app-page-probe.js.map +1 -1
- package/dist/server/app-page-render-observation.d.ts +35 -0
- package/dist/server/app-page-render-observation.js +68 -0
- package/dist/server/app-page-render-observation.js.map +1 -0
- package/dist/server/app-page-render.d.ts +12 -2
- package/dist/server/app-page-render.js +90 -7
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-request.d.ts +1 -0
- package/dist/server/app-page-request.js +2 -1
- package/dist/server/app-page-request.js.map +1 -1
- package/dist/server/app-page-response.d.ts +2 -0
- package/dist/server/app-page-response.js +18 -7
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +9 -3
- package/dist/server/app-page-route-wiring.js +91 -62
- package/dist/server/app-page-route-wiring.js.map +1 -1
- package/dist/server/app-page-segment-state.d.ts +10 -0
- package/dist/server/app-page-segment-state.js +87 -0
- package/dist/server/app-page-segment-state.js.map +1 -0
- package/dist/server/app-page-stream.d.ts +9 -2
- package/dist/server/app-page-stream.js +4 -1
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-post-middleware-context.js.map +1 -1
- package/dist/server/app-prerender-endpoints.js.map +1 -1
- package/dist/server/app-prerender-static-params.js.map +1 -1
- package/dist/server/app-render-dependency.js.map +1 -1
- package/dist/server/app-request-context.js.map +1 -1
- package/dist/server/app-route-handler-cache.js.map +1 -1
- package/dist/server/app-route-handler-dispatch.js +3 -1
- package/dist/server/app-route-handler-dispatch.js.map +1 -1
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-policy.js +1 -0
- package/dist/server/app-route-handler-policy.js.map +1 -1
- package/dist/server/app-route-handler-response.js +4 -3
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-route-handler-runtime.js.map +1 -1
- package/dist/server/app-router-entry.js +7 -15
- package/dist/server/app-router-entry.js.map +1 -1
- package/dist/server/app-rsc-cache-busting.d.ts +23 -2
- package/dist/server/app-rsc-cache-busting.js +75 -19
- package/dist/server/app-rsc-cache-busting.js.map +1 -1
- package/dist/server/app-rsc-embedded-chunks.d.ts +9 -0
- package/dist/server/app-rsc-embedded-chunks.js +34 -0
- package/dist/server/app-rsc-embedded-chunks.js.map +1 -0
- package/dist/server/app-rsc-error-handler.js.map +1 -1
- package/dist/server/app-rsc-errors.d.ts +4 -1
- package/dist/server/app-rsc-errors.js +1 -1
- package/dist/server/app-rsc-errors.js.map +1 -1
- package/dist/server/app-rsc-handler.d.ts +18 -1
- package/dist/server/app-rsc-handler.js +55 -16
- package/dist/server/app-rsc-handler.js.map +1 -1
- package/dist/server/app-rsc-render-mode.d.ts +11 -0
- package/dist/server/app-rsc-render-mode.js +21 -0
- package/dist/server/app-rsc-render-mode.js.map +1 -0
- package/dist/server/app-rsc-request-normalization.d.ts +4 -1
- package/dist/server/app-rsc-request-normalization.js +7 -2
- package/dist/server/app-rsc-request-normalization.js.map +1 -1
- package/dist/server/app-rsc-response-finalizer.d.ts +2 -1
- package/dist/server/app-rsc-response-finalizer.js +6 -1
- package/dist/server/app-rsc-response-finalizer.js.map +1 -1
- package/dist/server/app-rsc-route-matching.d.ts +23 -0
- package/dist/server/app-rsc-route-matching.js +45 -23
- package/dist/server/app-rsc-route-matching.js.map +1 -1
- package/dist/server/app-segment-config.js.map +1 -1
- package/dist/server/app-server-action-execution.d.ts +51 -5
- package/dist/server/app-server-action-execution.js +161 -51
- package/dist/server/app-server-action-execution.js.map +1 -1
- package/dist/server/app-ssr-entry.d.ts +7 -0
- package/dist/server/app-ssr-entry.js +44 -14
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/app-ssr-error-meta.d.ts +14 -0
- package/dist/server/app-ssr-error-meta.js +50 -0
- package/dist/server/app-ssr-error-meta.js.map +1 -0
- package/dist/server/app-ssr-stream.d.ts +1 -1
- package/dist/server/app-ssr-stream.js +9 -12
- package/dist/server/app-ssr-stream.js.map +1 -1
- package/dist/server/app-static-generation.js.map +1 -1
- package/dist/server/artifact-compatibility.d.ts +12 -2
- package/dist/server/artifact-compatibility.js +12 -8
- package/dist/server/artifact-compatibility.js.map +1 -1
- package/dist/server/cache-control.js +1 -0
- package/dist/server/cache-control.js.map +1 -1
- package/dist/server/cache-proof.d.ts +124 -5
- package/dist/server/cache-proof.js +416 -18
- package/dist/server/cache-proof.js.map +1 -1
- package/dist/server/csp.js.map +1 -1
- package/dist/server/dev-error-overlay-store.js.map +1 -1
- package/dist/server/dev-error-overlay.js +5 -0
- package/dist/server/dev-error-overlay.js.map +1 -1
- package/dist/server/dev-lockfile.d.ts +110 -0
- package/dist/server/dev-lockfile.js +180 -0
- package/dist/server/dev-lockfile.js.map +1 -0
- package/dist/server/dev-module-runner.js.map +1 -1
- package/dist/server/dev-origin-check.js.map +1 -1
- package/dist/server/dev-route-files.js.map +1 -1
- package/dist/server/dev-server.js +23 -10
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/file-based-metadata.d.ts +13 -0
- package/dist/server/file-based-metadata.js +49 -2
- package/dist/server/file-based-metadata.js.map +1 -1
- package/dist/server/headers.d.ts +81 -0
- package/dist/server/headers.js +104 -0
- package/dist/server/headers.js.map +1 -0
- package/dist/server/html.js +1 -1
- package/dist/server/html.js.map +1 -1
- package/dist/server/http-error-responses.d.ts +10 -0
- package/dist/server/http-error-responses.js +11 -1
- package/dist/server/http-error-responses.js.map +1 -1
- package/dist/server/image-optimization.d.ts +11 -1
- package/dist/server/image-optimization.js.map +1 -1
- package/dist/server/implicit-tags.js +2 -1
- package/dist/server/implicit-tags.js.map +1 -1
- package/dist/server/instrumentation-runtime.js.map +1 -1
- package/dist/server/instrumentation.js.map +1 -1
- package/dist/server/isr-cache.d.ts +12 -2
- package/dist/server/isr-cache.js +16 -5
- package/dist/server/isr-cache.js.map +1 -1
- package/dist/server/metadata-route-build-data.js.map +1 -1
- package/dist/server/metadata-route-response.js +22 -5
- package/dist/server/metadata-route-response.js.map +1 -1
- package/dist/server/metadata-routes.js +27 -8
- package/dist/server/metadata-routes.js.map +1 -1
- package/dist/server/middleware-matcher.js.map +1 -1
- package/dist/server/middleware-request-headers.d.ts +4 -1
- package/dist/server/middleware-request-headers.js +15 -8
- package/dist/server/middleware-request-headers.js.map +1 -1
- package/dist/server/middleware-response-headers.d.ts +2 -1
- package/dist/server/middleware-response-headers.js +1 -1
- package/dist/server/middleware-response-headers.js.map +1 -1
- package/dist/server/middleware-runtime.d.ts +1 -0
- package/dist/server/middleware-runtime.js +7 -3
- package/dist/server/middleware-runtime.js.map +1 -1
- package/dist/server/middleware.d.ts +12 -0
- package/dist/server/middleware.js +12 -0
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/navigation-planner.d.ts +133 -0
- package/dist/server/navigation-planner.js +432 -0
- package/dist/server/navigation-planner.js.map +1 -0
- package/dist/server/navigation-trace.d.ts +19 -2
- package/dist/server/navigation-trace.js +20 -1
- package/dist/server/navigation-trace.js.map +1 -1
- package/dist/server/next-error-digest.d.ts +3 -2
- package/dist/server/next-error-digest.js +4 -2
- package/dist/server/next-error-digest.js.map +1 -1
- package/dist/server/normalize-path.d.ts +2 -1
- package/dist/server/normalize-path.js +4 -1
- package/dist/server/normalize-path.js.map +1 -1
- package/dist/server/pages-api-route.js +1 -0
- package/dist/server/pages-api-route.js.map +1 -1
- package/dist/server/pages-i18n.js.map +1 -1
- package/dist/server/pages-media-type.js.map +1 -1
- package/dist/server/pages-node-compat.js.map +1 -1
- package/dist/server/pages-page-data.d.ts +3 -2
- package/dist/server/pages-page-data.js +27 -5
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.js +2 -1
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/prerender-work-unit-setup.js +1 -1
- package/dist/server/prerender-work-unit-setup.js.map +1 -1
- package/dist/server/prod-server.d.ts +28 -1
- package/dist/server/prod-server.js +97 -22
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/request-log.js.map +1 -1
- package/dist/server/request-pipeline.d.ts +1 -13
- package/dist/server/request-pipeline.js +3 -25
- package/dist/server/request-pipeline.js.map +1 -1
- package/dist/server/rsc-stream-hints.js.map +1 -1
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/server/server-action-not-found.d.ts +16 -3
- package/dist/server/server-action-not-found.js +22 -4
- package/dist/server/server-action-not-found.js.map +1 -1
- package/dist/server/server-globals.d.ts +5 -0
- package/dist/server/server-globals.js +37 -0
- package/dist/server/server-globals.js.map +1 -0
- package/dist/server/socket-error-backstop.js.map +1 -1
- package/dist/server/static-file-cache.js +1 -1
- package/dist/server/static-file-cache.js.map +1 -1
- package/dist/server/worker-utils.d.ts +0 -7
- package/dist/server/worker-utils.js +3 -2
- package/dist/server/worker-utils.js.map +1 -1
- package/dist/shims/amp.js.map +1 -1
- package/dist/shims/app.d.ts +37 -4
- package/dist/shims/app.js +50 -1
- package/dist/shims/app.js.map +1 -0
- package/dist/shims/cache-for-request.js.map +1 -1
- package/dist/shims/cache-runtime.d.ts +19 -2
- package/dist/shims/cache-runtime.js +87 -19
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/cache.d.ts +20 -21
- package/dist/shims/cache.js +101 -15
- package/dist/shims/cache.js.map +1 -1
- package/dist/shims/client-hook-error.js.map +1 -1
- package/dist/shims/compat-router.js.map +1 -1
- package/dist/shims/config.js.map +1 -1
- package/dist/shims/constants.js.map +1 -1
- package/dist/shims/document.js.map +1 -1
- package/dist/shims/dynamic.d.ts +18 -10
- package/dist/shims/dynamic.js +107 -51
- package/dist/shims/dynamic.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +35 -6
- package/dist/shims/error-boundary.js +116 -33
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/error.d.ts +18 -1
- package/dist/shims/error.js +56 -1
- package/dist/shims/error.js.map +1 -1
- package/dist/shims/fetch-cache.d.ts +25 -1
- package/dist/shims/fetch-cache.js +159 -13
- package/dist/shims/fetch-cache.js.map +1 -1
- package/dist/shims/font-google-base.d.ts +22 -8
- package/dist/shims/font-google-base.js +41 -71
- package/dist/shims/font-google-base.js.map +1 -1
- package/dist/shims/font-local.d.ts +3 -20
- package/dist/shims/font-local.js +23 -75
- package/dist/shims/font-local.js.map +1 -1
- package/dist/shims/font-utils.d.ts +51 -0
- package/dist/shims/font-utils.js +97 -0
- package/dist/shims/font-utils.js.map +1 -0
- package/dist/shims/form.js +3 -1
- package/dist/shims/form.js.map +1 -1
- package/dist/shims/hash-scroll.d.ts +7 -0
- package/dist/shims/hash-scroll.js +30 -0
- package/dist/shims/hash-scroll.js.map +1 -0
- package/dist/shims/head-state.js.map +1 -1
- package/dist/shims/head.d.ts +3 -1
- package/dist/shims/head.js +28 -16
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/headers.d.ts +11 -12
- package/dist/shims/headers.js +45 -8
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/i18n-context.js.map +1 -1
- package/dist/shims/i18n-state.js.map +1 -1
- package/dist/shims/image-config.d.ts +14 -1
- package/dist/shims/image-config.js +24 -1
- package/dist/shims/image-config.js.map +1 -1
- package/dist/shims/image.d.ts +1 -0
- package/dist/shims/image.js +159 -80
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/internal/als-registry.js.map +1 -1
- package/dist/shims/internal/app-router-context.d.ts +7 -6
- package/dist/shims/internal/app-router-context.js +17 -6
- package/dist/shims/internal/app-router-context.js.map +1 -1
- package/dist/shims/internal/cookie-serialize.js.map +1 -1
- package/dist/shims/internal/make-hanging-promise.d.ts +1 -1
- package/dist/shims/internal/make-hanging-promise.js +1 -1
- package/dist/shims/internal/make-hanging-promise.js.map +1 -1
- package/dist/shims/internal/parse-cookie-header.js.map +1 -1
- package/dist/shims/internal/utils.js.map +1 -1
- package/dist/shims/internal/work-unit-async-storage.js +2 -2
- package/dist/shims/internal/work-unit-async-storage.js.map +1 -1
- package/dist/shims/layout-segment-context.js.map +1 -1
- package/dist/shims/legacy-image.js.map +1 -1
- package/dist/shims/link-prefetch.d.ts +42 -0
- package/dist/shims/link-prefetch.js +45 -0
- package/dist/shims/link-prefetch.js.map +1 -0
- package/dist/shims/link.d.ts +37 -4
- package/dist/shims/link.js +156 -46
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +16 -30
- package/dist/shims/metadata.js +87 -28
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/navigation-state.js.map +1 -1
- package/dist/shims/navigation.d.ts +172 -10
- package/dist/shims/navigation.js +335 -70
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/navigation.react-server.d.ts +3 -2
- package/dist/shims/navigation.react-server.js +5 -2
- package/dist/shims/navigation.react-server.js.map +1 -1
- package/dist/shims/offline.js.map +1 -1
- package/dist/shims/pages-router-runtime.d.ts +7 -0
- package/dist/shims/pages-router-runtime.js +16 -0
- package/dist/shims/pages-router-runtime.js.map +1 -0
- package/dist/shims/readonly-url-search-params.js.map +1 -1
- package/dist/shims/request-context.js.map +1 -1
- package/dist/shims/root-params.js.map +1 -1
- package/dist/shims/router-state.js.map +1 -1
- package/dist/shims/router.d.ts +69 -7
- package/dist/shims/router.js +232 -249
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script-nonce-context.js.map +1 -1
- package/dist/shims/script.js +110 -32
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.js +12 -15
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/slot.d.ts +7 -1
- package/dist/shims/slot.js +60 -7
- package/dist/shims/slot.js.map +1 -1
- package/dist/shims/thenable-params.js.map +1 -1
- package/dist/shims/unified-request-context.js +5 -0
- package/dist/shims/unified-request-context.js.map +1 -1
- package/dist/shims/unrecognized-action-error.d.ts +35 -0
- package/dist/shims/unrecognized-action-error.js +41 -0
- package/dist/shims/unrecognized-action-error.js.map +1 -0
- package/dist/shims/url-safety.js.map +1 -1
- package/dist/shims/url-utils.d.ts +22 -1
- package/dist/shims/url-utils.js +76 -3
- package/dist/shims/url-utils.js.map +1 -1
- package/dist/shims/use-merged-ref.js.map +1 -1
- package/dist/shims/web-vitals.d.ts +4 -21
- package/dist/shims/web-vitals.js +19 -6
- package/dist/shims/web-vitals.js.map +1 -1
- package/dist/utils/asset-prefix.d.ts +69 -0
- package/dist/utils/asset-prefix.js +91 -0
- package/dist/utils/asset-prefix.js.map +1 -0
- package/dist/utils/base-path.d.ts +7 -1
- package/dist/utils/base-path.js +10 -1
- package/dist/utils/base-path.js.map +1 -1
- package/dist/utils/cache-control-metadata.js.map +1 -1
- package/dist/utils/domain-locale.js.map +1 -1
- package/dist/utils/encode-cache-tag.d.ts +31 -0
- package/dist/utils/encode-cache-tag.js +38 -0
- package/dist/utils/encode-cache-tag.js.map +1 -0
- package/dist/utils/error-cause.js.map +1 -1
- package/dist/utils/hash.js.map +1 -1
- package/dist/utils/lazy-chunks.js.map +1 -1
- package/dist/utils/manifest-paths.js.map +1 -1
- package/dist/utils/mdx-scan.js.map +1 -1
- package/dist/utils/navigation-signal.d.ts +5 -0
- package/dist/utils/navigation-signal.js +14 -0
- package/dist/utils/navigation-signal.js.map +1 -0
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/public-routes.js.map +1 -1
- package/dist/utils/query.js.map +1 -1
- package/dist/utils/safe-json-file.js.map +1 -1
- package/dist/utils/sorted-array.d.ts +9 -0
- package/dist/utils/sorted-array.js +22 -0
- package/dist/utils/sorted-array.js.map +1 -0
- package/dist/utils/text-stream.js.map +1 -1
- package/dist/utils/vinext-root.js.map +1 -1
- package/package.json +8 -6
|
@@ -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 { AppElementsWire } from \"../server/app-elements.js\";\nimport {\n createRscRequestHeaders,\n createRscRequestUrl,\n VINEXT_RSC_MOUNTED_SLOTS_HEADER,\n} from \"../server/app-rsc-cache-busting.js\";\nimport { toBrowserNavigationHref, toSameOriginAppPath } from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { ReadonlyURLSearchParams } from \"./readonly-url-search-params.js\";\nimport { assertSafeNavigationUrl } from \"./url-safety.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\n// Browser hydration has the same module-split shape as SSR in Vite dev:\n// the browser entry seeds the snapshot before hydrateRoot(), but client\n// components can import a different module instance of this shim.\nconst GLOBAL_HYDRATION_CONTEXT_KEY = Symbol.for(\"vinext.navigation.clientHydrationContext\");\nconst _GLOBAL_HYDRATION_CONTEXT_KEY = GLOBAL_HYDRATION_CONTEXT_KEY;\ntype _GlobalWithHydrationContext = typeof globalThis & {\n [_GLOBAL_HYDRATION_CONTEXT_KEY]?: NavigationContext | null;\n};\n\nfunction _getGlobalAccessors(): _StateAccessors | undefined {\n return (globalThis as _GlobalWithAccessors)[_GLOBAL_ACCESSORS_KEY];\n}\n\nfunction _getClientHydrationContext(): NavigationContext | null | undefined {\n const globalState = globalThis as _GlobalWithHydrationContext;\n if (Object.prototype.hasOwnProperty.call(globalState, _GLOBAL_HYDRATION_CONTEXT_KEY)) {\n return globalState[_GLOBAL_HYDRATION_CONTEXT_KEY] ?? null;\n }\n return undefined;\n}\n\nfunction _setClientHydrationContext(ctx: NavigationContext | null): void {\n (globalThis as _GlobalWithHydrationContext)[_GLOBAL_HYDRATION_CONTEXT_KEY] = ctx;\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 if (typeof window !== \"undefined\") {\n const hydrationContext = _getClientHydrationContext();\n return hydrationContext !== undefined ? hydrationContext : _serverContext;\n }\n const g = _getGlobalAccessors();\n return g ? g.getServerContext() : _serverContext;\n};\nlet _setServerContext = (ctx: NavigationContext | null): void => {\n if (typeof window !== \"undefined\") {\n _serverContext = ctx;\n _setClientHydrationContext(ctx);\n return;\n }\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 mountedSlotsHeader?: string | null;\n paramsHeader: string | null;\n url: string;\n};\n\nexport type PrefetchCacheEntry = {\n outcome: \"pending\" | \"cache-seeded\";\n snapshot?: CachedRscResponse;\n pending?: Promise<void>;\n timestamp: number;\n};\n\nexport function getCurrentInterceptionContext(): string | null {\n if (isServer) {\n return null;\n }\n\n return stripBasePath(window.location.pathname, __basePath);\n}\n\nexport function getCurrentNextUrl(): string {\n if (isServer) {\n return \"/\";\n }\n\n return window.location.pathname + window.location.search;\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 interception-aware cache key so distinct source routes do not alias.\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 and explicit slot context.\n * storePrefetchResponse() is kept for backward compatibility and test\n * helpers. It is slot-unaware: the snapshot's mountedSlotsHeader comes\n * from the response headers, not the caller, so consumePrefetchResponse\n * may reject the entry if the caller's slot context differs.\n *\n * NB: Caller is responsible for managing getPrefetchedUrls() — this\n * function only stores the response in the prefetch cache.\n */\nexport function storePrefetchResponse(\n rscUrl: string,\n response: Response,\n interceptionContext: string | null = null,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n evictPrefetchCacheIfNeeded();\n const entry: PrefetchCacheEntry = { outcome: \"pending\", timestamp: Date.now() };\n entry.pending = snapshotRscResponse(response)\n .then((snapshot) => {\n entry.snapshot = snapshot;\n })\n .catch(() => {\n getPrefetchCache().delete(cacheKey);\n })\n .finally(() => {\n entry.pending = undefined;\n if (entry.snapshot) {\n entry.outcome = \"cache-seeded\";\n }\n });\n getPrefetchCache().set(cacheKey, 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 mountedSlotsHeader: response.headers.get(\"X-Vinext-Mounted-Slots\"),\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.mountedSlotsHeader != null) {\n headers.set(\"X-Vinext-Mounted-Slots\", cached.mountedSlotsHeader);\n }\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(\n rscUrl: string,\n fetchPromise: Promise<Response>,\n interceptionContext: string | null = null,\n mountedSlotsHeader: string | null = null,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cache = getPrefetchCache();\n const prefetched = getPrefetchedUrls();\n const now = Date.now();\n\n const entry: PrefetchCacheEntry = { outcome: \"pending\", timestamp: now };\n\n entry.pending = fetchPromise\n .then(async (response) => {\n if (response.ok) {\n entry.snapshot = {\n ...(await snapshotRscResponse(response)),\n // Prefetch compatibility is defined by the slot context at fetch\n // time, not by whatever header a reused response happens to carry.\n mountedSlotsHeader,\n };\n } else {\n prefetched.delete(cacheKey);\n cache.delete(cacheKey);\n }\n })\n .catch(() => {\n prefetched.delete(cacheKey);\n cache.delete(cacheKey);\n })\n .finally(() => {\n entry.pending = undefined;\n if (entry.snapshot) {\n entry.outcome = \"cache-seeded\";\n }\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(cacheKey, 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(\n rscUrl: string,\n interceptionContext: string | null = null,\n mountedSlotsHeader: string | null = null,\n): CachedRscResponse | null {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cache = getPrefetchCache();\n const entry = cache.get(cacheKey);\n if (!entry) return null;\n\n // Skip in-flight snapshots and error-path residue where pending cleared\n // without a successful transition to a cache-seeded entry.\n if (entry.pending || entry.outcome !== \"cache-seeded\") return null;\n\n cache.delete(cacheKey);\n getPrefetchedUrls().delete(cacheKey);\n\n if (entry.snapshot) {\n if ((entry.snapshot.mountedSlotsHeader ?? null) !== mountedSlotsHeader) {\n // Entry was already removed above. Slot mismatch means the prefetch\n // used stale slot context and cannot be safely reused.\n return null;\n }\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\");\nconst _MOUNTED_SLOTS_HEADER_KEY = Symbol.for(\"vinext.mountedSlotsHeader\");\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 pendingPathname: string | null;\n pendingPathnameNavId: number | 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 CommitClientNavigationStateOptions = {\n releaseSnapshot?: boolean;\n};\n\ntype ClientNavigationGlobal = typeof globalThis & {\n [_CLIENT_NAV_STATE_KEY]?: ClientNavigationState;\n [_MOUNTED_SLOTS_HEADER_KEY]?: string | null;\n};\n\nexport function setMountedSlotsHeader(header: string | null): void {\n if (isServer) return;\n const globalState = window as ClientNavigationGlobal;\n globalState[_MOUNTED_SLOTS_HEADER_KEY] = header;\n}\n\nexport function getMountedSlotsHeader(): string | null {\n if (isServer) return null;\n const globalState = window as ClientNavigationGlobal;\n return globalState[_MOUNTED_SLOTS_HEADER_KEY] ?? null;\n}\n\nexport function 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 pendingPathname: null,\n pendingPathnameNavId: 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\n/**\n * Set the pending pathname for client-side navigation.\n * Strips the base path before storing. Associates the pathname with the given navId\n * so only that navigation (or a newer one) can clear it.\n */\nexport function setPendingPathname(pathname: string, navId: number): void {\n const state = getClientNavigationState();\n if (!state) return;\n state.pendingPathname = stripBasePath(pathname, __basePath);\n state.pendingPathnameNavId = navId;\n}\n\n/**\n * Clear the pending pathname, but only if the given navId matches the one\n * that set it, or if pendingPathnameNavId is null (no active owner).\n * This prevents superseded navigations from clearing state belonging to newer navigations.\n */\nexport function clearPendingPathname(navId: number): void {\n const state = getClientNavigationState();\n if (!state) return;\n // Only clear if this navId is the one that set the pendingPathname,\n // or if pendingPathnameNavId is null (no owner)\n if (state.pendingPathnameNavId === null || state.pendingPathnameNavId === navId) {\n state.pendingPathname = null;\n state.pendingPathnameNavId = null;\n }\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/* 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\n/**\n * Commit pending client navigation state to committed snapshots.\n *\n * navId is optional: callers that don't own pendingPathname (for example,\n * superseded pre-paint cleanup) may pass undefined to flush URL/params state\n * without clearing pendingPathname owned by the active navigation. Such callers\n * must opt in explicitly if they also own an activated render snapshot.\n */\nexport function commitClientNavigationState(\n navId?: number,\n options?: CommitClientNavigationStateOptions,\n): void {\n if (isServer) return;\n const state = getClientNavigationState();\n if (!state) return;\n\n // Only navigation-owned commits may release a render snapshot. Ownerless URL\n // syncs still update committed pathname/search state, but must not consume\n // the active snapshot for an in-flight App Router transition.\n const shouldReleaseSnapshot = navId !== undefined || options?.releaseSnapshot === true;\n if (shouldReleaseSnapshot && 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 // Clear pending pathname when navigation commits, but only if:\n // - The navId matches the one that set pendingPathname\n // - No newer navigation has overwritten pendingPathname (pendingPathnameNavId === null or matches)\n // - navId is undefined only for non-owning callers, which must not clear\n // pendingPathname for an active navigation.\n const canClearPendingPathname =\n state.pendingPathnameNavId === null ||\n (navId !== undefined && state.pendingPathnameNavId === navId);\n if (canClearPendingPathname) {\n state.pendingPathname = null;\n state.pendingPathnameNavId = 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 programmaticTransition = false,\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__(\n fullHref,\n 0,\n \"navigate\",\n mode,\n undefined,\n programmaticTransition,\n );\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 assertSafeNavigationUrl(href);\n if (isServer) return;\n React.startTransition(() => {\n void navigateClientSide(href, \"push\", options?.scroll !== false, true);\n });\n },\n replace(href: string, options?: { scroll?: boolean }): void {\n assertSafeNavigationUrl(href);\n if (isServer) return;\n React.startTransition(() => {\n void navigateClientSide(href, \"replace\", options?.scroll !== false, true);\n });\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 const rscNavigate = window.__VINEXT_RSC_NAVIGATE__;\n if (typeof rscNavigate === \"function\") {\n const navigate = () => {\n void rscNavigate(window.location.href, 0, \"refresh\", undefined, undefined, true);\n };\n React.startTransition(navigate);\n }\n },\n prefetch(href: string): void {\n assertSafeNavigationUrl(href);\n if (isServer) return;\n void (async () => {\n // Normalize same-origin absolute URLs to local paths; no-op for external\n // origins so we don't pollute the prefetch cache with a same-path .rsc on\n // the current origin. Mirrors Link's prefetchUrl and navigateClientSide.\n let prefetchHref = href;\n if (href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\")) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) return;\n prefetchHref = localPath;\n }\n\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(prefetchHref, window.location.href, __basePath);\n const interceptionContext = getCurrentInterceptionContext();\n const mountedSlotsHeader = getMountedSlotsHeader();\n const headers = createRscRequestHeaders({ interceptionContext });\n if (mountedSlotsHeader) {\n headers.set(VINEXT_RSC_MOUNTED_SLOTS_HEADER, mountedSlotsHeader);\n }\n const rscUrl = await createRscRequestUrl(fullHref, headers);\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(cacheKey)) return;\n prefetched.add(cacheKey);\n prefetchRscResponse(\n rscUrl,\n fetch(rscUrl, {\n headers,\n credentials: \"include\",\n priority: \"low\" as RequestInit[\"priority\"],\n }),\n interceptionContext,\n mountedSlotsHeader,\n );\n })().catch((error) => {\n console.error(\"[vinext] RSC prefetch setup error:\", error);\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 if (segments.length === 0) return null;\n\n return parallelRoutesKey === undefined || parallelRoutesKey === \"children\"\n ? segments[0]\n : segments[segments.length - 1];\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 * Render collected useServerInsertedHTML callbacks without unregistering them.\n *\n * Streaming SSR needs to invoke the same style-registry callbacks after each\n * Fizz flush. Libraries such as styled-components and Emotion clear their own\n * per-flush buffers inside the callback; the registration itself must survive\n * until the request stream is closed.\n */\nexport function renderServerInsertedHTML(): 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 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":";;;;;;;;;;;;;;;;;AAiCA,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;AAkC7F,MAAa,uBAAuB,OAAO,IAAI,oCAAoC;AACnF,MAAM,wBAA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2B,EACnC,8BAA6B"}
|
|
1
|
+
{"version":3,"file":"navigation.js","names":["React","globalState"],"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 { AppElementsWire } from \"../server/app-elements.js\";\nimport { createExternalHistoryStatePreservingMetadata } from \"../server/app-history-state.js\";\nimport {\n createRscRequestHeaders,\n createRscRequestUrl,\n VINEXT_RSC_COMPATIBILITY_ID_HEADER,\n VINEXT_RSC_CONTENT_TYPE,\n} from \"../server/app-rsc-cache-busting.js\";\nimport { VINEXT_MOUNTED_SLOTS_HEADER, VINEXT_PARAMS_HEADER } from \"../server/headers.js\";\nimport {\n isAbsoluteOrProtocolRelativeUrl,\n isHashOnlyBrowserUrlChange,\n toBrowserNavigationHref,\n toSameOriginAppPath,\n} from \"./url-utils.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { ReadonlyURLSearchParams } from \"./readonly-url-search-params.js\";\nimport { assertSafeNavigationUrl } from \"./url-safety.js\";\nimport { AppRouterContext } from \"./internal/app-router-context.js\";\nimport { scrollToHashTarget } from \"./hash-scroll.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\n// Browser hydration has the same module-split shape as SSR in Vite dev:\n// the browser entry seeds the snapshot before hydrateRoot(), but client\n// components can import a different module instance of this shim.\nconst GLOBAL_HYDRATION_CONTEXT_KEY = Symbol.for(\"vinext.navigation.clientHydrationContext\");\nconst _GLOBAL_HYDRATION_CONTEXT_KEY = GLOBAL_HYDRATION_CONTEXT_KEY;\ntype _GlobalWithHydrationContext = typeof globalThis & {\n [_GLOBAL_HYDRATION_CONTEXT_KEY]?: NavigationContext | null;\n};\n\nfunction _getGlobalAccessors(): _StateAccessors | undefined {\n return (globalThis as _GlobalWithAccessors)[_GLOBAL_ACCESSORS_KEY];\n}\n\nfunction _getClientHydrationContext(): NavigationContext | null | undefined {\n const globalState = globalThis as _GlobalWithHydrationContext;\n if (Object.prototype.hasOwnProperty.call(globalState, _GLOBAL_HYDRATION_CONTEXT_KEY)) {\n return globalState[_GLOBAL_HYDRATION_CONTEXT_KEY] ?? null;\n }\n return undefined;\n}\n\nfunction _setClientHydrationContext(ctx: NavigationContext | null): void {\n (globalThis as _GlobalWithHydrationContext)[_GLOBAL_HYDRATION_CONTEXT_KEY] = ctx;\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 if (typeof window !== \"undefined\") {\n const hydrationContext = _getClientHydrationContext();\n return hydrationContext !== undefined ? hydrationContext : _serverContext;\n }\n const g = _getGlobalAccessors();\n return g ? g.getServerContext() : _serverContext;\n};\nlet _setServerContext = (ctx: NavigationContext | null): void => {\n if (typeof window !== \"undefined\") {\n _serverContext = ctx;\n _setClientHydrationContext(ctx);\n return;\n }\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// Pages Router compat source.\n//\n// `next/navigation` is the App Router API surface, but Next.js exposes the\n// same hook names to Pages Router pages as a compat shim. In Next.js this is\n// done by wrapping pages with SearchParamsContext / PathParamsContext /\n// PathnameContext providers populated from the Pages Router's state — see:\n// .nextjs-ref/packages/next/src/server/render.tsx\n// .nextjs-ref/packages/next/src/client/index.tsx\n// .nextjs-ref/packages/next/src/shared/lib/router/adapters.tsx\n//\n// vinext drives these hooks from a module-level navigation context instead of\n// React Context, so we fall back to a Pages Router accessor when no App\n// Router context is set. The accessor is published by next/router via a\n// global Symbol.for handle (see packages/vinext/src/shims/router.ts); we do\n// NOT import router.ts here because doing so would force navigation.ts to be\n// loaded for every consumer of next/router, triggering window.history\n// patches in unit tests that only want the router shim.\n// ---------------------------------------------------------------------------\n\ntype PagesNavigationContext = {\n pathname: string;\n searchParams: URLSearchParams;\n params: Record<string, string | string[]>;\n};\n\nconst PAGES_NAVIGATION_ACCESSOR_KEY = Symbol.for(\n \"vinext.navigation.pagesNavigationContextAccessor\",\n);\ntype _GlobalWithPagesAccessor = typeof globalThis & {\n [PAGES_NAVIGATION_ACCESSOR_KEY]?: () => PagesNavigationContext | null;\n};\n\nfunction _getPagesNavigationContext(): PagesNavigationContext | null {\n const accessor = (globalThis as _GlobalWithPagesAccessor)[PAGES_NAVIGATION_ACCESSOR_KEY];\n if (!accessor) return null;\n try {\n return accessor();\n } catch {\n return null;\n }\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 compatibilityIdHeader?: string | null;\n buffer: ArrayBuffer;\n contentType: string;\n mountedSlotsHeader?: string | null;\n paramsHeader: string | null;\n url: string;\n};\n\nexport type PrefetchOptions = {\n kind?: unknown;\n onInvalidate?: () => void;\n};\n\nexport type PrefetchCacheEntry = {\n invalidationTimer?: ReturnType<typeof setTimeout>;\n onInvalidateCallbacks?: Set<() => void>;\n outcome: \"pending\" | \"cache-seeded\";\n snapshot?: CachedRscResponse;\n pending?: Promise<void>;\n timestamp: number;\n};\n\nexport function getCurrentInterceptionContext(): string | null {\n if (isServer) {\n return null;\n }\n\n return stripBasePath(window.location.pathname, __basePath);\n}\n\nexport function getCurrentNextUrl(): string {\n if (isServer) {\n return \"/\";\n }\n\n return window.location.pathname + window.location.search;\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 interception-aware cache key so distinct source routes do not alias.\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 deletePrefetchCacheEntry(cache, prefetched, key, entry, true);\n }\n }\n\n while (cache.size >= MAX_PREFETCH_CACHE_SIZE) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) {\n const entry = cache.get(oldest);\n if (entry) {\n deletePrefetchCacheEntry(cache, prefetched, oldest, entry, true);\n } else {\n cache.delete(oldest);\n prefetched.delete(oldest);\n }\n } else {\n break;\n }\n }\n}\n\nfunction clearPrefetchInvalidation(entry: PrefetchCacheEntry): void {\n if (entry.invalidationTimer !== undefined) {\n clearTimeout(entry.invalidationTimer);\n entry.invalidationTimer = undefined;\n }\n}\n\nfunction notifyPrefetchInvalidated(entry: PrefetchCacheEntry): void {\n clearPrefetchInvalidation(entry);\n const callbacks = entry.onInvalidateCallbacks;\n entry.onInvalidateCallbacks = undefined;\n if (callbacks === undefined) return;\n\n for (const onInvalidate of callbacks) {\n try {\n onInvalidate();\n } catch (error) {\n if (typeof reportError === \"function\") {\n reportError(error);\n } else {\n console.error(error);\n }\n }\n }\n}\n\nfunction deletePrefetchCacheEntry(\n cache: Map<string, PrefetchCacheEntry>,\n prefetched: Set<string>,\n cacheKey: string,\n entry: PrefetchCacheEntry,\n notify: boolean,\n): void {\n cache.delete(cacheKey);\n prefetched.delete(cacheKey);\n if (notify) {\n notifyPrefetchInvalidated(entry);\n } else {\n clearPrefetchInvalidation(entry);\n entry.onInvalidateCallbacks = undefined;\n }\n}\n\nfunction invalidatePrefetchCacheEntry(cacheKey: string): void {\n const cache = getPrefetchCache();\n const entry = cache.get(cacheKey);\n if (!entry) return;\n deletePrefetchCacheEntry(cache, getPrefetchedUrls(), cacheKey, entry, true);\n}\n\nfunction schedulePrefetchInvalidation(cacheKey: string, entry: PrefetchCacheEntry): void {\n if (entry.onInvalidateCallbacks === undefined || entry.onInvalidateCallbacks.size === 0) return;\n\n clearPrefetchInvalidation(entry);\n const elapsed = Date.now() - entry.timestamp;\n const delay = Math.max(0, PREFETCH_CACHE_TTL - elapsed);\n entry.invalidationTimer = setTimeout(() => {\n invalidatePrefetchCacheEntry(cacheKey);\n }, delay);\n}\n\nfunction addPrefetchInvalidationCallback(\n entry: PrefetchCacheEntry,\n onInvalidate: (() => void) | undefined,\n): void {\n if (onInvalidate === undefined) return;\n if (entry.onInvalidateCallbacks === undefined) {\n entry.onInvalidateCallbacks = new Set();\n }\n entry.onInvalidateCallbacks.add(onInvalidate);\n}\n\nfunction attachPrefetchInvalidationCallback(\n cacheKey: string,\n onInvalidate: (() => void) | undefined,\n): void {\n if (onInvalidate === undefined) return;\n const entry = getPrefetchCache().get(cacheKey);\n if (!entry) return;\n addPrefetchInvalidationCallback(entry, onInvalidate);\n if (entry.outcome === \"cache-seeded\") {\n schedulePrefetchInvalidation(cacheKey, entry);\n }\n}\n\nexport function invalidatePrefetchCache(): void {\n const cache = getPrefetchCache();\n const prefetched = getPrefetchedUrls();\n for (const [cacheKey, entry] of cache) {\n deletePrefetchCacheEntry(cache, prefetched, cacheKey, entry, true);\n }\n prefetched.clear();\n if (!isServer) {\n window.__VINEXT_PING_VISIBLE_LINKS__?.();\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 and explicit slot context.\n * storePrefetchResponse() is kept for backward compatibility and test\n * helpers. It is slot-unaware: the snapshot's mountedSlotsHeader comes\n * from the response headers, not the caller, so consumePrefetchResponse\n * may reject the entry if the caller's slot context differs.\n *\n * NB: Caller is responsible for managing getPrefetchedUrls() — this\n * function only stores the response in the prefetch cache.\n */\nexport function storePrefetchResponse(\n rscUrl: string,\n response: Response,\n interceptionContext: string | null = null,\n options?: PrefetchOptions,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n evictPrefetchCacheIfNeeded();\n const entry: PrefetchCacheEntry = {\n outcome: \"pending\",\n timestamp: Date.now(),\n };\n addPrefetchInvalidationCallback(entry, options?.onInvalidate);\n entry.pending = snapshotRscResponse(response)\n .then((snapshot) => {\n entry.snapshot = snapshot;\n })\n .catch(() => {\n deletePrefetchCacheEntry(getPrefetchCache(), getPrefetchedUrls(), cacheKey, entry, false);\n })\n .finally(() => {\n entry.pending = undefined;\n if (entry.snapshot) {\n entry.outcome = \"cache-seeded\";\n schedulePrefetchInvalidation(cacheKey, entry);\n }\n });\n getPrefetchCache().set(cacheKey, entry);\n}\n\nexport function createCachedRscResponseSnapshot(\n response: Response,\n buffer: ArrayBuffer,\n responseUrl: string | null = null,\n): CachedRscResponse {\n return {\n compatibilityIdHeader: response.headers.get(VINEXT_RSC_COMPATIBILITY_ID_HEADER),\n buffer,\n contentType: response.headers.get(\"content-type\") ?? VINEXT_RSC_CONTENT_TYPE,\n mountedSlotsHeader: response.headers.get(VINEXT_MOUNTED_SLOTS_HEADER),\n paramsHeader: response.headers.get(VINEXT_PARAMS_HEADER),\n url: responseUrl ?? response.url,\n };\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 return createCachedRscResponseSnapshot(response, await response.arrayBuffer());\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.mountedSlotsHeader != null) {\n headers.set(VINEXT_MOUNTED_SLOTS_HEADER, cached.mountedSlotsHeader);\n }\n if (cached.compatibilityIdHeader != null) {\n headers.set(VINEXT_RSC_COMPATIBILITY_ID_HEADER, cached.compatibilityIdHeader);\n }\n if (cached.paramsHeader != null) {\n headers.set(VINEXT_PARAMS_HEADER, 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(\n rscUrl: string,\n fetchPromise: Promise<Response>,\n interceptionContext: string | null = null,\n mountedSlotsHeader: string | null = null,\n options?: PrefetchOptions,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cache = getPrefetchCache();\n const prefetched = getPrefetchedUrls();\n const now = Date.now();\n\n const entry: PrefetchCacheEntry = {\n outcome: \"pending\",\n timestamp: now,\n };\n addPrefetchInvalidationCallback(entry, options?.onInvalidate);\n\n entry.pending = fetchPromise\n .then(async (response) => {\n if (response.ok) {\n entry.snapshot = {\n ...(await snapshotRscResponse(response)),\n // Prefetch compatibility is defined by the slot context at fetch\n // time, not by whatever header a reused response happens to carry.\n mountedSlotsHeader,\n };\n } else {\n deletePrefetchCacheEntry(cache, prefetched, cacheKey, entry, false);\n }\n })\n .catch(() => {\n deletePrefetchCacheEntry(cache, prefetched, cacheKey, entry, false);\n })\n .finally(() => {\n entry.pending = undefined;\n if (entry.snapshot) {\n entry.outcome = \"cache-seeded\";\n schedulePrefetchInvalidation(cacheKey, entry);\n }\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(cacheKey, 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(\n rscUrl: string,\n interceptionContext: string | null = null,\n mountedSlotsHeader: string | null = null,\n): CachedRscResponse | null {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cache = getPrefetchCache();\n const entry = cache.get(cacheKey);\n if (!entry) return null;\n\n // Skip in-flight snapshots and error-path residue where pending cleared\n // without a successful transition to a cache-seeded entry.\n if (entry.pending || entry.outcome !== \"cache-seeded\") return null;\n\n deletePrefetchCacheEntry(cache, getPrefetchedUrls(), cacheKey, entry, false);\n\n if (entry.snapshot) {\n if ((entry.snapshot.mountedSlotsHeader ?? null) !== mountedSlotsHeader) {\n // Entry was already removed above. Slot mismatch means the prefetch\n // used stale slot context and cannot be safely reused.\n return null;\n }\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\");\nconst _MOUNTED_SLOTS_HEADER_KEY = Symbol.for(\"vinext.mountedSlotsHeader\");\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 pendingPathname: string | null;\n pendingPathnameNavId: number | 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 CommitClientNavigationStateOptions = {\n releaseSnapshot?: boolean;\n};\n\ntype ClientNavigationGlobal = typeof globalThis & {\n [_CLIENT_NAV_STATE_KEY]?: ClientNavigationState;\n [_MOUNTED_SLOTS_HEADER_KEY]?: string | null;\n};\n\nexport function setMountedSlotsHeader(header: string | null): void {\n if (isServer) return;\n const globalState = window as ClientNavigationGlobal;\n globalState[_MOUNTED_SLOTS_HEADER_KEY] = header;\n}\n\nexport function getMountedSlotsHeader(): string | null {\n if (isServer) return null;\n const globalState = window as ClientNavigationGlobal;\n return globalState[_MOUNTED_SLOTS_HEADER_KEY] ?? null;\n}\n\nexport function 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 pendingPathname: null,\n pendingPathnameNavId: 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 App Router server context - try Pages Router compat shim.\n // See `adaptForSearchParams` in Next.js's adapters:\n // .nextjs-ref/packages/next/src/shared/lib/router/adapters.tsx\n const pagesCtx = _getPagesNavigationContext();\n if (pagesCtx) {\n return new ReadonlyURLSearchParams(pagesCtx.searchParams);\n }\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\n/**\n * Set the pending pathname for client-side navigation.\n * Strips the base path before storing. Associates the pathname with the given navId\n * so only that navigation (or a newer one) can clear it.\n */\nexport function setPendingPathname(pathname: string, navId: number): void {\n const state = getClientNavigationState();\n if (!state) return;\n state.pendingPathname = stripBasePath(pathname, __basePath);\n state.pendingPathnameNavId = navId;\n}\n\n/**\n * Clear the pending pathname, but only if the given navId matches the one\n * that set it, or if pendingPathnameNavId is null (no active owner).\n * This prevents superseded navigations from clearing state belonging to newer navigations.\n */\nexport function clearPendingPathname(navId: number): void {\n const state = getClientNavigationState();\n if (!state) return;\n // Only clear if this navId is the one that set the pendingPathname,\n // or if pendingPathnameNavId is null (no owner)\n if (state.pendingPathnameNavId === null || state.pendingPathnameNavId === navId) {\n state.pendingPathname = null;\n state.pendingPathnameNavId = null;\n }\n}\n\nfunction getClientParamsSnapshot(): Record<string, string | string[]> {\n const state = getClientNavigationState();\n if (state && Object.keys(state.clientParams).length > 0) {\n return state.clientParams;\n }\n // Fall back to the Pages Router compat shim if nothing has populated the\n // App Router client params (Pages Router pages never call setClientParams).\n const pagesCtx = _getPagesNavigationContext();\n if (pagesCtx) return pagesCtx.params;\n return state?.clientParams ?? _EMPTY_PARAMS;\n}\n\nfunction getServerParamsSnapshot(): Record<string, string | string[]> {\n const ctx = _getServerContext();\n if (ctx) return ctx.params;\n // No App Router navigation context — fall back to Pages Router state.\n // See `adaptForPathParams` in Next.js's pages-router adapter:\n // .nextjs-ref/packages/next/src/shared/lib/router/adapters.tsx\n const pagesCtx = _getPagesNavigationContext();\n return pagesCtx?.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/* 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 const ctx = _getServerContext();\n if (ctx) return ctx.pathname;\n // Pages Router compat shim: derive pathname from the Pages Router state.\n return _getPagesNavigationContext()?.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 ?? _getPagesNavigationContext()?.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 // getServerSearchParamsSnapshot also covers the Pages Router compat shim.\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 // getServerParamsSnapshot covers both App Router and Pages Router compat.\n return getServerParamsSnapshot() 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 isAbsoluteOrProtocolRelativeUrl(href);\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 return isHashOnlyBrowserUrlChange(href, window.location.href, __basePath);\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\n/**\n * Commit pending client navigation state to committed snapshots.\n *\n * navId is optional: callers that don't own pendingPathname (for example,\n * superseded pre-paint cleanup) may pass undefined to flush URL/params state\n * without clearing pendingPathname owned by the active navigation. Such callers\n * must opt in explicitly if they also own an activated render snapshot.\n */\nexport function commitClientNavigationState(\n navId?: number,\n options?: CommitClientNavigationStateOptions,\n): void {\n if (isServer) return;\n const state = getClientNavigationState();\n if (!state) return;\n\n // Only navigation-owned commits may release a render snapshot. Ownerless URL\n // syncs still update committed pathname/search state, but must not consume\n // the active snapshot for an in-flight App Router transition.\n const shouldReleaseSnapshot = navId !== undefined || options?.releaseSnapshot === true;\n if (shouldReleaseSnapshot && 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 // Clear pending pathname when navigation commits, but only if:\n // - The navId matches the one that set pendingPathname\n // - No newer navigation has overwritten pendingPathname (pendingPathnameNavId === null or matches)\n // - navId is undefined only for non-owning callers, which must not clear\n // pendingPathname for an active navigation.\n const canClearPendingPathname =\n state.pendingPathnameNavId === null ||\n (navId !== undefined && state.pendingPathnameNavId === navId);\n if (canClearPendingPathname) {\n state.pendingPathname = null;\n state.pendingPathnameNavId = null;\n }\n const shouldNotify = urlChanged || state.hasPendingNavigationUpdate;\n state.hasPendingNavigationUpdate = false;\n\n if (shouldNotify) {\n notifyNavigationListeners();\n window.__VINEXT_PING_VISIBLE_LINKS__?.();\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\nfunction commitHashOnlyHistoryState(href: string, mode: \"push\" | \"replace\", scroll: boolean): void {\n const commitAppRouterHashNavigation = window.__VINEXT_RSC_COMMIT_HASH_NAVIGATION__;\n if (commitAppRouterHashNavigation) {\n commitAppRouterHashNavigation(href, mode, scroll);\n return;\n }\n\n if (mode === \"replace\") {\n replaceHistoryStateWithoutNotify(null, \"\", href);\n } else {\n pushHistoryStateWithoutNotify(null, \"\", href);\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 programmaticTransition = false,\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 commitHashOnlyHistoryState(fullHref, mode, scroll);\n commitClientNavigationState();\n if (scroll) {\n scrollToHashTarget(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 publishes the committed URL.\n if (typeof window.__VINEXT_RSC_NAVIGATE__ === \"function\") {\n await window.__VINEXT_RSC_NAVIGATE__(\n fullHref,\n 0,\n \"navigate\",\n mode,\n undefined,\n programmaticTransition,\n );\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 scrollToHashTarget(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\n/**\n * App Router public router instance. Mirrors Next.js's\n * `publicAppRouterInstance` from\n * `packages/next/src/client/components/app-router-instance.ts`.\n *\n * Exported so the App Router browser entry can install it on\n * `window.next.router` for Next.js parity (see `client/window-next.ts`).\n * Internal callers in this file continue to use `_appRouter` for brevity.\n */\nconst _appRouter = {\n bfcacheId: \"0\",\n push(href: string, options?: { scroll?: boolean }): void {\n assertSafeNavigationUrl(href);\n if (isServer) return;\n React.startTransition(() => {\n void navigateClientSide(href, \"push\", options?.scroll !== false, true);\n });\n },\n replace(href: string, options?: { scroll?: boolean }): void {\n assertSafeNavigationUrl(href);\n if (isServer) return;\n React.startTransition(() => {\n void navigateClientSide(href, \"replace\", options?.scroll !== false, true);\n });\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 // Drop cached RSC payloads for every previously-visited / prefetched route\n // before re-fetching. Next.js's refresh-reducer invalidates the entire\n // segment cache (refresh-reducer.ts → invalidateSegmentCacheEntries), so\n // without this, a stale cached payload for a sibling route (e.g. a page\n // gated by a session that has since been cleared) would still satisfy a\n // subsequent client navigation and bypass the server's redirect logic.\n const clearCaches = window.__VINEXT_CLEAR_NAV_CACHES__;\n if (typeof clearCaches === \"function\") {\n clearCaches();\n }\n // Re-fetch the current page's RSC stream\n const rscNavigate = window.__VINEXT_RSC_NAVIGATE__;\n if (typeof rscNavigate === \"function\") {\n const navigate = () => {\n void rscNavigate(window.location.href, 0, \"refresh\", undefined, undefined, true);\n };\n React.startTransition(navigate);\n }\n },\n prefetch(href: string, options?: PrefetchOptions): void {\n assertSafeNavigationUrl(href);\n if (isServer) return;\n void (async () => {\n // Normalize same-origin absolute URLs to local paths; no-op for external\n // origins so we don't pollute the prefetch cache with a same-path .rsc on\n // the current origin. Mirrors Link's prefetchUrl and navigateClientSide.\n let prefetchHref = href;\n if (isAbsoluteOrProtocolRelativeUrl(href)) {\n const localPath = toSameOriginAppPath(href, __basePath);\n if (localPath == null) return;\n prefetchHref = localPath;\n }\n\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(prefetchHref, window.location.href, __basePath);\n const interceptionContext = getCurrentInterceptionContext();\n const mountedSlotsHeader = getMountedSlotsHeader();\n const headers = createRscRequestHeaders({ interceptionContext });\n if (mountedSlotsHeader) {\n headers.set(VINEXT_MOUNTED_SLOTS_HEADER, mountedSlotsHeader);\n }\n const rscUrl = await createRscRequestUrl(fullHref, headers);\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const prefetched = getPrefetchedUrls();\n if (prefetched.has(cacheKey)) {\n attachPrefetchInvalidationCallback(cacheKey, options?.onInvalidate);\n return;\n }\n prefetched.add(cacheKey);\n prefetchRscResponse(\n rscUrl,\n fetch(rscUrl, {\n headers,\n credentials: \"include\",\n priority: \"low\" as RequestInit[\"priority\"],\n }),\n interceptionContext,\n mountedSlotsHeader,\n options,\n );\n })().catch((error) => {\n console.error(\"[vinext] RSC prefetch setup error:\", error);\n });\n },\n};\n\n/**\n * Public App Router instance, exposed for the browser entry so it can wire\n * `window.next.router` to the same singleton returned from `useRouter()`.\n *\n * Mirrors `publicAppRouterInstance` from Next.js's\n * `packages/next/src/client/components/app-router-instance.ts` (line 392).\n */\nexport const appRouterInstance = _appRouter;\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 if (!AppRouterContext || typeof React.useContext !== \"function\") {\n throw new Error(\"invariant expected app router to be mounted\");\n }\n const router = React.useContext(AppRouterContext);\n if (router === null) {\n throw new Error(\"invariant expected app router to be mounted\");\n }\n return router;\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 if (segments.length === 0) return null;\n\n return parallelRoutesKey === undefined || parallelRoutesKey === \"children\"\n ? segments[0]\n : segments[segments.length - 1];\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 * Render collected useServerInsertedHTML callbacks without unregistering them.\n *\n * Streaming SSR needs to invoke the same style-registry callbacks after each\n * Fizz flush. Libraries such as styled-components and Emotion clear their own\n * per-flush buffers inside the callback; the registration itself must survive\n * until the request stream is closed.\n */\nexport function renderServerInsertedHTML(): 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 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// Internal-error predicates and rethrow\n//\n// `unstable_rethrow` is part of Next.js's public API. User code in try/catch\n// wrappers calls it to let Next.js's control-flow signals (redirect, notFound,\n// forbidden, unauthorized, dynamic-server-usage, bailout-to-CSR, …)\n// propagate up to the framework instead of being swallowed. The canonical\n// use case is a `fetch()` retry helper that needs to bail out the moment\n// fetch throws a framework signal — see Next.js's\n// test/e2e/app-dir/app-static/lib/fetch-retry.js.\n//\n// Ported from Next.js:\n// - packages/next/src/client/components/unstable-rethrow.ts (dispatcher)\n// - packages/next/src/client/components/unstable-rethrow.browser.ts\n// - packages/next/src/client/components/unstable-rethrow.server.ts\n// - packages/next/src/client/components/is-next-router-error.ts\n// - packages/next/src/client/components/redirect-error.ts\n// - packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts\n// - packages/next/src/client/components/hooks-server-context.ts\n//\n// Coverage of Next.js's 7 server-side categories (server build):\n// ✓ isNextRouterError (#1) — redirect + HTTP access fallback\n// ✓ isBailoutToCSRError (#2) — digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\"\n// ✓ isDynamicServerError (#3) — digest === \"DYNAMIC_SERVER_USAGE\"\n// ✗ isDynamicPostpone (#4) — PPR-internal message check; vinext has no PPR\n// ✗ isPostpone (#5) — React.unstable_postpone signal; vinext has no PPR\n// ✗ isHangingPromiseRejectionError (#6) — prerender abort signal\n// ✗ isPrerenderInterruptedError (#7) — prerender controller interrupt\n//\n// The four uncovered categories are server-only Next.js internals tied to\n// prerender-machinery vinext does not implement; user code cannot construct\n// them in normal use. They will be added if/when vinext grows PPR support.\n// ---------------------------------------------------------------------------\n\ntype _RedirectErrorShape = Error & { digest: string };\n\n/**\n * Check whether an error was produced by `redirect()` or `permanentRedirect()`.\n *\n * **Note on vinext public surface:** Next.js does NOT expose `isRedirectError`\n * from `next/navigation` — it's an internal predicate. vinext exposes it for\n * symmetry with the already-public `isHTTPAccessFallbackError` and because\n * `unstable_rethrow` consumers benefit from being able to narrow types.\n * Treat it as a vinext-only extension.\n *\n * **Divergence from Next.js:** Next.js's internal `isRedirectError` performs\n * full 4-segment validation — it splits the digest on `;`, checks `type` ∈\n * {push, replace}, requires a non-empty destination, and validates the\n * status code (303, 307, 308). See:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect-error.ts\n *\n * vinext instead uses a simple prefix check (`startsWith(\"NEXT_REDIRECT;\")`).\n * Reasons:\n * 1. vinext emits two digest shapes — 3-part for `redirect()`\n * (`NEXT_REDIRECT;{type};{encoded-url}`) and 4-part for\n * `permanentRedirect()` (`NEXT_REDIRECT;{type};{encoded-url};308`).\n * Strict validation would have to special-case both, and Next.js's\n * validator (tuned to its 5-part canary digests) rejects them.\n * 2. The `type` field is sometimes empty in vinext's redirect digests\n * (context-dependent resolution; see `redirect()` above), which the\n * strict check disallows.\n *\n * **Consequence:** A malformed digest such as `\"NEXT_REDIRECT;garbage\"`\n * returns `true` here, whereas Next.js would return `false`. In practice,\n * the only callers of this predicate are vinext-internal code paths\n * (`unstable_rethrow`, `unstable_catchError`, the redirect error boundary)\n * that see digests vinext itself emits — so the divergence does not surface\n * in normal use. Maintainers extending the prefix logic should keep this\n * predicate in lockstep with the corresponding `decode*` helpers in\n * `shims/error-boundary.tsx`.\n */\nexport function isRedirectError(error: unknown): error is _RedirectErrorShape {\n if (\n !error ||\n typeof error !== \"object\" ||\n !(\"digest\" in error) ||\n typeof (error as { digest: unknown }).digest !== \"string\"\n ) {\n return false;\n }\n return (error as { digest: string }).digest.startsWith(\"NEXT_REDIRECT;\");\n}\n\n/**\n * Returns true if the error is a Next.js navigation signal — either a redirect\n * or an HTTP access fallback (notFound / forbidden / unauthorized).\n *\n * **Note on vinext public surface:** Like `isRedirectError`, Next.js does NOT\n * expose this from `next/navigation`. vinext exposes it for symmetry — treat\n * it as a vinext-only extension.\n *\n * Ported from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/is-next-router-error.ts\n */\nexport function isNextRouterError(error: unknown): boolean {\n return isRedirectError(error) || isHTTPAccessFallbackError(error);\n}\n\n// ---------------------------------------------------------------------------\n// BailoutToCSRError — `next/dynamic` with `ssr: false` throws this during\n// server render to signal that the dynamic component must be rendered on\n// the client. Lives in shared (non-server) code so it can flow through both\n// the SSR pipeline and userland; third-party libraries that emulate\n// `next/dynamic` also construct it.\n//\n// Ported from Next.js:\n// https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts\n// ---------------------------------------------------------------------------\n\nconst _BAILOUT_TO_CSR_DIGEST = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n\n/**\n * Error thrown to bail out of server rendering and fall back to client-side\n * rendering. Used by `next/dynamic` with `ssr: false`.\n *\n * vinext does not yet emit this error itself — it's exposed so user code and\n * third-party libraries that mimic `next/dynamic`'s bailout semantics can\n * construct an error with the canonical digest that `unstable_rethrow`\n * recognises.\n *\n * Ported 1:1 from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts\n */\nexport class BailoutToCSRError extends Error {\n public readonly digest: typeof _BAILOUT_TO_CSR_DIGEST = _BAILOUT_TO_CSR_DIGEST;\n public readonly reason: string;\n\n constructor(reason: string) {\n super(`Bail out to client-side rendering: ${reason}`);\n this.reason = reason;\n }\n}\n\n/**\n * Returns true if the error is a `BailoutToCSRError`. Matches Next.js's\n * digest-based predicate, so any error from a foreign module instance of\n * the class (or constructed manually with the canonical digest) is also\n * detected.\n *\n * **Note on vinext public surface:** Next.js does NOT expose this from\n * `next/navigation`. vinext exposes it for symmetry with `isRedirectError`\n * — treat it as a vinext-only extension. The matching producer\n * (`BailoutToCSRError`) is the public detection contract; Next.js exposes\n * neither.\n *\n * Ported from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts\n */\nexport function isBailoutToCSRError(error: unknown): error is BailoutToCSRError {\n if (!error || typeof error !== \"object\" || !(\"digest\" in error)) {\n return false;\n }\n return (error as { digest: unknown }).digest === _BAILOUT_TO_CSR_DIGEST;\n}\n\n// ---------------------------------------------------------------------------\n// DynamicServerError — thrown by Next.js's internal `cookies()`/`headers()`\n// shims when called inside a static render context that cannot resolve\n// request-scoped data. vinext's own `next/headers` shim has its own throw\n// semantics, so vinext never constructs this error itself, but third-party\n// code or accidentally-bundled Next.js internals can.\n//\n// Ported from Next.js:\n// https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/hooks-server-context.ts\n// ---------------------------------------------------------------------------\n\nconst _DYNAMIC_SERVER_USAGE_DIGEST = \"DYNAMIC_SERVER_USAGE\";\n\n/**\n * Error thrown when dynamic server APIs (`cookies()`, `headers()`, etc.) are\n * used inside a static/prerender context. Carries the `DYNAMIC_SERVER_USAGE`\n * digest so `unstable_rethrow` can recognise and propagate it.\n *\n * vinext does not construct this error itself — exposed for the same\n * \"stable detection contract\" reason as `BailoutToCSRError` above.\n *\n * Ported 1:1 from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/hooks-server-context.ts\n */\nexport class DynamicServerError extends Error {\n public readonly digest: typeof _DYNAMIC_SERVER_USAGE_DIGEST = _DYNAMIC_SERVER_USAGE_DIGEST;\n public readonly description: string;\n\n constructor(description: string) {\n super(`Dynamic server usage: ${description}`);\n this.description = description;\n }\n}\n\n/**\n * Returns true if the error is a `DynamicServerError` (or any error with the\n * canonical `DYNAMIC_SERVER_USAGE` digest).\n *\n * **Note on vinext public surface:** Next.js does NOT expose this from\n * `next/navigation`. vinext exposes it for symmetry — treat it as a\n * vinext-only extension.\n *\n * Ported from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/hooks-server-context.ts\n */\nexport function isDynamicServerError(error: unknown): error is DynamicServerError {\n if (!error || typeof error !== \"object\" || !(\"digest\" in error)) {\n return false;\n }\n // `===` against a string literal already requires the operand to be a\n // string, so no separate `typeof digest === \"string\"` check is needed.\n // Matches `isBailoutToCSRError` above for stylistic consistency.\n return (error as { digest: unknown }).digest === _DYNAMIC_SERVER_USAGE_DIGEST;\n}\n\n/**\n * Rethrow internal Next.js errors so they're handled by the framework.\n *\n * When wrapping an API that uses errors for control flow (redirect, notFound,\n * cookies in static render, `next/dynamic` SSR bailout, etc.), call this\n * inside `catch` blocks before doing your own error handling. If the error\n * is a Next.js internal error, it's rethrown; otherwise this is a no-op\n * (apart from recursing through `error.cause`).\n *\n * Recognises (matches Next.js's browser build + the subset of the server\n * build that vinext can realistically encounter):\n * - `isNextRouterError`: redirect / notFound / forbidden / unauthorized\n * - `isBailoutToCSRError`: `next/dynamic` `ssr: false` bailout\n * - `isDynamicServerError`: dynamic API used in static render\n *\n * vinext does not yet recognise four additional server-only Next.js\n * categories — `isDynamicPostpone`, `isPostpone`,\n * `isHangingPromiseRejectionError`, `isPrerenderInterruptedError` — because\n * they signal PPR / prerender-controller events that vinext's render\n * pipeline does not generate. User code cannot construct these in normal\n * use; they will be added if/when vinext grows PPR support.\n *\n * Ported from Next.js:\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/unstable-rethrow.ts\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/unstable-rethrow.server.ts\n * https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/unstable-rethrow.browser.ts\n */\nexport function unstable_rethrow(error: unknown): void {\n if (isNextRouterError(error) || isBailoutToCSRError(error) || isDynamicServerError(error)) {\n throw error;\n }\n\n if (error instanceof Error && \"cause\" in error) {\n unstable_rethrow((error as Error & { cause: unknown }).cause);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Unrecognized server-action errors\n//\n// `UnrecognizedActionError` / `unstable_isUnrecognizedActionError` live in a\n// dedicated zero-dependency module so this `next/navigation` shim and vinext's\n// client server-action dispatcher (`server/server-action-not-found.ts`) share\n// one class. `instanceof` is identity-based per module instance, so the\n// dispatcher and user code must resolve the same class for the predicate to\n// work. Re-exported here to keep the public `next/navigation` surface intact.\n// ---------------------------------------------------------------------------\n\nexport {\n UnrecognizedActionError,\n unstable_isUnrecognizedActionError,\n} from \"./unrecognized-action-error.js\";\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(\n window.history,\n createExternalHistoryStatePreservingMetadata(data, window.history.state),\n unused,\n url,\n );\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(\n window.history,\n createExternalHistoryStatePreservingMetadata(data, window.history.state),\n unused,\n url,\n );\n if (state.suppressUrlNotifyCount === 0) {\n commitClientNavigationState();\n }\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,0BAA0B,OAAO,IAAI,8BAA8B;AACzE,MAAM,gCAAgC,OAAO,IAAI,mCAAmC;AAiCpF,SAAS,+BAEA;CACP,IAAI,OAAOA,QAAM,kBAAkB,YAAY,OAAO;CAEtD,MAAM,cAAc;CACpB,IAAI,CAAC,YAAY,gCACf,YAAY,iCAAiCA,QAAM,cAEjD,KAAK;CAGT,OAAO,YAAY,kCAAkC;;AAGvD,MAAa,4BAEF,8BAA8B;;;;;AAMzC,SAAgB,0BAA4D;CAC1E,IAAI,OAAOA,QAAM,kBAAkB,YAAY,OAAO;CAEtD,MAAM,cAAc;CACpB,IAAI,CAAC,YAAY,0BACf,YAAY,2BAA2BA,QAAM,cAA0B,EAAE,UAAU,EAAE,EAAE,CAAC;CAG1F,OAAO,YAAY,4BAA4B;;;;;;;AASjD,SAAS,iBAAiB,oBAA4B,YAAsB;CAC1E,MAAM,MAAM,yBAAyB;CACrC,IAAI,CAAC,KAAK,OAAO,EAAE;CAInB,IAAI;EAEF,OADmBA,QAAM,WAAW,IACnB,CAAC,sBAAsB,EAAE;SACpC;EACN,OAAO,EAAE;;;AAeb,MAAM,0BAA0B,OAAO,yCAAyC;AAChF,MAAM,iCAAiC,OAAO,+CAA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MAAM,OAAO,QAAQ,MAAM,EACxE,QACA,IACD;GACD,IAAI,MAAM,2BAA2B,GACnC,6BAA6B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReadonlyURLSearchParams } from "./readonly-url-search-params.js";
|
|
2
|
-
import { GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, NavigationContext, RedirectType, SegmentMap, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isHTTPAccessFallbackError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized } from "./navigation.js";
|
|
2
|
+
import { BailoutToCSRError, DynamicServerError, GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, NavigationContext, RedirectType, SegmentMap, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isBailoutToCSRError, isDynamicServerError, isHTTPAccessFallbackError, isNextRouterError, isRedirectError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, unstable_rethrow } from "./navigation.js";
|
|
3
3
|
|
|
4
4
|
//#region src/shims/navigation.react-server.d.ts
|
|
5
5
|
declare function usePathname(): never;
|
|
@@ -9,6 +9,7 @@ declare function useRouter(): never;
|
|
|
9
9
|
declare function useSelectedLayoutSegment(): never;
|
|
10
10
|
declare function useSelectedLayoutSegments(): never;
|
|
11
11
|
declare function useServerInsertedHTML(): never;
|
|
12
|
+
declare function unstable_isUnrecognizedActionError(): boolean;
|
|
12
13
|
//#endregion
|
|
13
|
-
export { GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, type NavigationContext, ReadonlyURLSearchParams, RedirectType, type SegmentMap, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isHTTPAccessFallbackError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, useServerInsertedHTML };
|
|
14
|
+
export { BailoutToCSRError, DynamicServerError, GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, type NavigationContext, ReadonlyURLSearchParams, RedirectType, type SegmentMap, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isBailoutToCSRError, isDynamicServerError, isHTTPAccessFallbackError, isNextRouterError, isRedirectError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, unstable_isUnrecognizedActionError, unstable_rethrow, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, useServerInsertedHTML };
|
|
14
15
|
//# sourceMappingURL=navigation.react-server.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReadonlyURLSearchParams } from "./readonly-url-search-params.js";
|
|
2
|
-
import { GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, RedirectType, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isHTTPAccessFallbackError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized } from "./navigation.js";
|
|
2
|
+
import { BailoutToCSRError, DynamicServerError, GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, RedirectType, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isBailoutToCSRError, isDynamicServerError, isHTTPAccessFallbackError, isNextRouterError, isRedirectError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, unstable_rethrow } from "./navigation.js";
|
|
3
3
|
import { throwClientHookError } from "./client-hook-error.js";
|
|
4
4
|
//#region src/shims/navigation.react-server.ts
|
|
5
5
|
function usePathname() {
|
|
@@ -23,7 +23,10 @@ function useSelectedLayoutSegments() {
|
|
|
23
23
|
function useServerInsertedHTML() {
|
|
24
24
|
throwClientHookError("useServerInsertedHTML()");
|
|
25
25
|
}
|
|
26
|
+
function unstable_isUnrecognizedActionError() {
|
|
27
|
+
throw new Error("`unstable_isUnrecognizedActionError` can only be used on the client.");
|
|
28
|
+
}
|
|
26
29
|
//#endregion
|
|
27
|
-
export { GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, ReadonlyURLSearchParams, RedirectType, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isHTTPAccessFallbackError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, useServerInsertedHTML };
|
|
30
|
+
export { BailoutToCSRError, DynamicServerError, GLOBAL_ACCESSORS_KEY, HTTP_ERROR_FALLBACK_ERROR_CODE, ReadonlyURLSearchParams, RedirectType, ServerInsertedHTMLContext, _registerStateAccessors, clearServerInsertedHTML, flushServerInsertedHTML, forbidden, getAccessFallbackHTTPStatus, getLayoutSegmentContext, getNavigationContext, isBailoutToCSRError, isDynamicServerError, isHTTPAccessFallbackError, isNextRouterError, isRedirectError, notFound, permanentRedirect, redirect, renderServerInsertedHTML, setNavigationContext, unauthorized, unstable_isUnrecognizedActionError, unstable_rethrow, useParams, usePathname, useRouter, useSearchParams, useSelectedLayoutSegment, useSelectedLayoutSegments, useServerInsertedHTML };
|
|
28
31
|
|
|
29
32
|
//# sourceMappingURL=navigation.react-server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation.react-server.js","names":[],"sources":["../../src/shims/navigation.react-server.ts"],"sourcesContent":["import { throwClientHookError } from \"./client-hook-error.js\";\n\n// Re-export server-safe APIs from the canonical navigation module.\n// This import uses a relative path to the source file, which does NOT\n// go through the `next/navigation` resolveId hook — so it always\n// resolves to the full module, avoiding a circular redirect.\nexport {\n // Types\n type NavigationContext,\n type SegmentMap,\n\n // Server-side navigation state\n GLOBAL_ACCESSORS_KEY,\n _registerStateAccessors,\n getNavigationContext,\n setNavigationContext,\n\n // Layout segment context (returns null in RSC — createContext unavailable)\n getLayoutSegmentContext,\n ServerInsertedHTMLContext,\n\n // Server-inserted HTML\n flushServerInsertedHTML,\n renderServerInsertedHTML,\n clearServerInsertedHTML,\n\n // Control-flow errors\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n isHTTPAccessFallbackError,\n getAccessFallbackHTTPStatus,\n RedirectType,\n redirect,\n permanentRedirect,\n notFound,\n forbidden,\n unauthorized,\n\n // Utilities\n ReadonlyURLSearchParams,\n} from \"./navigation.js\";\n\n// These hooks are client-only. Exporting error-throwing stubs (rather than\n// omitting them entirely) gives developers a clear, actionable error message\n// instead of the cryptic \"is not a function\" that Vite's runtime module\n// system produces for missing exports.\n\nexport function usePathname(): never {\n throwClientHookError(\"usePathname()\");\n}\n\nexport function useSearchParams(): never {\n throwClientHookError(\"useSearchParams()\");\n}\n\nexport function useParams(): never {\n throwClientHookError(\"useParams()\");\n}\n\nexport function useRouter(): never {\n throwClientHookError(\"useRouter()\");\n}\n\nexport function useSelectedLayoutSegment(): never {\n throwClientHookError(\"useSelectedLayoutSegment()\");\n}\n\nexport function useSelectedLayoutSegments(): never {\n throwClientHookError(\"useSelectedLayoutSegments()\");\n}\n\nexport function useServerInsertedHTML(): never {\n throwClientHookError(\"useServerInsertedHTML()\");\n}\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"navigation.react-server.js","names":[],"sources":["../../src/shims/navigation.react-server.ts"],"sourcesContent":["import { throwClientHookError } from \"./client-hook-error.js\";\n\n// Re-export server-safe APIs from the canonical navigation module.\n// This import uses a relative path to the source file, which does NOT\n// go through the `next/navigation` resolveId hook — so it always\n// resolves to the full module, avoiding a circular redirect.\nexport {\n // Types\n type NavigationContext,\n type SegmentMap,\n\n // Server-side navigation state\n GLOBAL_ACCESSORS_KEY,\n _registerStateAccessors,\n getNavigationContext,\n setNavigationContext,\n\n // Layout segment context (returns null in RSC — createContext unavailable)\n getLayoutSegmentContext,\n ServerInsertedHTMLContext,\n\n // Server-inserted HTML\n flushServerInsertedHTML,\n renderServerInsertedHTML,\n clearServerInsertedHTML,\n\n // Control-flow errors\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n isHTTPAccessFallbackError,\n getAccessFallbackHTTPStatus,\n RedirectType,\n redirect,\n permanentRedirect,\n notFound,\n forbidden,\n unauthorized,\n\n // Internal-error predicates and rethrow.\n //\n // These are environment-agnostic (no React hooks, no browser globals), so\n // we re-export the canonical implementation from `./navigation.js` to keep\n // a single source of truth across the react-server and client conditions.\n //\n // Ported from Next.js:\n // https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/navigation.react-server.ts\n // where `unstable_rethrow` is also re-exported in the react-server build.\n isRedirectError,\n isNextRouterError,\n isBailoutToCSRError,\n isDynamicServerError,\n BailoutToCSRError,\n DynamicServerError,\n unstable_rethrow,\n\n // Utilities\n ReadonlyURLSearchParams,\n} from \"./navigation.js\";\n\n// These hooks are client-only. Exporting error-throwing stubs (rather than\n// omitting them entirely) gives developers a clear, actionable error message\n// instead of the cryptic \"is not a function\" that Vite's runtime module\n// system produces for missing exports.\n\nexport function usePathname(): never {\n throwClientHookError(\"usePathname()\");\n}\n\nexport function useSearchParams(): never {\n throwClientHookError(\"useSearchParams()\");\n}\n\nexport function useParams(): never {\n throwClientHookError(\"useParams()\");\n}\n\nexport function useRouter(): never {\n throwClientHookError(\"useRouter()\");\n}\n\nexport function useSelectedLayoutSegment(): never {\n throwClientHookError(\"useSelectedLayoutSegment()\");\n}\n\nexport function useSelectedLayoutSegments(): never {\n throwClientHookError(\"useSelectedLayoutSegments()\");\n}\n\nexport function useServerInsertedHTML(): never {\n throwClientHookError(\"useServerInsertedHTML()\");\n}\n\n// `unstable_isUnrecognizedActionError` is client-only: server actions cannot\n// fail with \"unrecognized action\" inside the React-server render path because\n// they execute synchronously against the action manifest. Calling this from a\n// Server Component is always a programming error.\n//\n// Ported from Next.js:\n// https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/navigation.react-server.ts\n// which throws the same diagnostic message from the react-server condition.\nexport function unstable_isUnrecognizedActionError(): boolean {\n throw new Error(\"`unstable_isUnrecognizedActionError` can only be used on the client.\");\n}\n"],"mappings":";;;;AA+DA,SAAgB,cAAqB;CACnC,qBAAqB,gBAAgB;;AAGvC,SAAgB,kBAAyB;CACvC,qBAAqB,oBAAoB;;AAG3C,SAAgB,YAAmB;CACjC,qBAAqB,cAAc;;AAGrC,SAAgB,YAAmB;CACjC,qBAAqB,cAAc;;AAGrC,SAAgB,2BAAkC;CAChD,qBAAqB,6BAA6B;;AAGpD,SAAgB,4BAAmC;CACjD,qBAAqB,8BAA8B;;AAGrD,SAAgB,wBAA+B;CAC7C,qBAAqB,0BAA0B;;AAWjD,SAAgB,qCAA8C;CAC5D,MAAM,IAAI,MAAM,uEAAuE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"offline.js","names":[],"sources":["../../src/shims/offline.ts"],"sourcesContent":["/**\n * next/offline shim\n *\n * Stub for the experimental `useOffline()` hook added in Next.js\n * (vercel/next.js#92012). Returns `false` (online) unconditionally.\n * Full offline retry behavior (navigation retry, prefetch pause/resume,\n * OfflineProvider) will be implemented once the feature stabilizes upstream.\n */\n\"use client\";\n\nexport function useOffline(): boolean {\n return false;\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,aAAsB;
|
|
1
|
+
{"version":3,"file":"offline.js","names":[],"sources":["../../src/shims/offline.ts"],"sourcesContent":["/**\n * next/offline shim\n *\n * Stub for the experimental `useOffline()` hook added in Next.js\n * (vercel/next.js#92012). Returns `false` (online) unconditionally.\n * Full offline retry behavior (navigation retry, prefetch pause/resume,\n * OfflineProvider) will be implemented once the feature stabilizes upstream.\n */\n\"use client\";\n\nexport function useOffline(): boolean {\n return false;\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,aAAsB;CACpC,OAAO"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
//#region src/shims/pages-router-runtime.d.ts
|
|
2
|
+
type PagesRouterPopStateHandler = (event: PopStateEvent) => void;
|
|
3
|
+
declare function setPagesRouterPopStateHandler(handler: PagesRouterPopStateHandler): void;
|
|
4
|
+
declare function installPagesRouterRuntime(): void;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { installPagesRouterRuntime, setPagesRouterPopStateHandler };
|
|
7
|
+
//# sourceMappingURL=pages-router-runtime.d.ts.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/shims/pages-router-runtime.ts
|
|
2
|
+
let pagesRouterPopStateHandler;
|
|
3
|
+
let pagesRouterRuntimeInstalled = false;
|
|
4
|
+
function setPagesRouterPopStateHandler(handler) {
|
|
5
|
+
pagesRouterPopStateHandler = handler;
|
|
6
|
+
}
|
|
7
|
+
function installPagesRouterRuntime() {
|
|
8
|
+
if (typeof window === "undefined" || pagesRouterRuntimeInstalled) return;
|
|
9
|
+
if (!pagesRouterPopStateHandler) throw new Error("[vinext] Pages Router runtime installed before next/router was initialized");
|
|
10
|
+
pagesRouterRuntimeInstalled = true;
|
|
11
|
+
window.addEventListener("popstate", pagesRouterPopStateHandler);
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { installPagesRouterRuntime, setPagesRouterPopStateHandler };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=pages-router-runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pages-router-runtime.js","names":[],"sources":["../../src/shims/pages-router-runtime.ts"],"sourcesContent":["type PagesRouterPopStateHandler = (event: PopStateEvent) => void;\n\nlet pagesRouterPopStateHandler: PagesRouterPopStateHandler | undefined;\nlet pagesRouterRuntimeInstalled = false;\n\nexport function setPagesRouterPopStateHandler(handler: PagesRouterPopStateHandler): void {\n pagesRouterPopStateHandler = handler;\n}\n\nexport function installPagesRouterRuntime(): void {\n if (typeof window === \"undefined\" || pagesRouterRuntimeInstalled) {\n return;\n }\n\n if (!pagesRouterPopStateHandler) {\n throw new Error(\"[vinext] Pages Router runtime installed before next/router was initialized\");\n }\n\n pagesRouterRuntimeInstalled = true;\n window.addEventListener(\"popstate\", pagesRouterPopStateHandler);\n}\n"],"mappings":";AAEA,IAAI;AACJ,IAAI,8BAA8B;AAElC,SAAgB,8BAA8B,SAA2C;CACvF,6BAA6B;;AAG/B,SAAgB,4BAAkC;CAChD,IAAI,OAAO,WAAW,eAAe,6BACnC;CAGF,IAAI,CAAC,4BACH,MAAM,IAAI,MAAM,6EAA6E;CAG/F,8BAA8B;CAC9B,OAAO,iBAAiB,YAAY,2BAA2B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readonly-url-search-params.js","names":[],"sources":["../../src/shims/readonly-url-search-params.ts"],"sourcesContent":["class ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n \"Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams\",\n );\n }\n}\n\n/**\n * Read-only URLSearchParams wrapper matching Next.js runtime behavior.\n * Mutation methods remain present for instanceof/API compatibility but throw.\n */\nexport class ReadonlyURLSearchParams extends URLSearchParams {\n append(_name: string, _value: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n delete(_name: string, _value?: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n set(_name: string, _value: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n sort(): never {\n throw new ReadonlyURLSearchParamsError();\n }\n}\n"],"mappings":";AAAA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,cAAc;
|
|
1
|
+
{"version":3,"file":"readonly-url-search-params.js","names":[],"sources":["../../src/shims/readonly-url-search-params.ts"],"sourcesContent":["class ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n \"Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams\",\n );\n }\n}\n\n/**\n * Read-only URLSearchParams wrapper matching Next.js runtime behavior.\n * Mutation methods remain present for instanceof/API compatibility but throw.\n */\nexport class ReadonlyURLSearchParams extends URLSearchParams {\n append(_name: string, _value: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n delete(_name: string, _value?: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n set(_name: string, _value: string): never {\n throw new ReadonlyURLSearchParamsError();\n }\n\n sort(): never {\n throw new ReadonlyURLSearchParamsError();\n }\n}\n"],"mappings":";AAAA,IAAM,+BAAN,cAA2C,MAAM;CAC/C,cAAc;EACZ,MACE,0JACD;;;;;;;AAQL,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D,OAAO,OAAe,QAAuB;EAC3C,MAAM,IAAI,8BAA8B;;CAG1C,OAAO,OAAe,QAAwB;EAC5C,MAAM,IAAI,8BAA8B;;CAG1C,IAAI,OAAe,QAAuB;EACxC,MAAM,IAAI,8BAA8B;;CAG1C,OAAc;EACZ,MAAM,IAAI,8BAA8B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-context.js","names":[],"sources":["../../src/shims/request-context.ts"],"sourcesContent":["/**\n * Request ExecutionContext — AsyncLocalStorage-backed accessor.\n *\n * Makes the Cloudflare Workers `ExecutionContext` (which provides\n * `waitUntil`) available to any code on the call stack during a request\n * without requiring it to be threaded through every function signature.\n *\n * Usage:\n *\n * // In the worker entry, wrap the handler:\n * import { runWithExecutionContext } from \"vinext/shims/request-context\";\n * export default {\n * fetch(request, env, ctx) {\n * return runWithExecutionContext(ctx, () => handler.fetch(request, env, ctx));\n * }\n * };\n *\n * // Anywhere downstream:\n * import { getRequestExecutionContext } from \"vinext/shims/request-context\";\n * const ctx = getRequestExecutionContext(); // null on Node.js dev\n * ctx?.waitUntil(somePromise);\n */\n\nimport { getOrCreateAls } from \"./internal/als-registry.js\";\nimport {\n isInsideUnifiedScope,\n getRequestContext,\n runWithUnifiedStateMutation,\n} from \"./unified-request-context.js\";\n\n// ---------------------------------------------------------------------------\n// ExecutionContext interface\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal ExecutionContext interface matching the Cloudflare Workers runtime.\n * Using a structural interface so this file has no runtime dependency on\n * Cloudflare types packages.\n */\nexport type ExecutionContextLike = {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException?(): void;\n};\n\n// ---------------------------------------------------------------------------\n// ALS setup — stored on globalThis so all Vite environments (RSC/SSR/client)\n// share the same instance and see the same per-request context.\n// ---------------------------------------------------------------------------\n\nconst _als = getOrCreateAls<ExecutionContextLike | null>(\"vinext.requestContext.als\");\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run `fn` with the given `ExecutionContext` available via\n * `getRequestExecutionContext()` for the duration of the call (including\n * all async continuations, such as RSC streaming).\n *\n * Call this at the top of your Worker's `fetch` handler, wrapping the\n * delegation to vinext so the context propagates through the entire\n * request pipeline.\n */\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n if (isInsideUnifiedScope()) {\n return runWithUnifiedStateMutation((uCtx) => {\n uCtx.executionContext = ctx;\n }, fn);\n }\n return _als.run(ctx, fn);\n}\n\n/**\n * Get the `ExecutionContext` for the current request, or `null` when called\n * outside a `runWithExecutionContext()` scope (e.g. on Node.js dev server).\n *\n * Use `ctx?.waitUntil(promise)` to schedule background work that must\n * complete before the Worker isolate is torn down.\n */\nexport function getRequestExecutionContext(): ExecutionContextLike | null {\n if (isInsideUnifiedScope()) {\n return getRequestContext().executionContext;\n }\n // getStore() returns undefined when called outside an ALS scope;\n // normalise to null for a consistent return type.\n return _als.getStore() ?? null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,OAAO,eAA4C,4BAA4B;AAuBrF,SAAgB,wBACd,KACA,IACgB;
|
|
1
|
+
{"version":3,"file":"request-context.js","names":[],"sources":["../../src/shims/request-context.ts"],"sourcesContent":["/**\n * Request ExecutionContext — AsyncLocalStorage-backed accessor.\n *\n * Makes the Cloudflare Workers `ExecutionContext` (which provides\n * `waitUntil`) available to any code on the call stack during a request\n * without requiring it to be threaded through every function signature.\n *\n * Usage:\n *\n * // In the worker entry, wrap the handler:\n * import { runWithExecutionContext } from \"vinext/shims/request-context\";\n * export default {\n * fetch(request, env, ctx) {\n * return runWithExecutionContext(ctx, () => handler.fetch(request, env, ctx));\n * }\n * };\n *\n * // Anywhere downstream:\n * import { getRequestExecutionContext } from \"vinext/shims/request-context\";\n * const ctx = getRequestExecutionContext(); // null on Node.js dev\n * ctx?.waitUntil(somePromise);\n */\n\nimport { getOrCreateAls } from \"./internal/als-registry.js\";\nimport {\n isInsideUnifiedScope,\n getRequestContext,\n runWithUnifiedStateMutation,\n} from \"./unified-request-context.js\";\n\n// ---------------------------------------------------------------------------\n// ExecutionContext interface\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal ExecutionContext interface matching the Cloudflare Workers runtime.\n * Using a structural interface so this file has no runtime dependency on\n * Cloudflare types packages.\n */\nexport type ExecutionContextLike = {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException?(): void;\n};\n\n// ---------------------------------------------------------------------------\n// ALS setup — stored on globalThis so all Vite environments (RSC/SSR/client)\n// share the same instance and see the same per-request context.\n// ---------------------------------------------------------------------------\n\nconst _als = getOrCreateAls<ExecutionContextLike | null>(\"vinext.requestContext.als\");\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run `fn` with the given `ExecutionContext` available via\n * `getRequestExecutionContext()` for the duration of the call (including\n * all async continuations, such as RSC streaming).\n *\n * Call this at the top of your Worker's `fetch` handler, wrapping the\n * delegation to vinext so the context propagates through the entire\n * request pipeline.\n */\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithExecutionContext<T>(\n ctx: ExecutionContextLike,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n if (isInsideUnifiedScope()) {\n return runWithUnifiedStateMutation((uCtx) => {\n uCtx.executionContext = ctx;\n }, fn);\n }\n return _als.run(ctx, fn);\n}\n\n/**\n * Get the `ExecutionContext` for the current request, or `null` when called\n * outside a `runWithExecutionContext()` scope (e.g. on Node.js dev server).\n *\n * Use `ctx?.waitUntil(promise)` to schedule background work that must\n * complete before the Worker isolate is torn down.\n */\nexport function getRequestExecutionContext(): ExecutionContextLike | null {\n if (isInsideUnifiedScope()) {\n return getRequestContext().executionContext;\n }\n // getStore() returns undefined when called outside an ALS scope;\n // normalise to null for a consistent return type.\n return _als.getStore() ?? null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,OAAO,eAA4C,4BAA4B;AAuBrF,SAAgB,wBACd,KACA,IACgB;CAChB,IAAI,sBAAsB,EACxB,OAAO,6BAA6B,SAAS;EAC3C,KAAK,mBAAmB;IACvB,GAAG;CAER,OAAO,KAAK,IAAI,KAAK,GAAG;;;;;;;;;AAU1B,SAAgB,6BAA0D;CACxE,IAAI,sBAAsB,EACxB,OAAO,mBAAmB,CAAC;CAI7B,OAAO,KAAK,UAAU,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"root-params.js","names":[],"sources":["../../src/shims/root-params.ts"],"sourcesContent":["import { getRequestContext, isInsideUnifiedScope } from \"./unified-request-context.js\";\n\nexport type RootParams = Record<string, string | string[] | undefined>;\n\nexport type RootParamsState = {\n rootParams: RootParams | null;\n};\n\nconst _FALLBACK_KEY = Symbol.for(\"vinext.rootParams.fallback\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\n\nconst _fallbackState = (_g[_FALLBACK_KEY] ??= {\n rootParams: null,\n} satisfies RootParamsState) as RootParamsState;\n\nfunction getState(): RootParamsState {\n if (isInsideUnifiedScope()) {\n return getRequestContext();\n }\n return _fallbackState;\n}\n\nexport function pickRootParams(\n params: RootParams,\n rootParamNames: readonly string[] | null | undefined,\n): RootParams {\n const picked: RootParams = {};\n for (const name of rootParamNames ?? []) {\n picked[name] = params[name];\n }\n return picked;\n}\n\nexport function setRootParams(params: RootParams | null): void {\n getState().rootParams = params;\n}\n\nexport function getRootParam(name: string): Promise<string | string[] | undefined> {\n return Promise.resolve(getState().rootParams?.[name]);\n}\n"],"mappings":";;AAQA,MAAM,gBAAgB,OAAO,IAAI,6BAA6B;AAC9D,MAAM,KAAK;AAEX,MAAM,iBAAkB,GAAG,mBAAmB,EAC5C,YAAY,MACb;AAED,SAAS,WAA4B;
|
|
1
|
+
{"version":3,"file":"root-params.js","names":[],"sources":["../../src/shims/root-params.ts"],"sourcesContent":["import { getRequestContext, isInsideUnifiedScope } from \"./unified-request-context.js\";\n\nexport type RootParams = Record<string, string | string[] | undefined>;\n\nexport type RootParamsState = {\n rootParams: RootParams | null;\n};\n\nconst _FALLBACK_KEY = Symbol.for(\"vinext.rootParams.fallback\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\n\nconst _fallbackState = (_g[_FALLBACK_KEY] ??= {\n rootParams: null,\n} satisfies RootParamsState) as RootParamsState;\n\nfunction getState(): RootParamsState {\n if (isInsideUnifiedScope()) {\n return getRequestContext();\n }\n return _fallbackState;\n}\n\nexport function pickRootParams(\n params: RootParams,\n rootParamNames: readonly string[] | null | undefined,\n): RootParams {\n const picked: RootParams = {};\n for (const name of rootParamNames ?? []) {\n picked[name] = params[name];\n }\n return picked;\n}\n\nexport function setRootParams(params: RootParams | null): void {\n getState().rootParams = params;\n}\n\nexport function getRootParam(name: string): Promise<string | string[] | undefined> {\n return Promise.resolve(getState().rootParams?.[name]);\n}\n"],"mappings":";;AAQA,MAAM,gBAAgB,OAAO,IAAI,6BAA6B;AAC9D,MAAM,KAAK;AAEX,MAAM,iBAAkB,GAAG,mBAAmB,EAC5C,YAAY,MACb;AAED,SAAS,WAA4B;CACnC,IAAI,sBAAsB,EACxB,OAAO,mBAAmB;CAE5B,OAAO;;AAGT,SAAgB,eACd,QACA,gBACY;CACZ,MAAM,SAAqB,EAAE;CAC7B,KAAK,MAAM,QAAQ,kBAAkB,EAAE,EACrC,OAAO,QAAQ,OAAO;CAExB,OAAO;;AAGT,SAAgB,cAAc,QAAiC;CAC7D,UAAU,CAAC,aAAa;;AAG1B,SAAgB,aAAa,MAAsD;CACjF,OAAO,QAAQ,QAAQ,UAAU,CAAC,aAAa,MAAM"}
|