UNPKG

33.5 kBJavaScriptView Raw
1/**
2 * react-router v7.14.1
3 *
4 * Copyright (c) Remix Software Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE.md file in the root directory of this source tree.
8 *
9 * @license MIT
10 */
11"use client";
12import {
13 RSCRouterGlobalErrorBoundary,
14 deserializeErrors,
15 getHydrationData,
16 populateRSCRouteModules
17} from "./chunk-BFXCU3MI.mjs";
18import {
19 CRITICAL_CSS_DATA_ATTRIBUTE,
20 ErrorResponseImpl,
21 FrameworkContext,
22 RSCRouterContext,
23 RemixErrorBoundary,
24 RouterProvider,
25 createBrowserHistory,
26 createClientRoutes,
27 createClientRoutesWithHMRRevalidationOptOut,
28 createContext,
29 createRequestInit,
30 createRouter,
31 decodeViaTurboStream,
32 getPatchRoutesOnNavigationFunction,
33 getSingleFetchDataStrategyImpl,
34 getTurboStreamSingleFetchDataStrategy,
35 hydrationRouteProperties,
36 invalidProtocols,
37 invariant,
38 isMutationMethod,
39 mapRouteProperties,
40 noActionDefinedError,
41 setIsHydrated,
42 shouldHydrateRouteLoader,
43 singleFetchUrl,
44 stripIndexParam,
45 useFogOFWarDiscovery
46} from "./chunk-OE4NN4TA.mjs";
47
48// lib/dom-export/dom-router-provider.tsx
49import * as React from "react";
50import * as ReactDOM from "react-dom";
51function RouterProvider2(props) {
52 return /* @__PURE__ */ React.createElement(RouterProvider, { flushSync: ReactDOM.flushSync, ...props });
53}
54
55// lib/dom-export/hydrated-router.tsx
56import * as React2 from "react";
57var ssrInfo = null;
58var router = null;
59function initSsrInfo() {
60 if (!ssrInfo && window.__reactRouterContext && window.__reactRouterManifest && window.__reactRouterRouteModules) {
61 if (window.__reactRouterManifest.sri === true) {
62 const importMap = document.querySelector("script[rr-importmap]");
63 if (importMap?.textContent) {
64 try {
65 window.__reactRouterManifest.sri = JSON.parse(
66 importMap.textContent
67 ).integrity;
68 } catch (err) {
69 console.error("Failed to parse import map", err);
70 }
71 }
72 }
73 ssrInfo = {
74 context: window.__reactRouterContext,
75 manifest: window.__reactRouterManifest,
76 routeModules: window.__reactRouterRouteModules,
77 stateDecodingPromise: void 0,
78 router: void 0,
79 routerInitialized: false
80 };
81 }
82}
83function createHydratedRouter({
84 getContext,
85 unstable_instrumentations
86}) {
87 initSsrInfo();
88 if (!ssrInfo) {
89 throw new Error(
90 "You must be using the SSR features of React Router in order to skip passing a `router` prop to `<RouterProvider>`"
91 );
92 }
93 let localSsrInfo = ssrInfo;
94 if (!ssrInfo.stateDecodingPromise) {
95 let stream = ssrInfo.context.stream;
96 invariant(stream, "No stream found for single fetch decoding");
97 ssrInfo.context.stream = void 0;
98 ssrInfo.stateDecodingPromise = decodeViaTurboStream(stream, window).then((value) => {
99 ssrInfo.context.state = value.value;
100 localSsrInfo.stateDecodingPromise.value = true;
101 }).catch((e) => {
102 localSsrInfo.stateDecodingPromise.error = e;
103 });
104 }
105 if (ssrInfo.stateDecodingPromise.error) {
106 throw ssrInfo.stateDecodingPromise.error;
107 }
108 if (!ssrInfo.stateDecodingPromise.value) {
109 throw ssrInfo.stateDecodingPromise;
110 }
111 let routes = createClientRoutes(
112 ssrInfo.manifest.routes,
113 ssrInfo.routeModules,
114 ssrInfo.context.state,
115 ssrInfo.context.ssr,
116 ssrInfo.context.isSpaMode
117 );
118 let hydrationData = void 0;
119 if (ssrInfo.context.isSpaMode) {
120 let { loaderData } = ssrInfo.context.state;
121 if (ssrInfo.manifest.routes.root?.hasLoader && loaderData && "root" in loaderData) {
122 hydrationData = {
123 loaderData: {
124 root: loaderData.root
125 }
126 };
127 }
128 } else {
129 hydrationData = getHydrationData({
130 state: ssrInfo.context.state,
131 routes,
132 getRouteInfo: (routeId) => ({
133 clientLoader: ssrInfo.routeModules[routeId]?.clientLoader,
134 hasLoader: ssrInfo.manifest.routes[routeId]?.hasLoader === true,
135 hasHydrateFallback: ssrInfo.routeModules[routeId]?.HydrateFallback != null
136 }),
137 location: window.location,
138 basename: window.__reactRouterContext?.basename,
139 isSpaMode: ssrInfo.context.isSpaMode
140 });
141 if (hydrationData && hydrationData.errors) {
142 hydrationData.errors = deserializeErrors(hydrationData.errors);
143 }
144 }
145 if (window.history.state && window.history.state.masked) {
146 window.history.replaceState(
147 { ...window.history.state, masked: void 0 },
148 ""
149 );
150 }
151 let router2 = createRouter({
152 routes,
153 history: createBrowserHistory(),
154 basename: ssrInfo.context.basename,
155 getContext,
156 hydrationData,
157 hydrationRouteProperties,
158 unstable_instrumentations,
159 mapRouteProperties,
160 future: {
161 unstable_passThroughRequests: ssrInfo.context.future.unstable_passThroughRequests
162 },
163 dataStrategy: getTurboStreamSingleFetchDataStrategy(
164 () => router2,
165 ssrInfo.manifest,
166 ssrInfo.routeModules,
167 ssrInfo.context.ssr,
168 ssrInfo.context.basename,
169 ssrInfo.context.future.unstable_trailingSlashAwareDataRequests
170 ),
171 patchRoutesOnNavigation: getPatchRoutesOnNavigationFunction(
172 () => router2,
173 ssrInfo.manifest,
174 ssrInfo.routeModules,
175 ssrInfo.context.ssr,
176 ssrInfo.context.routeDiscovery,
177 ssrInfo.context.isSpaMode,
178 ssrInfo.context.basename
179 )
180 });
181 ssrInfo.router = router2;
182 if (router2.state.initialized) {
183 ssrInfo.routerInitialized = true;
184 router2.initialize();
185 }
186 router2.createRoutesForHMR = /* spacer so ts-ignore does not affect the right hand of the assignment */
187 createClientRoutesWithHMRRevalidationOptOut;
188 window.__reactRouterDataRouter = router2;
189 return router2;
190}
191function HydratedRouter(props) {
192 if (!router) {
193 router = createHydratedRouter({
194 getContext: props.getContext,
195 unstable_instrumentations: props.unstable_instrumentations
196 });
197 }
198 let [criticalCss, setCriticalCss] = React2.useState(
199 process.env.NODE_ENV === "development" ? ssrInfo?.context.criticalCss : void 0
200 );
201 React2.useEffect(() => {
202 if (process.env.NODE_ENV === "development") {
203 setCriticalCss(void 0);
204 }
205 }, []);
206 React2.useEffect(() => {
207 if (process.env.NODE_ENV === "development" && criticalCss === void 0) {
208 document.querySelectorAll(`[${CRITICAL_CSS_DATA_ATTRIBUTE}]`).forEach((element) => element.remove());
209 }
210 }, [criticalCss]);
211 let [location2, setLocation] = React2.useState(router.state.location);
212 React2.useLayoutEffect(() => {
213 if (ssrInfo && ssrInfo.router && !ssrInfo.routerInitialized) {
214 ssrInfo.routerInitialized = true;
215 ssrInfo.router.initialize();
216 }
217 }, []);
218 React2.useLayoutEffect(() => {
219 if (ssrInfo && ssrInfo.router) {
220 return ssrInfo.router.subscribe((newState) => {
221 if (newState.location !== location2) {
222 setLocation(newState.location);
223 }
224 });
225 }
226 }, [location2]);
227 invariant(ssrInfo, "ssrInfo unavailable for HydratedRouter");
228 useFogOFWarDiscovery(
229 router,
230 ssrInfo.manifest,
231 ssrInfo.routeModules,
232 ssrInfo.context.ssr,
233 ssrInfo.context.routeDiscovery,
234 ssrInfo.context.isSpaMode
235 );
236 return (
237 // This fragment is important to ensure we match the <ServerRouter> JSX
238 // structure so that useId values hydrate correctly
239 /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(
240 FrameworkContext.Provider,
241 {
242 value: {
243 manifest: ssrInfo.manifest,
244 routeModules: ssrInfo.routeModules,
245 future: ssrInfo.context.future,
246 criticalCss,
247 ssr: ssrInfo.context.ssr,
248 isSpaMode: ssrInfo.context.isSpaMode,
249 routeDiscovery: ssrInfo.context.routeDiscovery
250 }
251 },
252 /* @__PURE__ */ React2.createElement(RemixErrorBoundary, { location: location2 }, /* @__PURE__ */ React2.createElement(
253 RouterProvider2,
254 {
255 router,
256 unstable_useTransitions: props.unstable_useTransitions,
257 onError: props.onError
258 }
259 ))
260 ), /* @__PURE__ */ React2.createElement(React2.Fragment, null))
261 );
262}
263
264// lib/rsc/browser.tsx
265import * as React3 from "react";
266import * as ReactDOM2 from "react-dom";
267var defaultManifestPath = "/__manifest";
268function createCallServer({
269 createFromReadableStream,
270 createTemporaryReferenceSet,
271 encodeReply,
272 fetch: fetchImplementation = fetch
273}) {
274 const globalVar = window;
275 let landedActionId = 0;
276 return async (id, args) => {
277 let actionId = globalVar.__routerActionID = (globalVar.__routerActionID ?? (globalVar.__routerActionID = 0)) + 1;
278 const temporaryReferences = createTemporaryReferenceSet();
279 const payloadPromise = fetchImplementation(
280 new Request(location.href, {
281 body: await encodeReply(args, { temporaryReferences }),
282 method: "POST",
283 headers: {
284 Accept: "text/x-component",
285 "rsc-action-id": id
286 }
287 })
288 ).then((response) => {
289 if (!response.body) {
290 throw new Error("No response body");
291 }
292 return createFromReadableStream(response.body, {
293 temporaryReferences
294 });
295 });
296 React3.startTransition(
297 () => (
298 // @ts-expect-error - Needs React 19 types
299 Promise.resolve(payloadPromise).then(async (payload) => {
300 if (payload.type === "redirect") {
301 if (payload.reload || isExternalLocation(payload.location)) {
302 if (hasInvalidProtocol(payload.location)) {
303 throw new Error("Invalid redirect location");
304 }
305 window.location.href = payload.location;
306 return;
307 }
308 React3.startTransition(() => {
309 globalVar.__reactRouterDataRouter.navigate(payload.location, {
310 replace: payload.replace
311 });
312 });
313 return;
314 }
315 if (payload.type !== "action") {
316 throw new Error("Unexpected payload type");
317 }
318 const rerender = await payload.rerender;
319 if (rerender && landedActionId < actionId && globalVar.__routerActionID <= actionId) {
320 if (rerender.type === "redirect") {
321 if (rerender.reload || isExternalLocation(rerender.location)) {
322 if (hasInvalidProtocol(rerender.location)) {
323 throw new Error("Invalid redirect location");
324 }
325 window.location.href = rerender.location;
326 return;
327 }
328 React3.startTransition(() => {
329 globalVar.__reactRouterDataRouter.navigate(rerender.location, {
330 replace: rerender.replace
331 });
332 });
333 return;
334 }
335 React3.startTransition(() => {
336 let lastMatch;
337 for (const match of rerender.matches) {
338 globalVar.__reactRouterDataRouter.patchRoutes(
339 lastMatch?.id ?? null,
340 [createRouteFromServerManifest(match)],
341 true
342 );
343 lastMatch = match;
344 }
345 window.__reactRouterDataRouter._internalSetStateDoNotUseOrYouWillBreakYourApp(
346 {
347 loaderData: Object.assign(
348 {},
349 globalVar.__reactRouterDataRouter.state.loaderData,
350 rerender.loaderData
351 ),
352 errors: rerender.errors ? Object.assign(
353 {},
354 globalVar.__reactRouterDataRouter.state.errors,
355 rerender.errors
356 ) : null
357 }
358 );
359 });
360 }
361 }).catch(() => {
362 })
363 )
364 );
365 return payloadPromise.then((payload) => {
366 if (payload.type !== "action" && payload.type !== "redirect") {
367 throw new Error("Unexpected payload type");
368 }
369 return payload.actionResult;
370 });
371 };
372}
373function createRouterFromPayload({
374 fetchImplementation,
375 createFromReadableStream,
376 getContext,
377 payload
378}) {
379 const globalVar = window;
380 if (globalVar.__reactRouterDataRouter && globalVar.__reactRouterRouteModules)
381 return {
382 router: globalVar.__reactRouterDataRouter,
383 routeModules: globalVar.__reactRouterRouteModules
384 };
385 if (payload.type !== "render") throw new Error("Invalid payload type");
386 globalVar.__reactRouterRouteModules = globalVar.__reactRouterRouteModules ?? {};
387 populateRSCRouteModules(globalVar.__reactRouterRouteModules, payload.matches);
388 let routes = payload.matches.reduceRight((previous, match) => {
389 const route = createRouteFromServerManifest(
390 match,
391 payload
392 );
393 if (previous.length > 0) {
394 route.children = previous;
395 } else if (!route.index) {
396 route.children = [];
397 }
398 return [route];
399 }, []);
400 let applyPatchesPromise;
401 globalVar.__reactRouterDataRouter = createRouter({
402 routes,
403 getContext,
404 basename: payload.basename,
405 history: createBrowserHistory(),
406 hydrationData: getHydrationData({
407 state: {
408 loaderData: payload.loaderData,
409 actionData: payload.actionData,
410 errors: payload.errors
411 },
412 routes,
413 getRouteInfo: (routeId) => {
414 let match = payload.matches.find((m) => m.id === routeId);
415 invariant(match, "Route not found in payload");
416 return {
417 clientLoader: match.clientLoader,
418 hasLoader: match.hasLoader,
419 hasHydrateFallback: match.hydrateFallbackElement != null
420 };
421 },
422 location: payload.location,
423 basename: payload.basename,
424 isSpaMode: false
425 }),
426 async patchRoutesOnNavigation({ path, signal }) {
427 if (payload.routeDiscovery.mode === "initial") {
428 if (!applyPatchesPromise) {
429 applyPatchesPromise = (async () => {
430 if (!payload.patches) return;
431 let patches = await payload.patches;
432 React3.startTransition(() => {
433 patches.forEach((p) => {
434 window.__reactRouterDataRouter.patchRoutes(p.parentId ?? null, [
435 createRouteFromServerManifest(p)
436 ]);
437 });
438 });
439 })();
440 }
441 await applyPatchesPromise;
442 return;
443 }
444 if (discoveredPaths.has(path)) {
445 return;
446 }
447 await fetchAndApplyManifestPatches(
448 [path],
449 createFromReadableStream,
450 fetchImplementation,
451 signal
452 );
453 },
454 // FIXME: Pass `build.ssr` into this function
455 dataStrategy: getRSCSingleFetchDataStrategy(
456 () => globalVar.__reactRouterDataRouter,
457 true,
458 payload.basename,
459 createFromReadableStream,
460 fetchImplementation
461 )
462 });
463 if (globalVar.__reactRouterDataRouter.state.initialized) {
464 globalVar.__routerInitialized = true;
465 globalVar.__reactRouterDataRouter.initialize();
466 } else {
467 globalVar.__routerInitialized = false;
468 }
469 let lastLoaderData = void 0;
470 globalVar.__reactRouterDataRouter.subscribe(({ loaderData, actionData }) => {
471 if (lastLoaderData !== loaderData) {
472 globalVar.__routerActionID = (globalVar.__routerActionID ?? (globalVar.__routerActionID = 0)) + 1;
473 }
474 });
475 globalVar.__reactRouterDataRouter._updateRoutesForHMR = (routeUpdateByRouteId) => {
476 const oldRoutes = window.__reactRouterDataRouter.routes;
477 const newRoutes = [];
478 function walkRoutes(routes2, parentId) {
479 return routes2.map((route) => {
480 const routeUpdate = routeUpdateByRouteId.get(route.id);
481 if (routeUpdate) {
482 const {
483 routeModule,
484 hasAction,
485 hasComponent,
486 hasErrorBoundary,
487 hasLoader
488 } = routeUpdate;
489 const newRoute = createRouteFromServerManifest({
490 clientAction: routeModule.clientAction,
491 clientLoader: routeModule.clientLoader,
492 element: route.element,
493 errorElement: route.errorElement,
494 handle: route.handle,
495 hasAction,
496 hasComponent,
497 hasErrorBoundary,
498 hasLoader,
499 hydrateFallbackElement: route.hydrateFallbackElement,
500 id: route.id,
501 index: route.index,
502 links: routeModule.links,
503 meta: routeModule.meta,
504 parentId,
505 path: route.path,
506 shouldRevalidate: routeModule.shouldRevalidate
507 });
508 if (route.children) {
509 newRoute.children = walkRoutes(route.children, route.id);
510 }
511 return newRoute;
512 }
513 const updatedRoute = { ...route };
514 if (route.children) {
515 updatedRoute.children = walkRoutes(route.children, route.id);
516 }
517 return updatedRoute;
518 });
519 }
520 newRoutes.push(
521 ...walkRoutes(oldRoutes, void 0)
522 );
523 window.__reactRouterDataRouter._internalSetRoutes(newRoutes);
524 };
525 return {
526 router: globalVar.__reactRouterDataRouter,
527 routeModules: globalVar.__reactRouterRouteModules
528 };
529}
530var renderedRoutesContext = createContext();
531function getRSCSingleFetchDataStrategy(getRouter, ssr, basename, createFromReadableStream, fetchImplementation) {
532 let dataStrategy = getSingleFetchDataStrategyImpl(
533 getRouter,
534 (match) => {
535 let M = match;
536 return {
537 hasLoader: M.route.hasLoader,
538 hasClientLoader: M.route.hasClientLoader,
539 hasComponent: M.route.hasComponent,
540 hasAction: M.route.hasAction,
541 hasClientAction: M.route.hasClientAction,
542 hasShouldRevalidate: M.route.hasShouldRevalidate
543 };
544 },
545 // pass map into fetchAndDecode so it can add payloads
546 getFetchAndDecodeViaRSC(createFromReadableStream, fetchImplementation),
547 ssr,
548 basename,
549 // .rsc requests are always trailing slash aware
550 true,
551 // If the route has a component but we don't have an element, we need to hit
552 // the server loader flow regardless of whether the client loader calls
553 // `serverLoader` or not, otherwise we'll have nothing to render.
554 (match) => {
555 let M = match;
556 return M.route.hasComponent && !M.route.element;
557 }
558 );
559 return async (args) => args.runClientMiddleware(async () => {
560 let context = args.context;
561 context.set(renderedRoutesContext, []);
562 let results = await dataStrategy(args);
563 const renderedRoutesById = /* @__PURE__ */ new Map();
564 for (const route of context.get(renderedRoutesContext)) {
565 if (!renderedRoutesById.has(route.id)) {
566 renderedRoutesById.set(route.id, []);
567 }
568 renderedRoutesById.get(route.id).push(route);
569 }
570 React3.startTransition(() => {
571 for (const match of args.matches) {
572 const renderedRoutes = renderedRoutesById.get(match.route.id);
573 if (renderedRoutes) {
574 for (const rendered of renderedRoutes) {
575 window.__reactRouterDataRouter.patchRoutes(
576 rendered.parentId ?? null,
577 [createRouteFromServerManifest(rendered)],
578 true
579 );
580 }
581 }
582 }
583 });
584 return results;
585 });
586}
587function getFetchAndDecodeViaRSC(createFromReadableStream, fetchImplementation) {
588 return async (args, basename, trailingSlashAware, targetRoutes) => {
589 let { request, context } = args;
590 let url = singleFetchUrl(request.url, basename, trailingSlashAware, "rsc");
591 if (request.method === "GET") {
592 url = stripIndexParam(url);
593 if (targetRoutes) {
594 url.searchParams.set("_routes", targetRoutes.join(","));
595 }
596 }
597 let res = await fetchImplementation(
598 new Request(url, await createRequestInit(request))
599 );
600 if (res.status >= 400 && !res.headers.has("X-Remix-Response")) {
601 throw new ErrorResponseImpl(res.status, res.statusText, await res.text());
602 }
603 invariant(res.body, "No response body to decode");
604 try {
605 const payload = await createFromReadableStream(res.body, {
606 temporaryReferences: void 0
607 });
608 if (payload.type === "redirect") {
609 return {
610 status: res.status,
611 data: {
612 redirect: {
613 redirect: payload.location,
614 reload: payload.reload,
615 replace: payload.replace,
616 revalidate: false,
617 status: payload.status
618 }
619 }
620 };
621 }
622 if (payload.type !== "render") {
623 throw new Error("Unexpected payload type");
624 }
625 context.get(renderedRoutesContext).push(...payload.matches);
626 let results = { routes: {} };
627 const dataKey = isMutationMethod(request.method) ? "actionData" : "loaderData";
628 for (let [routeId, data] of Object.entries(payload[dataKey] || {})) {
629 results.routes[routeId] = { data };
630 }
631 if (payload.errors) {
632 for (let [routeId, error] of Object.entries(payload.errors)) {
633 results.routes[routeId] = { error };
634 }
635 }
636 return { status: res.status, data: results };
637 } catch (cause) {
638 throw new Error("Unable to decode RSC response", { cause });
639 }
640 };
641}
642function RSCHydratedRouter({
643 createFromReadableStream,
644 fetch: fetchImplementation = fetch,
645 payload,
646 getContext
647}) {
648 if (payload.type !== "render") throw new Error("Invalid payload type");
649 let { routeDiscovery } = payload;
650 let { router: router2, routeModules } = React3.useMemo(
651 () => createRouterFromPayload({
652 payload,
653 fetchImplementation,
654 getContext,
655 createFromReadableStream
656 }),
657 [createFromReadableStream, payload, fetchImplementation, getContext]
658 );
659 React3.useEffect(() => {
660 setIsHydrated();
661 }, []);
662 React3.useLayoutEffect(() => {
663 const globalVar = window;
664 if (!globalVar.__routerInitialized) {
665 globalVar.__routerInitialized = true;
666 globalVar.__reactRouterDataRouter.initialize();
667 }
668 }, []);
669 let [{ routes, state }, setState] = React3.useState(() => ({
670 routes: cloneRoutes(router2.routes),
671 state: router2.state
672 }));
673 React3.useLayoutEffect(
674 () => router2.subscribe((newState) => {
675 if (diffRoutes(router2.routes, routes))
676 React3.startTransition(() => {
677 setState({
678 routes: cloneRoutes(router2.routes),
679 state: newState
680 });
681 });
682 }),
683 [router2.subscribe, routes, router2]
684 );
685 const transitionEnabledRouter = React3.useMemo(
686 () => ({
687 ...router2,
688 state,
689 routes
690 }),
691 [router2, routes, state]
692 );
693 React3.useEffect(() => {
694 if (routeDiscovery.mode === "initial" || // @ts-expect-error - TS doesn't know about this yet
695 window.navigator?.connection?.saveData === true) {
696 return;
697 }
698 function registerElement(el) {
699 let path = el.tagName === "FORM" ? el.getAttribute("action") : el.getAttribute("href");
700 if (!path) {
701 return;
702 }
703 let pathname = el.tagName === "A" ? el.pathname : new URL(path, window.location.origin).pathname;
704 if (!discoveredPaths.has(pathname)) {
705 nextPaths.add(pathname);
706 }
707 }
708 async function fetchPatches() {
709 document.querySelectorAll("a[data-discover], form[data-discover]").forEach(registerElement);
710 let paths = Array.from(nextPaths.keys()).filter((path) => {
711 if (discoveredPaths.has(path)) {
712 nextPaths.delete(path);
713 return false;
714 }
715 return true;
716 });
717 if (paths.length === 0) {
718 return;
719 }
720 try {
721 await fetchAndApplyManifestPatches(
722 paths,
723 createFromReadableStream,
724 fetchImplementation
725 );
726 } catch (e) {
727 console.error("Failed to fetch manifest patches", e);
728 }
729 }
730 let debouncedFetchPatches = debounce(fetchPatches, 100);
731 fetchPatches();
732 let observer = new MutationObserver(() => debouncedFetchPatches());
733 observer.observe(document.documentElement, {
734 subtree: true,
735 childList: true,
736 attributes: true,
737 attributeFilter: ["data-discover", "href", "action"]
738 });
739 }, [routeDiscovery, createFromReadableStream, fetchImplementation]);
740 const frameworkContext = {
741 future: {
742 // These flags have no runtime impact so can always be false. If we add
743 // flags that drive runtime behavior they'll need to be proxied through.
744 v8_middleware: false,
745 unstable_subResourceIntegrity: false,
746 unstable_trailingSlashAwareDataRequests: true,
747 // always on for RSC
748 unstable_passThroughRequests: true
749 // always on for RSC
750 },
751 isSpaMode: false,
752 ssr: true,
753 criticalCss: "",
754 manifest: {
755 routes: {},
756 version: "1",
757 url: "",
758 entry: {
759 module: "",
760 imports: []
761 }
762 },
763 routeDiscovery: payload.routeDiscovery.mode === "initial" ? { mode: "initial", manifestPath: defaultManifestPath } : {
764 mode: "lazy",
765 manifestPath: payload.routeDiscovery.manifestPath || defaultManifestPath
766 },
767 routeModules
768 };
769 return /* @__PURE__ */ React3.createElement(RSCRouterContext.Provider, { value: true }, /* @__PURE__ */ React3.createElement(RSCRouterGlobalErrorBoundary, { location: state.location }, /* @__PURE__ */ React3.createElement(FrameworkContext.Provider, { value: frameworkContext }, /* @__PURE__ */ React3.createElement(
770 RouterProvider,
771 {
772 router: transitionEnabledRouter,
773 flushSync: ReactDOM2.flushSync
774 }
775 ))));
776}
777function createRouteFromServerManifest(match, payload) {
778 let hasInitialData = payload && match.id in payload.loaderData;
779 let initialData = payload?.loaderData[match.id];
780 let hasInitialError = payload?.errors && match.id in payload.errors;
781 let initialError = payload?.errors?.[match.id];
782 let isHydrationRequest = match.clientLoader?.hydrate === true || !match.hasLoader || // If the route has a component but we don't have an element, we need to hit
783 // the server loader flow regardless of whether the client loader calls
784 // `serverLoader` or not, otherwise we'll have nothing to render.
785 match.hasComponent && !match.element;
786 invariant(window.__reactRouterRouteModules);
787 populateRSCRouteModules(window.__reactRouterRouteModules, match);
788 let dataRoute = {
789 id: match.id,
790 element: match.element,
791 errorElement: match.errorElement,
792 handle: match.handle,
793 hasErrorBoundary: match.hasErrorBoundary,
794 hydrateFallbackElement: match.hydrateFallbackElement,
795 index: match.index,
796 loader: match.clientLoader ? async (args, singleFetch) => {
797 try {
798 let result = await match.clientLoader({
799 ...args,
800 serverLoader: () => {
801 preventInvalidServerHandlerCall(
802 "loader",
803 match.id,
804 match.hasLoader
805 );
806 if (isHydrationRequest) {
807 if (hasInitialData) {
808 return initialData;
809 }
810 if (hasInitialError) {
811 throw initialError;
812 }
813 }
814 return callSingleFetch(singleFetch);
815 }
816 });
817 return result;
818 } finally {
819 isHydrationRequest = false;
820 }
821 } : (
822 // We always make the call in this RSC world since even if we don't
823 // have a `loader` we may need to get the `element` implementation
824 (_, singleFetch) => callSingleFetch(singleFetch)
825 ),
826 action: match.clientAction ? (args, singleFetch) => match.clientAction({
827 ...args,
828 serverAction: async () => {
829 preventInvalidServerHandlerCall(
830 "action",
831 match.id,
832 match.hasLoader
833 );
834 return await callSingleFetch(singleFetch);
835 }
836 }) : match.hasAction ? (_, singleFetch) => callSingleFetch(singleFetch) : () => {
837 throw noActionDefinedError("action", match.id);
838 },
839 path: match.path,
840 shouldRevalidate: match.shouldRevalidate,
841 // We always have a "loader" in this RSC world since even if we don't
842 // have a `loader` we may need to get the `element` implementation
843 hasLoader: true,
844 hasClientLoader: match.clientLoader != null,
845 hasAction: match.hasAction,
846 hasClientAction: match.clientAction != null,
847 hasShouldRevalidate: match.shouldRevalidate != null
848 };
849 if (typeof dataRoute.loader === "function") {
850 dataRoute.loader.hydrate = shouldHydrateRouteLoader(
851 match.id,
852 match.clientLoader,
853 match.hasLoader,
854 false
855 );
856 }
857 return dataRoute;
858}
859function callSingleFetch(singleFetch) {
860 invariant(typeof singleFetch === "function", "Invalid singleFetch parameter");
861 return singleFetch();
862}
863function preventInvalidServerHandlerCall(type, routeId, hasHandler) {
864 if (!hasHandler) {
865 let fn = type === "action" ? "serverAction()" : "serverLoader()";
866 let msg = `You are trying to call ${fn} on a route that does not have a server ${type} (routeId: "${routeId}")`;
867 console.error(msg);
868 throw new ErrorResponseImpl(400, "Bad Request", new Error(msg), true);
869 }
870}
871var nextPaths = /* @__PURE__ */ new Set();
872var discoveredPathsMaxSize = 1e3;
873var discoveredPaths = /* @__PURE__ */ new Set();
874var URL_LIMIT = 7680;
875function getManifestUrl(paths) {
876 if (paths.length === 0) {
877 return null;
878 }
879 if (paths.length === 1) {
880 return new URL(`${paths[0]}.manifest`, window.location.origin);
881 }
882 const globalVar = window;
883 let basename = (globalVar.__reactRouterDataRouter.basename ?? "").replace(
884 /^\/|\/$/g,
885 ""
886 );
887 let url = new URL(`${basename}/.manifest`, window.location.origin);
888 url.searchParams.set("paths", paths.sort().join(","));
889 return url;
890}
891async function fetchAndApplyManifestPatches(paths, createFromReadableStream, fetchImplementation, signal) {
892 let url = getManifestUrl(paths);
893 if (url == null) {
894 return;
895 }
896 if (url.toString().length > URL_LIMIT) {
897 nextPaths.clear();
898 return;
899 }
900 let response = await fetchImplementation(new Request(url, { signal }));
901 if (!response.body || response.status < 200 || response.status >= 300) {
902 throw new Error("Unable to fetch new route matches from the server");
903 }
904 let payload = await createFromReadableStream(response.body, {
905 temporaryReferences: void 0
906 });
907 if (payload.type !== "manifest") {
908 throw new Error("Failed to patch routes");
909 }
910 paths.forEach((p) => addToFifoQueue(p, discoveredPaths));
911 let patches = await payload.patches;
912 React3.startTransition(() => {
913 patches.forEach((p) => {
914 window.__reactRouterDataRouter.patchRoutes(
915 p.parentId ?? null,
916 [createRouteFromServerManifest(p)]
917 );
918 });
919 });
920}
921function addToFifoQueue(path, queue) {
922 if (queue.size >= discoveredPathsMaxSize) {
923 let first = queue.values().next().value;
924 if (typeof first === "string") queue.delete(first);
925 }
926 queue.add(path);
927}
928function debounce(callback, wait) {
929 let timeoutId;
930 return (...args) => {
931 window.clearTimeout(timeoutId);
932 timeoutId = window.setTimeout(() => callback(...args), wait);
933 };
934}
935function isExternalLocation(location2) {
936 const newLocation = new URL(location2, window.location.href);
937 return newLocation.origin !== window.location.origin;
938}
939function hasInvalidProtocol(location2) {
940 try {
941 return invalidProtocols.includes(new URL(location2).protocol);
942 } catch {
943 return false;
944 }
945}
946function cloneRoutes(routes) {
947 if (!routes) return void 0;
948 return routes.map((route) => ({
949 ...route,
950 children: cloneRoutes(route.children)
951 }));
952}
953function diffRoutes(a, b) {
954 if (a.length !== b.length) return true;
955 return a.some((route, index) => {
956 if (route.element !== b[index].element) return true;
957 if (route.errorElement !== b[index].errorElement)
958 return true;
959 if (route.hydrateFallbackElement !== b[index].hydrateFallbackElement)
960 return true;
961 if (route.hasErrorBoundary !== b[index].hasErrorBoundary)
962 return true;
963 if (route.hasLoader !== b[index].hasLoader) return true;
964 if (route.hasClientLoader !== b[index].hasClientLoader)
965 return true;
966 if (route.hasAction !== b[index].hasAction) return true;
967 if (route.hasClientAction !== b[index].hasClientAction)
968 return true;
969 return diffRoutes(route.children || [], b[index].children || []);
970 });
971}
972
973// lib/rsc/html-stream/browser.ts
974function getRSCStream() {
975 let encoder = new TextEncoder();
976 let streamController = null;
977 let rscStream = new ReadableStream({
978 start(controller) {
979 if (typeof window === "undefined") {
980 return;
981 }
982 let handleChunk = (chunk) => {
983 if (typeof chunk === "string") {
984 controller.enqueue(encoder.encode(chunk));
985 } else {
986 controller.enqueue(chunk);
987 }
988 };
989 window.__FLIGHT_DATA || (window.__FLIGHT_DATA = []);
990 window.__FLIGHT_DATA.forEach(handleChunk);
991 window.__FLIGHT_DATA.push = (chunk) => {
992 handleChunk(chunk);
993 return 0;
994 };
995 streamController = controller;
996 }
997 });
998 if (typeof document !== "undefined" && document.readyState === "loading") {
999 document.addEventListener("DOMContentLoaded", () => {
1000 streamController?.close();
1001 });
1002 } else {
1003 streamController?.close();
1004 }
1005 return rscStream;
1006}
1007export {
1008 HydratedRouter,
1009 RouterProvider2 as RouterProvider,
1010 RSCHydratedRouter as unstable_RSCHydratedRouter,
1011 createCallServer as unstable_createCallServer,
1012 getRSCStream as unstable_getRSCStream
1013};