dom-export.mjs 31 KB

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