UNPKG

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