UNPKG

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