dom-export.js 34 KB

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