index.js 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820
  1. import { B as BROWSER } from "./chunks/false.js";
  2. import { json, text, error } from "@sveltejs/kit";
  3. import { Redirect, SvelteKitError, ActionFailure, HttpError } from "@sveltejs/kit/internal";
  4. import { with_request_store, merge_tracing, try_get_request_store } from "@sveltejs/kit/internal/server";
  5. import { a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js";
  6. import { E as ENDPOINT_METHODS, P as PAGE_METHODS, n as negotiate, m as method_not_allowed, h as handle_error_and_jsonify, g as get_status, i as is_form_content_type, a as normalize_error, b as get_global_name, s as serialize_uses, c as clarify_devalue_error, d as get_node_type, e as escape_html, S as SVELTE_KIT_ASSETS, f as create_remote_key, j as static_error_page, r as redirect_response, p as parse_remote_arg, k as stringify, l as deserialize_binary_form, o as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, q as handle_fatal_error, M as MUTATIVE_METHODS, t as format_server_error } from "./chunks/shared.js";
  7. import * as devalue from "devalue";
  8. import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, w as writable, r as readable, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, f as resolve, g as decode_pathname, h as validate_server_exports } from "./chunks/exports.js";
  9. import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js";
  10. import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js";
  11. import { parse, serialize } from "cookie";
  12. import * as set_cookie_parser from "set-cookie-parser";
  13. function with_resolvers() {
  14. let resolve2;
  15. let reject;
  16. const promise = new Promise((res, rej) => {
  17. resolve2 = res;
  18. reject = rej;
  19. });
  20. return { promise, resolve: resolve2, reject };
  21. }
  22. const NULL_BODY_STATUS = [101, 103, 204, 205, 304];
  23. const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer;
  24. async function render_endpoint(event, event_state, mod, state) {
  25. const method = (
  26. /** @type {import('types').HttpMethod} */
  27. event.request.method
  28. );
  29. let handler = mod[method] || mod.fallback;
  30. if (method === "HEAD" && !mod.HEAD && mod.GET) {
  31. handler = mod.GET;
  32. }
  33. if (!handler) {
  34. return method_not_allowed(mod, method);
  35. }
  36. const prerender = mod.prerender ?? state.prerender_default;
  37. if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) {
  38. throw new Error("Cannot prerender endpoints that have mutative methods");
  39. }
  40. if (state.prerendering && !state.prerendering.inside_reroute && !prerender) {
  41. if (state.depth > 0) {
  42. throw new Error(`${event.route.id} is not prerenderable`);
  43. } else {
  44. return new Response(void 0, { status: 204 });
  45. }
  46. }
  47. try {
  48. event_state.allows_commands = true;
  49. const response = await with_request_store(
  50. { event, state: event_state },
  51. () => handler(
  52. /** @type {import('@sveltejs/kit').RequestEvent<Record<string, any>>} */
  53. event
  54. )
  55. );
  56. if (!(response instanceof Response)) {
  57. throw new Error(
  58. `Invalid response from route ${event.url.pathname}: handler should return a Response object`
  59. );
  60. }
  61. if (state.prerendering && (!state.prerendering.inside_reroute || prerender)) {
  62. const cloned = new Response(response.clone().body, {
  63. status: response.status,
  64. statusText: response.statusText,
  65. headers: new Headers(response.headers)
  66. });
  67. cloned.headers.set("x-sveltekit-prerender", String(prerender));
  68. if (state.prerendering.inside_reroute && prerender) {
  69. cloned.headers.set(
  70. "x-sveltekit-routeid",
  71. encodeURI(
  72. /** @type {string} */
  73. event.route.id
  74. )
  75. );
  76. state.prerendering.dependencies.set(event.url.pathname, { response: cloned, body: null });
  77. } else {
  78. return cloned;
  79. }
  80. }
  81. return response;
  82. } catch (e) {
  83. if (e instanceof Redirect) {
  84. return new Response(void 0, {
  85. status: e.status,
  86. headers: { location: e.location }
  87. });
  88. }
  89. throw e;
  90. }
  91. }
  92. function is_endpoint_request(event) {
  93. const { method, headers: headers2 } = event.request;
  94. if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) {
  95. return true;
  96. }
  97. if (method === "POST" && headers2.get("x-sveltekit-action") === "true") return false;
  98. const accept = event.request.headers.get("accept") ?? "*/*";
  99. return negotiate(accept, ["*", "text/html"]) !== "text/html";
  100. }
  101. function compact(arr) {
  102. return arr.filter(
  103. /** @returns {val is NonNullable<T>} */
  104. (val) => val != null
  105. );
  106. }
  107. const DATA_SUFFIX = "/__data.json";
  108. const HTML_DATA_SUFFIX = ".html__data.json";
  109. function has_data_suffix(pathname) {
  110. return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX);
  111. }
  112. function add_data_suffix(pathname) {
  113. if (pathname.endsWith(".html")) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX);
  114. return pathname.replace(/\/$/, "") + DATA_SUFFIX;
  115. }
  116. function strip_data_suffix(pathname) {
  117. if (pathname.endsWith(HTML_DATA_SUFFIX)) {
  118. return pathname.slice(0, -HTML_DATA_SUFFIX.length) + ".html";
  119. }
  120. return pathname.slice(0, -DATA_SUFFIX.length);
  121. }
  122. const ROUTE_SUFFIX = "/__route.js";
  123. function has_resolution_suffix(pathname) {
  124. return pathname.endsWith(ROUTE_SUFFIX);
  125. }
  126. function add_resolution_suffix(pathname) {
  127. return pathname.replace(/\/$/, "") + ROUTE_SUFFIX;
  128. }
  129. function strip_resolution_suffix(pathname) {
  130. return pathname.slice(0, -ROUTE_SUFFIX.length);
  131. }
  132. const noop_span = {
  133. spanContext() {
  134. return noop_span_context;
  135. },
  136. setAttribute() {
  137. return this;
  138. },
  139. setAttributes() {
  140. return this;
  141. },
  142. addEvent() {
  143. return this;
  144. },
  145. setStatus() {
  146. return this;
  147. },
  148. updateName() {
  149. return this;
  150. },
  151. end() {
  152. return this;
  153. },
  154. isRecording() {
  155. return false;
  156. },
  157. recordException() {
  158. return this;
  159. },
  160. addLink() {
  161. return this;
  162. },
  163. addLinks() {
  164. return this;
  165. }
  166. };
  167. const noop_span_context = {
  168. traceId: "",
  169. spanId: "",
  170. traceFlags: 0
  171. };
  172. async function record_span({ name, attributes, fn }) {
  173. {
  174. return fn(noop_span);
  175. }
  176. }
  177. function is_action_json_request(event) {
  178. const accept = negotiate(event.request.headers.get("accept") ?? "*/*", [
  179. "application/json",
  180. "text/html"
  181. ]);
  182. return accept === "application/json" && event.request.method === "POST";
  183. }
  184. async function handle_action_json_request(event, event_state, options2, server) {
  185. const actions = server?.actions;
  186. if (!actions) {
  187. const no_actions_error = new SvelteKitError(
  188. 405,
  189. "Method Not Allowed",
  190. `POST method not allowed. No form actions exist for ${"this page"}`
  191. );
  192. return action_json(
  193. {
  194. type: "error",
  195. error: await handle_error_and_jsonify(event, event_state, options2, no_actions_error)
  196. },
  197. {
  198. status: no_actions_error.status,
  199. headers: {
  200. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
  201. // "The server must generate an Allow header field in a 405 status code response"
  202. allow: "GET"
  203. }
  204. }
  205. );
  206. }
  207. check_named_default_separate(actions);
  208. try {
  209. const data = await call_action(event, event_state, actions);
  210. if (BROWSER) ;
  211. if (data instanceof ActionFailure) {
  212. return action_json({
  213. type: "failure",
  214. status: data.status,
  215. // @ts-expect-error we assign a string to what is supposed to be an object. That's ok
  216. // because we don't use the object outside, and this way we have better code navigation
  217. // through knowing where the related interface is used.
  218. data: stringify_action_response(
  219. data.data,
  220. /** @type {string} */
  221. event.route.id,
  222. options2.hooks.transport
  223. )
  224. });
  225. } else {
  226. return action_json({
  227. type: "success",
  228. status: data ? 200 : 204,
  229. // @ts-expect-error see comment above
  230. data: stringify_action_response(
  231. data,
  232. /** @type {string} */
  233. event.route.id,
  234. options2.hooks.transport
  235. )
  236. });
  237. }
  238. } catch (e) {
  239. const err = normalize_error(e);
  240. if (err instanceof Redirect) {
  241. return action_json_redirect(err);
  242. }
  243. return action_json(
  244. {
  245. type: "error",
  246. error: await handle_error_and_jsonify(
  247. event,
  248. event_state,
  249. options2,
  250. check_incorrect_fail_use(err)
  251. )
  252. },
  253. {
  254. status: get_status(err)
  255. }
  256. );
  257. }
  258. }
  259. function check_incorrect_fail_use(error2) {
  260. return error2 instanceof ActionFailure ? new Error('Cannot "throw fail()". Use "return fail()"') : error2;
  261. }
  262. function action_json_redirect(redirect) {
  263. return action_json({
  264. type: "redirect",
  265. status: redirect.status,
  266. location: redirect.location
  267. });
  268. }
  269. function action_json(data, init2) {
  270. return json(data, init2);
  271. }
  272. function is_action_request(event) {
  273. return event.request.method === "POST";
  274. }
  275. async function handle_action_request(event, event_state, server) {
  276. const actions = server?.actions;
  277. if (!actions) {
  278. event.setHeaders({
  279. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
  280. // "The server must generate an Allow header field in a 405 status code response"
  281. allow: "GET"
  282. });
  283. return {
  284. type: "error",
  285. error: new SvelteKitError(
  286. 405,
  287. "Method Not Allowed",
  288. `POST method not allowed. No form actions exist for ${"this page"}`
  289. )
  290. };
  291. }
  292. check_named_default_separate(actions);
  293. try {
  294. const data = await call_action(event, event_state, actions);
  295. if (BROWSER) ;
  296. if (data instanceof ActionFailure) {
  297. return {
  298. type: "failure",
  299. status: data.status,
  300. data: data.data
  301. };
  302. } else {
  303. return {
  304. type: "success",
  305. status: 200,
  306. // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission
  307. data
  308. };
  309. }
  310. } catch (e) {
  311. const err = normalize_error(e);
  312. if (err instanceof Redirect) {
  313. return {
  314. type: "redirect",
  315. status: err.status,
  316. location: err.location
  317. };
  318. }
  319. return {
  320. type: "error",
  321. error: check_incorrect_fail_use(err)
  322. };
  323. }
  324. }
  325. function check_named_default_separate(actions) {
  326. if (actions.default && Object.keys(actions).length > 1) {
  327. throw new Error(
  328. "When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#named-actions"
  329. );
  330. }
  331. }
  332. async function call_action(event, event_state, actions) {
  333. const url = new URL(event.request.url);
  334. let name = "default";
  335. for (const param of url.searchParams) {
  336. if (param[0].startsWith("/")) {
  337. name = param[0].slice(1);
  338. if (name === "default") {
  339. throw new Error('Cannot use reserved action name "default"');
  340. }
  341. break;
  342. }
  343. }
  344. const action = actions[name];
  345. if (!action) {
  346. throw new SvelteKitError(404, "Not Found", `No action with name '${name}' found`);
  347. }
  348. if (!is_form_content_type(event.request)) {
  349. throw new SvelteKitError(
  350. 415,
  351. "Unsupported Media Type",
  352. `Form actions expect form-encoded data — received ${event.request.headers.get(
  353. "content-type"
  354. )}`
  355. );
  356. }
  357. return record_span({
  358. name: "sveltekit.form_action",
  359. attributes: {
  360. "http.route": event.route.id || "unknown"
  361. },
  362. fn: async (current2) => {
  363. const traced_event = merge_tracing(event, current2);
  364. event_state.allows_commands = true;
  365. const result = await with_request_store(
  366. { event: traced_event, state: event_state },
  367. () => action(traced_event)
  368. );
  369. if (result instanceof ActionFailure) {
  370. current2.setAttributes({
  371. "sveltekit.form_action.result.type": "failure",
  372. "sveltekit.form_action.result.status": result.status
  373. });
  374. }
  375. return result;
  376. }
  377. });
  378. }
  379. function validate_action_return(data) {
  380. if (data instanceof Redirect) {
  381. throw new Error("Cannot `return redirect(...)` — use `redirect(...)` instead");
  382. }
  383. if (data instanceof HttpError) {
  384. throw new Error("Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead");
  385. }
  386. }
  387. function uneval_action_response(data, route_id, transport) {
  388. const replacer = (thing) => {
  389. for (const key2 in transport) {
  390. const encoded = transport[key2].encode(thing);
  391. if (encoded) {
  392. return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
  393. }
  394. }
  395. };
  396. return try_serialize(data, (value) => devalue.uneval(value, replacer), route_id);
  397. }
  398. function stringify_action_response(data, route_id, transport) {
  399. const encoders = Object.fromEntries(
  400. Object.entries(transport).map(([key2, value]) => [key2, value.encode])
  401. );
  402. return try_serialize(data, (value) => devalue.stringify(value, encoders), route_id);
  403. }
  404. function try_serialize(data, fn, route_id) {
  405. try {
  406. return fn(data);
  407. } catch (e) {
  408. const error2 = (
  409. /** @type {any} */
  410. e
  411. );
  412. if (data instanceof Response) {
  413. throw new Error(
  414. `Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });`,
  415. { cause: e }
  416. );
  417. }
  418. if ("path" in error2) {
  419. let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`;
  420. if (error2.path !== "") message += ` (data.${error2.path})`;
  421. throw new Error(message, { cause: e });
  422. }
  423. throw error2;
  424. }
  425. }
  426. function create_async_iterator() {
  427. let resolved = -1;
  428. let returned = -1;
  429. const deferred = [];
  430. return {
  431. iterate: (transform = (x) => x) => {
  432. return {
  433. [Symbol.asyncIterator]() {
  434. return {
  435. next: async () => {
  436. const next = deferred[++returned];
  437. if (!next) return { value: null, done: true };
  438. const value = await next.promise;
  439. return { value: transform(value), done: false };
  440. }
  441. };
  442. }
  443. };
  444. },
  445. add: (promise) => {
  446. deferred.push(with_resolvers());
  447. void promise.then((value) => {
  448. deferred[++resolved].resolve(value);
  449. });
  450. }
  451. };
  452. }
  453. function server_data_serializer(event, event_state, options2) {
  454. let promise_id = 1;
  455. let max_nodes = -1;
  456. const iterator = create_async_iterator();
  457. const global = get_global_name(options2);
  458. function get_replacer(index) {
  459. return function replacer(thing) {
  460. if (typeof thing?.then === "function") {
  461. const id = promise_id++;
  462. const promise = thing.then(
  463. /** @param {any} data */
  464. (data) => ({ data })
  465. ).catch(
  466. /** @param {any} error */
  467. async (error2) => ({
  468. error: await handle_error_and_jsonify(event, event_state, options2, error2)
  469. })
  470. ).then(
  471. /**
  472. * @param {{data: any; error: any}} result
  473. */
  474. async ({ data, error: error2 }) => {
  475. let str;
  476. try {
  477. str = devalue.uneval(error2 ? [, error2] : [data], replacer);
  478. } catch {
  479. error2 = await handle_error_and_jsonify(
  480. event,
  481. event_state,
  482. options2,
  483. new Error(`Failed to serialize promise while rendering ${event.route.id}`)
  484. );
  485. str = devalue.uneval([, error2], replacer);
  486. }
  487. return {
  488. index,
  489. str: `${global}.resolve(${id}, ${str.includes("app.decode") ? `(app) => ${str}` : `() => ${str}`})`
  490. };
  491. }
  492. );
  493. iterator.add(promise);
  494. return `${global}.defer(${id})`;
  495. } else {
  496. for (const key2 in options2.hooks.transport) {
  497. const encoded = options2.hooks.transport[key2].encode(thing);
  498. if (encoded) {
  499. return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
  500. }
  501. }
  502. }
  503. };
  504. }
  505. const strings = (
  506. /** @type {string[]} */
  507. []
  508. );
  509. return {
  510. set_max_nodes(i) {
  511. max_nodes = i;
  512. },
  513. add_node(i, node) {
  514. try {
  515. if (!node) {
  516. strings[i] = "null";
  517. return;
  518. }
  519. const payload = { type: "data", data: node.data, uses: serialize_uses(node) };
  520. if (node.slash) payload.slash = node.slash;
  521. strings[i] = devalue.uneval(payload, get_replacer(i));
  522. } catch (e) {
  523. e.path = e.path.slice(1);
  524. throw new Error(clarify_devalue_error(
  525. event,
  526. /** @type {any} */
  527. e
  528. ), { cause: e });
  529. }
  530. },
  531. get_data(csp) {
  532. const open = `<script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ""}>`;
  533. const close = `<\/script>
  534. `;
  535. return {
  536. data: `[${compact(max_nodes > -1 ? strings.slice(0, max_nodes) : strings).join(",")}]`,
  537. chunks: promise_id > 1 ? iterator.iterate(({ index, str }) => {
  538. if (max_nodes > -1 && index >= max_nodes) {
  539. return "";
  540. }
  541. return open + str + close;
  542. }) : null
  543. };
  544. }
  545. };
  546. }
  547. function server_data_serializer_json(event, event_state, options2) {
  548. let promise_id = 1;
  549. const iterator = create_async_iterator();
  550. const reducers = {
  551. ...Object.fromEntries(
  552. Object.entries(options2.hooks.transport).map(([key2, value]) => [key2, value.encode])
  553. ),
  554. /** @param {any} thing */
  555. Promise: (thing) => {
  556. if (typeof thing?.then !== "function") {
  557. return;
  558. }
  559. const id = promise_id++;
  560. let key2 = "data";
  561. const promise = thing.catch(
  562. /** @param {any} e */
  563. async (e) => {
  564. key2 = "error";
  565. return handle_error_and_jsonify(
  566. event,
  567. event_state,
  568. options2,
  569. /** @type {any} */
  570. e
  571. );
  572. }
  573. ).then(
  574. /** @param {any} value */
  575. async (value) => {
  576. let str;
  577. try {
  578. str = devalue.stringify(value, reducers);
  579. } catch {
  580. const error2 = await handle_error_and_jsonify(
  581. event,
  582. event_state,
  583. options2,
  584. new Error(`Failed to serialize promise while rendering ${event.route.id}`)
  585. );
  586. key2 = "error";
  587. str = devalue.stringify(error2, reducers);
  588. }
  589. return `{"type":"chunk","id":${id},"${key2}":${str}}
  590. `;
  591. }
  592. );
  593. iterator.add(promise);
  594. return id;
  595. }
  596. };
  597. const strings = (
  598. /** @type {string[]} */
  599. []
  600. );
  601. return {
  602. add_node(i, node) {
  603. try {
  604. if (!node) {
  605. strings[i] = "null";
  606. return;
  607. }
  608. if (node.type === "error" || node.type === "skip") {
  609. strings[i] = JSON.stringify(node);
  610. return;
  611. }
  612. strings[i] = `{"type":"data","data":${devalue.stringify(node.data, reducers)},"uses":${JSON.stringify(
  613. serialize_uses(node)
  614. )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ""}}`;
  615. } catch (e) {
  616. e.path = "data" + e.path;
  617. throw new Error(clarify_devalue_error(
  618. event,
  619. /** @type {any} */
  620. e
  621. ), { cause: e });
  622. }
  623. },
  624. get_data() {
  625. return {
  626. data: `{"type":"data","nodes":[${strings.join(",")}]}
  627. `,
  628. chunks: promise_id > 1 ? iterator.iterate() : null
  629. };
  630. }
  631. };
  632. }
  633. async function load_server_data({ event, event_state, state, node, parent }) {
  634. if (!node?.server) return null;
  635. let is_tracking = true;
  636. const uses = {
  637. dependencies: /* @__PURE__ */ new Set(),
  638. params: /* @__PURE__ */ new Set(),
  639. parent: false,
  640. route: false,
  641. url: false,
  642. search_params: /* @__PURE__ */ new Set()
  643. };
  644. const load = node.server.load;
  645. const slash = node.server.trailingSlash;
  646. if (!load) {
  647. return { type: "data", data: null, uses, slash };
  648. }
  649. const url = make_trackable(
  650. event.url,
  651. () => {
  652. if (is_tracking) {
  653. uses.url = true;
  654. }
  655. },
  656. (param) => {
  657. if (is_tracking) {
  658. uses.search_params.add(param);
  659. }
  660. }
  661. );
  662. if (state.prerendering) {
  663. disable_search(url);
  664. }
  665. const result = await record_span({
  666. name: "sveltekit.load",
  667. attributes: {
  668. "sveltekit.load.node_id": node.server_id || "unknown",
  669. "sveltekit.load.node_type": get_node_type(node.server_id),
  670. "http.route": event.route.id || "unknown"
  671. },
  672. fn: async (current2) => {
  673. const traced_event = merge_tracing(event, current2);
  674. const result2 = await with_request_store(
  675. { event: traced_event, state: event_state },
  676. () => load.call(null, {
  677. ...traced_event,
  678. fetch: (info, init2) => {
  679. new URL(info instanceof Request ? info.url : info, event.url);
  680. return event.fetch(info, init2);
  681. },
  682. /** @param {string[]} deps */
  683. depends: (...deps) => {
  684. for (const dep of deps) {
  685. const { href } = new URL(dep, event.url);
  686. uses.dependencies.add(href);
  687. }
  688. },
  689. params: new Proxy(event.params, {
  690. get: (target, key2) => {
  691. if (is_tracking) {
  692. uses.params.add(key2);
  693. }
  694. return target[
  695. /** @type {string} */
  696. key2
  697. ];
  698. }
  699. }),
  700. parent: async () => {
  701. if (is_tracking) {
  702. uses.parent = true;
  703. }
  704. return parent();
  705. },
  706. route: new Proxy(event.route, {
  707. get: (target, key2) => {
  708. if (is_tracking) {
  709. uses.route = true;
  710. }
  711. return target[
  712. /** @type {'id'} */
  713. key2
  714. ];
  715. }
  716. }),
  717. url,
  718. untrack(fn) {
  719. is_tracking = false;
  720. try {
  721. return fn();
  722. } finally {
  723. is_tracking = true;
  724. }
  725. }
  726. })
  727. );
  728. return result2;
  729. }
  730. });
  731. return {
  732. type: "data",
  733. data: result ?? null,
  734. uses,
  735. slash
  736. };
  737. }
  738. async function load_data({
  739. event,
  740. event_state,
  741. fetched,
  742. node,
  743. parent,
  744. server_data_promise,
  745. state,
  746. resolve_opts,
  747. csr
  748. }) {
  749. const server_data_node = await server_data_promise;
  750. const load = node?.universal?.load;
  751. if (!load) {
  752. return server_data_node?.data ?? null;
  753. }
  754. const result = await record_span({
  755. name: "sveltekit.load",
  756. attributes: {
  757. "sveltekit.load.node_id": node.universal_id || "unknown",
  758. "sveltekit.load.node_type": get_node_type(node.universal_id),
  759. "http.route": event.route.id || "unknown"
  760. },
  761. fn: async (current2) => {
  762. const traced_event = merge_tracing(event, current2);
  763. return await with_request_store(
  764. { event: traced_event, state: event_state },
  765. () => load.call(null, {
  766. url: event.url,
  767. params: event.params,
  768. data: server_data_node?.data ?? null,
  769. route: event.route,
  770. fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts),
  771. setHeaders: event.setHeaders,
  772. depends: () => {
  773. },
  774. parent,
  775. untrack: (fn) => fn(),
  776. tracing: traced_event.tracing
  777. })
  778. );
  779. }
  780. });
  781. return result ?? null;
  782. }
  783. function create_universal_fetch(event, state, fetched, csr, resolve_opts) {
  784. const universal_fetch = async (input, init2) => {
  785. const cloned_body = input instanceof Request && input.body ? input.clone().body : null;
  786. const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers;
  787. let response = await event.fetch(input, init2);
  788. const url = new URL(input instanceof Request ? input.url : input, event.url);
  789. const same_origin = url.origin === event.url.origin;
  790. let dependency;
  791. if (same_origin) {
  792. if (state.prerendering) {
  793. dependency = { response, body: null };
  794. state.prerendering.dependencies.set(url.pathname, dependency);
  795. }
  796. } else if (url.protocol === "https:" || url.protocol === "http:") {
  797. const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors";
  798. if (mode === "no-cors") {
  799. response = new Response("", {
  800. status: response.status,
  801. statusText: response.statusText,
  802. headers: response.headers
  803. });
  804. } else {
  805. const acao = response.headers.get("access-control-allow-origin");
  806. if (!acao || acao !== event.url.origin && acao !== "*") {
  807. throw new Error(
  808. `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource`
  809. );
  810. }
  811. }
  812. }
  813. let teed_body;
  814. const proxy = new Proxy(response, {
  815. get(response2, key2, receiver) {
  816. async function push_fetched(body2, is_b64) {
  817. const status_number = Number(response2.status);
  818. if (isNaN(status_number)) {
  819. throw new Error(
  820. `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}`
  821. );
  822. }
  823. fetched.push({
  824. url: same_origin ? url.href.slice(event.url.origin.length) : url.href,
  825. method: event.request.method,
  826. request_body: (
  827. /** @type {string | ArrayBufferView | undefined} */
  828. input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body
  829. ),
  830. request_headers: cloned_headers,
  831. response_body: body2,
  832. response: response2,
  833. is_b64
  834. });
  835. }
  836. if (key2 === "body") {
  837. if (response2.body === null) {
  838. return null;
  839. }
  840. if (teed_body) {
  841. return teed_body;
  842. }
  843. const [a, b] = response2.body.tee();
  844. void (async () => {
  845. let result = new Uint8Array();
  846. for await (const chunk of a) {
  847. const combined = new Uint8Array(result.length + chunk.length);
  848. combined.set(result, 0);
  849. combined.set(chunk, result.length);
  850. result = combined;
  851. }
  852. if (dependency) {
  853. dependency.body = new Uint8Array(result);
  854. }
  855. void push_fetched(base64_encode(result), true);
  856. })();
  857. return teed_body = b;
  858. }
  859. if (key2 === "arrayBuffer") {
  860. return async () => {
  861. const buffer = await response2.arrayBuffer();
  862. const bytes = new Uint8Array(buffer);
  863. if (dependency) {
  864. dependency.body = bytes;
  865. }
  866. if (buffer instanceof ArrayBuffer) {
  867. await push_fetched(base64_encode(bytes), true);
  868. }
  869. return buffer;
  870. };
  871. }
  872. async function text2() {
  873. const body2 = await response2.text();
  874. if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) {
  875. await push_fetched(void 0, false);
  876. return void 0;
  877. }
  878. if (!body2 || typeof body2 === "string") {
  879. await push_fetched(body2, false);
  880. }
  881. if (dependency) {
  882. dependency.body = body2;
  883. }
  884. return body2;
  885. }
  886. if (key2 === "text") {
  887. return text2;
  888. }
  889. if (key2 === "json") {
  890. return async () => {
  891. const body2 = await text2();
  892. return body2 ? JSON.parse(body2) : void 0;
  893. };
  894. }
  895. const value = Reflect.get(response2, key2, response2);
  896. if (value instanceof Function) {
  897. return Object.defineProperties(
  898. /**
  899. * @this {any}
  900. */
  901. function() {
  902. return Reflect.apply(value, this === receiver ? response2 : this, arguments);
  903. },
  904. {
  905. name: { value: value.name },
  906. length: { value: value.length }
  907. }
  908. );
  909. }
  910. return value;
  911. }
  912. });
  913. if (csr) {
  914. const get = response.headers.get;
  915. response.headers.get = (key2) => {
  916. const lower = key2.toLowerCase();
  917. const value = get.call(response.headers, lower);
  918. if (value && !lower.startsWith("x-sveltekit-")) {
  919. const included = resolve_opts.filterSerializedResponseHeaders(lower, value);
  920. if (!included) {
  921. throw new Error(
  922. `Failed to get response header "${lower}" — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#Server-hooks-handle (at ${event.route.id})`
  923. );
  924. }
  925. }
  926. return value;
  927. };
  928. }
  929. return proxy;
  930. };
  931. return (input, init2) => {
  932. const response = universal_fetch(input, init2);
  933. response.catch(() => {
  934. });
  935. return response;
  936. };
  937. }
  938. async function stream_to_string(stream) {
  939. let result = "";
  940. const reader = stream.getReader();
  941. while (true) {
  942. const { done, value } = await reader.read();
  943. if (done) {
  944. break;
  945. }
  946. result += text_decoder.decode(value);
  947. }
  948. return result;
  949. }
  950. function hash(...values) {
  951. let hash2 = 5381;
  952. for (const value of values) {
  953. if (typeof value === "string") {
  954. let i = value.length;
  955. while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i);
  956. } else if (ArrayBuffer.isView(value)) {
  957. const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
  958. let i = buffer.length;
  959. while (i) hash2 = hash2 * 33 ^ buffer[--i];
  960. } else {
  961. throw new TypeError("value must be a string or TypedArray");
  962. }
  963. }
  964. return (hash2 >>> 0).toString(36);
  965. }
  966. const replacements = {
  967. "<": "\\u003C",
  968. "\u2028": "\\u2028",
  969. "\u2029": "\\u2029"
  970. };
  971. const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g");
  972. function serialize_data(fetched, filter, prerendering = false) {
  973. const headers2 = {};
  974. let cache_control = null;
  975. let age = null;
  976. let varyAny = false;
  977. for (const [key2, value] of fetched.response.headers) {
  978. if (filter(key2, value)) {
  979. headers2[key2] = value;
  980. }
  981. if (key2 === "cache-control") cache_control = value;
  982. else if (key2 === "age") age = value;
  983. else if (key2 === "vary" && value.trim() === "*") varyAny = true;
  984. }
  985. const payload = {
  986. status: fetched.response.status,
  987. statusText: fetched.response.statusText,
  988. headers: headers2,
  989. body: fetched.response_body
  990. };
  991. const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]);
  992. const attrs = [
  993. 'type="application/json"',
  994. "data-sveltekit-fetched",
  995. `data-url="${escape_html(fetched.url, true)}"`
  996. ];
  997. if (fetched.is_b64) {
  998. attrs.push("data-b64");
  999. }
  1000. if (fetched.request_headers || fetched.request_body) {
  1001. const values = [];
  1002. if (fetched.request_headers) {
  1003. values.push([...new Headers(fetched.request_headers)].join(","));
  1004. }
  1005. if (fetched.request_body) {
  1006. values.push(fetched.request_body);
  1007. }
  1008. attrs.push(`data-hash="${hash(...values)}"`);
  1009. }
  1010. if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) {
  1011. const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control);
  1012. if (match) {
  1013. const ttl = +match[1] - +(age ?? "0");
  1014. attrs.push(`data-ttl="${ttl}"`);
  1015. }
  1016. }
  1017. return `<script ${attrs.join(" ")}>${safe_payload}<\/script>`;
  1018. }
  1019. const s = JSON.stringify;
  1020. function sha256(data) {
  1021. if (!key[0]) precompute();
  1022. const out = init.slice(0);
  1023. const array2 = encode(data);
  1024. for (let i = 0; i < array2.length; i += 16) {
  1025. const w = array2.subarray(i, i + 16);
  1026. let tmp;
  1027. let a;
  1028. let b;
  1029. let out0 = out[0];
  1030. let out1 = out[1];
  1031. let out2 = out[2];
  1032. let out3 = out[3];
  1033. let out4 = out[4];
  1034. let out5 = out[5];
  1035. let out6 = out[6];
  1036. let out7 = out[7];
  1037. for (let i2 = 0; i2 < 64; i2++) {
  1038. if (i2 < 16) {
  1039. tmp = w[i2];
  1040. } else {
  1041. a = w[i2 + 1 & 15];
  1042. b = w[i2 + 14 & 15];
  1043. tmp = w[i2 & 15] = (a >>> 7 ^ a >>> 18 ^ a >>> 3 ^ a << 25 ^ a << 14) + (b >>> 17 ^ b >>> 19 ^ b >>> 10 ^ b << 15 ^ b << 13) + w[i2 & 15] + w[i2 + 9 & 15] | 0;
  1044. }
  1045. tmp = tmp + out7 + (out4 >>> 6 ^ out4 >>> 11 ^ out4 >>> 25 ^ out4 << 26 ^ out4 << 21 ^ out4 << 7) + (out6 ^ out4 & (out5 ^ out6)) + key[i2];
  1046. out7 = out6;
  1047. out6 = out5;
  1048. out5 = out4;
  1049. out4 = out3 + tmp | 0;
  1050. out3 = out2;
  1051. out2 = out1;
  1052. out1 = out0;
  1053. out0 = tmp + (out1 & out2 ^ out3 & (out1 ^ out2)) + (out1 >>> 2 ^ out1 >>> 13 ^ out1 >>> 22 ^ out1 << 30 ^ out1 << 19 ^ out1 << 10) | 0;
  1054. }
  1055. out[0] = out[0] + out0 | 0;
  1056. out[1] = out[1] + out1 | 0;
  1057. out[2] = out[2] + out2 | 0;
  1058. out[3] = out[3] + out3 | 0;
  1059. out[4] = out[4] + out4 | 0;
  1060. out[5] = out[5] + out5 | 0;
  1061. out[6] = out[6] + out6 | 0;
  1062. out[7] = out[7] + out7 | 0;
  1063. }
  1064. const bytes = new Uint8Array(out.buffer);
  1065. reverse_endianness(bytes);
  1066. return btoa(String.fromCharCode(...bytes));
  1067. }
  1068. const init = new Uint32Array(8);
  1069. const key = new Uint32Array(64);
  1070. function precompute() {
  1071. function frac(x) {
  1072. return (x - Math.floor(x)) * 4294967296;
  1073. }
  1074. let prime = 2;
  1075. for (let i = 0; i < 64; prime++) {
  1076. let is_prime = true;
  1077. for (let factor = 2; factor * factor <= prime; factor++) {
  1078. if (prime % factor === 0) {
  1079. is_prime = false;
  1080. break;
  1081. }
  1082. }
  1083. if (is_prime) {
  1084. if (i < 8) {
  1085. init[i] = frac(prime ** (1 / 2));
  1086. }
  1087. key[i] = frac(prime ** (1 / 3));
  1088. i++;
  1089. }
  1090. }
  1091. }
  1092. function reverse_endianness(bytes) {
  1093. for (let i = 0; i < bytes.length; i += 4) {
  1094. const a = bytes[i + 0];
  1095. const b = bytes[i + 1];
  1096. const c = bytes[i + 2];
  1097. const d = bytes[i + 3];
  1098. bytes[i + 0] = d;
  1099. bytes[i + 1] = c;
  1100. bytes[i + 2] = b;
  1101. bytes[i + 3] = a;
  1102. }
  1103. }
  1104. function encode(str) {
  1105. const encoded = text_encoder.encode(str);
  1106. const length = encoded.length * 8;
  1107. const size = 512 * Math.ceil((length + 65) / 512);
  1108. const bytes = new Uint8Array(size / 8);
  1109. bytes.set(encoded);
  1110. bytes[encoded.length] = 128;
  1111. reverse_endianness(bytes);
  1112. const words = new Uint32Array(bytes.buffer);
  1113. words[words.length - 2] = Math.floor(length / 4294967296);
  1114. words[words.length - 1] = length;
  1115. return words;
  1116. }
  1117. const array = new Uint8Array(16);
  1118. function generate_nonce() {
  1119. crypto.getRandomValues(array);
  1120. return btoa(String.fromCharCode(...array));
  1121. }
  1122. const quoted = /* @__PURE__ */ new Set([
  1123. "self",
  1124. "unsafe-eval",
  1125. "unsafe-hashes",
  1126. "unsafe-inline",
  1127. "none",
  1128. "strict-dynamic",
  1129. "report-sample",
  1130. "wasm-unsafe-eval",
  1131. "script"
  1132. ]);
  1133. const crypto_pattern = /^(nonce|sha\d\d\d)-/;
  1134. class BaseProvider {
  1135. /** @type {boolean} */
  1136. #use_hashes;
  1137. /** @type {boolean} */
  1138. #script_needs_csp;
  1139. /** @type {boolean} */
  1140. #script_src_needs_csp;
  1141. /** @type {boolean} */
  1142. #script_src_elem_needs_csp;
  1143. /** @type {boolean} */
  1144. #style_needs_csp;
  1145. /** @type {boolean} */
  1146. #style_src_needs_csp;
  1147. /** @type {boolean} */
  1148. #style_src_attr_needs_csp;
  1149. /** @type {boolean} */
  1150. #style_src_elem_needs_csp;
  1151. /** @type {import('types').CspDirectives} */
  1152. #directives;
  1153. /** @type {Set<import('types').Csp.Source>} */
  1154. #script_src;
  1155. /** @type {Set<import('types').Csp.Source>} */
  1156. #script_src_elem;
  1157. /** @type {Set<import('types').Csp.Source>} */
  1158. #style_src;
  1159. /** @type {Set<import('types').Csp.Source>} */
  1160. #style_src_attr;
  1161. /** @type {Set<import('types').Csp.Source>} */
  1162. #style_src_elem;
  1163. /** @type {boolean} */
  1164. script_needs_nonce;
  1165. /** @type {boolean} */
  1166. style_needs_nonce;
  1167. /** @type {boolean} */
  1168. script_needs_hash;
  1169. /** @type {string} */
  1170. #nonce;
  1171. /**
  1172. * @param {boolean} use_hashes
  1173. * @param {import('types').CspDirectives} directives
  1174. * @param {string} nonce
  1175. */
  1176. constructor(use_hashes, directives, nonce) {
  1177. this.#use_hashes = use_hashes;
  1178. this.#directives = directives;
  1179. const d = this.#directives;
  1180. this.#script_src = /* @__PURE__ */ new Set();
  1181. this.#script_src_elem = /* @__PURE__ */ new Set();
  1182. this.#style_src = /* @__PURE__ */ new Set();
  1183. this.#style_src_attr = /* @__PURE__ */ new Set();
  1184. this.#style_src_elem = /* @__PURE__ */ new Set();
  1185. const effective_script_src = d["script-src"] || d["default-src"];
  1186. const script_src_elem = d["script-src-elem"];
  1187. const effective_style_src = d["style-src"] || d["default-src"];
  1188. const style_src_attr = d["style-src-attr"];
  1189. const style_src_elem = d["style-src-elem"];
  1190. const style_needs_csp = (directive) => !!directive && !directive.some((value) => value === "unsafe-inline");
  1191. const script_needs_csp = (directive) => !!directive && (!directive.some((value) => value === "unsafe-inline") || directive.some((value) => value === "strict-dynamic"));
  1192. this.#script_src_needs_csp = script_needs_csp(effective_script_src);
  1193. this.#script_src_elem_needs_csp = script_needs_csp(script_src_elem);
  1194. this.#style_src_needs_csp = style_needs_csp(effective_style_src);
  1195. this.#style_src_attr_needs_csp = style_needs_csp(style_src_attr);
  1196. this.#style_src_elem_needs_csp = style_needs_csp(style_src_elem);
  1197. this.#script_needs_csp = this.#script_src_needs_csp || this.#script_src_elem_needs_csp;
  1198. this.#style_needs_csp = this.#style_src_needs_csp || this.#style_src_attr_needs_csp || this.#style_src_elem_needs_csp;
  1199. this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
  1200. this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
  1201. this.script_needs_hash = this.#script_needs_csp && this.#use_hashes;
  1202. this.#nonce = nonce;
  1203. }
  1204. /** @param {string} content */
  1205. add_script(content) {
  1206. if (!this.#script_needs_csp) return;
  1207. const source = this.#use_hashes ? `sha256-${sha256(content)}` : `nonce-${this.#nonce}`;
  1208. if (this.#script_src_needs_csp) {
  1209. this.#script_src.add(source);
  1210. }
  1211. if (this.#script_src_elem_needs_csp) {
  1212. this.#script_src_elem.add(source);
  1213. }
  1214. }
  1215. /** @param {`sha256-${string}`[]} hashes */
  1216. add_script_hashes(hashes) {
  1217. for (const hash2 of hashes) {
  1218. if (this.#script_src_needs_csp) {
  1219. this.#script_src.add(hash2);
  1220. }
  1221. if (this.#script_src_elem_needs_csp) {
  1222. this.#script_src_elem.add(hash2);
  1223. }
  1224. }
  1225. }
  1226. /** @param {string} content */
  1227. add_style(content) {
  1228. if (!this.#style_needs_csp) return;
  1229. const source = this.#use_hashes ? `sha256-${sha256(content)}` : `nonce-${this.#nonce}`;
  1230. if (this.#style_src_needs_csp) {
  1231. this.#style_src.add(source);
  1232. }
  1233. if (this.#style_src_attr_needs_csp) {
  1234. this.#style_src_attr.add(source);
  1235. }
  1236. if (this.#style_src_elem_needs_csp) {
  1237. const sha256_empty_comment_hash = "sha256-9OlNO0DNEeaVzHL4RZwCLsBHA8WBQ8toBp/4F5XV2nc=";
  1238. const d = this.#directives;
  1239. if (d["style-src-elem"] && !d["style-src-elem"].includes(sha256_empty_comment_hash) && !this.#style_src_elem.has(sha256_empty_comment_hash)) {
  1240. this.#style_src_elem.add(sha256_empty_comment_hash);
  1241. }
  1242. if (source !== sha256_empty_comment_hash) {
  1243. this.#style_src_elem.add(source);
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * @param {boolean} [is_meta]
  1249. */
  1250. get_header(is_meta = false) {
  1251. const header = [];
  1252. const directives = { ...this.#directives };
  1253. if (this.#style_src.size > 0) {
  1254. directives["style-src"] = [
  1255. ...directives["style-src"] || directives["default-src"] || [],
  1256. ...this.#style_src
  1257. ];
  1258. }
  1259. if (this.#style_src_attr.size > 0) {
  1260. directives["style-src-attr"] = [
  1261. ...directives["style-src-attr"] || [],
  1262. ...this.#style_src_attr
  1263. ];
  1264. }
  1265. if (this.#style_src_elem.size > 0) {
  1266. directives["style-src-elem"] = [
  1267. ...directives["style-src-elem"] || [],
  1268. ...this.#style_src_elem
  1269. ];
  1270. }
  1271. if (this.#script_src.size > 0) {
  1272. directives["script-src"] = [
  1273. ...directives["script-src"] || directives["default-src"] || [],
  1274. ...this.#script_src
  1275. ];
  1276. }
  1277. if (this.#script_src_elem.size > 0) {
  1278. directives["script-src-elem"] = [
  1279. ...directives["script-src-elem"] || [],
  1280. ...this.#script_src_elem
  1281. ];
  1282. }
  1283. for (const key2 in directives) {
  1284. if (is_meta && (key2 === "frame-ancestors" || key2 === "report-uri" || key2 === "sandbox")) {
  1285. continue;
  1286. }
  1287. const value = (
  1288. /** @type {string[] | true} */
  1289. directives[key2]
  1290. );
  1291. if (!value) continue;
  1292. const directive = [key2];
  1293. if (Array.isArray(value)) {
  1294. value.forEach((value2) => {
  1295. if (quoted.has(value2) || crypto_pattern.test(value2)) {
  1296. directive.push(`'${value2}'`);
  1297. } else {
  1298. directive.push(value2);
  1299. }
  1300. });
  1301. }
  1302. header.push(directive.join(" "));
  1303. }
  1304. return header.join("; ");
  1305. }
  1306. }
  1307. class CspProvider extends BaseProvider {
  1308. get_meta() {
  1309. const content = this.get_header(true);
  1310. if (!content) {
  1311. return;
  1312. }
  1313. return `<meta http-equiv="content-security-policy" content="${escape_html(content, true)}">`;
  1314. }
  1315. }
  1316. class CspReportOnlyProvider extends BaseProvider {
  1317. /**
  1318. * @param {boolean} use_hashes
  1319. * @param {import('types').CspDirectives} directives
  1320. * @param {string} nonce
  1321. */
  1322. constructor(use_hashes, directives, nonce) {
  1323. super(use_hashes, directives, nonce);
  1324. if (Object.values(directives).filter((v) => !!v).length > 0) {
  1325. const has_report_to = directives["report-to"]?.length ?? 0 > 0;
  1326. const has_report_uri = directives["report-uri"]?.length ?? 0 > 0;
  1327. if (!has_report_to && !has_report_uri) {
  1328. throw Error(
  1329. "`content-security-policy-report-only` must be specified with either the `report-to` or `report-uri` directives, or both"
  1330. );
  1331. }
  1332. }
  1333. }
  1334. }
  1335. class Csp {
  1336. /** @readonly */
  1337. nonce = generate_nonce();
  1338. /** @type {CspProvider} */
  1339. csp_provider;
  1340. /** @type {CspReportOnlyProvider} */
  1341. report_only_provider;
  1342. /**
  1343. * @param {import('./types.js').CspConfig} config
  1344. * @param {import('./types.js').CspOpts} opts
  1345. */
  1346. constructor({ mode, directives, reportOnly }, { prerender }) {
  1347. const use_hashes = mode === "hash" || mode === "auto" && prerender;
  1348. this.csp_provider = new CspProvider(use_hashes, directives, this.nonce);
  1349. this.report_only_provider = new CspReportOnlyProvider(use_hashes, reportOnly, this.nonce);
  1350. }
  1351. get script_needs_hash() {
  1352. return this.csp_provider.script_needs_hash || this.report_only_provider.script_needs_hash;
  1353. }
  1354. get script_needs_nonce() {
  1355. return this.csp_provider.script_needs_nonce || this.report_only_provider.script_needs_nonce;
  1356. }
  1357. get style_needs_nonce() {
  1358. return this.csp_provider.style_needs_nonce || this.report_only_provider.style_needs_nonce;
  1359. }
  1360. /** @param {string} content */
  1361. add_script(content) {
  1362. this.csp_provider.add_script(content);
  1363. this.report_only_provider.add_script(content);
  1364. }
  1365. /** @param {`sha256-${string}`[]} hashes */
  1366. add_script_hashes(hashes) {
  1367. this.csp_provider.add_script_hashes(hashes);
  1368. this.report_only_provider.add_script_hashes(hashes);
  1369. }
  1370. /** @param {string} content */
  1371. add_style(content) {
  1372. this.csp_provider.add_style(content);
  1373. this.report_only_provider.add_style(content);
  1374. }
  1375. }
  1376. function exec(match, params, matchers) {
  1377. const result = {};
  1378. const values = match.slice(1);
  1379. const values_needing_match = values.filter((value) => value !== void 0);
  1380. let buffered = 0;
  1381. for (let i = 0; i < params.length; i += 1) {
  1382. const param = params[i];
  1383. let value = values[i - buffered];
  1384. if (param.chained && param.rest && buffered) {
  1385. value = values.slice(i - buffered, i + 1).filter((s2) => s2).join("/");
  1386. buffered = 0;
  1387. }
  1388. if (value === void 0) {
  1389. if (param.rest) {
  1390. value = "";
  1391. } else {
  1392. continue;
  1393. }
  1394. }
  1395. if (!param.matcher || matchers[param.matcher](value)) {
  1396. result[param.name] = value;
  1397. const next_param = params[i + 1];
  1398. const next_value = values[i + 1];
  1399. if (next_param && !next_param.rest && next_param.optional && next_value && param.chained) {
  1400. buffered = 0;
  1401. }
  1402. if (!next_param && !next_value && Object.keys(result).length === values_needing_match.length) {
  1403. buffered = 0;
  1404. }
  1405. continue;
  1406. }
  1407. if (param.optional && param.chained) {
  1408. buffered++;
  1409. continue;
  1410. }
  1411. return;
  1412. }
  1413. if (buffered) return;
  1414. return result;
  1415. }
  1416. function find_route(path, routes, matchers) {
  1417. for (const route of routes) {
  1418. const match = route.pattern.exec(path);
  1419. if (!match) continue;
  1420. const matched = exec(match, route.params, matchers);
  1421. if (matched) {
  1422. return {
  1423. route,
  1424. params: decode_params(matched)
  1425. };
  1426. }
  1427. }
  1428. return null;
  1429. }
  1430. function generate_route_object(route, url, manifest) {
  1431. const { errors, layouts, leaf } = route;
  1432. const nodes = [...errors, ...layouts.map((l) => l?.[1]), leaf[1]].filter((n) => typeof n === "number").map((n) => `'${n}': () => ${create_client_import(manifest._.client.nodes?.[n], url)}`).join(",\n ");
  1433. return [
  1434. `{
  1435. id: ${s(route.id)}`,
  1436. `errors: ${s(route.errors)}`,
  1437. `layouts: ${s(route.layouts)}`,
  1438. `leaf: ${s(route.leaf)}`,
  1439. `nodes: {
  1440. ${nodes}
  1441. }
  1442. }`
  1443. ].join(",\n ");
  1444. }
  1445. function create_client_import(import_path, url) {
  1446. if (!import_path) return "Promise.resolve({})";
  1447. if (import_path[0] === "/") {
  1448. return `import('${import_path}')`;
  1449. }
  1450. if (assets !== "") {
  1451. return `import('${assets}/${import_path}')`;
  1452. }
  1453. let path = get_relative_path(url.pathname, `${base}/${import_path}`);
  1454. if (path[0] !== ".") path = `./${path}`;
  1455. return `import('${path}')`;
  1456. }
  1457. async function resolve_route(resolved_path, url, manifest) {
  1458. if (!manifest._.client.routes) {
  1459. return text("Server-side route resolution disabled", { status: 400 });
  1460. }
  1461. const matchers = await manifest._.matchers();
  1462. const result = find_route(resolved_path, manifest._.client.routes, matchers);
  1463. return create_server_routing_response(result?.route ?? null, result?.params ?? {}, url, manifest).response;
  1464. }
  1465. function create_server_routing_response(route, params, url, manifest) {
  1466. const headers2 = new Headers({
  1467. "content-type": "application/javascript; charset=utf-8"
  1468. });
  1469. if (route) {
  1470. const csr_route = generate_route_object(route, url, manifest);
  1471. const body2 = `${create_css_import(route, url, manifest)}
  1472. export const route = ${csr_route}; export const params = ${JSON.stringify(params)};`;
  1473. return { response: text(body2, { headers: headers2 }), body: body2 };
  1474. } else {
  1475. return { response: text("", { headers: headers2 }), body: "" };
  1476. }
  1477. }
  1478. function create_css_import(route, url, manifest) {
  1479. const { errors, layouts, leaf } = route;
  1480. let css = "";
  1481. for (const node of [...errors, ...layouts.map((l) => l?.[1]), leaf[1]]) {
  1482. if (typeof node !== "number") continue;
  1483. const node_css = manifest._.client.css?.[node];
  1484. for (const css_path of node_css ?? []) {
  1485. css += `'${assets || base}/${css_path}',`;
  1486. }
  1487. }
  1488. if (!css) return "";
  1489. return `${create_client_import(
  1490. /** @type {string} */
  1491. manifest._.client.start,
  1492. url
  1493. )}.then(x => x.load_css([${css}]));`;
  1494. }
  1495. const updated = {
  1496. ...readable(false),
  1497. check: () => false
  1498. };
  1499. async function render_response({
  1500. branch,
  1501. fetched,
  1502. options: options2,
  1503. manifest,
  1504. state,
  1505. page_config,
  1506. status,
  1507. error: error2 = null,
  1508. event,
  1509. event_state,
  1510. resolve_opts,
  1511. action_result,
  1512. data_serializer,
  1513. error_components
  1514. }) {
  1515. if (state.prerendering) {
  1516. if (options2.csp.mode === "nonce") {
  1517. throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
  1518. }
  1519. if (options2.app_template_contains_nonce) {
  1520. throw new Error("Cannot use prerendering if page template contains %sveltekit.nonce%");
  1521. }
  1522. }
  1523. const { client } = manifest._;
  1524. const modulepreloads = new Set(client.imports);
  1525. const stylesheets = new Set(client.stylesheets);
  1526. const fonts = new Set(client.fonts);
  1527. const link_headers = /* @__PURE__ */ new Set();
  1528. const inline_styles = /* @__PURE__ */ new Map();
  1529. let rendered;
  1530. const form_value = action_result?.type === "success" || action_result?.type === "failure" ? action_result.data ?? null : null;
  1531. let base$1 = base;
  1532. let assets$1 = assets;
  1533. let base_expression = s(base);
  1534. const csp = new Csp(options2.csp, {
  1535. prerender: !!state.prerendering
  1536. });
  1537. {
  1538. if (!state.prerendering?.fallback) {
  1539. const segments = event.url.pathname.slice(base.length).split("/").slice(2);
  1540. base$1 = segments.map(() => "..").join("/") || ".";
  1541. base_expression = `new URL(${s(base$1)}, location).pathname.slice(0, -1)`;
  1542. if (!assets || assets[0] === "/" && assets !== SVELTE_KIT_ASSETS) {
  1543. assets$1 = base$1;
  1544. }
  1545. } else if (options2.hash_routing) {
  1546. base_expression = "new URL('.', location).pathname.slice(0, -1)";
  1547. }
  1548. }
  1549. if (page_config.ssr) {
  1550. const props = {
  1551. stores: {
  1552. page: writable(null),
  1553. navigating: writable(null),
  1554. updated
  1555. },
  1556. constructors: await Promise.all(
  1557. branch.map(({ node }) => {
  1558. if (!node.component) {
  1559. throw new Error(`Missing +page.svelte component for route ${event.route.id}`);
  1560. }
  1561. return node.component();
  1562. })
  1563. ),
  1564. form: form_value
  1565. };
  1566. if (error_components) {
  1567. if (error2) {
  1568. props.error = error2;
  1569. }
  1570. props.errors = error_components;
  1571. }
  1572. let data2 = {};
  1573. for (let i = 0; i < branch.length; i += 1) {
  1574. data2 = { ...data2, ...branch[i].data };
  1575. props[`data_${i}`] = data2;
  1576. }
  1577. props.page = {
  1578. error: error2,
  1579. params: (
  1580. /** @type {Record<string, any>} */
  1581. event.params
  1582. ),
  1583. route: event.route,
  1584. status,
  1585. url: event.url,
  1586. data: data2,
  1587. form: form_value,
  1588. state: {}
  1589. };
  1590. const render_opts = {
  1591. context: /* @__PURE__ */ new Map([
  1592. [
  1593. "__request__",
  1594. {
  1595. page: props.page
  1596. }
  1597. ]
  1598. ]),
  1599. csp: csp.script_needs_nonce ? { nonce: csp.nonce } : { hash: csp.script_needs_hash },
  1600. transformError: error_components ? (
  1601. /** @param {unknown} e */
  1602. async (e) => {
  1603. const transformed2 = await handle_error_and_jsonify(event, event_state, options2, e);
  1604. props.page.error = props.error = error2 = transformed2;
  1605. props.page.status = status = get_status(e);
  1606. return transformed2;
  1607. }
  1608. ) : void 0
  1609. };
  1610. const fetch2 = globalThis.fetch;
  1611. try {
  1612. if (BROWSER) ;
  1613. event_state.allows_commands = false;
  1614. rendered = await with_request_store({ event, state: event_state }, async () => {
  1615. if (relative) override({ base: base$1, assets: assets$1 });
  1616. const maybe_promise = options2.root.render(props, render_opts);
  1617. const rendered2 = options2.async && "then" in maybe_promise ? (
  1618. /** @type {ReturnType<typeof options.root.render> & Promise<any>} */
  1619. maybe_promise.then((r) => r)
  1620. ) : maybe_promise;
  1621. if (options2.async) {
  1622. reset();
  1623. }
  1624. const { head: head2, html: html2, css, hashes } = (
  1625. /** @type {ReturnType<typeof options.root.render>} */
  1626. options2.async ? await rendered2 : rendered2
  1627. );
  1628. if (hashes) {
  1629. csp.add_script_hashes(hashes.script);
  1630. }
  1631. return { head: head2, html: html2, css, hashes };
  1632. });
  1633. } finally {
  1634. reset();
  1635. }
  1636. for (const { node } of branch) {
  1637. for (const url of node.imports) modulepreloads.add(url);
  1638. for (const url of node.stylesheets) stylesheets.add(url);
  1639. for (const url of node.fonts) fonts.add(url);
  1640. if (node.inline_styles && !client.inline) {
  1641. Object.entries(await node.inline_styles()).forEach(([filename, css]) => {
  1642. if (typeof css === "string") {
  1643. inline_styles.set(filename, css);
  1644. return;
  1645. }
  1646. inline_styles.set(filename, css(`${assets$1}/${app_dir}/immutable/assets`, assets$1));
  1647. });
  1648. }
  1649. }
  1650. } else {
  1651. rendered = { head: "", html: "", css: { code: "", map: null }, hashes: { script: [] } };
  1652. }
  1653. const head = new Head(rendered.head, !!state.prerendering);
  1654. let body2 = rendered.html;
  1655. const prefixed = (path) => {
  1656. if (path.startsWith("/")) {
  1657. return base + path;
  1658. }
  1659. return `${assets$1}/${path}`;
  1660. };
  1661. const style = client.inline ? client.inline?.style : Array.from(inline_styles.values()).join("\n");
  1662. if (style) {
  1663. const attributes = [];
  1664. if (csp.style_needs_nonce) attributes.push(`nonce="${csp.nonce}"`);
  1665. csp.add_style(style);
  1666. head.add_style(style, attributes);
  1667. }
  1668. for (const dep of stylesheets) {
  1669. const path = prefixed(dep);
  1670. const attributes = ['rel="stylesheet"'];
  1671. if (inline_styles.has(dep)) {
  1672. attributes.push("disabled", 'media="(max-width: 0)"');
  1673. } else {
  1674. if (resolve_opts.preload({ type: "css", path })) {
  1675. link_headers.add(`<${encodeURI(path)}>; rel="preload"; as="style"; nopush`);
  1676. }
  1677. }
  1678. head.add_stylesheet(path, attributes);
  1679. }
  1680. for (const dep of fonts) {
  1681. const path = prefixed(dep);
  1682. if (resolve_opts.preload({ type: "font", path })) {
  1683. const ext = dep.slice(dep.lastIndexOf(".") + 1);
  1684. head.add_link_tag(path, ['rel="preload"', 'as="font"', `type="font/${ext}"`, "crossorigin"]);
  1685. link_headers.add(
  1686. `<${encodeURI(path)}>; rel="preload"; as="font"; type="font/${ext}"; crossorigin; nopush`
  1687. );
  1688. }
  1689. }
  1690. const global = get_global_name(options2);
  1691. const { data, chunks } = data_serializer.get_data(csp);
  1692. if (page_config.ssr && page_config.csr) {
  1693. body2 += `
  1694. ${fetched.map(
  1695. (item) => serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!state.prerendering)
  1696. ).join("\n ")}`;
  1697. }
  1698. if (page_config.csr) {
  1699. const route = manifest._.client.routes?.find((r) => r.id === event.route.id) ?? null;
  1700. if (client.uses_env_dynamic_public && state.prerendering) {
  1701. modulepreloads.add(`${app_dir}/env.js`);
  1702. }
  1703. if (!client.inline) {
  1704. const included_modulepreloads = Array.from(modulepreloads, (dep) => prefixed(dep)).filter(
  1705. (path) => resolve_opts.preload({ type: "js", path })
  1706. );
  1707. for (const path of included_modulepreloads) {
  1708. link_headers.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
  1709. if (options2.preload_strategy !== "modulepreload") {
  1710. head.add_script_preload(path);
  1711. } else {
  1712. head.add_link_tag(path, ['rel="modulepreload"']);
  1713. }
  1714. }
  1715. }
  1716. if (manifest._.client.routes && state.prerendering && !state.prerendering.fallback) {
  1717. const pathname = add_resolution_suffix(event.url.pathname);
  1718. state.prerendering.dependencies.set(
  1719. pathname,
  1720. create_server_routing_response(route, event.params, new URL(pathname, event.url), manifest)
  1721. );
  1722. }
  1723. const blocks = [];
  1724. const load_env_eagerly = client.uses_env_dynamic_public && state.prerendering;
  1725. const properties = [`base: ${base_expression}`];
  1726. if (assets) {
  1727. properties.push(`assets: ${s(assets)}`);
  1728. }
  1729. if (client.uses_env_dynamic_public) {
  1730. properties.push(`env: ${load_env_eagerly ? "null" : s(public_env)}`);
  1731. }
  1732. if (chunks) {
  1733. blocks.push("const deferred = new Map();");
  1734. properties.push(`defer: (id) => new Promise((fulfil, reject) => {
  1735. deferred.set(id, { fulfil, reject });
  1736. })`);
  1737. let app_declaration = "";
  1738. if (Object.keys(options2.hooks.transport).length > 0) {
  1739. if (client.inline) {
  1740. app_declaration = `const app = __sveltekit_${options2.version_hash}.app.app;`;
  1741. } else if (client.app) {
  1742. app_declaration = `const app = await import(${s(prefixed(client.app))});`;
  1743. } else {
  1744. app_declaration = `const { app } = await import(${s(prefixed(client.start))});`;
  1745. }
  1746. }
  1747. const prelude = app_declaration ? `${app_declaration}
  1748. const [data, error] = fn(app);` : `const [data, error] = fn();`;
  1749. properties.push(`resolve: async (id, fn) => {
  1750. ${prelude}
  1751. const try_to_resolve = () => {
  1752. if (!deferred.has(id)) {
  1753. setTimeout(try_to_resolve, 0);
  1754. return;
  1755. }
  1756. const { fulfil, reject } = deferred.get(id);
  1757. deferred.delete(id);
  1758. if (error) reject(error);
  1759. else fulfil(data);
  1760. }
  1761. try_to_resolve();
  1762. }`);
  1763. }
  1764. blocks.push(`${global} = {
  1765. ${properties.join(",\n ")}
  1766. };`);
  1767. const args = ["element"];
  1768. blocks.push("const element = document.currentScript.parentElement;");
  1769. if (page_config.ssr) {
  1770. const serialized = { form: "null", error: "null" };
  1771. if (form_value) {
  1772. serialized.form = uneval_action_response(
  1773. form_value,
  1774. /** @type {string} */
  1775. event.route.id,
  1776. options2.hooks.transport
  1777. );
  1778. }
  1779. if (error2) {
  1780. serialized.error = devalue.uneval(error2);
  1781. }
  1782. const hydrate = [
  1783. `node_ids: [${branch.map(({ node }) => node.index).join(", ")}]`,
  1784. `data: ${data}`,
  1785. `form: ${serialized.form}`,
  1786. `error: ${serialized.error}`
  1787. ];
  1788. if (status !== 200) {
  1789. hydrate.push(`status: ${status}`);
  1790. }
  1791. if (manifest._.client.routes) {
  1792. if (route) {
  1793. const stringified = generate_route_object(route, event.url, manifest).replaceAll(
  1794. "\n",
  1795. "\n "
  1796. );
  1797. hydrate.push(`params: ${devalue.uneval(event.params)}`, `server_route: ${stringified}`);
  1798. }
  1799. } else if (options2.embedded) {
  1800. hydrate.push(`params: ${devalue.uneval(event.params)}`, `route: ${s(event.route)}`);
  1801. }
  1802. const indent = " ".repeat(load_env_eagerly ? 7 : 6);
  1803. args.push(`{
  1804. ${indent} ${hydrate.join(`,
  1805. ${indent} `)}
  1806. ${indent}}`);
  1807. }
  1808. const { remote_data: remote_cache } = event_state;
  1809. let serialized_remote_data = "";
  1810. if (remote_cache) {
  1811. const remote = {};
  1812. for (const [info, cache] of remote_cache) {
  1813. if (!info.id) continue;
  1814. for (const key2 in cache) {
  1815. const remote_key = create_remote_key(info.id, key2);
  1816. if (event_state.refreshes?.[remote_key] !== void 0) {
  1817. remote[remote_key] = await cache[key2];
  1818. } else {
  1819. const result = await Promise.race([
  1820. Promise.resolve(cache[key2]).then(
  1821. (v) => (
  1822. /** @type {const} */
  1823. { settled: true, value: v }
  1824. ),
  1825. (e) => (
  1826. /** @type {const} */
  1827. { settled: true, error: e }
  1828. )
  1829. ),
  1830. new Promise((resolve2) => {
  1831. queueMicrotask(() => resolve2(
  1832. /** @type {const} */
  1833. { settled: false }
  1834. ));
  1835. })
  1836. ]);
  1837. if (result.settled) {
  1838. if ("error" in result) throw result.error;
  1839. remote[remote_key] = result.value;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. const replacer = (thing) => {
  1845. for (const key2 in options2.hooks.transport) {
  1846. const encoded = options2.hooks.transport[key2].encode(thing);
  1847. if (encoded) {
  1848. return `app.decode('${key2}', ${devalue.uneval(encoded, replacer)})`;
  1849. }
  1850. }
  1851. };
  1852. serialized_remote_data = `${global}.data = ${devalue.uneval(remote, replacer)};
  1853. `;
  1854. }
  1855. const boot = client.inline ? `${client.inline.script}
  1856. ${serialized_remote_data}${global}.app.start(${args.join(", ")});` : client.app ? `Promise.all([
  1857. import(${s(prefixed(client.start))}),
  1858. import(${s(prefixed(client.app))})
  1859. ]).then(([kit, app]) => {
  1860. ${serialized_remote_data}kit.start(app, ${args.join(", ")});
  1861. });` : `import(${s(prefixed(client.start))}).then((app) => {
  1862. ${serialized_remote_data}app.start(${args.join(", ")})
  1863. });`;
  1864. if (load_env_eagerly) {
  1865. blocks.push(`import(${s(`${base$1}/${app_dir}/env.js`)}).then(({ env }) => {
  1866. ${global}.env = env;
  1867. ${boot.replace(/\n/g, "\n ")}
  1868. });`);
  1869. } else {
  1870. blocks.push(boot);
  1871. }
  1872. if (options2.service_worker) {
  1873. let opts = "";
  1874. if (options2.service_worker_options != null) {
  1875. const service_worker_options = { ...options2.service_worker_options };
  1876. opts = `, ${s(service_worker_options)}`;
  1877. }
  1878. blocks.push(`if ('serviceWorker' in navigator) {
  1879. addEventListener('load', function () {
  1880. navigator.serviceWorker.register('${prefixed("service-worker.js")}'${opts});
  1881. });
  1882. }`);
  1883. }
  1884. const init_app = `
  1885. {
  1886. ${blocks.join("\n\n ")}
  1887. }
  1888. `;
  1889. csp.add_script(init_app);
  1890. body2 += `
  1891. <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ""}>${init_app}<\/script>
  1892. `;
  1893. }
  1894. const headers2 = new Headers({
  1895. "x-sveltekit-page": "true",
  1896. "content-type": "text/html"
  1897. });
  1898. if (state.prerendering) {
  1899. const csp_headers = csp.csp_provider.get_meta();
  1900. if (csp_headers) {
  1901. head.add_http_equiv(csp_headers);
  1902. }
  1903. if (state.prerendering.cache) {
  1904. head.add_http_equiv(
  1905. `<meta http-equiv="cache-control" content="${state.prerendering.cache}">`
  1906. );
  1907. }
  1908. } else {
  1909. const csp_header = csp.csp_provider.get_header();
  1910. if (csp_header) {
  1911. headers2.set("content-security-policy", csp_header);
  1912. }
  1913. const report_only_header = csp.report_only_provider.get_header();
  1914. if (report_only_header) {
  1915. headers2.set("content-security-policy-report-only", report_only_header);
  1916. }
  1917. if (link_headers.size) {
  1918. headers2.set("link", Array.from(link_headers).join(", "));
  1919. }
  1920. }
  1921. const html = options2.templates.app({
  1922. head: head.build(),
  1923. body: body2,
  1924. assets: assets$1,
  1925. nonce: (
  1926. /** @type {string} */
  1927. csp.nonce
  1928. ),
  1929. env: public_env
  1930. });
  1931. const transformed = await resolve_opts.transformPageChunk({
  1932. html,
  1933. done: true
  1934. }) || "";
  1935. if (!chunks) {
  1936. headers2.set("etag", `"${hash(transformed)}"`);
  1937. }
  1938. return !chunks ? text(transformed, {
  1939. status,
  1940. headers: headers2
  1941. }) : new Response(
  1942. new ReadableStream({
  1943. async start(controller) {
  1944. controller.enqueue(text_encoder.encode(transformed + "\n"));
  1945. for await (const chunk of chunks) {
  1946. if (chunk.length) controller.enqueue(text_encoder.encode(chunk));
  1947. }
  1948. controller.close();
  1949. },
  1950. type: "bytes"
  1951. }),
  1952. {
  1953. headers: headers2
  1954. }
  1955. );
  1956. }
  1957. class Head {
  1958. #rendered;
  1959. #prerendering;
  1960. /** @type {string[]} */
  1961. #http_equiv = [];
  1962. /** @type {string[]} */
  1963. #link_tags = [];
  1964. /** @type {string[]} */
  1965. #script_preloads = [];
  1966. /** @type {string[]} */
  1967. #style_tags = [];
  1968. /** @type {string[]} */
  1969. #stylesheet_links = [];
  1970. /**
  1971. * @param {string} rendered
  1972. * @param {boolean} prerendering
  1973. */
  1974. constructor(rendered, prerendering) {
  1975. this.#rendered = rendered;
  1976. this.#prerendering = prerendering;
  1977. }
  1978. build() {
  1979. return [
  1980. ...this.#http_equiv,
  1981. ...this.#link_tags,
  1982. ...this.#script_preloads,
  1983. this.#rendered,
  1984. ...this.#style_tags,
  1985. ...this.#stylesheet_links
  1986. ].join("\n ");
  1987. }
  1988. /**
  1989. * @param {string} style
  1990. * @param {string[]} attributes
  1991. */
  1992. add_style(style, attributes) {
  1993. this.#style_tags.push(
  1994. `<style${attributes.length ? " " + attributes.join(" ") : ""}>${style}</style>`
  1995. );
  1996. }
  1997. /**
  1998. * @param {string} href
  1999. * @param {string[]} attributes
  2000. */
  2001. add_stylesheet(href, attributes) {
  2002. this.#stylesheet_links.push(`<link href="${href}" ${attributes.join(" ")}>`);
  2003. }
  2004. /** @param {string} href */
  2005. add_script_preload(href) {
  2006. this.#script_preloads.push(
  2007. `<link rel="preload" as="script" crossorigin="anonymous" href="${href}">`
  2008. );
  2009. }
  2010. /**
  2011. * @param {string} href
  2012. * @param {string[]} attributes
  2013. */
  2014. add_link_tag(href, attributes) {
  2015. if (!this.#prerendering) return;
  2016. this.#link_tags.push(`<link href="${href}" ${attributes.join(" ")}>`);
  2017. }
  2018. /** @param {string} tag */
  2019. add_http_equiv(tag) {
  2020. if (!this.#prerendering) return;
  2021. this.#http_equiv.push(tag);
  2022. }
  2023. }
  2024. class PageNodes {
  2025. data;
  2026. /**
  2027. * @param {Array<import('types').SSRNode | undefined>} nodes
  2028. */
  2029. constructor(nodes) {
  2030. this.data = nodes;
  2031. }
  2032. layouts() {
  2033. return this.data.slice(0, -1);
  2034. }
  2035. page() {
  2036. return this.data.at(-1);
  2037. }
  2038. validate() {
  2039. for (const layout of this.layouts()) {
  2040. if (layout) {
  2041. validate_layout_server_exports(
  2042. layout.server,
  2043. /** @type {string} */
  2044. layout.server_id
  2045. );
  2046. validate_layout_exports(
  2047. layout.universal,
  2048. /** @type {string} */
  2049. layout.universal_id
  2050. );
  2051. }
  2052. }
  2053. const page = this.page();
  2054. if (page) {
  2055. validate_page_server_exports(
  2056. page.server,
  2057. /** @type {string} */
  2058. page.server_id
  2059. );
  2060. validate_page_exports(
  2061. page.universal,
  2062. /** @type {string} */
  2063. page.universal_id
  2064. );
  2065. }
  2066. }
  2067. /**
  2068. * @template {'prerender' | 'ssr' | 'csr' | 'trailingSlash'} Option
  2069. * @param {Option} option
  2070. * @returns {Value | undefined}
  2071. */
  2072. #get_option(option) {
  2073. return this.data.reduce(
  2074. (value, node) => {
  2075. return node?.universal?.[option] ?? node?.server?.[option] ?? value;
  2076. },
  2077. /** @type {Value | undefined} */
  2078. void 0
  2079. );
  2080. }
  2081. csr() {
  2082. return this.#get_option("csr") ?? true;
  2083. }
  2084. ssr() {
  2085. return this.#get_option("ssr") ?? true;
  2086. }
  2087. prerender() {
  2088. return this.#get_option("prerender") ?? false;
  2089. }
  2090. trailing_slash() {
  2091. return this.#get_option("trailingSlash") ?? "never";
  2092. }
  2093. get_config() {
  2094. let current2 = {};
  2095. for (const node of this.data) {
  2096. if (!node?.universal?.config && !node?.server?.config) continue;
  2097. current2 = {
  2098. ...current2,
  2099. // TODO: should we override the server config value with the universal value similar to other page options?
  2100. ...node?.universal?.config,
  2101. ...node?.server?.config
  2102. };
  2103. }
  2104. return Object.keys(current2).length ? current2 : void 0;
  2105. }
  2106. should_prerender_data() {
  2107. return this.data.some(
  2108. // prerender in case of trailingSlash because the client retrieves that value from the server
  2109. (node) => node?.server?.load || node?.server?.trailingSlash !== void 0
  2110. );
  2111. }
  2112. }
  2113. async function respond_with_error({
  2114. event,
  2115. event_state,
  2116. options: options2,
  2117. manifest,
  2118. state,
  2119. status,
  2120. error: error2,
  2121. resolve_opts
  2122. }) {
  2123. if (event.request.headers.get("x-sveltekit-error")) {
  2124. return static_error_page(
  2125. options2,
  2126. status,
  2127. /** @type {Error} */
  2128. error2.message
  2129. );
  2130. }
  2131. const fetched = [];
  2132. try {
  2133. const branch = [];
  2134. const default_layout = await manifest._.nodes[0]();
  2135. const nodes = new PageNodes([default_layout]);
  2136. const ssr = nodes.ssr();
  2137. const csr = nodes.csr();
  2138. const data_serializer = server_data_serializer(event, event_state, options2);
  2139. if (ssr) {
  2140. state.error = true;
  2141. const server_data_promise = load_server_data({
  2142. event,
  2143. event_state,
  2144. state,
  2145. node: default_layout,
  2146. // eslint-disable-next-line @typescript-eslint/require-await
  2147. parent: async () => ({})
  2148. });
  2149. const server_data = await server_data_promise;
  2150. data_serializer.add_node(0, server_data);
  2151. const data = await load_data({
  2152. event,
  2153. event_state,
  2154. fetched,
  2155. node: default_layout,
  2156. // eslint-disable-next-line @typescript-eslint/require-await
  2157. parent: async () => ({}),
  2158. resolve_opts,
  2159. server_data_promise,
  2160. state,
  2161. csr
  2162. });
  2163. branch.push(
  2164. {
  2165. node: default_layout,
  2166. server_data,
  2167. data
  2168. },
  2169. {
  2170. node: await manifest._.nodes[1](),
  2171. // 1 is always the root error
  2172. data: null,
  2173. server_data: null
  2174. }
  2175. );
  2176. }
  2177. return await render_response({
  2178. options: options2,
  2179. manifest,
  2180. state,
  2181. page_config: {
  2182. ssr,
  2183. csr
  2184. },
  2185. status,
  2186. error: await handle_error_and_jsonify(event, event_state, options2, error2),
  2187. branch,
  2188. error_components: [],
  2189. fetched,
  2190. event,
  2191. event_state,
  2192. resolve_opts,
  2193. data_serializer
  2194. });
  2195. } catch (e) {
  2196. if (e instanceof Redirect) {
  2197. return redirect_response(e.status, e.location);
  2198. }
  2199. return static_error_page(
  2200. options2,
  2201. get_status(e),
  2202. (await handle_error_and_jsonify(event, event_state, options2, e)).message
  2203. );
  2204. }
  2205. }
  2206. async function handle_remote_call(event, state, options2, manifest, id) {
  2207. return record_span({
  2208. name: "sveltekit.remote.call",
  2209. attributes: {},
  2210. fn: (current2) => {
  2211. const traced_event = merge_tracing(event, current2);
  2212. return with_request_store(
  2213. { event: traced_event, state },
  2214. () => handle_remote_call_internal(traced_event, state, options2, manifest, id)
  2215. );
  2216. }
  2217. });
  2218. }
  2219. async function handle_remote_call_internal(event, state, options2, manifest, id) {
  2220. const [hash2, name, additional_args] = id.split("/");
  2221. const remotes = manifest._.remotes;
  2222. if (!remotes[hash2]) error(404);
  2223. const module = await remotes[hash2]();
  2224. const fn = module.default[name];
  2225. if (!fn) error(404);
  2226. const info = fn.__;
  2227. const transport = options2.hooks.transport;
  2228. event.tracing.current.setAttributes({
  2229. "sveltekit.remote.call.type": info.type,
  2230. "sveltekit.remote.call.name": info.name
  2231. });
  2232. let form_client_refreshes;
  2233. try {
  2234. if (info.type === "query_batch") {
  2235. if (event.request.method !== "POST") {
  2236. throw new SvelteKitError(
  2237. 405,
  2238. "Method Not Allowed",
  2239. `\`query.batch\` functions must be invoked via POST request, not ${event.request.method}`
  2240. );
  2241. }
  2242. const { payloads } = await event.request.json();
  2243. const args = await Promise.all(
  2244. payloads.map((payload2) => parse_remote_arg(payload2, transport))
  2245. );
  2246. const results = await with_request_store({ event, state }, () => info.run(args, options2));
  2247. return json(
  2248. /** @type {RemoteFunctionResponse} */
  2249. {
  2250. type: "result",
  2251. result: stringify(results, transport)
  2252. }
  2253. );
  2254. }
  2255. if (info.type === "form") {
  2256. if (event.request.method !== "POST") {
  2257. throw new SvelteKitError(
  2258. 405,
  2259. "Method Not Allowed",
  2260. `\`form\` functions must be invoked via POST request, not ${event.request.method}`
  2261. );
  2262. }
  2263. if (!is_form_content_type(event.request)) {
  2264. throw new SvelteKitError(
  2265. 415,
  2266. "Unsupported Media Type",
  2267. `\`form\` functions expect form-encoded data — received ${event.request.headers.get(
  2268. "content-type"
  2269. )}`
  2270. );
  2271. }
  2272. const { data: data2, meta, form_data } = await deserialize_binary_form(event.request);
  2273. form_client_refreshes = meta.remote_refreshes;
  2274. if (additional_args && !("id" in data2)) {
  2275. data2.id = JSON.parse(decodeURIComponent(additional_args));
  2276. }
  2277. const fn2 = info.fn;
  2278. const result = await with_request_store({ event, state }, () => fn2(data2, meta, form_data));
  2279. return json(
  2280. /** @type {RemoteFunctionResponse} */
  2281. {
  2282. type: "result",
  2283. result: stringify(result, transport),
  2284. refreshes: result.issues ? void 0 : await serialize_refreshes(meta.remote_refreshes)
  2285. }
  2286. );
  2287. }
  2288. if (info.type === "command") {
  2289. const { payload: payload2, refreshes } = await event.request.json();
  2290. const arg = parse_remote_arg(payload2, transport);
  2291. const data2 = await with_request_store({ event, state }, () => fn(arg));
  2292. return json(
  2293. /** @type {RemoteFunctionResponse} */
  2294. {
  2295. type: "result",
  2296. result: stringify(data2, transport),
  2297. refreshes: await serialize_refreshes(refreshes)
  2298. }
  2299. );
  2300. }
  2301. const payload = info.type === "prerender" ? additional_args : (
  2302. /** @type {string} */
  2303. // new URL(...) necessary because we're hiding the URL from the user in the event object
  2304. new URL(event.request.url).searchParams.get("payload")
  2305. );
  2306. const data = await with_request_store(
  2307. { event, state },
  2308. () => fn(parse_remote_arg(payload, transport))
  2309. );
  2310. return json(
  2311. /** @type {RemoteFunctionResponse} */
  2312. {
  2313. type: "result",
  2314. result: stringify(data, transport)
  2315. }
  2316. );
  2317. } catch (error2) {
  2318. if (error2 instanceof Redirect) {
  2319. return json(
  2320. /** @type {RemoteFunctionResponse} */
  2321. {
  2322. type: "redirect",
  2323. location: error2.location,
  2324. refreshes: await serialize_refreshes(form_client_refreshes)
  2325. }
  2326. );
  2327. }
  2328. const status = error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : 500;
  2329. return json(
  2330. /** @type {RemoteFunctionResponse} */
  2331. {
  2332. type: "error",
  2333. error: await handle_error_and_jsonify(event, state, options2, error2),
  2334. status
  2335. },
  2336. {
  2337. // By setting a non-200 during prerendering we fail the prerender process (unless handleHttpError handles it).
  2338. // Errors at runtime will be passed to the client and are handled there
  2339. status: state.prerendering ? status : void 0,
  2340. headers: {
  2341. "cache-control": "private, no-store"
  2342. }
  2343. }
  2344. );
  2345. }
  2346. async function serialize_refreshes(client_refreshes) {
  2347. const refreshes = state.refreshes ?? {};
  2348. if (client_refreshes) {
  2349. for (const key2 of client_refreshes) {
  2350. if (refreshes[key2] !== void 0) continue;
  2351. const [hash3, name2, payload] = key2.split("/");
  2352. const loader = manifest._.remotes[hash3];
  2353. const fn2 = (await loader?.())?.default?.[name2];
  2354. if (!fn2) error(400, "Bad Request");
  2355. refreshes[key2] = with_request_store(
  2356. { event, state },
  2357. () => fn2(parse_remote_arg(payload, transport))
  2358. );
  2359. }
  2360. }
  2361. if (Object.keys(refreshes).length === 0) {
  2362. return void 0;
  2363. }
  2364. return stringify(
  2365. Object.fromEntries(
  2366. await Promise.all(
  2367. Object.entries(refreshes).map(async ([key2, promise]) => [key2, await promise])
  2368. )
  2369. ),
  2370. transport
  2371. );
  2372. }
  2373. }
  2374. async function handle_remote_form_post(event, state, manifest, id) {
  2375. return record_span({
  2376. name: "sveltekit.remote.form.post",
  2377. attributes: {},
  2378. fn: (current2) => {
  2379. const traced_event = merge_tracing(event, current2);
  2380. return with_request_store(
  2381. { event: traced_event, state },
  2382. () => handle_remote_form_post_internal(traced_event, state, manifest, id)
  2383. );
  2384. }
  2385. });
  2386. }
  2387. async function handle_remote_form_post_internal(event, state, manifest, id) {
  2388. const [hash2, name, action_id] = id.split("/");
  2389. const remotes = manifest._.remotes;
  2390. const module = await remotes[hash2]?.();
  2391. let form = (
  2392. /** @type {RemoteForm<any, any>} */
  2393. module?.default[name]
  2394. );
  2395. if (!form) {
  2396. event.setHeaders({
  2397. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
  2398. // "The server must generate an Allow header field in a 405 status code response"
  2399. allow: "GET"
  2400. });
  2401. return {
  2402. type: "error",
  2403. error: new SvelteKitError(
  2404. 405,
  2405. "Method Not Allowed",
  2406. `POST method not allowed. No form actions exist for ${"this page"}`
  2407. )
  2408. };
  2409. }
  2410. if (action_id) {
  2411. form = with_request_store({ event, state }, () => form.for(JSON.parse(action_id)));
  2412. }
  2413. try {
  2414. const fn = (
  2415. /** @type {RemoteInfo & { type: 'form' }} */
  2416. /** @type {any} */
  2417. form.__.fn
  2418. );
  2419. const { data, meta, form_data } = await deserialize_binary_form(event.request);
  2420. if (action_id && !("id" in data)) {
  2421. data.id = JSON.parse(decodeURIComponent(action_id));
  2422. }
  2423. await with_request_store({ event, state }, () => fn(data, meta, form_data));
  2424. return {
  2425. type: "success",
  2426. status: 200
  2427. };
  2428. } catch (e) {
  2429. const err = normalize_error(e);
  2430. if (err instanceof Redirect) {
  2431. return {
  2432. type: "redirect",
  2433. status: err.status,
  2434. location: err.location
  2435. };
  2436. }
  2437. return {
  2438. type: "error",
  2439. error: check_incorrect_fail_use(err)
  2440. };
  2441. }
  2442. }
  2443. function get_remote_id(url) {
  2444. return url.pathname.startsWith(`${base}/${app_dir}/remote/`) && url.pathname.replace(`${base}/${app_dir}/remote/`, "");
  2445. }
  2446. function get_remote_action(url) {
  2447. return url.searchParams.get("/remote");
  2448. }
  2449. const MAX_DEPTH = 10;
  2450. async function render_page(event, event_state, page, options2, manifest, state, nodes, resolve_opts) {
  2451. if (state.depth > MAX_DEPTH) {
  2452. return text(`Not found: ${event.url.pathname}`, {
  2453. status: 404
  2454. // TODO in some cases this should be 500. not sure how to differentiate
  2455. });
  2456. }
  2457. if (is_action_json_request(event)) {
  2458. const node = await manifest._.nodes[page.leaf]();
  2459. return handle_action_json_request(event, event_state, options2, node?.server);
  2460. }
  2461. try {
  2462. const leaf_node = (
  2463. /** @type {import('types').SSRNode} */
  2464. nodes.page()
  2465. );
  2466. let status = 200;
  2467. let action_result = void 0;
  2468. if (is_action_request(event)) {
  2469. const remote_id = get_remote_action(event.url);
  2470. if (remote_id) {
  2471. action_result = await handle_remote_form_post(event, event_state, manifest, remote_id);
  2472. } else {
  2473. action_result = await handle_action_request(event, event_state, leaf_node.server);
  2474. }
  2475. if (action_result?.type === "redirect") {
  2476. return redirect_response(action_result.status, action_result.location);
  2477. }
  2478. if (action_result?.type === "error") {
  2479. status = get_status(action_result.error);
  2480. }
  2481. if (action_result?.type === "failure") {
  2482. status = action_result.status;
  2483. }
  2484. }
  2485. const should_prerender = nodes.prerender();
  2486. if (should_prerender) {
  2487. const mod = leaf_node.server;
  2488. if (mod?.actions) {
  2489. throw new Error("Cannot prerender pages with actions");
  2490. }
  2491. } else if (state.prerendering) {
  2492. return new Response(void 0, {
  2493. status: 204
  2494. });
  2495. }
  2496. state.prerender_default = should_prerender;
  2497. const should_prerender_data = nodes.should_prerender_data();
  2498. const data_pathname = add_data_suffix(event.url.pathname);
  2499. const fetched = [];
  2500. const ssr = nodes.ssr();
  2501. const csr = nodes.csr();
  2502. if (ssr === false && !(state.prerendering && should_prerender_data)) {
  2503. if (BROWSER && action_result && !event.request.headers.has("x-sveltekit-action")) ;
  2504. return await render_response({
  2505. branch: [],
  2506. fetched,
  2507. page_config: {
  2508. ssr: false,
  2509. csr
  2510. },
  2511. status,
  2512. error: null,
  2513. event,
  2514. event_state,
  2515. options: options2,
  2516. manifest,
  2517. state,
  2518. resolve_opts,
  2519. data_serializer: server_data_serializer(event, event_state, options2)
  2520. });
  2521. }
  2522. const branch = [];
  2523. let load_error = null;
  2524. const data_serializer = server_data_serializer(event, event_state, options2);
  2525. const data_serializer_json = state.prerendering && should_prerender_data ? server_data_serializer_json(event, event_state, options2) : null;
  2526. const server_promises = nodes.data.map((node, i) => {
  2527. if (load_error) {
  2528. throw load_error;
  2529. }
  2530. return Promise.resolve().then(async () => {
  2531. try {
  2532. if (node === leaf_node && action_result?.type === "error") {
  2533. throw action_result.error;
  2534. }
  2535. const server_data = await load_server_data({
  2536. event,
  2537. event_state,
  2538. state,
  2539. node,
  2540. parent: async () => {
  2541. const data = {};
  2542. for (let j = 0; j < i; j += 1) {
  2543. const parent = await server_promises[j];
  2544. if (parent) Object.assign(data, parent.data);
  2545. }
  2546. return data;
  2547. }
  2548. });
  2549. if (node) {
  2550. data_serializer.add_node(i, server_data);
  2551. }
  2552. data_serializer_json?.add_node(i, server_data);
  2553. return server_data;
  2554. } catch (e) {
  2555. load_error = /** @type {Error} */
  2556. e;
  2557. throw load_error;
  2558. }
  2559. });
  2560. });
  2561. const load_promises = nodes.data.map((node, i) => {
  2562. if (load_error) throw load_error;
  2563. return Promise.resolve().then(async () => {
  2564. try {
  2565. return await load_data({
  2566. event,
  2567. event_state,
  2568. fetched,
  2569. node,
  2570. parent: async () => {
  2571. const data = {};
  2572. for (let j = 0; j < i; j += 1) {
  2573. Object.assign(data, await load_promises[j]);
  2574. }
  2575. return data;
  2576. },
  2577. resolve_opts,
  2578. server_data_promise: server_promises[i],
  2579. state,
  2580. csr
  2581. });
  2582. } catch (e) {
  2583. load_error = /** @type {Error} */
  2584. e;
  2585. throw load_error;
  2586. }
  2587. });
  2588. });
  2589. for (const p of server_promises) p.catch(() => {
  2590. });
  2591. for (const p of load_promises) p.catch(() => {
  2592. });
  2593. for (let i = 0; i < nodes.data.length; i += 1) {
  2594. const node = nodes.data[i];
  2595. if (node) {
  2596. try {
  2597. const server_data = await server_promises[i];
  2598. const data = await load_promises[i];
  2599. branch.push({ node, server_data, data });
  2600. } catch (e) {
  2601. const err = normalize_error(e);
  2602. if (err instanceof Redirect) {
  2603. if (state.prerendering && should_prerender_data) {
  2604. const body2 = JSON.stringify({
  2605. type: "redirect",
  2606. location: err.location
  2607. });
  2608. state.prerendering.dependencies.set(data_pathname, {
  2609. response: text(body2),
  2610. body: body2
  2611. });
  2612. }
  2613. return redirect_response(err.status, err.location);
  2614. }
  2615. const status2 = get_status(err);
  2616. const error2 = await handle_error_and_jsonify(event, event_state, options2, err);
  2617. while (i--) {
  2618. if (page.errors[i]) {
  2619. const index = (
  2620. /** @type {number} */
  2621. page.errors[i]
  2622. );
  2623. const node2 = await manifest._.nodes[index]();
  2624. let j = i;
  2625. while (!branch[j]) j -= 1;
  2626. data_serializer.set_max_nodes(j + 1);
  2627. const layouts = compact(branch.slice(0, j + 1));
  2628. const nodes2 = new PageNodes(layouts.map((layout) => layout.node));
  2629. const error_branch = layouts.concat({
  2630. node: node2,
  2631. data: null,
  2632. server_data: null
  2633. });
  2634. return await render_response({
  2635. event,
  2636. event_state,
  2637. options: options2,
  2638. manifest,
  2639. state,
  2640. resolve_opts,
  2641. page_config: {
  2642. ssr: nodes2.ssr(),
  2643. csr: nodes2.csr()
  2644. },
  2645. status: status2,
  2646. error: error2,
  2647. error_components: await load_error_components(
  2648. options2,
  2649. ssr,
  2650. error_branch,
  2651. page,
  2652. manifest
  2653. ),
  2654. branch: error_branch,
  2655. fetched,
  2656. data_serializer
  2657. });
  2658. }
  2659. }
  2660. return static_error_page(options2, status2, error2.message);
  2661. }
  2662. } else {
  2663. branch.push(null);
  2664. }
  2665. }
  2666. if (state.prerendering && data_serializer_json) {
  2667. let { data, chunks } = data_serializer_json.get_data();
  2668. if (chunks) {
  2669. for await (const chunk of chunks) {
  2670. data += chunk;
  2671. }
  2672. }
  2673. state.prerendering.dependencies.set(data_pathname, {
  2674. response: text(data),
  2675. body: data
  2676. });
  2677. }
  2678. return await render_response({
  2679. event,
  2680. event_state,
  2681. options: options2,
  2682. manifest,
  2683. state,
  2684. resolve_opts,
  2685. page_config: {
  2686. csr,
  2687. ssr
  2688. },
  2689. status,
  2690. error: null,
  2691. branch: !ssr ? [] : compact(branch),
  2692. action_result,
  2693. fetched,
  2694. data_serializer: !ssr ? server_data_serializer(event, event_state, options2) : data_serializer,
  2695. error_components: await load_error_components(options2, ssr, branch, page, manifest)
  2696. });
  2697. } catch (e) {
  2698. if (e instanceof Redirect) {
  2699. return redirect_response(e.status, e.location);
  2700. }
  2701. return await respond_with_error({
  2702. event,
  2703. event_state,
  2704. options: options2,
  2705. manifest,
  2706. state,
  2707. status: e instanceof HttpError ? e.status : 500,
  2708. error: e,
  2709. resolve_opts
  2710. });
  2711. }
  2712. }
  2713. async function load_error_components(options2, ssr, branch, page, manifest) {
  2714. let error_components;
  2715. if (options2.server_error_boundaries && ssr) {
  2716. let last_idx = -1;
  2717. error_components = await Promise.all(
  2718. // eslint-disable-next-line @typescript-eslint/await-thenable
  2719. branch.map((b, i) => {
  2720. if (i === 0) return void 0;
  2721. if (!b) return null;
  2722. i--;
  2723. while (i > last_idx + 1 && page.errors[i] === void 0) i -= 1;
  2724. last_idx = i;
  2725. const idx = page.errors[i];
  2726. if (idx == null) return void 0;
  2727. return manifest._.nodes[idx]?.().then((e) => e.component?.()).catch(() => void 0);
  2728. }).filter((e) => e !== null)
  2729. );
  2730. }
  2731. return error_components;
  2732. }
  2733. function once(fn) {
  2734. let done = false;
  2735. let result;
  2736. return () => {
  2737. if (done) return result;
  2738. done = true;
  2739. return result = fn();
  2740. };
  2741. }
  2742. async function render_data(event, event_state, route, options2, manifest, state, invalidated_data_nodes, trailing_slash) {
  2743. if (!route.page) {
  2744. return new Response(void 0, {
  2745. status: 404
  2746. });
  2747. }
  2748. try {
  2749. const node_ids = [...route.page.layouts, route.page.leaf];
  2750. const invalidated = invalidated_data_nodes ?? node_ids.map(() => true);
  2751. let aborted = false;
  2752. const url = new URL(event.url);
  2753. url.pathname = normalize_path(url.pathname, trailing_slash);
  2754. const new_event = { ...event, url };
  2755. const functions = node_ids.map((n, i) => {
  2756. return once(async () => {
  2757. try {
  2758. if (aborted) {
  2759. return (
  2760. /** @type {import('types').ServerDataSkippedNode} */
  2761. {
  2762. type: "skip"
  2763. }
  2764. );
  2765. }
  2766. const node = n == void 0 ? n : await manifest._.nodes[n]();
  2767. return load_server_data({
  2768. event: new_event,
  2769. event_state,
  2770. state,
  2771. node,
  2772. parent: async () => {
  2773. const data2 = {};
  2774. for (let j = 0; j < i; j += 1) {
  2775. const parent = (
  2776. /** @type {import('types').ServerDataNode | null} */
  2777. await functions[j]()
  2778. );
  2779. if (parent) {
  2780. Object.assign(data2, parent.data);
  2781. }
  2782. }
  2783. return data2;
  2784. }
  2785. });
  2786. } catch (e) {
  2787. aborted = true;
  2788. throw e;
  2789. }
  2790. });
  2791. });
  2792. const promises = functions.map(async (fn, i) => {
  2793. if (!invalidated[i]) {
  2794. return (
  2795. /** @type {import('types').ServerDataSkippedNode} */
  2796. {
  2797. type: "skip"
  2798. }
  2799. );
  2800. }
  2801. return fn();
  2802. });
  2803. let length = promises.length;
  2804. const nodes = await Promise.all(
  2805. promises.map(
  2806. (p, i) => p.catch(async (error2) => {
  2807. if (error2 instanceof Redirect) {
  2808. throw error2;
  2809. }
  2810. length = Math.min(length, i + 1);
  2811. return (
  2812. /** @type {import('types').ServerErrorNode} */
  2813. {
  2814. type: "error",
  2815. error: await handle_error_and_jsonify(event, event_state, options2, error2),
  2816. status: error2 instanceof HttpError || error2 instanceof SvelteKitError ? error2.status : void 0
  2817. }
  2818. );
  2819. })
  2820. )
  2821. );
  2822. const data_serializer = server_data_serializer_json(event, event_state, options2);
  2823. for (let i = 0; i < nodes.length; i++) data_serializer.add_node(i, nodes[i]);
  2824. const { data, chunks } = data_serializer.get_data();
  2825. if (!chunks) {
  2826. return json_response(data);
  2827. }
  2828. return new Response(
  2829. new ReadableStream({
  2830. async start(controller) {
  2831. controller.enqueue(text_encoder.encode(data));
  2832. for await (const chunk of chunks) {
  2833. controller.enqueue(text_encoder.encode(chunk));
  2834. }
  2835. controller.close();
  2836. },
  2837. type: "bytes"
  2838. }),
  2839. {
  2840. headers: {
  2841. // we use a proprietary content type to prevent buffering.
  2842. // the `text` prefix makes it inspectable
  2843. "content-type": "text/sveltekit-data",
  2844. "cache-control": "private, no-store"
  2845. }
  2846. }
  2847. );
  2848. } catch (e) {
  2849. const error2 = normalize_error(e);
  2850. if (error2 instanceof Redirect) {
  2851. return redirect_json_response(error2);
  2852. } else {
  2853. return json_response(await handle_error_and_jsonify(event, event_state, options2, error2), 500);
  2854. }
  2855. }
  2856. }
  2857. function json_response(json2, status = 200) {
  2858. return text(typeof json2 === "string" ? json2 : JSON.stringify(json2), {
  2859. status,
  2860. headers: {
  2861. "content-type": "application/json",
  2862. "cache-control": "private, no-store"
  2863. }
  2864. });
  2865. }
  2866. function redirect_json_response(redirect) {
  2867. return json_response(
  2868. /** @type {import('types').ServerRedirectNode} */
  2869. {
  2870. type: "redirect",
  2871. location: redirect.location
  2872. }
  2873. );
  2874. }
  2875. const INVALID_COOKIE_CHARACTER_REGEX = /[\x00-\x1F\x7F()<>@,;:"/[\]?={} \t]/;
  2876. function validate_options(options2) {
  2877. if (options2?.path === void 0) {
  2878. throw new Error("You must specify a `path` when setting, deleting or serializing cookies");
  2879. }
  2880. }
  2881. function generate_cookie_key(domain, path, name) {
  2882. return `${domain || ""}${path}?${encodeURIComponent(name)}`;
  2883. }
  2884. function get_cookies(request, url) {
  2885. const header = request.headers.get("cookie") ?? "";
  2886. const initial_cookies = parse(header, { decode: (value) => value });
  2887. let normalized_url;
  2888. const new_cookies = /* @__PURE__ */ new Map();
  2889. const defaults = {
  2890. httpOnly: true,
  2891. sameSite: "lax",
  2892. secure: url.hostname === "localhost" && url.protocol === "http:" ? false : true
  2893. };
  2894. const cookies = {
  2895. // The JSDoc param annotations appearing below for get, set and delete
  2896. // are necessary to expose the `cookie` library types to
  2897. // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not
  2898. // sufficient to do so.
  2899. /**
  2900. * @param {string} name
  2901. * @param {import('cookie').CookieParseOptions} [opts]
  2902. */
  2903. get(name, opts) {
  2904. const best_match = Array.from(new_cookies.values()).filter((c) => {
  2905. return c.name === name && domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path);
  2906. }).sort((a, b) => b.options.path.length - a.options.path.length)[0];
  2907. if (best_match) {
  2908. return best_match.options.maxAge === 0 ? void 0 : best_match.value;
  2909. }
  2910. const req_cookies = parse(header, { decode: opts?.decode });
  2911. const cookie = req_cookies[name];
  2912. return cookie;
  2913. },
  2914. /**
  2915. * @param {import('cookie').CookieParseOptions} [opts]
  2916. */
  2917. getAll(opts) {
  2918. const cookies2 = parse(header, { decode: opts?.decode });
  2919. const lookup = /* @__PURE__ */ new Map();
  2920. for (const c of new_cookies.values()) {
  2921. if (domain_matches(url.hostname, c.options.domain) && path_matches(url.pathname, c.options.path)) {
  2922. const existing = lookup.get(c.name);
  2923. if (!existing || c.options.path.length > existing.options.path.length) {
  2924. lookup.set(c.name, c);
  2925. }
  2926. }
  2927. }
  2928. for (const c of lookup.values()) {
  2929. cookies2[c.name] = c.value;
  2930. }
  2931. return Object.entries(cookies2).map(([name, value]) => ({ name, value }));
  2932. },
  2933. /**
  2934. * @param {string} name
  2935. * @param {string} value
  2936. * @param {import('./page/types.js').Cookie['options']} options
  2937. */
  2938. set(name, value, options2) {
  2939. const illegal_characters = name.match(INVALID_COOKIE_CHARACTER_REGEX);
  2940. if (illegal_characters) {
  2941. console.warn(
  2942. `The cookie name "${name}" will be invalid in SvelteKit 3.0 as it contains ${illegal_characters.join(
  2943. " and "
  2944. )}. See RFC 2616 for more details https://datatracker.ietf.org/doc/html/rfc2616#section-2.2`
  2945. );
  2946. }
  2947. validate_options(options2);
  2948. set_internal(name, value, { ...defaults, ...options2 });
  2949. },
  2950. /**
  2951. * @param {string} name
  2952. * @param {import('./page/types.js').Cookie['options']} options
  2953. */
  2954. delete(name, options2) {
  2955. validate_options(options2);
  2956. cookies.set(name, "", { ...options2, maxAge: 0 });
  2957. },
  2958. /**
  2959. * @param {string} name
  2960. * @param {string} value
  2961. * @param {import('./page/types.js').Cookie['options']} options
  2962. */
  2963. serialize(name, value, options2) {
  2964. validate_options(options2);
  2965. let path = options2.path;
  2966. if (!options2.domain || options2.domain === url.hostname) {
  2967. if (!normalized_url) {
  2968. throw new Error("Cannot serialize cookies until after the route is determined");
  2969. }
  2970. path = resolve(normalized_url, path);
  2971. }
  2972. return serialize(name, value, { ...defaults, ...options2, path });
  2973. }
  2974. };
  2975. function get_cookie_header(destination, header2) {
  2976. const combined_cookies = {
  2977. // cookies sent by the user agent have lowest precedence
  2978. ...initial_cookies
  2979. };
  2980. for (const cookie of new_cookies.values()) {
  2981. if (!domain_matches(destination.hostname, cookie.options.domain)) continue;
  2982. if (!path_matches(destination.pathname, cookie.options.path)) continue;
  2983. const encoder = cookie.options.encode || encodeURIComponent;
  2984. combined_cookies[cookie.name] = encoder(cookie.value);
  2985. }
  2986. if (header2) {
  2987. const parsed = parse(header2, { decode: (value) => value });
  2988. for (const name in parsed) {
  2989. combined_cookies[name] = parsed[name];
  2990. }
  2991. }
  2992. return Object.entries(combined_cookies).map(([name, value]) => `${name}=${value}`).join("; ");
  2993. }
  2994. const internal_queue = [];
  2995. function set_internal(name, value, options2) {
  2996. if (!normalized_url) {
  2997. internal_queue.push(() => set_internal(name, value, options2));
  2998. return;
  2999. }
  3000. let path = options2.path;
  3001. if (!options2.domain || options2.domain === url.hostname) {
  3002. path = resolve(normalized_url, path);
  3003. }
  3004. const cookie_key = generate_cookie_key(options2.domain, path, name);
  3005. const cookie = { name, value, options: { ...options2, path } };
  3006. new_cookies.set(cookie_key, cookie);
  3007. }
  3008. function set_trailing_slash(trailing_slash) {
  3009. normalized_url = normalize_path(url.pathname, trailing_slash);
  3010. internal_queue.forEach((fn) => fn());
  3011. }
  3012. return { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash };
  3013. }
  3014. function domain_matches(hostname, constraint) {
  3015. if (!constraint) return true;
  3016. const normalized = constraint[0] === "." ? constraint.slice(1) : constraint;
  3017. if (hostname === normalized) return true;
  3018. return hostname.endsWith("." + normalized);
  3019. }
  3020. function path_matches(path, constraint) {
  3021. if (!constraint) return true;
  3022. const normalized = constraint.endsWith("/") ? constraint.slice(0, -1) : constraint;
  3023. if (path === normalized) return true;
  3024. return path.startsWith(normalized + "/");
  3025. }
  3026. function add_cookies_to_headers(headers2, cookies) {
  3027. for (const new_cookie of cookies) {
  3028. const { name, value, options: options2 } = new_cookie;
  3029. headers2.append("set-cookie", serialize(name, value, options2));
  3030. if (options2.path.endsWith(".html")) {
  3031. const path = add_data_suffix(options2.path);
  3032. headers2.append("set-cookie", serialize(name, value, { ...options2, path }));
  3033. }
  3034. }
  3035. }
  3036. function create_fetch({ event, options: options2, manifest, state, get_cookie_header, set_internal }) {
  3037. const server_fetch = async (info, init2) => {
  3038. const original_request = normalize_fetch_input(info, init2, event.url);
  3039. let mode = (info instanceof Request ? info.mode : init2?.mode) ?? "cors";
  3040. let credentials = (info instanceof Request ? info.credentials : init2?.credentials) ?? "same-origin";
  3041. return options2.hooks.handleFetch({
  3042. event,
  3043. request: original_request,
  3044. fetch: async (info2, init3) => {
  3045. const request = normalize_fetch_input(info2, init3, event.url);
  3046. const url = new URL(request.url);
  3047. if (!request.headers.has("origin")) {
  3048. request.headers.set("origin", event.url.origin);
  3049. }
  3050. if (info2 !== original_request) {
  3051. mode = (info2 instanceof Request ? info2.mode : init3?.mode) ?? "cors";
  3052. credentials = (info2 instanceof Request ? info2.credentials : init3?.credentials) ?? "same-origin";
  3053. }
  3054. if ((request.method === "GET" || request.method === "HEAD") && (mode === "no-cors" && url.origin !== event.url.origin || url.origin === event.url.origin)) {
  3055. request.headers.delete("origin");
  3056. }
  3057. const decoded = decodeURIComponent(url.pathname);
  3058. if (url.origin !== event.url.origin || base && decoded !== base && !decoded.startsWith(`${base}/`)) {
  3059. if (`.${url.hostname}`.endsWith(`.${event.url.hostname}`) && credentials !== "omit") {
  3060. const cookie = get_cookie_header(url, request.headers.get("cookie"));
  3061. if (cookie) request.headers.set("cookie", cookie);
  3062. }
  3063. return fetch(request);
  3064. }
  3065. const prefix = assets || base;
  3066. const filename = (decoded.startsWith(prefix) ? decoded.slice(prefix.length) : decoded).slice(1);
  3067. const filename_html = `${filename}/index.html`;
  3068. const is_asset = manifest.assets.has(filename) || filename in manifest._.server_assets;
  3069. const is_asset_html = manifest.assets.has(filename_html) || filename_html in manifest._.server_assets;
  3070. if (is_asset || is_asset_html) {
  3071. const file = is_asset ? filename : filename_html;
  3072. if (state.read) {
  3073. const type = is_asset ? manifest.mimeTypes[filename.slice(filename.lastIndexOf("."))] : "text/html";
  3074. return new Response(state.read(file), {
  3075. headers: type ? { "content-type": type } : {}
  3076. });
  3077. } else if (read_implementation && file in manifest._.server_assets) {
  3078. const length = manifest._.server_assets[file];
  3079. const type = manifest.mimeTypes[file.slice(file.lastIndexOf("."))];
  3080. return new Response(read_implementation(file), {
  3081. headers: {
  3082. "Content-Length": "" + length,
  3083. "Content-Type": type
  3084. }
  3085. });
  3086. }
  3087. return await fetch(request);
  3088. }
  3089. if (has_prerendered_path(manifest, base + decoded)) {
  3090. return await fetch(request);
  3091. }
  3092. if (credentials !== "omit") {
  3093. const cookie = get_cookie_header(url, request.headers.get("cookie"));
  3094. if (cookie) {
  3095. request.headers.set("cookie", cookie);
  3096. }
  3097. const authorization = event.request.headers.get("authorization");
  3098. if (authorization && !request.headers.has("authorization")) {
  3099. request.headers.set("authorization", authorization);
  3100. }
  3101. }
  3102. if (!request.headers.has("accept")) {
  3103. request.headers.set("accept", "*/*");
  3104. }
  3105. if (!request.headers.has("accept-language")) {
  3106. request.headers.set(
  3107. "accept-language",
  3108. /** @type {string} */
  3109. event.request.headers.get("accept-language")
  3110. );
  3111. }
  3112. const response = await internal_fetch(request, options2, manifest, state);
  3113. const set_cookie = response.headers.get("set-cookie");
  3114. if (set_cookie) {
  3115. for (const str of set_cookie_parser.splitCookiesString(set_cookie)) {
  3116. const { name, value, ...options3 } = set_cookie_parser.parseString(str, {
  3117. decodeValues: false
  3118. });
  3119. const path = options3.path ?? (url.pathname.split("/").slice(0, -1).join("/") || "/");
  3120. set_internal(name, value, {
  3121. path,
  3122. encode: (value2) => value2,
  3123. .../** @type {import('cookie').CookieSerializeOptions} */
  3124. options3
  3125. });
  3126. }
  3127. }
  3128. return response;
  3129. }
  3130. });
  3131. };
  3132. return (input, init2) => {
  3133. const response = server_fetch(input, init2);
  3134. response.catch(() => {
  3135. });
  3136. return response;
  3137. };
  3138. }
  3139. function normalize_fetch_input(info, init2, url) {
  3140. if (info instanceof Request) {
  3141. return info;
  3142. }
  3143. return new Request(typeof info === "string" ? new URL(info, url) : info, init2);
  3144. }
  3145. async function internal_fetch(request, options2, manifest, state) {
  3146. if (request.signal) {
  3147. if (request.signal.aborted) {
  3148. throw new DOMException("The operation was aborted.", "AbortError");
  3149. }
  3150. let remove_abort_listener = () => {
  3151. };
  3152. const abort_promise = new Promise((_, reject) => {
  3153. const on_abort = () => {
  3154. reject(new DOMException("The operation was aborted.", "AbortError"));
  3155. };
  3156. request.signal.addEventListener("abort", on_abort, { once: true });
  3157. remove_abort_listener = () => request.signal.removeEventListener("abort", on_abort);
  3158. });
  3159. const result = await Promise.race([
  3160. respond(request, options2, manifest, {
  3161. ...state,
  3162. depth: state.depth + 1
  3163. }),
  3164. abort_promise
  3165. ]);
  3166. remove_abort_listener();
  3167. return result;
  3168. } else {
  3169. return await respond(request, options2, manifest, {
  3170. ...state,
  3171. depth: state.depth + 1
  3172. });
  3173. }
  3174. }
  3175. let body;
  3176. let etag;
  3177. let headers;
  3178. function get_public_env(request) {
  3179. body ??= `export const env=${JSON.stringify(public_env)}`;
  3180. etag ??= `W/${Date.now()}`;
  3181. headers ??= new Headers({
  3182. "content-type": "application/javascript; charset=utf-8",
  3183. etag
  3184. });
  3185. if (request.headers.get("if-none-match") === etag) {
  3186. return new Response(void 0, { status: 304, headers });
  3187. }
  3188. return new Response(body, { headers });
  3189. }
  3190. const default_transform = ({ html }) => html;
  3191. const default_filter = () => false;
  3192. const default_preload = ({ type }) => type === "js" || type === "css";
  3193. const page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "POST"]);
  3194. const allowed_page_methods = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
  3195. let warned_on_devtools_json_request = false;
  3196. const respond = propagate_context(internal_respond);
  3197. async function internal_respond(request, options2, manifest, state) {
  3198. const url = new URL(request.url);
  3199. const is_route_resolution_request = has_resolution_suffix(url.pathname);
  3200. const is_data_request = has_data_suffix(url.pathname);
  3201. const remote_id = get_remote_id(url);
  3202. {
  3203. const request_origin = request.headers.get("origin");
  3204. if (remote_id) {
  3205. if (request.method !== "GET" && request_origin !== url.origin) {
  3206. const message = "Cross-site remote requests are forbidden";
  3207. return json({ message }, { status: 403 });
  3208. }
  3209. } else if (options2.csrf_check_origin) {
  3210. const forbidden = is_form_content_type(request) && (request.method === "POST" || request.method === "PUT" || request.method === "PATCH" || request.method === "DELETE") && request_origin !== url.origin && (!request_origin || !options2.csrf_trusted_origins.includes(request_origin));
  3211. if (forbidden) {
  3212. const message = `Cross-site ${request.method} form submissions are forbidden`;
  3213. const opts = { status: 403 };
  3214. if (request.headers.get("accept") === "application/json") {
  3215. return json({ message }, opts);
  3216. }
  3217. return text(message, opts);
  3218. }
  3219. }
  3220. }
  3221. if (options2.hash_routing && url.pathname !== base + "/" && url.pathname !== "/[fallback]") {
  3222. return text("Not found", { status: 404 });
  3223. }
  3224. let invalidated_data_nodes;
  3225. if (is_route_resolution_request) {
  3226. url.pathname = strip_resolution_suffix(url.pathname);
  3227. } else if (is_data_request) {
  3228. url.pathname = strip_data_suffix(url.pathname) + (url.searchParams.get(TRAILING_SLASH_PARAM) === "1" ? "/" : "") || "/";
  3229. url.searchParams.delete(TRAILING_SLASH_PARAM);
  3230. invalidated_data_nodes = url.searchParams.get(INVALIDATED_PARAM)?.split("").map((node) => node === "1");
  3231. url.searchParams.delete(INVALIDATED_PARAM);
  3232. } else if (remote_id) {
  3233. url.pathname = request.headers.get("x-sveltekit-pathname") ?? base;
  3234. url.search = request.headers.get("x-sveltekit-search") ?? "";
  3235. }
  3236. const headers2 = {};
  3237. const { cookies, new_cookies, get_cookie_header, set_internal, set_trailing_slash } = get_cookies(
  3238. request,
  3239. url
  3240. );
  3241. const event_state = {
  3242. prerendering: state.prerendering,
  3243. transport: options2.hooks.transport,
  3244. handleValidationError: options2.hooks.handleValidationError,
  3245. tracing: {
  3246. record_span
  3247. },
  3248. is_in_remote_function: false
  3249. };
  3250. const event = {
  3251. cookies,
  3252. // @ts-expect-error `fetch` needs to be created after the `event` itself
  3253. fetch: null,
  3254. getClientAddress: state.getClientAddress || (() => {
  3255. throw new Error(
  3256. `${"@sveltejs/adapter-static"} does not specify getClientAddress. Please raise an issue`
  3257. );
  3258. }),
  3259. locals: {},
  3260. params: {},
  3261. platform: state.platform,
  3262. request,
  3263. route: { id: null },
  3264. setHeaders: (new_headers) => {
  3265. for (const key2 in new_headers) {
  3266. const lower = key2.toLowerCase();
  3267. const value = new_headers[key2];
  3268. if (lower === "set-cookie") {
  3269. throw new Error(
  3270. "Use `event.cookies.set(name, value, options)` instead of `event.setHeaders` to set cookies"
  3271. );
  3272. } else if (lower in headers2) {
  3273. if (lower === "server-timing") {
  3274. headers2[lower] += ", " + value;
  3275. } else {
  3276. throw new Error(`"${key2}" header is already set`);
  3277. }
  3278. } else {
  3279. headers2[lower] = value;
  3280. if (state.prerendering && lower === "cache-control") {
  3281. state.prerendering.cache = /** @type {string} */
  3282. value;
  3283. }
  3284. }
  3285. }
  3286. },
  3287. url,
  3288. isDataRequest: is_data_request,
  3289. isSubRequest: state.depth > 0,
  3290. isRemoteRequest: !!remote_id
  3291. };
  3292. event.fetch = create_fetch({
  3293. event,
  3294. options: options2,
  3295. manifest,
  3296. state,
  3297. get_cookie_header,
  3298. set_internal
  3299. });
  3300. if (state.emulator?.platform) {
  3301. event.platform = await state.emulator.platform({
  3302. config: {},
  3303. prerender: !!state.prerendering?.fallback
  3304. });
  3305. }
  3306. let resolved_path = url.pathname;
  3307. if (!remote_id) {
  3308. const prerendering_reroute_state = state.prerendering?.inside_reroute;
  3309. try {
  3310. if (state.prerendering) state.prerendering.inside_reroute = true;
  3311. resolved_path = await options2.hooks.reroute({ url: new URL(url), fetch: event.fetch }) ?? url.pathname;
  3312. } catch {
  3313. return text("Internal Server Error", {
  3314. status: 500
  3315. });
  3316. } finally {
  3317. if (state.prerendering) state.prerendering.inside_reroute = prerendering_reroute_state;
  3318. }
  3319. }
  3320. try {
  3321. resolved_path = decode_pathname(resolved_path);
  3322. } catch {
  3323. return text("Malformed URI", { status: 400 });
  3324. }
  3325. if (
  3326. // the resolved path has been decoded so it should be compared to the decoded url pathname
  3327. resolved_path !== decode_pathname(url.pathname) && !state.prerendering?.fallback && has_prerendered_path(manifest, resolved_path)
  3328. ) {
  3329. const url2 = new URL(request.url);
  3330. url2.pathname = is_data_request ? add_data_suffix(resolved_path) : is_route_resolution_request ? add_resolution_suffix(resolved_path) : resolved_path;
  3331. try {
  3332. const response = await fetch(url2, request);
  3333. const headers22 = new Headers(response.headers);
  3334. if (headers22.has("content-encoding")) {
  3335. headers22.delete("content-encoding");
  3336. headers22.delete("content-length");
  3337. }
  3338. return new Response(response.body, {
  3339. headers: headers22,
  3340. status: response.status,
  3341. statusText: response.statusText
  3342. });
  3343. } catch (error2) {
  3344. return await handle_fatal_error(event, event_state, options2, error2);
  3345. }
  3346. }
  3347. let route = null;
  3348. if (base && !state.prerendering?.fallback) {
  3349. if (!resolved_path.startsWith(base)) {
  3350. return text("Not found", { status: 404 });
  3351. }
  3352. resolved_path = resolved_path.slice(base.length) || "/";
  3353. }
  3354. if (is_route_resolution_request) {
  3355. return resolve_route(resolved_path, new URL(request.url), manifest);
  3356. }
  3357. if (resolved_path === `/${app_dir}/env.js`) {
  3358. return get_public_env(request);
  3359. }
  3360. if (!remote_id && resolved_path.startsWith(`/${app_dir}`)) {
  3361. const headers22 = new Headers();
  3362. headers22.set("cache-control", "public, max-age=0, must-revalidate");
  3363. return text("Not found", { status: 404, headers: headers22 });
  3364. }
  3365. if (!state.prerendering?.fallback) {
  3366. const matchers = await manifest._.matchers();
  3367. const result = find_route(resolved_path, manifest._.routes, matchers);
  3368. if (result) {
  3369. route = result.route;
  3370. event.route = { id: route.id };
  3371. event.params = result.params;
  3372. }
  3373. }
  3374. let resolve_opts = {
  3375. transformPageChunk: default_transform,
  3376. filterSerializedResponseHeaders: default_filter,
  3377. preload: default_preload
  3378. };
  3379. let trailing_slash = "never";
  3380. try {
  3381. const page_nodes = route?.page ? new PageNodes(await load_page_nodes(route.page, manifest)) : void 0;
  3382. if (route && !remote_id) {
  3383. if (url.pathname === base || url.pathname === base + "/") {
  3384. trailing_slash = "always";
  3385. } else if (page_nodes) {
  3386. if (BROWSER) ;
  3387. trailing_slash = page_nodes.trailing_slash();
  3388. } else if (route.endpoint) {
  3389. const node = await route.endpoint();
  3390. trailing_slash = node.trailingSlash ?? "never";
  3391. if (BROWSER) ;
  3392. }
  3393. if (!is_data_request) {
  3394. const normalized = normalize_path(url.pathname, trailing_slash);
  3395. if (normalized !== url.pathname && !state.prerendering?.fallback) {
  3396. return new Response(void 0, {
  3397. status: 308,
  3398. headers: {
  3399. "x-sveltekit-normalize": "1",
  3400. location: (
  3401. // ensure paths starting with '//' are not treated as protocol-relative
  3402. (normalized.startsWith("//") ? url.origin + normalized : normalized) + (url.search === "?" ? "" : url.search)
  3403. )
  3404. }
  3405. });
  3406. }
  3407. }
  3408. if (state.before_handle || state.emulator?.platform) {
  3409. let config = {};
  3410. let prerender = false;
  3411. if (route.endpoint) {
  3412. const node = await route.endpoint();
  3413. config = node.config ?? config;
  3414. prerender = node.prerender ?? prerender;
  3415. } else if (page_nodes) {
  3416. config = page_nodes.get_config() ?? config;
  3417. prerender = page_nodes.prerender();
  3418. }
  3419. if (state.before_handle) {
  3420. state.before_handle(event, config, prerender);
  3421. }
  3422. if (state.emulator?.platform) {
  3423. event.platform = await state.emulator.platform({ config, prerender });
  3424. }
  3425. }
  3426. }
  3427. set_trailing_slash(trailing_slash);
  3428. if (state.prerendering && !state.prerendering.fallback && !state.prerendering.inside_reroute) {
  3429. disable_search(url);
  3430. }
  3431. const response = await record_span({
  3432. name: "sveltekit.handle.root",
  3433. attributes: {
  3434. "http.route": event.route.id || "unknown",
  3435. "http.method": event.request.method,
  3436. "http.url": event.url.href,
  3437. "sveltekit.is_data_request": is_data_request,
  3438. "sveltekit.is_sub_request": event.isSubRequest
  3439. },
  3440. fn: async (root_span) => {
  3441. const traced_event = {
  3442. ...event,
  3443. tracing: {
  3444. enabled: false,
  3445. root: root_span,
  3446. current: root_span
  3447. }
  3448. };
  3449. event_state.allows_commands = MUTATIVE_METHODS.includes(request.method);
  3450. return await with_request_store(
  3451. { event: traced_event, state: event_state },
  3452. () => options2.hooks.handle({
  3453. event: traced_event,
  3454. resolve: (event2, opts) => {
  3455. return record_span({
  3456. name: "sveltekit.resolve",
  3457. attributes: {
  3458. "http.route": event2.route.id || "unknown"
  3459. },
  3460. fn: (resolve_span) => {
  3461. return with_request_store(
  3462. null,
  3463. () => resolve2(merge_tracing(event2, resolve_span), page_nodes, opts).then(
  3464. (response2) => {
  3465. for (const key2 in headers2) {
  3466. const value = headers2[key2];
  3467. response2.headers.set(
  3468. key2,
  3469. /** @type {string} */
  3470. value
  3471. );
  3472. }
  3473. add_cookies_to_headers(response2.headers, new_cookies.values());
  3474. if (state.prerendering && event2.route.id !== null) {
  3475. response2.headers.set("x-sveltekit-routeid", encodeURI(event2.route.id));
  3476. }
  3477. resolve_span.setAttributes({
  3478. "http.response.status_code": response2.status,
  3479. "http.response.body.size": response2.headers.get("content-length") || "unknown"
  3480. });
  3481. return response2;
  3482. }
  3483. )
  3484. );
  3485. }
  3486. });
  3487. }
  3488. })
  3489. );
  3490. }
  3491. });
  3492. if (response.status === 200 && response.headers.has("etag")) {
  3493. let if_none_match_value = request.headers.get("if-none-match");
  3494. if (if_none_match_value?.startsWith('W/"')) {
  3495. if_none_match_value = if_none_match_value.substring(2);
  3496. }
  3497. const etag2 = (
  3498. /** @type {string} */
  3499. response.headers.get("etag")
  3500. );
  3501. if (if_none_match_value === etag2) {
  3502. const headers22 = new Headers({ etag: etag2 });
  3503. for (const key2 of [
  3504. "cache-control",
  3505. "content-location",
  3506. "date",
  3507. "expires",
  3508. "vary",
  3509. "set-cookie"
  3510. ]) {
  3511. const value = response.headers.get(key2);
  3512. if (value) headers22.set(key2, value);
  3513. }
  3514. return new Response(void 0, {
  3515. status: 304,
  3516. headers: headers22
  3517. });
  3518. }
  3519. }
  3520. if (is_data_request && response.status >= 300 && response.status <= 308) {
  3521. const location = response.headers.get("location");
  3522. if (location) {
  3523. return redirect_json_response(new Redirect(
  3524. /** @type {any} */
  3525. response.status,
  3526. location
  3527. ));
  3528. }
  3529. }
  3530. return response;
  3531. } catch (e) {
  3532. if (e instanceof Redirect) {
  3533. const response = is_data_request || remote_id ? redirect_json_response(e) : route?.page && is_action_json_request(event) ? action_json_redirect(e) : redirect_response(e.status, e.location);
  3534. add_cookies_to_headers(response.headers, new_cookies.values());
  3535. return response;
  3536. }
  3537. return await handle_fatal_error(event, event_state, options2, e);
  3538. }
  3539. async function resolve2(event2, page_nodes, opts) {
  3540. try {
  3541. if (opts) {
  3542. resolve_opts = {
  3543. transformPageChunk: opts.transformPageChunk || default_transform,
  3544. filterSerializedResponseHeaders: opts.filterSerializedResponseHeaders || default_filter,
  3545. preload: opts.preload || default_preload
  3546. };
  3547. }
  3548. if (options2.hash_routing || state.prerendering?.fallback) {
  3549. return await render_response({
  3550. event: event2,
  3551. event_state,
  3552. options: options2,
  3553. manifest,
  3554. state,
  3555. page_config: { ssr: false, csr: true },
  3556. status: 200,
  3557. error: null,
  3558. branch: [],
  3559. fetched: [],
  3560. resolve_opts,
  3561. data_serializer: server_data_serializer(event2, event_state, options2)
  3562. });
  3563. }
  3564. if (remote_id) {
  3565. return await handle_remote_call(event2, event_state, options2, manifest, remote_id);
  3566. }
  3567. if (route) {
  3568. const method = (
  3569. /** @type {import('types').HttpMethod} */
  3570. event2.request.method
  3571. );
  3572. let response2;
  3573. if (is_data_request) {
  3574. response2 = await render_data(
  3575. event2,
  3576. event_state,
  3577. route,
  3578. options2,
  3579. manifest,
  3580. state,
  3581. invalidated_data_nodes,
  3582. trailing_slash
  3583. );
  3584. } else if (route.endpoint && (!route.page || is_endpoint_request(event2))) {
  3585. response2 = await render_endpoint(event2, event_state, await route.endpoint(), state);
  3586. } else if (route.page) {
  3587. if (!page_nodes) {
  3588. throw new Error("page_nodes not found. This should never happen");
  3589. } else if (page_methods.has(method)) {
  3590. response2 = await render_page(
  3591. event2,
  3592. event_state,
  3593. route.page,
  3594. options2,
  3595. manifest,
  3596. state,
  3597. page_nodes,
  3598. resolve_opts
  3599. );
  3600. } else {
  3601. const allowed_methods = new Set(allowed_page_methods);
  3602. const node = await manifest._.nodes[route.page.leaf]();
  3603. if (node?.server?.actions) {
  3604. allowed_methods.add("POST");
  3605. }
  3606. if (method === "OPTIONS") {
  3607. response2 = new Response(null, {
  3608. status: 204,
  3609. headers: {
  3610. allow: Array.from(allowed_methods.values()).join(", ")
  3611. }
  3612. });
  3613. } else {
  3614. const mod = [...allowed_methods].reduce(
  3615. (acc, curr) => {
  3616. acc[curr] = true;
  3617. return acc;
  3618. },
  3619. /** @type {Record<string, any>} */
  3620. {}
  3621. );
  3622. response2 = method_not_allowed(mod, method);
  3623. }
  3624. }
  3625. } else {
  3626. throw new Error("Route is neither page nor endpoint. This should never happen");
  3627. }
  3628. if (request.method === "GET" && route.page && route.endpoint) {
  3629. const vary = response2.headers.get("vary")?.split(",")?.map((v) => v.trim().toLowerCase());
  3630. if (!(vary?.includes("accept") || vary?.includes("*"))) {
  3631. response2 = new Response(response2.body, {
  3632. status: response2.status,
  3633. statusText: response2.statusText,
  3634. headers: new Headers(response2.headers)
  3635. });
  3636. response2.headers.append("Vary", "Accept");
  3637. }
  3638. }
  3639. return response2;
  3640. }
  3641. if (state.error && event2.isSubRequest) {
  3642. const headers22 = new Headers(request.headers);
  3643. headers22.set("x-sveltekit-error", "true");
  3644. return await fetch(request, { headers: headers22 });
  3645. }
  3646. if (state.error) {
  3647. return text("Internal Server Error", {
  3648. status: 500
  3649. });
  3650. }
  3651. if (state.depth === 0) {
  3652. if (BROWSER && event2.url.pathname === "/.well-known/appspecific/com.chrome.devtools.json") ;
  3653. return await respond_with_error({
  3654. event: event2,
  3655. event_state,
  3656. options: options2,
  3657. manifest,
  3658. state,
  3659. status: 404,
  3660. error: new SvelteKitError(404, "Not Found", `Not found: ${event2.url.pathname}`),
  3661. resolve_opts
  3662. });
  3663. }
  3664. if (state.prerendering) {
  3665. return text("not found", { status: 404 });
  3666. }
  3667. const response = await fetch(request);
  3668. return new Response(response.body, response);
  3669. } catch (e) {
  3670. return await handle_fatal_error(event2, event_state, options2, e);
  3671. } finally {
  3672. event2.cookies.set = () => {
  3673. throw new Error("Cannot use `cookies.set(...)` after the response has been generated");
  3674. };
  3675. event2.setHeaders = () => {
  3676. throw new Error("Cannot use `setHeaders(...)` after the response has been generated");
  3677. };
  3678. }
  3679. }
  3680. }
  3681. function load_page_nodes(page, manifest) {
  3682. return Promise.all([
  3683. // we use == here rather than === because [undefined] serializes as "[null]"
  3684. ...page.layouts.map((n) => n == void 0 ? n : manifest._.nodes[n]()),
  3685. manifest._.nodes[page.leaf]()
  3686. ]);
  3687. }
  3688. function propagate_context(fn) {
  3689. return async (req, ...rest) => {
  3690. {
  3691. return fn(req, ...rest);
  3692. }
  3693. };
  3694. }
  3695. function filter_env(env, allowed, disallowed) {
  3696. return Object.fromEntries(
  3697. Object.entries(env).filter(
  3698. ([k]) => k.startsWith(allowed) && (disallowed === "" || !k.startsWith(disallowed))
  3699. )
  3700. );
  3701. }
  3702. function set_app(value) {
  3703. }
  3704. let init_promise;
  3705. let current = null;
  3706. class Server {
  3707. /** @type {import('types').SSROptions} */
  3708. #options;
  3709. /** @type {import('@sveltejs/kit').SSRManifest} */
  3710. #manifest;
  3711. /** @param {import('@sveltejs/kit').SSRManifest} manifest */
  3712. constructor(manifest) {
  3713. this.#options = options;
  3714. this.#manifest = manifest;
  3715. if (IN_WEBCONTAINER) {
  3716. const respond2 = this.respond.bind(this);
  3717. this.respond = async (...args) => {
  3718. const { promise, resolve: resolve2 } = (
  3719. /** @type {PromiseWithResolvers<void>} */
  3720. with_resolvers()
  3721. );
  3722. const previous = current;
  3723. current = promise;
  3724. await previous;
  3725. return respond2(...args).finally(resolve2);
  3726. };
  3727. }
  3728. }
  3729. /**
  3730. * @param {import('@sveltejs/kit').ServerInitOptions} opts
  3731. */
  3732. async init({ env, read }) {
  3733. const { env_public_prefix, env_private_prefix } = this.#options;
  3734. set_private_env(filter_env(env, env_private_prefix, env_public_prefix));
  3735. set_public_env(filter_env(env, env_public_prefix, env_private_prefix));
  3736. if (read) {
  3737. const wrapped_read = (file) => {
  3738. const result = read(file);
  3739. if (result instanceof ReadableStream) {
  3740. return result;
  3741. } else {
  3742. return new ReadableStream({
  3743. async start(controller) {
  3744. try {
  3745. const stream = await Promise.resolve(result);
  3746. if (!stream) {
  3747. controller.close();
  3748. return;
  3749. }
  3750. const reader = stream.getReader();
  3751. while (true) {
  3752. const { done, value } = await reader.read();
  3753. if (done) break;
  3754. controller.enqueue(value);
  3755. }
  3756. controller.close();
  3757. } catch (error2) {
  3758. controller.error(error2);
  3759. }
  3760. }
  3761. });
  3762. }
  3763. };
  3764. set_read_implementation(wrapped_read);
  3765. }
  3766. await (init_promise ??= (async () => {
  3767. try {
  3768. const module = await get_hooks();
  3769. this.#options.hooks = {
  3770. handle: module.handle || (({ event, resolve: resolve2 }) => resolve2(event)),
  3771. handleError: module.handleError || (({ status, error: error2, event }) => {
  3772. const error_message = format_server_error(
  3773. status,
  3774. /** @type {Error} */
  3775. error2,
  3776. event
  3777. );
  3778. console.error(error_message);
  3779. }),
  3780. handleFetch: module.handleFetch || (({ request, fetch: fetch2 }) => fetch2(request)),
  3781. handleValidationError: module.handleValidationError || (({ issues }) => {
  3782. console.error("Remote function schema validation failed:", issues);
  3783. return { message: "Bad Request" };
  3784. }),
  3785. reroute: module.reroute || (() => {
  3786. }),
  3787. transport: module.transport || {}
  3788. };
  3789. set_app({
  3790. decoders: module.transport ? Object.fromEntries(Object.entries(module.transport).map(([k, v]) => [k, v.decode])) : {}
  3791. });
  3792. if (module.init) {
  3793. await module.init();
  3794. }
  3795. } catch (e) {
  3796. {
  3797. throw e;
  3798. }
  3799. }
  3800. })());
  3801. }
  3802. /**
  3803. * @param {Request} request
  3804. * @param {import('types').RequestOptions} options
  3805. */
  3806. async respond(request, options2) {
  3807. return respond(request, this.#options, this.#manifest, {
  3808. ...options2,
  3809. error: false,
  3810. depth: 0
  3811. });
  3812. }
  3813. }
  3814. export {
  3815. Server
  3816. };