index-react-server.mjs 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473
  1. import { AsyncLocalStorage } from 'node:async_hooks';
  2. import * as React2 from 'react';
  3. import { splitCookiesString } from 'set-cookie-parser';
  4. import { UNSAFE_AwaitContextProvider, UNSAFE_WithComponentProps, Outlet as Outlet$1, UNSAFE_WithErrorBoundaryProps, UNSAFE_WithHydrateFallbackProps } from 'react-router/internal/react-server-client';
  5. export { BrowserRouter, Form, HashRouter, Link, Links, MemoryRouter, Meta, NavLink, Navigate, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, StaticRouter, StaticRouterProvider, unstable_HistoryRouter } from 'react-router/internal/react-server-client';
  6. import { serialize, parse } from 'cookie';
  7. /**
  8. * react-router v7.10.1
  9. *
  10. * Copyright (c) Remix Software Inc.
  11. *
  12. * This source code is licensed under the MIT license found in the
  13. * LICENSE.md file in the root directory of this source tree.
  14. *
  15. * @license MIT
  16. */
  17. var __typeError = (msg) => {
  18. throw TypeError(msg);
  19. };
  20. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  21. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  22. var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
  23. // lib/router/history.ts
  24. function invariant(value, message) {
  25. if (value === false || value === null || typeof value === "undefined") {
  26. throw new Error(message);
  27. }
  28. }
  29. function warning(cond, message) {
  30. if (!cond) {
  31. if (typeof console !== "undefined") console.warn(message);
  32. try {
  33. throw new Error(message);
  34. } catch (e) {
  35. }
  36. }
  37. }
  38. function createKey() {
  39. return Math.random().toString(36).substring(2, 10);
  40. }
  41. function createLocation(current, to, state = null, key) {
  42. let location = {
  43. pathname: typeof current === "string" ? current : current.pathname,
  44. search: "",
  45. hash: "",
  46. ...typeof to === "string" ? parsePath(to) : to,
  47. state,
  48. // TODO: This could be cleaned up. push/replace should probably just take
  49. // full Locations now and avoid the need to run through this flow at all
  50. // But that's a pretty big refactor to the current test suite so going to
  51. // keep as is for the time being and just let any incoming keys take precedence
  52. key: to && to.key || key || createKey()
  53. };
  54. return location;
  55. }
  56. function createPath({
  57. pathname = "/",
  58. search = "",
  59. hash = ""
  60. }) {
  61. if (search && search !== "?")
  62. pathname += search.charAt(0) === "?" ? search : "?" + search;
  63. if (hash && hash !== "#")
  64. pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  65. return pathname;
  66. }
  67. function parsePath(path) {
  68. let parsedPath = {};
  69. if (path) {
  70. let hashIndex = path.indexOf("#");
  71. if (hashIndex >= 0) {
  72. parsedPath.hash = path.substring(hashIndex);
  73. path = path.substring(0, hashIndex);
  74. }
  75. let searchIndex = path.indexOf("?");
  76. if (searchIndex >= 0) {
  77. parsedPath.search = path.substring(searchIndex);
  78. path = path.substring(0, searchIndex);
  79. }
  80. if (path) {
  81. parsedPath.pathname = path;
  82. }
  83. }
  84. return parsedPath;
  85. }
  86. // lib/router/instrumentation.ts
  87. var UninstrumentedSymbol = Symbol("Uninstrumented");
  88. function getRouteInstrumentationUpdates(fns, route) {
  89. let aggregated = {
  90. lazy: [],
  91. "lazy.loader": [],
  92. "lazy.action": [],
  93. "lazy.middleware": [],
  94. middleware: [],
  95. loader: [],
  96. action: []
  97. };
  98. fns.forEach(
  99. (fn) => fn({
  100. id: route.id,
  101. index: route.index,
  102. path: route.path,
  103. instrument(i) {
  104. let keys = Object.keys(aggregated);
  105. for (let key of keys) {
  106. if (i[key]) {
  107. aggregated[key].push(i[key]);
  108. }
  109. }
  110. }
  111. })
  112. );
  113. let updates = {};
  114. if (typeof route.lazy === "function" && aggregated.lazy.length > 0) {
  115. let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0);
  116. if (instrumented) {
  117. updates.lazy = instrumented;
  118. }
  119. }
  120. if (typeof route.lazy === "object") {
  121. let lazyObject = route.lazy;
  122. ["middleware", "loader", "action"].forEach((key) => {
  123. let lazyFn = lazyObject[key];
  124. let instrumentations = aggregated[`lazy.${key}`];
  125. if (typeof lazyFn === "function" && instrumentations.length > 0) {
  126. let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0);
  127. if (instrumented) {
  128. updates.lazy = Object.assign(updates.lazy || {}, {
  129. [key]: instrumented
  130. });
  131. }
  132. }
  133. });
  134. }
  135. ["loader", "action"].forEach((key) => {
  136. let handler = route[key];
  137. if (typeof handler === "function" && aggregated[key].length > 0) {
  138. let original = handler[UninstrumentedSymbol] ?? handler;
  139. let instrumented = wrapImpl(
  140. aggregated[key],
  141. original,
  142. (...args) => getHandlerInfo(args[0])
  143. );
  144. if (instrumented) {
  145. instrumented[UninstrumentedSymbol] = original;
  146. updates[key] = instrumented;
  147. }
  148. }
  149. });
  150. if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) {
  151. updates.middleware = route.middleware.map((middleware) => {
  152. let original = middleware[UninstrumentedSymbol] ?? middleware;
  153. let instrumented = wrapImpl(
  154. aggregated.middleware,
  155. original,
  156. (...args) => getHandlerInfo(args[0])
  157. );
  158. if (instrumented) {
  159. instrumented[UninstrumentedSymbol] = original;
  160. return instrumented;
  161. }
  162. return middleware;
  163. });
  164. }
  165. return updates;
  166. }
  167. function wrapImpl(impls, handler, getInfo) {
  168. if (impls.length === 0) {
  169. return null;
  170. }
  171. return async (...args) => {
  172. let result = await recurseRight(
  173. impls,
  174. getInfo(...args),
  175. () => handler(...args),
  176. impls.length - 1
  177. );
  178. if (result.type === "error") {
  179. throw result.value;
  180. }
  181. return result.value;
  182. };
  183. }
  184. async function recurseRight(impls, info, handler, index) {
  185. let impl = impls[index];
  186. let result;
  187. if (!impl) {
  188. try {
  189. let value = await handler();
  190. result = { type: "success", value };
  191. } catch (e) {
  192. result = { type: "error", value: e };
  193. }
  194. } else {
  195. let handlerPromise = void 0;
  196. let callHandler = async () => {
  197. if (handlerPromise) {
  198. console.error("You cannot call instrumented handlers more than once");
  199. } else {
  200. handlerPromise = recurseRight(impls, info, handler, index - 1);
  201. }
  202. result = await handlerPromise;
  203. invariant(result, "Expected a result");
  204. if (result.type === "error" && result.value instanceof Error) {
  205. return { status: "error", error: result.value };
  206. }
  207. return { status: "success", error: void 0 };
  208. };
  209. try {
  210. await impl(callHandler, info);
  211. } catch (e) {
  212. console.error("An instrumentation function threw an error:", e);
  213. }
  214. if (!handlerPromise) {
  215. await callHandler();
  216. }
  217. await handlerPromise;
  218. }
  219. if (result) {
  220. return result;
  221. }
  222. return {
  223. type: "error",
  224. value: new Error("No result assigned in instrumentation chain.")
  225. };
  226. }
  227. function getHandlerInfo(args) {
  228. let { request, context, params, unstable_pattern } = args;
  229. return {
  230. request: getReadonlyRequest(request),
  231. params: { ...params },
  232. unstable_pattern,
  233. context: getReadonlyContext(context)
  234. };
  235. }
  236. function getReadonlyRequest(request) {
  237. return {
  238. method: request.method,
  239. url: request.url,
  240. headers: {
  241. get: (...args) => request.headers.get(...args)
  242. }
  243. };
  244. }
  245. function getReadonlyContext(context) {
  246. if (isPlainObject(context)) {
  247. let frozen = { ...context };
  248. Object.freeze(frozen);
  249. return frozen;
  250. } else {
  251. return {
  252. get: (ctx) => context.get(ctx)
  253. };
  254. }
  255. }
  256. var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
  257. function isPlainObject(thing) {
  258. if (thing === null || typeof thing !== "object") {
  259. return false;
  260. }
  261. const proto = Object.getPrototypeOf(thing);
  262. return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
  263. }
  264. // lib/router/utils.ts
  265. function createContext(defaultValue) {
  266. return { defaultValue };
  267. }
  268. var _map;
  269. var RouterContextProvider = class {
  270. /**
  271. * Create a new `RouterContextProvider` instance
  272. * @param init An optional initial context map to populate the provider with
  273. */
  274. constructor(init) {
  275. __privateAdd(this, _map, /* @__PURE__ */ new Map());
  276. if (init) {
  277. for (let [context, value] of init) {
  278. this.set(context, value);
  279. }
  280. }
  281. }
  282. /**
  283. * Access a value from the context. If no value has been set for the context,
  284. * it will return the context's `defaultValue` if provided, or throw an error
  285. * if no `defaultValue` was set.
  286. * @param context The context to get the value for
  287. * @returns The value for the context, or the context's `defaultValue` if no
  288. * value was set
  289. */
  290. get(context) {
  291. if (__privateGet(this, _map).has(context)) {
  292. return __privateGet(this, _map).get(context);
  293. }
  294. if (context.defaultValue !== void 0) {
  295. return context.defaultValue;
  296. }
  297. throw new Error("No value found for context");
  298. }
  299. /**
  300. * Set a value for the context. If the context already has a value set, this
  301. * will overwrite it.
  302. *
  303. * @param context The context to set the value for
  304. * @param value The value to set for the context
  305. * @returns {void}
  306. */
  307. set(context, value) {
  308. __privateGet(this, _map).set(context, value);
  309. }
  310. };
  311. _map = new WeakMap();
  312. var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
  313. "lazy",
  314. "caseSensitive",
  315. "path",
  316. "id",
  317. "index",
  318. "children"
  319. ]);
  320. function isUnsupportedLazyRouteObjectKey(key) {
  321. return unsupportedLazyRouteObjectKeys.has(
  322. key
  323. );
  324. }
  325. var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
  326. "lazy",
  327. "caseSensitive",
  328. "path",
  329. "id",
  330. "index",
  331. "middleware",
  332. "children"
  333. ]);
  334. function isUnsupportedLazyRouteFunctionKey(key) {
  335. return unsupportedLazyRouteFunctionKeys.has(
  336. key
  337. );
  338. }
  339. function isIndexRoute(route) {
  340. return route.index === true;
  341. }
  342. function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
  343. return routes.map((route, index) => {
  344. let treePath = [...parentPath, String(index)];
  345. let id = typeof route.id === "string" ? route.id : treePath.join("-");
  346. invariant(
  347. route.index !== true || !route.children,
  348. `Cannot specify children on an index route`
  349. );
  350. invariant(
  351. allowInPlaceMutations || !manifest[id],
  352. `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
  353. );
  354. if (isIndexRoute(route)) {
  355. let indexRoute = {
  356. ...route,
  357. id
  358. };
  359. manifest[id] = mergeRouteUpdates(
  360. indexRoute,
  361. mapRouteProperties(indexRoute)
  362. );
  363. return indexRoute;
  364. } else {
  365. let pathOrLayoutRoute = {
  366. ...route,
  367. id,
  368. children: void 0
  369. };
  370. manifest[id] = mergeRouteUpdates(
  371. pathOrLayoutRoute,
  372. mapRouteProperties(pathOrLayoutRoute)
  373. );
  374. if (route.children) {
  375. pathOrLayoutRoute.children = convertRoutesToDataRoutes(
  376. route.children,
  377. mapRouteProperties,
  378. treePath,
  379. manifest,
  380. allowInPlaceMutations
  381. );
  382. }
  383. return pathOrLayoutRoute;
  384. }
  385. });
  386. }
  387. function mergeRouteUpdates(route, updates) {
  388. return Object.assign(route, {
  389. ...updates,
  390. ...typeof updates.lazy === "object" && updates.lazy != null ? {
  391. lazy: {
  392. ...route.lazy,
  393. ...updates.lazy
  394. }
  395. } : {}
  396. });
  397. }
  398. function matchRoutes(routes, locationArg, basename = "/") {
  399. return matchRoutesImpl(routes, locationArg, basename, false);
  400. }
  401. function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
  402. let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  403. let pathname = stripBasename(location.pathname || "/", basename);
  404. if (pathname == null) {
  405. return null;
  406. }
  407. let branches = flattenRoutes(routes);
  408. rankRouteBranches(branches);
  409. let matches = null;
  410. for (let i = 0; matches == null && i < branches.length; ++i) {
  411. let decoded = decodePath(pathname);
  412. matches = matchRouteBranch(
  413. branches[i],
  414. decoded,
  415. allowPartial
  416. );
  417. }
  418. return matches;
  419. }
  420. function convertRouteMatchToUiMatch(match, loaderData) {
  421. let { route, pathname, params } = match;
  422. return {
  423. id: route.id,
  424. pathname,
  425. params,
  426. data: loaderData[route.id],
  427. loaderData: loaderData[route.id],
  428. handle: route.handle
  429. };
  430. }
  431. function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) {
  432. let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => {
  433. let meta = {
  434. relativePath: relativePath === void 0 ? route.path || "" : relativePath,
  435. caseSensitive: route.caseSensitive === true,
  436. childrenIndex: index,
  437. route
  438. };
  439. if (meta.relativePath.startsWith("/")) {
  440. if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) {
  441. return;
  442. }
  443. invariant(
  444. meta.relativePath.startsWith(parentPath),
  445. `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
  446. );
  447. meta.relativePath = meta.relativePath.slice(parentPath.length);
  448. }
  449. let path = joinPaths([parentPath, meta.relativePath]);
  450. let routesMeta = parentsMeta.concat(meta);
  451. if (route.children && route.children.length > 0) {
  452. invariant(
  453. // Our types know better, but runtime JS may not!
  454. // @ts-expect-error
  455. route.index !== true,
  456. `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
  457. );
  458. flattenRoutes(
  459. route.children,
  460. branches,
  461. routesMeta,
  462. path,
  463. hasParentOptionalSegments
  464. );
  465. }
  466. if (route.path == null && !route.index) {
  467. return;
  468. }
  469. branches.push({
  470. path,
  471. score: computeScore(path, route.index),
  472. routesMeta
  473. });
  474. };
  475. routes.forEach((route, index) => {
  476. if (route.path === "" || !route.path?.includes("?")) {
  477. flattenRoute(route, index);
  478. } else {
  479. for (let exploded of explodeOptionalSegments(route.path)) {
  480. flattenRoute(route, index, true, exploded);
  481. }
  482. }
  483. });
  484. return branches;
  485. }
  486. function explodeOptionalSegments(path) {
  487. let segments = path.split("/");
  488. if (segments.length === 0) return [];
  489. let [first, ...rest] = segments;
  490. let isOptional = first.endsWith("?");
  491. let required = first.replace(/\?$/, "");
  492. if (rest.length === 0) {
  493. return isOptional ? [required, ""] : [required];
  494. }
  495. let restExploded = explodeOptionalSegments(rest.join("/"));
  496. let result = [];
  497. result.push(
  498. ...restExploded.map(
  499. (subpath) => subpath === "" ? required : [required, subpath].join("/")
  500. )
  501. );
  502. if (isOptional) {
  503. result.push(...restExploded);
  504. }
  505. return result.map(
  506. (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
  507. );
  508. }
  509. function rankRouteBranches(branches) {
  510. branches.sort(
  511. (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
  512. a.routesMeta.map((meta) => meta.childrenIndex),
  513. b.routesMeta.map((meta) => meta.childrenIndex)
  514. )
  515. );
  516. }
  517. var paramRe = /^:[\w-]+$/;
  518. var dynamicSegmentValue = 3;
  519. var indexRouteValue = 2;
  520. var emptySegmentValue = 1;
  521. var staticSegmentValue = 10;
  522. var splatPenalty = -2;
  523. var isSplat = (s) => s === "*";
  524. function computeScore(path, index) {
  525. let segments = path.split("/");
  526. let initialScore = segments.length;
  527. if (segments.some(isSplat)) {
  528. initialScore += splatPenalty;
  529. }
  530. if (index) {
  531. initialScore += indexRouteValue;
  532. }
  533. return segments.filter((s) => !isSplat(s)).reduce(
  534. (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
  535. initialScore
  536. );
  537. }
  538. function compareIndexes(a, b) {
  539. let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
  540. return siblings ? (
  541. // If two routes are siblings, we should try to match the earlier sibling
  542. // first. This allows people to have fine-grained control over the matching
  543. // behavior by simply putting routes with identical paths in the order they
  544. // want them tried.
  545. a[a.length - 1] - b[b.length - 1]
  546. ) : (
  547. // Otherwise, it doesn't really make sense to rank non-siblings by index,
  548. // so they sort equally.
  549. 0
  550. );
  551. }
  552. function matchRouteBranch(branch, pathname, allowPartial = false) {
  553. let { routesMeta } = branch;
  554. let matchedParams = {};
  555. let matchedPathname = "/";
  556. let matches = [];
  557. for (let i = 0; i < routesMeta.length; ++i) {
  558. let meta = routesMeta[i];
  559. let end = i === routesMeta.length - 1;
  560. let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
  561. let match = matchPath(
  562. { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
  563. remainingPathname
  564. );
  565. let route = meta.route;
  566. if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
  567. match = matchPath(
  568. {
  569. path: meta.relativePath,
  570. caseSensitive: meta.caseSensitive,
  571. end: false
  572. },
  573. remainingPathname
  574. );
  575. }
  576. if (!match) {
  577. return null;
  578. }
  579. Object.assign(matchedParams, match.params);
  580. matches.push({
  581. // TODO: Can this as be avoided?
  582. params: matchedParams,
  583. pathname: joinPaths([matchedPathname, match.pathname]),
  584. pathnameBase: normalizePathname(
  585. joinPaths([matchedPathname, match.pathnameBase])
  586. ),
  587. route
  588. });
  589. if (match.pathnameBase !== "/") {
  590. matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
  591. }
  592. }
  593. return matches;
  594. }
  595. function matchPath(pattern, pathname) {
  596. if (typeof pattern === "string") {
  597. pattern = { path: pattern, caseSensitive: false, end: true };
  598. }
  599. let [matcher, compiledParams] = compilePath(
  600. pattern.path,
  601. pattern.caseSensitive,
  602. pattern.end
  603. );
  604. let match = pathname.match(matcher);
  605. if (!match) return null;
  606. let matchedPathname = match[0];
  607. let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
  608. let captureGroups = match.slice(1);
  609. let params = compiledParams.reduce(
  610. (memo, { paramName, isOptional }, index) => {
  611. if (paramName === "*") {
  612. let splatValue = captureGroups[index] || "";
  613. pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
  614. }
  615. const value = captureGroups[index];
  616. if (isOptional && !value) {
  617. memo[paramName] = void 0;
  618. } else {
  619. memo[paramName] = (value || "").replace(/%2F/g, "/");
  620. }
  621. return memo;
  622. },
  623. {}
  624. );
  625. return {
  626. params,
  627. pathname: matchedPathname,
  628. pathnameBase,
  629. pattern
  630. };
  631. }
  632. function compilePath(path, caseSensitive = false, end = true) {
  633. warning(
  634. path === "*" || !path.endsWith("*") || path.endsWith("/*"),
  635. `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
  636. );
  637. let params = [];
  638. let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
  639. /\/:([\w-]+)(\?)?/g,
  640. (_, paramName, isOptional) => {
  641. params.push({ paramName, isOptional: isOptional != null });
  642. return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
  643. }
  644. ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2");
  645. if (path.endsWith("*")) {
  646. params.push({ paramName: "*" });
  647. regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
  648. } else if (end) {
  649. regexpSource += "\\/*$";
  650. } else if (path !== "" && path !== "/") {
  651. regexpSource += "(?:(?=\\/|$))";
  652. } else ;
  653. let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
  654. return [matcher, params];
  655. }
  656. function decodePath(value) {
  657. try {
  658. return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
  659. } catch (error) {
  660. warning(
  661. false,
  662. `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
  663. );
  664. return value;
  665. }
  666. }
  667. function stripBasename(pathname, basename) {
  668. if (basename === "/") return pathname;
  669. if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
  670. return null;
  671. }
  672. let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
  673. let nextChar = pathname.charAt(startIndex);
  674. if (nextChar && nextChar !== "/") {
  675. return null;
  676. }
  677. return pathname.slice(startIndex) || "/";
  678. }
  679. function prependBasename({
  680. basename,
  681. pathname
  682. }) {
  683. return pathname === "/" ? basename : joinPaths([basename, pathname]);
  684. }
  685. var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  686. var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url);
  687. function resolvePath(to, fromPathname = "/") {
  688. let {
  689. pathname: toPathname,
  690. search = "",
  691. hash = ""
  692. } = typeof to === "string" ? parsePath(to) : to;
  693. let pathname;
  694. if (toPathname) {
  695. if (isAbsoluteUrl(toPathname)) {
  696. pathname = toPathname;
  697. } else {
  698. if (toPathname.includes("//")) {
  699. let oldPathname = toPathname;
  700. toPathname = toPathname.replace(/\/\/+/g, "/");
  701. warning(
  702. false,
  703. `Pathnames cannot have embedded double slashes - normalizing ${oldPathname} -> ${toPathname}`
  704. );
  705. }
  706. if (toPathname.startsWith("/")) {
  707. pathname = resolvePathname(toPathname.substring(1), "/");
  708. } else {
  709. pathname = resolvePathname(toPathname, fromPathname);
  710. }
  711. }
  712. } else {
  713. pathname = fromPathname;
  714. }
  715. return {
  716. pathname,
  717. search: normalizeSearch(search),
  718. hash: normalizeHash(hash)
  719. };
  720. }
  721. function resolvePathname(relativePath, fromPathname) {
  722. let segments = fromPathname.replace(/\/+$/, "").split("/");
  723. let relativeSegments = relativePath.split("/");
  724. relativeSegments.forEach((segment) => {
  725. if (segment === "..") {
  726. if (segments.length > 1) segments.pop();
  727. } else if (segment !== ".") {
  728. segments.push(segment);
  729. }
  730. });
  731. return segments.length > 1 ? segments.join("/") : "/";
  732. }
  733. function getInvalidPathError(char, field, dest, path) {
  734. return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
  735. path
  736. )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
  737. }
  738. function getPathContributingMatches(matches) {
  739. return matches.filter(
  740. (match, index) => index === 0 || match.route.path && match.route.path.length > 0
  741. );
  742. }
  743. function getResolveToMatches(matches) {
  744. let pathMatches = getPathContributingMatches(matches);
  745. return pathMatches.map(
  746. (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
  747. );
  748. }
  749. function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
  750. let to;
  751. if (typeof toArg === "string") {
  752. to = parsePath(toArg);
  753. } else {
  754. to = { ...toArg };
  755. invariant(
  756. !to.pathname || !to.pathname.includes("?"),
  757. getInvalidPathError("?", "pathname", "search", to)
  758. );
  759. invariant(
  760. !to.pathname || !to.pathname.includes("#"),
  761. getInvalidPathError("#", "pathname", "hash", to)
  762. );
  763. invariant(
  764. !to.search || !to.search.includes("#"),
  765. getInvalidPathError("#", "search", "hash", to)
  766. );
  767. }
  768. let isEmptyPath = toArg === "" || to.pathname === "";
  769. let toPathname = isEmptyPath ? "/" : to.pathname;
  770. let from;
  771. if (toPathname == null) {
  772. from = locationPathname;
  773. } else {
  774. let routePathnameIndex = routePathnames.length - 1;
  775. if (!isPathRelative && toPathname.startsWith("..")) {
  776. let toSegments = toPathname.split("/");
  777. while (toSegments[0] === "..") {
  778. toSegments.shift();
  779. routePathnameIndex -= 1;
  780. }
  781. to.pathname = toSegments.join("/");
  782. }
  783. from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
  784. }
  785. let path = resolvePath(to, from);
  786. let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
  787. let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
  788. if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
  789. path.pathname += "/";
  790. }
  791. return path;
  792. }
  793. var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
  794. var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
  795. var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
  796. var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
  797. var DataWithResponseInit = class {
  798. constructor(data2, init) {
  799. this.type = "DataWithResponseInit";
  800. this.data = data2;
  801. this.init = init || null;
  802. }
  803. };
  804. function data(data2, init) {
  805. return new DataWithResponseInit(
  806. data2,
  807. typeof init === "number" ? { status: init } : init
  808. );
  809. }
  810. var redirect = (url, init = 302) => {
  811. let responseInit = init;
  812. if (typeof responseInit === "number") {
  813. responseInit = { status: responseInit };
  814. } else if (typeof responseInit.status === "undefined") {
  815. responseInit.status = 302;
  816. }
  817. let headers = new Headers(responseInit.headers);
  818. headers.set("Location", url);
  819. return new Response(null, { ...responseInit, headers });
  820. };
  821. var redirectDocument = (url, init) => {
  822. let response = redirect(url, init);
  823. response.headers.set("X-Remix-Reload-Document", "true");
  824. return response;
  825. };
  826. var replace = (url, init) => {
  827. let response = redirect(url, init);
  828. response.headers.set("X-Remix-Replace", "true");
  829. return response;
  830. };
  831. var ErrorResponseImpl = class {
  832. constructor(status, statusText, data2, internal = false) {
  833. this.status = status;
  834. this.statusText = statusText || "";
  835. this.internal = internal;
  836. if (data2 instanceof Error) {
  837. this.data = data2.toString();
  838. this.error = data2;
  839. } else {
  840. this.data = data2;
  841. }
  842. }
  843. };
  844. function isRouteErrorResponse(error) {
  845. return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
  846. }
  847. function getRoutePattern(matches) {
  848. return matches.map((m) => m.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/";
  849. }
  850. // lib/router/router.ts
  851. var validMutationMethodsArr = [
  852. "POST",
  853. "PUT",
  854. "PATCH",
  855. "DELETE"
  856. ];
  857. var validMutationMethods = new Set(
  858. validMutationMethodsArr
  859. );
  860. var validRequestMethodsArr = [
  861. "GET",
  862. ...validMutationMethodsArr
  863. ];
  864. var validRequestMethods = new Set(validRequestMethodsArr);
  865. var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  866. var defaultMapRouteProperties = (route) => ({
  867. hasErrorBoundary: Boolean(route.hasErrorBoundary)
  868. });
  869. var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
  870. function createStaticHandler(routes, opts) {
  871. invariant(
  872. routes.length > 0,
  873. "You must provide a non-empty routes array to createStaticHandler"
  874. );
  875. let manifest = {};
  876. let basename = (opts ? opts.basename : null) || "/";
  877. let _mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
  878. let mapRouteProperties = _mapRouteProperties;
  879. if (opts?.unstable_instrumentations) {
  880. let instrumentations = opts.unstable_instrumentations;
  881. mapRouteProperties = (route) => {
  882. return {
  883. ..._mapRouteProperties(route),
  884. ...getRouteInstrumentationUpdates(
  885. instrumentations.map((i) => i.route).filter(Boolean),
  886. route
  887. )
  888. };
  889. };
  890. }
  891. let dataRoutes = convertRoutesToDataRoutes(
  892. routes,
  893. mapRouteProperties,
  894. void 0,
  895. manifest
  896. );
  897. async function query(request, {
  898. requestContext,
  899. filterMatchesToLoad,
  900. skipLoaderErrorBubbling,
  901. skipRevalidation,
  902. dataStrategy,
  903. generateMiddlewareResponse
  904. } = {}) {
  905. let url = new URL(request.url);
  906. let method = request.method;
  907. let location = createLocation("", createPath(url), null, "default");
  908. let matches = matchRoutes(dataRoutes, location, basename);
  909. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  910. if (!isValidMethod(method) && method !== "HEAD") {
  911. let error = getInternalRouterError(405, { method });
  912. let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
  913. let staticContext = {
  914. basename,
  915. location,
  916. matches: methodNotAllowedMatches,
  917. loaderData: {},
  918. actionData: null,
  919. errors: {
  920. [route.id]: error
  921. },
  922. statusCode: error.status,
  923. loaderHeaders: {},
  924. actionHeaders: {}
  925. };
  926. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  927. } else if (!matches) {
  928. let error = getInternalRouterError(404, { pathname: location.pathname });
  929. let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
  930. let staticContext = {
  931. basename,
  932. location,
  933. matches: notFoundMatches,
  934. loaderData: {},
  935. actionData: null,
  936. errors: {
  937. [route.id]: error
  938. },
  939. statusCode: error.status,
  940. loaderHeaders: {},
  941. actionHeaders: {}
  942. };
  943. return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext;
  944. }
  945. if (generateMiddlewareResponse) {
  946. invariant(
  947. requestContext instanceof RouterContextProvider,
  948. "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  949. );
  950. try {
  951. await loadLazyMiddlewareForMatches(
  952. matches,
  953. manifest,
  954. mapRouteProperties
  955. );
  956. let renderedStaticContext;
  957. let response = await runServerMiddlewarePipeline(
  958. {
  959. request,
  960. unstable_pattern: getRoutePattern(matches),
  961. matches,
  962. params: matches[0].params,
  963. // If we're calling middleware then it must be enabled so we can cast
  964. // this to the proper type knowing it's not an `AppLoadContext`
  965. context: requestContext
  966. },
  967. async () => {
  968. let res = await generateMiddlewareResponse(
  969. async (revalidationRequest, opts2 = {}) => {
  970. let result2 = await queryImpl(
  971. revalidationRequest,
  972. location,
  973. matches,
  974. requestContext,
  975. dataStrategy || null,
  976. skipLoaderErrorBubbling === true,
  977. null,
  978. "filterMatchesToLoad" in opts2 ? opts2.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null,
  979. skipRevalidation === true
  980. );
  981. if (isResponse(result2)) {
  982. return result2;
  983. }
  984. renderedStaticContext = { location, basename, ...result2 };
  985. return renderedStaticContext;
  986. }
  987. );
  988. return res;
  989. },
  990. async (error, routeId) => {
  991. if (isRedirectResponse(error)) {
  992. return error;
  993. }
  994. if (isResponse(error)) {
  995. try {
  996. error = new ErrorResponseImpl(
  997. error.status,
  998. error.statusText,
  999. await parseResponseBody(error)
  1000. );
  1001. } catch (e) {
  1002. error = e;
  1003. }
  1004. }
  1005. if (isDataWithResponseInit(error)) {
  1006. error = dataWithResponseInitToErrorResponse(error);
  1007. }
  1008. if (renderedStaticContext) {
  1009. if (routeId in renderedStaticContext.loaderData) {
  1010. renderedStaticContext.loaderData[routeId] = void 0;
  1011. }
  1012. let staticContext = getStaticContextFromError(
  1013. dataRoutes,
  1014. renderedStaticContext,
  1015. error,
  1016. skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
  1017. );
  1018. return generateMiddlewareResponse(
  1019. () => Promise.resolve(staticContext)
  1020. );
  1021. } else {
  1022. let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
  1023. matches,
  1024. matches.find(
  1025. (m) => m.route.id === routeId || m.route.loader
  1026. )?.route.id || routeId
  1027. ).route.id;
  1028. let staticContext = {
  1029. matches,
  1030. location,
  1031. basename,
  1032. loaderData: {},
  1033. actionData: null,
  1034. errors: {
  1035. [boundaryRouteId]: error
  1036. },
  1037. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  1038. actionHeaders: {},
  1039. loaderHeaders: {}
  1040. };
  1041. return generateMiddlewareResponse(
  1042. () => Promise.resolve(staticContext)
  1043. );
  1044. }
  1045. }
  1046. );
  1047. invariant(isResponse(response), "Expected a response in query()");
  1048. return response;
  1049. } catch (e) {
  1050. if (isResponse(e)) {
  1051. return e;
  1052. }
  1053. throw e;
  1054. }
  1055. }
  1056. let result = await queryImpl(
  1057. request,
  1058. location,
  1059. matches,
  1060. requestContext,
  1061. dataStrategy || null,
  1062. skipLoaderErrorBubbling === true,
  1063. null,
  1064. filterMatchesToLoad || null,
  1065. skipRevalidation === true
  1066. );
  1067. if (isResponse(result)) {
  1068. return result;
  1069. }
  1070. return { location, basename, ...result };
  1071. }
  1072. async function queryRoute(request, {
  1073. routeId,
  1074. requestContext,
  1075. dataStrategy,
  1076. generateMiddlewareResponse
  1077. } = {}) {
  1078. let url = new URL(request.url);
  1079. let method = request.method;
  1080. let location = createLocation("", createPath(url), null, "default");
  1081. let matches = matchRoutes(dataRoutes, location, basename);
  1082. requestContext = requestContext != null ? requestContext : new RouterContextProvider();
  1083. if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
  1084. throw getInternalRouterError(405, { method });
  1085. } else if (!matches) {
  1086. throw getInternalRouterError(404, { pathname: location.pathname });
  1087. }
  1088. let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
  1089. if (routeId && !match) {
  1090. throw getInternalRouterError(403, {
  1091. pathname: location.pathname,
  1092. routeId
  1093. });
  1094. } else if (!match) {
  1095. throw getInternalRouterError(404, { pathname: location.pathname });
  1096. }
  1097. if (generateMiddlewareResponse) {
  1098. invariant(
  1099. requestContext instanceof RouterContextProvider,
  1100. "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`"
  1101. );
  1102. await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
  1103. let response = await runServerMiddlewarePipeline(
  1104. {
  1105. request,
  1106. unstable_pattern: getRoutePattern(matches),
  1107. matches,
  1108. params: matches[0].params,
  1109. // If we're calling middleware then it must be enabled so we can cast
  1110. // this to the proper type knowing it's not an `AppLoadContext`
  1111. context: requestContext
  1112. },
  1113. async () => {
  1114. let res = await generateMiddlewareResponse(
  1115. async (innerRequest) => {
  1116. let result2 = await queryImpl(
  1117. innerRequest,
  1118. location,
  1119. matches,
  1120. requestContext,
  1121. dataStrategy || null,
  1122. false,
  1123. match,
  1124. null,
  1125. false
  1126. );
  1127. let processed = handleQueryResult(result2);
  1128. return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed);
  1129. }
  1130. );
  1131. return res;
  1132. },
  1133. (error) => {
  1134. if (isDataWithResponseInit(error)) {
  1135. return Promise.resolve(dataWithResponseInitToResponse(error));
  1136. }
  1137. if (isResponse(error)) {
  1138. return Promise.resolve(error);
  1139. }
  1140. throw error;
  1141. }
  1142. );
  1143. return response;
  1144. }
  1145. let result = await queryImpl(
  1146. request,
  1147. location,
  1148. matches,
  1149. requestContext,
  1150. dataStrategy || null,
  1151. false,
  1152. match,
  1153. null,
  1154. false
  1155. );
  1156. return handleQueryResult(result);
  1157. function handleQueryResult(result2) {
  1158. if (isResponse(result2)) {
  1159. return result2;
  1160. }
  1161. let error = result2.errors ? Object.values(result2.errors)[0] : void 0;
  1162. if (error !== void 0) {
  1163. throw error;
  1164. }
  1165. if (result2.actionData) {
  1166. return Object.values(result2.actionData)[0];
  1167. }
  1168. if (result2.loaderData) {
  1169. return Object.values(result2.loaderData)[0];
  1170. }
  1171. return void 0;
  1172. }
  1173. }
  1174. async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
  1175. invariant(
  1176. request.signal,
  1177. "query()/queryRoute() requests must contain an AbortController signal"
  1178. );
  1179. try {
  1180. if (isMutationMethod(request.method)) {
  1181. let result2 = await submit(
  1182. request,
  1183. matches,
  1184. routeMatch || getTargetMatch(matches, location),
  1185. requestContext,
  1186. dataStrategy,
  1187. skipLoaderErrorBubbling,
  1188. routeMatch != null,
  1189. filterMatchesToLoad,
  1190. skipRevalidation
  1191. );
  1192. return result2;
  1193. }
  1194. let result = await loadRouteData(
  1195. request,
  1196. matches,
  1197. requestContext,
  1198. dataStrategy,
  1199. skipLoaderErrorBubbling,
  1200. routeMatch,
  1201. filterMatchesToLoad
  1202. );
  1203. return isResponse(result) ? result : {
  1204. ...result,
  1205. actionData: null,
  1206. actionHeaders: {}
  1207. };
  1208. } catch (e) {
  1209. if (isDataStrategyResult(e) && isResponse(e.result)) {
  1210. if (e.type === "error" /* error */) {
  1211. throw e.result;
  1212. }
  1213. return e.result;
  1214. }
  1215. if (isRedirectResponse(e)) {
  1216. return e;
  1217. }
  1218. throw e;
  1219. }
  1220. }
  1221. async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
  1222. let result;
  1223. if (!actionMatch.route.action && !actionMatch.route.lazy) {
  1224. let error = getInternalRouterError(405, {
  1225. method: request.method,
  1226. pathname: new URL(request.url).pathname,
  1227. routeId: actionMatch.route.id
  1228. });
  1229. if (isRouteRequest) {
  1230. throw error;
  1231. }
  1232. result = {
  1233. type: "error" /* error */,
  1234. error
  1235. };
  1236. } else {
  1237. let dsMatches = getTargetedDataStrategyMatches(
  1238. mapRouteProperties,
  1239. manifest,
  1240. request,
  1241. matches,
  1242. actionMatch,
  1243. [],
  1244. requestContext
  1245. );
  1246. let results = await callDataStrategy(
  1247. request,
  1248. dsMatches,
  1249. isRouteRequest,
  1250. requestContext,
  1251. dataStrategy
  1252. );
  1253. result = results[actionMatch.route.id];
  1254. if (request.signal.aborted) {
  1255. throwStaticHandlerAbortedError(request, isRouteRequest);
  1256. }
  1257. }
  1258. if (isRedirectResult(result)) {
  1259. throw new Response(null, {
  1260. status: result.response.status,
  1261. headers: {
  1262. Location: result.response.headers.get("Location")
  1263. }
  1264. });
  1265. }
  1266. if (isRouteRequest) {
  1267. if (isErrorResult(result)) {
  1268. throw result.error;
  1269. }
  1270. return {
  1271. matches: [actionMatch],
  1272. loaderData: {},
  1273. actionData: { [actionMatch.route.id]: result.data },
  1274. errors: null,
  1275. // Note: statusCode + headers are unused here since queryRoute will
  1276. // return the raw Response or value
  1277. statusCode: 200,
  1278. loaderHeaders: {},
  1279. actionHeaders: {}
  1280. };
  1281. }
  1282. if (skipRevalidation) {
  1283. if (isErrorResult(result)) {
  1284. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  1285. return {
  1286. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  1287. actionData: null,
  1288. actionHeaders: {
  1289. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  1290. },
  1291. matches,
  1292. loaderData: {},
  1293. errors: {
  1294. [boundaryMatch.route.id]: result.error
  1295. },
  1296. loaderHeaders: {}
  1297. };
  1298. } else {
  1299. return {
  1300. actionData: {
  1301. [actionMatch.route.id]: result.data
  1302. },
  1303. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
  1304. matches,
  1305. loaderData: {},
  1306. errors: null,
  1307. statusCode: result.statusCode || 200,
  1308. loaderHeaders: {}
  1309. };
  1310. }
  1311. }
  1312. let loaderRequest = new Request(request.url, {
  1313. headers: request.headers,
  1314. redirect: request.redirect,
  1315. signal: request.signal
  1316. });
  1317. if (isErrorResult(result)) {
  1318. let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
  1319. let handlerContext2 = await loadRouteData(
  1320. loaderRequest,
  1321. matches,
  1322. requestContext,
  1323. dataStrategy,
  1324. skipLoaderErrorBubbling,
  1325. null,
  1326. filterMatchesToLoad,
  1327. [boundaryMatch.route.id, result]
  1328. );
  1329. return {
  1330. ...handlerContext2,
  1331. statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
  1332. actionData: null,
  1333. actionHeaders: {
  1334. ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
  1335. }
  1336. };
  1337. }
  1338. let handlerContext = await loadRouteData(
  1339. loaderRequest,
  1340. matches,
  1341. requestContext,
  1342. dataStrategy,
  1343. skipLoaderErrorBubbling,
  1344. null,
  1345. filterMatchesToLoad
  1346. );
  1347. return {
  1348. ...handlerContext,
  1349. actionData: {
  1350. [actionMatch.route.id]: result.data
  1351. },
  1352. // action status codes take precedence over loader status codes
  1353. ...result.statusCode ? { statusCode: result.statusCode } : {},
  1354. actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
  1355. };
  1356. }
  1357. async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
  1358. let isRouteRequest = routeMatch != null;
  1359. if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
  1360. throw getInternalRouterError(400, {
  1361. method: request.method,
  1362. pathname: new URL(request.url).pathname,
  1363. routeId: routeMatch?.route.id
  1364. });
  1365. }
  1366. let dsMatches;
  1367. if (routeMatch) {
  1368. dsMatches = getTargetedDataStrategyMatches(
  1369. mapRouteProperties,
  1370. manifest,
  1371. request,
  1372. matches,
  1373. routeMatch,
  1374. [],
  1375. requestContext
  1376. );
  1377. } else {
  1378. let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
  1379. // Up to but not including the boundary
  1380. matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
  1381. ) : void 0;
  1382. let pattern = getRoutePattern(matches);
  1383. dsMatches = matches.map((match, index) => {
  1384. if (maxIdx != null && index > maxIdx) {
  1385. return getDataStrategyMatch(
  1386. mapRouteProperties,
  1387. manifest,
  1388. request,
  1389. pattern,
  1390. match,
  1391. [],
  1392. requestContext,
  1393. false
  1394. );
  1395. }
  1396. return getDataStrategyMatch(
  1397. mapRouteProperties,
  1398. manifest,
  1399. request,
  1400. pattern,
  1401. match,
  1402. [],
  1403. requestContext,
  1404. (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
  1405. );
  1406. });
  1407. }
  1408. if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
  1409. return {
  1410. matches,
  1411. loaderData: {},
  1412. errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
  1413. [pendingActionResult[0]]: pendingActionResult[1].error
  1414. } : null,
  1415. statusCode: 200,
  1416. loaderHeaders: {}
  1417. };
  1418. }
  1419. let results = await callDataStrategy(
  1420. request,
  1421. dsMatches,
  1422. isRouteRequest,
  1423. requestContext,
  1424. dataStrategy
  1425. );
  1426. if (request.signal.aborted) {
  1427. throwStaticHandlerAbortedError(request, isRouteRequest);
  1428. }
  1429. let handlerContext = processRouteLoaderData(
  1430. matches,
  1431. results,
  1432. pendingActionResult,
  1433. true,
  1434. skipLoaderErrorBubbling
  1435. );
  1436. return {
  1437. ...handlerContext,
  1438. matches
  1439. };
  1440. }
  1441. async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
  1442. let results = await callDataStrategyImpl(
  1443. dataStrategy || defaultDataStrategy,
  1444. request,
  1445. matches,
  1446. null,
  1447. requestContext);
  1448. let dataResults = {};
  1449. await Promise.all(
  1450. matches.map(async (match) => {
  1451. if (!(match.route.id in results)) {
  1452. return;
  1453. }
  1454. let result = results[match.route.id];
  1455. if (isRedirectDataStrategyResult(result)) {
  1456. let response = result.result;
  1457. throw normalizeRelativeRoutingRedirectResponse(
  1458. response,
  1459. request,
  1460. match.route.id,
  1461. matches,
  1462. basename
  1463. );
  1464. }
  1465. if (isRouteRequest) {
  1466. if (isResponse(result.result)) {
  1467. throw result;
  1468. } else if (isDataWithResponseInit(result.result)) {
  1469. throw dataWithResponseInitToResponse(result.result);
  1470. }
  1471. }
  1472. dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
  1473. })
  1474. );
  1475. return dataResults;
  1476. }
  1477. return {
  1478. dataRoutes,
  1479. query,
  1480. queryRoute
  1481. };
  1482. }
  1483. function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
  1484. let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
  1485. return {
  1486. ...handlerContext,
  1487. statusCode: isRouteErrorResponse(error) ? error.status : 500,
  1488. errors: {
  1489. [errorBoundaryId]: error
  1490. }
  1491. };
  1492. }
  1493. function throwStaticHandlerAbortedError(request, isRouteRequest) {
  1494. if (request.signal.reason !== void 0) {
  1495. throw request.signal.reason;
  1496. }
  1497. let method = isRouteRequest ? "queryRoute" : "query";
  1498. throw new Error(
  1499. `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
  1500. );
  1501. }
  1502. function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
  1503. let contextualMatches;
  1504. let activeRouteMatch;
  1505. {
  1506. contextualMatches = matches;
  1507. activeRouteMatch = matches[matches.length - 1];
  1508. }
  1509. let path = resolveTo(
  1510. to ? to : ".",
  1511. getResolveToMatches(contextualMatches),
  1512. stripBasename(location.pathname, basename) || location.pathname,
  1513. relative === "path"
  1514. );
  1515. if (to == null) {
  1516. path.search = location.search;
  1517. path.hash = location.hash;
  1518. }
  1519. if ((to == null || to === "" || to === ".") && activeRouteMatch) {
  1520. let nakedIndex = hasNakedIndexQuery(path.search);
  1521. if (activeRouteMatch.route.index && !nakedIndex) {
  1522. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  1523. } else if (!activeRouteMatch.route.index && nakedIndex) {
  1524. let params = new URLSearchParams(path.search);
  1525. let indexValues = params.getAll("index");
  1526. params.delete("index");
  1527. indexValues.filter((v) => v).forEach((v) => params.append("index", v));
  1528. let qs = params.toString();
  1529. path.search = qs ? `?${qs}` : "";
  1530. }
  1531. }
  1532. if (basename !== "/") {
  1533. path.pathname = prependBasename({ basename, pathname: path.pathname });
  1534. }
  1535. return createPath(path);
  1536. }
  1537. function shouldRevalidateLoader(loaderMatch, arg) {
  1538. if (loaderMatch.route.shouldRevalidate) {
  1539. let routeChoice = loaderMatch.route.shouldRevalidate(arg);
  1540. if (typeof routeChoice === "boolean") {
  1541. return routeChoice;
  1542. }
  1543. }
  1544. return arg.defaultShouldRevalidate;
  1545. }
  1546. var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
  1547. var loadLazyRouteProperty = ({
  1548. key,
  1549. route,
  1550. manifest,
  1551. mapRouteProperties
  1552. }) => {
  1553. let routeToUpdate = manifest[route.id];
  1554. invariant(routeToUpdate, "No route found in manifest");
  1555. if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
  1556. return;
  1557. }
  1558. let lazyFn = routeToUpdate.lazy[key];
  1559. if (!lazyFn) {
  1560. return;
  1561. }
  1562. let cache2 = lazyRoutePropertyCache.get(routeToUpdate);
  1563. if (!cache2) {
  1564. cache2 = {};
  1565. lazyRoutePropertyCache.set(routeToUpdate, cache2);
  1566. }
  1567. let cachedPromise = cache2[key];
  1568. if (cachedPromise) {
  1569. return cachedPromise;
  1570. }
  1571. let propertyPromise = (async () => {
  1572. let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
  1573. let staticRouteValue = routeToUpdate[key];
  1574. let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
  1575. if (isUnsupported) {
  1576. warning(
  1577. !isUnsupported,
  1578. "Route property " + key + " is not a supported lazy route property. This property will be ignored."
  1579. );
  1580. cache2[key] = Promise.resolve();
  1581. } else if (isStaticallyDefined) {
  1582. warning(
  1583. false,
  1584. `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
  1585. );
  1586. } else {
  1587. let value = await lazyFn();
  1588. if (value != null) {
  1589. Object.assign(routeToUpdate, { [key]: value });
  1590. Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
  1591. }
  1592. }
  1593. if (typeof routeToUpdate.lazy === "object") {
  1594. routeToUpdate.lazy[key] = void 0;
  1595. if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
  1596. routeToUpdate.lazy = void 0;
  1597. }
  1598. }
  1599. })();
  1600. cache2[key] = propertyPromise;
  1601. return propertyPromise;
  1602. };
  1603. var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
  1604. function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
  1605. let routeToUpdate = manifest[route.id];
  1606. invariant(routeToUpdate, "No route found in manifest");
  1607. if (!route.lazy) {
  1608. return {
  1609. lazyRoutePromise: void 0,
  1610. lazyHandlerPromise: void 0
  1611. };
  1612. }
  1613. if (typeof route.lazy === "function") {
  1614. let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
  1615. if (cachedPromise) {
  1616. return {
  1617. lazyRoutePromise: cachedPromise,
  1618. lazyHandlerPromise: cachedPromise
  1619. };
  1620. }
  1621. let lazyRoutePromise2 = (async () => {
  1622. invariant(
  1623. typeof route.lazy === "function",
  1624. "No lazy route function found"
  1625. );
  1626. let lazyRoute = await route.lazy();
  1627. let routeUpdates = {};
  1628. for (let lazyRouteProperty in lazyRoute) {
  1629. let lazyValue = lazyRoute[lazyRouteProperty];
  1630. if (lazyValue === void 0) {
  1631. continue;
  1632. }
  1633. let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
  1634. let staticRouteValue = routeToUpdate[lazyRouteProperty];
  1635. let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
  1636. // on the route updates
  1637. lazyRouteProperty !== "hasErrorBoundary";
  1638. if (isUnsupported) {
  1639. warning(
  1640. !isUnsupported,
  1641. "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
  1642. );
  1643. } else if (isStaticallyDefined) {
  1644. warning(
  1645. !isStaticallyDefined,
  1646. `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
  1647. );
  1648. } else {
  1649. routeUpdates[lazyRouteProperty] = lazyValue;
  1650. }
  1651. }
  1652. Object.assign(routeToUpdate, routeUpdates);
  1653. Object.assign(routeToUpdate, {
  1654. // To keep things framework agnostic, we use the provided `mapRouteProperties`
  1655. // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
  1656. // since the logic will differ between frameworks.
  1657. ...mapRouteProperties(routeToUpdate),
  1658. lazy: void 0
  1659. });
  1660. })();
  1661. lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
  1662. lazyRoutePromise2.catch(() => {
  1663. });
  1664. return {
  1665. lazyRoutePromise: lazyRoutePromise2,
  1666. lazyHandlerPromise: lazyRoutePromise2
  1667. };
  1668. }
  1669. let lazyKeys = Object.keys(route.lazy);
  1670. let lazyPropertyPromises = [];
  1671. let lazyHandlerPromise = void 0;
  1672. for (let key of lazyKeys) {
  1673. if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
  1674. continue;
  1675. }
  1676. let promise = loadLazyRouteProperty({
  1677. key,
  1678. route,
  1679. manifest,
  1680. mapRouteProperties
  1681. });
  1682. if (promise) {
  1683. lazyPropertyPromises.push(promise);
  1684. if (key === type) {
  1685. lazyHandlerPromise = promise;
  1686. }
  1687. }
  1688. }
  1689. let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
  1690. }) : void 0;
  1691. lazyRoutePromise?.catch(() => {
  1692. });
  1693. lazyHandlerPromise?.catch(() => {
  1694. });
  1695. return {
  1696. lazyRoutePromise,
  1697. lazyHandlerPromise
  1698. };
  1699. }
  1700. function isNonNullable(value) {
  1701. return value !== void 0;
  1702. }
  1703. function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
  1704. let promises = matches.map(({ route }) => {
  1705. if (typeof route.lazy !== "object" || !route.lazy.middleware) {
  1706. return void 0;
  1707. }
  1708. return loadLazyRouteProperty({
  1709. key: "middleware",
  1710. route,
  1711. manifest,
  1712. mapRouteProperties
  1713. });
  1714. }).filter(isNonNullable);
  1715. return promises.length > 0 ? Promise.all(promises) : void 0;
  1716. }
  1717. async function defaultDataStrategy(args) {
  1718. let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
  1719. let keyedResults = {};
  1720. let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
  1721. results.forEach((result, i) => {
  1722. keyedResults[matchesToLoad[i].route.id] = result;
  1723. });
  1724. return keyedResults;
  1725. }
  1726. function runServerMiddlewarePipeline(args, handler, errorHandler) {
  1727. return runMiddlewarePipeline(
  1728. args,
  1729. handler,
  1730. processResult,
  1731. isResponse,
  1732. errorHandler
  1733. );
  1734. function processResult(result) {
  1735. return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result;
  1736. }
  1737. }
  1738. async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) {
  1739. let { matches, request, params, context, unstable_pattern } = args;
  1740. let tuples = matches.flatMap(
  1741. (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : []
  1742. );
  1743. let result = await callRouteMiddleware(
  1744. {
  1745. request,
  1746. params,
  1747. context,
  1748. unstable_pattern
  1749. },
  1750. tuples,
  1751. handler,
  1752. processResult,
  1753. isResult,
  1754. errorHandler
  1755. );
  1756. return result;
  1757. }
  1758. async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) {
  1759. let { request } = args;
  1760. if (request.signal.aborted) {
  1761. throw request.signal.reason ?? new Error(`Request aborted: ${request.method} ${request.url}`);
  1762. }
  1763. let tuple = middlewares[idx];
  1764. if (!tuple) {
  1765. let result = await handler();
  1766. return result;
  1767. }
  1768. let [routeId, middleware] = tuple;
  1769. let nextResult;
  1770. let next = async () => {
  1771. if (nextResult) {
  1772. throw new Error("You may only call `next()` once per middleware");
  1773. }
  1774. try {
  1775. let result = await callRouteMiddleware(
  1776. args,
  1777. middlewares,
  1778. handler,
  1779. processResult,
  1780. isResult,
  1781. errorHandler,
  1782. idx + 1
  1783. );
  1784. nextResult = { value: result };
  1785. return nextResult.value;
  1786. } catch (error) {
  1787. nextResult = { value: await errorHandler(error, routeId, nextResult) };
  1788. return nextResult.value;
  1789. }
  1790. };
  1791. try {
  1792. let value = await middleware(args, next);
  1793. let result = value != null ? processResult(value) : void 0;
  1794. if (isResult(result)) {
  1795. return result;
  1796. } else if (nextResult) {
  1797. return result ?? nextResult.value;
  1798. } else {
  1799. nextResult = { value: await next() };
  1800. return nextResult.value;
  1801. }
  1802. } catch (error) {
  1803. let response = await errorHandler(error, routeId, nextResult);
  1804. return response;
  1805. }
  1806. }
  1807. function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
  1808. let lazyMiddlewarePromise = loadLazyRouteProperty({
  1809. key: "middleware",
  1810. route: match.route,
  1811. manifest,
  1812. mapRouteProperties
  1813. });
  1814. let lazyRoutePromises = loadLazyRoute(
  1815. match.route,
  1816. isMutationMethod(request.method) ? "action" : "loader",
  1817. manifest,
  1818. mapRouteProperties,
  1819. lazyRoutePropertiesToSkip
  1820. );
  1821. return {
  1822. middleware: lazyMiddlewarePromise,
  1823. route: lazyRoutePromises.lazyRoutePromise,
  1824. handler: lazyRoutePromises.lazyHandlerPromise
  1825. };
  1826. }
  1827. function getDataStrategyMatch(mapRouteProperties, manifest, request, unstable_pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null) {
  1828. let isUsingNewApi = false;
  1829. let _lazyPromises = getDataStrategyMatchLazyPromises(
  1830. mapRouteProperties,
  1831. manifest,
  1832. request,
  1833. match,
  1834. lazyRoutePropertiesToSkip
  1835. );
  1836. return {
  1837. ...match,
  1838. _lazyPromises,
  1839. shouldLoad,
  1840. shouldRevalidateArgs,
  1841. shouldCallHandler(defaultShouldRevalidate) {
  1842. isUsingNewApi = true;
  1843. if (!shouldRevalidateArgs) {
  1844. return shouldLoad;
  1845. }
  1846. if (typeof defaultShouldRevalidate === "boolean") {
  1847. return shouldRevalidateLoader(match, {
  1848. ...shouldRevalidateArgs,
  1849. defaultShouldRevalidate
  1850. });
  1851. }
  1852. return shouldRevalidateLoader(match, shouldRevalidateArgs);
  1853. },
  1854. resolve(handlerOverride) {
  1855. let { lazy, loader, middleware } = match.route;
  1856. let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader);
  1857. let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy;
  1858. if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) {
  1859. return callLoaderOrAction({
  1860. request,
  1861. unstable_pattern,
  1862. match,
  1863. lazyHandlerPromise: _lazyPromises?.handler,
  1864. lazyRoutePromise: _lazyPromises?.route,
  1865. handlerOverride,
  1866. scopedContext
  1867. });
  1868. }
  1869. return Promise.resolve({ type: "data" /* data */, result: void 0 });
  1870. }
  1871. };
  1872. }
  1873. function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
  1874. return matches.map((match) => {
  1875. if (match.route.id !== targetMatch.route.id) {
  1876. return {
  1877. ...match,
  1878. shouldLoad: false,
  1879. shouldRevalidateArgs,
  1880. shouldCallHandler: () => false,
  1881. _lazyPromises: getDataStrategyMatchLazyPromises(
  1882. mapRouteProperties,
  1883. manifest,
  1884. request,
  1885. match,
  1886. lazyRoutePropertiesToSkip
  1887. ),
  1888. resolve: () => Promise.resolve({ type: "data", result: void 0 })
  1889. };
  1890. }
  1891. return getDataStrategyMatch(
  1892. mapRouteProperties,
  1893. manifest,
  1894. request,
  1895. getRoutePattern(matches),
  1896. match,
  1897. lazyRoutePropertiesToSkip,
  1898. scopedContext,
  1899. true,
  1900. shouldRevalidateArgs
  1901. );
  1902. });
  1903. }
  1904. async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
  1905. if (matches.some((m) => m._lazyPromises?.middleware)) {
  1906. await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
  1907. }
  1908. let dataStrategyArgs = {
  1909. request,
  1910. unstable_pattern: getRoutePattern(matches),
  1911. params: matches[0].params,
  1912. context: scopedContext,
  1913. matches
  1914. };
  1915. let runClientMiddleware = () => {
  1916. throw new Error(
  1917. "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
  1918. );
  1919. } ;
  1920. let results = await dataStrategyImpl({
  1921. ...dataStrategyArgs,
  1922. fetcherKey,
  1923. runClientMiddleware
  1924. });
  1925. try {
  1926. await Promise.all(
  1927. matches.flatMap((m) => [
  1928. m._lazyPromises?.handler,
  1929. m._lazyPromises?.route
  1930. ])
  1931. );
  1932. } catch (e) {
  1933. }
  1934. return results;
  1935. }
  1936. async function callLoaderOrAction({
  1937. request,
  1938. unstable_pattern,
  1939. match,
  1940. lazyHandlerPromise,
  1941. lazyRoutePromise,
  1942. handlerOverride,
  1943. scopedContext
  1944. }) {
  1945. let result;
  1946. let onReject;
  1947. let isAction = isMutationMethod(request.method);
  1948. let type = isAction ? "action" : "loader";
  1949. let runHandler = (handler) => {
  1950. let reject;
  1951. let abortPromise = new Promise((_, r) => reject = r);
  1952. onReject = () => reject();
  1953. request.signal.addEventListener("abort", onReject);
  1954. let actualHandler = (ctx) => {
  1955. if (typeof handler !== "function") {
  1956. return Promise.reject(
  1957. new Error(
  1958. `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
  1959. )
  1960. );
  1961. }
  1962. return handler(
  1963. {
  1964. request,
  1965. unstable_pattern,
  1966. params: match.params,
  1967. context: scopedContext
  1968. },
  1969. ...ctx !== void 0 ? [ctx] : []
  1970. );
  1971. };
  1972. let handlerPromise = (async () => {
  1973. try {
  1974. let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
  1975. return { type: "data", result: val };
  1976. } catch (e) {
  1977. return { type: "error", result: e };
  1978. }
  1979. })();
  1980. return Promise.race([handlerPromise, abortPromise]);
  1981. };
  1982. try {
  1983. let handler = isAction ? match.route.action : match.route.loader;
  1984. if (lazyHandlerPromise || lazyRoutePromise) {
  1985. if (handler) {
  1986. let handlerError;
  1987. let [value] = await Promise.all([
  1988. // If the handler throws, don't let it immediately bubble out,
  1989. // since we need to let the lazy() execution finish so we know if this
  1990. // route has a boundary that can handle the error
  1991. runHandler(handler).catch((e) => {
  1992. handlerError = e;
  1993. }),
  1994. // Ensure all lazy route promises are resolved before continuing
  1995. lazyHandlerPromise,
  1996. lazyRoutePromise
  1997. ]);
  1998. if (handlerError !== void 0) {
  1999. throw handlerError;
  2000. }
  2001. result = value;
  2002. } else {
  2003. await lazyHandlerPromise;
  2004. let handler2 = isAction ? match.route.action : match.route.loader;
  2005. if (handler2) {
  2006. [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
  2007. } else if (type === "action") {
  2008. let url = new URL(request.url);
  2009. let pathname = url.pathname + url.search;
  2010. throw getInternalRouterError(405, {
  2011. method: request.method,
  2012. pathname,
  2013. routeId: match.route.id
  2014. });
  2015. } else {
  2016. return { type: "data" /* data */, result: void 0 };
  2017. }
  2018. }
  2019. } else if (!handler) {
  2020. let url = new URL(request.url);
  2021. let pathname = url.pathname + url.search;
  2022. throw getInternalRouterError(404, {
  2023. pathname
  2024. });
  2025. } else {
  2026. result = await runHandler(handler);
  2027. }
  2028. } catch (e) {
  2029. return { type: "error" /* error */, result: e };
  2030. } finally {
  2031. if (onReject) {
  2032. request.signal.removeEventListener("abort", onReject);
  2033. }
  2034. }
  2035. return result;
  2036. }
  2037. async function parseResponseBody(response) {
  2038. let contentType = response.headers.get("Content-Type");
  2039. if (contentType && /\bapplication\/json\b/.test(contentType)) {
  2040. return response.body == null ? null : response.json();
  2041. }
  2042. return response.text();
  2043. }
  2044. async function convertDataStrategyResultToDataResult(dataStrategyResult) {
  2045. let { result, type } = dataStrategyResult;
  2046. if (isResponse(result)) {
  2047. let data2;
  2048. try {
  2049. data2 = await parseResponseBody(result);
  2050. } catch (e) {
  2051. return { type: "error" /* error */, error: e };
  2052. }
  2053. if (type === "error" /* error */) {
  2054. return {
  2055. type: "error" /* error */,
  2056. error: new ErrorResponseImpl(result.status, result.statusText, data2),
  2057. statusCode: result.status,
  2058. headers: result.headers
  2059. };
  2060. }
  2061. return {
  2062. type: "data" /* data */,
  2063. data: data2,
  2064. statusCode: result.status,
  2065. headers: result.headers
  2066. };
  2067. }
  2068. if (type === "error" /* error */) {
  2069. if (isDataWithResponseInit(result)) {
  2070. if (result.data instanceof Error) {
  2071. return {
  2072. type: "error" /* error */,
  2073. error: result.data,
  2074. statusCode: result.init?.status,
  2075. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  2076. };
  2077. }
  2078. return {
  2079. type: "error" /* error */,
  2080. error: dataWithResponseInitToErrorResponse(result),
  2081. statusCode: isRouteErrorResponse(result) ? result.status : void 0,
  2082. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  2083. };
  2084. }
  2085. return {
  2086. type: "error" /* error */,
  2087. error: result,
  2088. statusCode: isRouteErrorResponse(result) ? result.status : void 0
  2089. };
  2090. }
  2091. if (isDataWithResponseInit(result)) {
  2092. return {
  2093. type: "data" /* data */,
  2094. data: result.data,
  2095. statusCode: result.init?.status,
  2096. headers: result.init?.headers ? new Headers(result.init.headers) : void 0
  2097. };
  2098. }
  2099. return { type: "data" /* data */, data: result };
  2100. }
  2101. function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
  2102. let location = response.headers.get("Location");
  2103. invariant(
  2104. location,
  2105. "Redirects returned/thrown from loaders/actions must have a Location header"
  2106. );
  2107. if (!isAbsoluteUrl(location)) {
  2108. let trimmedMatches = matches.slice(
  2109. 0,
  2110. matches.findIndex((m) => m.route.id === routeId) + 1
  2111. );
  2112. location = normalizeTo(
  2113. new URL(request.url),
  2114. trimmedMatches,
  2115. basename,
  2116. location
  2117. );
  2118. response.headers.set("Location", location);
  2119. }
  2120. return response;
  2121. }
  2122. function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
  2123. let loaderData = {};
  2124. let errors = null;
  2125. let statusCode;
  2126. let foundError = false;
  2127. let loaderHeaders = {};
  2128. let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
  2129. matches.forEach((match) => {
  2130. if (!(match.route.id in results)) {
  2131. return;
  2132. }
  2133. let id = match.route.id;
  2134. let result = results[id];
  2135. invariant(
  2136. !isRedirectResult(result),
  2137. "Cannot handle redirect results in processLoaderData"
  2138. );
  2139. if (isErrorResult(result)) {
  2140. let error = result.error;
  2141. if (pendingError !== void 0) {
  2142. error = pendingError;
  2143. pendingError = void 0;
  2144. }
  2145. errors = errors || {};
  2146. if (skipLoaderErrorBubbling) {
  2147. errors[id] = error;
  2148. } else {
  2149. let boundaryMatch = findNearestBoundary(matches, id);
  2150. if (errors[boundaryMatch.route.id] == null) {
  2151. errors[boundaryMatch.route.id] = error;
  2152. }
  2153. }
  2154. if (!isStaticHandler) {
  2155. loaderData[id] = ResetLoaderDataSymbol;
  2156. }
  2157. if (!foundError) {
  2158. foundError = true;
  2159. statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
  2160. }
  2161. if (result.headers) {
  2162. loaderHeaders[id] = result.headers;
  2163. }
  2164. } else {
  2165. loaderData[id] = result.data;
  2166. if (result.statusCode && result.statusCode !== 200 && !foundError) {
  2167. statusCode = result.statusCode;
  2168. }
  2169. if (result.headers) {
  2170. loaderHeaders[id] = result.headers;
  2171. }
  2172. }
  2173. });
  2174. if (pendingError !== void 0 && pendingActionResult) {
  2175. errors = { [pendingActionResult[0]]: pendingError };
  2176. if (pendingActionResult[2]) {
  2177. loaderData[pendingActionResult[2]] = void 0;
  2178. }
  2179. }
  2180. return {
  2181. loaderData,
  2182. errors,
  2183. statusCode: statusCode || 200,
  2184. loaderHeaders
  2185. };
  2186. }
  2187. function findNearestBoundary(matches, routeId) {
  2188. let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
  2189. return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
  2190. }
  2191. function getShortCircuitMatches(routes) {
  2192. let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
  2193. id: `__shim-error-route__`
  2194. };
  2195. return {
  2196. matches: [
  2197. {
  2198. params: {},
  2199. pathname: "",
  2200. pathnameBase: "",
  2201. route
  2202. }
  2203. ],
  2204. route
  2205. };
  2206. }
  2207. function getInternalRouterError(status, {
  2208. pathname,
  2209. routeId,
  2210. method,
  2211. type,
  2212. message
  2213. } = {}) {
  2214. let statusText = "Unknown Server Error";
  2215. let errorMessage = "Unknown @remix-run/router error";
  2216. if (status === 400) {
  2217. statusText = "Bad Request";
  2218. if (method && pathname && routeId) {
  2219. errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
  2220. } else if (type === "invalid-body") {
  2221. errorMessage = "Unable to encode submission body";
  2222. }
  2223. } else if (status === 403) {
  2224. statusText = "Forbidden";
  2225. errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
  2226. } else if (status === 404) {
  2227. statusText = "Not Found";
  2228. errorMessage = `No route matches URL "${pathname}"`;
  2229. } else if (status === 405) {
  2230. statusText = "Method Not Allowed";
  2231. if (method && pathname && routeId) {
  2232. errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
  2233. } else if (method) {
  2234. errorMessage = `Invalid request method "${method.toUpperCase()}"`;
  2235. }
  2236. }
  2237. return new ErrorResponseImpl(
  2238. status || 500,
  2239. statusText,
  2240. new Error(errorMessage),
  2241. true
  2242. );
  2243. }
  2244. function dataWithResponseInitToResponse(data2) {
  2245. return Response.json(data2.data, data2.init ?? void 0);
  2246. }
  2247. function dataWithResponseInitToErrorResponse(data2) {
  2248. return new ErrorResponseImpl(
  2249. data2.init?.status ?? 500,
  2250. data2.init?.statusText ?? "Internal Server Error",
  2251. data2.data
  2252. );
  2253. }
  2254. function isDataStrategyResult(result) {
  2255. return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
  2256. }
  2257. function isRedirectDataStrategyResult(result) {
  2258. return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
  2259. }
  2260. function isErrorResult(result) {
  2261. return result.type === "error" /* error */;
  2262. }
  2263. function isRedirectResult(result) {
  2264. return (result && result.type) === "redirect" /* redirect */;
  2265. }
  2266. function isDataWithResponseInit(value) {
  2267. return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
  2268. }
  2269. function isResponse(value) {
  2270. return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
  2271. }
  2272. function isRedirectStatusCode(statusCode) {
  2273. return redirectStatusCodes.has(statusCode);
  2274. }
  2275. function isRedirectResponse(result) {
  2276. return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
  2277. }
  2278. function isValidMethod(method) {
  2279. return validRequestMethods.has(method.toUpperCase());
  2280. }
  2281. function isMutationMethod(method) {
  2282. return validMutationMethods.has(method.toUpperCase());
  2283. }
  2284. function hasNakedIndexQuery(search) {
  2285. return new URLSearchParams(search).getAll("index").some((v) => v === "");
  2286. }
  2287. function getTargetMatch(matches, location) {
  2288. let search = typeof location === "string" ? parsePath(location).search : location.search;
  2289. if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
  2290. return matches[matches.length - 1];
  2291. }
  2292. let pathMatches = getPathContributingMatches(matches);
  2293. return pathMatches[pathMatches.length - 1];
  2294. }
  2295. // lib/server-runtime/invariant.ts
  2296. function invariant2(value, message) {
  2297. if (value === false || value === null || typeof value === "undefined") {
  2298. console.error(
  2299. "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
  2300. );
  2301. throw new Error(message);
  2302. }
  2303. }
  2304. // lib/server-runtime/headers.ts
  2305. function getDocumentHeadersImpl(context, getRouteHeadersFn, _defaultHeaders) {
  2306. let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
  2307. let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
  2308. let errorHeaders;
  2309. if (boundaryIdx >= 0) {
  2310. let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
  2311. context.matches.slice(boundaryIdx).some((match) => {
  2312. let id = match.route.id;
  2313. if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) {
  2314. errorHeaders = actionHeaders[id];
  2315. } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {
  2316. errorHeaders = loaderHeaders[id];
  2317. }
  2318. return errorHeaders != null;
  2319. });
  2320. }
  2321. const defaultHeaders = new Headers(_defaultHeaders);
  2322. return matches.reduce((parentHeaders, match, idx) => {
  2323. let { id } = match.route;
  2324. let loaderHeaders = context.loaderHeaders[id] || new Headers();
  2325. let actionHeaders = context.actionHeaders[id] || new Headers();
  2326. let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
  2327. let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
  2328. let headersFn = getRouteHeadersFn(match);
  2329. if (headersFn == null) {
  2330. let headers2 = new Headers(parentHeaders);
  2331. if (includeErrorCookies) {
  2332. prependCookies(errorHeaders, headers2);
  2333. }
  2334. prependCookies(actionHeaders, headers2);
  2335. prependCookies(loaderHeaders, headers2);
  2336. return headers2;
  2337. }
  2338. let headers = new Headers(
  2339. typeof headersFn === "function" ? headersFn({
  2340. loaderHeaders,
  2341. parentHeaders,
  2342. actionHeaders,
  2343. errorHeaders: includeErrorHeaders ? errorHeaders : void 0
  2344. }) : headersFn
  2345. );
  2346. if (includeErrorCookies) {
  2347. prependCookies(errorHeaders, headers);
  2348. }
  2349. prependCookies(actionHeaders, headers);
  2350. prependCookies(loaderHeaders, headers);
  2351. prependCookies(parentHeaders, headers);
  2352. return headers;
  2353. }, new Headers(defaultHeaders));
  2354. }
  2355. function prependCookies(parentHeaders, childHeaders) {
  2356. let parentSetCookieString = parentHeaders.get("Set-Cookie");
  2357. if (parentSetCookieString) {
  2358. let cookies = splitCookiesString(parentSetCookieString);
  2359. let childCookies = new Set(childHeaders.getSetCookie());
  2360. cookies.forEach((cookie) => {
  2361. if (!childCookies.has(cookie)) {
  2362. childHeaders.append("Set-Cookie", cookie);
  2363. }
  2364. });
  2365. }
  2366. }
  2367. var SINGLE_FETCH_REDIRECT_STATUS = 202;
  2368. var Outlet = Outlet$1;
  2369. var WithComponentProps = UNSAFE_WithComponentProps;
  2370. var WithErrorBoundaryProps = UNSAFE_WithErrorBoundaryProps;
  2371. var WithHydrateFallbackProps = UNSAFE_WithHydrateFallbackProps;
  2372. var globalVar = typeof globalThis !== "undefined" ? globalThis : global;
  2373. var ServerStorage = globalVar.___reactRouterServerStorage___ ?? (globalVar.___reactRouterServerStorage___ = new AsyncLocalStorage());
  2374. var redirect2 = (...args) => {
  2375. const response = redirect(...args);
  2376. const ctx = ServerStorage.getStore();
  2377. if (ctx && ctx.runningAction) {
  2378. ctx.redirect = response;
  2379. }
  2380. return response;
  2381. };
  2382. var redirectDocument2 = (...args) => {
  2383. const response = redirectDocument(...args);
  2384. const ctx = ServerStorage.getStore();
  2385. if (ctx && ctx.runningAction) {
  2386. ctx.redirect = response;
  2387. }
  2388. return response;
  2389. };
  2390. var replace2 = (...args) => {
  2391. const response = replace(...args);
  2392. const ctx = ServerStorage.getStore();
  2393. if (ctx && ctx.runningAction) {
  2394. ctx.redirect = response;
  2395. }
  2396. return response;
  2397. };
  2398. var cachedResolvePromise = (
  2399. // @ts-expect-error - on 18 types, requires 19.
  2400. React2.cache(async (resolve) => {
  2401. return Promise.allSettled([resolve]).then((r) => r[0]);
  2402. })
  2403. );
  2404. var Await = async ({
  2405. children,
  2406. resolve,
  2407. errorElement
  2408. }) => {
  2409. let promise = cachedResolvePromise(resolve);
  2410. let resolved = await promise;
  2411. if (resolved.status === "rejected" && !errorElement) {
  2412. throw resolved.reason;
  2413. }
  2414. if (resolved.status === "rejected") {
  2415. return React2.createElement(UNSAFE_AwaitContextProvider, {
  2416. children: React2.createElement(React2.Fragment, null, errorElement),
  2417. value: { _tracked: true, _error: resolved.reason }
  2418. });
  2419. }
  2420. const toRender = typeof children === "function" ? children(resolved.value) : children;
  2421. return React2.createElement(UNSAFE_AwaitContextProvider, {
  2422. children: toRender,
  2423. value: { _tracked: true, _data: resolved.value }
  2424. });
  2425. };
  2426. async function matchRSCServerRequest({
  2427. createTemporaryReferenceSet,
  2428. basename,
  2429. decodeReply,
  2430. requestContext,
  2431. loadServerAction,
  2432. decodeAction,
  2433. decodeFormState,
  2434. onError,
  2435. request,
  2436. routes,
  2437. generateResponse
  2438. }) {
  2439. let requestUrl = new URL(request.url);
  2440. const temporaryReferences = createTemporaryReferenceSet();
  2441. if (isManifestRequest(requestUrl)) {
  2442. let response2 = await generateManifestResponse(
  2443. routes,
  2444. basename,
  2445. request,
  2446. generateResponse,
  2447. temporaryReferences
  2448. );
  2449. return response2;
  2450. }
  2451. let isDataRequest = isReactServerRequest(requestUrl);
  2452. const url = new URL(request.url);
  2453. let routerRequest = request;
  2454. if (isDataRequest) {
  2455. url.pathname = url.pathname.replace(/(_root)?\.rsc$/, "");
  2456. routerRequest = new Request(url.toString(), {
  2457. method: request.method,
  2458. headers: request.headers,
  2459. body: request.body,
  2460. signal: request.signal,
  2461. duplex: request.body ? "half" : void 0
  2462. });
  2463. }
  2464. let matches = matchRoutes(routes, url.pathname, basename);
  2465. if (matches) {
  2466. await Promise.all(matches.map((m) => explodeLazyRoute(m.route)));
  2467. }
  2468. const leafMatch = matches?.[matches.length - 1];
  2469. if (!isDataRequest && leafMatch && !leafMatch.route.Component && !leafMatch.route.ErrorBoundary) {
  2470. return generateResourceResponse(
  2471. routerRequest,
  2472. routes,
  2473. basename,
  2474. leafMatch.route.id,
  2475. requestContext,
  2476. onError
  2477. );
  2478. }
  2479. let response = await generateRenderResponse(
  2480. routerRequest,
  2481. routes,
  2482. basename,
  2483. isDataRequest,
  2484. decodeReply,
  2485. requestContext,
  2486. loadServerAction,
  2487. decodeAction,
  2488. decodeFormState,
  2489. onError,
  2490. generateResponse,
  2491. temporaryReferences
  2492. );
  2493. response.headers.set("X-Remix-Response", "yes");
  2494. return response;
  2495. }
  2496. async function generateManifestResponse(routes, basename, request, generateResponse, temporaryReferences) {
  2497. let url = new URL(request.url);
  2498. let pathParam = url.searchParams.get("paths");
  2499. let pathnames = pathParam ? pathParam.split(",").filter(Boolean) : [url.pathname.replace(/\.manifest$/, "")];
  2500. let routeIds = /* @__PURE__ */ new Set();
  2501. let matchedRoutes = pathnames.flatMap((pathname) => {
  2502. let pathnameMatches = matchRoutes(routes, pathname, basename);
  2503. return pathnameMatches?.map((m, i) => ({
  2504. ...m.route,
  2505. parentId: pathnameMatches[i - 1]?.route.id
  2506. })) ?? [];
  2507. }).filter((route) => {
  2508. if (!routeIds.has(route.id)) {
  2509. routeIds.add(route.id);
  2510. return true;
  2511. }
  2512. return false;
  2513. });
  2514. let payload = {
  2515. type: "manifest",
  2516. patches: (await Promise.all([
  2517. ...matchedRoutes.map((route) => getManifestRoute(route)),
  2518. getAdditionalRoutePatches(
  2519. pathnames,
  2520. routes,
  2521. basename,
  2522. Array.from(routeIds)
  2523. )
  2524. ])).flat(1)
  2525. };
  2526. return generateResponse(
  2527. {
  2528. statusCode: 200,
  2529. headers: new Headers({
  2530. "Content-Type": "text/x-component",
  2531. Vary: "Content-Type"
  2532. }),
  2533. payload
  2534. },
  2535. { temporaryReferences }
  2536. );
  2537. }
  2538. function prependBasenameToRedirectResponse(response, basename = "/") {
  2539. if (basename === "/") {
  2540. return response;
  2541. }
  2542. let redirect3 = response.headers.get("Location");
  2543. if (!redirect3 || isAbsoluteUrl(redirect3)) {
  2544. return response;
  2545. }
  2546. response.headers.set(
  2547. "Location",
  2548. prependBasename({ basename, pathname: redirect3 })
  2549. );
  2550. return response;
  2551. }
  2552. async function processServerAction(request, basename, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences) {
  2553. const getRevalidationRequest = () => new Request(request.url, {
  2554. method: "GET",
  2555. headers: request.headers,
  2556. signal: request.signal
  2557. });
  2558. const isFormRequest = canDecodeWithFormData(
  2559. request.headers.get("Content-Type")
  2560. );
  2561. const actionId = request.headers.get("rsc-action-id");
  2562. if (actionId) {
  2563. if (!decodeReply || !loadServerAction) {
  2564. throw new Error(
  2565. "Cannot handle enhanced server action without decodeReply and loadServerAction functions"
  2566. );
  2567. }
  2568. const reply = isFormRequest ? await request.formData() : await request.text();
  2569. const actionArgs = await decodeReply(reply, { temporaryReferences });
  2570. const action = await loadServerAction(actionId);
  2571. const serverAction = action.bind(null, ...actionArgs);
  2572. let actionResult = Promise.resolve(serverAction());
  2573. try {
  2574. await actionResult;
  2575. } catch (error) {
  2576. if (isResponse(error)) {
  2577. return error;
  2578. }
  2579. onError?.(error);
  2580. }
  2581. let maybeFormData = actionArgs.length === 1 ? actionArgs[0] : actionArgs[1];
  2582. let formData = maybeFormData && typeof maybeFormData === "object" && maybeFormData instanceof FormData ? maybeFormData : null;
  2583. let skipRevalidation = formData?.has("$SKIP_REVALIDATION") ?? false;
  2584. return {
  2585. actionResult,
  2586. revalidationRequest: getRevalidationRequest(),
  2587. skipRevalidation
  2588. };
  2589. } else if (isFormRequest) {
  2590. const formData = await request.clone().formData();
  2591. if (Array.from(formData.keys()).some((k) => k.startsWith("$ACTION_"))) {
  2592. if (!decodeAction) {
  2593. throw new Error(
  2594. "Cannot handle form actions without a decodeAction function"
  2595. );
  2596. }
  2597. const action = await decodeAction(formData);
  2598. let formState = void 0;
  2599. try {
  2600. let result = await action();
  2601. if (isRedirectResponse(result)) {
  2602. result = prependBasenameToRedirectResponse(result, basename);
  2603. }
  2604. formState = decodeFormState?.(result, formData);
  2605. } catch (error) {
  2606. if (isRedirectResponse(error)) {
  2607. return prependBasenameToRedirectResponse(error, basename);
  2608. }
  2609. if (isResponse(error)) {
  2610. return error;
  2611. }
  2612. onError?.(error);
  2613. }
  2614. return {
  2615. formState,
  2616. revalidationRequest: getRevalidationRequest(),
  2617. skipRevalidation: false
  2618. };
  2619. }
  2620. }
  2621. }
  2622. async function generateResourceResponse(request, routes, basename, routeId, requestContext, onError) {
  2623. try {
  2624. const staticHandler = createStaticHandler(routes, {
  2625. basename
  2626. });
  2627. let response = await staticHandler.queryRoute(request, {
  2628. routeId,
  2629. requestContext,
  2630. async generateMiddlewareResponse(queryRoute) {
  2631. try {
  2632. let response2 = await queryRoute(request);
  2633. return generateResourceResponse2(response2);
  2634. } catch (error) {
  2635. return generateErrorResponse(error);
  2636. }
  2637. }
  2638. });
  2639. return response;
  2640. } catch (error) {
  2641. return generateErrorResponse(error);
  2642. }
  2643. function generateErrorResponse(error) {
  2644. let response;
  2645. if (isResponse(error)) {
  2646. response = error;
  2647. } else if (isRouteErrorResponse(error)) {
  2648. onError?.(error);
  2649. const errorMessage = typeof error.data === "string" ? error.data : error.statusText;
  2650. response = new Response(errorMessage, {
  2651. status: error.status,
  2652. statusText: error.statusText
  2653. });
  2654. } else {
  2655. onError?.(error);
  2656. response = new Response("Internal Server Error", { status: 500 });
  2657. }
  2658. return generateResourceResponse2(response);
  2659. }
  2660. function generateResourceResponse2(response) {
  2661. const headers = new Headers(response.headers);
  2662. headers.set("React-Router-Resource", "true");
  2663. return new Response(response.body, {
  2664. status: response.status,
  2665. statusText: response.statusText,
  2666. headers
  2667. });
  2668. }
  2669. }
  2670. async function generateRenderResponse(request, routes, basename, isDataRequest, decodeReply, requestContext, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences) {
  2671. let statusCode = 200;
  2672. let url = new URL(request.url);
  2673. let isSubmission = isMutationMethod(request.method);
  2674. let routeIdsToLoad = !isSubmission && url.searchParams.has("_routes") ? url.searchParams.get("_routes").split(",") : null;
  2675. const staticHandler = createStaticHandler(routes, {
  2676. basename,
  2677. mapRouteProperties: (r) => ({
  2678. hasErrorBoundary: r.ErrorBoundary != null
  2679. })
  2680. });
  2681. let actionResult;
  2682. const ctx = {
  2683. runningAction: false
  2684. };
  2685. const result = await ServerStorage.run(
  2686. ctx,
  2687. () => staticHandler.query(request, {
  2688. requestContext,
  2689. skipLoaderErrorBubbling: isDataRequest,
  2690. skipRevalidation: isSubmission,
  2691. ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : {},
  2692. async generateMiddlewareResponse(query) {
  2693. let formState;
  2694. let skipRevalidation = false;
  2695. if (request.method === "POST") {
  2696. ctx.runningAction = true;
  2697. let result2 = await processServerAction(
  2698. request,
  2699. basename,
  2700. decodeReply,
  2701. loadServerAction,
  2702. decodeAction,
  2703. decodeFormState,
  2704. onError,
  2705. temporaryReferences
  2706. );
  2707. ctx.runningAction = false;
  2708. if (isResponse(result2)) {
  2709. return generateRedirectResponse(
  2710. result2,
  2711. actionResult,
  2712. basename,
  2713. isDataRequest,
  2714. generateResponse,
  2715. temporaryReferences,
  2716. ctx.redirect?.headers
  2717. );
  2718. }
  2719. skipRevalidation = result2?.skipRevalidation ?? false;
  2720. actionResult = result2?.actionResult;
  2721. formState = result2?.formState;
  2722. request = result2?.revalidationRequest ?? request;
  2723. if (ctx.redirect) {
  2724. return generateRedirectResponse(
  2725. ctx.redirect,
  2726. actionResult,
  2727. basename,
  2728. isDataRequest,
  2729. generateResponse,
  2730. temporaryReferences,
  2731. void 0
  2732. );
  2733. }
  2734. }
  2735. let staticContext = await query(
  2736. request,
  2737. skipRevalidation ? {
  2738. filterMatchesToLoad: () => false
  2739. } : void 0
  2740. );
  2741. if (isResponse(staticContext)) {
  2742. return generateRedirectResponse(
  2743. staticContext,
  2744. actionResult,
  2745. basename,
  2746. isDataRequest,
  2747. generateResponse,
  2748. temporaryReferences,
  2749. ctx.redirect?.headers
  2750. );
  2751. }
  2752. return generateStaticContextResponse(
  2753. routes,
  2754. basename,
  2755. generateResponse,
  2756. statusCode,
  2757. routeIdsToLoad,
  2758. isDataRequest,
  2759. isSubmission,
  2760. actionResult,
  2761. formState,
  2762. staticContext,
  2763. temporaryReferences,
  2764. skipRevalidation,
  2765. ctx.redirect?.headers
  2766. );
  2767. }
  2768. })
  2769. );
  2770. if (isRedirectResponse(result)) {
  2771. return generateRedirectResponse(
  2772. result,
  2773. actionResult,
  2774. basename,
  2775. isDataRequest,
  2776. generateResponse,
  2777. temporaryReferences,
  2778. ctx.redirect?.headers
  2779. );
  2780. }
  2781. invariant2(isResponse(result), "Expected a response from query");
  2782. return result;
  2783. }
  2784. function generateRedirectResponse(response, actionResult, basename, isDataRequest, generateResponse, temporaryReferences, sideEffectRedirectHeaders) {
  2785. let redirect3 = response.headers.get("Location");
  2786. if (isDataRequest && basename) {
  2787. redirect3 = stripBasename(redirect3, basename) || redirect3;
  2788. }
  2789. let payload = {
  2790. type: "redirect",
  2791. location: redirect3,
  2792. reload: response.headers.get("X-Remix-Reload-Document") === "true",
  2793. replace: response.headers.get("X-Remix-Replace") === "true",
  2794. status: response.status,
  2795. actionResult
  2796. };
  2797. let headers = new Headers(sideEffectRedirectHeaders);
  2798. for (const [key, value] of response.headers.entries()) {
  2799. headers.append(key, value);
  2800. }
  2801. headers.delete("Location");
  2802. headers.delete("X-Remix-Reload-Document");
  2803. headers.delete("X-Remix-Replace");
  2804. headers.delete("Content-Length");
  2805. headers.set("Content-Type", "text/x-component");
  2806. headers.set("Vary", "Content-Type");
  2807. return generateResponse(
  2808. {
  2809. statusCode: SINGLE_FETCH_REDIRECT_STATUS,
  2810. headers,
  2811. payload
  2812. },
  2813. { temporaryReferences }
  2814. );
  2815. }
  2816. async function generateStaticContextResponse(routes, basename, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences, skipRevalidation, sideEffectRedirectHeaders) {
  2817. statusCode = staticContext.statusCode ?? statusCode;
  2818. if (staticContext.errors) {
  2819. staticContext.errors = Object.fromEntries(
  2820. Object.entries(staticContext.errors).map(([key, error]) => [
  2821. key,
  2822. isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error
  2823. ])
  2824. );
  2825. }
  2826. staticContext.matches.forEach((m) => {
  2827. const routeHasNoLoaderData = staticContext.loaderData[m.route.id] === void 0;
  2828. const routeHasError = Boolean(
  2829. staticContext.errors && m.route.id in staticContext.errors
  2830. );
  2831. if (routeHasNoLoaderData && !routeHasError) {
  2832. staticContext.loaderData[m.route.id] = null;
  2833. }
  2834. });
  2835. let headers = getDocumentHeadersImpl(
  2836. staticContext,
  2837. (match) => match.route.headers,
  2838. sideEffectRedirectHeaders
  2839. );
  2840. headers.delete("Content-Length");
  2841. const baseRenderPayload = {
  2842. type: "render",
  2843. basename,
  2844. actionData: staticContext.actionData,
  2845. errors: staticContext.errors,
  2846. loaderData: staticContext.loaderData,
  2847. location: staticContext.location,
  2848. formState
  2849. };
  2850. const renderPayloadPromise = () => getRenderPayload(
  2851. baseRenderPayload,
  2852. routes,
  2853. basename,
  2854. routeIdsToLoad,
  2855. isDataRequest,
  2856. staticContext
  2857. );
  2858. let payload;
  2859. if (actionResult) {
  2860. payload = {
  2861. type: "action",
  2862. actionResult,
  2863. rerender: skipRevalidation ? void 0 : renderPayloadPromise()
  2864. };
  2865. } else if (isSubmission && isDataRequest) {
  2866. payload = {
  2867. ...baseRenderPayload,
  2868. matches: [],
  2869. patches: []
  2870. };
  2871. } else {
  2872. payload = await renderPayloadPromise();
  2873. }
  2874. return generateResponse(
  2875. {
  2876. statusCode,
  2877. headers,
  2878. payload
  2879. },
  2880. { temporaryReferences }
  2881. );
  2882. }
  2883. async function getRenderPayload(baseRenderPayload, routes, basename, routeIdsToLoad, isDataRequest, staticContext) {
  2884. let deepestRenderedRouteIdx = staticContext.matches.length - 1;
  2885. let parentIds = {};
  2886. staticContext.matches.forEach((m, i) => {
  2887. if (i > 0) {
  2888. parentIds[m.route.id] = staticContext.matches[i - 1].route.id;
  2889. }
  2890. if (staticContext.errors && m.route.id in staticContext.errors && deepestRenderedRouteIdx > i) {
  2891. deepestRenderedRouteIdx = i;
  2892. }
  2893. });
  2894. let matchesPromise = Promise.all(
  2895. staticContext.matches.map((match, i) => {
  2896. let isBelowErrorBoundary = i > deepestRenderedRouteIdx;
  2897. let parentId = parentIds[match.route.id];
  2898. return getRSCRouteMatch({
  2899. staticContext,
  2900. match,
  2901. routeIdsToLoad,
  2902. isBelowErrorBoundary,
  2903. parentId
  2904. });
  2905. })
  2906. );
  2907. let patchesPromise = getAdditionalRoutePatches(
  2908. [staticContext.location.pathname],
  2909. routes,
  2910. basename,
  2911. staticContext.matches.map((m) => m.route.id)
  2912. );
  2913. let [matches, patches] = await Promise.all([matchesPromise, patchesPromise]);
  2914. return {
  2915. ...baseRenderPayload,
  2916. matches,
  2917. patches
  2918. };
  2919. }
  2920. async function getRSCRouteMatch({
  2921. staticContext,
  2922. match,
  2923. isBelowErrorBoundary,
  2924. routeIdsToLoad,
  2925. parentId
  2926. }) {
  2927. await explodeLazyRoute(match.route);
  2928. const Layout = match.route.Layout || React2.Fragment;
  2929. const Component = match.route.Component;
  2930. const ErrorBoundary = match.route.ErrorBoundary;
  2931. const HydrateFallback = match.route.HydrateFallback;
  2932. const loaderData = staticContext.loaderData[match.route.id];
  2933. const actionData = staticContext.actionData?.[match.route.id];
  2934. const params = match.params;
  2935. let element = void 0;
  2936. let shouldLoadRoute = !routeIdsToLoad || routeIdsToLoad.includes(match.route.id);
  2937. if (Component && shouldLoadRoute) {
  2938. element = !isBelowErrorBoundary ? React2.createElement(
  2939. Layout,
  2940. null,
  2941. isClientReference(Component) ? React2.createElement(WithComponentProps, {
  2942. children: React2.createElement(Component)
  2943. }) : React2.createElement(Component, {
  2944. loaderData,
  2945. actionData,
  2946. params,
  2947. matches: staticContext.matches.map(
  2948. (match2) => convertRouteMatchToUiMatch(match2, staticContext.loaderData)
  2949. )
  2950. })
  2951. ) : React2.createElement(Outlet);
  2952. }
  2953. let error = void 0;
  2954. if (ErrorBoundary && staticContext.errors) {
  2955. error = staticContext.errors[match.route.id];
  2956. }
  2957. const errorElement = ErrorBoundary ? React2.createElement(
  2958. Layout,
  2959. null,
  2960. isClientReference(ErrorBoundary) ? React2.createElement(WithErrorBoundaryProps, {
  2961. children: React2.createElement(ErrorBoundary)
  2962. }) : React2.createElement(ErrorBoundary, {
  2963. loaderData,
  2964. actionData,
  2965. params,
  2966. error
  2967. })
  2968. ) : void 0;
  2969. const hydrateFallbackElement = HydrateFallback ? React2.createElement(
  2970. Layout,
  2971. null,
  2972. isClientReference(HydrateFallback) ? React2.createElement(WithHydrateFallbackProps, {
  2973. children: React2.createElement(HydrateFallback)
  2974. }) : React2.createElement(HydrateFallback, {
  2975. loaderData,
  2976. actionData,
  2977. params
  2978. })
  2979. ) : void 0;
  2980. return {
  2981. clientAction: match.route.clientAction,
  2982. clientLoader: match.route.clientLoader,
  2983. element,
  2984. errorElement,
  2985. handle: match.route.handle,
  2986. hasAction: !!match.route.action,
  2987. hasComponent: !!Component,
  2988. hasErrorBoundary: !!ErrorBoundary,
  2989. hasLoader: !!match.route.loader,
  2990. hydrateFallbackElement,
  2991. id: match.route.id,
  2992. index: match.route.index,
  2993. links: match.route.links,
  2994. meta: match.route.meta,
  2995. params,
  2996. parentId,
  2997. path: match.route.path,
  2998. pathname: match.pathname,
  2999. pathnameBase: match.pathnameBase,
  3000. shouldRevalidate: match.route.shouldRevalidate,
  3001. // Add an unused client-only export (if present) so HMR can support
  3002. // switching between server-first and client-only routes during development
  3003. ...match.route.__ensureClientRouteModuleForHMR ? {
  3004. __ensureClientRouteModuleForHMR: match.route.__ensureClientRouteModuleForHMR
  3005. } : {}
  3006. };
  3007. }
  3008. async function getManifestRoute(route) {
  3009. await explodeLazyRoute(route);
  3010. const Layout = route.Layout || React2.Fragment;
  3011. const errorElement = route.ErrorBoundary ? React2.createElement(
  3012. Layout,
  3013. null,
  3014. React2.createElement(route.ErrorBoundary)
  3015. ) : void 0;
  3016. return {
  3017. clientAction: route.clientAction,
  3018. clientLoader: route.clientLoader,
  3019. handle: route.handle,
  3020. hasAction: !!route.action,
  3021. hasComponent: !!route.Component,
  3022. hasErrorBoundary: !!route.ErrorBoundary,
  3023. errorElement,
  3024. hasLoader: !!route.loader,
  3025. id: route.id,
  3026. parentId: route.parentId,
  3027. path: route.path,
  3028. index: "index" in route ? route.index : void 0,
  3029. links: route.links,
  3030. meta: route.meta
  3031. };
  3032. }
  3033. async function explodeLazyRoute(route) {
  3034. if ("lazy" in route && route.lazy) {
  3035. let {
  3036. default: lazyDefaultExport,
  3037. Component: lazyComponentExport,
  3038. ...lazyProperties
  3039. } = await route.lazy();
  3040. let Component = lazyComponentExport || lazyDefaultExport;
  3041. if (Component && !route.Component) {
  3042. route.Component = Component;
  3043. }
  3044. for (let [k, v] of Object.entries(lazyProperties)) {
  3045. if (k !== "id" && k !== "path" && k !== "index" && k !== "children" && route[k] == null) {
  3046. route[k] = v;
  3047. }
  3048. }
  3049. route.lazy = void 0;
  3050. }
  3051. }
  3052. async function getAdditionalRoutePatches(pathnames, routes, basename, matchedRouteIds) {
  3053. let patchRouteMatches = /* @__PURE__ */ new Map();
  3054. let matchedPaths = /* @__PURE__ */ new Set();
  3055. for (const pathname of pathnames) {
  3056. let segments = pathname.split("/").filter(Boolean);
  3057. let paths = ["/"];
  3058. segments.pop();
  3059. while (segments.length > 0) {
  3060. paths.push(`/${segments.join("/")}`);
  3061. segments.pop();
  3062. }
  3063. paths.forEach((path) => {
  3064. if (matchedPaths.has(path)) {
  3065. return;
  3066. }
  3067. matchedPaths.add(path);
  3068. let matches = matchRoutes(routes, path, basename) || [];
  3069. matches.forEach((m, i) => {
  3070. if (patchRouteMatches.get(m.route.id)) {
  3071. return;
  3072. }
  3073. patchRouteMatches.set(m.route.id, {
  3074. ...m.route,
  3075. parentId: matches[i - 1]?.route.id
  3076. });
  3077. });
  3078. });
  3079. }
  3080. let patches = await Promise.all(
  3081. [...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getManifestRoute(route))
  3082. );
  3083. return patches;
  3084. }
  3085. function isReactServerRequest(url) {
  3086. return url.pathname.endsWith(".rsc");
  3087. }
  3088. function isManifestRequest(url) {
  3089. return url.pathname.endsWith(".manifest");
  3090. }
  3091. function isClientReference(x) {
  3092. try {
  3093. return x.$$typeof === Symbol.for("react.client.reference");
  3094. } catch {
  3095. return false;
  3096. }
  3097. }
  3098. function canDecodeWithFormData(contentType) {
  3099. if (!contentType) return false;
  3100. return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
  3101. }
  3102. // lib/href.ts
  3103. function href(path, ...args) {
  3104. let params = args[0];
  3105. let result = trimTrailingSplat(path).replace(
  3106. /\/:([\w-]+)(\?)?/g,
  3107. // same regex as in .\router\utils.ts: compilePath().
  3108. (_, param, questionMark) => {
  3109. const isRequired = questionMark === void 0;
  3110. const value = params?.[param];
  3111. if (isRequired && value === void 0) {
  3112. throw new Error(
  3113. `Path '${path}' requires param '${param}' but it was not provided`
  3114. );
  3115. }
  3116. return value === void 0 ? "" : "/" + value;
  3117. }
  3118. );
  3119. if (path.endsWith("*")) {
  3120. const value = params?.["*"];
  3121. if (value !== void 0) {
  3122. result += "/" + value;
  3123. }
  3124. }
  3125. return result || "/";
  3126. }
  3127. function trimTrailingSplat(path) {
  3128. let i = path.length - 1;
  3129. let char = path[i];
  3130. if (char !== "*" && char !== "/") return path;
  3131. i--;
  3132. for (; i >= 0; i--) {
  3133. if (path[i] !== "/") break;
  3134. }
  3135. return path.slice(0, i + 1);
  3136. }
  3137. // lib/server-runtime/crypto.ts
  3138. var encoder = /* @__PURE__ */ new TextEncoder();
  3139. var sign = async (value, secret) => {
  3140. let data2 = encoder.encode(value);
  3141. let key = await createKey2(secret, ["sign"]);
  3142. let signature = await crypto.subtle.sign("HMAC", key, data2);
  3143. let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(
  3144. /=+$/,
  3145. ""
  3146. );
  3147. return value + "." + hash;
  3148. };
  3149. var unsign = async (cookie, secret) => {
  3150. let index = cookie.lastIndexOf(".");
  3151. let value = cookie.slice(0, index);
  3152. let hash = cookie.slice(index + 1);
  3153. let data2 = encoder.encode(value);
  3154. let key = await createKey2(secret, ["verify"]);
  3155. try {
  3156. let signature = byteStringToUint8Array(atob(hash));
  3157. let valid = await crypto.subtle.verify("HMAC", key, signature, data2);
  3158. return valid ? value : false;
  3159. } catch (error) {
  3160. return false;
  3161. }
  3162. };
  3163. var createKey2 = async (secret, usages) => crypto.subtle.importKey(
  3164. "raw",
  3165. encoder.encode(secret),
  3166. { name: "HMAC", hash: "SHA-256" },
  3167. false,
  3168. usages
  3169. );
  3170. function byteStringToUint8Array(byteString) {
  3171. let array = new Uint8Array(byteString.length);
  3172. for (let i = 0; i < byteString.length; i++) {
  3173. array[i] = byteString.charCodeAt(i);
  3174. }
  3175. return array;
  3176. }
  3177. // lib/server-runtime/warnings.ts
  3178. var alreadyWarned = {};
  3179. function warnOnce(condition, message) {
  3180. if (!condition && !alreadyWarned[message]) {
  3181. alreadyWarned[message] = true;
  3182. console.warn(message);
  3183. }
  3184. }
  3185. // lib/server-runtime/cookies.ts
  3186. var createCookie = (name, cookieOptions = {}) => {
  3187. let { secrets = [], ...options } = {
  3188. path: "/",
  3189. sameSite: "lax",
  3190. ...cookieOptions
  3191. };
  3192. warnOnceAboutExpiresCookie(name, options.expires);
  3193. return {
  3194. get name() {
  3195. return name;
  3196. },
  3197. get isSigned() {
  3198. return secrets.length > 0;
  3199. },
  3200. get expires() {
  3201. return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
  3202. },
  3203. async parse(cookieHeader, parseOptions) {
  3204. if (!cookieHeader) return null;
  3205. let cookies = parse(cookieHeader, { ...options, ...parseOptions });
  3206. if (name in cookies) {
  3207. let value = cookies[name];
  3208. if (typeof value === "string" && value !== "") {
  3209. let decoded = await decodeCookieValue(value, secrets);
  3210. return decoded;
  3211. } else {
  3212. return "";
  3213. }
  3214. } else {
  3215. return null;
  3216. }
  3217. },
  3218. async serialize(value, serializeOptions) {
  3219. return serialize(
  3220. name,
  3221. value === "" ? "" : await encodeCookieValue(value, secrets),
  3222. {
  3223. ...options,
  3224. ...serializeOptions
  3225. }
  3226. );
  3227. }
  3228. };
  3229. };
  3230. var isCookie = (object) => {
  3231. return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
  3232. };
  3233. async function encodeCookieValue(value, secrets) {
  3234. let encoded = encodeData(value);
  3235. if (secrets.length > 0) {
  3236. encoded = await sign(encoded, secrets[0]);
  3237. }
  3238. return encoded;
  3239. }
  3240. async function decodeCookieValue(value, secrets) {
  3241. if (secrets.length > 0) {
  3242. for (let secret of secrets) {
  3243. let unsignedValue = await unsign(value, secret);
  3244. if (unsignedValue !== false) {
  3245. return decodeData(unsignedValue);
  3246. }
  3247. }
  3248. return null;
  3249. }
  3250. return decodeData(value);
  3251. }
  3252. function encodeData(value) {
  3253. return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
  3254. }
  3255. function decodeData(value) {
  3256. try {
  3257. return JSON.parse(decodeURIComponent(myEscape(atob(value))));
  3258. } catch (error) {
  3259. return {};
  3260. }
  3261. }
  3262. function myEscape(value) {
  3263. let str = value.toString();
  3264. let result = "";
  3265. let index = 0;
  3266. let chr, code;
  3267. while (index < str.length) {
  3268. chr = str.charAt(index++);
  3269. if (/[\w*+\-./@]/.exec(chr)) {
  3270. result += chr;
  3271. } else {
  3272. code = chr.charCodeAt(0);
  3273. if (code < 256) {
  3274. result += "%" + hex(code, 2);
  3275. } else {
  3276. result += "%u" + hex(code, 4).toUpperCase();
  3277. }
  3278. }
  3279. }
  3280. return result;
  3281. }
  3282. function hex(code, length) {
  3283. let result = code.toString(16);
  3284. while (result.length < length) result = "0" + result;
  3285. return result;
  3286. }
  3287. function myUnescape(value) {
  3288. let str = value.toString();
  3289. let result = "";
  3290. let index = 0;
  3291. let chr, part;
  3292. while (index < str.length) {
  3293. chr = str.charAt(index++);
  3294. if (chr === "%") {
  3295. if (str.charAt(index) === "u") {
  3296. part = str.slice(index + 1, index + 5);
  3297. if (/^[\da-f]{4}$/i.exec(part)) {
  3298. result += String.fromCharCode(parseInt(part, 16));
  3299. index += 5;
  3300. continue;
  3301. }
  3302. } else {
  3303. part = str.slice(index, index + 2);
  3304. if (/^[\da-f]{2}$/i.exec(part)) {
  3305. result += String.fromCharCode(parseInt(part, 16));
  3306. index += 2;
  3307. continue;
  3308. }
  3309. }
  3310. }
  3311. result += chr;
  3312. }
  3313. return result;
  3314. }
  3315. function warnOnceAboutExpiresCookie(name, expires) {
  3316. warnOnce(
  3317. !expires,
  3318. `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`
  3319. );
  3320. }
  3321. // lib/server-runtime/sessions.ts
  3322. function flash(name) {
  3323. return `__flash_${name}__`;
  3324. }
  3325. var createSession = (initialData = {}, id = "") => {
  3326. let map = new Map(Object.entries(initialData));
  3327. return {
  3328. get id() {
  3329. return id;
  3330. },
  3331. get data() {
  3332. return Object.fromEntries(map);
  3333. },
  3334. has(name) {
  3335. return map.has(name) || map.has(flash(name));
  3336. },
  3337. get(name) {
  3338. if (map.has(name)) return map.get(name);
  3339. let flashName = flash(name);
  3340. if (map.has(flashName)) {
  3341. let value = map.get(flashName);
  3342. map.delete(flashName);
  3343. return value;
  3344. }
  3345. return void 0;
  3346. },
  3347. set(name, value) {
  3348. map.set(name, value);
  3349. },
  3350. flash(name, value) {
  3351. map.set(flash(name), value);
  3352. },
  3353. unset(name) {
  3354. map.delete(name);
  3355. }
  3356. };
  3357. };
  3358. var isSession = (object) => {
  3359. return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function";
  3360. };
  3361. function createSessionStorage({
  3362. cookie: cookieArg,
  3363. createData,
  3364. readData,
  3365. updateData,
  3366. deleteData
  3367. }) {
  3368. let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
  3369. warnOnceAboutSigningSessionCookie(cookie);
  3370. return {
  3371. async getSession(cookieHeader, options) {
  3372. let id = cookieHeader && await cookie.parse(cookieHeader, options);
  3373. let data2 = id && await readData(id);
  3374. return createSession(data2 || {}, id || "");
  3375. },
  3376. async commitSession(session, options) {
  3377. let { id, data: data2 } = session;
  3378. let expires = options?.maxAge != null ? new Date(Date.now() + options.maxAge * 1e3) : options?.expires != null ? options.expires : cookie.expires;
  3379. if (id) {
  3380. await updateData(id, data2, expires);
  3381. } else {
  3382. id = await createData(data2, expires);
  3383. }
  3384. return cookie.serialize(id, options);
  3385. },
  3386. async destroySession(session, options) {
  3387. await deleteData(session.id);
  3388. return cookie.serialize("", {
  3389. ...options,
  3390. maxAge: void 0,
  3391. expires: /* @__PURE__ */ new Date(0)
  3392. });
  3393. }
  3394. };
  3395. }
  3396. function warnOnceAboutSigningSessionCookie(cookie) {
  3397. warnOnce(
  3398. cookie.isSigned,
  3399. `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`
  3400. );
  3401. }
  3402. // lib/server-runtime/sessions/cookieStorage.ts
  3403. function createCookieSessionStorage({ cookie: cookieArg } = {}) {
  3404. let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
  3405. warnOnceAboutSigningSessionCookie(cookie);
  3406. return {
  3407. async getSession(cookieHeader, options) {
  3408. return createSession(
  3409. cookieHeader && await cookie.parse(cookieHeader, options) || {}
  3410. );
  3411. },
  3412. async commitSession(session, options) {
  3413. let serializedCookie = await cookie.serialize(session.data, options);
  3414. if (serializedCookie.length > 4096) {
  3415. throw new Error(
  3416. "Cookie length will exceed browser maximum. Length: " + serializedCookie.length
  3417. );
  3418. }
  3419. return serializedCookie;
  3420. },
  3421. async destroySession(_session, options) {
  3422. return cookie.serialize("", {
  3423. ...options,
  3424. maxAge: void 0,
  3425. expires: /* @__PURE__ */ new Date(0)
  3426. });
  3427. }
  3428. };
  3429. }
  3430. // lib/server-runtime/sessions/memoryStorage.ts
  3431. function createMemorySessionStorage({ cookie } = {}) {
  3432. let map = /* @__PURE__ */ new Map();
  3433. return createSessionStorage({
  3434. cookie,
  3435. async createData(data2, expires) {
  3436. let id = Math.random().toString(36).substring(2, 10);
  3437. map.set(id, { data: data2, expires });
  3438. return id;
  3439. },
  3440. async readData(id) {
  3441. if (map.has(id)) {
  3442. let { data: data2, expires } = map.get(id);
  3443. if (!expires || expires > /* @__PURE__ */ new Date()) {
  3444. return data2;
  3445. }
  3446. if (expires) map.delete(id);
  3447. }
  3448. return null;
  3449. },
  3450. async updateData(id, data2, expires) {
  3451. map.set(id, { data: data2, expires });
  3452. },
  3453. async deleteData(id) {
  3454. map.delete(id);
  3455. }
  3456. });
  3457. }
  3458. export { Await, RouterContextProvider, createContext, createCookie, createCookieSessionStorage, createMemorySessionStorage, createSession, createSessionStorage, createStaticHandler, data, href, isCookie, isRouteErrorResponse, isSession, matchRoutes, redirect2 as redirect, redirectDocument2 as redirectDocument, replace2 as replace, matchRSCServerRequest as unstable_matchRSCServerRequest };