gemi 0.224.0 → 0.225.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/ai/providers/call.d.ts.map +1 -1
  3. package/dist/ai/testing/index.js +1 -1
  4. package/dist/bin/http-client/model.d.ts +1 -1
  5. package/dist/bin/http-client/model.d.ts.map +1 -1
  6. package/dist/bin/http-client/patch.d.ts +11 -0
  7. package/dist/bin/http-client/patch.d.ts.map +1 -0
  8. package/dist/bin/http-client/render.d.ts +3 -3
  9. package/dist/bin/http-client/render.d.ts.map +1 -1
  10. package/dist/{chunk-qnag7887.js → chunk-8pz8yzax.js} +2 -2
  11. package/dist/{chunk-qnag7887.js.map → chunk-8pz8yzax.js.map} +3 -3
  12. package/dist/{chunk-ftq3tapd.js → chunk-dgy6pf2h.js} +1 -1
  13. package/dist/{chunk-9yascc81.js → chunk-dpmvvwts.js} +3 -3
  14. package/dist/{chunk-9yascc81.js.map → chunk-dpmvvwts.js.map} +3 -3
  15. package/dist/{chunk-39kzdd32.js → chunk-jychsmhf.js} +2 -2
  16. package/dist/{chunk-39kzdd32.js.map → chunk-jychsmhf.js.map} +1 -1
  17. package/dist/{chunk-qgfwa4jm.js → chunk-knfvx96p.js} +1 -1
  18. package/dist/{chunk-3k4p9agd.js → chunk-mdg8g8h2.js} +22 -22
  19. package/dist/{chunk-3k4p9agd.js.map → chunk-mdg8g8h2.js.map} +8 -7
  20. package/dist/{chunk-n2epez2r.js → chunk-rdfatx17.js} +1 -1
  21. package/dist/chunks/{RealtimeClient-CuTFz0v1.js → RealtimeClient-C5Zh3fD6.js} +2 -2
  22. package/dist/chunks/{RealtimeClient-CuTFz0v1.js.map → RealtimeClient-C5Zh3fD6.js.map} +1 -1
  23. package/dist/chunks/{ThemeProvider-BO3sQkWl.js → ThemeProvider-bbbE-N3t.js} +5 -3
  24. package/dist/chunks/ThemeProvider-bbbE-N3t.js.map +1 -0
  25. package/dist/chunks/{fetchFileRequest-CrKd0rD5.js → fetchFileRequest-JXhnEi-R.js} +2 -2
  26. package/dist/chunks/{fetchFileRequest-CrKd0rD5.js.map → fetchFileRequest-JXhnEi-R.js.map} +1 -1
  27. package/dist/chunks/{live-BCCfTb28.js → live-CApTRvmK.js} +3 -3
  28. package/dist/chunks/{live-BCCfTb28.js.map → live-CApTRvmK.js.map} +1 -1
  29. package/dist/chunks/{mutationExtras-cPXZS6Hf.js → mutationExtras-C2qSSZ2Q.js} +34 -3
  30. package/dist/chunks/mutationExtras-C2qSSZ2Q.js.map +1 -0
  31. package/dist/chunks/{subscriptionStream-CRrAISl8.js → subscriptionStream-DQLW7dTW.js} +2 -2
  32. package/dist/chunks/{subscriptionStream-CRrAISl8.js.map → subscriptionStream-DQLW7dTW.js.map} +1 -1
  33. package/dist/client/QueryManagerContext.d.ts +2 -0
  34. package/dist/client/QueryManagerContext.d.ts.map +1 -1
  35. package/dist/client/index.d.ts +2 -1
  36. package/dist/client/index.d.ts.map +1 -1
  37. package/dist/client/index.js +63 -8
  38. package/dist/client/index.js.map +1 -1
  39. package/dist/client/islands.d.ts.map +1 -1
  40. package/dist/client/mutationExtras.d.ts +1 -1
  41. package/dist/client/mutationExtras.d.ts.map +1 -1
  42. package/dist/client/queryUpdates.d.ts +8 -0
  43. package/dist/client/queryUpdates.d.ts.map +1 -1
  44. package/dist/client/useInvalidate.d.ts +13 -0
  45. package/dist/client/useInvalidate.d.ts.map +1 -0
  46. package/dist/client/useMutation.d.ts +17 -0
  47. package/dist/client/useMutation.d.ts.map +1 -1
  48. package/dist/facades/Prefetch.d.ts +22 -0
  49. package/dist/facades/Prefetch.d.ts.map +1 -1
  50. package/dist/facades/index.js +1 -1
  51. package/dist/http/index.js +1 -1
  52. package/dist/i18n/index.js +1 -1
  53. package/dist/kernel/index.js +1 -1
  54. package/dist/server/index.js +1 -1
  55. package/dist/services/index.js +1 -1
  56. package/dist/services/router/ServerQueryStore.d.ts +8 -0
  57. package/dist/services/router/ServerQueryStore.d.ts.map +1 -1
  58. package/dist/testing/index.js +2 -2
  59. package/dist/utils/invalidation.d.ts +16 -0
  60. package/dist/utils/invalidation.d.ts.map +1 -0
  61. package/package.json +1 -1
  62. package/dist/chunks/ThemeProvider-BO3sQkWl.js.map +0 -1
  63. package/dist/chunks/mutationExtras-cPXZS6Hf.js.map +0 -1
  64. /package/dist/{chunk-ftq3tapd.js.map → chunk-dgy6pf2h.js.map} +0 -0
  65. /package/dist/{chunk-qgfwa4jm.js.map → chunk-knfvx96p.js.map} +0 -0
  66. /package/dist/{chunk-n2epez2r.js.map → chunk-rdfatx17.js.map} +0 -0
@@ -1,51 +1,51 @@
1
1
  // @bun
2
- import{Sh as HF}from"./chunk-j9abwrkv.js";import{ki as MF}from"./chunk-4v5nwqw6.js";import{Bi as Z3,Ci as Z8,Di as eW,Ei as E2,Fi as u,Hi as x8,Ii as b$,Ji as d2,Ki as R2,Li as k2,Mi as X6,Ni as A,Oi as KW,Pi as i8,Qi as LZ,Ri as C8,Si as D6,Ui as R$,Vi as h,Wi as n4,dj as O6,jj as L6,li as B3,pi as SB,qi as Q9,ri as B9,rj as E1,si as I8,ti as P8,wi as N8,xi as K8,xj as rG,yi as IB,yj as XZ,zi as hW,zj as GZ}from"./chunk-zcmz311y.js";import{Bj as o1,Cj as q0,Dj as t1,Ej as V9}from"./chunk-h1wmpa03.js";import{Fj as WZ,Gj as $2,Kj as ZY,Lj as J8,Mj as N}from"./chunk-t586p2g2.js";import{Tj as pG,Wj as i3}from"./chunk-2y0nr525.js";import{_j as DY,bk as tB}from"./chunk-p4v71qfx.js";import{tk as E$,yk as a1}from"./chunk-anc5v266.js";import{Mk as KG}from"./chunk-wy82t7mz.js";import{Nk as QZ,Qk as oB,al as e3}from"./chunk-tac25cnj.js";import{cl as M$}from"./chunk-0k2r6bep.js";import{dl as B6,el as $$,fl as g$,gl as O8,hl as VF,jl as g5,kl as UF,ul as L8,wl as DF,xl as OF,yl as LF}from"./chunk-0av1gyns.js";import{Nl as y$}from"./chunk-zmt5kdpb.js";import{Sl as cW,Xl as dW}from"./chunk-rat2827k.js";import{cm as pW,hm as d}from"./chunk-yj7pbbnm.js";import{im as $3,lm as H}from"./chunk-37209psn.js";import{tm as fW}from"./chunk-swmf6w3z.js";import{Im as SW}from"./chunk-5mrtgr7q.js";import{Jm as Y8,Lm as bB}from"./chunk-55btq9c7.js";import{Qm as lW}from"./chunk-3dkv4989.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var H2=Symbol.for("gemi.HttpResponse"),xF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[H2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return M2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!xF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return M2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function M2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[H2]===!0}function CF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function j6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function AF($){return"total"in $&&"partial"in $&&"body"in $}function T2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function z3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":K8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function SF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(AF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function _8($,Z){if($ instanceof Response)return $;if(!$)return T2();let J=await SF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return T2()}let{range:G}=Z;if(G){if(z<=0)return z3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=P8(G,z);if(!B)return z3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",N8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",j6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var bF=["content-type"];var P2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function EF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function X3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!EF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!P2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!P2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function K2($,Z){return $.origins==="*"||$.origins.includes(Z)}function RF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function _2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),RF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function I2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function N2($,Z,J){if(Z.origins!=="*")I2($,["Origin"]);if(!J||!K2(Z,J))return;if(_2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function x2($,Z,J){let W=J.headers.get("Origin");try{return N2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return N2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function C2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function A2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(I2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!K2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??bF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(_2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function kF($){return Y6($)}function S2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!kF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return S2(Z[this.methodName].bind(Z),$)}return S2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,`a ${this.method} route`),this}}class w2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:X3($,"a proxy route"),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of E2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(k2($.rawRequest))throw new x8(R2($.rawRequest));throw J}}}class f2{constructor(...$){return new n(...$)}}class q2 extends n{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=I8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await _8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof C8)return z3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class v2{constructor(...$){return new q2(...$)}}class g2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new g2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${b2($)}.`);return wF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${b2($)}.`);return fF($)}file($,Z){return new f2("GET",$,Z)}stream($,Z){return new v2("GET",$,Z)}proxy($,Z={}){return new w2($,Z)}}function b2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function wF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function fF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var qF=/^[A-Za-z0-9_-]+$/,vF=/^:[A-Za-z_][A-Za-z0-9_]*$/,y2=/^[A-Za-z0-9_-]{1,128}$/,gF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function m2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function VZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(vF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!qF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function G3($,Z={}){let J=VZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!y2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function A8($){if(VZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function h2($){if(typeof $!=="string"||$.length===0||$.length>64||!gF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function p2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&y2.test(W[j]))}var U0="user";function UZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return G3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class G6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??b$("50mb"):b$(Z);return X6(this.req.rawRequest,J),{}}}function yF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function mF($){return{"body-limit":G6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:b$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=b$($.uploadBodyLimit??"50mb"),this.builtinAliases=mF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||d2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;X6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of yF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:c2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:c2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await hF(W.slice(j+1)),z}return Y})()}}function c2($){return $?.runsOnRefusal===!0}async function hF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class Q6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class s2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{uF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!n2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=G3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return N.exit(()=>B6.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await u2(X);if(!Q)return{ok:!1,code:"denied"};if(j=UZ(Q),Y.visibility==="private"&&Y.authorizer){if(await l2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await l2(Y.authorizer,X,z):await u2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(dF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function pF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;o2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function n2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function u2($){if(!N.getStore().user&&S$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function l2($,Z,J){if(cF($))return new $().authorize(Z,J);return $(Z,J)}function cF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function dF($){return $?.kind===o1||a1($)||E$($)}var i2=new WeakSet;function uF($){if(i2.has($))return;o2($),i2.add($)}function o2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!n2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=VZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(lF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function lF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class S8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class F6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class b8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function iF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function sF($,Z){let J=iF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class a2{static __brand="McpRouter";routes={};scopes;param($){return new S8($.as,$.input,$.bind)}fromTool($,Z={}){return new b8($,Z)}fromApiRoute($,Z,J){return new F6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...P}=Y[U],K=O??(D?sF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...P,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};V[K]=new F6($,Z,C)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class E8 extends q0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new E8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new E8($,Z)}}class t2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function R8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",j6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class r2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function e2($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class $9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=e2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class Z9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=e2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new $9($,Z)}file($){return new r2($)}redirect($){return new t2($)}layout($,Z,J){return new Z9($,Z,J)}}function nF($){return $}function oF(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function DZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function k8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function aF($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(d).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function tF($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function V6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=aF($,!W);if(W||!tF(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class J9 extends Z0{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(E),J);if(!W)throw new R$({redirectTo:V6(J,$)});return Z.setUser(W),{}}}var f8="gemi_same_site",w8="private, no-cache, no-store, max-age=0, must-revalidate";class U6 extends Z0{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(f8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(f8,"1"),new W9(`${W.pathname}${W.search}`)}}class W9 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=rF($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":w8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":w8}},viewData:{status:200,data:{},headers:{"Cache-Control":w8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function rF($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class Y9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var j9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class z9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...j9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...j9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var eF="Rate limit exceeded";class r1 extends q0{result;retryAfter;constructor($,Z=eF){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?q8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function q8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(X9("window",W),X9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function X9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as v8}from"net";function k$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return v8(j)===6?j:null}if(v8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&v8(J[1])===4?J[1]:null}class F9 extends Z0{async run($,Z){let J=$V();if(!J)return{};let W=await J.consume(this.key(),{limit:G9($)??this.config.limit,window:G9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(q8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=Q9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${OZ(this.req)}:${this.req.routePath??"*"}`}}function $V(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function OZ($){let Z=B9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function G9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class U9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new g8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new g8;return{}}}class g8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:V9("csrf","Invalid CSRF token",403)}},view:{}}}class D9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class O9{all($,Z){return!0}}class y8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new LZ:new D6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof LZ:$ instanceof D6}}function ZV($){return new y8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await DV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return UV(z,Z,J,$.url)}async function UV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new L6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function DV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function H6($){return new TextDecoder("utf-8").decode($)}var OV={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function w$($){return $.replace(/[&<>"']/g,(Z)=>OV[Z])}var LV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function m8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return LV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function h8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function L9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(m8($.slice(W)));return}if(Y>W)Z.text(m8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(h8($.slice(Y+2,j).trim())),W=j+1}else{let j=MV($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=h8(z.slice(0,G));if(Q){if(Z.open(Q,HV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function MV($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function HV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[h8(W[1])]=m8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var N9="http://www.sitemaps.org/schemas/sitemap/0.9",TV="http://www.w3.org/1999/xhtml",d8=`<?xml version="1.0" encoding="UTF-8"?>
3
- `,M9=`<urlset xmlns="${N9}" xmlns:xhtml="${TV}">
4
- `,H9=`</urlset>
5
- `,f$=50000,Q3=52428800,T9=2048,PV=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),NV=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,KV="application/xml; charset=utf-8",P9=new TextEncoder;function u8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>T9)throw new j0(`Sitemap: ${Z} is over ${T9} characters: "${W.slice(0,80)}\u2026".`);return W}function K9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!NV.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function _V($){let Z=u8($.loc,"loc"),J=`<url><loc>${w$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${w$(K9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!PV.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=u8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${w$(Y)}" href="${w$(j)}"/>`}return`${J}</url>
6
- `}function IV($){let Z=$.maxUrls??f$,J=$.maxBytes??Q3;if(!Number.isInteger(Z)||Z<1||Z>f$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${f$}.`);if(!Number.isInteger(J)||J<1||J>Q3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${Q3}.`);return{maxUrls:Z,maxBytes:J}}function _9($,Z={}){let{maxUrls:J,maxBytes:W}=IV(Z),Y=P9.encode(d8+M9+H9).byteLength,j=[],z=[],X=Y,G=()=>{j.push(d8+M9+z.join("")+H9),z=[],X=Y};for(let Q of $){let F=_V(Q),V=P9.encode(F).byteLength;if(Y+V>W)throw new j0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+V>W)G();z.push(F),X+=V}if(z.length>0||j.length===0)G();return j}function I9($){let Z="",J=0;for(let W of $){if(++J>f$)throw new j0(`Sitemap: an index can list at most ${f$} sitemaps.`);let Y=u8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${w$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${w$(K9(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
- `}return`${d8}<sitemapindex xmlns="${N9}">
2
+ import{Sh as NF}from"./chunk-j9abwrkv.js";import{ki as PF}from"./chunk-4v5nwqw6.js";import{Bi as Z3,Ci as Z8,Di as eW,Ei as R2,Fi as u,Hi as x8,Ii as b$,Ji as u2,Ki as k2,Li as w2,Mi as X6,Ni as A,Oi as KW,Pi as i8,Qi as MZ,Ri as C8,Si as D6,Ui as R$,Vi as h,Wi as n4,dj as O6,jj as L6,li as F3,pi as bB,qi as B9,ri as F9,rj as E1,si as I8,ti as P8,wi as N8,xi as K8,xj as eG,yi as xB,yj as GZ,zi as hW,zj as QZ}from"./chunk-zcmz311y.js";import{Bj as o1,Cj as q0,Dj as t1,Ej as U9}from"./chunk-h1wmpa03.js";import{Fj as WZ,Gj as Z2,Kj as JY,Lj as J8,Mj as N}from"./chunk-t586p2g2.js";import{Tj as cG,Wj as s3}from"./chunk-2y0nr525.js";import{_j as OY,bk as $F}from"./chunk-p4v71qfx.js";import{tk as E$,yk as a1}from"./chunk-anc5v266.js";import{Mk as _G}from"./chunk-wy82t7mz.js";import{Nk as BZ,Qk as rB,al as e3}from"./chunk-tac25cnj.js";import{cl as M$}from"./chunk-0k2r6bep.js";import{dl as B6,el as $$,fl as g$,gl as O8,hl as OF,jl as g5,kl as LF,ul as L8,wl as MF,xl as HF,yl as TF}from"./chunk-0av1gyns.js";import{Nl as y$}from"./chunk-zmt5kdpb.js";import{Sl as cW,Xl as dW}from"./chunk-rat2827k.js";import{cm as pW,hm as d}from"./chunk-yj7pbbnm.js";import{im as $3,lm as H}from"./chunk-37209psn.js";import{tm as fW}from"./chunk-swmf6w3z.js";import{Im as SW}from"./chunk-5mrtgr7q.js";import{Jm as Y8,Lm as EB}from"./chunk-55btq9c7.js";import{Qm as lW}from"./chunk-3dkv4989.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var T2=Symbol.for("gemi.HttpResponse"),SF=new Set([301,302,303,307,308]);class V1{kind;body;status;headers;[T2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return H2(J,"json"),new V1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return V1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!SF.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new V1("empty",void 0,J,Y)}static noContent($={}){return new V1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return H2(J,"text"),new V1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function H2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function i1($){return typeof $==="object"&&$!==null&&$[T2]===!0}function bF($,Z,J={}){return V1.error($,Z,J)}function r0($){return typeof $==="string"?[$]:$}function j6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function EF($){return"total"in $&&"partial"in $&&"body"in $}function P2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function X3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":K8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function RF($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(EF($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function _8($,Z){if($ instanceof Response)return $;if(!$)return P2();let J=await RF($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return P2()}let{range:G}=Z;if(G){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=P8(G,z);if(!B)return X3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,F=Q?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),Q)V.set("Content-Range",N8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",j6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))V.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:F,headers:V})}return new Response(W,{status:F,headers:V})}var kF=["content-type"];var N2=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function wF($){try{let Z=new URL($);return Z.origin!=="null"&&Z.origin===$}catch{return!1}}function G3($,Z){let J=(Y)=>{throw Error(`CORS policy on ${Z}: ${Y}`)};if($===null||typeof $!=="object")J('expected an object such as { origins: "*" } or `false`.');let W=$.origins==="*"?"*":typeof $.origins==="string"?[$.origins]:$.origins;if(W!=="*"){if(!Array.isArray(W)||W.length===0)J('`origins` must be "*", an origin or a non-empty list of origins.');for(let Y of W){if(Y==="*")J('"*" goes on its own (`origins: "*"`), not in a list.');if(Y!=="null"&&!wF(Y))J(`"${Y}" is not an origin. Write scheme, host and port only, e.g. "https://shop.example".`)}}if($.credentials){if(W==="*")J("`credentials: true` needs a list of exact origins: browsers refuse credentials with `*`, and echoing any origin with credentials lets every site read the answer as the user.");if(W.includes("null"))J('`credentials: true` cannot admit "null": any site can send `Origin: null` (a sandboxed frame), so credentials for it are credentials for everyone. Authenticate such callers with a token instead.')}for(let Y of $.methods??[])if(!N2.test(Y))J(`"${Y}" is not a method.`);for(let Y of[...$.headers??[],...$.exposeHeaders??[]])if(!N2.test(Y))J(`"${Y}" is not a header name.`);if($.maxAge!==void 0&&!(Number.isInteger($.maxAge)&&$.maxAge>=0))J("`maxAge` must be a whole number of seconds.");return{...$,origins:W}}function _2($,Z){return $.origins==="*"||$.origins.includes(Z)}function fF($,Z){return $.credentials===!0&&$.origins!=="*"&&Z!=="null"}function I2($,Z,J){if($.set("Access-Control-Allow-Origin",Z.origins==="*"?"*":J),fF(Z,J))$.set("Access-Control-Allow-Credentials","true");else $.delete("Access-Control-Allow-Credentials")}function x2($,Z){let J=($.get("Vary")??"").split(",").map((Y)=>Y.trim()).filter(Boolean);if(J.includes("*"))return;let W=J.map((Y)=>Y.toLowerCase());for(let Y of Z)if(!W.includes(Y.toLowerCase()))J.push(Y);$.set("Vary",J.join(", "))}function K2($,Z,J){if(Z.origins!=="*")x2($,["Origin"]);if(!J||!_2(Z,J))return;if(I2($,Z,J),Z.exposeHeaders?.length)$.set("Access-Control-Expose-Headers",Z.exposeHeaders.join(", "))}function C2($,Z,J){let W=J.headers.get("Origin");try{return K2($.headers,Z,W),$}catch{let Y=new Headers($.headers);return K2(Y,Z,W),new Response($.body,{status:$.status,statusText:$.statusText,headers:Y})}}function A2($){return $.method==="OPTIONS"&&$.headers.has("Access-Control-Request-Method")}function S2($,Z){let J=new Headers,W=$.headers.get("Origin"),Y=$.headers.get("Access-Control-Request-Method").trim().toUpperCase(),j=Z[Y];if(x2(J,["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]),!j||!W||!_2(j,W))return new Response(null,{status:204,headers:J});let z=Object.keys(Z).filter((F)=>Z[F]===j),X=j.methods?j.methods.map((F)=>F.toUpperCase()).filter((F)=>z.includes(F)):z;if(!X.includes(Y))return new Response(null,{status:204,headers:J});let G=(j.headers??kF).map((F)=>F.toLowerCase());if(($.headers.get("Access-Control-Request-Headers")??"").split(",").map((F)=>F.trim().toLowerCase()).filter(Boolean).some((F)=>!G.includes(F)))return new Response(null,{status:204,headers:J});if(I2(J,j,W),J.set("Access-Control-Allow-Methods",X.join(", ")),G.length)J.set("Access-Control-Allow-Headers",G.join(", "));return J.set("Access-Control-Max-Age",String(j.maxAge??600)),new Response(null,{status:204,headers:J})}function qF($){return Y6($)}function b2($,Z){if($.length===0)return $();return $(Z??new A)}class n{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];__internal_bodyLimitDefault;constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!qF(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return b2(Z[this.methodName].bind(Z),$)}return b2(this.handler,$)}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:G3($,`a ${this.method} route`),this}}class f2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=r0($),this}corsPolicy;cors($){return this.corsPolicy=$===!1?!1:G3($,"a proxy route"),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of R2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(w2($.rawRequest))throw new x8(k2($.rawRequest));throw J}}}class q2{constructor(...$){return new n(...$)}}class v2 extends n{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=I8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(i1(Y))return Y;return await _8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof C8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class g2{constructor(...$){return new v2(...$)}}class y2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new n("GET",$,"list"),post:new n("POST",$,"store")},this.second={get:new n("GET",$,"show"),put:new n("PUT",$,"update"),delete:new n("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class x0{static __brand="ApiRouter";routes={};middlewares=[];cors;middleware($){}get($,Z){return new n("GET",$,Z)}post($,Z){return new n("POST",$,Z)}put($,Z){return new n("PUT",$,Z)}patch($,Z){return new n("PATCH",$,Z)}delete($,Z){return new n("DELETE",$,Z)}resource($){return new y2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${E2($)}.`);return vF($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${E2($)}.`);return gF($)}file($,Z){return new q2("GET",$,Z)}stream($,Z){return new g2("GET",$,Z)}proxy($,Z={}){return new f2($,Z)}}function E2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function vF($){let Z={stream:new n("POST",$,"stream"),attach:new n("POST",$,"attach"),watch:new n("POST",$,"watch"),stop:new n("POST",$,"stop"),upload:new n("POST",$,"upload")};return Z.stream.__internal_bodyLimitDefault="none",Z.upload.__internal_bodyLimitDefault="upload",class extends x0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function gF($){let Z={start:new n("POST",$,"voiceStart"),update:new n("PATCH",$,"voiceUpdate"),end:new n("DELETE",$,"voiceEnd")};return class extends x0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var s1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var yF=/^[A-Za-z0-9_-]+$/,mF=/^:[A-Za-z_][A-Za-z0-9_]*$/,m2=/^[A-Za-z0-9_-]{1,128}$/,hF=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function h2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new i("A channel pattern must be a non-empty string.");if($.length>255)throw new i(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(mF.test(W)){let Y=W.slice(1);if(J.has(Y))throw new i(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new i(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!yF.test(W))throw new i(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function Q3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new i(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!m2.test(G))throw new i(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new i(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new i(`The topic built from "${$}" is longer than 255 characters.`);return Y}function A8($){if(UZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function p2($){if(typeof $!=="string"||$.length===0||$.length>64||!hF.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function c2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&m2.test(W[j]))}var U0="user";function DZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return Q3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class G6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');let J=Z==="upload"?this.config.uploadLimit??b$("50mb"):b$(Z);return X6(this.req.rawRequest,J),{}}}function pF($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}function cF($){return{"body-limit":G6.configure({uploadLimit:$})}}class n1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:b$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=b$($.uploadBodyLimit??"50mb"),this.builtinAliases=cF(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||u2($))return;let J=Z==="upload"?Math.max(this.defaultBodyLimit,this.uploadBodyLimit):this.defaultBodyLimit;X6($,J,{checkDeclared:!1,uploadLimit:this.uploadBodyLimit})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new A,J=this.aliases,W=[];for(let[Y,j]of pF($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:d2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:d2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await dF(W.slice(j+1)),z}return Y})()}}function d2($){return $?.runsOnRefusal===!0}async function dF($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class Q6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...r0($)],this}events(...$){return this}}class n2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{sF(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!o2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=Q3(Z,J??{})}catch(G){if(G instanceof i)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new A($,z,"api",Z);return N.exit(()=>B6.exit(()=>N.run(X,async()=>{let G=N.getStore();try{if(Y.middlewares.length>0)await H(n1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await l2(X);if(!Q)return{ok:!1,code:"denied"};if(j=DZ(Q),Y.visibility==="private"&&Y.authorizer){if(await i2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await i2(Y.authorizer,X,z):await l2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(iF(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function uF($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;a2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function o2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function l2($){if(!N.getStore().user&&S$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function i2($,Z,J){if(lF($))return new $().authorize(Z,J);return $(Z,J)}function lF($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function iF($){return $?.kind===o1||a1($)||E$($)}var s2=new WeakSet;function sF($){if(s2.has($))return;a2($),s2.add($)}function a2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!o2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new i(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new i(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new i(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(nF(J[W].segments,J[Y].segments))throw new i(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function nF($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class S8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class F6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class b8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function oF($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function aF($,Z){let J=oF($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class t2{static __brand="McpRouter";routes={};scopes;param($){return new S8($.as,$.input,$.bind)}fromTool($,Z={}){return new b8($,Z)}fromApiRoute($,Z,J){return new F6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,F=Object.keys(Y??{});if(F.length===0)throw Error(`${Q}: declare at least one audience.`);let V={},B=new Map;for(let U of F){let{name:O,casing:D,description:L,params:M,files:T,...P}=Y[U],K=O??(D?aF(W,D):W);if(B.has(K))throw Error(`${Q}: the audiences "${B.get(K)}" and "${U}" are both named "${K}". Give one its own name or casing.`);B.set(K,U);let R=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof R!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let C={...G,...P,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};V[K]=new F6($,Z,C)}return V}}function D0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class E8 extends q0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class S1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new E8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new E8($,Z)}}class r2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function R8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",j6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class e2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function $9($,Z){if(i1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class Z9{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=$9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=r0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class J9{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=$9(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=r0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new Z9($,Z)}file($){return new e2($)}redirect($){return new r2($)}layout($,Z,J){return new J9($,Z,J)}}function tF($){return $}function rF(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function OZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function k8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function eF($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(d).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function $V($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function V6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=eF($,!W);if(W||!$V(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class W9 extends Z0{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(E),J);if(!W)throw new R$({redirectTo:V6(J,$)});return Z.setUser(W),{}}}var f8="gemi_same_site",w8="private, no-cache, no-store, max-age=0, must-revalidate";class U6 extends Z0{run(){let $=N.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(f8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(f8,"1"),new Y9(`${W.pathname}${W.search}`)}}class Y9 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=ZV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":w8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":w8}},viewData:{status:200,data:{},headers:{"Cache-Control":w8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function ZV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class j9 extends Z0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var z9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class X9 extends Z0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...z9,...this.config.origins[Z]};if(Z==="null")delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...z9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var JV="Rate limit exceeded";class r1 extends q0{result;retryAfter;constructor($,Z=JV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?q8($):{}};this.payload={api:{status:429,data:{error:{...t1("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function q8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class D1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(G9("window",W),G9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new r1(W,typeof J==="function"?J(W):J);return W}}function G9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as v8}from"net";function k$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return v8(j)===6?j:null}if(v8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&v8(J[1])===4?J[1]:null}class V9 extends Z0{async run($,Z){let J=WV();if(!J)return{};let W=await J.consume(this.key(),{limit:Q9($)??this.config.limit,window:Q9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(q8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new r1(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=B9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${LZ(this.req)}:${this.req.routePath??"*"}`}}function WV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function LZ($){let Z=F9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function Q9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class D9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new g8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new g8;return{}}}class g8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:U9("csrf","Invalid CSRF token",403)}},view:{}}}class O9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class L9{all($,Z){return!0}}class y8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new MZ:new D6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new A,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends Z0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof MZ:$ instanceof D6}}function YV($){return new y8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await MV($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return LV(z,Z,J,$.url)}async function LV($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:F}=await Y.read();if(Q)break;if(z+F.byteLength>Z){if(!J)throw new L6(W,Z);j.push(F.subarray(0,Z-z)),z=Z;break}j.push(F),z+=F.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function MV($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function H6($){return new TextDecoder("utf-8").decode($)}var HV={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function w$($){return $.replace(/[&<>"']/g,(Z)=>HV[Z])}var TV={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function m8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return TV[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function h8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function M9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(m8($.slice(W)));return}if(Y>W)Z.text(m8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(h8($.slice(Y+2,j).trim())),W=j+1}else{let j=PV($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=h8(z.slice(0,G));if(Q){if(Z.open(Q,NV(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function PV($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function NV($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[h8(W[1])]=m8(W[2]??W[3]??"");return Z}class j0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var K9="http://www.sitemaps.org/schemas/sitemap/0.9",KV="http://www.w3.org/1999/xhtml",d8=`<?xml version="1.0" encoding="UTF-8"?>
3
+ `,H9=`<urlset xmlns="${K9}" xmlns:xhtml="${KV}">
4
+ `,T9=`</urlset>
5
+ `,f$=50000,B3=52428800,P9=2048,_V=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),IV=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,xV="application/xml; charset=utf-8",N9=new TextEncoder;function u8($,Z){let J;try{J=new URL($)}catch{throw new j0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new j0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>P9)throw new j0(`Sitemap: ${Z} is over ${P9} characters: "${W.slice(0,80)}\u2026".`);return W}function _9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!IV.test($))throw new j0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function CV($){let Z=u8($.loc,"loc"),J=`<url><loc>${w$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${w$(_9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!_V.has($.changefreq))throw new j0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new j0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new j0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=u8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${w$(Y)}" href="${w$(j)}"/>`}return`${J}</url>
6
+ `}function AV($){let Z=$.maxUrls??f$,J=$.maxBytes??B3;if(!Number.isInteger(Z)||Z<1||Z>f$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${f$}.`);if(!Number.isInteger(J)||J<1||J>B3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${B3}.`);return{maxUrls:Z,maxBytes:J}}function I9($,Z={}){let{maxUrls:J,maxBytes:W}=AV(Z),Y=N9.encode(d8+H9+T9).byteLength,j=[],z=[],X=Y,G=()=>{j.push(d8+H9+z.join("")+T9),z=[],X=Y};for(let Q of $){let F=CV(Q),V=N9.encode(F).byteLength;if(Y+V>W)throw new j0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+V>W)G();z.push(F),X+=V}if(z.length>0||j.length===0)G();return j}function x9($){let Z="",J=0;for(let W of $){if(++J>f$)throw new j0(`Sitemap: an index can list at most ${f$} sitemaps.`);let Y=u8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${w$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${w$(_9(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
+ `}return`${d8}<sitemapindex xmlns="${K9}">
8
8
  ${Z}</sitemapindex>
9
- `}function p8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",KV);return new Response($,{status:Z,headers:W})}function xV($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function CV($,Z={}){let J=_9($,Z),W=xV(Z.page);if(W!==null){let j=J[W-1];return j?p8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return p8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new j0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return p8(I9(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function c8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function x9($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let B=[];for(let U of W.split(/\r?\n/)){if(B.length>=J)break;let O=U.trim()?c8(U):null;if(O)B.push({loc:O})}if(B.length===0&&W.length>0)throw new j0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:B}}let Y=null,j=[],z=[],X=[],G=null,Q=null,F="",V=()=>Y==="index"?z.length:j.length;if(L9(W,{stopped:()=>V()>=J,open(B,U){let O=X[X.length-1];if(X.push(B),Y===null){if(B==="urlset")Y="urlset";else if(B==="sitemapindex")Y="index";return}if(Y==="urlset"&&B==="url"&&O==="urlset"||Y==="index"&&B==="sitemap"&&O==="sitemapindex")G={};else if(G&&(O==="url"||O==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))Q=B,F="";else if(G&&Y==="urlset"&&O==="url"&&B==="link"){let D=U.href?c8(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&D)(G.alternates??=[]).push({hrefLang:U.hreflang,href:D})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,Q&&B===Q&&G)G[Q]=F.trim(),Q=null;else if(G&&(B==="url"||B==="sitemap")){let O=G;G=null,Q=null;let D=O.loc?c8(O.loc):null;if(!D)return;if(Y==="index"){z.push(O.lastmod?{loc:D,lastmod:O.lastmod}:{loc:D});return}let L={loc:D};if(O.lastmod)L.lastmod=O.lastmod;if(O.changefreq)L.changefreq=O.changefreq;let M=O.priority?Number(O.priority):NaN;if(Number.isFinite(M))L.priority=M;if(O.alternates)L.alternates=O.alternates;j.push(L)}},text(B){if(Q)F+=B}}),Y===null)throw new j0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*AV($,Z={}){let{maxUrls:J=f$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=Q3,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,F=0,V=0;while(G.length>0&&V<J&&F<W){let B=G.shift(),U=B.url.replace(/#.*$/,"");if(Q.has(U))continue;Q.add(U),F++;let O;try{let D=await E1(B.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new j0(`Sitemap: ${B.url} answered ${D.status}.`,B.url,D.status);let L=H6(await M6(D,j));O=x9(L,{maxUrls:Math.max(J-V,W-F)})}catch(D){if(B.depth===0||!z||X.signal?.aborted)throw D;z(D,B.url);continue}if(O.kind==="index"){if(B.depth>=Y)continue;G=O.sitemaps.slice(0,W-F).map((L)=>({url:L.loc,depth:B.depth+1})).concat(G);continue}for(let D of O.urls)if(yield{...D,sitemap:B.url},++V>=J)return}}var C9={response:CV,chunk:_9,index:I9,parse:x9,read:AV,MAX_URLS:f$,MAX_BYTES:Q3};var SV=512000,bV=new TextEncoder;function A9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function S9($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let Y=$.codePointAt(J);if(Y>65535)J++;for(let j of bV.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function EV($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class MZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=A9($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=S9(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!EV(j.path,J))continue;let z=j.path.length,X=j.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var RV={"user-agent":"user-agent",useragent:"user-agent","user agent":"user-agent",allow:"allow",disallow:"disallow",dissallow:"disallow",disalow:"disallow",sitemap:"sitemap","site-map":"sitemap","crawl-delay":"crawl-delay"};function b9($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),G=(X===-1?z:z.slice(0,X)).trim(),Q=G.indexOf(":");if(Q===-1)continue;let F=RV[G.slice(0,Q).trim().toLowerCase()],V=G.slice(Q+1).trim();if(!F)continue;if(F==="sitemap"){if(!V||/\s/.test(V))continue;try{let B=Z.url?new URL(V,Z.url):new URL(V);if(B.protocol==="http:"||B.protocol==="https:")W.push(B.href)}catch{}continue}if(F==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let B=A9(V);if(B)Y.userAgents.push(B);continue}if(!Y)continue;if(j=!1,F==="crawl-delay"){let B=Number(V);if(Number.isFinite(B)&&B>=0)Y.crawlDelay=B;continue}if(!V)continue;Y.rules.push({type:F,path:S9(V)})}return new MZ(J,W)}async function kV($,Z={}){let{maxSize:J=SV,...W}=Z,Y=new URL("/robots.txt",$),j=await E1(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new MZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new MZ([],[],"unavailable");let X=await M6(j,J,!0),G=H6(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
10
- `)));return b9(G,{url:j.url})}function l8($){return $===void 0?[]:typeof $==="string"?[$]:$}function T6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
- `}function E9($){let Z=[];for(let W of $.rules??[]){let Y=l8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>T6("User-agent",X)).join(""),z=[...l8(W.allow).map((X)=>["Allow",X]),...l8(W.disallow).map((X)=>["Disallow",X])];for(let[X,G]of z){if(!G.startsWith("/")&&!G.startsWith("*"))throw TypeError(`Robots: ${X} "${G}" must start with "/" or "*".`);j+=T6(X,G)}if(z.length===0)j+=`Disallow:
9
+ `}function p8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",xV);return new Response($,{status:Z,headers:W})}function SV($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function bV($,Z={}){let J=I9($,Z),W=SV(Z.page);if(W!==null){let j=J[W-1];return j?p8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return p8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new j0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return p8(x9(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function c8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function C9($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let B=[];for(let U of W.split(/\r?\n/)){if(B.length>=J)break;let O=U.trim()?c8(U):null;if(O)B.push({loc:O})}if(B.length===0&&W.length>0)throw new j0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:B}}let Y=null,j=[],z=[],X=[],G=null,Q=null,F="",V=()=>Y==="index"?z.length:j.length;if(M9(W,{stopped:()=>V()>=J,open(B,U){let O=X[X.length-1];if(X.push(B),Y===null){if(B==="urlset")Y="urlset";else if(B==="sitemapindex")Y="index";return}if(Y==="urlset"&&B==="url"&&O==="urlset"||Y==="index"&&B==="sitemap"&&O==="sitemapindex")G={};else if(G&&(O==="url"||O==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))Q=B,F="";else if(G&&Y==="urlset"&&O==="url"&&B==="link"){let D=U.href?c8(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&D)(G.alternates??=[]).push({hrefLang:U.hreflang,href:D})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,Q&&B===Q&&G)G[Q]=F.trim(),Q=null;else if(G&&(B==="url"||B==="sitemap")){let O=G;G=null,Q=null;let D=O.loc?c8(O.loc):null;if(!D)return;if(Y==="index"){z.push(O.lastmod?{loc:D,lastmod:O.lastmod}:{loc:D});return}let L={loc:D};if(O.lastmod)L.lastmod=O.lastmod;if(O.changefreq)L.changefreq=O.changefreq;let M=O.priority?Number(O.priority):NaN;if(Number.isFinite(M))L.priority=M;if(O.alternates)L.alternates=O.alternates;j.push(L)}},text(B){if(Q)F+=B}}),Y===null)throw new j0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*EV($,Z={}){let{maxUrls:J=f$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=B3,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,F=0,V=0;while(G.length>0&&V<J&&F<W){let B=G.shift(),U=B.url.replace(/#.*$/,"");if(Q.has(U))continue;Q.add(U),F++;let O;try{let D=await E1(B.url,{...X,maxSize:j});if(!D.ok)throw D.body?.cancel().catch(()=>{}),new j0(`Sitemap: ${B.url} answered ${D.status}.`,B.url,D.status);let L=H6(await M6(D,j));O=C9(L,{maxUrls:Math.max(J-V,W-F)})}catch(D){if(B.depth===0||!z||X.signal?.aborted)throw D;z(D,B.url);continue}if(O.kind==="index"){if(B.depth>=Y)continue;G=O.sitemaps.slice(0,W-F).map((L)=>({url:L.loc,depth:B.depth+1})).concat(G);continue}for(let D of O.urls)if(yield{...D,sitemap:B.url},++V>=J)return}}var A9={response:bV,chunk:I9,index:x9,parse:C9,read:EV,MAX_URLS:f$,MAX_BYTES:B3};var RV=512000,kV=new TextEncoder;function S9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function b9($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let Y=$.codePointAt(J);if(Y>65535)J++;for(let j of kV.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function wV($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class HZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=S9($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=b9(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!wV(j.path,J))continue;let z=j.path.length,X=j.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var fV={"user-agent":"user-agent",useragent:"user-agent","user agent":"user-agent",allow:"allow",disallow:"disallow",dissallow:"disallow",disalow:"disallow",sitemap:"sitemap","site-map":"sitemap","crawl-delay":"crawl-delay"};function E9($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),G=(X===-1?z:z.slice(0,X)).trim(),Q=G.indexOf(":");if(Q===-1)continue;let F=fV[G.slice(0,Q).trim().toLowerCase()],V=G.slice(Q+1).trim();if(!F)continue;if(F==="sitemap"){if(!V||/\s/.test(V))continue;try{let B=Z.url?new URL(V,Z.url):new URL(V);if(B.protocol==="http:"||B.protocol==="https:")W.push(B.href)}catch{}continue}if(F==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let B=S9(V);if(B)Y.userAgents.push(B);continue}if(!Y)continue;if(j=!1,F==="crawl-delay"){let B=Number(V);if(Number.isFinite(B)&&B>=0)Y.crawlDelay=B;continue}if(!V)continue;Y.rules.push({type:F,path:b9(V)})}return new HZ(J,W)}async function qV($,Z={}){let{maxSize:J=RV,...W}=Z,Y=new URL("/robots.txt",$),j=await E1(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new HZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new HZ([],[],"unavailable");let X=await M6(j,J,!0),G=H6(X);if(X.byteLength>=J)G=G.slice(0,Math.max(0,G.lastIndexOf(`
10
+ `)));return E9(G,{url:j.url})}function l8($){return $===void 0?[]:typeof $==="string"?[$]:$}function T6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
+ `}function R9($){let Z=[];for(let W of $.rules??[]){let Y=l8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>T6("User-agent",X)).join(""),z=[...l8(W.allow).map((X)=>["Allow",X]),...l8(W.disallow).map((X)=>["Disallow",X])];for(let[X,G]of z){if(!G.startsWith("/")&&!G.startsWith("*"))throw TypeError(`Robots: ${X} "${G}" must start with "/" or "*".`);j+=T6(X,G)}if(z.length===0)j+=`Disallow:
12
12
  `;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);j+=T6("Crawl-delay",String(W.crawlDelay))}Z.push(j)}let J=($.sitemaps??[]).map((W)=>{let Y;try{Y=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return T6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function wV($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(E9($),{status:200,headers:J})}var R9={response:wV,text:E9,parse:b9,fetch:kV};import{createHmac as k9,randomBytes as fV}from"crypto";var s8="v2.";function n8($){return $.startsWith(s8)}function HZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function w9($){let Z=fV(16).toString("hex"),J=k9("sha256",HZ()).update(`${$}:${Z}`).digest("hex");return`${s8}${J}`}function P6($,Z){let J=k9("sha256",HZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${s8}${J}`}import{createHash as gV,createHmac as yV,randomInt as mV,timingSafeEqual as v9}from"crypto";function f9($,Z){return Math.floor($/Z)*Z}function qV($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function o8($,Z,J,W){return Z*qV(J,W)+$}function vV($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let G=Math.max(0,Y-W);if(J>0){let F=Y*(1-(X-Z)/J);if(F<=Y)return Math.max(0,Math.ceil(F-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=Y*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function q9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let F=o8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-F)),resetAt:Y-j+z,retryAfter:0}}let Q=vV({current:J,previous:W,elapsed:j,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:Y+Q,retryAfter:Q}}class a8{}class t8 extends a8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=f9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let F=o8(G.current,G.previous,X,W)+Y<=J;if(F)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return q9({allowed:F,current:G.current,previous:G.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var y9="h1.";function N6($,Z,J){let W=yV("sha256",HZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${y9}${W}`}function TZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(y9),X=N6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return v9(G,G),!1;return v9(G,Q)}function m9($){let Z="";for(let J=0;J<$;J++)Z+=String(mV(0,10));return Z}var h9=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>h9)return null;return Z.toLowerCase()}function K6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>h9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var g9=null;function p9(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(D1))return $.make(D1)}catch{}return g9??=new D1({driver:new t8,limit:1000,window:60}),g9}function r8($){return $.length<=64?$:`sha256:${gV("sha256").update($).digest("hex")}`}function hV($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function v$($,Z,J,W,Y,j){let z=p9(),X=[["perIp",`ip:${r8(OZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${r8(Z)}`,W.perEmail]);for(let[G,Q,F]of X){if(!F)continue;let V=Y?await Y({req:J,scope:$,limit:G}):void 0,B=hV($),U=V?`${B}:p:${r8(String(V))}:${Q}`:`${B}:${Q}`,[O,D]=F,L=await z.consume(U,{limit:O,window:D});if(!L.allowed)throw await j?.(G),new r1(L)}}async function c9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await p9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as $7}from"crypto";class e8 extends A{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}import{createHash as pV,timingSafeEqual as cV}from"crypto";function u9($){let Z=$??process.env.AUTH_FIXED_CODE;return typeof Z==="string"&&Z!==""?Z:null}function l9($){if($!==void 0&&$!==null)return $===!0;return process.env.AUTH_FIXED_CODE_ALLOW_PRODUCTION==="1"}var dV="[gemi] WARNING: a fixed sign-in code is enabled in production (AUTH_FIXED_CODE / auth.emailCode.fixedCode, opted in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1 / auth.emailCode.allowFixedCodeInProduction). Anyone who knows the code can sign in as any user. This is meant for local test servers only; never set it on a real deployment.";function i9($={},{warn:Z=!1}={}){let{fixedCode:J,allowFixedCodeInProduction:W}=$??{};if(J!==void 0&&J!==null&&typeof J!=="string")throw Error(`auth.emailCode.fixedCode must be a string, got ${JSON.stringify(J)}`);if(W!==void 0&&W!==null&&typeof W!=="boolean")throw Error(`auth.emailCode.allowFixedCodeInProduction must be a boolean, got ${JSON.stringify(W)}`);let Y=u9(J);if(Y===null)return;let j=J?"auth.emailCode.fixedCode":"AUTH_FIXED_CODE",z=Bun.env.NODE_ENV==="production";if(z&&!l9(W))throw Error(`${j} is set, but a fixed sign-in code is for development and tests only and is refused when NODE_ENV=production. Unset it in this environment (a local production-build test server can opt in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1).`);if(Y.trim()!==Y||Y.length>256)throw Error(`${j} must have no surrounding whitespace and at most 256 characters`);if(z&&Z)console.warn(dV)}function uV($={}){if(Bun.env.NODE_ENV==="production"&&!l9($.allowFixedCodeInProduction))return null;return u9($.fixedCode)}function d9($){return pV("sha256").update($).digest()}function s9($,Z={}){let J=uV(Z);if(J===null||typeof $!=="string"||$==="")return!1;return cV(d9($),d9(J))}async function R1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Z7($){return $===!0||typeof $==="function"}function J7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function F3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function lV($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function W7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return F3("length",Z,4,12),F3("expiresInMinutes",J,1),F3("linkExpiresInMinutes",W,1),F3("maxAttempts",Y,1),F3("activeCodes",j,1,5),i9($),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)}),fixedCode:$.fixedCode??null,allowFixedCodeInProduction:$.allowFixedCodeInProduction??null}}async function iV($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function n9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J,enabled:W}=$;return{provider:Z,...J!==void 0?{feature:J}:{},...W!==void 0?{enabled:W}:{}}}function o9($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature, enabled } with an OAuthProvider.`);if(W.enabled!==void 0&&typeof W.enabled!=="boolean"&&typeof W.enabled!=="function")throw Error(`auth.oauthProviders.${Z}.enabled must be true, false or a function of the request.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function qN($){return $}function a9($={}){return lV($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:J7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:e8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:iV,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>$7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return $7(32).toString("hex")},generateMagicLinkToken:()=>$7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:W7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var sV=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),nV=new Set(["svg","math"]);function t9($){return $===32||$===9||$===10||$===12||$===13}function r9($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function e9(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,F=()=>{if(!J&&sV.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(nV.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},V=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(r9(B))$="tagName",J=!1,z=!1,Z=String.fromCharCode(_6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(r9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(t9(B)||B===47)$="inTag",z=B===47;else if(B===62)F();else Z+=String.fromCharCode(_6(B));return;case"inTag":if(B===62){F();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(_6(B)===W.charCodeAt(Y))Y+=1;else Y=B===60?1:0;return}if(B===62)$="data",Z="";else if(t9(B)||B===47)$="inTag",Z="";else Y=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(Q())return U;V(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)V(B[U])},isSafe:Q}}function i0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function $Y($){return $?`<script nonce="${$}">`:"<script>"}function oV($,Z){let J=i0([$.path,$.variantKey,$.data]);return`${$Y(Z)}(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${J})</script>`}function aV($,Z){let J=i0([$.id,$.locale,$.strings]);return`${$Y(Z)}(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${J})</script>`}function Y7($,Z,J={},W,Y){let j=new TextEncoder,z=[],X=!1,G=!1,Q=()=>{if(G)return;G=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;z.push(oV(D,Y))}),W?.onUse((D)=>{z.push(aV(D,Y))});let F=$.getReader(),V=e9(),B=(D,L)=>{D.enqueue(L),J.onChunk?.(L)},U=(D)=>{while(z.length>0){let L=j.encode(z.shift());V.write(L),B(D,L)}},O=(D,L)=>{if(z.length===0){V.write(L),B(D,L);return}let M=V.scanToInsertionPoint(L);if(M>0)B(D,L.subarray(0,M));if(V.isSafe())U(D);let T=L.subarray(M);if(T.length>0)V.write(T),B(D,T)};return new ReadableStream({async pull(D){let L;try{L=await F.read()}catch(P){throw Q(),P}let{done:M,value:T}=L;if(M){U(D),D.close(),Q();return}if(!X){if(X=!0,V.write(T),B(D,T),J.onShell?.(),V.isSafe())U(D);return}O(D,T)},cancel(D){return Q(),F.cancel(D)}})}var tV=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return tV.test($)}async function JY($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await rV($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:ZY(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function WY($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function rV($,Z){if(!$.context)return{};try{let J=N.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function YY($,Z){return`${$}:${Z}`}function j7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function jY($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function zY($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=$U($,Z,J,W.buckets);return jY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function eV($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function $U($,Z,J,W){let Y=YY(Z.salt??$,eV(J));if(!W)return j7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=j7(Y);return W.set(Y,z),z}class XY extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class z7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new XY(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=ZU(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function ZU($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class JU{}class WU extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class X7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class GY extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class QY{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class e1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new z7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new GY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=YU(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new X7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new QY(this,WY($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=zY($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await JY(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function YU($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function BY($){if($===void 0)return!0;return await H(e1).enabled($)}function FY(){try{return N.getStore()?.req??null}catch{return null}}async function PZ($,Z,J=FY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=n9($[Z]);if(!W||!await BY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await R1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function VY($,Z=FY()){let J=[];for(let W of Object.keys($))if(await PZ($,W,Z))J.push(W);return J}function G7($){if($&&typeof $==="object")delete $.password;return $}function jU(){return new Proxy({},{get:($,Z)=>DY(Z)})}var UY=new WeakMap;function OY($){if($&&typeof $==="object"){for(let Z of Object.values($))OY(Z);Object.freeze($)}return $}var zU={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},XU=OY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:zU});class Q7{models;constructor($=jU()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return XU}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??g$(),W=H(y$).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await $$()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||$$())return Y();let z=(UY.get(W)??Promise.resolve()).then(Y,Y);return UY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return G7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return G7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?G7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as FL}from"crypto";function v0($,Z,J,W,Y){return e0(Z,RY($,Z),J,W,Y)}function e0($,Z,J,W,Y,j){let z=D7(Z,J,W);if(Y&&Z!==z)throw RangeError(DX($,Z,J,W,j));return z}function RY($,Z){let J=$[Z];if(J===void 0)throw TypeError(dJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function K7($){return c$({name:$},1)}function c$($,Z){return W1((J)=>({value:J,configurable:1,writable:!Z}),$)}function kY($){return W1((Z)=>({get:Z,configurable:1}),$)}function h6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function AZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function W1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function P3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function GU($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function _7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function I7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function wY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function fY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function qY($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function q($,...Z){return(...J)=>$(...Z,...J)}function LY($){return $[0].toUpperCase()+$.substring(1)}function N3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function Z$($,Z){return Math.sign($-Z)}function D7($,Z,J){return Math.min(Math.max($,Z),J)}function w1($,Z){return[Math.floor($/Z),U3($,Z)]}function U3($,Z){return($%Z+Z)%Z}function Y$($,Z){return[p6($,Z),x7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function x7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function vY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=L1[X],F=s/Q,[V,B]=Y$(G,F);W+=B*Q,Y+=V}let[j,z]=Y$(W,s);return[Y+j,z]}function c6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=L1[Y];W[J[Y]]=p6($,j),$=x7($,j)}return W}function gY($){return $===v?K4:[]}function yY($){return $===v?R3:[]}function mY($){return $===v?["year","day"]:[]}function hY($){if($!==void 0)return J0($)}function pY($){if($!==void 0)return Y1($)}function C7($){if($!==void 0)return K3($)}function Y1($){return uY(K3($))}function K3($){return dY(eU($))}function A7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function cY($,Z){if(Z==null)throw RangeError(dJ($));return Z}function q1($){if(!L0($))throw TypeError(UX);return $}function d6($,Z,J=$){if(typeof Z!==$)throw TypeError(S3(J,Z));return Z}function dY($,Z="number"){if(!Number.isInteger($))throw RangeError(IU(Z,$));return $||0}function uY($,Z="number"){if($<=0)throw RangeError(xU(Z,$));return $}function S7($){if(typeof $=="symbol")throw TypeError(bU);return String($)}function k6($,Z){return L0($)?String($):J0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(SU($));return $}function lY($,Z="number"){if(typeof $=="bigint")throw TypeError(AU(Z));if($=Number($),!Number.isFinite($))throw RangeError(CU(Z,$));return $}function C0($,Z){return Math.trunc(lY($,Z))||0}function iY($,Z){return dY(lY($,Z),Z)}function MY($,Z){return uY(C0($,Z),Z)}function b7($,Z){let[J,W]=Y$(Z,s),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*s),[Y,W]}function KZ($,Z,J=1){return b7($[0]+Z[0]*J,$[1]+Z[1]*J)}function _Z($,Z){return b7($[0],$[1]+Z)}function s0($,Z){return KZ(Z,$,-1)}function S0($,Z){return Z$($[0],Z[0])||Z$($[1],Z[1])}function sY($,Z,J){return S0($,Z)===-1||S0($,J)===1}function l6($,Z=1){let J=BigInt(s/Z);return[Number($/J),Number($%J)*Z]}function IZ($,Z=1){let J=s/Z,[W,Y]=Y$($,J);return[W,Y*Z]}function nY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=s/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function n0($,Z=1,J){let[W,Y]=$,[j,z]=Y$(Y,Z);return W*(s/Z)+(j+(J?z/Z:0))}function E7($,Z,J=w1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(s/Z)+j,z]}function R7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function k7($){return v0($,"isoYear",T3,H3,1),$.isoYear===T3?v0($,"isoMonth",4,12,1):$.isoYear===H3&&v0($,"isoMonth",1,9,1),$}function J$($){return v1({...$,...J1,isoHour:12}),$}function v1($){let Z=v0($,"isoYear",T3,H3,1),J=Z===T3?1:Z===H3?-1:0;return J&&o0(A0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function o0($){if(!$||sY($,zD,jD))throw RangeError(H4);return $}function j$($){return vY($,5,G1)[1]}function i6($){let[Z,J]=w1($,s);return[c6(J,5,G1),Z]}function oY($){return aY($)[0]}function aY($){return E7($,Z1)}function b0($){return SZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function A0($){let Z=b0($);if(Z!==void 0){let[J,W]=Y$(Z,y0);return[J,W*M1+($.isoMicrosecond||0)*t$+($.isoNanosecond||0)]}}function w7($,Z){let[J,W]=i6(j$($)-Z);return o0(A0({...$,isoDay:$.isoDay+W,...J}))}function w6(...$){return SZ(...$)/xX}function SZ(...$){let[Z,J]=tY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function tY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===T3?1:$===H3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function X$($,Z){let[J,W]=_Z($,Z);W<0&&(W+=s,J-=1);let[Y,j]=w1(W,M1),[z,X]=w1(j,t$);return s6(J*y0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-YD)/y0)*Math.sign($),Y=new Date($-W*y0);return AZ(I4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function rY($){return[$.isoYear,$.isoMonth,$.isoDay]}function eY(){return k1}function f7($,Z){switch(Z){case 2:return q7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function $j($){return q7($)?366:365}function q7($){return $%4==0&&($%100!=0||$%400==0)}function Zj($){let[Z,J]=tY($.isoYear,$.isoMonth,$.isoDay);return U3(Z.getUTCDay()-J,7)||7}function Jj({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function QU($){let Z=b0($);if(Z<GD)return Jj($);let J=R7(X5(xZ),Z),{era:W,eraYear:Y}=Uz(J,xZ);return[W,Y]}function n6($){return d$($),o6($,1),$}function d$($){return Wj($,1),$}function HY($){return fY(eJ,$,Wj($))}function Wj($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,eY(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,f7(J,W),Z)}}function o6($,Z){return AZ(G1,[v0($,"isoHour",0,23,Z),v0($,"isoMinute",0,59,Z),v0($,"isoSecond",0,59,Z),v0($,"isoMillisecond",0,999,Z),v0($,"isoMicrosecond",0,999,Z),v0($,"isoNanosecond",0,999,Z)])}function m($){return $===void 0?0:cX(q1($))}function _3($,Z=0){$=j1($);let J=dX($),W=HD($,Z);return[cX($),W,J]}function v7($){return dX(j1($))}function Yj($){return $=j1($),J5($,9,6,1)}function bZ($,Z,J,W=9,Y=0,j=4){Z=j1(Z);let z=J5(Z,W,Y),X=m7(Z),G=w3(Z,j),Q=k3(Z,W,Y,1);return z==null?z=Math.max(J,Q):Gj(z,Q),X=h7(X,Q,1),$&&(G=((F)=>F<4?(F+2)%4:F)(G)),[z,Q,X,G]}function a6($,Z=6,J){let W=m7($=p7($,m6)),Y=w3($,7),j=k3($,Z);return j=cY(m6,j),W=h7(W,j,void 0,J),[j,W,Y]}function g7($){return W5(j1($))}function jj($,Z){return y7(j1($),Z)}function y7($,Z=4){let J=Xj($);return[w3($,4),...zj(k3($,Z),J)]}function zj($,Z){return $!=null?[L1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function m7($){let Z=$[D3];return Z===void 0?1:C0(Z,D3)}function h7($,Z,J,W){let Y=W?s:L1[Z+1];if(Y){let j=L1[Z];if(Y%(($=e0(D3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(S3(D3,$))}else $=e0(D3,$,1,J?1e9:1,1);return $}function Xj($){let Z=$[U7];if(Z!==void 0){if(typeof Z!="number"){if(S7(Z)==="auto")return;throw RangeError(S3(U7,Z))}Z=e0(U7,Math.floor(Z),0,9,1)}return Z}function j1($){return $===void 0?{}:q1($)}function p7($,Z){return typeof $=="string"?{[Z]:$}:q1($)}function z0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(UX)}}function t6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:BD[Z]})}function c7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=S7(j),j==="auto")return Y?W:null;let z=H7[j];if(z===void 0&&(z=JD[j]),z===void 0)throw RangeError(MX($,j,H7));return e0($,z,W,J,1,E3),z}function u$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=S7(Y),z=Z[j];if(z===void 0)throw RangeError(MX($,j,Z));return z}function Gj($,Z){if(Z>$)throw RangeError(nU)}function M0($){return{branding:C4,epochNanoseconds:$}}function N0($,Z,J){return{branding:h1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:e$,calendar:Z,...p0(yX,$)}}function G0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0($5,$)}}function h$($,Z=$.calendar){return{branding:gZ,calendar:Z,...p0($5,$)}}function f6($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0($5,$)}}function z1($){return{branding:x4,...p0(gX,$)}}function e($){return{branding:A4,sign:G$($),...p0(aJ,$)}}function Qj($){return oY($.epochNanoseconds)}function r6($){return E7($.epochNanoseconds,M1)[0]}function Bj($){return nY($.epochNanoseconds,t$)}function Fj($){return nY($.epochNanoseconds)}function Vj($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:J0($.id)}function EZ($,Z){return $===Z||T0($)===T0(Z)}function Uj($,Z,J,W,Y){let j=p$(W),[z,X]=((L,M)=>{let T=M((L=p7(L,N7))[hX]),P=MD(L);return P=cY(N7,P),[P,T]})(Y,$);if(L3(Math.max(z,j),X))return TY(W,z);if(!X)throw RangeError(T4);let[G,Q,F]=Y4(Z,J,X),V=VJ(F),B=j4(F),U=UJ(F),O=B(Q,G,W),D=U(Q,G,O,z);return L3(z,X)?TY(D,z):((L,M,T,P,K,R,C)=>{let S=G$(L),[w,x]=d7(P,rJ(T,L),T,S,K,R,C),f=u7(M,w,x);return L[p[T]]+f*S})(D,V(O),z,Q,G,V,B)}function TY($,Z){return n0(O0($),L1[Z],1)}function d7($,Z,J,W,Y,j,z){let X=p[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),F=z($,Y,G);return[j(Q),j(F)]}function u7($,Z,J){let W=n0(s0(Z,J));if(!W)throw RangeError(b3);return n0(s0(Z,$))/W}function Dj($,Z){let[J,W,Y]=a6(Z,5,1);return M0($4($.epochNanoseconds,J,W,Y,1))}function Oj($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,G]=a6(J);if(z===0&&X===1)return Z;let Q=$(Y);if(z===6)W=((F,V,B,U)=>{let O=E0(B,V),[D,L]=F(O),M=B.epochNanoseconds,T=h0(V,D),P=h0(V,L);if(sY(M,T,P))throw RangeError(b3);return Ij(u7(M,T,P),U)?P:T})(Kj,Q,Z,G);else{let F=Q.getOffsetNanosecondsFor(W);W=i$(Q,Pj(X$(W,F),z,X,G),F,2,0,1)}return N0(W,Y,j)}function Lj($,Z){return X0(Pj($,...a6(Z)),$.calendar)}function Mj($,Z){let[J,W,Y]=a6(Z,5);var j;return z1((j=Y,l7($,I3(J,W),j)[0]))}function Hj($,Z){let J=$(Z.timeZone),W=E0(Z,J),[Y,j]=Kj(W),z=n0(s0(h0(J,Y),h0(J,j)),N4,1);if(z<=0)throw RangeError(b3);return z}function Tj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(E0(X,z))))(_j,$(J),Z);return N0(Y,J,W)}function Pj($,Z,J,W){return Nj($,I3(Z,J),W)}function Nj($,Z,J){let[W,Y]=l7($,Z,J);return v1({...s$($,Y),...W})}function l7($,Z,J){return i6(z$(j$($),Z,J))}function q6($){return z$($,P4,7)}function I3($,Z){return L1[$]*Z}function Kj($){let Z=_j($);return[Z,s$(Z,1)]}function _j($){return WD(6,$)}function BU($,Z,J){let W=Math.min(p$($),6);return kZ(Z4(O0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let F=L3(W,X)?z4(X)&&W<6&&J>=6?VU:FU:UU,[V,B,U]=F($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(V=((O,D,L,M,T,P,K,R)=>{let C=G$(O);for(let S=M+1;S<=L;S++){if(S===7&&L!==7)continue;let w=rJ(S,O);w[p[S]]+=C;let x=n0(s0(K(R(T,P,w)),D));if(x&&Math.sign(x)!==C)break;O=w}return O})(V,B,J,Math.max(6,W),z,X,G,Q)),V}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/s)($);return[z$(j,J,W),0]}return Z4($,I3(Z,J),W,Y)}function Z4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=s,Y-=1);let[z,X]=w1(z$(j,Z,J),s);return b7(Y+z,X)}function z$($,Z,J){return Ij($/Z,J)*Z}function Ij($,Z){return ND[Z]($)}function FU($,Z,J,W,Y,j){let z=G$($),X=O0($),G=$4(X,W,Y,j),Q=s0(X,G),F=Math.sign(G[0]-X[0])===z,V=kZ(G,Math.min(J,6));return[{...$,...V},KZ(Z,Q),F]}function VU($,Z,J,W,Y,j,z,X,G,Q){let F=G$($),V=n0(O0($,5)),B=I3(W,Y),U=z$(V,B,j),[O,D]=d7(z,{...$,...tJ},6,F,X,G,Q),L=U-n0(s0(O,D)),M=0;L&&Math.sign(L)!==F?Z=_Z(O,U):(M+=F,U=z$(L,B,j),Z=_Z(D,U));let T=G4(U);return[{...$,...T,days:$.days+M},Z,Boolean(M)]}function UU($,Z,J,W,Y,j,z,X,G,Q){let F=G$($),V=p[W],B=rJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=p6($[V],Y)*Y;B[V]=U;let[O,D]=d7(z,B,W,Y*F,X,G,Q),L=U+u7(Z,O,D)*F*Y,M=z$(L,Y,j),T=Math.sign(M-L)===F;return B[V]=M,[B,T?D:O,T]}function i7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let F=y7(Q=j1(Q));return[Q.timeZone,...F]})(W),G=Y!==void 0;return((Q,F,V,B,U,O)=>{V=Z4(V,U,B,1);let D=F.getOffsetNanosecondsFor(V);return e7(X$(V,D),O)+(Q?l$(q6(D)):"Z")})(G,Z(G?$(Y):$Z),J.epochNanoseconds,j,z,X)}function s7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=j1(Q);let F=W5(Q),V=Xj(Q),B=PD(Q),U=w3(Q,4),O=k3(Q,4);return[F,TD(Q),B,U,...zj(O,V)]})(J);return((Q,F,V,B,U,O,D,L,M,T)=>{B=Z4(B,M,L,1);let P=Q(V).getOffsetNanosecondsFor(B);return e7(X$(B,P),T)+l$(q6(P),D)+((K,R)=>R!==1?"["+(R===2?"!":"")+T0(K)+"]":"")(V,O)+$J(F,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function n7($,Z){let[J,W,Y,j]=((Q)=>(Q=j1(Q),[W5(Q),...y7(Q)]))(Z);return z=$.calendar,X=J,G=j,e7(Nj($,Y,W),G)+$J(z,X);var z,X,G}function o7($,Z){return J=$.calendar,W=$,Y=g7(Z),v6(W)+$J(J,Y);var J,W,Y}function a7($,Z){return xj($.calendar,Cj,$,g7(Z))}function t7($,Z){return xj($.calendar,DU,$,g7(Z))}function r7($,Z){let[J,W,Y]=jj(Z);return j=Y,Aj(l7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=jj(Z,3);return W>1&&($={...$,...BU($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?R0(j):j,{hours:Q,minutes:F}=G,[V,B]=E7(O0(G,3),Z1,Y$);qj(V);let U=ZJ(B,z),O=z>=0||!X||U;return(X<0?"-":"")+"P"+PY({Y:m$(G.years),M:m$(G.months),W:m$(G.weeks),D:m$(G.days)})+(Q||F||V||O?"T"+PY({H:m$(Q),M:m$(F),S:m$(V,O)+U}):"")})($,Y)}function xj($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==v;return W===1?Y===v?Z(J):v6(J):j?v6(J)+Sj(Y,W===2):Z(J)}function PY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function e7($,Z){return v6($)+"T"+Aj($,Z)}function v6($){return Cj($)+"-"+$1($.isoDay)}function Cj($){let{isoYear:Z}=$;return(Z<0||Z>9999?bj(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+$1($.isoMonth)}function DU($){return $1($.isoMonth)+"-"+$1($.isoDay)}function Aj($,Z){let J=[$1($.isoHour),$1($.isoMinute)];return Z!==-1&&J.push($1($.isoSecond)+((W,Y,j,z)=>ZJ(W*M1+Y*t$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function l$($,Z=0){if(Z===1)return"";let[J,W]=w1(Math.abs($),N4),[Y,j]=w1(W,P4),[z,X]=w1(j,Z1);return bj($)+$1(J)+":"+$1(Y)+(z||X?":"+$1(z)+ZJ(X):"")}function $J($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==v)return Sj(J,Z===2)}return""}function Sj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function ZJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(ID,""):J.slice(0,Z),J?"."+J:""}function bj($){return $<0?"-":"+"}function m$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function OU($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=X$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Ej($,Z){let J=E0(Z,$);return{calendar:Z.calendar,...p0(yX,J),offset:l$(J.offsetNanoseconds),timeZone:Z.timeZone}}function i$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return w7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,F,V,B)=>{let U=A0(F);B&&(V=q6(V));for(let O of Q){let D=n0(s0(O,U));if(B&&(D=q6(D)),D===V)return O}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(cU)}return z?A0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(dU);if(W.length)return W[J===3?1:0];let Y=A0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(_Z(G,-s));return WJ(X.getOffsetNanosecondsFor(_Z(G,s))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(X$(Y,z)))[J===2?0:W.length-1]}function JJ($){if(Math.abs($)>=s)throw RangeError(hU);return $}function WJ($){if($>s)throw RangeError(pU);return $}function YJ($,Z,J){return M0(o0(KZ(Z.epochNanoseconds,((W)=>{if(vj(W))throw RangeError(iU);return O0(W,5)})($?R0(J):J))))}function jJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...BJ(z,X,W,J?R0(Y):Y,j)}}function zJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return X0(FJ($(j),J,Z?R0(W):W,Y),j)}function XJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?R0(W):W,Y),j)}function GJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=O3(z,J);Z&&(W=X4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=s$(X,-1));let G=z.dateAdd(X,W,Y);return h$(O3(z,G),j)}function QJ($,Z,J){return z1(Rj(Z,$?R0(J):J)[0])}function BJ($,Z,J,W,Y){let j=O0(W,5),z=J.epochNanoseconds;if(vj(W)){let X=E0(J,$);z=KZ(h0($,{...W4(Z,X,{...W,...tJ},Y),...p0(G1,X)}),j)}else z=KZ(z,j),m(Y);return{epochNanoseconds:o0(z)}}function FJ($,Z,J,W){let[Y,j]=Rj(Z,J);return v1({...W4($,Z,{...J,...tJ,days:J.days+j},W),...Y})}function W4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);m(W);let Y=J.days+O0(J,5)[0];return Y?J$(s$(Z,Y)):Z}function O3($,Z,J=1){return s$(Z,J-$.day(Z))}function Rj($,Z){let[J,W]=O0(Z,5),[Y,j]=i6(j$($)+W);return[Y,J+j]}function s$($,Z){return Z?{...$,...s6(b0($)+Z*y0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...J1},W]}function VJ($){return $?Vj:A0}function j4($){return $?q(BJ,$):FJ}function UJ($){return $?q(MU,$):HU}function z4($){return $&&$.epochNanoseconds}function L3($,Z){return $<=6-(z4(Z)?1:0)}function DJ($,Z,J,W,Y,j,z){let X=$(j1(z).relativeTo),G=Math.max(p$(Y),p$(j));if(L3(G,X))return e(RZ(((D,L,M,T)=>{let P=KZ(O0(D),O0(L),T?-1:1);if(!Number.isFinite(P[0]))throw RangeError(H4);return{...P0,...kZ(P,M)}})(Y,j,G,W)));if(!X)throw RangeError(T4);W&&(j=R0(j));let[Q,F,V]=Y4(Z,J,X),B=j4(V),U=UJ(V),O=B(F,Q,Y);return e(U(F,Q,B(F,O,j),G))}function kj($,Z,J,W,Y){let j=p$(W),[z,X,G,Q,F]=((C,S,w)=>{C=p7(C,m6);let x=J5(C),f=w(C[hX]),_=m7(C),k=w3(C,7),H0=k3(C);if(x===void 0&&H0===void 0)throw RangeError(sU);return H0==null&&(H0=0),x==null&&(x=Math.max(H0,S)),Gj(x,H0),_=h7(_,H0,1),[x,H0,_,k,f]})(Y,j,$),V=Math.max(j,z);if(!z4(F)&&V<=6)return e(RZ(((C,S,w,x,f)=>{let _=$4(O0(C),w,x,f);return{...P0,...kZ(_,S)}})(W,z,X,G,Q)));if(!F)throw RangeError(T4);let[B,U,O]=Y4(Z,J,F),D=VJ(O),L=j4(O),M=UJ(O),T=L(U,B,W),P=M(U,B,T,z),K=W.sign,R=G$(P);if(K&&R&&K!==R)throw RangeError(b3);return R&&(P=e6(P,D(T),z,X,G,Q,U,B,D,L)),e(P)}function wj($){return $.sign===-1?X4($):$}function X4($){return e(R0($))}function R0($){let Z={};for(let J of p)Z[J]=-1*$[J]||0;return Z}function fj($){return!$.sign}function G$($,Z=p){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(lU);J=Y}}return J}function RZ($){for(let Z of ZD)e0(Z,$[Z],-AY,AY,1);return qj(n0(O0($),Z1)),$}function qj($){if(!Number.isSafeInteger($))throw RangeError(uU)}function O0($,Z=6){return vY($,Z,p)}function kZ($,Z=6){let[J,W]=$,Y=c6(W,Z,p);if(Y[p[Z]]+=J*(s/L1[Z]),!Number.isFinite(Y[p[Z]]))throw RangeError(H4);return Y}function G4($,Z=5){return c6($,Z,p)}function vj($){return Boolean(G$($,vX))}function p$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function LU($,Z){return[$,Z]}function NY($){let Z=Math.floor($/b6)*b6;return[Z,Z+b6]}function gj($){let Z=Q$($=k6($));if(!Z)throw RangeError(g0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(g0($));J=wZ(Z.offset)}return Z.timeZone&&HJ(Z.timeZone,1),M0(w7(n6(Z),J))}function yj($){let Z=Q$(J0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return sj(Z,Z.offset?wZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return oj(Z)}function mj($,Z){let J=Q$(J0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?wZ(W):void 0,[,j,z]=_3(Z);return sj(J,Y,j,z)}function wZ($){let Z=HJ($);if(Z===void 0)throw RangeError(g0($));return Z}function hj($){let Z=Q$(J0($));if(!Z||Z.m)throw RangeError(g0($));return X0(nj(Z))}function Q4($){let Z=Q$(J0($));if(!Z||Z.m)throw RangeError(g0($));return G0(Z.p?nj(Z):oj(Z))}function pj($,Z){let J=LJ(J0(Z));if(J)return OJ(J),h$(k7(d$(J)));let W=Q4(Z);return h$(O3($(W.calendar),W))}function OJ($){if($.calendar!==v)throw RangeError(f1($.calendar))}function cj($,Z){let J=MJ(J0(Z));if(J)return OJ(J),f6(d$(J));let W=Q4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,F]=j.I(z,X),[V,B]=j.N(Q,F,G);return f6(J$(j.P(V,B,G)),Y)}function dj($){let Z,J=((W)=>{let Y=bD.exec(W);return Y?(B4(Y[10]),rj(Y)):void 0})(J0($));if(!J){if(J=Q$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(f1("Z"));OJ(J)}if((Z=LJ($))&&HY(Z))throw RangeError(g0($));if((Z=MJ($))&&HY(Z))throw RangeError(g0($));return z1(o6(J,1))}function uj($){let Z=((J)=>{let W=kD.exec(J);return W?((Y)=>{function j(F,V,B){let U=0,O=0;if(B&&([U,G]=w1(G,L1[B])),F!==void 0){if(X)throw RangeError(f1(F));O=((D)=>{let L=parseInt(D);if(!Number.isFinite(L))throw RangeError(f1(D));return L})(F),z=1,V&&(G=TJ(V)*(L1[B]/Z1),X=1)}return U+O}let z=0,X=0,G=0,Q={...AZ(p,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...c6(G,2,p)};if(!z)throw RangeError(OX(p));return PJ(Y[1])<0&&(Q=R0(Q)),Q})(W):void 0})(J0($));if(!Z)throw RangeError(g0($));return e(RZ(Z))}function lj($){let Z=Q$($)||LJ($)||MJ($);return Z?Z.calendar:$}function ij($){let Z=Q$($);return Z&&(Z.timeZone||Z.m&&$Z||Z.offset)||$}function sj($,Z,J=0,W=0){let Y=F4($.timeZone),j=S4(Y);return N0(i$(j,n6($),Z,J,W,!j.v,$.m),Y,x3($.calendar))}function nj($){return aj(v1(n6($)))}function oj($){return aj(J$(d$($)))}function aj($){return{...$,calendar:x3($.calendar)}}function Q$($){let Z=SD.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:tj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...rj(J.slice(5)),...B4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function LJ($){let Z=CD.exec($);return Z?((J)=>({isoYear:tj(J),isoMonth:parseInt(J[4]),isoDay:1,...B4(J[5])}))(Z):void 0}function MJ($){let Z=AD.exec($);return Z?((J)=>({isoYear:CZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...B4(J[3])}))(Z):void 0}function HJ($,Z){let J=ED.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(f1(j));return JJ((NZ(W[2])*N4+NZ(W[3])*P4+NZ(W[4])*Z1+TJ(W[5]||""))*PJ(W[1]))})(J,Z):void 0}function tj($){let Z=PJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(f1(-0));return Z*J}function rj($){let Z=NZ($[3]);return{...i6(TJ($[4]||""))[0],isoHour:NZ($[1]),isoMinute:NZ($[2]),isoSecond:Z===60?59:Z}}function B4($){let Z,J,W=[];if($.replace(RD,(Y,j,z)=>{let X=Boolean(j),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(f1(Y))}else{if(J)throw RangeError(f1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(f1($));return{timeZone:J,calendar:W[0]||v}}function TJ($){return parseInt($.padEnd(9,"0"))}function fZ($){return new RegExp(`^${$}$`,"i")}function PJ($){return $&&$!=="+"?-1:1}function NZ($){return $===void 0?0:parseInt($)}function ej($){return F4(J0($))}function F4($){let Z=NJ($);return typeof Z=="number"?l$(Z):Z?((J)=>{if(fD.test(J))throw RangeError(mU);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?LY(j).replace(/island|noronha|murdo|rivadavia|urville/,LY):j)).join("/")})($):$Z}function KY($){let Z=NJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:$Z}function NJ($){let Z=HJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==$Z?wD($):void 0}function KJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function _J($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function $z($,Z,J,W,Y,j){let z=$(j1(j).relativeTo),X=Math.max(p$(W),p$(Y));if(fY(p,W,Y))return 0;if(L3(X,z))return S0(O0(W),O0(Y));if(!z)throw RangeError(T4);let[G,Q,F]=Y4(Z,J,z),V=VJ(F),B=j4(F);return S0(V(B(Q,G,W)),V(B(Q,G,Y)))}function IJ($,Z){return n$($,Z)||V4($,Z)}function n$($,Z){return Z$(b0($),b0(Z))}function V4($,Z){return Z$(j$($),j$(Z))}function Zz($,Z){return!KJ($,Z)}function Jz($,Z){return!_J($,Z)&&!!U4($.timeZone,Z.timeZone)&&EZ($.calendar,Z.calendar)}function Wz($,Z){return!IJ($,Z)&&EZ($.calendar,Z.calendar)}function Yz($,Z){return!n$($,Z)&&EZ($.calendar,Z.calendar)}function jz($,Z){return!n$($,Z)&&EZ($.calendar,Z.calendar)}function zz($,Z){return!n$($,Z)&&EZ($.calendar,Z.calendar)}function Xz($,Z){return!V4($,Z)}function U4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return KY(J)===KY(W)}catch(Y){}}function xJ($,Z,J,W){let Y=bZ($,z0(W),3,5),j=D4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return e($?R0(j):j)}function CJ($,Z,J,W,Y,j){let z=L4(W.calendar,Y.calendar),X=z0(j),[G,Q,F,V]=bZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,O=S0(U,B),D;if(O)if(G<6)D=D4(B,U,G,Q,F,V);else{let L=Z(((T,P)=>{if(!U4(T,P))throw RangeError(NX);return T})(W.timeZone,Y.timeZone)),M=$(z);D=Qz(M,L,W,Y,O,G,X),D=e6(D,U,G,Q,F,V,M,W,Vj,q(BJ,L))}else D=P0;return e(J?R0(D):D)}function AJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),[X,G,Q,F]=bZ(Z,z,6),V=A0(J),B=A0(W),U=S0(B,V),O;if(U)if(X<=6)O=D4(V,B,X,G,Q,F);else{let D=$(j);O=Bz(D,J,W,U,X,z),O=e6(O,B,X,G,Q,F,D,J,A0,FJ)}else O=P0;return e(Z?R0(O):O)}function SJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y);return Gz(Z,()=>$(j),J,W,...bZ(Z,z,6,9,6),z)}function bJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),X=bZ(Z,z,9,9,8),G=$(j);return Gz(Z,()=>G,O3(G,J),O3(G,W),...X,z)}function Gz($,Z,J,W,Y,j,z,X,G){let Q=A0(J),F=A0(W),V;if(S0(F,Q))if(Y===6)V=D4(Q,F,Y,j,z,X);else{let B=Z();V=B.dateUntil(J,W,Y,G),j===6&&z===1||(V=e6(V,F,Y,j,z,X,B,J,A0,W4))}else V=P0;return e($?R0(V):V)}function EJ($,Z,J,W){let Y=z0(W),[j,z,X,G]=bZ($,Y,5,5),Q=z$(RJ(Z,J),I3(z,X),G),F={...P0,...G4(Q,j)};return e($?R0(F):F)}function MU($,Z,J,W,Y,j){let z=S0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Fz(J.epochNanoseconds,W.epochNanoseconds,Y):Qz(Z,$,J,W,z,Y,j):P0}function HU($,Z,J,W,Y){let j=A0(Z),z=A0(J),X=S0(z,j);return X?W<=6?Fz(j,z,W):Bz($,Z,J,X,W,Y):P0}function Qz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,O,D)=>{function L(){return S={...s$(P,R++*-D),...T},w=h0(B,S),S0(K,w)===-D}let M=E0(U,B),T=p0(G1,M),P=E0(O,B),K=O.epochNanoseconds,R=0,C=RJ(M,P),S,w;if(Math.sign(C)===-D&&R++,L()&&(D===-1||L()))throw RangeError(b3);let x=n0(s0(w,K));return[M,S,x]})(Z,J,W,Y);var F,V;return{...j===6?(F=X,V=G,{...P0,days:Vz(F,V)}):$.dateUntil(X,G,j,z),...G4(Q)}}function Bz($,Z,J,W,Y,j){let[z,X,G]=((Q,F,V)=>{let B=F,U=RJ(Q,F);return Math.sign(U)===-V&&(B=s$(F,-V),U+=s*V),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...G4(G)}}function D4($,Z,J,W,Y,j){return{...P0,...kZ($4(s0($,Z),W,Y,j),J)}}function Fz($,Z,J){return{...P0,...kZ(s0($,Z),J)}}function Vz($,Z){return O4(b0($),b0(Z))}function O4($,Z){return Math.trunc((Z-$)/y0)}function RJ($,Z){return j$(Z)-j$($)}function L4($,Z){if(!EZ($,Z))throw RangeError(iJ);return $}function TU($){function Z(Y){return((j,z)=>({...Uz(j,z),F:j.month,day:parseInt(j.day)}))(R7(J,Y),W)}let J=X5($),W=g6($);return{id:$,O:PU(Z),B:NU(Z)}}function PU($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function NU($){let Z=$(0).year-XD;return m0((J)=>{let W,Y=SZ(J-Z),j=[],z=[];do Y+=400*y0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*y0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=y0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:IX(z.reverse())}})}function Uz($,Z){let J,W,Y=Dz($);if($.era){let j=wX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=Tz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Dz($){return parseInt($.relatedYear||$.year)}function O7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function M3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function C6($){let Z=IY(this,$),J=IY(this,$-1),W=Z.length;if(W>J.length){let Y=Pz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function A6($){return O4(M3.call(this,$),M3.call(this,$+1))}function _Y($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),O4(J[Z-1],Y[W-1])}function S6($){return this.B($).k.length}function IY($,Z){return Object.keys($.B(Z).C)}function Oz($){return x3(J0($))}function x3($){if(($=$.toLowerCase())!==v&&$!==_4&&g6($)!==g6(X5($).resolvedOptions().calendar))throw RangeError(yU($));return $}function g6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Lz($){return this.R($)[0]}function Mz($){return this.R($)[1]}function kJ($){let[Z]=this.h($);return O4(this.q(Z),b0($))+1}function Hz($){let Z=vD.exec($);if(!Z)throw RangeError(vU($));return[parseInt(Z[1]),Boolean(Z[2])]}function y6($,Z,J){return $+(Z||J&&$>=J?1:0)}function L7($,Z){return $-(Z&&$>=Z?1:0)}function Tz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function M7($){return wX[Nz($)]}function Pz($){return rU[Nz($)]}function Nz($){return g6($.id||v)}function Kz($,Z,J,W){let Y=B$(J,W,X1,[],bX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=o$(Y),X=$(Y.timeZone);return{epochNanoseconds:i$(Z(X),{...j,...z},Y.offset!==void 0?wZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...J1}}function _z($,Z,J,W,Y,j){let z=B$(J,Y,X1,AX,bX),X=$(z.timeZone),[G,Q,F]=_3(j),V=J.dateFromFields(z,t6(j,G)),B=o$(z,G);return N0(i$(Z(X),{...V,...B},z.offset!==void 0?wZ(z.offset):void 0,Q,F),X,W)}function Iz($,Z,J){let W=B$($,Z,X1,[],m1),Y=m(J);return X0(v1({...$.dateFromFields(W,t6(J,Y)),...o$(W,Y)}))}function wJ($,Z,J,W=[]){let Y=B$($,Z,X1,W);return $.dateFromFields(Y,J)}function fJ($,Z,J,W){let Y=B$($,Z,oJ,W);return $.yearMonthFromFields(Y,J)}function qJ($,Z,J,W,Y=[]){let j=B$($,J,X1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=CZ),$.monthDayFromFields(j,W)}function xz($,Z){let J=m(Z);return z1(o$(O1($,T7,[],1),J))}function Cz($){let Z=O1($,aJ);return e(RZ({...P0,...Z}))}function B$($,Z,J,W=[],Y=[]){return O1(Z,[...$.fields(J),...Y].sort(),W)}function O1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(EU(X));if(X==="constructor"||X==="__proto__")throw RangeError(uJ(X));let G=$[X];if(G!==void 0)z=1,SY[X]&&(G=SY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(dJ(X));Y[X]=kX[X]}j=X}if(W&&!z)throw TypeError(OX(Z));return Y}function o$($,Z){return o6(hD({...kX,...$}),Z)}function Az($,Z,J,W,Y,j){let z=z0(j),{calendar:X,timeZone:G}=J;return N0(((Q,F,V,B,U)=>{let O=C3(Q,V,B,X1,SX,CX),[D,L,M]=_3(U,2);return i$(F,{...Q.dateFromFields(O,t6(U,D)),...o$(O,D)},wZ(O.offset),L,M)})($(X),Z(G),W,Y,z),G,X)}function Sz($,Z,J,W,Y){let j=z0(Y);return X0(((z,X,G,Q)=>{let F=C3(z,X,G,X1,m1),V=m(Q);return v1({...z.dateFromFields(F,t6(Q,V)),...o$(F,V)})})($(Z.calendar),J,W,j))}function bz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let F=C3(z,X,G,X1);return z.dateFromFields(F,Q)})($(Z.calendar),J,W,j)}function Ez($,Z,J,W,Y){let j=z0(Y);return h$(((z,X,G,Q)=>{let F=C3(z,X,G,oJ);return z.yearMonthFromFields(F,Q)})($(Z.calendar),J,W,j))}function Rz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let F=C3(z,X,G,X1);return z.monthDayFromFields(F,Q)})($(Z.calendar),J,W,j)}function kz($,Z,J){return z1(((W,Y,j)=>{let z=m(j);return o$({...p0(T7,W),...O1(Y,T7)},z)})($,Z,J))}function wz($,Z){return e((J=$,W=Z,RZ({...J,...O1(W,aJ)})));var J,W}function C3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=O1(Z,z,j),G=O1(J,z);return X=$.mergeFields(X,G),O1(X,z,[])}function vJ($,Z){let J=B$($,Z,RX);return $.monthDayFromFields(J)}function gJ($,Z,J){let W=B$($,Z,EX);return $.yearMonthFromFields(W,J)}function fz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=O1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=O1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function B7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=M7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(kU);if(!j)throw RangeError(RU);let z=j[J];if(z===void 0)throw RangeError(fU(J));let X=Tz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(wU);Y=X}else if(Y===void 0)throw TypeError(qU(j));return Y}function F7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,F)=>{let V=X.U(Q),[B,U]=Hz(G),O=y6(B,U,V);if(U){let D=Pz(X);if(D===void 0)throw RangeError(V3);if(D>0){if(O>D)throw RangeError(V3);if(V===void 0){if(F===1)throw RangeError(V3);O--}}else{if(O!==-D)throw RangeError(V3);if(V===void 0&&F===1)throw RangeError(V3)}}return O})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(TX);Y=z,W=1}else if(Y===void 0)throw TypeError(gU);return e0("month",Y,1,$.L(J),W)}function xY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function V7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function qz($){return M0(o0(l6(u6($))))}function vz($,Z,J,W,Y=v){return N0(o0(l6(u6(J))),Z(W),$(Y))}function gz($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,F=v){return X0(v1(n6(W1(C0,AZ(I4,[Z,J,W,Y,j,z,X,G,Q])))),$(F))}function yz($,Z,J,W,Y=v){return G0(J$(d$(W1(C0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function mz($,Z,J,W=v,Y=1){let j=C0(Z),z=C0(J),X=$(W);return h$(k7(d$({isoYear:j,isoMonth:z,isoDay:C0(Y)})),X)}function hz($,Z,J,W=v,Y=CZ){let j=C0(Z),z=C0(J),X=$(W);return f6(J$(d$({isoYear:C0(Y),isoMonth:j,isoDay:z})),X)}function pz($=0,Z=0,J=0,W=0,Y=0,j=0){return z1(o6(W1(C0,AZ(G1,[$,Z,J,W,Y,j])),1))}function cz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return e(RZ(W1(iY,AZ(p,[$,Z,J,W,Y,j,z,X,G,Q]))))}function yJ($,Z,J=v){return N0($.epochNanoseconds,Z,J)}function dz($){return M0($.epochNanoseconds)}function mJ($,Z){return X0(E0(Z,$))}function hJ($,Z){return G0(E0(Z,$))}function uz($,Z,J){return gJ($(Z.calendar),J)}function lz($,Z,J){return vJ($(Z.calendar),J)}function pJ($,Z){return z1(E0(Z,$))}function iz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=v7(G);return h0(j(z),X,Q)})($,J,Z,W);return N0(o0(Y),J,Z.calendar)}function sz($,Z,J){let W=$(Z.calendar);return h$({...Z,...gJ(W,J)})}function nz($,Z,J){return vJ($(Z.calendar),J)}function oz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):J1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function az($,Z=J1){return X0(v1({...$,...Z}))}function tz($,Z,J){return gJ($(Z.calendar),J)}function rz($,Z,J){return vJ($(Z.calendar),J)}function ez($,Z,J,W){return((Y,j,z)=>fz(Y,j,EX,q1(z),R3))($(Z.calendar),J,W)}function $X($,Z,J,W){return((Y,j,z)=>fz(Y,j,RX,q1(z),K4))($(Z.calendar),J,W)}function ZX($,Z,J,W,Y){let j=q1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function JX($,Z){return X0(v1({...$,...Z}))}function WX($){return M0(o0(IZ($,Z1)))}function YX($){return M0(o0(IZ($,M1)))}function jX($){return M0(o0(l6(u6($),t$)))}function zX($){return M0(o0(l6(u6($))))}function XX($,Z,J=J1){let W=Z.timeZone,Y=$(W),j={...E0(Z,Y),...J};return N0(i$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function GX($,Z,J){let W=Z.timeZone,Y=$(W),j={...E0(Z,Y),...J},z=VX(Z.calendar,J.calendar);return N0(i$(Y,j,j.offsetNanoseconds,2),W,z)}function QX($,Z=J1){return X0({...$,...Z})}function BX($,Z){return X0({...$,...Z},VX($.calendar,Z.calendar))}function M4($,Z){return{...$,calendar:Z}}function FX($,Z){return{...$,timeZone:Z}}function VX($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===v)return Z;if(W===v)return $;throw RangeError(iJ)}function KU($,Z){return(J)=>J===v?$:J===_4||J===xZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),qD(J))}function a$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=_7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=$Z,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function g1($,Z=cJ){let[J,,,W]=$;return(Y,j=JO,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,..._U($,G,z)]}}function cJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(oU);J.timeZone=$}return new F$(Z,J)}function _U($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==v)&&z!==X)throw RangeError(iJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function qZ($){let Z=A3();return X$(Z,$.getOffsetNanosecondsFor(Z))}function A3(){return IZ(Date.now(),M1)}function y1(){return EY||(EY=new F$().resolvedOptions().timeZone)}var IU=($,Z)=>`Non-integer ${$}: ${Z}`,xU=($,Z)=>`Non-positive ${$}: ${Z}`,CU=($,Z)=>`Non-finite ${$}: ${Z}`,AU=($)=>`Cannot convert bigint to ${$}`,SU=($)=>`Invalid bigint: ${$}`,bU="Cannot convert Symbol to string",UX="Invalid object",DX=($,Z,J,W,Y)=>Y?DX($,Y[Z],Y[J],Y[W]):S3($,Z)+`; must be between ${J}-${W}`,S3=($,Z)=>`Invalid ${$}: ${Z}`,dJ=($)=>`Missing ${$}`,uJ=($)=>`Invalid field ${$}`,EU=($)=>`Duplicate field ${$}`,OX=($)=>"No valid fields: "+$.join(),LX="Invalid bag",MX=($,Z,J)=>S3($,Z)+"; must be "+Object.keys(J).join(),HX="Cannot use valueOf",lJ="Invalid calling context",RU="Forbidden era/eraYear",kU="Mismatching era/eraYear",wU="Mismatching year/eraYear",fU=($)=>`Invalid era: ${$}`,qU=($)=>"Missing year"+($?"/era/eraYear":""),vU=($)=>`Invalid monthCode: ${$}`,TX="Mismatching month/monthCode",gU="Missing month/monthCode",CY="Cannot guess year",V3="Invalid leap month",PX="Invalid protocol",b3="Invalid protocol results",iJ="Mismatching Calendars",yU=($)=>`Invalid Calendar: ${$}`,NX="Mismatching TimeZones",mU="Forbidden ICU TimeZone",hU="Out-of-bounds offset",pU="Out-of-bounds TimeZone gap",cU="Invalid TimeZone offset",dU="Ambiguous offset",H4="Out-of-bounds date",uU="Out-of-bounds duration",lU="Cannot mix duration signs",T4="Missing relativeTo",iU="Cannot use large units",sU="Required smallestUnit or largestUnit",nU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,f1=($)=>`Invalid substring: ${$}`,KX=($)=>`Cannot format ${$}`,_X="Mismatching types for formatting",oU="Cannot specify TimeZone",IX=q(P3,($,Z)=>Z),vZ=q(P3,($,Z,J)=>J),$1=q(R6,2),H7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},E3=Object.keys(H7),y0=86400000,xX=1000,t$=1000,M1=1e6,Z1=1e9,P4=60000000000,N4=3600000000000,s=86400000000000,L1=[1,t$,M1,Z1,P4,N4,s],m1=E3.slice(0,6),T7=N3(m1),CX=["offset"],AX=["timeZone"],SX=m1.concat(CX),bX=SX.concat(AX),P7=["era","eraYear"],aU=P7.concat(["year"]),K4=["year"],sJ=["monthCode"],nJ=["month"].concat(sJ),R3=["day"],oJ=nJ.concat(K4),EX=sJ.concat(K4),X1=R3.concat(oJ),tU=R3.concat(nJ),RX=R3.concat(sJ),kX=vZ(m1,0),v="iso8601",_4="gregory",xZ="japanese",wX={[_4]:{bce:-1,ce:0},[xZ]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},rU={chinese:13,dangi:13,hebrew:-6},J0=q(d6,"string"),fX=q(d6,"boolean"),eU=q(d6,"number"),qX=q(d6,"function"),p=E3.map(($)=>$+"s"),aJ=N3(p),$D=p.slice(0,6),vX=p.slice(6),ZD=vX.slice(1),JD=IX(p),P0=vZ(p,0),tJ=vZ($D,0),rJ=q(qY,p),G1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],eJ=["isoDay","isoMonth","isoYear"],I4=G1.concat(eJ),$5=N3(eJ),gX=N3(G1),yX=N3(I4),J1=vZ(gX,0),WD=q(qY,I4),F$=Intl.DateTimeFormat,mX="en-GB",Z5=1e8,YD=Z5*y0,jD=[Z5,0],zD=[-Z5,0],H3=275760,T3=-271821,XD=1970,CZ=1972,k1=12,GD=SZ(1868,9,8),QD=m0(QU,WeakMap),m6="smallestUnit",N7="unit",D3="roundingIncrement",U7="fractionalSecondDigits",hX="relativeTo",pX={constrain:0,reject:1},BD=Object.keys(pX),FD={compatible:0,reject:1,earlier:2,later:3},VD={reject:0,use:1,prefer:2,ignore:3},UD={auto:0,never:1,critical:2,always:3},DD={auto:0,never:1,critical:2},OD={auto:0,never:1},LD={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},k3=q(c7,m6),J5=q(c7,"largestUnit"),MD=q(c7,N7),cX=q(u$,"overflow",pX),dX=q(u$,"disambiguation",FD),HD=q(u$,"offset",VD),W5=q(u$,"calendarName",UD),TD=q(u$,"timeZoneName",DD),PD=q(u$,"offset",OD),w3=q(u$,"roundingMode",LD),gZ="PlainYearMonth",yZ="PlainMonthDay",r$="PlainDate",e$="PlainDateTime",x4="PlainTime",h1="ZonedDateTime",C4="Instant",A4="Duration",ND=[Math.floor,($)=>x6($)?Math.floor($):Math.round($),Math.ceil,($)=>x6($)?Math.ceil($):Math.round($),Math.trunc,($)=>x6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>x6($)?($=Math.trunc($)||0)+$%2:Math.round($)],$Z="UTC",b6=5184000,KD=w6(1847),_D=w6(new Date().getUTCFullYear()+10),ID=/0+$/,E0=m0(OU,WeakMap),AY=4294967295,S4=m0(($)=>{let Z=NJ($);return typeof Z=="object"?new lX(Z):new uX(Z||0)});class uX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[w7($,this.v)]}l(){}}class lX{constructor($){this.$=((Z)=>{function J(G){let Q=D7(G,z,X),[F,V]=NY(Q),B=Y(F),U=Y(V);return B===U?B:W(j(F,V),B,U,G)}function W(G,Q,F,V){let B,U;for(;(V===void 0||(B=V<G[0]?Q:V>=G[1]?F:void 0)===void 0)&&(U=G[1]-G[0]);){let O=G[0]+Math.floor(U/2);Z(O)===F?G[1]=O:G[0]=O+1}return B}let Y=m0(Z),j=m0(LU),z=KD,X=_D;return{G(G){let Q=J(G-86400),F=J(G+86400),V=G-Q,B=G-F;if(Q===F)return[V];let U=J(V);return U===J(B)?[G-U]:Q>F?[V,B]:[]},V:J,l(G,Q){let F=D7(G,z,X),[V,B]=NY(F),U=b6*Q,O=Q<0?()=>B>z||(z=F,0):()=>V<X||(X=F,0);for(;O();){let D=Y(V),L=Y(B);if(D!==L){let M=j(V,B);W(M,D,L);let T=M[0];if((Z$(T,G)||1)===Q)return T}V+=U,B+=U}}}})(((Z)=>(J)=>{let W=R7(Z,J*xX);return w6(Dz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(oY($))*Z1}getPossibleInstantsFor($){let[Z,J]=[w6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*M1+W.isoMicrosecond*t$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>o0(_Z(IZ(Y,Z1),J)))}l($,Z){let[J,W]=aY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return IZ(Y,Z1)}}var Y5="([+\u2212-])",E6="(?:[.,](\\d{1,9}))?",iX=`(?:(?:${Y5}(\\d{6}))|(\\d{4}))-?(\\d{2})`,j5="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+E6+")?)?",z5=Y5+j5,xD=iX+"-?(\\d{2})(?:[T ]"+j5+"(Z|"+z5+")?)?",sX="\\[(!?)([^\\]]*)\\]",b4=`((?:${sX}){0,9})`,CD=fZ(iX+b4),AD=fZ("(?:--)?(\\d{2})-?(\\d{2})"+b4),SD=fZ(xD+b4),bD=fZ("T?"+j5+"(?:"+z5+")?"+b4),ED=fZ(z5),RD=new RegExp(sX,"g"),kD=fZ(`${Y5}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${E6}H)?(?:(\\d+)${E6}M)?(?:(\\d+)${E6}S)?)?`),wD=m0(($)=>new F$(mX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),fD=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,qD=m0(TU),X5=m0(($)=>new F$(mX,{calendar:$,timeZone:$Z,era:"short",year:"numeric",month:"short",day:"numeric"})),vD=/^M(\d{2})(L?)$/,gD={era:k6,eraYear:C0,year:C0,month:MY,monthCode:k6,day:MY},yD=vZ(m1,C0),mD=vZ(p,iY),SY=Object.assign({},gD,yD,mD,{offset:k6}),hD=q(GU,m1,G1),bY={dateAdd($,Z,J){let W=m(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=O0(Z,5)[0],j||z)Y=((Q,F,V,B,U)=>{let[O,D,L]=Q.h(F);if(V){let[M,T]=Q.I(O,D);O+=V,D=y6(M,T,Q.U(O)),D=e0("month",D,1,Q.L(O),U)}return B&&([O,D]=Q._(O,D,B)),L=e0("day",L,1,Q.j(O,D),U),Q.q(O,D,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=b0($)}return Y+=(7*X+G)*y0,J$(s6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Vz({...$,...J1},{...Z,...J1});return J===7&&([G,Q]=Y$(Q,7)),{...P0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,F,V,B,U,O)=>{let D=B-Q,L=U-F,M=O-V;if(D||L){let T=Math.sign(D||L),P=G.j(B,U),K=0;if(Math.sign(M)===-T){let R=P;[B,U]=G._(B,U,-T),D=B-Q,L=U-F,P=G.j(B,U),K=T<0?-R:P}if(M=O-Math.min(V,P)+K,D){let[R,C]=G.I(Q,F),[S,w]=G.I(B,U);if(L=S-R||Number(w)-Number(C),Math.sign(L)===-T){let x=T<0&&-G.L(B);D=(B-=T)-Q,L=U-y6(R,C,G.U(B))+(x||G.L(B))}}}return[D,L,M]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...P0,years:j,months:z,days:X}},dateFromFields($,Z){let J=m(Z),W=B7(this,$),Y=F7(this,$,W,J),j=xY(this,$,Y,W,J);return G0(J$(this.P(W,Y,j)),this.id||v)},yearMonthFromFields($,Z){let J=m(Z),W=B7(this,$),Y=F7(this,$,W,J);return h$(k7(this.P(W,Y,1)),this.id||v)},monthDayFromFields($,Z){let J=m(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,G,Q,F,V;if(Y!==void 0){[X,G]=Hz(Y),V=RY($,"day");let B=this.N(X,G,V);if(!B)throw RangeError(CY);if([Q,F]=B,z!==void 0&&z!==F)throw RangeError(TX);W&&(F=e0("month",F,1,k1,1),V=e0("day",V,1,f7(j!==void 0?j:Q,F),J))}else{Q=j===void 0&&W?CZ:B7(this,$),F=F7(this,$,Q,J),V=xY(this,$,F,Q,J);let B=this.U(Q);G=F===B,X=L7(F,B);let U=this.N(X,G,V);if(!U)throw RangeError(CY);[Q,F]=U}return f6(J$(this.P(Q,F,V)),this.id||v)},fields($){return M7(this)&&$.includes("year")?[...$,...P7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return V7(J,Z,nJ),M7(this)&&(V7(J,Z,aU),this.id===xZ&&V7(J,Z,tU,P7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:kJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+$1(j)+(z?"L":""))(W,Y)},dayOfWeek:Zj,daysInWeek(){return 7}},pD={dayOfYear:kJ,h:rY,q:SZ},cD=Object.assign({},pD,{weekOfYear:Lz,yearOfWeek:Mz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let O=$j(B+U),D=U||1,L=Z(U3(G+O*D,7));return F=(O+(L-Q)*D)/7}let W=this.id?1:4,Y=Zj($),j=this.dayOfYear($),z=U3(Y-1,7),X=j-1,G=U3(z-X,7),Q=Z(G),F,V=Math.floor((X-Q)/7)+1,B=$.isoYear;return V?V>J(0)&&(V=1,B++):(V=J(-1),B--),[V,B,F]}}),dD={dayOfYear:kJ,h:O7,q:M3,weekOfYear:Lz,yearOfWeek:Mz,R(){return[]}},mZ=KU(Object.assign({},bY,cD,{h:rY,ee($){return this.id===_4?Jj($):this.id===xZ?QD($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[CZ,$]},K:q7,U(){},L:eY,J:($)=>$*k1,j:f7,X:$j,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:SZ,_:($,Z,J)=>($+=p6(J,k1),(Z+=x7(J,k1))<1?($--,Z+=k1):Z>k1&&($++,Z-=k1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},bY,dD,{h:O7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[L7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=O7.call(this,{isoYear:CZ,isoMonth:k1,isoDay:31}),z=C6.call(this,W),X=Y===z;(Z$($,L7(Y,z))||Z$(Number(Z),Number(X))||Z$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,F=C6.call(this,Q),V=y6($,Z,F);if(Z===(V===F)&&J<=_Y.call(this,Q,V))return[Q,V]}},K($){let Z=A6.call(this,$);return Z>A6.call(this,$-1)&&Z>A6.call(this,$+1)},U:C6,L:S6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=S6.call(this,z+Y);return j},j:_Y,X:A6,P($,Z,J){return s6(M3.call(this,$,Z,J))},q:M3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(H4);if(J<0)for(;Z<1;)Z+=S6.call(this,--$);else{let W;for(;Z>(W=S6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),W$="numeric",hZ=["timeZoneName"],nX={month:W$,day:W$},G5={year:W$,month:W$},Q5=Object.assign({},G5,{day:W$}),B5={hour:W$,minute:W$,second:W$},F5=Object.assign({},Q5,B5),uD=Object.assign({},F5,{timeZoneName:"short"}),lD=Object.keys(G5),iD=Object.keys(nX),sD=Object.keys(Q5),nD=Object.keys(B5),V5=["dateStyle"],oD=lD.concat(V5),aD=iD.concat(V5),U5=sD.concat(V5,["weekday"]),f3=nD.concat(["dayPeriod","timeStyle"]),D5=U5.concat(f3),tD=D5.concat(hZ),rD=hZ.concat(f3),eD=hZ.concat(U5),$O=hZ.concat(["day","weekday"],f3),ZO=hZ.concat(["year","weekday"],f3),JO={},O5=[a$(D5,F5),r6],oX=[a$(tD,uD),r6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(NX);return J}],L5=[a$(D5,F5,hZ),b0],M5=[a$(U5,Q5,rD),b0],H5=[a$(f3,B5,eD),($)=>j$($)/M1],T5=[a$(oD,G5,$O),b0,1],P5=[a$(aD,nX,ZO),b0,1],EY;function P1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(lJ);eX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...F){return G.call(this,X(this),...F)},K7(Q))}function X(G){let Q=I0(G);if(!Q||Q.branding!==$)throw TypeError(lJ);return Q}return Object.defineProperties(j.prototype,{...kY(W1(z,J)),...c$(W1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...c$(Y),...K7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return eX(Q,G),Q},X]}function JG($){return $=$.concat("id").sort(),(Z)=>{if(!wY(Z,$))throw TypeError(PX);return Z}}function uZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(LX);return $}function E4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=I0(j)||{},{branding:X}=z,G=X===r$||Z.includes(X)?z:w0(j);return Y[W](G)};return J}function _5($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?mZ(j):(z=j,Object.assign(Object.create(HO),{i:z})))[J](W);var j,z};return Z}function L$(){throw TypeError(HX)}function v3({calendar:$}){return typeof $=="string"?new k5($):$}function aX($,Z){if(Z=z0(Z),L0($)){let W=I0($);if(W&&W.branding===yZ)return m(Z),W;let Y=jG($);return qJ(g4(Y||v),!Y,$,Z)}let J=cj(mZ,$);return m(Z),J}function WG($,Z,J){return W=Z.call($,k0(M0(J))),JJ(K3(W));var W}function R4($,Z=QG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=q(Z[Y],$,qX($[Y]));return W}function o($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return o($,K5)}function H1($){if(L0($)){let Z=I0($);if(Z)switch(Z.branding){case C4:return Z;case h1:return M0(Z.epochNanoseconds)}}return gj($)}function tX($,Z,J){let W=Z.l(H1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function t($){return L0($)?(I0($)||{}).timeZone||IO($):((Z)=>F4(ij(J0(Z))))($)}function V$($,Z){if(L0($)){let J=I0($)||{};switch(J.branding){case x4:return m(Z),J;case e$:return m(Z),z1(J);case h1:return m(Z),pJ(B0,J)}return xz($,Z)}return m(Z),dj($)}function I5($){return $===void 0?void 0:V$($)}function pZ($,Z){if(Z=z0(Z),L0($)){let W=I0($);return W&&W.branding===gZ?(m(Z),W):fJ(q4(g3($)),$,Z)}let J=pj(mZ,$);return m(Z),J}function U$($,Z){if(Z=z0(Z),L0($)){let W=I0($)||{};switch(W.branding){case e$:return m(Z),W;case r$:return m(Z),X0({...W,...J1});case h1:return m(Z),mJ(B0,W)}return Iz(v4(g3($)),$,Z)}let J=hj($);return m(Z),J}function w0($,Z){if(Z=z0(Z),L0($)){let W=I0($)||{};switch(W.branding){case r$:return m(Z),W;case e$:return m(Z),G0(W);case h1:return m(Z),hJ(B0,W)}return wJ(v4(g3($)),$,Z)}let J=Q4($);return m(Z),J}function YG($,Z,J){return Y1(Z.call($,Y0(G0(J,$))))}function N1($){return(Z)=>typeof Z=="string"?mZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=q(W[z],J,J[z]);return j})(Z,$)}function W0($){if(L0($)){let Z=I0($);return Z&&Z.branding===A4?Z:Cz($)}return uj($)}function q3($){if($!==void 0){if(L0($)){let Z=I0($)||{};switch(Z.branding){case h1:case r$:return Z;case e$:return G0(Z)}let J=g3($);return{...Kz(t,o,v4(J),$),calendar:J}}return yj($)}}function g3($){return jG($)||v}function jG($){let{calendar:Z}=$;if(Z!==void 0)return _0(Z)}function _0($){return L0($)?(I0($)||{}).calendar||mO($):((Z)=>x3(lj(J0(Z))))($)}function cZ($,Z){if(Z=z0(Z),L0($)){let J=I0($);if(J&&J.branding===h1)return _3(Z),J;let W=g3($);return _z(t,o,v4(W),W,$,Z)}return mj($,Z)}function rX($){return W1((Z)=>(J)=>Z(N5(J)),$)}function N5($){return E0($,B0)}function WO(){let $=F$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(F$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);w5.set(this,((z,X={})=>{let G=new F$(z,X),Q=G.resolvedOptions(),F=Q.locale,V=p0(Object.keys(X),Q),B=m0(zO),U=(...O)=>{let D,L=O.map((M,T)=>{let P=I0(M),K=(P||{}).branding;if(T&&D&&D!==K)throw TypeError(_X);return D=K,P});return D?B(D)(F,V,...L):[G,...O]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&YO(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||jO(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function YO($){return function(...Z){let J=w5.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function jO($){return function(...Z){return w5.get(this).u[$](...Z)}}function zO($){let Z=XO[$];if(!Z)throw TypeError(KX($));return g1(Z,m0(cJ))}var XO={Instant:O5,PlainDateTime:L5,PlainDate:M5,PlainTime:H5,PlainYearMonth:T5,PlainMonthDay:P5},GO=g1(O5),QO=g1(oX),BO=g1(L5),FO=g1(M5),VO=g1(H5),UO=g1(T5),DO=g1(P5),x5={era:hY,eraYear:C7,year:K3,month:Y1,daysInMonth:Y1,daysInYear:Y1,inLeapYear:fX,monthsInYear:Y1},w4={monthCode:J0},C5={day:Y1},zG={dayOfWeek:Y1,dayOfYear:Y1,weekOfYear:pY,yearOfWeek:C7,daysInWeek:Y1},XG=Object.assign({},x5,w4,C5,zG),k4=new WeakMap,I0=k4.get.bind(k4),eX=k4.set.bind(k4),OO={...E4(x5,[gZ]),...E4(zG,[]),...E4(w4,[gZ,yZ]),...E4(C5,[yZ])},A5=_5(XG),LO=_5({...x5,...w4}),MO=_5({...w4,...C5}),y3={calendarId:($)=>T0($.calendar)},HO=W1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(G0(J,W))))},XG),TO=P3(($)=>(Z)=>Z[$],p.concat("sign")),S5=P3(($,Z)=>(J)=>J[G1[Z]],m1),GG={epochSeconds:Qj,epochMilliseconds:r6,epochMicroseconds:Bj,epochNanoseconds:Fj},m3=q(_7,new Set(["branding"])),[PO,dZ,NO]=P1(yZ,q(hz,_0),{...y3,...MO},{getISOFields:m3,getCalendar:v3,with($,Z,J){return dZ(Rz(vO,$,this,uZ(Z),J))},equals:($,Z)=>zz($,aX(Z)),toPlainDate($,Z){return Y0($X(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=DO(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:L$},{from:($,Z)=>dZ(aX($,Z))}),QG={getOffsetNanosecondsFor:WG,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,K0(X0(J,v)))].map((j)=>_O(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(S0),WJ(n0(s0(W[0],W[Y-1])))),W}},K5={getOffsetNanosecondsFor:WG},[KO,k0,_O]=P1(C4,qz,GG,{add:($,Z)=>k0(YJ(0,$,W0(Z))),subtract:($,Z)=>k0(YJ(1,$,W0(Z))),until:($,Z,J)=>a(xJ(0,$,H1(Z),J)),since:($,Z,J)=>a(xJ(1,$,H1(Z),J)),round:($,Z)=>k0(Dj($,Z)),equals:($,Z)=>Zz($,H1(Z)),toZonedDateTime($,Z){let J=q1(Z);return Q0(yJ($,t(J.timeZone),_0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(yJ($,t(Z))),toLocaleString($,Z,J){let[W,Y]=GO(Z,J,$);return W.format(Y)},toString:($,Z)=>i7(t,B0,$,Z),toJSON:($)=>i7(t,B0,$),valueOf:L$},{from:($)=>k0(H1($)),fromEpochSeconds:($)=>k0(WX($)),fromEpochMilliseconds:($)=>k0(YX($)),fromEpochMicroseconds:($)=>k0(jX($)),fromEpochNanoseconds:($)=>k0(zX($)),compare:($,Z)=>KJ(H1($),H1(Z))}),[f4,DK]=P1("TimeZone",($)=>{let Z=ej($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(U$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(H1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=H1(Z).epochNanoseconds,W=R4(this,K5).getOffsetNanosecondsFor(J);return l$(W)},getPlainDateTimeFor($,Z,J=v){let W=H1(Z).epochNanoseconds,Y=R4(this,K5).getOffsetNanosecondsFor(W);return K0(X0(X$(W,Y),_0(J)))},getInstantFor($,Z,J){let W=U$(Z),Y=v7(J),j=R4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>tX(1,$,Z),getPreviousTransition:({o:$},Z)=>tX(-1,$,Z),equals($,Z){return!!U4(this,t(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=t($);return typeof Z=="string"?new f4(Z):Z}}),IO=JG(Object.keys(QG)),[xO,D$]=P1(x4,pz,S5,{getISOFields:m3,with($,Z,J){return D$(kz(this,uZ(Z),J))},add:($,Z)=>D$(QJ(0,$,W0(Z))),subtract:($,Z)=>D$(QJ(1,$,W0(Z))),until:($,Z,J)=>a(EJ(0,$,V$(Z),J)),since:($,Z,J)=>a(EJ(1,$,V$(Z),J)),round:($,Z)=>D$(Mj($,Z)),equals:($,Z)=>Xz($,V$(Z)),toZonedDateTime:($,Z)=>Q0(ZX(t,w0,o,$,Z)),toPlainDateTime:($,Z)=>K0(JX($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=VO(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:L$},{from:($,Z)=>D$(V$($,Z)),compare:($,Z)=>V4(V$($),V$(Z))}),[CO,O$,AO]=P1(gZ,q(mz,_0),{...y3,...LO},{getISOFields:m3,getCalendar:v3,with($,Z,J){return O$(Ez(qO,$,this,uZ(Z),J))},add:($,Z,J)=>O$(GJ($G,0,$,W0(Z),J)),subtract:($,Z,J)=>O$(GJ($G,1,$,W0(Z),J)),until:($,Z,J)=>a(bJ(ZG,0,$,pZ(Z),J)),since:($,Z,J)=>a(bJ(ZG,1,$,pZ(Z),J)),equals:($,Z)=>jz($,pZ(Z)),toPlainDate($,Z){return Y0(ez(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=UO(Z,J,$);return W.format(Y)},toString:a7,toJSON:($)=>a7($),valueOf:L$},{from:($,Z)=>O$(pZ($,Z)),compare:($,Z)=>n$(pZ($),pZ(Z))}),[SO,K0]=P1(e$,q(gz,_0),{...y3,...A5,...S5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return K0(Sz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>K0(M4($,_0(Z))),withPlainDate:($,Z)=>K0(BX($,w0(Z))),withPlainTime:($,Z)=>K0(QX($,I5(Z))),add:($,Z,J)=>K0(zJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>K0(zJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(AJ(T1,0,$,U$(Z),J)),since:($,Z,J)=>a(AJ(T1,1,$,U$(Z),J)),round:($,Z)=>K0(Lj($,Z)),equals:($,Z)=>Wz($,U$(Z)),toZonedDateTime:($,Z,J)=>Q0(iz(o,$,t(Z),J)),toPlainDate:($)=>Y0(G0($)),toPlainTime:($)=>D$(z1($)),toPlainYearMonth($){return O$(sz(q4,$,this))},toPlainMonthDay($){return dZ(nz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=BO(Z,J,$);return W.format(Y)},toString:n7,toJSON:($)=>n7($),valueOf:L$},{from:($,Z)=>K0(U$($,Z)),compare:($,Z)=>IJ(U$($),U$(Z))}),[bO,Y0,BG]=P1(r$,q(yz,_0),{...y3,...A5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return Y0(bz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>Y0(M4($,_0(Z))),add:($,Z,J)=>Y0(XJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(XJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(SJ(T1,0,$,w0(Z),J)),since:($,Z,J)=>a(SJ(T1,1,$,w0(Z),J)),equals:($,Z)=>Yz($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof f4?{timeZone:Z}:Z;return Q0(oz(t,V$,o,$,J))},toPlainDateTime:($,Z)=>K0(az($,I5(Z))),toPlainYearMonth($){return O$(tz(q4,$,this))},toPlainMonthDay($){return dZ(rz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=FO(Z,J,$);return W.format(Y)},toString:o7,toJSON:($)=>o7($),valueOf:L$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>n$(w0($),w0(Z))}),b5={fields($,Z,J){return[...Z.call($,J)]}},FG=Object.assign({dateFromFields($,Z,J,W){return BG(Z.call($,Object.assign(Object.create(null),J),W))}},b5),VG=Object.assign({yearMonthFromFields($,Z,J,W){return AO(Z.call($,Object.assign(Object.create(null),J),W))}},b5),UG=Object.assign({monthDayFromFields($,Z,J,W){return NO(Z.call($,Object.assign(Object.create(null),J),W))}},b5),E5={mergeFields($,Z,J,W){return q1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},EO=Object.assign({},FG,E5),RO=Object.assign({},VG,E5),kO=Object.assign({},UG,E5),R5={dateAdd($,Z,J,W,Y){return BG(Z.call($,Y0(G0(J,$)),a(e(W)),Y))}},DG=Object.assign({},R5,{dateUntil($,Z,J,W,Y,j){return yO(Z.call($,Y0(G0(J,$)),Y0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:E3[Y]})))}}),wO=Object.assign({},R5,{day:YG}),fO=Object.assign({},DG,{day:YG}),q4=N1(VG),v4=N1(FG),g4=N1(UG),qO=N1(RO),h3=N1(EO),vO=N1(kO),ZZ=N1(R5),T1=N1(DG),$G=N1(wO),ZG=N1(fO),[gO,a,yO]=P1(A4,cz,{...TO,blank:fj},{with:($,Z)=>a(wz($,Z)),negated:($)=>a(X4($)),abs:($)=>a(wj($)),add:($,Z,J)=>a(DJ(q3,T1,o,0,$,W0(Z),J)),subtract:($,Z,J)=>a(DJ(q3,T1,o,1,$,W0(Z),J)),round:($,Z)=>a(kj(q3,T1,o,$,Z)),total:($,Z)=>Uj(q3,T1,o,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:L$},{from:($)=>a(W0($)),compare:($,Z,J)=>$z(q3,ZZ,o,W0($),W0(Z),J)}),OG={toString:($)=>$.id,toJSON:($)=>$.id,...OO,dateAdd:({id:$,o:Z},J,W,Y)=>Y0(G0(Z.dateAdd(w0(J),W0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>a(e($.dateUntil(w0(Z),w0(J),Yj(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(wJ(Z,J,W,mY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>O$(fJ(Z,J,W,gY($))),monthDayFromFields:({id:$,o:Z},J,W)=>dZ(qJ(Z,0,J,W,yY($))),fields({o:$},Z){let J=new Set(X1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(uJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(I7(A7(Z)),I7(A7(J)))},[k5]=P1("Calendar",($)=>{let Z=Oz($);return{branding:"Calendar",id:Z,o:mZ(Z)}},{id:($)=>$.id},OG,{from($){let Z=_0($);return typeof Z=="string"?new k5(Z):Z}}),mO=JG(Object.keys(OG).slice(4)),[hO,Q0]=P1(h1,q(vz,_0,t),{...GG,...y3,...rX(A5),...rX(S5),offset:($)=>l$(N5($).offsetNanoseconds),offsetNanoseconds:($)=>N5($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Hj(o,$)},{getISOFields:($)=>Ej(B0,$),getCalendar:v3,getTimeZone:({timeZone:$})=>typeof $=="string"?new f4($):$,with($,Z,J){return Q0(Az(h3,o,$,this,uZ(Z),J))},withCalendar:($,Z)=>Q0(M4($,_0(Z))),withTimeZone:($,Z)=>Q0(FX($,t(Z))),withPlainDate:($,Z)=>Q0(GX(o,$,w0(Z))),withPlainTime:($,Z)=>Q0(XX(o,$,I5(Z))),add:($,Z,J)=>Q0(jJ(ZZ,o,0,$,W0(Z),J)),subtract:($,Z,J)=>Q0(jJ(ZZ,o,1,$,W0(Z),J)),until:($,Z,J)=>a(e(CJ(T1,o,0,$,cZ(Z),J))),since:($,Z,J)=>a(e(CJ(T1,o,1,$,cZ(Z),J))),round:($,Z)=>Q0(Oj(o,$,Z)),startOfDay:($)=>Q0(Tj(o,$)),equals:($,Z)=>Jz($,cZ(Z)),toInstant:($)=>k0(dz($)),toPlainDateTime:($)=>K0(mJ(B0,$)),toPlainDate:($)=>Y0(hJ(B0,$)),toPlainTime:($)=>D$(pJ(B0,$)),toPlainYearMonth($){return O$(uz(q4,$,this))},toPlainMonthDay($){return dZ(lz(g4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=QO(Z,J,$);return W.format(Y)},toString:($,Z)=>s7(B0,$,Z),toJSON:($)=>s7(B0,$),valueOf:L$},{from:($,Z)=>Q0(cZ($,Z)),compare:($,Z)=>_J(cZ($),cZ(Z))}),pO=Object.defineProperties({},{...h6("Temporal.Now"),...c$({timeZoneId:()=>y1(),instant:()=>k0(M0(A3())),zonedDateTime:($,Z=y1())=>Q0(N0(A3(),t(Z),_0($))),zonedDateTimeISO:($=y1())=>Q0(N0(A3(),t($),v)),plainDateTime:($,Z=y1())=>K0(X0(qZ(B0(t(Z))),_0($))),plainDateTimeISO:($=y1())=>K0(X0(qZ(B0(t($))),v)),plainDate:($,Z=y1())=>Y0(G0(qZ(B0(t(Z))),_0($))),plainDateISO:($=y1())=>Y0(G0(qZ(B0(t($))),v)),plainTimeISO:($=y1())=>D$(z1(qZ(B0(t($)))))})}),lZ=Object.defineProperties({},{...h6("Temporal"),...c$({PlainYearMonth:CO,PlainMonthDay:PO,PlainDate:bO,PlainTime:xO,PlainDateTime:SO,ZonedDateTime:hO,Instant:KO,Calendar:k5,TimeZone:f4,Duration:gO,Now:pO})}),cO=WO(),w5=new WeakMap,dO=Object.defineProperties(Object.create(Intl),c$({DateTimeFormat:cO}));var y4="x-gemi-socket";var PK="gemi.v1",LG="/__gemi/socket",NK=/^[A-Za-z0-9_-]{1,32}$/,KK={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function CK($){return $}function MG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:LG,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as uO,randomBytes as lO}from"crypto";function iO($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(uO("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var sO="__control",f5=250,nO=1e4,oO=15000;class q5{config;prefix;controlChannel;instanceId=lO(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??iO(),this.controlChannel=this.prefix+sO,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=p3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),oO,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${HG(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(nO,f5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(f5,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;p3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${HG(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??aO(Math.min(Z,f5));await p3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await p3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await p3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function p3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function aO($){return new Promise((Z)=>setTimeout(Z,$))}function HG($){return $ instanceof Error?$.message:String($)}import{createHmac as tO,hkdfSync as rO,randomBytes as TG}from"crypto";function PG($){return tO("sha256",eO()).update($).digest("base64url").slice(0,22)}var m4=null;function eO(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from(rO("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):TG(32);return m4={secret:$,key:Z},Z}function RK(){return TG(16).toString("base64url")}var $L=/^[A-Za-z0-9_-]{8,64}$/;function v5($){return typeof $==="string"&&$L.test($)}function NG($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class _G extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=M$(MG(),$),this.driver=WL(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new c3(this,h4($,Z[0]),null)}toUser($){return new c3(this,{topic:UZ($),pattern:U0},null)}toOthers($){return new IG(this,JL($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(h4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){h2(Z);let Y;try{Y=NG($.topic,Z,J,W?PG(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){g5(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=ZL($);g5(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new _G(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class c3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class IG{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new c3(this.manager,h4($,Z[0]),this.except)}toUser($){return new c3(this.manager,{topic:UZ($),pattern:U0},this.except)}}function h4($,Z){if(m2($))return{topic:A8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:G3($,Z??{}),pattern:$};if($===U0)throw new i('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:A8($)}}function ZL($){if($&&typeof $==="object"&&"user"in $)return{user:UZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:h4($.channel,$.params).topic};throw new i("Broadcast.revoke takes { user } or { channel }.")}function JL($){if($===null||$===void 0)return null;if(typeof $==="string")return v5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(y4);return v5(J)?J:null}function WL($,Z){let J=$.driver;if(J===void 0||J==="memory")return new KG;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new q5({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class y5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class YL{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1;clientFor($){return Promise.resolve(void 0)}async isAvailable($){return await this.clientFor($)!==null}async redirectUriFor($){return(await this.clientFor($))?.redirectUri}}import{createHash as m5,createHmac as jL,randomBytes as xG,timingSafeEqual as SG}from"crypto";var u3=600,p4="gemi_oauth",zL=`__Host-${p4}`;function iZ($,Z=p4){if(Z===p4)return $?zL:p4;return $?`__Host-${Z}`:Z}function d3($){return $.toString("base64url")}function bG($){return jL("sha256",HZ()).update(`gemi-oauth-state:${$}`).digest()}function CG($,Z){let J=m5("sha256").update($).digest(),W=m5("sha256").update(Z).digest();return SG(J,W)&&$.length===Z.length}function c4($,Z=Date.now(),J={}){let W=d3(xG(32)),Y=d3(xG(32)),j=XL(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+u3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{},...J.redirectUri!==void 0?{redirectUri:J.redirectUri}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:GL(z)}}function XL($){return d3(m5("sha256").update($).digest())}function GL($){let Z=d3(Buffer.from(JSON.stringify($)));return`${Z}.${d3(bG(Z))}`}function QL($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=bG(J);if(W.length!==Y.length||!SG(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string"||j.redirectUri!==void 0&&typeof j.redirectUri!=="string")return null;return j}catch{return null}}var H$=new Map,AG=1e4;function BL($,Z,J){if(H$.size>=AG){for(let[W,Y]of H$)if(Y<=J)H$.delete(W);while(H$.size>=AG){let W=H$.keys().next().value;if(W===void 0)break;H$.delete(W)}}H$.set($,Z)}function d4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=QL($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=CG(J.state,$.returnedState),Y=CG(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(H$.has(J.state))return{ok:!1,reason:"invalid_state"};return BL(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var h5=new WeakMap;function VL($){let Z=h5.get($);if(!Z)Z=$(FL(32).toString("hex")),h5.set($,Z),Z.catch(()=>h5.delete($));return Z}async function u4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await VL($.hashPassword))}catch{}return!1}async function JZ($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class c5 extends Error{}function p5($){return typeof $==="string"&&$!==""?$:null}function EG($){return q$($)}var UL=256;function RG($){return typeof $==="string"&&$!==""&&$.length<=UL?$:null}function kG($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function qG($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function wG($){let Z=$.cookies.get(i4);if(!Z)return null;qG($);try{return U1(decodeURIComponent(Z),"")||null}catch{return null}}class d5 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class vG extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class gG extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new q0("Not found",{status:404})}async function p1($,Z){if(!await R1(H(E).config[$],Z))l4()}async function l3($,Z,J,W){let{config:Y}=H(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await v$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function fG($,Z,J){let{config:W}=H(E);await l3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function sZ($){return await R1(H(E).config.verifyEmail,$)}class $0 extends B3{async me(){let $=await f0.user();if(!$)throw new i8;return $}async verifyEmail($=new A){await p1("password",$);let Z=await $.input(),{userProvider:J}=H(E),W=p5(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new A){let Z=H(E),{userProvider:J}=Z;if(!await R1(Z.config.magicLink,$)&&!await R1(Z.config.emailCode.enabled,$))l4();let W=p5($.search.get("token")),Y=null;try{Y=q$(decodeURIComponent($.search.get("email")??""))}catch{}if(await v$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp},Z.config.rateLimitKey),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,H(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await p1("magicLink",$);let Z=H(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=RG(Y);if(await v$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new u({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new u({pin:["Too many attempts"]});if(X.status!=="ok")throw new u({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new A){let Z=H(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new A){let Z=H(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new d5){await p1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(E);await fG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await sZ($)),X=typeof W==="string"&&await u4(j.config,W,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await JZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signIn($=new d5){await p1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(E);await fG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await sZ($)),X=typeof W==="string"&&await u4(j.config,W,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await JZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signUp(){let $=H(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await p1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:kG(Y.toJSON()),req:W},F=EG(j);if(await l3("signUp",F,W),!F)throw new u({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new u({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new u({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(F,!1))throw new u({email:["Email address already exists"]});let B=await J.hashPassword(z),U=H(d).detectLocale(W),O;if(G)O=await Z.findInvitation(G,F);let D,L="";if(O)D=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let M=await Z.createUser({email:F,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:O.organizationId,userId:M.id,organizationRole:O.role}),await J.onUserCreated(M,Q),M});else{if(L=await J.generateEmailVerificationToken(F),typeof J.verifyEmail==="function"&&!await sZ(W))L="";D=await Z.transaction(async()=>{let M=await Z.createUser({email:F,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(M,Q),M})}return await J.onSignUp(D,L,W.search.toJSON(),{req:W}),D}async signOut($=new A){let Z=S$($),J=H(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(E).accessTokenCookieOptions($,new Date(0))),H(E).cookieDomain($))$.ctx().setCookie("access_token","",{...H(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)DL(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new vG){await p1("password",$);let Z=await $.input(),J=EG(Z.get("email"));if(await l3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=H(E),j=await W.findUserByEmailAddress(J,await sZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new gG){await p1("password",$);let{userProvider:Z,config:J}=H(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=p5(j);await l3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new u({token:["Invalid token"]});if(lZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(lZ.Now.instant()).sign>=0)throw new u({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,await sZ($));if(!Q)throw new u({email:["User not found"]});let F=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:F}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new A){await p1("password",$);let{userProvider:Z,config:J}=H(E),W=await f0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await l3("signIn",q$(W?.email),$),typeof z!=="string")throw new u({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await sZ($));if(!(typeof j==="string"&&await u4(J,j,X?.password)))throw new u({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new A){let{provider:Z}=$.params,J=H(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await PZ(J,Z,$);if(!Y){if(W)throw new q0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=DZ($.rawRequest),z=U1($.search.get(l0),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else qG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:F}=c4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(iZ(j),F,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:u3}),{destination:await Y.getRedirectUrl($,{state:G,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new A){let{provider:Z}=$.params,J=H(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await PZ(Y.oauthProviders,Z,$);if(j&&!z)throw new q0("Not found",{status:404});let X=DZ($.rawRequest),G=iZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let F=$.search.get("error");if(F)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");let V=d4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(V.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let x=await z.redirectUriFor($);if(x!==void 0&&x!==V.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(x){if(x instanceof y5)return this.oauthFailure($,x.code);return console.error("Authentication error: OAuth provider callback failed",x),this.oauthFailure($,"provider_error")}let{name:U,username:O,providerId:D,emailVerified:L}=B??{},M=typeof B?.email==="string"?B.email:void 0,T=M?K6(M):null,P=D?await W.findUserBySocialAccount(Z,D):null,K="signin",R=!P&&!T&&!M&&!!D&&z.createUsersWithoutEmail===!0;if(!P&&R){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{P=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:U,username:O,locale:H(d).detectLocale($),req:$}),K="signup"}catch(x){let f=await W.findUserBySocialAccount(Z,D);if(!f)throw x;P=f}}if(!P){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,M?"invalid_email":D?"missing_email":"no_identity");if(L===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let x=H(d).detectLocale($);try{let f=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:M,name:U,username:O,locale:x,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(f==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(f==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(f)P=f.user,K=f.action}catch(f){let _=D?await W.findUserBySocialAccount(Z,D):null;if(!_)throw f;P=_}if(!P)return this.oauthFailure($,"account_conflict")}let C=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",C.token,H(E).accessTokenCookieOptions($,C.expiresAt)),K==="signup")await Y.onSignUp(P,"",$.search.toJSON(),{req:$});else await Y.onSignIn(P,$.search.toJSON(),{req:$});await JZ(J.config,{session:C,user:P,isNewUser:K==="signup",method:"oauth",req:$});let S=wG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?U1(Y.oauthCompleteProfilePath,""):"";if(w&&!P.email){let x=new URL(w,"http://gemi.invalid");x.searchParams.set(l0,S),S=`${x.pathname}${x.search}${x.hash}`}return{session:C,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=H(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=wG($),W=H(E).config.oauthFailurePath;if(W){let Y=U1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);S1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:G,config:Q}=H(E),F=(O)=>({provider:Z,userId:O,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!V&&B&&B!==W)V=await G.findUserByEmailAddress(B,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let O=await G.findSocialAccounts(V.id,Z);if(O.some((L)=>L.providerId===J))return{user:V,action:"signin"};if(O.some((L)=>L.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let D=O[0];if(D){if(!await G.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(F(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let O=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(F(O.id));return await Q.onUserCreated(O,{method:"oauth",input:{},req:$.req}),O}),action:"signup"}}async createMagicLinkToken($=new A){await p1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=H(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await v$("request",J,$,j,W.config.rateLimitKey),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new A){let Z=H(E),J=Z.config.emailCode;if(!await R1(J.enabled,$))l4();let W=await $.input(),Y=K6(W.get("email"));if(await v$("request",Y,$,J.requestLimit,Z.config.rateLimitKey),!Y)throw new u({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new A){let Z=H(E),{userProvider:J,config:W}=Z;if(!await R1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=K6(j),Q=RG(z);if(await v$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new u({code:["invalid_code"]});let F=null;if(!s9(Q,W.emailCode)){let D=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(D.status==="too_many_attempts")throw new u({code:["too_many_attempts"]});if(D.status!=="ok")throw new u({code:["invalid_code"]});F=D.row}let V=async()=>F?await Z.claimOneTimeCode(G,F.id):!0,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await V())throw new u({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let D=H(d).detectLocale($);try{B=await J.transaction(async()=>{if(!await V())throw new c5;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(L,{method:"email-code",input:kG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof c5)throw new u({code:["invalid_code"]});throw L}}else throw await V(),new u({code:["invalid_code"]});let O=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",O.token,H(E).accessTokenCookieOptions($,O.expiresAt)),await W.onSignIn(O,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:O,isNewUser:U,method:"email-code",req:$}),{session:O,isNewUser:U}}}function DL($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var yG="gemi_oauth_connection";class s4 extends B3{async connect($=new A){let Z=String($.params.provider??""),W=H(i3).providers[Z],Y=await f0.user(),j=U1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=DZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=c4(mG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(iZ(z,yG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:u3}),S1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:hG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new A){let Z=String($.params.provider??""),J=H(i3),W=await f0.user(),Y=DZ($.rawRequest),j=iZ(Y,yG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=d4({provider:mG(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let F=$.search.get("error");if(F)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:hG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await H(E).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof pG)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(G,Z,B.providerError??B.code);throw B}return this.finish(G,Z)}finish($,Z,J){let W=$||U1(H(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw S1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function mG($){return`connection:${$}`}function hG($,Z,J){if(J)return J;return`${WZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function cG($){return $.magicLink!==!1||Z7($.emailCode?.enabled)}function dG($){return Object.keys($.oauthProviders??{}).length>0}function uG($={}){let Z=[];if(cG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Z7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(dG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class lG extends b1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([U6,"auth"])}}function iG($={}){let Z=cG($),J=dG($);class W extends b1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[$0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[$0,"oauthCallback"])}}return class extends b1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[$0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":lG}}}class u5 extends x0{middlewares=["cache:private"];routes={"/sign-in":this.post($0,"signIn"),"/sign-in-v2":this.post($0,"signInV2"),"/sign-up":this.post($0,"signUp"),"/sign-out":this.post($0,"signOut"),"/forgot-password":this.post($0,"forgotPassword"),"/reset-password":this.post($0,"resetPassword"),"/change-password":this.post($0,"changePassword"),"/verify-email":this.post($0,"verifyEmail"),"/me":this.get($0,"me").middleware(["auth"]),"/magic-link":this.post($0,"createMagicLinkToken"),"/sign-in-with-pin":this.post($0,"signInWithPin"),"/sign-in-with-pin-v2":this.post($0,"signInWithPinV2"),"/email-code":this.post($0,"requestEmailCode"),"/email-code/verify":this.post($0,"verifyEmailCode")}}class l5 extends x0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new A().params.locale;return await H(d).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new A,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(d),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class i5{}class s5 extends i5{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await n4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function u_($){return $}function sG(){return{driver:new s5,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var OL=new Set([301,302,303,307,308]),LL="/api/__gemi__/services/image/";async function oG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=nG($,Y);try{for(let z=0;;z++){let X=await ML(j,Z,W),G=X.headers.get("location");if(OL.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=nG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw TL(z,W)}}function nG($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function ML($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(LL))throw new F0(403,"This image source is not allowed");if(HL($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return E1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return E1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function HL($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function TL($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof O6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class n5 extends x0{routes={"/resize":this.file(async()=>{let $=new A,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return aG(400,"url query parameter is required");let X=H(tG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=WZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let F;try{F=await oG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof F0)return aG(U.status,U.message);throw U}let V=await X.resize(F.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(F.cacheControl)B.set("Cache-Control",F.cacheControl);return new Response(new Uint8Array(V),{headers:B})})}}function aG($,Z){return Response.json({error:Z},{status:$})}class tG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=sG();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class o5 extends x0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(rG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function jI($){return $}function eG(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function $Q(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,assetCors:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function PL($){return"run"in $}function NL($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function KL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function _L($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function IL($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function ZQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function xL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function a5($,Z="",J=[],W){let Y={},j=(X)=>{return(X.corsPolicy===void 0?W:X.corsPolicy)||void 0};function z(X,G,Q,F,V,B,U){let O=X==="/"?"":X,D=Z==="/"?"":Z,L=xL((`${D}${O}`===""?"/":`${D}${O}`).replaceAll("//","/"));if(!Y[L])Y[L]={};Y[L][G.toUpperCase()]={exec:Q,middleware:[...J,...F],...V?{source:V}:{},...B?{bodyLimitDefault:B}:{},...U?{cors:U}:{}},Y[L].OPTIONS={exec:()=>{let T=new A().ctx().headers;return new Response(null,{headers:T,status:204})},middleware:[]}}for(let[X,G]of Object.entries($)){if(IL(G)){let Q=G;for(let F of["GET","POST","PUT","DELETE"])z(X,F,Q.run.bind(Q),Q.middlewares,void 0,void 0,j(Q));continue}if(PL(G)){let Q=G,F=Q.method,V=Q.middlewares,B=Q.run.bind(Q),U=j(Q);if(z(X,F,B,V,Q.source,Q.__internal_bodyLimitDefault,U),ZQ(G))z(X,"HEAD",B,V,Q.source,void 0,U)}if(NL(G))for(let[Q,F]of Object.entries(G)){let V=F,B=V.middlewares,U=V.run.bind(V),O=j(V);if(z(X,Q,U,B,V.source,V.__internal_bodyLimitDefault,O),Q==="get"&&ZQ(V))z(X,"HEAD",U,B,V.source,void 0,O)}if(_L(G)){let Q=new G,F=`the router at "${Z}${X}"`;if(Q.cors===!0)throw Error(`CORS policy on ${F}: \`cors = true\` is not a policy; write one such as { origins: "*" }.`);let V=Q.cors===void 0?W:Q.cors===!1?void 0:X3(Q.cors,F),B=a5(Q.routes,`${Z}${X}`,[...J,...Q.middlewares],V);for(let[U,O]of Object.entries(B)){let D=U.replaceAll("//","/");Y[D]={...Y[D],...O}}}if(KL(G)){let{first:Q,second:F}=G;for(let[V,B]of Object.entries(Q)){let U=B.middlewares,O=B.run.bind(B),[D,...L]=X.split("/").reverse();if(!D.startsWith(":"))throw Error("Resource route must end with a dynamic segment");z(L.reverse().join("/"),V,O,U,B.source,void 0,j(B))}for(let[V,B]of Object.entries(F)){let U=B.middlewares,O=B.run.bind(B);z(X,V,O,U,B.source,void 0,j(B))}}}return Object.fromEntries(Object.entries(Y).sort(([X],[G])=>{let Q=X.split("/").length+X.split(":").length,F=G.split("/").length+G.split(":").length;return Q-F}))}var CL=Object.defineProperty,I=($,Z)=>CL($,"name",{value:Z,configurable:!0}),aZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};I(aZ,"Part");var AL=/[$_\p{ID_Start}]/u,SL=/[$_\u200C\u200D\p{ID_Continue}]/u,r5=".*";function JQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}I(JQ,"isASCII");function ZW($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=I(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let G=$.substr(X,1);if(X===W+1&&AL.test(G)||X!==W+1&&SL.test(G)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",G=W+1,Q=!1;if($[G]==="?"){j(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!JQ($[G],!1)){j(`Invalid character '${$[G]}' at ${G}.`),Q=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){j(`Capturing groups are not allowed at ${G}`),Q=!0;break}X+=$[G++]}if(Q)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=G;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}I(ZW,"lexer");function JW($,Z={}){let J=ZW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${d0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",G=new Set,Q=I((P)=>{if(z<J.length&&J[z].type===P)return J[z++].value},"tryConsume"),F=I(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),V=I((P)=>{let K=Q(P);if(K!==void 0)return K;let{type:R,index:C}=J[z];throw TypeError(`Unexpected ${R} at ${C}, expected ${P}`)},"mustConsume"),B=I(()=>{let P="",K;for(;K=Q("CHAR")??Q("ESCAPED_CHAR");)P+=K;return P},"consumeText"),U=I((P)=>P,"DefaultEncodePart"),O=Z.encodePart||U,D="",L=I((P)=>{D+=P},"appendToPendingFixedValue"),M=I(()=>{D.length&&(Y.push(new aZ(3,"","",O(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=I((P,K,R,C,S)=>{let w=3;switch(S){case"?":w=1;break;case"*":w=0;break;case"+":w=2;break}if(!K&&!R&&w===3){L(P);return}if(M(),!K&&!R){if(!P)return;Y.push(new aZ(3,"","",O(P),"",w));return}let x;R?R==="*"?x=r5:x=R:x=W;let f=2;x===W?(f=1,x=""):x===r5&&(f=0,x="");let _;if(K?_=K:R&&(_=j++),G.has(_))throw TypeError(`Duplicate name '${_}'.`);G.add(_),Y.push(new aZ(f,_,O(P),x,O(C),w))},"addPart");for(;z<J.length;){let P=Q("CHAR"),K=Q("NAME"),R=Q("REGEX");if(!K&&!R&&(R=Q("ASTERISK")),K||R){let S=P??"";Z.prefixes.indexOf(S)===-1&&(L(S),S=""),M();let w=F();T(S,K,R,"",w);continue}let C=P??Q("ESCAPED_CHAR");if(C){L(C);continue}if(Q("OPEN")){let S=B(),w=Q("NAME"),x=Q("REGEX");!w&&!x&&(x=Q("ASTERISK"));let f=B();V("CLOSE");let _=F();T(S,w,x,f,_);continue}M(),V("END")}return Y}I(JW,"parse");function d0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(d0,"escapeString");function e5($){return $&&$.ignoreCase?"ui":"u"}I(e5,"flags");function WQ($,Z,J){return WW(JW($,J),Z,J)}I(WQ,"stringToRegexp");function YZ($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}I(YZ,"modifierToString");function WW($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=d0(X.value):W+=`(?:${d0(X.value)})${YZ(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${d0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=r5),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${Q})${YZ(X.modifier)}`:W+=`((?:${Q})${YZ(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${d0(X.prefix)}(${Q})${d0(X.suffix)})`,W+=YZ(X.modifier);continue}W+=`(?:${d0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=d0(X.suffix),W+=d0(X.prefix),W+=`(?:${Q}))*)${d0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${d0(J.endsWith)}]|$`,j=`[${d0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,e5(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,e5(J))}I(WW,"partsToRegexp");var P$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},bL={delimiter:".",prefixes:"",sensitive:!0,strict:!0},EL={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function YQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}I(YQ,"isAbsolutePathname");function YW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}I(YW,"maybeStripPrefix");function jQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}I(jQ,"maybeStripSuffix");function jW($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}I(jW,"treatAsIPv6Hostname");var zQ=["ftp","file","http","https","ws","wss"];function zW($){if(!$)return!0;for(let Z of zQ)if($.test(Z))return!0;return!1}I(zW,"isSpecialScheme");function XQ($,Z){if($=YW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}I(XQ,"canonicalizeHash");function GQ($,Z){if($=YW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}I(GQ,"canonicalizeSearch");function QQ($,Z){return Z||$===""?$:jW($)?QW($):GW($)}I(QQ,"canonicalizeHostname");function BQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}I(BQ,"canonicalizePassword");function FQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}I(FQ,"canonicalizeUsername");function VQ($,Z,J){if(J||$==="")return $;if(Z&&!zQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}I(VQ,"canonicalizePathname");function UQ($,Z,J){return XW(Z)===$&&($=""),J||$===""?$:BW($)}I(UQ,"canonicalizePort");function DQ($,Z){return $=jQ($,":"),Z||$===""?$:o4($)}I(DQ,"canonicalizeProtocol");function XW($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}I(XW,"defaultPortForProtocol");function o4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}I(o4,"protocolEncodeCallback");function OQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}I(OQ,"usernameEncodeCallback");function LQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}I(LQ,"passwordEncodeCallback");function GW($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}I(GW,"hostnameEncodeCallback");function QW($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}I(QW,"ipv6HostnameEncodeCallback");function BW($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}I(BW,"portEncodeCallback");function MQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}I(MQ,"standardURLPathnameEncodeCallback");function HQ($){return $===""?$:new URL(`data:${$}`).pathname}I(HQ,"pathURLPathnameEncodeCallback");function TQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}I(TQ,"searchEncodeCallback");function PQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}I(PQ,"hashEncodeCallback");var NQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#Q=0;#X=0;#U=0;#D=0;#O=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=ZW(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#T(),this.#B()?this.#J(9,1):this.#F()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#V(5);continue}this.#J(10,0);break}if(this.#U>0)if(this.#C())this.#U-=1;else continue;if(this.#x()){this.#U+=1;continue}switch(this.#X){case 0:this.#P()&&this.#V(1);break;case 1:if(this.#P()){this.#b();let $=7,Z=1;this.#K()?($=2,Z=3):this.#O&&($=2),this.#J($,Z)}break;case 2:this.#M()?this.#V(3):(this.#H()||this.#F()||this.#B())&&this.#V(5);break;case 3:this.#_()?this.#J(4,1):this.#M()&&this.#J(5,1);break;case 4:this.#M()&&this.#J(5,1);break;case 5:this.#A()?this.#D+=1:this.#S()&&(this.#D-=1),this.#I()&&!this.#D?this.#J(6,1):this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 7:this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 8:this.#B()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#O?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#N($,Z)}#N($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#Y=0}#T(){this.#$=this.#Q,this.#Y=0}#V($){this.#T(),this.#X=$}#L($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#L($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#K(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#M(){return this.#z(this.#$,"@")}#_(){return this.#z(this.#$,":")}#I(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#L(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#B(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#G(){let $=this.#W[this.#$],Z=this.#L(this.#Q).index;return this.#j.substring(Z,$.index)}#b(){let $={};Object.assign($,P$),$.encodePart=o4;let Z=WQ(this.#G(),void 0,$);this.#O=zW(Z)}};I(NQ,"Parser");var t5=["protocol","username","password","hostname","port","pathname","search","hash"],T$="*";function $W($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}I($W,"extractValues");function K1($,Z){return Z?oZ($):$}I(K1,"processBaseURLString");function nZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=K1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=K1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=K1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=K1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=K1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=K1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=K1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=K1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=DQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=FQ(Z.username,J)),typeof Z.password=="string"&&($.password=BQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=QQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=UQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!YQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=K1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=VQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=GQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=XQ(Z.hash,J)),$}I(nZ,"applyInit");function oZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}I(oZ,"escapePatternString");function KQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(KQ,"escapeRegexpString");function _Q($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${KQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=oZ(X.value);continue}j+=`{${oZ(X.value)}}${YZ(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),F=z>0?$[z-1]:null,V=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&V&&!V.prefix.length&&!V.suffix.length)if(V.type===3){let B=V.value.length>0?V.value[0]:"";Q=Y.test(B)}else Q=!V.hasCustomName();if(!Q&&!X.prefix.length&&F&&F.type===3){let B=F.value[F.value.length-1];Q=Z.prefixes.includes(B)}Q&&(j+="{"),j+=oZ(X.prefix),G&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?G||(j+=`(${W})`):X.type===0&&(!G&&(!F||F.type===3||F.modifier!==3||Q||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&G&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=oZ(X.suffix),Q&&(j+="}"),X.modifier!==3&&(j+=YZ(X.modifier))}return j}I(_Q,"partsToPattern");var s3=class{#j;#W={};#Z={};#$={};#Y={};#Q=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new NQ($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:T$,protocol:T$,username:T$,password:T$,hostname:T$,port:T$,search:T$,hash:T$};this.#j=nZ(j,$,!0),XW(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of t5){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,P$),X.encodePart=o4;break;case"username":Object.assign(X,P$),X.encodePart=OQ;break;case"password":Object.assign(X,P$),X.encodePart=LQ;break;case"hostname":Object.assign(X,bL),jW(G)?X.encodePart=QW:X.encodePart=GW;break;case"port":Object.assign(X,P$),X.encodePart=BW;break;case"pathname":zW(this.#W.protocol)?(Object.assign(X,EL,Y),X.encodePart=MQ):(Object.assign(X,P$,Y),X.encodePart=HQ);break;case"search":Object.assign(X,P$,Y),X.encodePart=TQ;break;case"hash":Object.assign(X,P$,Y),X.encodePart=PQ;break}try{this.#Y[z]=JW(G,X),this.#W[z]=WW(this.#Y[z],this.#Z[z],X),this.#$[z]=_Q(this.#Y[z],X),this.#Q=this.#Q||this.#Y[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=nZ(J,$,!1):J=nZ(J,$W($,Z),!1)}catch{return!1}let W;for(W of t5)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=nZ(J,$,!1):J=nZ(J,$W($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of t5){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,G]of this.#Z[Y].entries())if(typeof G=="string"||typeof G=="number"){let Q=j[X+1];z[G]=Q}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=I((X,G)=>{for(let Q of["type","modifier","prefix","value","suffix"]){if(X[Q]<G[Q])return-1;if(X[Q]===G[Q])continue;return 1}return 0},"comparePart"),Y=new aZ(3,"","","","",3),j=new aZ(0,"","","","",3),z=I((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let F=W(X[Q],G[Q]);if(F)return F}return X.length===G.length?0:W(X[Q]??Y,G[Q]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#Q}};I(s3,"URLPattern");if(!globalThis.URLPattern)globalThis.URLPattern=s3;function a4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function FW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function VW($){let Z=a4($);return Z.length>1?Z.replace(/\/$/,""):Z}function IQ($,Z){return Z.map((J)=>({...J,path:VW(FW($,J.path))}))}function t4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=t4(j.routes);for(let[X,{exec:G,middleware:Q,segments:F,features:V,static:B}]of Object.entries(z)){let U=FW(J,X),O=(D)=>Y.run.call(Y,D,J);Z[a4(U)]={exec:[O,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:VW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...IQ(J,F)],...B?{static:B}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[a4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:VW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=t4(Y.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:F,features:V,static:B}]of Object.entries(j)){let U=FW(J,z);Z[a4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Q,segments:IQ(J,F),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var UW="theme";function xQ($){return $==="light"||$==="dark"||$==="system"}function CQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
13
+ `)}function vV($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(R9($),{status:200,headers:J})}var k9={response:vV,text:R9,parse:E9,fetch:qV};import{createHmac as w9,randomBytes as gV}from"crypto";var s8="v2.";function n8($){return $.startsWith(s8)}function TZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function f9($){let Z=gV(16).toString("hex"),J=w9("sha256",TZ()).update(`${$}:${Z}`).digest("hex");return`${s8}${J}`}function P6($,Z){let J=w9("sha256",TZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${s8}${J}`}import{createHash as hV,createHmac as pV,randomInt as cV,timingSafeEqual as g9}from"crypto";function q9($,Z){return Math.floor($/Z)*Z}function yV($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function o8($,Z,J,W){return Z*yV(J,W)+$}function mV($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let G=Math.max(0,Y-W);if(J>0){let F=Y*(1-(X-Z)/J);if(F<=Y)return Math.max(0,Math.ceil(F-W))}if(Z<=X)return G;if(Z<=0)return G;let Q=Y*(1-X/Z);return G+Math.max(0,Math.ceil(Q))}function v9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let F=o8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-F)),resetAt:Y-j+z,retryAfter:0}}let Q=mV({current:J,previous:W,elapsed:j,window:z,limit:X,cost:G});return{allowed:!1,limit:X,remaining:0,resetAt:Y+Q,retryAfter:Q}}class a8{}class t8 extends a8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=q9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let F=o8(G.current,G.previous,X,W)+Y<=J;if(F)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return v9({allowed:F,current:G.current,previous:G.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var m9="h1.";function N6($,Z,J){let W=pV("sha256",TZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${m9}${W}`}function PZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(m9),X=N6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return g9(G,G),!1;return g9(G,Q)}function h9($){let Z="";for(let J=0;J<$;J++)Z+=String(cV(0,10));return Z}var p9=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>p9)return null;return Z.toLowerCase()}function K6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>p9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var y9=null;function c9(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(D1))return $.make(D1)}catch{}return y9??=new D1({driver:new t8,limit:1000,window:60}),y9}function r8($){return $.length<=64?$:`sha256:${hV("sha256").update($).digest("hex")}`}function dV($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function v$($,Z,J,W,Y,j){let z=c9(),X=[["perIp",`ip:${r8(LZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${r8(Z)}`,W.perEmail]);for(let[G,Q,F]of X){if(!F)continue;let V=Y?await Y({req:J,scope:$,limit:G}):void 0,B=dV($),U=V?`${B}:p:${r8(String(V))}:${Q}`:`${B}:${Q}`,[O,D]=F,L=await z.consume(U,{limit:O,window:D});if(!L.allowed)throw await j?.(G),new r1(L)}}async function d9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await c9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as $7}from"crypto";class e8 extends A{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}import{createHash as uV,timingSafeEqual as lV}from"crypto";function l9($){let Z=$??process.env.AUTH_FIXED_CODE;return typeof Z==="string"&&Z!==""?Z:null}function i9($){if($!==void 0&&$!==null)return $===!0;return process.env.AUTH_FIXED_CODE_ALLOW_PRODUCTION==="1"}var iV="[gemi] WARNING: a fixed sign-in code is enabled in production (AUTH_FIXED_CODE / auth.emailCode.fixedCode, opted in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1 / auth.emailCode.allowFixedCodeInProduction). Anyone who knows the code can sign in as any user. This is meant for local test servers only; never set it on a real deployment.";function s9($={},{warn:Z=!1}={}){let{fixedCode:J,allowFixedCodeInProduction:W}=$??{};if(J!==void 0&&J!==null&&typeof J!=="string")throw Error(`auth.emailCode.fixedCode must be a string, got ${JSON.stringify(J)}`);if(W!==void 0&&W!==null&&typeof W!=="boolean")throw Error(`auth.emailCode.allowFixedCodeInProduction must be a boolean, got ${JSON.stringify(W)}`);let Y=l9(J);if(Y===null)return;let j=J?"auth.emailCode.fixedCode":"AUTH_FIXED_CODE",z=Bun.env.NODE_ENV==="production";if(z&&!i9(W))throw Error(`${j} is set, but a fixed sign-in code is for development and tests only and is refused when NODE_ENV=production. Unset it in this environment (a local production-build test server can opt in with AUTH_FIXED_CODE_ALLOW_PRODUCTION=1).`);if(Y.trim()!==Y||Y.length>256)throw Error(`${j} must have no surrounding whitespace and at most 256 characters`);if(z&&Z)console.warn(iV)}function sV($={}){if(Bun.env.NODE_ENV==="production"&&!i9($.allowFixedCodeInProduction))return null;return l9($.fixedCode)}function u9($){return uV("sha256").update($).digest()}function n9($,Z={}){let J=sV(Z);if(J===null||typeof $!=="string"||$==="")return!1;return lV(u9($),u9(J))}async function R1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Z7($){return $===!0||typeof $==="function"}function J7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function V3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function nV($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function W7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return V3("length",Z,4,12),V3("expiresInMinutes",J,1),V3("linkExpiresInMinutes",W,1),V3("maxAttempts",Y,1),V3("activeCodes",j,1,5),s9($),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)}),fixedCode:$.fixedCode??null,allowFixedCodeInProduction:$.allowFixedCodeInProduction??null}}async function oV($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function o9($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J,enabled:W}=$;return{provider:Z,...J!==void 0?{feature:J}:{},...W!==void 0?{enabled:W}:{}}}function a9($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature, enabled } with an OAuthProvider.`);if(W.enabled!==void 0&&typeof W.enabled!=="boolean"&&typeof W.enabled!=="function")throw Error(`auth.oauthProviders.${Z}.enabled must be true, false or a function of the request.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function yN($){return $}function t9($={}){return nV($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:J7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:e8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:oV,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>$7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return $7(32).toString("hex")},generateMagicLinkToken:()=>$7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:W7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var aV=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),tV=new Set(["svg","math"]);function r9($){return $===32||$===9||$===10||$===12||$===13}function e9($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function $Y(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,F=()=>{if(!J&&aV.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(tV.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},V=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(e9(B))$="tagName",J=!1,z=!1,Z=String.fromCharCode(_6(B));else if(B===63)$="bogus";else if(B===60)$="tagOpen";else $="data";return;case"endTagOpen":if(e9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(r9(B)||B===47)$="inTag",z=B===47;else if(B===62)F();else Z+=String.fromCharCode(_6(B));return;case"inTag":if(B===62){F();return}if(z=B===47,B===34)$="attrDouble";else if(B===39)$="attrSingle";return;case"attrDouble":if(B===34)$="inTag";z=!1;return;case"attrSingle":if(B===39)$="inTag";z=!1;return;case"bang":if(B===45){if(j+=1,j===2)$="comment",j=0}else if(B===62)$="data";else $="bogus";return;case"bogus":if(B===62)$="data";return;case"comment":if(B===45)j=j<2?j+1:2;else if(B===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(_6(B)===W.charCodeAt(Y))Y+=1;else Y=B===60?1:0;return}if(B===62)$="data",Z="";else if(r9(B)||B===47)$="inTag",Z="";else Y=B===60?1:0;return}}};return{scanToInsertionPoint(B){for(let U=0;U<B.length;U++){if(Q())return U;V(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)V(B[U])},isSafe:Q}}function i0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ZY($){return $?`<script nonce="${$}">`:"<script>"}function rV($,Z){let J=i0([$.path,$.variantKey,$.data]);return`${ZY(Z)}(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${J})</script>`}function eV($,Z){let J=i0([$.id,$.locale,$.strings]);return`${ZY(Z)}(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${J})</script>`}function Y7($,Z,J={},W,Y){let j=new TextEncoder,z=[],X=!1,G=!1,Q=()=>{if(G)return;G=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;z.push(rV(D,Y))}),W?.onUse((D)=>{z.push(eV(D,Y))});let F=$.getReader(),V=$Y(),B=(D,L)=>{D.enqueue(L),J.onChunk?.(L)},U=(D)=>{while(z.length>0){let L=j.encode(z.shift());V.write(L),B(D,L)}},O=(D,L)=>{if(z.length===0){V.write(L),B(D,L);return}let M=V.scanToInsertionPoint(L);if(M>0)B(D,L.subarray(0,M));if(V.isSafe())U(D);let T=L.subarray(M);if(T.length>0)V.write(T),B(D,T)};return new ReadableStream({async pull(D){let L;try{L=await F.read()}catch(P){throw Q(),P}let{done:M,value:T}=L;if(M){U(D),D.close(),Q();return}if(!X){if(X=!0,V.write(T),B(D,T),J.onShell?.(),V.isSafe())U(D);return}O(D,T)},cancel(D){return Q(),F.cancel(D)}})}var $U=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return $U.test($)}async function WY($,Z=()=>{}){let J=N.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await ZU($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:JY(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function YY($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function ZU($,Z){if(!$.context)return{};try{let J=N.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function jY($,Z){return`${$}:${Z}`}function j7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function zY($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function XY($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=WU($,Z,J,W.buckets);return zY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function JU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function WU($,Z,J,W){let Y=jY(Z.salt??$,JU(J));if(!W)return j7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=j7(Y);return W.set(Y,z),z}class GY extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class z7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new GY(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=YU(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function YU($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class jU{}class zU extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class X7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class QY extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class BY{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class e1{config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new z7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new QY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=XU(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new X7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new BY(this,YY($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),G=XY($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,G),this.notify($,G,Z),G}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await WY(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function XU($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function FY($){if($===void 0)return!0;return await H(e1).enabled($)}function VY(){try{return N.getStore()?.req??null}catch{return null}}async function NZ($,Z,J=VY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=o9($[Z]);if(!W||!await FY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await R1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function UY($,Z=VY()){let J=[];for(let W of Object.keys($))if(await NZ($,W,Z))J.push(W);return J}function G7($){if($&&typeof $==="object")delete $.password;return $}function GU(){return new Proxy({},{get:($,Z)=>OY(Z)})}var DY=new WeakMap;function LY($){if($&&typeof $==="object"){for(let Z of Object.values($))LY(Z);Object.freeze($)}return $}var QU={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},BU=LY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:QU});class Q7{models;constructor($=GU()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return BU}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??g$(),W=H(y$).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await $$()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||$$())return Y();let z=(DY.get(W)??Promise.resolve()).then(Y,Y);return DY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return G7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return G7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?G7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as DL}from"crypto";function v0($,Z,J,W,Y){return e0(Z,kY($,Z),J,W,Y)}function e0($,Z,J,W,Y,j){let z=D7(Z,J,W);if(Y&&Z!==z)throw RangeError(OX($,Z,J,W,j));return z}function kY($,Z){let J=$[Z];if(J===void 0)throw TypeError(dJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function K7($){return c$({name:$},1)}function c$($,Z){return W1((J)=>({value:J,configurable:1,writable:!Z}),$)}function wY($){return W1((Z)=>({get:Z,configurable:1}),$)}function h6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function SZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function W1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function N3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function FU($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function _7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function I7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function fY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function qY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function vY($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function q($,...Z){return(...J)=>$(...Z,...J)}function MY($){return $[0].toUpperCase()+$.substring(1)}function K3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function Z$($,Z){return Math.sign($-Z)}function D7($,Z,J){return Math.min(Math.max($,Z),J)}function w1($,Z){return[Math.floor($/Z),D3($,Z)]}function D3($,Z){return($%Z+Z)%Z}function Y$($,Z){return[p6($,Z),x7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function x7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function gY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=L1[X],F=s/Q,[V,B]=Y$(G,F);W+=B*Q,Y+=V}let[j,z]=Y$(W,s);return[Y+j,z]}function c6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=L1[Y];W[J[Y]]=p6($,j),$=x7($,j)}return W}function yY($){return $===v?K4:[]}function mY($){return $===v?k3:[]}function hY($){return $===v?["year","day"]:[]}function pY($){if($!==void 0)return J0($)}function cY($){if($!==void 0)return Y1($)}function C7($){if($!==void 0)return _3($)}function Y1($){return lY(_3($))}function _3($){return uY(JD($))}function A7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function dY($,Z){if(Z==null)throw RangeError(dJ($));return Z}function q1($){if(!L0($))throw TypeError(DX);return $}function d6($,Z,J=$){if(typeof Z!==$)throw TypeError(b3(J,Z));return Z}function uY($,Z="number"){if(!Number.isInteger($))throw RangeError(AU(Z,$));return $||0}function lY($,Z="number"){if($<=0)throw RangeError(SU(Z,$));return $}function S7($){if(typeof $=="symbol")throw TypeError(kU);return String($)}function k6($,Z){return L0($)?String($):J0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(RU($));return $}function iY($,Z="number"){if(typeof $=="bigint")throw TypeError(EU(Z));if($=Number($),!Number.isFinite($))throw RangeError(bU(Z,$));return $}function C0($,Z){return Math.trunc(iY($,Z))||0}function sY($,Z){return uY(iY($,Z),Z)}function HY($,Z){return lY(C0($,Z),Z)}function b7($,Z){let[J,W]=Y$(Z,s),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*s),[Y,W]}function _Z($,Z,J=1){return b7($[0]+Z[0]*J,$[1]+Z[1]*J)}function IZ($,Z){return b7($[0],$[1]+Z)}function s0($,Z){return _Z(Z,$,-1)}function S0($,Z){return Z$($[0],Z[0])||Z$($[1],Z[1])}function nY($,Z,J){return S0($,Z)===-1||S0($,J)===1}function l6($,Z=1){let J=BigInt(s/Z);return[Number($/J),Number($%J)*Z]}function xZ($,Z=1){let J=s/Z,[W,Y]=Y$($,J);return[W,Y*Z]}function oY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=s/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function n0($,Z=1,J){let[W,Y]=$,[j,z]=Y$(Y,Z);return W*(s/Z)+(j+(J?z/Z:0))}function E7($,Z,J=w1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(s/Z)+j,z]}function R7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function k7($){return v0($,"isoYear",P3,T3,1),$.isoYear===P3?v0($,"isoMonth",4,12,1):$.isoYear===T3&&v0($,"isoMonth",1,9,1),$}function J$($){return v1({...$,...J1,isoHour:12}),$}function v1($){let Z=v0($,"isoYear",P3,T3,1),J=Z===P3?1:Z===T3?-1:0;return J&&o0(A0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function o0($){if(!$||nY($,QD,GD))throw RangeError(H4);return $}function j$($){return gY($,5,G1)[1]}function i6($){let[Z,J]=w1($,s);return[c6(J,5,G1),Z]}function aY($){return tY($)[0]}function tY($){return E7($,Z1)}function b0($){return bZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function A0($){let Z=b0($);if(Z!==void 0){let[J,W]=Y$(Z,y0);return[J,W*M1+($.isoMicrosecond||0)*t$+($.isoNanosecond||0)]}}function w7($,Z){let[J,W]=i6(j$($)-Z);return o0(A0({...$,isoDay:$.isoDay+W,...J}))}function w6(...$){return bZ(...$)/CX}function bZ(...$){let[Z,J]=rY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function rY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===P3?1:$===T3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function X$($,Z){let[J,W]=IZ($,Z);W<0&&(W+=s,J-=1);let[Y,j]=w1(W,M1),[z,X]=w1(j,t$);return s6(J*y0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-XD)/y0)*Math.sign($),Y=new Date($-W*y0);return SZ(I4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function eY($){return[$.isoYear,$.isoMonth,$.isoDay]}function $j(){return k1}function f7($,Z){switch(Z){case 2:return q7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function Zj($){return q7($)?366:365}function q7($){return $%4==0&&($%100!=0||$%400==0)}function Jj($){let[Z,J]=rY($.isoYear,$.isoMonth,$.isoDay);return D3(Z.getUTCDay()-J,7)||7}function Wj({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function VU($){let Z=b0($);if(Z<FD)return Wj($);let J=R7(X5(CZ),Z),{era:W,eraYear:Y}=Dz(J,CZ);return[W,Y]}function n6($){return d$($),o6($,1),$}function d$($){return Yj($,1),$}function TY($){return qY(eJ,$,Yj($))}function Yj($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,$j(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,f7(J,W),Z)}}function o6($,Z){return SZ(G1,[v0($,"isoHour",0,23,Z),v0($,"isoMinute",0,59,Z),v0($,"isoSecond",0,59,Z),v0($,"isoMillisecond",0,999,Z),v0($,"isoMicrosecond",0,999,Z),v0($,"isoNanosecond",0,999,Z)])}function m($){return $===void 0?0:dX(q1($))}function I3($,Z=0){$=j1($);let J=uX($),W=ND($,Z);return[dX($),W,J]}function v7($){return uX(j1($))}function jj($){return $=j1($),J5($,9,6,1)}function EZ($,Z,J,W=9,Y=0,j=4){Z=j1(Z);let z=J5(Z,W,Y),X=m7(Z),G=f3(Z,j),Q=w3(Z,W,Y,1);return z==null?z=Math.max(J,Q):Qj(z,Q),X=h7(X,Q,1),$&&(G=((F)=>F<4?(F+2)%4:F)(G)),[z,Q,X,G]}function a6($,Z=6,J){let W=m7($=p7($,m6)),Y=f3($,7),j=w3($,Z);return j=dY(m6,j),W=h7(W,j,void 0,J),[j,W,Y]}function g7($){return W5(j1($))}function zj($,Z){return y7(j1($),Z)}function y7($,Z=4){let J=Gj($);return[f3($,4),...Xj(w3($,Z),J)]}function Xj($,Z){return $!=null?[L1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function m7($){let Z=$[O3];return Z===void 0?1:C0(Z,O3)}function h7($,Z,J,W){let Y=W?s:L1[Z+1];if(Y){let j=L1[Z];if(Y%(($=e0(O3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(b3(O3,$))}else $=e0(O3,$,1,J?1e9:1,1);return $}function Gj($){let Z=$[U7];if(Z!==void 0){if(typeof Z!="number"){if(S7(Z)==="auto")return;throw RangeError(b3(U7,Z))}Z=e0(U7,Math.floor(Z),0,9,1)}return Z}function j1($){return $===void 0?{}:q1($)}function p7($,Z){return typeof $=="string"?{[Z]:$}:q1($)}function z0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(DX)}}function t6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:UD[Z]})}function c7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=S7(j),j==="auto")return Y?W:null;let z=H7[j];if(z===void 0&&(z=jD[j]),z===void 0)throw RangeError(HX($,j,H7));return e0($,z,W,J,1,R3),z}function u$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=S7(Y),z=Z[j];if(z===void 0)throw RangeError(HX($,j,Z));return z}function Qj($,Z){if(Z>$)throw RangeError(tU)}function M0($){return{branding:C4,epochNanoseconds:$}}function N0($,Z,J){return{branding:h1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:e$,calendar:Z,...p0(mX,$)}}function G0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0($5,$)}}function h$($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0($5,$)}}function f6($,Z=$.calendar){return{branding:mZ,calendar:Z,...p0($5,$)}}function z1($){return{branding:x4,...p0(yX,$)}}function e($){return{branding:A4,sign:G$($),...p0(aJ,$)}}function Bj($){return aY($.epochNanoseconds)}function r6($){return E7($.epochNanoseconds,M1)[0]}function Fj($){return oY($.epochNanoseconds,t$)}function Vj($){return oY($.epochNanoseconds)}function Uj($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:J0($.id)}function RZ($,Z){return $===Z||T0($)===T0(Z)}function Dj($,Z,J,W,Y){let j=p$(W),[z,X]=((L,M)=>{let T=M((L=p7(L,N7))[pX]),P=PD(L);return P=dY(N7,P),[P,T]})(Y,$);if(M3(Math.max(z,j),X))return PY(W,z);if(!X)throw RangeError(T4);let[G,Q,F]=Y4(Z,J,X),V=VJ(F),B=j4(F),U=UJ(F),O=B(Q,G,W),D=U(Q,G,O,z);return M3(z,X)?PY(D,z):((L,M,T,P,K,R,C)=>{let S=G$(L),[w,x]=d7(P,rJ(T,L),T,S,K,R,C),f=u7(M,w,x);return L[p[T]]+f*S})(D,V(O),z,Q,G,V,B)}function PY($,Z){return n0(O0($),L1[Z],1)}function d7($,Z,J,W,Y,j,z){let X=p[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),F=z($,Y,G);return[j(Q),j(F)]}function u7($,Z,J){let W=n0(s0(Z,J));if(!W)throw RangeError(E3);return n0(s0(Z,$))/W}function Oj($,Z){let[J,W,Y]=a6(Z,5,1);return M0($4($.epochNanoseconds,J,W,Y,1))}function Lj($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,G]=a6(J);if(z===0&&X===1)return Z;let Q=$(Y);if(z===6)W=((F,V,B,U)=>{let O=E0(B,V),[D,L]=F(O),M=B.epochNanoseconds,T=h0(V,D),P=h0(V,L);if(nY(M,T,P))throw RangeError(E3);return xj(u7(M,T,P),U)?P:T})(_j,Q,Z,G);else{let F=Q.getOffsetNanosecondsFor(W);W=i$(Q,Nj(X$(W,F),z,X,G),F,2,0,1)}return N0(W,Y,j)}function Mj($,Z){return X0(Nj($,...a6(Z)),$.calendar)}function Hj($,Z){let[J,W,Y]=a6(Z,5);var j;return z1((j=Y,l7($,x3(J,W),j)[0]))}function Tj($,Z){let J=$(Z.timeZone),W=E0(Z,J),[Y,j]=_j(W),z=n0(s0(h0(J,Y),h0(J,j)),N4,1);if(z<=0)throw RangeError(E3);return z}function Pj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(E0(X,z))))(Ij,$(J),Z);return N0(Y,J,W)}function Nj($,Z,J,W){return Kj($,x3(Z,J),W)}function Kj($,Z,J){let[W,Y]=l7($,Z,J);return v1({...s$($,Y),...W})}function l7($,Z,J){return i6(z$(j$($),Z,J))}function q6($){return z$($,P4,7)}function x3($,Z){return L1[$]*Z}function _j($){let Z=Ij($);return[Z,s$(Z,1)]}function Ij($){return zD(6,$)}function UU($,Z,J){let W=Math.min(p$($),6);return wZ(Z4(O0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let F=M3(W,X)?z4(X)&&W<6&&J>=6?OU:DU:LU,[V,B,U]=F($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(V=((O,D,L,M,T,P,K,R)=>{let C=G$(O);for(let S=M+1;S<=L;S++){if(S===7&&L!==7)continue;let w=rJ(S,O);w[p[S]]+=C;let x=n0(s0(K(R(T,P,w)),D));if(x&&Math.sign(x)!==C)break;O=w}return O})(V,B,J,Math.max(6,W),z,X,G,Q)),V}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/s)($);return[z$(j,J,W),0]}return Z4($,x3(Z,J),W,Y)}function Z4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=s,Y-=1);let[z,X]=w1(z$(j,Z,J),s);return b7(Y+z,X)}function z$($,Z,J){return xj($/Z,J)*Z}function xj($,Z){return ID[Z]($)}function DU($,Z,J,W,Y,j){let z=G$($),X=O0($),G=$4(X,W,Y,j),Q=s0(X,G),F=Math.sign(G[0]-X[0])===z,V=wZ(G,Math.min(J,6));return[{...$,...V},_Z(Z,Q),F]}function OU($,Z,J,W,Y,j,z,X,G,Q){let F=G$($),V=n0(O0($,5)),B=x3(W,Y),U=z$(V,B,j),[O,D]=d7(z,{...$,...tJ},6,F,X,G,Q),L=U-n0(s0(O,D)),M=0;L&&Math.sign(L)!==F?Z=IZ(O,U):(M+=F,U=z$(L,B,j),Z=IZ(D,U));let T=G4(U);return[{...$,...T,days:$.days+M},Z,Boolean(M)]}function LU($,Z,J,W,Y,j,z,X,G,Q){let F=G$($),V=p[W],B=rJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=p6($[V],Y)*Y;B[V]=U;let[O,D]=d7(z,B,W,Y*F,X,G,Q),L=U+u7(Z,O,D)*F*Y,M=z$(L,Y,j),T=Math.sign(M-L)===F;return B[V]=M,[B,T?D:O,T]}function i7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let F=y7(Q=j1(Q));return[Q.timeZone,...F]})(W),G=Y!==void 0;return((Q,F,V,B,U,O)=>{V=Z4(V,U,B,1);let D=F.getOffsetNanosecondsFor(V);return e7(X$(V,D),O)+(Q?l$(q6(D)):"Z")})(G,Z(G?$(Y):$Z),J.epochNanoseconds,j,z,X)}function s7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=j1(Q);let F=W5(Q),V=Gj(Q),B=_D(Q),U=f3(Q,4),O=w3(Q,4);return[F,KD(Q),B,U,...Xj(O,V)]})(J);return((Q,F,V,B,U,O,D,L,M,T)=>{B=Z4(B,M,L,1);let P=Q(V).getOffsetNanosecondsFor(B);return e7(X$(B,P),T)+l$(q6(P),D)+((K,R)=>R!==1?"["+(R===2?"!":"")+T0(K)+"]":"")(V,O)+$J(F,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function n7($,Z){let[J,W,Y,j]=((Q)=>(Q=j1(Q),[W5(Q),...y7(Q)]))(Z);return z=$.calendar,X=J,G=j,e7(Kj($,Y,W),G)+$J(z,X);var z,X,G}function o7($,Z){return J=$.calendar,W=$,Y=g7(Z),v6(W)+$J(J,Y);var J,W,Y}function a7($,Z){return Cj($.calendar,Aj,$,g7(Z))}function t7($,Z){return Cj($.calendar,MU,$,g7(Z))}function r7($,Z){let[J,W,Y]=zj(Z);return j=Y,Sj(l7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=zj(Z,3);return W>1&&($={...$,...UU($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?R0(j):j,{hours:Q,minutes:F}=G,[V,B]=E7(O0(G,3),Z1,Y$);vj(V);let U=ZJ(B,z),O=z>=0||!X||U;return(X<0?"-":"")+"P"+NY({Y:m$(G.years),M:m$(G.months),W:m$(G.weeks),D:m$(G.days)})+(Q||F||V||O?"T"+NY({H:m$(Q),M:m$(F),S:m$(V,O)+U}):"")})($,Y)}function Cj($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==v;return W===1?Y===v?Z(J):v6(J):j?v6(J)+bj(Y,W===2):Z(J)}function NY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function e7($,Z){return v6($)+"T"+Sj($,Z)}function v6($){return Aj($)+"-"+$1($.isoDay)}function Aj($){let{isoYear:Z}=$;return(Z<0||Z>9999?Ej(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+$1($.isoMonth)}function MU($){return $1($.isoMonth)+"-"+$1($.isoDay)}function Sj($,Z){let J=[$1($.isoHour),$1($.isoMinute)];return Z!==-1&&J.push($1($.isoSecond)+((W,Y,j,z)=>ZJ(W*M1+Y*t$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function l$($,Z=0){if(Z===1)return"";let[J,W]=w1(Math.abs($),N4),[Y,j]=w1(W,P4),[z,X]=w1(j,Z1);return Ej($)+$1(J)+":"+$1(Y)+(z||X?":"+$1(z)+ZJ(X):"")}function $J($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==v)return bj(J,Z===2)}return""}function bj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function ZJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(AD,""):J.slice(0,Z),J?"."+J:""}function Ej($){return $<0?"-":"+"}function m$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function HU($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=X$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Rj($,Z){let J=E0(Z,$);return{calendar:Z.calendar,...p0(mX,J),offset:l$(J.offsetNanoseconds),timeZone:Z.timeZone}}function i$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return w7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,F,V,B)=>{let U=A0(F);B&&(V=q6(V));for(let O of Q){let D=n0(s0(O,U));if(B&&(D=q6(D)),D===V)return O}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(lU)}return z?A0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(iU);if(W.length)return W[J===3?1:0];let Y=A0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(IZ(G,-s));return WJ(X.getOffsetNanosecondsFor(IZ(G,s))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(X$(Y,z)))[J===2?0:W.length-1]}function JJ($){if(Math.abs($)>=s)throw RangeError(dU);return $}function WJ($){if($>s)throw RangeError(uU);return $}function YJ($,Z,J){return M0(o0(_Z(Z.epochNanoseconds,((W)=>{if(gj(W))throw RangeError(oU);return O0(W,5)})($?R0(J):J))))}function jJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...BJ(z,X,W,J?R0(Y):Y,j)}}function zJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return X0(FJ($(j),J,Z?R0(W):W,Y),j)}function XJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?R0(W):W,Y),j)}function GJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=L3(z,J);Z&&(W=X4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=s$(X,-1));let G=z.dateAdd(X,W,Y);return h$(L3(z,G),j)}function QJ($,Z,J){return z1(kj(Z,$?R0(J):J)[0])}function BJ($,Z,J,W,Y){let j=O0(W,5),z=J.epochNanoseconds;if(gj(W)){let X=E0(J,$);z=_Z(h0($,{...W4(Z,X,{...W,...tJ},Y),...p0(G1,X)}),j)}else z=_Z(z,j),m(Y);return{epochNanoseconds:o0(z)}}function FJ($,Z,J,W){let[Y,j]=kj(Z,J);return v1({...W4($,Z,{...J,...tJ,days:J.days+j},W),...Y})}function W4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);m(W);let Y=J.days+O0(J,5)[0];return Y?J$(s$(Z,Y)):Z}function L3($,Z,J=1){return s$(Z,J-$.day(Z))}function kj($,Z){let[J,W]=O0(Z,5),[Y,j]=i6(j$($)+W);return[Y,J+j]}function s$($,Z){return Z?{...$,...s6(b0($)+Z*y0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...J1},W]}function VJ($){return $?Uj:A0}function j4($){return $?q(BJ,$):FJ}function UJ($){return $?q(PU,$):NU}function z4($){return $&&$.epochNanoseconds}function M3($,Z){return $<=6-(z4(Z)?1:0)}function DJ($,Z,J,W,Y,j,z){let X=$(j1(z).relativeTo),G=Math.max(p$(Y),p$(j));if(M3(G,X))return e(kZ(((D,L,M,T)=>{let P=_Z(O0(D),O0(L),T?-1:1);if(!Number.isFinite(P[0]))throw RangeError(H4);return{...P0,...wZ(P,M)}})(Y,j,G,W)));if(!X)throw RangeError(T4);W&&(j=R0(j));let[Q,F,V]=Y4(Z,J,X),B=j4(V),U=UJ(V),O=B(F,Q,Y);return e(U(F,Q,B(F,O,j),G))}function wj($,Z,J,W,Y){let j=p$(W),[z,X,G,Q,F]=((C,S,w)=>{C=p7(C,m6);let x=J5(C),f=w(C[pX]),_=m7(C),k=f3(C,7),H0=w3(C);if(x===void 0&&H0===void 0)throw RangeError(aU);return H0==null&&(H0=0),x==null&&(x=Math.max(H0,S)),Qj(x,H0),_=h7(_,H0,1),[x,H0,_,k,f]})(Y,j,$),V=Math.max(j,z);if(!z4(F)&&V<=6)return e(kZ(((C,S,w,x,f)=>{let _=$4(O0(C),w,x,f);return{...P0,...wZ(_,S)}})(W,z,X,G,Q)));if(!F)throw RangeError(T4);let[B,U,O]=Y4(Z,J,F),D=VJ(O),L=j4(O),M=UJ(O),T=L(U,B,W),P=M(U,B,T,z),K=W.sign,R=G$(P);if(K&&R&&K!==R)throw RangeError(E3);return R&&(P=e6(P,D(T),z,X,G,Q,U,B,D,L)),e(P)}function fj($){return $.sign===-1?X4($):$}function X4($){return e(R0($))}function R0($){let Z={};for(let J of p)Z[J]=-1*$[J]||0;return Z}function qj($){return!$.sign}function G$($,Z=p){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(nU);J=Y}}return J}function kZ($){for(let Z of YD)e0(Z,$[Z],-SY,SY,1);return vj(n0(O0($),Z1)),$}function vj($){if(!Number.isSafeInteger($))throw RangeError(sU)}function O0($,Z=6){return gY($,Z,p)}function wZ($,Z=6){let[J,W]=$,Y=c6(W,Z,p);if(Y[p[Z]]+=J*(s/L1[Z]),!Number.isFinite(Y[p[Z]]))throw RangeError(H4);return Y}function G4($,Z=5){return c6($,Z,p)}function gj($){return Boolean(G$($,gX))}function p$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function TU($,Z){return[$,Z]}function KY($){let Z=Math.floor($/b6)*b6;return[Z,Z+b6]}function yj($){let Z=Q$($=k6($));if(!Z)throw RangeError(g0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(g0($));J=fZ(Z.offset)}return Z.timeZone&&HJ(Z.timeZone,1),M0(w7(n6(Z),J))}function mj($){let Z=Q$(J0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return nj(Z,Z.offset?fZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return aj(Z)}function hj($,Z){let J=Q$(J0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?fZ(W):void 0,[,j,z]=I3(Z);return nj(J,Y,j,z)}function fZ($){let Z=HJ($);if(Z===void 0)throw RangeError(g0($));return Z}function pj($){let Z=Q$(J0($));if(!Z||Z.m)throw RangeError(g0($));return X0(oj(Z))}function Q4($){let Z=Q$(J0($));if(!Z||Z.m)throw RangeError(g0($));return G0(Z.p?oj(Z):aj(Z))}function cj($,Z){let J=LJ(J0(Z));if(J)return OJ(J),h$(k7(d$(J)));let W=Q4(Z);return h$(L3($(W.calendar),W))}function OJ($){if($.calendar!==v)throw RangeError(f1($.calendar))}function dj($,Z){let J=MJ(J0(Z));if(J)return OJ(J),f6(d$(J));let W=Q4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,F]=j.I(z,X),[V,B]=j.N(Q,F,G);return f6(J$(j.P(V,B,G)),Y)}function uj($){let Z,J=((W)=>{let Y=kD.exec(W);return Y?(B4(Y[10]),ej(Y)):void 0})(J0($));if(!J){if(J=Q$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(f1("Z"));OJ(J)}if((Z=LJ($))&&TY(Z))throw RangeError(g0($));if((Z=MJ($))&&TY(Z))throw RangeError(g0($));return z1(o6(J,1))}function lj($){let Z=((J)=>{let W=qD.exec(J);return W?((Y)=>{function j(F,V,B){let U=0,O=0;if(B&&([U,G]=w1(G,L1[B])),F!==void 0){if(X)throw RangeError(f1(F));O=((D)=>{let L=parseInt(D);if(!Number.isFinite(L))throw RangeError(f1(D));return L})(F),z=1,V&&(G=TJ(V)*(L1[B]/Z1),X=1)}return U+O}let z=0,X=0,G=0,Q={...SZ(p,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...c6(G,2,p)};if(!z)throw RangeError(LX(p));return PJ(Y[1])<0&&(Q=R0(Q)),Q})(W):void 0})(J0($));if(!Z)throw RangeError(g0($));return e(kZ(Z))}function ij($){let Z=Q$($)||LJ($)||MJ($);return Z?Z.calendar:$}function sj($){let Z=Q$($);return Z&&(Z.timeZone||Z.m&&$Z||Z.offset)||$}function nj($,Z,J=0,W=0){let Y=F4($.timeZone),j=S4(Y);return N0(i$(j,n6($),Z,J,W,!j.v,$.m),Y,C3($.calendar))}function oj($){return tj(v1(n6($)))}function aj($){return tj(J$(d$($)))}function tj($){return{...$,calendar:C3($.calendar)}}function Q$($){let Z=RD.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:rj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...ej(J.slice(5)),...B4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function LJ($){let Z=bD.exec($);return Z?((J)=>({isoYear:rj(J),isoMonth:parseInt(J[4]),isoDay:1,...B4(J[5])}))(Z):void 0}function MJ($){let Z=ED.exec($);return Z?((J)=>({isoYear:AZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...B4(J[3])}))(Z):void 0}function HJ($,Z){let J=wD.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(f1(j));return JJ((KZ(W[2])*N4+KZ(W[3])*P4+KZ(W[4])*Z1+TJ(W[5]||""))*PJ(W[1]))})(J,Z):void 0}function rj($){let Z=PJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(f1(-0));return Z*J}function ej($){let Z=KZ($[3]);return{...i6(TJ($[4]||""))[0],isoHour:KZ($[1]),isoMinute:KZ($[2]),isoSecond:Z===60?59:Z}}function B4($){let Z,J,W=[];if($.replace(fD,(Y,j,z)=>{let X=Boolean(j),[G,Q]=z.split("=").reverse();if(Q){if(Q==="u-ca")W.push(G),Z||(Z=X);else if(X||/[A-Z]/.test(Q))throw RangeError(f1(Y))}else{if(J)throw RangeError(f1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(f1($));return{timeZone:J,calendar:W[0]||v}}function TJ($){return parseInt($.padEnd(9,"0"))}function qZ($){return new RegExp(`^${$}$`,"i")}function PJ($){return $&&$!=="+"?-1:1}function KZ($){return $===void 0?0:parseInt($)}function $z($){return F4(J0($))}function F4($){let Z=NJ($);return typeof Z=="number"?l$(Z):Z?((J)=>{if(gD.test(J))throw RangeError(cU);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?MY(j).replace(/island|noronha|murdo|rivadavia|urville/,MY):j)).join("/")})($):$Z}function _Y($){let Z=NJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:$Z}function NJ($){let Z=HJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==$Z?vD($):void 0}function KJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function _J($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function Zz($,Z,J,W,Y,j){let z=$(j1(j).relativeTo),X=Math.max(p$(W),p$(Y));if(qY(p,W,Y))return 0;if(M3(X,z))return S0(O0(W),O0(Y));if(!z)throw RangeError(T4);let[G,Q,F]=Y4(Z,J,z),V=VJ(F),B=j4(F);return S0(V(B(Q,G,W)),V(B(Q,G,Y)))}function IJ($,Z){return n$($,Z)||V4($,Z)}function n$($,Z){return Z$(b0($),b0(Z))}function V4($,Z){return Z$(j$($),j$(Z))}function Jz($,Z){return!KJ($,Z)}function Wz($,Z){return!_J($,Z)&&!!U4($.timeZone,Z.timeZone)&&RZ($.calendar,Z.calendar)}function Yz($,Z){return!IJ($,Z)&&RZ($.calendar,Z.calendar)}function jz($,Z){return!n$($,Z)&&RZ($.calendar,Z.calendar)}function zz($,Z){return!n$($,Z)&&RZ($.calendar,Z.calendar)}function Xz($,Z){return!n$($,Z)&&RZ($.calendar,Z.calendar)}function Gz($,Z){return!V4($,Z)}function U4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return _Y(J)===_Y(W)}catch(Y){}}function xJ($,Z,J,W){let Y=EZ($,z0(W),3,5),j=D4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return e($?R0(j):j)}function CJ($,Z,J,W,Y,j){let z=L4(W.calendar,Y.calendar),X=z0(j),[G,Q,F,V]=EZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,O=S0(U,B),D;if(O)if(G<6)D=D4(B,U,G,Q,F,V);else{let L=Z(((T,P)=>{if(!U4(T,P))throw RangeError(KX);return T})(W.timeZone,Y.timeZone)),M=$(z);D=Bz(M,L,W,Y,O,G,X),D=e6(D,U,G,Q,F,V,M,W,Uj,q(BJ,L))}else D=P0;return e(J?R0(D):D)}function AJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),[X,G,Q,F]=EZ(Z,z,6),V=A0(J),B=A0(W),U=S0(B,V),O;if(U)if(X<=6)O=D4(V,B,X,G,Q,F);else{let D=$(j);O=Fz(D,J,W,U,X,z),O=e6(O,B,X,G,Q,F,D,J,A0,FJ)}else O=P0;return e(Z?R0(O):O)}function SJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y);return Qz(Z,()=>$(j),J,W,...EZ(Z,z,6,9,6),z)}function bJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),X=EZ(Z,z,9,9,8),G=$(j);return Qz(Z,()=>G,L3(G,J),L3(G,W),...X,z)}function Qz($,Z,J,W,Y,j,z,X,G){let Q=A0(J),F=A0(W),V;if(S0(F,Q))if(Y===6)V=D4(Q,F,Y,j,z,X);else{let B=Z();V=B.dateUntil(J,W,Y,G),j===6&&z===1||(V=e6(V,F,Y,j,z,X,B,J,A0,W4))}else V=P0;return e($?R0(V):V)}function EJ($,Z,J,W){let Y=z0(W),[j,z,X,G]=EZ($,Y,5,5),Q=z$(RJ(Z,J),x3(z,X),G),F={...P0,...G4(Q,j)};return e($?R0(F):F)}function PU($,Z,J,W,Y,j){let z=S0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Vz(J.epochNanoseconds,W.epochNanoseconds,Y):Bz(Z,$,J,W,z,Y,j):P0}function NU($,Z,J,W,Y){let j=A0(Z),z=A0(J),X=S0(z,j);return X?W<=6?Vz(j,z,W):Fz($,Z,J,X,W,Y):P0}function Bz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,O,D)=>{function L(){return S={...s$(P,R++*-D),...T},w=h0(B,S),S0(K,w)===-D}let M=E0(U,B),T=p0(G1,M),P=E0(O,B),K=O.epochNanoseconds,R=0,C=RJ(M,P),S,w;if(Math.sign(C)===-D&&R++,L()&&(D===-1||L()))throw RangeError(E3);let x=n0(s0(w,K));return[M,S,x]})(Z,J,W,Y);var F,V;return{...j===6?(F=X,V=G,{...P0,days:Uz(F,V)}):$.dateUntil(X,G,j,z),...G4(Q)}}function Fz($,Z,J,W,Y,j){let[z,X,G]=((Q,F,V)=>{let B=F,U=RJ(Q,F);return Math.sign(U)===-V&&(B=s$(F,-V),U+=s*V),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...G4(G)}}function D4($,Z,J,W,Y,j){return{...P0,...wZ($4(s0($,Z),W,Y,j),J)}}function Vz($,Z,J){return{...P0,...wZ(s0($,Z),J)}}function Uz($,Z){return O4(b0($),b0(Z))}function O4($,Z){return Math.trunc((Z-$)/y0)}function RJ($,Z){return j$(Z)-j$($)}function L4($,Z){if(!RZ($,Z))throw RangeError(iJ);return $}function KU($){function Z(Y){return((j,z)=>({...Dz(j,z),F:j.month,day:parseInt(j.day)}))(R7(J,Y),W)}let J=X5($),W=g6($);return{id:$,O:_U(Z),B:IU(Z)}}function _U($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function IU($){let Z=$(0).year-BD;return m0((J)=>{let W,Y=bZ(J-Z),j=[],z=[];do Y+=400*y0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*y0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=y0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:xX(z.reverse())}})}function Dz($,Z){let J,W,Y=Oz($);if($.era){let j=fX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=Pz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Oz($){return parseInt($.relatedYear||$.year)}function O7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function H3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*y0}function C6($){let Z=xY(this,$),J=xY(this,$-1),W=Z.length;if(W>J.length){let Y=Nz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function A6($){return O4(H3.call(this,$),H3.call(this,$+1))}function IY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),O4(J[Z-1],Y[W-1])}function S6($){return this.B($).k.length}function xY($,Z){return Object.keys($.B(Z).C)}function Lz($){return C3(J0($))}function C3($){if(($=$.toLowerCase())!==v&&$!==_4&&g6($)!==g6(X5($).resolvedOptions().calendar))throw RangeError(pU($));return $}function g6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Mz($){return this.R($)[0]}function Hz($){return this.R($)[1]}function kJ($){let[Z]=this.h($);return O4(this.q(Z),b0($))+1}function Tz($){let Z=mD.exec($);if(!Z)throw RangeError(mU($));return[parseInt(Z[1]),Boolean(Z[2])]}function y6($,Z,J){return $+(Z||J&&$>=J?1:0)}function L7($,Z){return $-(Z&&$>=Z?1:0)}function Pz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function M7($){return fX[Kz($)]}function Nz($){return ZD[Kz($)]}function Kz($){return g6($.id||v)}function _z($,Z,J,W){let Y=B$(J,W,X1,[],EX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=o$(Y),X=$(Y.timeZone);return{epochNanoseconds:i$(Z(X),{...j,...z},Y.offset!==void 0?fZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...J1}}function Iz($,Z,J,W,Y,j){let z=B$(J,Y,X1,SX,EX),X=$(z.timeZone),[G,Q,F]=I3(j),V=J.dateFromFields(z,t6(j,G)),B=o$(z,G);return N0(i$(Z(X),{...V,...B},z.offset!==void 0?fZ(z.offset):void 0,Q,F),X,W)}function xz($,Z,J){let W=B$($,Z,X1,[],m1),Y=m(J);return X0(v1({...$.dateFromFields(W,t6(J,Y)),...o$(W,Y)}))}function wJ($,Z,J,W=[]){let Y=B$($,Z,X1,W);return $.dateFromFields(Y,J)}function fJ($,Z,J,W){let Y=B$($,Z,oJ,W);return $.yearMonthFromFields(Y,J)}function qJ($,Z,J,W,Y=[]){let j=B$($,J,X1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=AZ),$.monthDayFromFields(j,W)}function Cz($,Z){let J=m(Z);return z1(o$(O1($,T7,[],1),J))}function Az($){let Z=O1($,aJ);return e(kZ({...P0,...Z}))}function B$($,Z,J,W=[],Y=[]){return O1(Z,[...$.fields(J),...Y].sort(),W)}function O1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(wU(X));if(X==="constructor"||X==="__proto__")throw RangeError(uJ(X));let G=$[X];if(G!==void 0)z=1,bY[X]&&(G=bY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(dJ(X));Y[X]=wX[X]}j=X}if(W&&!z)throw TypeError(LX(Z));return Y}function o$($,Z){return o6(dD({...wX,...$}),Z)}function Sz($,Z,J,W,Y,j){let z=z0(j),{calendar:X,timeZone:G}=J;return N0(((Q,F,V,B,U)=>{let O=A3(Q,V,B,X1,bX,AX),[D,L,M]=I3(U,2);return i$(F,{...Q.dateFromFields(O,t6(U,D)),...o$(O,D)},fZ(O.offset),L,M)})($(X),Z(G),W,Y,z),G,X)}function bz($,Z,J,W,Y){let j=z0(Y);return X0(((z,X,G,Q)=>{let F=A3(z,X,G,X1,m1),V=m(Q);return v1({...z.dateFromFields(F,t6(Q,V)),...o$(F,V)})})($(Z.calendar),J,W,j))}function Ez($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let F=A3(z,X,G,X1);return z.dateFromFields(F,Q)})($(Z.calendar),J,W,j)}function Rz($,Z,J,W,Y){let j=z0(Y);return h$(((z,X,G,Q)=>{let F=A3(z,X,G,oJ);return z.yearMonthFromFields(F,Q)})($(Z.calendar),J,W,j))}function kz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let F=A3(z,X,G,X1);return z.monthDayFromFields(F,Q)})($(Z.calendar),J,W,j)}function wz($,Z,J){return z1(((W,Y,j)=>{let z=m(j);return o$({...p0(T7,W),...O1(Y,T7)},z)})($,Z,J))}function fz($,Z){return e((J=$,W=Z,kZ({...J,...O1(W,aJ)})));var J,W}function A3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=O1(Z,z,j),G=O1(J,z);return X=$.mergeFields(X,G),O1(X,z,[])}function vJ($,Z){let J=B$($,Z,kX);return $.monthDayFromFields(J)}function gJ($,Z,J){let W=B$($,Z,RX);return $.yearMonthFromFields(W,J)}function qz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=O1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=O1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function B7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=M7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(qU);if(!j)throw RangeError(fU);let z=j[J];if(z===void 0)throw RangeError(gU(J));let X=Pz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(vU);Y=X}else if(Y===void 0)throw TypeError(yU(j));return Y}function F7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,F)=>{let V=X.U(Q),[B,U]=Tz(G),O=y6(B,U,V);if(U){let D=Nz(X);if(D===void 0)throw RangeError(U3);if(D>0){if(O>D)throw RangeError(U3);if(V===void 0){if(F===1)throw RangeError(U3);O--}}else{if(O!==-D)throw RangeError(U3);if(V===void 0&&F===1)throw RangeError(U3)}}return O})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(PX);Y=z,W=1}else if(Y===void 0)throw TypeError(hU);return e0("month",Y,1,$.L(J),W)}function CY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function V7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function vz($){return M0(o0(l6(u6($))))}function gz($,Z,J,W,Y=v){return N0(o0(l6(u6(J))),Z(W),$(Y))}function yz($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,F=v){return X0(v1(n6(W1(C0,SZ(I4,[Z,J,W,Y,j,z,X,G,Q])))),$(F))}function mz($,Z,J,W,Y=v){return G0(J$(d$(W1(C0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function hz($,Z,J,W=v,Y=1){let j=C0(Z),z=C0(J),X=$(W);return h$(k7(d$({isoYear:j,isoMonth:z,isoDay:C0(Y)})),X)}function pz($,Z,J,W=v,Y=AZ){let j=C0(Z),z=C0(J),X=$(W);return f6(J$(d$({isoYear:C0(Y),isoMonth:j,isoDay:z})),X)}function cz($=0,Z=0,J=0,W=0,Y=0,j=0){return z1(o6(W1(C0,SZ(G1,[$,Z,J,W,Y,j])),1))}function dz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return e(kZ(W1(sY,SZ(p,[$,Z,J,W,Y,j,z,X,G,Q]))))}function yJ($,Z,J=v){return N0($.epochNanoseconds,Z,J)}function uz($){return M0($.epochNanoseconds)}function mJ($,Z){return X0(E0(Z,$))}function hJ($,Z){return G0(E0(Z,$))}function lz($,Z,J){return gJ($(Z.calendar),J)}function iz($,Z,J){return vJ($(Z.calendar),J)}function pJ($,Z){return z1(E0(Z,$))}function sz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=v7(G);return h0(j(z),X,Q)})($,J,Z,W);return N0(o0(Y),J,Z.calendar)}function nz($,Z,J){let W=$(Z.calendar);return h$({...Z,...gJ(W,J)})}function oz($,Z,J){return vJ($(Z.calendar),J)}function az($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):J1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function tz($,Z=J1){return X0(v1({...$,...Z}))}function rz($,Z,J){return gJ($(Z.calendar),J)}function ez($,Z,J){return vJ($(Z.calendar),J)}function $X($,Z,J,W){return((Y,j,z)=>qz(Y,j,RX,q1(z),k3))($(Z.calendar),J,W)}function ZX($,Z,J,W){return((Y,j,z)=>qz(Y,j,kX,q1(z),K4))($(Z.calendar),J,W)}function JX($,Z,J,W,Y){let j=q1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function WX($,Z){return X0(v1({...$,...Z}))}function YX($){return M0(o0(xZ($,Z1)))}function jX($){return M0(o0(xZ($,M1)))}function zX($){return M0(o0(l6(u6($),t$)))}function XX($){return M0(o0(l6(u6($))))}function GX($,Z,J=J1){let W=Z.timeZone,Y=$(W),j={...E0(Z,Y),...J};return N0(i$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function QX($,Z,J){let W=Z.timeZone,Y=$(W),j={...E0(Z,Y),...J},z=UX(Z.calendar,J.calendar);return N0(i$(Y,j,j.offsetNanoseconds,2),W,z)}function BX($,Z=J1){return X0({...$,...Z})}function FX($,Z){return X0({...$,...Z},UX($.calendar,Z.calendar))}function M4($,Z){return{...$,calendar:Z}}function VX($,Z){return{...$,timeZone:Z}}function UX($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===v)return Z;if(W===v)return $;throw RangeError(iJ)}function xU($,Z){return(J)=>J===v?$:J===_4||J===CZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),yD(J))}function a$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=_7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=$Z,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function g1($,Z=cJ){let[J,,,W]=$;return(Y,j=jO,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...CU($,G,z)]}}function cJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(rU);J.timeZone=$}return new F$(Z,J)}function CU($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==v)&&z!==X)throw RangeError(iJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function vZ($){let Z=S3();return X$(Z,$.getOffsetNanosecondsFor(Z))}function S3(){return xZ(Date.now(),M1)}function y1(){return RY||(RY=new F$().resolvedOptions().timeZone)}var AU=($,Z)=>`Non-integer ${$}: ${Z}`,SU=($,Z)=>`Non-positive ${$}: ${Z}`,bU=($,Z)=>`Non-finite ${$}: ${Z}`,EU=($)=>`Cannot convert bigint to ${$}`,RU=($)=>`Invalid bigint: ${$}`,kU="Cannot convert Symbol to string",DX="Invalid object",OX=($,Z,J,W,Y)=>Y?OX($,Y[Z],Y[J],Y[W]):b3($,Z)+`; must be between ${J}-${W}`,b3=($,Z)=>`Invalid ${$}: ${Z}`,dJ=($)=>`Missing ${$}`,uJ=($)=>`Invalid field ${$}`,wU=($)=>`Duplicate field ${$}`,LX=($)=>"No valid fields: "+$.join(),MX="Invalid bag",HX=($,Z,J)=>b3($,Z)+"; must be "+Object.keys(J).join(),TX="Cannot use valueOf",lJ="Invalid calling context",fU="Forbidden era/eraYear",qU="Mismatching era/eraYear",vU="Mismatching year/eraYear",gU=($)=>`Invalid era: ${$}`,yU=($)=>"Missing year"+($?"/era/eraYear":""),mU=($)=>`Invalid monthCode: ${$}`,PX="Mismatching month/monthCode",hU="Missing month/monthCode",AY="Cannot guess year",U3="Invalid leap month",NX="Invalid protocol",E3="Invalid protocol results",iJ="Mismatching Calendars",pU=($)=>`Invalid Calendar: ${$}`,KX="Mismatching TimeZones",cU="Forbidden ICU TimeZone",dU="Out-of-bounds offset",uU="Out-of-bounds TimeZone gap",lU="Invalid TimeZone offset",iU="Ambiguous offset",H4="Out-of-bounds date",sU="Out-of-bounds duration",nU="Cannot mix duration signs",T4="Missing relativeTo",oU="Cannot use large units",aU="Required smallestUnit or largestUnit",tU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,f1=($)=>`Invalid substring: ${$}`,_X=($)=>`Cannot format ${$}`,IX="Mismatching types for formatting",rU="Cannot specify TimeZone",xX=q(N3,($,Z)=>Z),gZ=q(N3,($,Z,J)=>J),$1=q(R6,2),H7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},R3=Object.keys(H7),y0=86400000,CX=1000,t$=1000,M1=1e6,Z1=1e9,P4=60000000000,N4=3600000000000,s=86400000000000,L1=[1,t$,M1,Z1,P4,N4,s],m1=R3.slice(0,6),T7=K3(m1),AX=["offset"],SX=["timeZone"],bX=m1.concat(AX),EX=bX.concat(SX),P7=["era","eraYear"],eU=P7.concat(["year"]),K4=["year"],sJ=["monthCode"],nJ=["month"].concat(sJ),k3=["day"],oJ=nJ.concat(K4),RX=sJ.concat(K4),X1=k3.concat(oJ),$D=k3.concat(nJ),kX=k3.concat(sJ),wX=gZ(m1,0),v="iso8601",_4="gregory",CZ="japanese",fX={[_4]:{bce:-1,ce:0},[CZ]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},ZD={chinese:13,dangi:13,hebrew:-6},J0=q(d6,"string"),qX=q(d6,"boolean"),JD=q(d6,"number"),vX=q(d6,"function"),p=R3.map(($)=>$+"s"),aJ=K3(p),WD=p.slice(0,6),gX=p.slice(6),YD=gX.slice(1),jD=xX(p),P0=gZ(p,0),tJ=gZ(WD,0),rJ=q(vY,p),G1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],eJ=["isoDay","isoMonth","isoYear"],I4=G1.concat(eJ),$5=K3(eJ),yX=K3(G1),mX=K3(I4),J1=gZ(yX,0),zD=q(vY,I4),F$=Intl.DateTimeFormat,hX="en-GB",Z5=1e8,XD=Z5*y0,GD=[Z5,0],QD=[-Z5,0],T3=275760,P3=-271821,BD=1970,AZ=1972,k1=12,FD=bZ(1868,9,8),VD=m0(VU,WeakMap),m6="smallestUnit",N7="unit",O3="roundingIncrement",U7="fractionalSecondDigits",pX="relativeTo",cX={constrain:0,reject:1},UD=Object.keys(cX),DD={compatible:0,reject:1,earlier:2,later:3},OD={reject:0,use:1,prefer:2,ignore:3},LD={auto:0,never:1,critical:2,always:3},MD={auto:0,never:1,critical:2},HD={auto:0,never:1},TD={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},w3=q(c7,m6),J5=q(c7,"largestUnit"),PD=q(c7,N7),dX=q(u$,"overflow",cX),uX=q(u$,"disambiguation",DD),ND=q(u$,"offset",OD),W5=q(u$,"calendarName",LD),KD=q(u$,"timeZoneName",MD),_D=q(u$,"offset",HD),f3=q(u$,"roundingMode",TD),yZ="PlainYearMonth",mZ="PlainMonthDay",r$="PlainDate",e$="PlainDateTime",x4="PlainTime",h1="ZonedDateTime",C4="Instant",A4="Duration",ID=[Math.floor,($)=>x6($)?Math.floor($):Math.round($),Math.ceil,($)=>x6($)?Math.ceil($):Math.round($),Math.trunc,($)=>x6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>x6($)?($=Math.trunc($)||0)+$%2:Math.round($)],$Z="UTC",b6=5184000,xD=w6(1847),CD=w6(new Date().getUTCFullYear()+10),AD=/0+$/,E0=m0(HU,WeakMap),SY=4294967295,S4=m0(($)=>{let Z=NJ($);return typeof Z=="object"?new iX(Z):new lX(Z||0)});class lX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[w7($,this.v)]}l(){}}class iX{constructor($){this.$=((Z)=>{function J(G){let Q=D7(G,z,X),[F,V]=KY(Q),B=Y(F),U=Y(V);return B===U?B:W(j(F,V),B,U,G)}function W(G,Q,F,V){let B,U;for(;(V===void 0||(B=V<G[0]?Q:V>=G[1]?F:void 0)===void 0)&&(U=G[1]-G[0]);){let O=G[0]+Math.floor(U/2);Z(O)===F?G[1]=O:G[0]=O+1}return B}let Y=m0(Z),j=m0(TU),z=xD,X=CD;return{G(G){let Q=J(G-86400),F=J(G+86400),V=G-Q,B=G-F;if(Q===F)return[V];let U=J(V);return U===J(B)?[G-U]:Q>F?[V,B]:[]},V:J,l(G,Q){let F=D7(G,z,X),[V,B]=KY(F),U=b6*Q,O=Q<0?()=>B>z||(z=F,0):()=>V<X||(X=F,0);for(;O();){let D=Y(V),L=Y(B);if(D!==L){let M=j(V,B);W(M,D,L);let T=M[0];if((Z$(T,G)||1)===Q)return T}V+=U,B+=U}}}})(((Z)=>(J)=>{let W=R7(Z,J*CX);return w6(Oz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(aY($))*Z1}getPossibleInstantsFor($){let[Z,J]=[w6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*M1+W.isoMicrosecond*t$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>o0(IZ(xZ(Y,Z1),J)))}l($,Z){let[J,W]=tY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return xZ(Y,Z1)}}var Y5="([+\u2212-])",E6="(?:[.,](\\d{1,9}))?",sX=`(?:(?:${Y5}(\\d{6}))|(\\d{4}))-?(\\d{2})`,j5="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+E6+")?)?",z5=Y5+j5,SD=sX+"-?(\\d{2})(?:[T ]"+j5+"(Z|"+z5+")?)?",nX="\\[(!?)([^\\]]*)\\]",b4=`((?:${nX}){0,9})`,bD=qZ(sX+b4),ED=qZ("(?:--)?(\\d{2})-?(\\d{2})"+b4),RD=qZ(SD+b4),kD=qZ("T?"+j5+"(?:"+z5+")?"+b4),wD=qZ(z5),fD=new RegExp(nX,"g"),qD=qZ(`${Y5}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${E6}H)?(?:(\\d+)${E6}M)?(?:(\\d+)${E6}S)?)?`),vD=m0(($)=>new F$(hX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),gD=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,yD=m0(KU),X5=m0(($)=>new F$(hX,{calendar:$,timeZone:$Z,era:"short",year:"numeric",month:"short",day:"numeric"})),mD=/^M(\d{2})(L?)$/,hD={era:k6,eraYear:C0,year:C0,month:HY,monthCode:k6,day:HY},pD=gZ(m1,C0),cD=gZ(p,sY),bY=Object.assign({},hD,pD,cD,{offset:k6}),dD=q(FU,m1,G1),EY={dateAdd($,Z,J){let W=m(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=O0(Z,5)[0],j||z)Y=((Q,F,V,B,U)=>{let[O,D,L]=Q.h(F);if(V){let[M,T]=Q.I(O,D);O+=V,D=y6(M,T,Q.U(O)),D=e0("month",D,1,Q.L(O),U)}return B&&([O,D]=Q._(O,D,B)),L=e0("day",L,1,Q.j(O,D),U),Q.q(O,D,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=b0($)}return Y+=(7*X+G)*y0,J$(s6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Uz({...$,...J1},{...Z,...J1});return J===7&&([G,Q]=Y$(Q,7)),{...P0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,F,V,B,U,O)=>{let D=B-Q,L=U-F,M=O-V;if(D||L){let T=Math.sign(D||L),P=G.j(B,U),K=0;if(Math.sign(M)===-T){let R=P;[B,U]=G._(B,U,-T),D=B-Q,L=U-F,P=G.j(B,U),K=T<0?-R:P}if(M=O-Math.min(V,P)+K,D){let[R,C]=G.I(Q,F),[S,w]=G.I(B,U);if(L=S-R||Number(w)-Number(C),Math.sign(L)===-T){let x=T<0&&-G.L(B);D=(B-=T)-Q,L=U-y6(R,C,G.U(B))+(x||G.L(B))}}}return[D,L,M]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...P0,years:j,months:z,days:X}},dateFromFields($,Z){let J=m(Z),W=B7(this,$),Y=F7(this,$,W,J),j=CY(this,$,Y,W,J);return G0(J$(this.P(W,Y,j)),this.id||v)},yearMonthFromFields($,Z){let J=m(Z),W=B7(this,$),Y=F7(this,$,W,J);return h$(k7(this.P(W,Y,1)),this.id||v)},monthDayFromFields($,Z){let J=m(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,G,Q,F,V;if(Y!==void 0){[X,G]=Tz(Y),V=kY($,"day");let B=this.N(X,G,V);if(!B)throw RangeError(AY);if([Q,F]=B,z!==void 0&&z!==F)throw RangeError(PX);W&&(F=e0("month",F,1,k1,1),V=e0("day",V,1,f7(j!==void 0?j:Q,F),J))}else{Q=j===void 0&&W?AZ:B7(this,$),F=F7(this,$,Q,J),V=CY(this,$,F,Q,J);let B=this.U(Q);G=F===B,X=L7(F,B);let U=this.N(X,G,V);if(!U)throw RangeError(AY);[Q,F]=U}return f6(J$(this.P(Q,F,V)),this.id||v)},fields($){return M7(this)&&$.includes("year")?[...$,...P7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return V7(J,Z,nJ),M7(this)&&(V7(J,Z,eU),this.id===CZ&&V7(J,Z,$D,P7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:kJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+$1(j)+(z?"L":""))(W,Y)},dayOfWeek:Jj,daysInWeek(){return 7}},uD={dayOfYear:kJ,h:eY,q:bZ},lD=Object.assign({},uD,{weekOfYear:Mz,yearOfWeek:Hz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let O=Zj(B+U),D=U||1,L=Z(D3(G+O*D,7));return F=(O+(L-Q)*D)/7}let W=this.id?1:4,Y=Jj($),j=this.dayOfYear($),z=D3(Y-1,7),X=j-1,G=D3(z-X,7),Q=Z(G),F,V=Math.floor((X-Q)/7)+1,B=$.isoYear;return V?V>J(0)&&(V=1,B++):(V=J(-1),B--),[V,B,F]}}),iD={dayOfYear:kJ,h:O7,q:H3,weekOfYear:Mz,yearOfWeek:Hz,R(){return[]}},hZ=xU(Object.assign({},EY,lD,{h:eY,ee($){return this.id===_4?Wj($):this.id===CZ?VD($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[AZ,$]},K:q7,U(){},L:$j,J:($)=>$*k1,j:f7,X:Zj,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:bZ,_:($,Z,J)=>($+=p6(J,k1),(Z+=x7(J,k1))<1?($--,Z+=k1):Z>k1&&($++,Z-=k1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},EY,iD,{h:O7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[L7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=O7.call(this,{isoYear:AZ,isoMonth:k1,isoDay:31}),z=C6.call(this,W),X=Y===z;(Z$($,L7(Y,z))||Z$(Number(Z),Number(X))||Z$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,F=C6.call(this,Q),V=y6($,Z,F);if(Z===(V===F)&&J<=IY.call(this,Q,V))return[Q,V]}},K($){let Z=A6.call(this,$);return Z>A6.call(this,$-1)&&Z>A6.call(this,$+1)},U:C6,L:S6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=S6.call(this,z+Y);return j},j:IY,X:A6,P($,Z,J){return s6(H3.call(this,$,Z,J))},q:H3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(H4);if(J<0)for(;Z<1;)Z+=S6.call(this,--$);else{let W;for(;Z>(W=S6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),W$="numeric",pZ=["timeZoneName"],oX={month:W$,day:W$},G5={year:W$,month:W$},Q5=Object.assign({},G5,{day:W$}),B5={hour:W$,minute:W$,second:W$},F5=Object.assign({},Q5,B5),sD=Object.assign({},F5,{timeZoneName:"short"}),nD=Object.keys(G5),oD=Object.keys(oX),aD=Object.keys(Q5),tD=Object.keys(B5),V5=["dateStyle"],rD=nD.concat(V5),eD=oD.concat(V5),U5=aD.concat(V5,["weekday"]),q3=tD.concat(["dayPeriod","timeStyle"]),D5=U5.concat(q3),$O=D5.concat(pZ),ZO=pZ.concat(q3),JO=pZ.concat(U5),WO=pZ.concat(["day","weekday"],q3),YO=pZ.concat(["year","weekday"],q3),jO={},O5=[a$(D5,F5),r6],aX=[a$($O,sD),r6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(KX);return J}],L5=[a$(D5,F5,pZ),b0],M5=[a$(U5,Q5,ZO),b0],H5=[a$(q3,B5,JO),($)=>j$($)/M1],T5=[a$(rD,G5,WO),b0,1],P5=[a$(eD,oX,YO),b0,1],RY;function P1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(lJ);$G(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...F){return G.call(this,X(this),...F)},K7(Q))}function X(G){let Q=I0(G);if(!Q||Q.branding!==$)throw TypeError(lJ);return Q}return Object.defineProperties(j.prototype,{...wY(W1(z,J)),...c$(W1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...c$(Y),...K7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return $G(Q,G),Q},X]}function WG($){return $=$.concat("id").sort(),(Z)=>{if(!fY(Z,$))throw TypeError(NX);return Z}}function lZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(MX);return $}function E4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=I0(j)||{},{branding:X}=z,G=X===r$||Z.includes(X)?z:w0(j);return Y[W](G)};return J}function _5($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?hZ(j):(z=j,Object.assign(Object.create(NO),{i:z})))[J](W);var j,z};return Z}function L$(){throw TypeError(TX)}function g3({calendar:$}){return typeof $=="string"?new k5($):$}function tX($,Z){if(Z=z0(Z),L0($)){let W=I0($);if(W&&W.branding===mZ)return m(Z),W;let Y=zG($);return qJ(g4(Y||v),!Y,$,Z)}let J=dj(hZ,$);return m(Z),J}function YG($,Z,J){return W=Z.call($,k0(M0(J))),JJ(_3(W));var W}function R4($,Z=BG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=q(Z[Y],$,vX($[Y]));return W}function o($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return o($,K5)}function H1($){if(L0($)){let Z=I0($);if(Z)switch(Z.branding){case C4:return Z;case h1:return M0(Z.epochNanoseconds)}}return yj($)}function rX($,Z,J){let W=Z.l(H1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function t($){return L0($)?(I0($)||{}).timeZone||AO($):((Z)=>F4(sj(J0(Z))))($)}function V$($,Z){if(L0($)){let J=I0($)||{};switch(J.branding){case x4:return m(Z),J;case e$:return m(Z),z1(J);case h1:return m(Z),pJ(B0,J)}return Cz($,Z)}return m(Z),uj($)}function I5($){return $===void 0?void 0:V$($)}function cZ($,Z){if(Z=z0(Z),L0($)){let W=I0($);return W&&W.branding===yZ?(m(Z),W):fJ(q4(y3($)),$,Z)}let J=cj(hZ,$);return m(Z),J}function U$($,Z){if(Z=z0(Z),L0($)){let W=I0($)||{};switch(W.branding){case e$:return m(Z),W;case r$:return m(Z),X0({...W,...J1});case h1:return m(Z),mJ(B0,W)}return xz(v4(y3($)),$,Z)}let J=pj($);return m(Z),J}function w0($,Z){if(Z=z0(Z),L0($)){let W=I0($)||{};switch(W.branding){case r$:return m(Z),W;case e$:return m(Z),G0(W);case h1:return m(Z),hJ(B0,W)}return wJ(v4(y3($)),$,Z)}let J=Q4($);return m(Z),J}function jG($,Z,J){return Y1(Z.call($,Y0(G0(J,$))))}function N1($){return(Z)=>typeof Z=="string"?hZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=q(W[z],J,J[z]);return j})(Z,$)}function W0($){if(L0($)){let Z=I0($);return Z&&Z.branding===A4?Z:Az($)}return lj($)}function v3($){if($!==void 0){if(L0($)){let Z=I0($)||{};switch(Z.branding){case h1:case r$:return Z;case e$:return G0(Z)}let J=y3($);return{..._z(t,o,v4(J),$),calendar:J}}return mj($)}}function y3($){return zG($)||v}function zG($){let{calendar:Z}=$;if(Z!==void 0)return _0(Z)}function _0($){return L0($)?(I0($)||{}).calendar||cO($):((Z)=>C3(ij(J0(Z))))($)}function dZ($,Z){if(Z=z0(Z),L0($)){let J=I0($);if(J&&J.branding===h1)return I3(Z),J;let W=y3($);return Iz(t,o,v4(W),W,$,Z)}return hj($,Z)}function eX($){return W1((Z)=>(J)=>Z(N5(J)),$)}function N5($){return E0($,B0)}function zO(){let $=F$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(F$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);w5.set(this,((z,X={})=>{let G=new F$(z,X),Q=G.resolvedOptions(),F=Q.locale,V=p0(Object.keys(X),Q),B=m0(QO),U=(...O)=>{let D,L=O.map((M,T)=>{let P=I0(M),K=(P||{}).branding;if(T&&D&&D!==K)throw TypeError(IX);return D=K,P});return D?B(D)(F,V,...L):[G,...O]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&XO(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||GO(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function XO($){return function(...Z){let J=w5.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function GO($){return function(...Z){return w5.get(this).u[$](...Z)}}function QO($){let Z=BO[$];if(!Z)throw TypeError(_X($));return g1(Z,m0(cJ))}var BO={Instant:O5,PlainDateTime:L5,PlainDate:M5,PlainTime:H5,PlainYearMonth:T5,PlainMonthDay:P5},FO=g1(O5),VO=g1(aX),UO=g1(L5),DO=g1(M5),OO=g1(H5),LO=g1(T5),MO=g1(P5),x5={era:pY,eraYear:C7,year:_3,month:Y1,daysInMonth:Y1,daysInYear:Y1,inLeapYear:qX,monthsInYear:Y1},w4={monthCode:J0},C5={day:Y1},XG={dayOfWeek:Y1,dayOfYear:Y1,weekOfYear:cY,yearOfWeek:C7,daysInWeek:Y1},GG=Object.assign({},x5,w4,C5,XG),k4=new WeakMap,I0=k4.get.bind(k4),$G=k4.set.bind(k4),HO={...E4(x5,[yZ]),...E4(XG,[]),...E4(w4,[yZ,mZ]),...E4(C5,[mZ])},A5=_5(GG),TO=_5({...x5,...w4}),PO=_5({...w4,...C5}),m3={calendarId:($)=>T0($.calendar)},NO=W1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(G0(J,W))))},GG),KO=N3(($)=>(Z)=>Z[$],p.concat("sign")),S5=N3(($,Z)=>(J)=>J[G1[Z]],m1),QG={epochSeconds:Bj,epochMilliseconds:r6,epochMicroseconds:Fj,epochNanoseconds:Vj},h3=q(_7,new Set(["branding"])),[_O,uZ,IO]=P1(mZ,q(pz,_0),{...m3,...PO},{getISOFields:h3,getCalendar:g3,with($,Z,J){return uZ(kz(mO,$,this,lZ(Z),J))},equals:($,Z)=>Xz($,tX(Z)),toPlainDate($,Z){return Y0(ZX(p3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=MO(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:L$},{from:($,Z)=>uZ(tX($,Z))}),BG={getOffsetNanosecondsFor:YG,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,K0(X0(J,v)))].map((j)=>CO(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(S0),WJ(n0(s0(W[0],W[Y-1])))),W}},K5={getOffsetNanosecondsFor:YG},[xO,k0,CO]=P1(C4,vz,QG,{add:($,Z)=>k0(YJ(0,$,W0(Z))),subtract:($,Z)=>k0(YJ(1,$,W0(Z))),until:($,Z,J)=>a(xJ(0,$,H1(Z),J)),since:($,Z,J)=>a(xJ(1,$,H1(Z),J)),round:($,Z)=>k0(Oj($,Z)),equals:($,Z)=>Jz($,H1(Z)),toZonedDateTime($,Z){let J=q1(Z);return Q0(yJ($,t(J.timeZone),_0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(yJ($,t(Z))),toLocaleString($,Z,J){let[W,Y]=FO(Z,J,$);return W.format(Y)},toString:($,Z)=>i7(t,B0,$,Z),toJSON:($)=>i7(t,B0,$),valueOf:L$},{from:($)=>k0(H1($)),fromEpochSeconds:($)=>k0(YX($)),fromEpochMilliseconds:($)=>k0(jX($)),fromEpochMicroseconds:($)=>k0(zX($)),fromEpochNanoseconds:($)=>k0(XX($)),compare:($,Z)=>KJ(H1($),H1(Z))}),[f4,MK]=P1("TimeZone",($)=>{let Z=$z($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(U$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(H1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=H1(Z).epochNanoseconds,W=R4(this,K5).getOffsetNanosecondsFor(J);return l$(W)},getPlainDateTimeFor($,Z,J=v){let W=H1(Z).epochNanoseconds,Y=R4(this,K5).getOffsetNanosecondsFor(W);return K0(X0(X$(W,Y),_0(J)))},getInstantFor($,Z,J){let W=U$(Z),Y=v7(J),j=R4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>rX(1,$,Z),getPreviousTransition:({o:$},Z)=>rX(-1,$,Z),equals($,Z){return!!U4(this,t(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=t($);return typeof Z=="string"?new f4(Z):Z}}),AO=WG(Object.keys(BG)),[SO,D$]=P1(x4,cz,S5,{getISOFields:h3,with($,Z,J){return D$(wz(this,lZ(Z),J))},add:($,Z)=>D$(QJ(0,$,W0(Z))),subtract:($,Z)=>D$(QJ(1,$,W0(Z))),until:($,Z,J)=>a(EJ(0,$,V$(Z),J)),since:($,Z,J)=>a(EJ(1,$,V$(Z),J)),round:($,Z)=>D$(Hj($,Z)),equals:($,Z)=>Gz($,V$(Z)),toZonedDateTime:($,Z)=>Q0(JX(t,w0,o,$,Z)),toPlainDateTime:($,Z)=>K0(WX($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=OO(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:L$},{from:($,Z)=>D$(V$($,Z)),compare:($,Z)=>V4(V$($),V$(Z))}),[bO,O$,EO]=P1(yZ,q(hz,_0),{...m3,...TO},{getISOFields:h3,getCalendar:g3,with($,Z,J){return O$(Rz(yO,$,this,lZ(Z),J))},add:($,Z,J)=>O$(GJ(ZG,0,$,W0(Z),J)),subtract:($,Z,J)=>O$(GJ(ZG,1,$,W0(Z),J)),until:($,Z,J)=>a(bJ(JG,0,$,cZ(Z),J)),since:($,Z,J)=>a(bJ(JG,1,$,cZ(Z),J)),equals:($,Z)=>zz($,cZ(Z)),toPlainDate($,Z){return Y0($X(p3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=LO(Z,J,$);return W.format(Y)},toString:a7,toJSON:($)=>a7($),valueOf:L$},{from:($,Z)=>O$(cZ($,Z)),compare:($,Z)=>n$(cZ($),cZ(Z))}),[RO,K0]=P1(e$,q(yz,_0),{...m3,...A5,...S5},{getISOFields:h3,getCalendar:g3,with($,Z,J){return K0(bz(p3,$,this,lZ(Z),J))},withCalendar:($,Z)=>K0(M4($,_0(Z))),withPlainDate:($,Z)=>K0(FX($,w0(Z))),withPlainTime:($,Z)=>K0(BX($,I5(Z))),add:($,Z,J)=>K0(zJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>K0(zJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(AJ(T1,0,$,U$(Z),J)),since:($,Z,J)=>a(AJ(T1,1,$,U$(Z),J)),round:($,Z)=>K0(Mj($,Z)),equals:($,Z)=>Yz($,U$(Z)),toZonedDateTime:($,Z,J)=>Q0(sz(o,$,t(Z),J)),toPlainDate:($)=>Y0(G0($)),toPlainTime:($)=>D$(z1($)),toPlainYearMonth($){return O$(nz(q4,$,this))},toPlainMonthDay($){return uZ(oz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=UO(Z,J,$);return W.format(Y)},toString:n7,toJSON:($)=>n7($),valueOf:L$},{from:($,Z)=>K0(U$($,Z)),compare:($,Z)=>IJ(U$($),U$(Z))}),[kO,Y0,FG]=P1(r$,q(mz,_0),{...m3,...A5},{getISOFields:h3,getCalendar:g3,with($,Z,J){return Y0(Ez(p3,$,this,lZ(Z),J))},withCalendar:($,Z)=>Y0(M4($,_0(Z))),add:($,Z,J)=>Y0(XJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(XJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(SJ(T1,0,$,w0(Z),J)),since:($,Z,J)=>a(SJ(T1,1,$,w0(Z),J)),equals:($,Z)=>jz($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof f4?{timeZone:Z}:Z;return Q0(az(t,V$,o,$,J))},toPlainDateTime:($,Z)=>K0(tz($,I5(Z))),toPlainYearMonth($){return O$(rz(q4,$,this))},toPlainMonthDay($){return uZ(ez(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=DO(Z,J,$);return W.format(Y)},toString:o7,toJSON:($)=>o7($),valueOf:L$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>n$(w0($),w0(Z))}),b5={fields($,Z,J){return[...Z.call($,J)]}},VG=Object.assign({dateFromFields($,Z,J,W){return FG(Z.call($,Object.assign(Object.create(null),J),W))}},b5),UG=Object.assign({yearMonthFromFields($,Z,J,W){return EO(Z.call($,Object.assign(Object.create(null),J),W))}},b5),DG=Object.assign({monthDayFromFields($,Z,J,W){return IO(Z.call($,Object.assign(Object.create(null),J),W))}},b5),E5={mergeFields($,Z,J,W){return q1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},wO=Object.assign({},VG,E5),fO=Object.assign({},UG,E5),qO=Object.assign({},DG,E5),R5={dateAdd($,Z,J,W,Y){return FG(Z.call($,Y0(G0(J,$)),a(e(W)),Y))}},OG=Object.assign({},R5,{dateUntil($,Z,J,W,Y,j){return pO(Z.call($,Y0(G0(J,$)),Y0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:R3[Y]})))}}),vO=Object.assign({},R5,{day:jG}),gO=Object.assign({},OG,{day:jG}),q4=N1(UG),v4=N1(VG),g4=N1(DG),yO=N1(fO),p3=N1(wO),mO=N1(qO),ZZ=N1(R5),T1=N1(OG),ZG=N1(vO),JG=N1(gO),[hO,a,pO]=P1(A4,dz,{...KO,blank:qj},{with:($,Z)=>a(fz($,Z)),negated:($)=>a(X4($)),abs:($)=>a(fj($)),add:($,Z,J)=>a(DJ(v3,T1,o,0,$,W0(Z),J)),subtract:($,Z,J)=>a(DJ(v3,T1,o,1,$,W0(Z),J)),round:($,Z)=>a(wj(v3,T1,o,$,Z)),total:($,Z)=>Dj(v3,T1,o,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:L$},{from:($)=>a(W0($)),compare:($,Z,J)=>Zz(v3,ZZ,o,W0($),W0(Z),J)}),LG={toString:($)=>$.id,toJSON:($)=>$.id,...HO,dateAdd:({id:$,o:Z},J,W,Y)=>Y0(G0(Z.dateAdd(w0(J),W0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>a(e($.dateUntil(w0(Z),w0(J),jj(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(wJ(Z,J,W,hY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>O$(fJ(Z,J,W,yY($))),monthDayFromFields:({id:$,o:Z},J,W)=>uZ(qJ(Z,0,J,W,mY($))),fields({o:$},Z){let J=new Set(X1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(uJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(I7(A7(Z)),I7(A7(J)))},[k5]=P1("Calendar",($)=>{let Z=Lz($);return{branding:"Calendar",id:Z,o:hZ(Z)}},{id:($)=>$.id},LG,{from($){let Z=_0($);return typeof Z=="string"?new k5(Z):Z}}),cO=WG(Object.keys(LG).slice(4)),[dO,Q0]=P1(h1,q(gz,_0,t),{...QG,...m3,...eX(A5),...eX(S5),offset:($)=>l$(N5($).offsetNanoseconds),offsetNanoseconds:($)=>N5($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Tj(o,$)},{getISOFields:($)=>Rj(B0,$),getCalendar:g3,getTimeZone:({timeZone:$})=>typeof $=="string"?new f4($):$,with($,Z,J){return Q0(Sz(p3,o,$,this,lZ(Z),J))},withCalendar:($,Z)=>Q0(M4($,_0(Z))),withTimeZone:($,Z)=>Q0(VX($,t(Z))),withPlainDate:($,Z)=>Q0(QX(o,$,w0(Z))),withPlainTime:($,Z)=>Q0(GX(o,$,I5(Z))),add:($,Z,J)=>Q0(jJ(ZZ,o,0,$,W0(Z),J)),subtract:($,Z,J)=>Q0(jJ(ZZ,o,1,$,W0(Z),J)),until:($,Z,J)=>a(e(CJ(T1,o,0,$,dZ(Z),J))),since:($,Z,J)=>a(e(CJ(T1,o,1,$,dZ(Z),J))),round:($,Z)=>Q0(Lj(o,$,Z)),startOfDay:($)=>Q0(Pj(o,$)),equals:($,Z)=>Wz($,dZ(Z)),toInstant:($)=>k0(uz($)),toPlainDateTime:($)=>K0(mJ(B0,$)),toPlainDate:($)=>Y0(hJ(B0,$)),toPlainTime:($)=>D$(pJ(B0,$)),toPlainYearMonth($){return O$(lz(q4,$,this))},toPlainMonthDay($){return uZ(iz(g4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=VO(Z,J,$);return W.format(Y)},toString:($,Z)=>s7(B0,$,Z),toJSON:($)=>s7(B0,$),valueOf:L$},{from:($,Z)=>Q0(dZ($,Z)),compare:($,Z)=>_J(dZ($),dZ(Z))}),uO=Object.defineProperties({},{...h6("Temporal.Now"),...c$({timeZoneId:()=>y1(),instant:()=>k0(M0(S3())),zonedDateTime:($,Z=y1())=>Q0(N0(S3(),t(Z),_0($))),zonedDateTimeISO:($=y1())=>Q0(N0(S3(),t($),v)),plainDateTime:($,Z=y1())=>K0(X0(vZ(B0(t(Z))),_0($))),plainDateTimeISO:($=y1())=>K0(X0(vZ(B0(t($))),v)),plainDate:($,Z=y1())=>Y0(G0(vZ(B0(t(Z))),_0($))),plainDateISO:($=y1())=>Y0(G0(vZ(B0(t($))),v)),plainTimeISO:($=y1())=>D$(z1(vZ(B0(t($)))))})}),iZ=Object.defineProperties({},{...h6("Temporal"),...c$({PlainYearMonth:bO,PlainMonthDay:_O,PlainDate:kO,PlainTime:SO,PlainDateTime:RO,ZonedDateTime:dO,Instant:xO,Calendar:k5,TimeZone:f4,Duration:hO,Now:uO})}),lO=zO(),w5=new WeakMap,iO=Object.defineProperties(Object.create(Intl),c$({DateTimeFormat:lO}));var y4="x-gemi-socket";var _K="gemi.v1",MG="/__gemi/socket",IK=/^[A-Za-z0-9_-]{1,32}$/,xK={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function bK($){return $}function HG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:MG,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as sO,randomBytes as nO}from"crypto";function oO($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(sO("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var aO="__control",f5=250,tO=1e4,rO=15000;class q5{config;prefix;controlChannel;instanceId=nO(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??oO(),this.controlChannel=this.prefix+aO,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=c3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),rO,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${TG(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(tO,f5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(f5,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;c3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${TG(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??eO(Math.min(Z,f5));await c3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await c3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await c3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function c3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function eO($){return new Promise((Z)=>setTimeout(Z,$))}function TG($){return $ instanceof Error?$.message:String($)}import{createHmac as $L,hkdfSync as ZL,randomBytes as PG}from"crypto";function NG($){return $L("sha256",JL()).update($).digest("base64url").slice(0,22)}var m4=null;function JL(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from(ZL("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):PG(32);return m4={secret:$,key:Z},Z}function fK(){return PG(16).toString("base64url")}var WL=/^[A-Za-z0-9_-]{8,64}$/;function v5($){return typeof $==="string"&&WL.test($)}function KG($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class IG extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=M$(HG(),$),this.driver=zL(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new d3(this,h4($,Z[0]),null)}toUser($){return new d3(this,{topic:DZ($),pattern:U0},null)}toOthers($){return new xG(this,jL($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(h4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){p2(Z);let Y;try{Y=KG($.topic,Z,J,W?NG(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){g5(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=YL($);g5(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new IG(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class d3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class xG{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new d3(this.manager,h4($,Z[0]),this.except)}toUser($){return new d3(this.manager,{topic:DZ($),pattern:U0},this.except)}}function h4($,Z){if(h2($))return{topic:A8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:Q3($,Z??{}),pattern:$};if($===U0)throw new i('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:A8($)}}function YL($){if($&&typeof $==="object"&&"user"in $)return{user:DZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:h4($.channel,$.params).topic};throw new i("Broadcast.revoke takes { user } or { channel }.")}function jL($){if($===null||$===void 0)return null;if(typeof $==="string")return v5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(y4);return v5(J)?J:null}function zL($,Z){let J=$.driver;if(J===void 0||J==="memory")return new _G;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new q5({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class y5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class XL{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1;clientFor($){return Promise.resolve(void 0)}async isAvailable($){return await this.clientFor($)!==null}async redirectUriFor($){return(await this.clientFor($))?.redirectUri}}import{createHash as m5,createHmac as GL,randomBytes as CG,timingSafeEqual as bG}from"crypto";var l3=600,p4="gemi_oauth",QL=`__Host-${p4}`;function sZ($,Z=p4){if(Z===p4)return $?QL:p4;return $?`__Host-${Z}`:Z}function u3($){return $.toString("base64url")}function EG($){return GL("sha256",TZ()).update(`gemi-oauth-state:${$}`).digest()}function AG($,Z){let J=m5("sha256").update($).digest(),W=m5("sha256").update(Z).digest();return bG(J,W)&&$.length===Z.length}function c4($,Z=Date.now(),J={}){let W=u3(CG(32)),Y=u3(CG(32)),j=BL(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+l3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{},...J.redirectUri!==void 0?{redirectUri:J.redirectUri}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:FL(z)}}function BL($){return u3(m5("sha256").update($).digest())}function FL($){let Z=u3(Buffer.from(JSON.stringify($)));return`${Z}.${u3(EG(Z))}`}function VL($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=EG(J);if(W.length!==Y.length||!bG(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string"||j.redirectUri!==void 0&&typeof j.redirectUri!=="string")return null;return j}catch{return null}}var H$=new Map,SG=1e4;function UL($,Z,J){if(H$.size>=SG){for(let[W,Y]of H$)if(Y<=J)H$.delete(W);while(H$.size>=SG){let W=H$.keys().next().value;if(W===void 0)break;H$.delete(W)}}H$.set($,Z)}function d4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=VL($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=AG(J.state,$.returnedState),Y=AG(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(H$.has(J.state))return{ok:!1,reason:"invalid_state"};return UL(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var h5=new WeakMap;function OL($){let Z=h5.get($);if(!Z)Z=$(DL(32).toString("hex")),h5.set($,Z),Z.catch(()=>h5.delete($));return Z}async function u4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await OL($.hashPassword))}catch{}return!1}async function JZ($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class c5 extends Error{}function p5($){return typeof $==="string"&&$!==""?$:null}function RG($){return q$($)}var LL=256;function kG($){return typeof $==="string"&&$!==""&&$.length<=LL?$:null}function wG($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function vG($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function fG($){let Z=$.cookies.get(i4);if(!Z)return null;vG($);try{return U1(decodeURIComponent(Z),"")||null}catch{return null}}class d5 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class gG extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class yG extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new q0("Not found",{status:404})}async function p1($,Z){if(!await R1(H(E).config[$],Z))l4()}async function i3($,Z,J,W){let{config:Y}=H(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await v$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function qG($,Z,J){let{config:W}=H(E);await i3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function nZ($){return await R1(H(E).config.verifyEmail,$)}class $0 extends F3{async me(){let $=await f0.user();if(!$)throw new i8;return $}async verifyEmail($=new A){await p1("password",$);let Z=await $.input(),{userProvider:J}=H(E),W=p5(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new A){let Z=H(E),{userProvider:J}=Z;if(!await R1(Z.config.magicLink,$)&&!await R1(Z.config.emailCode.enabled,$))l4();let W=p5($.search.get("token")),Y=null;try{Y=q$(decodeURIComponent($.search.get("email")??""))}catch{}if(await v$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp},Z.config.rateLimitKey),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,H(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await p1("magicLink",$);let Z=H(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=kG(Y);if(await v$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new u({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new u({pin:["Too many attempts"]});if(X.status!=="ok")throw new u({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new A){let Z=H(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new A){let Z=H(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new d5){await p1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(E);await qG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await nZ($)),X=typeof W==="string"&&await u4(j.config,W,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await JZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signIn($=new d5){await p1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(E);await qG(J,W,$);let z=await j.userProvider.findUserByEmailAddress(Y,await nZ($)),X=typeof W==="string"&&await u4(j.config,W,z?.password);if(!z||!X)throw new u({invalid_credentials:["Invalid credentials"]});let G=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",G.token,H(E).accessTokenCookieOptions($,G.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await JZ(j.config,{session:G,user:z,isNewUser:!1,method:"password",req:$});let{password:Q,...F}=z;return F}async signUp(){let $=H(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await p1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:wG(Y.toJSON()),req:W},F=RG(j);if(await i3("signUp",F,W),!F)throw new u({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new u({password:["Invalid password"]});if(G!=null&&typeof G!=="string")throw new u({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(F,!1))throw new u({email:["Email address already exists"]});let B=await J.hashPassword(z),U=H(d).detectLocale(W),O;if(G)O=await Z.findInvitation(G,F);let D,L="";if(O)D=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let M=await Z.createUser({email:F,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:O.organizationId,userId:M.id,organizationRole:O.role}),await J.onUserCreated(M,Q),M});else{if(L=await J.generateEmailVerificationToken(F),typeof J.verifyEmail==="function"&&!await nZ(W))L="";D=await Z.transaction(async()=>{let M=await Z.createUser({email:F,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(M,Q),M})}return await J.onSignUp(D,L,W.search.toJSON(),{req:W}),D}async signOut($=new A){let Z=S$($),J=H(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(E).accessTokenCookieOptions($,new Date(0))),H(E).cookieDomain($))$.ctx().setCookie("access_token","",{...H(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)ML(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new gG){await p1("password",$);let Z=await $.input(),J=RG(Z.get("email"));if(await i3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=H(E),j=await W.findUserByEmailAddress(J,await nZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new yG){await p1("password",$);let{userProvider:Z,config:J}=H(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=p5(j);await i3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new u({token:["Invalid token"]});if(iZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(iZ.Now.instant()).sign>=0)throw new u({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let Q=await Z.findUserByEmailAddress(X.user.email,await nZ($));if(!Q)throw new u({email:["User not found"]});let F=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:F}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new A){await p1("password",$);let{userProvider:Z,config:J}=H(E),W=await f0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await i3("signIn",q$(W?.email),$),typeof z!=="string")throw new u({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await nZ($));if(!(typeof j==="string"&&await u4(J,j,X?.password)))throw new u({oldPassword:["Incorrect password"]});let Q=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:Q}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new A){let{provider:Z}=$.params,J=H(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await NZ(J,Z,$);if(!Y){if(W)throw new q0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=OZ($.rawRequest),z=U1($.search.get(l0),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else vG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:F}=c4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(sZ(j),F,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:l3}),{destination:await Y.getRedirectUrl($,{state:G,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new A){let{provider:Z}=$.params,J=H(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await NZ(Y.oauthProviders,Z,$);if(j&&!z)throw new q0("Not found",{status:404});let X=OZ($.rawRequest),G=sZ(X),Q=$.cookies.get(G);if(Q!==void 0&&Q!==null)$.ctx().setCookie(G,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let F=$.search.get("error");if(F)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");let V=d4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(V.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let x=await z.redirectUriFor($);if(x!==void 0&&x!==V.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let B;try{B=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(x){if(x instanceof y5)return this.oauthFailure($,x.code);return console.error("Authentication error: OAuth provider callback failed",x),this.oauthFailure($,"provider_error")}let{name:U,username:O,providerId:D,emailVerified:L}=B??{},M=typeof B?.email==="string"?B.email:void 0,T=M?K6(M):null,P=D?await W.findUserBySocialAccount(Z,D):null,K="signin",R=!P&&!T&&!M&&!!D&&z.createUsersWithoutEmail===!0;if(!P&&R){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{P=await this.createOAuthUserWithoutEmail({provider:Z,providerId:D,name:U,username:O,locale:H(d).detectLocale($),req:$}),K="signup"}catch(x){let f=await W.findUserBySocialAccount(Z,D);if(!f)throw x;P=f}}if(!P){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,M?"invalid_email":D?"missing_email":"no_identity");if(L===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let x=H(d).detectLocale($);try{let f=await this.linkOAuthAccount({provider:Z,providerId:D,email:T,rawEmail:M,name:U,username:O,locale:x,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(f==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(f==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(f)P=f.user,K=f.action}catch(f){let _=D?await W.findUserBySocialAccount(Z,D):null;if(!_)throw f;P=_}if(!P)return this.oauthFailure($,"account_conflict")}let C=await J.createOrUpdateSessionV2({email:P.email,id:P.id});if($.ctx().setCookie("access_token",C.token,H(E).accessTokenCookieOptions($,C.expiresAt)),K==="signup")await Y.onSignUp(P,"",$.search.toJSON(),{req:$});else await Y.onSignIn(P,$.search.toJSON(),{req:$});await JZ(J.config,{session:C,user:P,isNewUser:K==="signup",method:"oauth",req:$});let S=fG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?U1(Y.oauthCompleteProfilePath,""):"";if(w&&!P.email){let x=new URL(w,"http://gemi.invalid");x.searchParams.set(l0,S),S=`${x.pathname}${x.search}${x.hash}`}return{session:C,redirectTo:S}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=H(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=fG($),W=H(E).config.oauthFailurePath;if(W){let Y=U1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);S1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:G,config:Q}=H(E),F=(O)=>({provider:Z,userId:O,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!V&&B&&B!==W)V=await G.findUserByEmailAddress(B,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let O=await G.findSocialAccounts(V.id,Z);if(O.some((L)=>L.providerId===J))return{user:V,action:"signin"};if(O.some((L)=>L.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let D=O[0];if(D){if(!await G.claimSocialAccount(D,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(F(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let O=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(F(O.id));return await Q.onUserCreated(O,{method:"oauth",input:{},req:$.req}),O}),action:"signup"}}async createMagicLinkToken($=new A){await p1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=H(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await v$("request",J,$,j,W.config.rateLimitKey),!J)return{email:null};let{user:z,pin:X,token:G}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:G,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new A){let Z=H(E),J=Z.config.emailCode;if(!await R1(J.enabled,$))l4();let W=await $.input(),Y=K6(W.get("email"));if(await v$("request",Y,$,J.requestLimit,Z.config.rateLimitKey),!Y)throw new u({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new A){let Z=H(E),{userProvider:J,config:W}=Z;if(!await R1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=K6(j),Q=kG(z);if(await v$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new u({code:["invalid_code"]});let F=null;if(!n9(Q,W.emailCode)){let D=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(D.status==="too_many_attempts")throw new u({code:["too_many_attempts"]});if(D.status!=="ok")throw new u({code:["invalid_code"]});F=D.row}let V=async()=>F?await Z.claimOneTimeCode(G,F.id):!0,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await V())throw new u({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let D=H(d).detectLocale($);try{B=await J.transaction(async()=>{if(!await V())throw new c5;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:D});return await W.onUserCreated(L,{method:"email-code",input:wG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof c5)throw new u({code:["invalid_code"]});throw L}}else throw await V(),new u({code:["invalid_code"]});let O=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",O.token,H(E).accessTokenCookieOptions($,O.expiresAt)),await W.onSignIn(O,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:O,isNewUser:U,method:"email-code",req:$}),{session:O,isNewUser:U}}}function ML($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var mG="gemi_oauth_connection";class s4 extends F3{async connect($=new A){let Z=String($.params.provider??""),W=H(s3).providers[Z],Y=await f0.user(),j=U1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=OZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=c4(hG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(sZ(z,mG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:l3}),S1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:pG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new A){let Z=String($.params.provider??""),J=H(s3),W=await f0.user(),Y=OZ($.rawRequest),j=sZ(Y,mG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=d4({provider:hG(Z),cookieValue:z,returnedState:$.search.get("state")}),G="payload"in X?X.payload.returnTo??"":"",Q=J.providers[Z];if(!Q)return this.finish(G,Z,"unknown_provider");let F=$.search.get("error");if(F)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(F)?F:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(G,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(G,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:pG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await H(E).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof cG)return console.error(`OAuth connection to ${Z} failed: ${B.message}`),this.finish(G,Z,B.providerError??B.code);throw B}return this.finish(G,Z)}finish($,Z,J){let W=$||U1(H(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw S1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function hG($){return`connection:${$}`}function pG($,Z,J){if(J)return J;return`${WZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function dG($){return $.magicLink!==!1||Z7($.emailCode?.enabled)}function uG($){return Object.keys($.oauthProviders??{}).length>0}function lG($={}){let Z=[];if(dG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Z7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(uG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class iG extends b1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([U6,"auth"])}}function sG($={}){let Z=dG($),J=uG($);class W extends b1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[$0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[$0,"oauthCallback"])}}return class extends b1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[$0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":iG}}}class u5 extends x0{middlewares=["cache:private"];routes={"/sign-in":this.post($0,"signIn"),"/sign-in-v2":this.post($0,"signInV2"),"/sign-up":this.post($0,"signUp"),"/sign-out":this.post($0,"signOut"),"/forgot-password":this.post($0,"forgotPassword"),"/reset-password":this.post($0,"resetPassword"),"/change-password":this.post($0,"changePassword"),"/verify-email":this.post($0,"verifyEmail"),"/me":this.get($0,"me").middleware(["auth"]),"/magic-link":this.post($0,"createMagicLinkToken"),"/sign-in-with-pin":this.post($0,"signInWithPin"),"/sign-in-with-pin-v2":this.post($0,"signInWithPinV2"),"/email-code":this.post($0,"requestEmailCode"),"/email-code/verify":this.post($0,"verifyEmailCode")}}class l5 extends x0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new A().params.locale;return await H(d).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new A,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(d),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class i5{}class s5 extends i5{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await n4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function s_($){return $}function nG(){return{driver:new s5,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var HL=new Set([301,302,303,307,308]),TL="/api/__gemi__/services/image/";async function aG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=oG($,Y);try{for(let z=0;;z++){let X=await PL(j,Z,W),G=X.headers.get("location");if(HL.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=oG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw KL(z,W)}}function oG($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function PL($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(TL))throw new F0(403,"This image source is not allowed");if(NL($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return E1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return E1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function NL($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function KL($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof O6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class n5 extends x0{routes={"/resize":this.file(async()=>{let $=new A,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return tG(400,"url query parameter is required");let X=H(rG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=WZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let F;try{F=await aG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof F0)return tG(U.status,U.message);throw U}let V=await X.resize(F.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(F.cacheControl)B.set("Cache-Control",F.cacheControl);return new Response(new Uint8Array(V),{headers:B})})}}function tG($,Z){return Response.json({error:Z},{status:$})}class rG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=nG();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class o5 extends x0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(eG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function GI($){return $}function $Q(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function ZQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,assetCors:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function _L($){return"run"in $}function IL($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function xL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function CL($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function AL($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function JQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function SL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function a5($,Z="",J=[],W){let Y={},j=(X)=>{return(X.corsPolicy===void 0?W:X.corsPolicy)||void 0};function z(X,G,Q,F,V,B,U){let O=X==="/"?"":X,D=Z==="/"?"":Z,L=SL((`${D}${O}`===""?"/":`${D}${O}`).replaceAll("//","/"));if(!Y[L])Y[L]={};Y[L][G.toUpperCase()]={exec:Q,middleware:[...J,...F],...V?{source:V}:{},...B?{bodyLimitDefault:B}:{},...U?{cors:U}:{}},Y[L].OPTIONS={exec:()=>{let T=new A().ctx().headers;return new Response(null,{headers:T,status:204})},middleware:[]}}for(let[X,G]of Object.entries($)){if(AL(G)){let Q=G;for(let F of["GET","POST","PUT","DELETE"])z(X,F,Q.run.bind(Q),Q.middlewares,void 0,void 0,j(Q));continue}if(_L(G)){let Q=G,F=Q.method,V=Q.middlewares,B=Q.run.bind(Q),U=j(Q);if(z(X,F,B,V,Q.source,Q.__internal_bodyLimitDefault,U),JQ(G))z(X,"HEAD",B,V,Q.source,void 0,U)}if(IL(G))for(let[Q,F]of Object.entries(G)){let V=F,B=V.middlewares,U=V.run.bind(V),O=j(V);if(z(X,Q,U,B,V.source,V.__internal_bodyLimitDefault,O),Q==="get"&&JQ(V))z(X,"HEAD",U,B,V.source,void 0,O)}if(CL(G)){let Q=new G,F=`the router at "${Z}${X}"`;if(Q.cors===!0)throw Error(`CORS policy on ${F}: \`cors = true\` is not a policy; write one such as { origins: "*" }.`);let V=Q.cors===void 0?W:Q.cors===!1?void 0:G3(Q.cors,F),B=a5(Q.routes,`${Z}${X}`,[...J,...Q.middlewares],V);for(let[U,O]of Object.entries(B)){let D=U.replaceAll("//","/");Y[D]={...Y[D],...O}}}if(xL(G)){let{first:Q,second:F}=G;for(let[V,B]of Object.entries(Q)){let U=B.middlewares,O=B.run.bind(B),[D,...L]=X.split("/").reverse();if(!D.startsWith(":"))throw Error("Resource route must end with a dynamic segment");z(L.reverse().join("/"),V,O,U,B.source,void 0,j(B))}for(let[V,B]of Object.entries(F)){let U=B.middlewares,O=B.run.bind(B);z(X,V,O,U,B.source,void 0,j(B))}}}return Object.fromEntries(Object.entries(Y).sort(([X],[G])=>{let Q=X.split("/").length+X.split(":").length,F=G.split("/").length+G.split(":").length;return Q-F}))}var bL=Object.defineProperty,I=($,Z)=>bL($,"name",{value:Z,configurable:!0}),tZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};I(tZ,"Part");var EL=/[$_\p{ID_Start}]/u,RL=/[$_\u200C\u200D\p{ID_Continue}]/u,r5=".*";function WQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}I(WQ,"isASCII");function ZW($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=I(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let G=$.substr(X,1);if(X===W+1&&EL.test(G)||X!==W+1&&RL.test(G)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",G=W+1,Q=!1;if($[G]==="?"){j(`Pattern cannot start with "?" at ${G}`);continue}for(;G<$.length;){if(!WQ($[G],!1)){j(`Invalid character '${$[G]}' at ${G}.`),Q=!0;break}if($[G]==="\\"){X+=$[G++]+$[G++];continue}if($[G]===")"){if(z--,z===0){G++;break}}else if($[G]==="("&&(z++,$[G+1]!=="?")){j(`Capturing groups are not allowed at ${G}`),Q=!0;break}X+=$[G++]}if(Q)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=G;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}I(ZW,"lexer");function JW($,Z={}){let J=ZW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${d0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",G=new Set,Q=I((P)=>{if(z<J.length&&J[z].type===P)return J[z++].value},"tryConsume"),F=I(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),V=I((P)=>{let K=Q(P);if(K!==void 0)return K;let{type:R,index:C}=J[z];throw TypeError(`Unexpected ${R} at ${C}, expected ${P}`)},"mustConsume"),B=I(()=>{let P="",K;for(;K=Q("CHAR")??Q("ESCAPED_CHAR");)P+=K;return P},"consumeText"),U=I((P)=>P,"DefaultEncodePart"),O=Z.encodePart||U,D="",L=I((P)=>{D+=P},"appendToPendingFixedValue"),M=I(()=>{D.length&&(Y.push(new tZ(3,"","",O(D),"",3)),D="")},"maybeAddPartFromPendingFixedValue"),T=I((P,K,R,C,S)=>{let w=3;switch(S){case"?":w=1;break;case"*":w=0;break;case"+":w=2;break}if(!K&&!R&&w===3){L(P);return}if(M(),!K&&!R){if(!P)return;Y.push(new tZ(3,"","",O(P),"",w));return}let x;R?R==="*"?x=r5:x=R:x=W;let f=2;x===W?(f=1,x=""):x===r5&&(f=0,x="");let _;if(K?_=K:R&&(_=j++),G.has(_))throw TypeError(`Duplicate name '${_}'.`);G.add(_),Y.push(new tZ(f,_,O(P),x,O(C),w))},"addPart");for(;z<J.length;){let P=Q("CHAR"),K=Q("NAME"),R=Q("REGEX");if(!K&&!R&&(R=Q("ASTERISK")),K||R){let S=P??"";Z.prefixes.indexOf(S)===-1&&(L(S),S=""),M();let w=F();T(S,K,R,"",w);continue}let C=P??Q("ESCAPED_CHAR");if(C){L(C);continue}if(Q("OPEN")){let S=B(),w=Q("NAME"),x=Q("REGEX");!w&&!x&&(x=Q("ASTERISK"));let f=B();V("CLOSE");let _=F();T(S,w,x,f,_);continue}M(),V("END")}return Y}I(JW,"parse");function d0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(d0,"escapeString");function e5($){return $&&$.ignoreCase?"ui":"u"}I(e5,"flags");function YQ($,Z,J){return WW(JW($,J),Z,J)}I(YQ,"stringToRegexp");function YZ($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}I(YZ,"modifierToString");function WW($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=d0(X.value):W+=`(?:${d0(X.value)})${YZ(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${d0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=r5),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${Q})${YZ(X.modifier)}`:W+=`((?:${Q})${YZ(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${d0(X.prefix)}(${Q})${d0(X.suffix)})`,W+=YZ(X.modifier);continue}W+=`(?:${d0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=d0(X.suffix),W+=d0(X.prefix),W+=`(?:${Q}))*)${d0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${d0(J.endsWith)}]|$`,j=`[${d0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,e5(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,e5(J))}I(WW,"partsToRegexp");var P$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},kL={delimiter:".",prefixes:"",sensitive:!0,strict:!0},wL={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function jQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}I(jQ,"isAbsolutePathname");function YW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}I(YW,"maybeStripPrefix");function zQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}I(zQ,"maybeStripSuffix");function jW($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}I(jW,"treatAsIPv6Hostname");var XQ=["ftp","file","http","https","ws","wss"];function zW($){if(!$)return!0;for(let Z of XQ)if($.test(Z))return!0;return!1}I(zW,"isSpecialScheme");function GQ($,Z){if($=YW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}I(GQ,"canonicalizeHash");function QQ($,Z){if($=YW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}I(QQ,"canonicalizeSearch");function BQ($,Z){return Z||$===""?$:jW($)?QW($):GW($)}I(BQ,"canonicalizeHostname");function FQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}I(FQ,"canonicalizePassword");function VQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}I(VQ,"canonicalizeUsername");function UQ($,Z,J){if(J||$==="")return $;if(Z&&!XQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}I(UQ,"canonicalizePathname");function DQ($,Z,J){return XW(Z)===$&&($=""),J||$===""?$:BW($)}I(DQ,"canonicalizePort");function OQ($,Z){return $=zQ($,":"),Z||$===""?$:o4($)}I(OQ,"canonicalizeProtocol");function XW($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}I(XW,"defaultPortForProtocol");function o4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}I(o4,"protocolEncodeCallback");function LQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}I(LQ,"usernameEncodeCallback");function MQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}I(MQ,"passwordEncodeCallback");function GW($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}I(GW,"hostnameEncodeCallback");function QW($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}I(QW,"ipv6HostnameEncodeCallback");function BW($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}I(BW,"portEncodeCallback");function HQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}I(HQ,"standardURLPathnameEncodeCallback");function TQ($){return $===""?$:new URL(`data:${$}`).pathname}I(TQ,"pathURLPathnameEncodeCallback");function PQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}I(PQ,"searchEncodeCallback");function NQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}I(NQ,"hashEncodeCallback");var KQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#Q=0;#X=0;#U=0;#D=0;#O=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=ZW(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#T(),this.#B()?this.#J(9,1):this.#F()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#V(5);continue}this.#J(10,0);break}if(this.#U>0)if(this.#C())this.#U-=1;else continue;if(this.#x()){this.#U+=1;continue}switch(this.#X){case 0:this.#P()&&this.#V(1);break;case 1:if(this.#P()){this.#b();let $=7,Z=1;this.#K()?($=2,Z=3):this.#O&&($=2),this.#J($,Z)}break;case 2:this.#M()?this.#V(3):(this.#H()||this.#F()||this.#B())&&this.#V(5);break;case 3:this.#_()?this.#J(4,1):this.#M()&&this.#J(5,1);break;case 4:this.#M()&&this.#J(5,1);break;case 5:this.#A()?this.#D+=1:this.#S()&&(this.#D-=1),this.#I()&&!this.#D?this.#J(6,1):this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 7:this.#F()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 8:this.#B()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#G();break;case 2:break;case 3:this.#Z.username=this.#G();break;case 4:this.#Z.password=this.#G();break;case 5:this.#Z.hostname=this.#G();break;case 6:this.#Z.port=this.#G();break;case 7:this.#Z.pathname=this.#G();break;case 8:this.#Z.search=this.#G();break;case 9:this.#Z.hash=this.#G();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#O?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#N($,Z)}#N($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#Y=0}#T(){this.#$=this.#Q,this.#Y=0}#V($){this.#T(),this.#X=$}#L($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#L($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#K(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#M(){return this.#z(this.#$,"@")}#_(){return this.#z(this.#$,":")}#I(){return this.#z(this.#$,":")}#H(){return this.#z(this.#$,"/")}#F(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#L(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#B(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#G(){let $=this.#W[this.#$],Z=this.#L(this.#Q).index;return this.#j.substring(Z,$.index)}#b(){let $={};Object.assign($,P$),$.encodePart=o4;let Z=YQ(this.#G(),void 0,$);this.#O=zW(Z)}};I(KQ,"Parser");var t5=["protocol","username","password","hostname","port","pathname","search","hash"],T$="*";function $W($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}I($W,"extractValues");function K1($,Z){return Z?aZ($):$}I(K1,"processBaseURLString");function oZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=K1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=K1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=K1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=K1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=K1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=K1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=K1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=K1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=OQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=VQ(Z.username,J)),typeof Z.password=="string"&&($.password=FQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=BQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=DQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!jQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=K1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=UQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=QQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=GQ(Z.hash,J)),$}I(oZ,"applyInit");function aZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}I(aZ,"escapePatternString");function _Q($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(_Q,"escapeRegexpString");function IQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${_Q(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=aZ(X.value);continue}j+=`{${aZ(X.value)}}${YZ(X.modifier)}`;continue}let G=X.hasCustomName(),Q=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),F=z>0?$[z-1]:null,V=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&V&&!V.prefix.length&&!V.suffix.length)if(V.type===3){let B=V.value.length>0?V.value[0]:"";Q=Y.test(B)}else Q=!V.hasCustomName();if(!Q&&!X.prefix.length&&F&&F.type===3){let B=F.value[F.value.length-1];Q=Z.prefixes.includes(B)}Q&&(j+="{"),j+=aZ(X.prefix),G&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?G||(j+=`(${W})`):X.type===0&&(!G&&(!F||F.type===3||F.modifier!==3||Q||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&G&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=aZ(X.suffix),Q&&(j+="}"),X.modifier!==3&&(j+=YZ(X.modifier))}return j}I(IQ,"partsToPattern");var n3=class{#j;#W={};#Z={};#$={};#Y={};#Q=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new KQ($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:T$,protocol:T$,username:T$,password:T$,hostname:T$,port:T$,search:T$,hash:T$};this.#j=oZ(j,$,!0),XW(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of t5){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,P$),X.encodePart=o4;break;case"username":Object.assign(X,P$),X.encodePart=LQ;break;case"password":Object.assign(X,P$),X.encodePart=MQ;break;case"hostname":Object.assign(X,kL),jW(G)?X.encodePart=QW:X.encodePart=GW;break;case"port":Object.assign(X,P$),X.encodePart=BW;break;case"pathname":zW(this.#W.protocol)?(Object.assign(X,wL,Y),X.encodePart=HQ):(Object.assign(X,P$,Y),X.encodePart=TQ);break;case"search":Object.assign(X,P$,Y),X.encodePart=PQ;break;case"hash":Object.assign(X,P$,Y),X.encodePart=NQ;break}try{this.#Y[z]=JW(G,X),this.#W[z]=WW(this.#Y[z],this.#Z[z],X),this.#$[z]=IQ(this.#Y[z],X),this.#Q=this.#Q||this.#Y[z].some((Q)=>Q.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=oZ(J,$,!1):J=oZ(J,$W($,Z),!1)}catch{return!1}let W;for(W of t5)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=oZ(J,$,!1):J=oZ(J,$W($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of t5){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,G]of this.#Z[Y].entries())if(typeof G=="string"||typeof G=="number"){let Q=j[X+1];z[G]=Q}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=I((X,G)=>{for(let Q of["type","modifier","prefix","value","suffix"]){if(X[Q]<G[Q])return-1;if(X[Q]===G[Q])continue;return 1}return 0},"comparePart"),Y=new tZ(3,"","","","",3),j=new tZ(0,"","","","",3),z=I((X,G)=>{let Q=0;for(;Q<Math.min(X.length,G.length);++Q){let F=W(X[Q],G[Q]);if(F)return F}return X.length===G.length?0:W(X[Q]??Y,G[Q]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#Q}};I(n3,"URLPattern");if(!globalThis.URLPattern)globalThis.URLPattern=n3;function a4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function FW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function VW($){let Z=a4($);return Z.length>1?Z.replace(/\/$/,""):Z}function xQ($,Z){return Z.map((J)=>({...J,path:VW(FW($,J.path))}))}function t4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=t4(j.routes);for(let[X,{exec:G,middleware:Q,segments:F,features:V,static:B}]of Object.entries(z)){let U=FW(J,X),O=(D)=>Y.run.call(Y,D,J);Z[a4(U)]={exec:[O,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:VW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...xQ(J,F)],...B?{static:B}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[a4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:VW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=t4(Y.routes);for(let[z,{exec:X,middleware:G,viewPath:Q,segments:F,features:V,static:B}]of Object.entries(j)){let U=FW(J,z);Z[a4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Q,segments:xQ(J,F),...B?{static:B}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var UW="theme";function CQ($){return $==="light"||$==="dark"||$==="system"}function AQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
14
14
  for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
15
15
  if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
16
16
  if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
17
17
  if(!e)return;
18
18
  if(e==='system')e=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
19
- c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}function tZ($,Z){for(let[J,W]of Object.entries($)){let Y=new s3({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}function AQ($,Z){return tZ($,Z)?.route.segments.at(-1)?.viewPath==="FILE"}function SQ($,Z){return Z.endsWith(".json")&&!AQ($,Z)}function bQ($,Z){return Z.endsWith(".og")&&!AQ($,Z)}var jZ={startIndex:0,carriedViews:[]};function EQ($,Z){let J=D0($.path,Z);return J.includes("*")?null:J}function RL($,Z){if(!$)return jZ;if($.search!==Z.search)return jZ;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=EQ(Y,$.params),X=EQ(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return jZ;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function kL($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function RQ($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return jZ;let z;try{z=new URL(W,Y)}catch{return jZ}if(z.origin!==Y)return jZ;let X=tZ(Z,kL(z.pathname,J));if(!X)return jZ;return RL({segments:X.route.segments,params:X.params,search:z.search},j)}var DW="x-gemi-from";import{cloneElement as SM,createElement as c1,Fragment as PB}from"react";import{createElement as kQ,Fragment as wQ}from"react";function fQ($,Z,J){return[kQ(wQ,{key:"preloads"},...$),kQ(wQ,{key:"head"},...Z),J]}function wL($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function r4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=r4(j.routes);for(let[X,G]of Object.entries(z)){let Q=J==="/"?X:`${J}${X}`,F=X==="/"&&J!=="/"?J:Q;Z[F]=[Y,...G]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=r4(Y.routes);for(let[z,X]of Object.entries(j)){let G=J==="/"?z:`${J}${z}`,Q=z==="/"&&J!=="/"?J:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[wL(J),W]))}function e4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)e4(Y[1],j)}function $8($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=$8(j.routes);e4(Z,[Y,z])}else e4(Z,[Y,[]])}else{let Y=new W,j=$8(Y.routes);for(let z of j)e4(Z,z)}return Z}function OW($){let Z=[];for(let[J,W]of $)Z.push(J,...OW(W).flat());return Array.from(new Set(Z))}function qQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class N$ extends h{static getFacadeAccessor(){return d}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??N$.locale(),$.timeZone??N$.timeZone())}static setLocale($=N$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=N.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class LW{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function vQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var fL=50;class rZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}locate($,Z){let J=Z.params??{},W=new URLSearchParams(vQ(Z.search??{}));W.delete("json"),W.sort();let Y=D0($,J),j=W.toString();return{params:J,searchParams:W,path:Y,variantKey:j,key:this.keyFor(Y,j)}}find($,Z={}){return this.entries.get(this.locate($,Z).key)}entriesFor($){return Array.from(this.entries.values()).filter((Z)=>Z.path===$)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let{params:W,searchParams:Y,path:j,variantKey:z,key:X}=this.locate($,Z),G=this.entries.get(X);if(G)return G;let Q;if(J==="render"&&this.renderStartedAt!==null){let U=Math.round(performance.now()-this.renderStartedAt);if(U>fL)Q=U}let F,V=new Promise((U)=>{F=U}),B={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:V,source:J,startedAt:this.elapsed()};return this.entries.set(X,B),this.fetcher($,W,Y).then((U)=>{B.status="resolved",B.data=U},(U)=>{B.status="rejected",B.error=U}).then(()=>{if(B.settledAt=this.elapsed(),this.maybeLogLateDiscovery(B),B.status==="rejected"&&this.failListener)this.failListener(B);if(this.settleListener)this.settleListener(B);else this.settledBacklog.push(B);F()}),B}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class a0 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function eZ(){let $=JSON.stringify({error:t1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function MW(){return{status:403,error:{message:"Forbidden"}}}function n3($){let Z=$3.getStore(),J=N.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[D0(W,Y),j.toString()].filter((V)=>V.length>0).join("?"),G=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),Q=Z8($);if(Q)Z3(G,Q);let F=new A(G,Y);return $3.run(Z,()=>N.run(F,async()=>{let V=J?.locale;if(V&&H(d).isLocaleAware)N.getStore().setLocale(V);try{let B=H(Q1).dispatchers(Q).api,U=await B.runRouteMiddleware(W,F)??await B.getRouteData(W);if(i1(U)){if(!U.ok)throw new a0(D0(W,Y),j.toString(),U.status,U.body);return U.body}if(U instanceof Response){let O=await U.json().catch(()=>null);if(!U.ok)throw new a0(D0(W,Y),j.toString(),U.status,O);return O}return U}catch(B){if(B instanceof a0)throw B;let U=new a0(D0(W,Y),j.toString(),500,{message:B instanceof Error?B.message:String(B)});throw U.cause=B,U}}))}}var qL=new Set(["script","style","template","title"]),vL=/\shidden([\s=/]|$)/i,gL=/"[^"]*"|'[^']*'/g;function yL($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let V=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=V;else Z+=V}if(j===-1)break;if($.startsWith("<!--",j)){let V=$.indexOf("-->",j+4);Y=V===-1?$.length:V+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let G=$.slice(j+1,X);Y=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let F=G.startsWith("/");if(!F&&qL.has(Q)&&!G.endsWith("/")){let V=$.indexOf(`</${Q}`,Y);Y=V===-1?$.length:V;continue}if(Q!=="div")continue;if(F){if(W>0)W-=1}else if(W>0)W+=1;else if(vL.test(G.replace(gL,'""')))W=1}return{shellChars:Z,deferredChars:J}}var mL=1000,hL=64;function pL($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function cL($,Z){if(Z.deferredChars<mL)return null;if(Z.shellChars>=hL)return null;return`[gemi] GET ${$} streams ${pL(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function gQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=cL(J,W);if(!Y)return;Z.add(J),$(Y)}}}function yQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),yL(Z)}}}function mQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(F)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:F})};j=G,z.enqueue(Y.encode(`${JSON.stringify($)}
19
+ c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}function rZ($,Z){for(let[J,W]of Object.entries($)){let Y=new n3({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}function SQ($,Z){return rZ($,Z)?.route.segments.at(-1)?.viewPath==="FILE"}function bQ($,Z){return Z.endsWith(".json")&&!SQ($,Z)}function EQ($,Z){return Z.endsWith(".og")&&!SQ($,Z)}var jZ={startIndex:0,carriedViews:[]};function RQ($,Z){let J=D0($.path,Z);return J.includes("*")?null:J}function fL($,Z){if(!$)return jZ;if($.search!==Z.search)return jZ;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=RQ(Y,$.params),X=RQ(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return jZ;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function qL($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function kQ($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return jZ;let z;try{z=new URL(W,Y)}catch{return jZ}if(z.origin!==Y)return jZ;let X=rZ(Z,qL(z.pathname,J));if(!X)return jZ;return fL({segments:X.route.segments,params:X.params,search:z.search},j)}var DW="x-gemi-from";import{cloneElement as RM,createElement as c1,Fragment as NB}from"react";import{createElement as wQ,Fragment as fQ}from"react";function qQ($,Z,J){return[wQ(fQ,{key:"preloads"},...$),wQ(fQ,{key:"head"},...Z),J]}function vL($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function r4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=r4(j.routes);for(let[X,G]of Object.entries(z)){let Q=J==="/"?X:`${J}${X}`,F=X==="/"&&J!=="/"?J:Q;Z[F]=[Y,...G]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=r4(Y.routes);for(let[z,X]of Object.entries(j)){let G=J==="/"?z:`${J}${z}`,Q=z==="/"&&J!=="/"?J:G;Z[Q]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[vL(J),W]))}function e4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)e4(Y[1],j)}function $8($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=$8(j.routes);e4(Z,[Y,z])}else e4(Z,[Y,[]])}else{let Y=new W,j=$8(Y.routes);for(let z of j)e4(Z,z)}return Z}function OW($){let Z=[];for(let[J,W]of $)Z.push(J,...OW(W).flat());return Array.from(new Set(Z))}function vQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class N$ extends h{static getFacadeAccessor(){return d}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??N$.locale(),$.timeZone??N$.timeZone())}static setLocale($=N$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=N.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class LW{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function gQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var gL=50;class zZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}locate($,Z){let J=Z.params??{},W=new URLSearchParams(gQ(Z.search??{}));W.delete("json"),W.sort();let Y=D0($,J),j=W.toString();return{params:J,searchParams:W,path:Y,variantKey:j,key:this.keyFor(Y,j)}}find($,Z={}){return this.entries.get(this.locate($,Z).key)}entriesFor($){return Array.from(this.entries.values()).filter((Z)=>Z.path===$)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let{params:W,searchParams:Y,path:j,variantKey:z,key:X}=this.locate($,Z),G=this.entries.get(X);if(G)return G;let Q;if(J==="render"&&this.renderStartedAt!==null){let U=Math.round(performance.now()-this.renderStartedAt);if(U>gL)Q=U}let F,V=new Promise((U)=>{F=U}),B={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:V,source:J,startedAt:this.elapsed()};return this.entries.set(X,B),this.fetcher($,W,Y).then((U)=>{B.status="resolved",B.data=U},(U)=>{B.status="rejected",B.error=U}).then(()=>{if(B.settledAt=this.elapsed(),this.maybeLogLateDiscovery(B),B.status==="rejected"&&this.failListener)this.failListener(B);if(this.settleListener)this.settleListener(B);else this.settledBacklog.push(B);F()}),B}prefill($,Z,J){let{path:W,variantKey:Y,key:j}=this.locate($,Z),z=this.entries.get(j);if(z)return z;let X=this.elapsed(),G={path:W,patternPath:$,variantKey:Y,status:"resolved",data:J,promise:Promise.resolve(),source:"prefetch",startedAt:X,settledAt:X};return this.entries.set(j,G),G}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class a0 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function eZ(){let $=JSON.stringify({error:t1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function MW(){return{status:403,error:{message:"Forbidden"}}}function J3($){let Z=$3.getStore(),J=N.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[D0(W,Y),j.toString()].filter((V)=>V.length>0).join("?"),G=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),Q=Z8($);if(Q)Z3(G,Q);let F=new A(G,Y);return $3.run(Z,()=>N.run(F,async()=>{let V=J?.locale;if(V&&H(d).isLocaleAware)N.getStore().setLocale(V);try{let B=H(Q1).dispatchers(Q).api,U=await B.runRouteMiddleware(W,F)??await B.getRouteData(W);if(i1(U)){if(!U.ok)throw new a0(D0(W,Y),j.toString(),U.status,U.body);return U.body}if(U instanceof Response){let O=await U.json().catch(()=>null);if(!U.ok)throw new a0(D0(W,Y),j.toString(),U.status,O);return O}return U}catch(B){if(B instanceof a0)throw B;let U=new a0(D0(W,Y),j.toString(),500,{message:B instanceof Error?B.message:String(B)});throw U.cause=B,U}}))}}var yL=new Set(["script","style","template","title"]),mL=/\shidden([\s=/]|$)/i,hL=/"[^"]*"|'[^']*'/g;function pL($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let V=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=V;else Z+=V}if(j===-1)break;if($.startsWith("<!--",j)){let V=$.indexOf("-->",j+4);Y=V===-1?$.length:V+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let G=$.slice(j+1,X);Y=X+1;let Q=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(G)?.[1]?.toLowerCase();if(!Q)continue;let F=G.startsWith("/");if(!F&&yL.has(Q)&&!G.endsWith("/")){let V=$.indexOf(`</${Q}`,Y);Y=V===-1?$.length:V;continue}if(Q!=="div")continue;if(F){if(W>0)W-=1}else if(W>0)W+=1;else if(mL.test(G.replace(hL,'""')))W=1}return{shellChars:Z,deferredChars:J}}var cL=1000,dL=64;function uL($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function lL($,Z){if(Z.deferredChars<cL)return null;if(Z.shellChars>=dL)return null;return`[gemi] GET ${$} streams ${uL(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function yQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=lL(J,W);if(!Y)return;Z.add(J),$(Y)}}}function mQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),pL(Z)}}}function hQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(F)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:F})};j=G,z.enqueue(Y.encode(`${JSON.stringify($)}
20
20
  `)),Z.onSettle((F)=>{if(X||F.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([F.path,F.variantKey,F.data])}
21
- `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as cx,createContext as GM,createElement as dx,lazy as ux,use as lx,useContext as ix}from"react";import{createContext as dL}from"react";var uL=dL(null);import{createContext as sL,useContext as Dx}from"react";import{useContext as Qx}from"react";import{createContext as lL}from"react";import{jsx as zx}from"react/jsx-runtime";var iL=lL({});var nL="gemi.islandI18n",oL=globalThis[Symbol.for(nL)]??=sL(null);import{createContext as aQ,useMemo as wx,useRef as fx}from"react";class HW{subscribers=new Set;value;constructor($){this.value=$,this.subscribe=this.subscribe.bind(this),this.next=this.next.bind(this),this.getValue=this.getValue.bind(this)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}next($){this.value=$,this.subscribers.forEach((Z)=>Z($))}getValue(){return this.value}}function hQ($,Z=Date.now()){if($==null)return;let J=$.trim();if(J==="")return;if(/^\d+$/.test(J))return Number(J)*1000;let W=Date.parse(J);if(Number.isNaN(W))return;return Math.max(0,W-Z)}function pQ($){if($.status===204||$.status===205)return Promise.resolve(null);let Z=$.headers?.get?.("Content-Type")??"";if(/^text\/plain\b/i.test(Z))return $.text();return $.json()}var cQ="/auth/sign-in",aL=1000,tL=2,TW,PW=null,J3="idle",dQ=0,NW=[];function lQ($,Z){if($!==401)return!1;let J=Z&&typeof Z==="object"?Z.error:void 0;if(typeof J==="string")return J==="Authentication error";return!!J&&typeof J==="object"&&J.kind==="authentication"}function rL($){let Z=$?.get?.(KW);if(typeof Z!=="string"||Z==="")return cQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return cQ}function eL(){let $=PW?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var uQ=($)=>$.replace(/\/+$/,"")||"/";function $M($,Z){let J=k8($),W=new URL($,"http://gemi.invalid");if(!J&&uQ(W.pathname)===uQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function ZM($){if(!k8($)&&PW)PW.replace($);else window.location.replace($)}function iQ($){if(!TW||typeof window>"u")return;if(!lQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(J3==="handled")return;if(J3==="idle"&&dQ>=tL)return;if($.refetch)NW.push($.refetch);if(J3==="checking")return;J3="checking",dQ++;let Z=$;setTimeout(()=>{JM(Z)},aL)}async function JM($){let Z=!1,J=$.headers?.get?.(KW)?$.headers:null;try{let X=await fetch("/api/auth/me",{cache:"no-store",headers:{Accept:"application/json"}}),G=null;try{G=await X.json()}catch{}if(Z=lQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=NW;if(NW=[],!Z){J3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}J3="handled";let Y=eL();if(!Y)return;let j=$M(rL(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>ZM(j)};try{if(TW==="redirect")z.redirect();else TW?.(z)}catch(X){console.error(X)}}class _W extends Error{url;timeout;constructor($,Z){super(`Request to ${$} timed out after ${Z}ms`);this.url=$;this.timeout=Z;this.name="TimeoutError"}}function sQ($,Z){let J=!1,W=!1,Y,j=1/0,z=null,X=(G)=>{if(!$||W)return;if(typeof G!=="number"||!(G>0)||!Number.isFinite(G))return;let Q=Date.now();if(Q+G>=j)return;if(Y=G,j=Q+G,z!==null)clearTimeout(z);z=setTimeout(()=>{J=!0,$.abort()},G)};return X(Z),{timedOut:()=>J,timeout:()=>Y,tighten:X,clear:()=>{if(W=!0,z!==null)clearTimeout(z)}}}var IW=5000,WM=2147483647;class zZ{store;staleVariants=new Set;lastFetchRecord=new Map;key;inflight=new Set;pending=new Map;watchers=new Map;failures=new Map;retryTimers=new Map;seq=0;issued=new Map;applied=new Map;controllers=new Map;streamed=new Set;timeouts=new Map;renderTimeouts=new Map;renderTimeoutsClearing=!1;requestTimers=new Map;constructor($,Z){this.key=$,this.store=new HW(new Map),this.hydrate(Z)}hydrate($,Z=!1){let J=this.store.getValue(),W=Date.now(),Y=!1;for(let[j,z]of Object.entries($??{})){if(z===void 0)continue;let X=J.get(j);if(X?.loading)continue;if(X?.hasData&&X.data===z)continue;if(this.fill(J,j,z,W),Z)this.streamed.add(j);Y=!0}if(Y)this.store.next(J)}pendingFor($){let Z=this.pending.get($);if(!Z){let J;Z={promise:new Promise((Y)=>{J=Y}),resolve:J},this.pending.set($,Z)}return Z}settle($){let Z=this.pending.get($);if(Z)this.pending.delete($),Z.resolve()}isStale($,Z){if(this.staleVariants.has($))return!0;let J=Date.now();return J-(this.lastFetchRecord.get($)??J)>=Z}peek($){return this.store.getValue().get($)}peekForHydration($){return this.streamed.has($)?void 0:this.peek($)}setRequestTimeout($,Z){if(!nQ(Z))return;this.tightenInflight($,Z);let J=this.renderTimeouts.get($);if(J===void 0||Z<J)this.renderTimeouts.set($,Z);if(this.renderTimeoutsClearing)return;this.renderTimeoutsClearing=!0,Promise.resolve().then(()=>{this.renderTimeoutsClearing=!1,this.renderTimeouts.clear()})}holdRequestTimeout($,Z){if(!nQ(Z))return()=>{};this.tightenInflight($,Z);let J={},W=this.timeouts.get($);if(!W)W=new Map,this.timeouts.set($,W);return W.set(J,Z),()=>{let Y=this.timeouts.get($);if(!Y)return;if(Y.delete(J),Y.size===0)this.timeouts.delete($)}}tightenInflight($,Z){for(let J of this.requestTimers.get($)??[])J.tighten(Z)}requestTimeout($){let Z=this.renderTimeouts.get($);for(let J of this.timeouts.get($)?.values()??[])if(Z===void 0||J<Z)Z=J;return Z}isFetching($){return this.inflight.has($)}start($){if(typeof window>"u")return;if(this.store.getValue().has($))return;if(this.inflight.has($))return;this.resolveVariant($,!0)}read($,Z=IW){let J=this.peek($);if(J?.hasData){if(!this.inflight.has($)&&this.isStale($,Z))this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0);return{state:J}}if(J?.error)return{state:J};if(typeof window>"u")return{state:J};let W=this.pendingFor($);if(!this.inflight.has($))this.resolveVariant($,!0);return{state:J,promise:W.promise}}getVariant($,Z=IW){let J=this.store.getValue();if(!J.has($)){if(!this.inflight.has($))this.resolveVariant($)}else{let W=J.get($);if(!W.loading&&!this.inflight.has($)){if(!W.hasData)return this.resolveVariant($),J.get($);if(this.isStale($,Z))return this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0),J.get($)}}return J.get($)}revalidate($,Z=IW){if(typeof window>"u")return;if(this.inflight.has($))return;let J=this.peek($);if(J?.loading)return;if(J?.hasData){if(!this.isStale($,Z))return;this.lastFetchRecord.set($,Date.now())}this.resolveVariant($,!0)}clearError($){let Z=this.store.getValue(),J=!1;for(let[W,Y]of Z){if($!==void 0&&W!==$)continue;if(Y.error)Z.set(W,{...Y,error:null,reconnecting:!1}),J=!0}if(J)this.store.next(Z)}retain($){this.watchers.set($,(this.watchers.get($)??0)+1);let Z=!1;return()=>{if(Z)return;Z=!0;let J=(this.watchers.get($)??1)-1;if(J>0)this.watchers.set($,J);else this.watchers.delete($),this.cancelRetry($),this.setReconnecting($,!1),this.scheduleAbort($)}}scheduleAbort($){if(!this.controllers.has($))return;setTimeout(()=>{if(this.watchers.has($))return;this.abort($)},0)}abort($){let Z=this.controllers.get($);if(!Z)return;this.controllers.delete($);for(let J of Z)J.abort()}failureCount($){return this.failures.get($)??0}scheduleRetry($,Z){if(typeof window>"u")return;if(this.setReconnecting($,!0),this.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),WM),W=setTimeout(()=>{if(this.retryTimers.delete($),!this.watchers.has($))return;if(this.inflight.has($))return;let Y=this.peek($);if(!Y?.error||Y.loading)return;this.resolveVariant($,Y.hasData,!0,!0)},J);this.retryTimers.set($,W)}giveUpRetry($){if(this.retryTimers.has($)||this.inflight.has($))return;this.setReconnecting($,!1)}setReconnecting($,Z){let J=this.store.getValue(),W=J.get($);if(!W||!!W.reconnecting===Z)return;this.store.next(J.set($,{...W,reconnecting:Z}))}cancelRetry($){let Z=this.retryTimers.get($);if(Z!==void 0)clearTimeout(Z),this.retryTimers.delete($)}retryNow($){if(typeof window>"u")return;if(this.inflight.has($))return;let Z=this.peek($);if(!Z?.error||Z.loading)return;this.resolveVariant($,!0)}variantKeys(){return[...this.store.getValue().keys()]}invalidate($,Z){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(Z&&W?.hasData)this.markApplied($),this.store.next(J.set($,{...W,data:Z(W.data),error:null,reconnecting:!1}));if(this.staleVariants.add($),this.watchers.has($))this.resolveVariant($,!1,!1)}dropHttpCache($){let Z=[typeof window<"u"&&window.location?.origin?window.location.origin:"",this.key,$].filter((J)=>J.length>0).join("?");try{if(caches)caches?.delete(Z)}catch{}}mutate($,Z=(J)=>J){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(!W||!W.hasData){this.resolveVariant($,!1,!1);return}let Y=Z(W.data);this.markApplied($),this.staleVariants.add($),this.store.next(J.set($,{loading:!1,data:Y,hasData:!0,error:null,version:W.version})),this.resolveVariant($,!1,!1)}fill($,Z,J,W){$.set(Z,{loading:!1,data:J,hasData:!0,error:null,version:W}),this.staleVariants.delete(Z),this.lastFetchRecord.set(Z,W),this.failures.delete(Z),this.cancelRetry(Z),this.settle(Z)}refetch($){this.resolveVariant($,!1,!1)}markApplied($){this.applied.set($,this.seq)}async resolveVariant($,Z=!1,J=!0,W=!1){if(typeof window>"u")return;this.cancelRetry($),this.inflight.add($);let Y=++this.seq;this.issued.set($,Y);let j=typeof AbortController>"u"?null:new AbortController;if(j){let U=this.controllers.get($);if(!U)U=new Set,this.controllers.set($,U);U.add(j)}let z=sQ(j,this.requestTimeout($)),X=this.requestTimers.get($);if(!X)X=new Set,this.requestTimers.set($,X);X.add(z);let G=()=>this.issued.get($)===Y,Q=()=>(this.applied.get($)??0)>=Y,F=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},V=this.store.getValue(),B=(U)=>{if(!G())return;F();let O=V.get($);this.store.next(V.set($,{loading:!1,data:O?.data,hasData:O?.hasData??!1,error:U,version:O?.version,reconnecting:O?.reconnecting}))};try{let U=V.get($);if(!Z)V.set($,{loading:!0,data:U?.data,hasData:U?.hasData??!1,error:U?.error,version:U?.version,reconnecting:U?.reconnecting});let O=null,D=null,L=[this.key,$].filter((M)=>M.length).join("?");try{D=await fetch(`/api${L}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{O=await pQ(D)}catch(M){if(D.ok||z.timedOut())throw M;O=null}}catch(M){if(z.timedOut()){B(new _W(`/api${L}`,z.timeout()));return}if(j?.signal.aborted){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}console.error(`Error fetching url /api${L}`,M),B(M);return}if(D.ok){if(Q()){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}this.applied.set($,Y);let M=V.get($);this.store.next(V.set($,{loading:G()?!1:M?.loading??!1,data:O,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let M=new a0(this.key,$,D.status,O,hQ(D.headers?.get?.("retry-after")));if(B(M),G())iQ({source:"query",path:this.key,status:D.status,body:O,headers:D.headers,error:M,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{z.clear();let U=this.requestTimers.get($);if(U?.delete(z),U?.size===0)this.requestTimers.delete($);if(j){let O=this.controllers.get($);if(O?.delete(j),O?.size===0)this.controllers.delete($)}if(G())this.inflight.delete($);this.settle($)}}}function nQ($){return typeof $==="number"&&$>0}import{jsx as jM}from"react/jsx-runtime";var vx=aQ(null);var tQ=aQ({getResource:($,Z={})=>{return new zZ($,Z)},hydrate:()=>{},clearErrors:()=>{}});function YM(){let $=new Map;return{getResource(Z,J){let W=$.get(Z);if(!W)W=new zZ(Z,J??{}),$.set(Z,W);return W},hydrate(Z,J=!1){if(!Z)return;for(let[W,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;let j=$.get(W);if(!j)j=new zZ(W,{}),$.set(W,j);j.hydrate(Y,J)}},clearErrors(){for(let Z of $.values())Z.clearError()}}}var oQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(oQ)]){let Z=YM(),J={seed:Z.hydrate,Provider:({children:W})=>jM(tQ.Provider,{value:Z,children:W})};$[Symbol.for(oQ)]=J}}import{createContext as zM}from"react";var XM=zM(null);function rQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,F){let V=J.find(Q,F);if(!V||V.source!=="prefetch"||V.status==="rejected")return null;return z(V),V}}:null,z=(Q)=>Y.set(`${Q.path}?${Q.variantKey}`,Q),G={queries:j,queriesRead:Y,createQueryManager:()=>{if(!J)return null;let Q=new Map;return{getResource(F,V){let B=Q.get(F);if(!B){let U=new Map(J.entriesFor(F).filter((D)=>D.source==="prefetch"&&D.status==="resolved").map((D)=>[D.variantKey,D]));B=new zZ(F,U.size>0?Object.fromEntries(Array.from(U,([D,L])=>[D,L.data])):V??{});let O=B.peek.bind(B);B.peek=(D)=>{let L=U.get(D);if(L)z(L);return O(D)},Q.set(F,B)}return B},hydrate(){},clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,F,V){let B=`${Q} ${F}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,F,V])},onUse(){}}};for(let Q of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(G.i18n,Q,{enumerable:!0,get(){return G.i18nUsed=!0,Z[Q]}});return G}function eQ($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:J,timeZone:W}=$.i18n;return{...Z?{currentLocale:Z}:{},...J?{defaultLocale:J}:{},...W?{timeZone:W}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}function $B($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var o3="gemi-slot",ZB="data-slot",JB="data-gemi-slot";var QM=Symbol.for("gemi.staticRender"),WB=globalThis[QM]??=GM(null);import{createHash as GB}from"crypto";var xW='var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")y(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],N=O(r),p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)Y(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();D(r,L(r));_(!0);';import{createHash as BM}from"crypto";import{existsSync as jB,readFileSync as FM}from"fs";import{join as bW}from"path";var zB=".script",VM=[".ts",".js"],UM="document-scripts.json",XB="data-gemi-script",DM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function OM($){if(typeof $!=="string"||!DM.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function LM($,Z){for(let J of VM){let W=bW($,"views",`${Z}${zB}${J}`);if(jB(W))return W}return null}async function YB($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
21
+ `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as lx,createContext as FM,createElement as ix,lazy as sx,use as nx,useContext as ox}from"react";import{createContext as iL}from"react";var sL=iL(null);import{createContext as aL,useContext as Mx}from"react";import{useContext as Vx}from"react";import{createContext as nL}from"react";import{jsx as Qx}from"react/jsx-runtime";var oL=nL({});var tL="gemi.islandI18n",rL=globalThis[Symbol.for(tL)]??=aL(null);import{createContext as tQ,useMemo as vx,useRef as gx}from"react";class HW{subscribers=new Set;value;constructor($){this.value=$,this.subscribe=this.subscribe.bind(this),this.next=this.next.bind(this),this.getValue=this.getValue.bind(this)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($)}}next($){this.value=$,this.subscribers.forEach((Z)=>Z($))}getValue(){return this.value}}function pQ($,Z=Date.now()){if($==null)return;let J=$.trim();if(J==="")return;if(/^\d+$/.test(J))return Number(J)*1000;let W=Date.parse(J);if(Number.isNaN(W))return;return Math.max(0,W-Z)}function cQ($){if($.status===204||$.status===205)return Promise.resolve(null);let Z=$.headers?.get?.("Content-Type")??"";if(/^text\/plain\b/i.test(Z))return $.text();return $.json()}var dQ="/auth/sign-in",eL=1000,$M=2,TW,PW=null,W3="idle",uQ=0,NW=[];function iQ($,Z){if($!==401)return!1;let J=Z&&typeof Z==="object"?Z.error:void 0;if(typeof J==="string")return J==="Authentication error";return!!J&&typeof J==="object"&&J.kind==="authentication"}function ZM($){let Z=$?.get?.(KW);if(typeof Z!=="string"||Z==="")return dQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return dQ}function JM(){let $=PW?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var lQ=($)=>$.replace(/\/+$/,"")||"/";function WM($,Z){let J=k8($),W=new URL($,"http://gemi.invalid");if(!J&&lQ(W.pathname)===lQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function YM($){if(!k8($)&&PW)PW.replace($);else window.location.replace($)}function sQ($){if(!TW||typeof window>"u")return;if(!iQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(W3==="handled")return;if(W3==="idle"&&uQ>=$M)return;if($.refetch)NW.push($.refetch);if(W3==="checking")return;W3="checking",uQ++;let Z=$;setTimeout(()=>{jM(Z)},eL)}async function jM($){let Z=!1,J=$.headers?.get?.(KW)?$.headers:null;try{let X=await fetch("/api/auth/me",{cache:"no-store",headers:{Accept:"application/json"}}),G=null;try{G=await X.json()}catch{}if(Z=iQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=NW;if(NW=[],!Z){W3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}W3="handled";let Y=JM();if(!Y)return;let j=WM(ZM(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>YM(j)};try{if(TW==="redirect")z.redirect();else TW?.(z)}catch(X){console.error(X)}}class _W extends Error{url;timeout;constructor($,Z){super(`Request to ${$} timed out after ${Z}ms`);this.url=$;this.timeout=Z;this.name="TimeoutError"}}function nQ($,Z){let J=!1,W=!1,Y,j=1/0,z=null,X=(G)=>{if(!$||W)return;if(typeof G!=="number"||!(G>0)||!Number.isFinite(G))return;let Q=Date.now();if(Q+G>=j)return;if(Y=G,j=Q+G,z!==null)clearTimeout(z);z=setTimeout(()=>{J=!0,$.abort()},G)};return X(Z),{timedOut:()=>J,timeout:()=>Y,tighten:X,clear:()=>{if(W=!0,z!==null)clearTimeout(z)}}}var IW=5000,zM=2147483647;class XZ{store;staleVariants=new Set;lastFetchRecord=new Map;key;inflight=new Set;pending=new Map;watchers=new Map;failures=new Map;retryTimers=new Map;seq=0;issued=new Map;applied=new Map;controllers=new Map;streamed=new Set;timeouts=new Map;renderTimeouts=new Map;renderTimeoutsClearing=!1;requestTimers=new Map;constructor($,Z){this.key=$,this.store=new HW(new Map),this.hydrate(Z)}hydrate($,Z=!1){let J=this.store.getValue(),W=Date.now(),Y=!1;for(let[j,z]of Object.entries($??{})){if(z===void 0)continue;let X=J.get(j);if(X?.loading)continue;if(X?.hasData&&X.data===z)continue;if(this.fill(J,j,z,W),Z)this.streamed.add(j);Y=!0}if(Y)this.store.next(J)}pendingFor($){let Z=this.pending.get($);if(!Z){let J;Z={promise:new Promise((Y)=>{J=Y}),resolve:J},this.pending.set($,Z)}return Z}settle($){let Z=this.pending.get($);if(Z)this.pending.delete($),Z.resolve()}isStale($,Z){if(this.staleVariants.has($))return!0;let J=Date.now();return J-(this.lastFetchRecord.get($)??J)>=Z}peek($){return this.store.getValue().get($)}peekForHydration($){return this.streamed.has($)?void 0:this.peek($)}setRequestTimeout($,Z){if(!oQ(Z))return;this.tightenInflight($,Z);let J=this.renderTimeouts.get($);if(J===void 0||Z<J)this.renderTimeouts.set($,Z);if(this.renderTimeoutsClearing)return;this.renderTimeoutsClearing=!0,Promise.resolve().then(()=>{this.renderTimeoutsClearing=!1,this.renderTimeouts.clear()})}holdRequestTimeout($,Z){if(!oQ(Z))return()=>{};this.tightenInflight($,Z);let J={},W=this.timeouts.get($);if(!W)W=new Map,this.timeouts.set($,W);return W.set(J,Z),()=>{let Y=this.timeouts.get($);if(!Y)return;if(Y.delete(J),Y.size===0)this.timeouts.delete($)}}tightenInflight($,Z){for(let J of this.requestTimers.get($)??[])J.tighten(Z)}requestTimeout($){let Z=this.renderTimeouts.get($);for(let J of this.timeouts.get($)?.values()??[])if(Z===void 0||J<Z)Z=J;return Z}isFetching($){return this.inflight.has($)}start($){if(typeof window>"u")return;if(this.store.getValue().has($))return;if(this.inflight.has($))return;this.resolveVariant($,!0)}read($,Z=IW){let J=this.peek($);if(J?.hasData){if(!this.inflight.has($)&&this.isStale($,Z))this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0);return{state:J}}if(J?.error)return{state:J};if(typeof window>"u")return{state:J};let W=this.pendingFor($);if(!this.inflight.has($))this.resolveVariant($,!0);return{state:J,promise:W.promise}}getVariant($,Z=IW){let J=this.store.getValue();if(!J.has($)){if(!this.inflight.has($))this.resolveVariant($)}else{let W=J.get($);if(!W.loading&&!this.inflight.has($)){if(!W.hasData)return this.resolveVariant($),J.get($);if(this.isStale($,Z))return this.lastFetchRecord.set($,Date.now()),this.resolveVariant($,!0),J.get($)}}return J.get($)}revalidate($,Z=IW){if(typeof window>"u")return;if(this.inflight.has($))return;let J=this.peek($);if(J?.loading)return;if(J?.hasData){if(!this.isStale($,Z))return;this.lastFetchRecord.set($,Date.now())}this.resolveVariant($,!0)}clearError($){let Z=this.store.getValue(),J=!1;for(let[W,Y]of Z){if($!==void 0&&W!==$)continue;if(Y.error)Z.set(W,{...Y,error:null,reconnecting:!1}),J=!0}if(J)this.store.next(Z)}retain($){this.watchers.set($,(this.watchers.get($)??0)+1);let Z=!1;return()=>{if(Z)return;Z=!0;let J=(this.watchers.get($)??1)-1;if(J>0)this.watchers.set($,J);else this.watchers.delete($),this.cancelRetry($),this.setReconnecting($,!1),this.scheduleAbort($)}}scheduleAbort($){if(!this.controllers.has($))return;setTimeout(()=>{if(this.watchers.has($))return;this.abort($)},0)}abort($){let Z=this.controllers.get($);if(!Z)return;this.controllers.delete($);for(let J of Z)J.abort()}failureCount($){return this.failures.get($)??0}scheduleRetry($,Z){if(typeof window>"u")return;if(this.setReconnecting($,!0),this.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),zM),W=setTimeout(()=>{if(this.retryTimers.delete($),!this.watchers.has($))return;if(this.inflight.has($))return;let Y=this.peek($);if(!Y?.error||Y.loading)return;this.resolveVariant($,Y.hasData,!0,!0)},J);this.retryTimers.set($,W)}giveUpRetry($){if(this.retryTimers.has($)||this.inflight.has($))return;this.setReconnecting($,!1)}setReconnecting($,Z){let J=this.store.getValue(),W=J.get($);if(!W||!!W.reconnecting===Z)return;this.store.next(J.set($,{...W,reconnecting:Z}))}cancelRetry($){let Z=this.retryTimers.get($);if(Z!==void 0)clearTimeout(Z),this.retryTimers.delete($)}retryNow($){if(typeof window>"u")return;if(this.inflight.has($))return;let Z=this.peek($);if(!Z?.error||Z.loading)return;this.resolveVariant($,!0)}variantKeys(){return[...this.store.getValue().keys()]}invalidate($,Z){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(Z&&W?.hasData)this.markApplied($),this.store.next(J.set($,{...W,data:Z(W.data),error:null,reconnecting:!1}));if(this.staleVariants.add($),this.watchers.has($))this.resolveVariant($,!1,!1)}dropHttpCache($){let Z=[typeof window<"u"&&window.location?.origin?window.location.origin:"",this.key,$].filter((J)=>J.length>0).join("?");try{if(caches)caches?.delete(Z)}catch{}}mutate($,Z=(J)=>J){this.dropHttpCache($);let J=this.store.getValue(),W=J.get($);if(!W||!W.hasData){this.resolveVariant($,!1,!1);return}let Y=Z(W.data);this.markApplied($),this.staleVariants.add($),this.store.next(J.set($,{loading:!1,data:Y,hasData:!0,error:null,version:W.version})),this.resolveVariant($,!1,!1)}fill($,Z,J,W){$.set(Z,{loading:!1,data:J,hasData:!0,error:null,version:W}),this.staleVariants.delete(Z),this.lastFetchRecord.set(Z,W),this.failures.delete(Z),this.cancelRetry(Z),this.settle(Z)}refetch($){this.resolveVariant($,!1,!1)}markApplied($){this.applied.set($,this.seq)}async resolveVariant($,Z=!1,J=!0,W=!1){if(typeof window>"u")return;this.cancelRetry($),this.inflight.add($);let Y=++this.seq;this.issued.set($,Y);let j=typeof AbortController>"u"?null:new AbortController;if(j){let U=this.controllers.get($);if(!U)U=new Set,this.controllers.set($,U);U.add(j)}let z=nQ(j,this.requestTimeout($)),X=this.requestTimers.get($);if(!X)X=new Set,this.requestTimers.set($,X);X.add(z);let G=()=>this.issued.get($)===Y,Q=()=>(this.applied.get($)??0)>=Y,F=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},V=this.store.getValue(),B=(U)=>{if(!G())return;F();let O=V.get($);this.store.next(V.set($,{loading:!1,data:O?.data,hasData:O?.hasData??!1,error:U,version:O?.version,reconnecting:O?.reconnecting}))};try{let U=V.get($);if(!Z)V.set($,{loading:!0,data:U?.data,hasData:U?.hasData??!1,error:U?.error,version:U?.version,reconnecting:U?.reconnecting});let O=null,D=null,L=[this.key,$].filter((M)=>M.length).join("?");try{D=await fetch(`/api${L}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{O=await cQ(D)}catch(M){if(D.ok||z.timedOut())throw M;O=null}}catch(M){if(z.timedOut()){B(new _W(`/api${L}`,z.timeout()));return}if(j?.signal.aborted){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}console.error(`Error fetching url /api${L}`,M),B(M);return}if(D.ok){if(Q()){let T=V.get($);if(G()&&T?.loading)this.store.next(V.set($,{...T,loading:!1}));return}this.applied.set($,Y);let M=V.get($);this.store.next(V.set($,{loading:G()?!1:M?.loading??!1,data:O,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let M=new a0(this.key,$,D.status,O,pQ(D.headers?.get?.("retry-after")));if(B(M),G())sQ({source:"query",path:this.key,status:D.status,body:O,headers:D.headers,error:M,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{z.clear();let U=this.requestTimers.get($);if(U?.delete(z),U?.size===0)this.requestTimers.delete($);if(j){let O=this.controllers.get($);if(O?.delete(j),O?.size===0)this.controllers.delete($)}if(G())this.inflight.delete($);this.settle($)}}}function oQ($){return typeof $==="number"&&$>0}import{jsx as GM}from"react/jsx-runtime";var mx=tQ(null);var rQ=tQ({getResource:($,Z={})=>{return new XZ($,Z)},hydrate:()=>{},allResources:()=>[],clearErrors:()=>{}});function XM(){let $=new Map;return{getResource(Z,J){let W=$.get(Z);if(!W)W=new XZ(Z,J??{}),$.set(Z,W);return W},hydrate(Z,J=!1){if(!Z)return;for(let[W,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;let j=$.get(W);if(!j)j=new XZ(W,{}),$.set(W,j);j.hydrate(Y,J)}},allResources:()=>$.values(),clearErrors(){for(let Z of $.values())Z.clearError()}}}var aQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(aQ)]){let Z=XM(),J={seed:Z.hydrate,Provider:({children:W})=>GM(rQ.Provider,{value:Z,children:W})};$[Symbol.for(aQ)]=J}}import{createContext as QM}from"react";var BM=QM(null);function eQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,F){let V=J.find(Q,F);if(!V||V.source!=="prefetch"||V.status==="rejected")return null;return z(V),V}}:null,z=(Q)=>Y.set(`${Q.path}?${Q.variantKey}`,Q),G={queries:j,queriesRead:Y,createQueryManager:()=>{if(!J)return null;let Q=new Map;return{getResource(F,V){let B=Q.get(F);if(!B){let U=new Map(J.entriesFor(F).filter((D)=>D.source==="prefetch"&&D.status==="resolved").map((D)=>[D.variantKey,D]));B=new XZ(F,U.size>0?Object.fromEntries(Array.from(U,([D,L])=>[D,L.data])):V??{});let O=B.peek.bind(B);B.peek=(D)=>{let L=U.get(D);if(L)z(L);return O(D)},Q.set(F,B)}return B},hydrate(){},allResources:()=>Q.values(),clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,F,V){let B=`${Q} ${F}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,F,V])},onUse(){}}};for(let Q of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(G.i18n,Q,{enumerable:!0,get(){return G.i18nUsed=!0,Z[Q]}});return G}function $B($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:J,timeZone:W}=$.i18n;return{...Z?{currentLocale:Z}:{},...J?{defaultLocale:J}:{},...W?{timeZone:W}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}function ZB($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var o3="gemi-slot",JB="data-slot",WB="data-gemi-slot";var VM=Symbol.for("gemi.staticRender"),YB=globalThis[VM]??=FM(null);import{createHash as QB}from"crypto";var xW='var r=document,i=window,a=history;i.__gemi_nav?.d();var C=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:C.signal,...s}),q=i.__gemi_nav={d:()=>C.abort()},y=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},L=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},D=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")y(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>y(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),y(n,s)});for(let m of n.children)l.observe(m)}}},R=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(R)?.content,O=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],N=O(r),p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},v={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,Y=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},j=(t)=>{let e=r.body,n=t.body,s=L(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),D(e,s)},H=async(t,e)=>{let n=++b,s=!e&&v[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||O(d)!=N)throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),j(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)Y(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),v[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=v[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(v[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(R)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();D(r,L(r));_(!0);';import{createHash as UM}from"crypto";import{existsSync as zB,readFileSync as DM}from"fs";import{join as bW}from"path";var XB=".script",OM=[".ts",".js"],LM="document-scripts.json",GB="data-gemi-script",MM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function HM($){if(typeof $!=="string"||!MM.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function TM($,Z){for(let J of OM){let W=bW($,"views",`${Z}${XB}${J}`);if(zB(W))return W}return null}async function jB($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
22
22
  `);throw Error(`The document script ${$} does not bundle.
23
- ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function EW($){return`'sha256-${BM("sha256").update($).digest("base64")}'`}var CW,AW=new Map;function MM(){if(CW===void 0){let $=bW(SW(),"dist","server",UM);CW=jB($)?JSON.parse(FM($,"utf8")):null}return CW??null}async function RW($){OM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=MM()?.[$];if(j!==void 0)return j;let z=AW.get($);if(z)return z}let J=bW(SW(),"app"),W=LM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${zB}.ts (or .js).`);if(!Z)return YB(W);let Y=YB(W);return AW.set($,Y),Y.catch(()=>AW.delete($)),Y}async function YC($){return EW(await RW($))}var HM="gemi-islands",TM="gemi-island-i18n",PM="gemi-island-queries",VC=`'sha256-${GB("sha256").update(fW).digest("base64")}'`;function kW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var wW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),UC=`'sha256-${GB("sha256").update(xW).digest("base64")}'`,NM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',KM="gemi-static";function QB($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let P=T.module?J(T.module):void 0;if(!P)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let K of P.preload)X.add(K);if(T.preloadDynamic)for(let K of P.dynamicPreload??[])X.add(K)}return{s:P.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),F=j?`<script type="module" ${XB}="${wW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return kW($,"</head>",F,!1);let B=(Y?`<meta name="${KM}" content="${wW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${wW(T)}"/>`).join("")+F,U=Y?xW:fW,O=W?NM+U:U;z?.push(O);let D=Q?eQ(Z):void 0,L=Q?$B(Z):void 0,M=(Q?`<script type="application/json" id="${HM}">${i0({i:G})}</script>`:"")+(D?`<script type="application/json" id="${TM}">${i0(D)}</script>`:"")+(L?`<script type="application/json" id="${PM}">${i0(L)}</script>`:"")+`<script type="module">${O}</script>`;return kW(kW($,"</head>",B,!1),"</body>",M,!0)}function _M($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function BB($){let Z=`<template ${JB}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=_M($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${o3} ${ZB}="${j}" style="display:contents"></${o3}>`;$=$.split(G).join(`<${o3} style="display:contents">${X}</${o3}>`)}return $}function qW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function DB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function IM($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var FB=new Set,xM=new Set(["public","private","s-maxage","proxy-revalidate"]);function vW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=OB(J);if(Bun.env.NODE_ENV!=="production"&&!FB.has(Z)){FB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function OB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!xM.has(W)})].join(", ")}var VB=new Set;function LB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=OB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!VB.has(Z))VB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var UB=new Set;function MB($,Z){if(!IM($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!UB.has(Z))UB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var CM="'strict-dynamic' 'self' https: 'unsafe-inline'",HB="Content-Security-Policy",TB="Content-Security-Policy-Report-Only";function AM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${CM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function gW($,Z,J){if(!Z)return;if($.has(HB)||$.has(TB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?TB:HB,AM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(EW)},W))}var bM=async()=>(await import("./chunk-bqm79ar0.js")).default,yW,a3=async(...$)=>{return yW??=import("react-dom/server.browser").catch((Z)=>{throw yW=void 0,Z}),(await yW).renderToReadableStream(...$)},NB=1e4,KB="no-locale",EM="no-theme";async function RM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var uW="/assets";function kM($){return $===uW||$.startsWith(`${uW}/`)}function wM($){let Z=$.filter(kM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${uW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function fM($){let Z=H(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function mW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function qM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class t3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=gQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;assetCors;translate;csp;constructor($,Z={}){let J=$Q();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.assetCors=$.assetCors??J.assetCors,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":iG(Z)};if(this.requiredViews=Object.fromEntries(uG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)wM(Object.keys(this.flatViewRoutes));this.routeManifest=r4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=OW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H(e1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)J8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{XZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let F of J?.[Q]??[])G.add(F);return[...G].map((Q)=>c1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let F=dW(),V=new AbortController,B=setTimeout(()=>V.abort(),NB),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},O=rQ(async(D,L)=>{let M=await a3(D,{signal:V.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let D,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)D={name:L,source:await RW(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",D?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await a3(c1(WB.Provider,{value:O,children:c1(PB,{children:[...Q,c1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let P=BB(await new Response(T).text()),K=[],R=QB(P,O,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,D,K);return gW(X,this.csp,{nonce:hW(Z.rawRequest),inlineScripts:K}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:V,noTheme:B,url:U,user:O,viewData:D,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:P,appId:K,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??UW,default:this.theme.default??null,value:vM(Z,this.theme.cookie??UW)},x=M?qQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?fM(Z):null},appId:K,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:Y3=[],loaders:BZ,getStyles:_$,viewImportMap:c,cssManifest:g,ogMap:V0,viewModules:B1,clientEntry:I$,modulePreloadManifest:j3,assetBase:u0,resolveIsland:x$,buildId:C1}=H0,A1=I$?[]:Y3,l=(y)=>[y,`window.loaders=${BZ}`,...I$?[`import(${JSON.stringify(I$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let y=null,F1=null;for(let b of k??[])if(typeof V0[b]==="function")F1=b,y=V0[b];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await a3(c1(y,Z6[F1]),{onError:()=>{}})}catch(b){let{fonts:r,...l1}=b.satoriOptions,J6=await Promise.all(r.map((W6)=>{return RM(W6.name,W6.weight,W6.style).then((IF)=>({...W6,data:IF}))})),L2=new Headers(j);L2.set("Content-Type","image/png");let[PF,NF]=await Promise.all([bM(),n4("Rendering an OG image")]),KF=await PF(b.jsx,{...l1,fonts:J6}),_F=await NF(Buffer.from(KF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(_F),{headers:L2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:f.data,serverQueries:Q,headers:j,getStyles:_$,viewImportMap:c,viewModules:B1,resolveIsland:x$,buildId:C1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!c[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:f.data,serverQueries:Q,headers:j,getStyles:_$,viewImportMap:{...c,"404":c[y]},viewModules:B1&&{...B1,"404":B1[y]},resolveIsland:x$,buildId:C1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=j3??{},u0&&u0!=="/")f.data.assetBase=u0;if(C1&&C1!=="dev")f.data.buildId=C1;let H8=_B(this.modulePreloadLinks({clientEntry:I$,modulePreloadManifest:j3,views:k??["404"],routeKey:Y??"404"}),S),T8=_B(await _$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let t0=new AbortController,FZ=setTimeout(()=>t0.abort(),NB),C$=I6(F)||V,u1=Bun.env.NODE_ENV!=="production"&&!C$&&Y&&this.shellReporter.shouldObserve(Y)?yQ():null,A$=dW();try{let y=await a3(c1(PB,{children:fQ(H8,[...T8,...w?[c1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:CQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],c1(_,{data:f.data,viewImportMap:c,viewModules:B1,serverQueries:Q,dictionarySink:A$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:A1,nonce:S,signal:t0.signal,...C$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(FZ)),C$)await y.allReady.catch(()=>{});return new Response(Y7(y,Q,{onShell:C$?void 0:()=>Q.markShell(),onChunk:u1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(t0.signal.aborted)),u1)this.shellReporter.report(Y,u1.measure())})},A$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(FZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted))),y;let F1=await a3(c1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...A1]:A1,nonce:S});return new Response(Y7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(E$(Z))return 404;if(Z?.kind===o1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(a1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof a0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=SQ(this.flatViewRoutes,J.pathname),Y=bQ(this.flatViewRoutes,J.pathname),j=W?J.pathname.slice(0,-5):Y?J.pathname.slice(0,-3):J.pathname,[,z,...X]=j.split("/"),G=j,Q=null,F=null,V=H(d),B=tZ(this.flatViewRoutes,j),U=V.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(KB);if(U&&V.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&F===null&&!(F===null&&B!==null)){let _=pW(z,V.supportedLocales,V.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(d).detectLocale(new A($,{},"view",G));if(F===null&&_!==V.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let D=[],L=[],M=null,T={},P=null,K=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=tZ(this.flatViewRoutes,G);if(F&&_?.route.middleware.includes(KB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,D=_.route.exec,L=_.route.middleware,C=_.route.features,K=L.includes("no-stream"),R=L.includes(EM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(DW),H0=RQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(d).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)D=D.slice(H0.startIndex),P={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let f=new A($,T,"view",M);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let _=null,k=N.getStore(),H0=$3.getStore(),Y3=(g)=>$3.run(H0,()=>N.runWith(k,g));k.serverQueries=new rZ(n3($));let BZ=new Set;k.serverQueries.onQueryFail((g)=>{BZ.add(g.error);try{Y3(()=>Promise.resolve(this.hooks.onRequestFail(c,g.error)).catch(()=>{}))}catch{}});let _$=qW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(F){let g=F.replaceAll("/","");N$.setLocale(g,{cookie:_$.locale})}else if(V.isLocaleAware&&!U)k.setLocale(V.defaultLocale);else N$.setLocale(void 0,{cookie:_$.locale});let c=k.req;if(_$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(d).isLocaleAware){let{supportedLocales:b,defaultLocale:r}=H(d),l1=await this.detectLocale(c,{supportedLocales:b,defaultLocale:r}),J6=typeof l1==="string"?pW(l1,b,r):null;if(J6)k.setLocale(J6)}try{await H(n1).runMiddleware(L)}catch(b){if(g=this.viewRefusalStatus(c,b,BZ),g===null)throw b}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,D=[],c.routePath="";let V0=H(d),B1=V0.isEnabled,I$=V0.isLocaleAware,j3=new A($,c.params),u0={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(j3)};if(I$){let b=null;if(F)b=F.replaceAll("/",""),k.setLocale(b);else if(!U)b=k.locale??V0.defaultLocale;else b=V0.detectLocale(j3),k.setLocale(b);let r=B1?V0.getPageTranslations(b,c.routePath):{};u0={...u0,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:r},defaultLocale:V0.defaultLocale,...U?{}:{localeRouting:"off"}}}await cW(u0.currentLocale??"");let x$;try{x$=await Promise.all(D.map((b)=>b(c)))}catch(b){if(g=this.viewRefusalStatus(c,b,BZ),g===null)throw b;M=null,D=[],c.routePath="",x$=[]}let C1=void 0;if(M===null){if(C1=await this.hooks.onNotFound(c,{status:g??404}),I$&&!U&&k.locale&&k.locale!==u0.currentLocale){let b=k.locale;u0={...u0,currentLocale:b,dictionary:{[b]:B1?V0.getPageTranslations(b,c.routePath):{}}},await cW(b)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(c):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:A1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:x$,cookies:A1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:c.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(LW).id,features:await H(e1).forClient()};let{params:H8,user:T8}=_,t0={},FZ={};for(let b of x$??[]){let[r,l1]=Object.entries(b)?.[0]??[];if(!r||!l1)continue;FZ[`${r}:${M}`]=l1.breadcrumb,t0[r]=l1}let C$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(C$&&C1)t0["404"]=C1;let u1=t0.FILE;if(u1){try{await this.onRequestEnd(c,{mintSession:!1})}catch(r){XZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let b;if(u1 instanceof Response)b=W8(u1,l,A1);else{for(let r of A1)l.append("Set-Cookie",r.toString());b=await R8(u1,l)}return MB(b,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",DW),A1.forEach((r)=>l.append("Set-Cookie",r.toString())),vW(l,M),await this.hooks.onRequestEnd(c);let b={meta:P&&!k.metadata.touched?null:_.meta,data:{[G]:t0},breadcrumbs:FZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:P};return new Response(mQ(b,k.serverQueries,void 0,({aborted:r})=>Y3(()=>this.completeStream(c,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let A$=M?S:C$,y=Boolean(A$),F1=qW(A$);if(!K&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let b of A1)l.append("Set-Cookie",b.toString());if(!y||F1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(c,{mintSession:!y||F1.session})}catch(b){XZ.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(y&&(M||!w))DB(l,A$);vW(l,M);let Z6=y?void 0:IB($);if(!y)gW(l,this.csp,{nonce:Z6});if(hW($))LB(l,M,y);return await this.render({req:c,runInRequestScope:Y3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:H8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:K,noTheme:R,url:J,user:T8,viewData:t0,breadcrumbs:FZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:A$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===o1){let V0=W?qM(g.payload.viewData??g.payload.api):mW(g.payload.view);for(let B1 of k.cookies)V0.headers.append("Set-Cookie",B1.toString());return V0}if(!BZ.has(g))this.hooks.onRequestFail(c,g);if(a1(g))return console.error(g),W?eZ():mW(MW());if(g instanceof a0&&g.status===403)return W?eZ():mW(MW());throw g}},Z)}}function _B($,Z){return Z?$.map((J)=>SM(J,{nonce:Z})):$}function vM($,Z){let J=$.cookies?.get(Z);return xQ(J)?J:null}function gM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function iW($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?gM(z):encodeURIComponent(String(z))}`});return`${Y8}${J==="/"?"":J}`||Y8}var xB=new Map;function CB($,Z){let J=xB.get($);if(!J)J=new URLPattern({pathname:`${Y8}${$==="/"?"":$}`}),xB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;return Y?sW(Y):null}function sW($){let Z=[];try{for(let[J,W]of Object.entries($))if(W!==void 0)Z.push([J,decodeURIComponent(W)])}catch{return null}return Object.fromEntries(Z)}function nW(){let $=JSON.stringify({error:t1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class EB extends x0{routes={"/api-routes":this.get(()=>{let $=H(j8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(t3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var yM=new Set([s1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),mM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function pM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(yM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===s1)throw Error(`dispatchAs: credentials may not set the "${s1}" cookie. The access token stays the initiator's.`);if(!mM.test(Y)||!hM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function cM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function AB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function W8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function dM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=eG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=a5({"/":$.rootRouter,"/auth":u5,"/__gemi__/services/i18n":l5,"/__gemi__/services/image":n5,...dM()?{"/__gemi__/services/logs":o5,"/__gemi__/debug":EB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=bB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let X=new URLPattern({pathname:j}).exec({pathname:J});if(X){let G=sW(X.pathname.groups);if(!G)break;Y=j,W=G;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(n1).runMiddleware(W)}catch(Y){if(Y.kind===o1)return AB(Y.payload.api);else{if(E$(Y))return nW();if(this.onRequestFail(Z,Y),console.error(Y),a1(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===o1)return AB(j.payload.api);if(E$(j))return nW();if(this.onRequestFail(J.req,j),console.error(j),a1(j))return eZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){XZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(Y&&C2($)){let X={};for(let[G,Q]of Object.entries(Y))if(G!=="OPTIONS")X[G]=Q.cors;if(Object.values(X).some(Boolean))return A2($,X)}if(!Y||!Y[$.method])return new Response(JSON.stringify({error:t1("not_found","Not found",404)}),{status:404});let j=Y[$.method].cors,z=await this.dispatchRoute($,J,W,Z);return j?x2(z,j,$):z}async dispatchRoute($,Z,J,W){let Y=this.flatRoutes[J],j=new A($,Z,"api",J);if(!this.isFrameworkRoute(J))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,J)};try{let Q=H(d);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(n1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let F=await this.runRouteMiddleware(J,j);if(F instanceof Response){let D=W8(F,z.headers,z.cookies);return await G(),D}let V=await this.getRouteData(J),B=z.headers,U=z.cookies;if(V instanceof Response){let D=W8(V,B,U);if(this.isOpenEndedBody($,D)){let L=cM(D,()=>this.endRequest(z,j,J));return X=!0,L}return await G(),D}let O=(i1(V)?V:V1.json(V)).toResponse(B,U);return await G(),O}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},W)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],V=G?null:$.cookies.get(s1);if(V)F.push(`${s1}=${V}`);if(Y?.credentials)pM(Q,F,Y.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let B=G?null:$.headers.get(s1);if(B)Q.set(s1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let O;if(W instanceof FormData)O=W;else if(W!==void 0)Q.set("Content-Type","application/json"),O=JSON.stringify(W);let D=new Request(z,{method:Z,headers:Q,body:O,...Y?.signal?{signal:Y.signal}:{}});if(SB(D,OZ($),G?.grant,Y?.progress),$.domain)Z3(D,$.domain);let L=G?{user:G.user}:void 0;return N.exit(()=>B6.exit(()=>this.handleApiRequest(D,L)))}}import{timingSafeEqual as uM}from"crypto";var G8="",tW="*",lM=60000,iM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,oW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,aW="x-forwarded-host";function kB($){return $.startsWith(":")}function r3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&uM(J,W)}function sM($){if(!$)return[];if($===!0)return[{header:aW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:aW;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function nM($){if(!$||$===!0)return;if(!Array.isArray($)){RB($,"route.domains.trustProxy",aW);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);RB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function RB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!oW.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!oW.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!oW.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<X8)throw Error(`\`${Z}.secret.value\` must be at least ${X8} characters. A guessable one lets any client name its own host.`)}function _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function oM($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function wB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function aM($){let Z=_1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<X8)throw Error(`\`route.domains.ask.secret\` must be at least ${X8} characters. A guessable one is worse than leaving \`ask\` out.`);nM($.trustProxy),wB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),kB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class rW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){aM($),this.root=_1($.root),this.devHosts=wB($.devHosts),this.hostTrusts=sM($.trustProxy);for(let Z of $.groups??[])if(kB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??lM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||r3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&_1(Y)?oM(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:tW,params:{},custom:!0};return null}async allows($,Z){let J=_1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:G8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=iM)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=_1($);if(Z)this.cache.delete(Z)}}}var tM={kind:"none"};function sA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return tM;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function nA($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var fB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,qB=16;function oA($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!fB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!fB.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<qB)throw Error(`GEMI_PROXY_SECRET must be at least ${qB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function vB($,Z){if(!r3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var rM="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(G8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new rW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new t3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(tW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes||Y.assetCors!==$.view.assetCors)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes,assetCors:Z.assetCors}}applyClientIp($){let Z=this.clientIpTrust;if(Z)eW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?vB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)eW($,J);let Z=Z8($)??await this.resolver.resolve($);if(!Z)return null;return Z3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==rM)return null;if(!r3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??G8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function W3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var gB=600000;function yB($,Z){return[P6($,Z),P6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new Q7){o9($.oauthProviders),this.config={...M$(a9($),$),emailCode:W7($.emailCode),passwordLimits:J7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await PZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await VY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Q1)?H(Q1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!n8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=W3(J.expiresAt),j=W3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/gB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=P6($,j),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of yB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(n8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/gB),W=yB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=w9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:m9(Z),G=N6("link",$,j),Q=N6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let F=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+F>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return TZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return TZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await c9(Q.id,W3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(TZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return TZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(TZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(W3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class f0 extends h{static getFacadeAccessor(){return E}static async user(){let $=await f0.userOrNull();if($)return $;throw new R$({redirectTo:V6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return U1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await f0.user();if(!await $(Z))throw new LZ}static async guardSafe($){let Z=await f0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class Q8{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new rZ(n3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Q8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Q8.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new rZ(n3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function mB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=eM(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function eM($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class hB{static origin($){return $2($)}static absolute($,...Z){return`${WZ()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return mB({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return iW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${$2()}${iW(String($),Z[0]??{})}`}static matchApi($,Z){return CB(String($),Z)}}class pB{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static tags($){N.getStore().metadata.tags($)}static robots($){N.getStore().metadata.robots($)}static translate($=!0){N.getStore().metadata.translate($)}static fonts($){N.getStore().metadata.fonts($)}}var $H={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class d1 extends h{static getFacadeAccessor(){return GZ}static get client(){return this.getFacadeRoot().client}static get($){return d1.client.get($)}static set($,Z){return d1.client.set($,Z)}static del(...$){return d1.client.del(...$)}static exists($){return d1.client.exists($)}static incr($){return d1.client.incr($)}static expire($,Z){return d1.client.expire($,Z)}static ttl($){return d1.client.ttl($)}}function uS($){return $}function cB(){return{store:"memory",ttl:null}}class Z2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var ZH="500";class J2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${JH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",ZH]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(GZ)?$.make(GZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function JH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var WH="k:",dB="tag:",YH="t:";class W2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class Y2 extends W2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=M$(cB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)QZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new lB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return WH+iB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=dB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=uB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(dB+Z,uB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:QZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new Z2(this.config.memory);if($==="redis"){let Z=this.options.application;return new J2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(GZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class lB extends W2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){iB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${YH}${Z.join(",")}:${$}`}}function iB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function uB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class sB extends h{static getFacadeAccessor(){return Y2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class nB extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class aB extends h{static getFacadeAccessor(){return oB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class rB extends h{static getFacadeAccessor(){return tB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class eB extends h{static getFacadeAccessor(){return i3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}class $F extends h{static getFacadeAccessor(){return e3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class $6 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof $6)return Z;let J=new $6($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${j2($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${j2($,Z,J)} not to have been broadcast, but it was broadcast ${z2(W.length)}: ${X2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${j2($,J,W)} to have been broadcast ${z2(Z)}, but it was broadcast ${z2(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${X2(this.sent)}.`)}matching($,Z,J){return VZ($),this.sent.filter((W)=>(W.pattern===$||p2($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${X2(this.sent)}.`}}function j2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function z2($){return`${$} ${$===1?"time":"times"}`}function X2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${jH(Z.data)})`).join(", ")}function jH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class ZF extends h{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return $6.install(H())}}function bb($){return $}function JF(){return{store:"memory",sweepLimit:500}}var G2=["completed","failed","cancelled","timed_out"],I1=["pending","running"];function x1($){return G2.includes($)}class Q2{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,B2($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(x1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(I1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function B2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class U2{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of zH(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
23
+ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function EW($){return`'sha256-${UM("sha256").update($).digest("base64")}'`}var CW,AW=new Map;function PM(){if(CW===void 0){let $=bW(SW(),"dist","server",LM);CW=zB($)?JSON.parse(DM($,"utf8")):null}return CW??null}async function RW($){HM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=PM()?.[$];if(j!==void 0)return j;let z=AW.get($);if(z)return z}let J=bW(SW(),"app"),W=TM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${XB}.ts (or .js).`);if(!Z)return jB(W);let Y=jB(W);return AW.set($,Y),Y.catch(()=>AW.delete($)),Y}async function XC($){return EW(await RW($))}var NM="gemi-islands",KM="gemi-island-i18n",_M="gemi-island-queries",OC=`'sha256-${QB("sha256").update(fW).digest("base64")}'`;function kW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var wW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),LC=`'sha256-${QB("sha256").update(xW).digest("base64")}'`,IM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',xM="gemi-static";function BB($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let P=T.module?J(T.module):void 0;if(!P)return console.error(`[gemi] island ${T.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(T.load==="eager"){for(let K of P.preload)X.add(K);if(T.preloadDynamic)for(let K of P.dynamicPreload??[])X.add(K)}return{s:P.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),F=j?`<script type="module" ${GB}="${wW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return kW($,"</head>",F,!1);let B=(Y?`<meta name="${xM}" content="${wW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${wW(T)}"/>`).join("")+F,U=Y?xW:fW,O=W?IM+U:U;z?.push(O);let D=Q?$B(Z):void 0,L=Q?ZB(Z):void 0,M=(Q?`<script type="application/json" id="${NM}">${i0({i:G})}</script>`:"")+(D?`<script type="application/json" id="${KM}">${i0(D)}</script>`:"")+(L?`<script type="application/json" id="${_M}">${i0(L)}</script>`:"")+`<script type="module">${O}</script>`;return kW(kW($,"</head>",B,!1),"</body>",M,!0)}function CM($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function FB($){let Z=`<template ${WB}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=CM($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let G=`<${o3} ${JB}="${j}" style="display:contents"></${o3}>`;$=$.split(G).join(`<${o3} style="display:contents">${X}</${o3}>`)}return $}function qW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function OB($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function AM($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var VB=new Set,SM=new Set(["public","private","s-maxage","proxy-revalidate"]);function vW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=LB(J);if(Bun.env.NODE_ENV!=="production"&&!VB.has(Z)){VB.add(Z);let Y=[...new Set($.getSetCookie().map((j)=>j.split("=")[0]))];console.warn(`[gemi] The view "${Z??""}" sets cookies (${Y.join(", ")}) on a response with Cache-Control "${J}", so it was sent "${W}" instead: a shared cache would hand those cookies to every visitor. To let a CDN cache the page, make it a static view with .static({ cacheControl }).`)}$.set("Cache-Control",W)}function LB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!SM.has(W)})].join(", ")}var UB=new Set;function MB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=LB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!UB.has(Z))UB.add(Z),console.warn(`[gemi] The static view "${Z??""}" asked for a CSP nonce (cspNonce()) on a response with Cache-Control "${W}", so it was sent "${Y}" instead: a shared cache would hand the same nonce to every visitor. Allow a static page's scripts by hash instead (route.view.csp does).`);$.set("Cache-Control",Y)}var DB=new Set;function HB($,Z){if(!AM($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!DB.has(Z))DB.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var bM="'strict-dynamic' 'self' https: 'unsafe-inline'",TB="Content-Security-Policy",PB="Content-Security-Policy-Report-Only";function EM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${bM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function gW($,Z,J){if(!Z)return;if($.has(TB)||$.has(PB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?PB:TB,EM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(EW)},W))}var kM=async()=>(await import("./chunk-bqm79ar0.js")).default,yW,a3=async(...$)=>{return yW??=import("react-dom/server.browser").catch((Z)=>{throw yW=void 0,Z}),(await yW).renderToReadableStream(...$)},KB=1e4,_B="no-locale",wM="no-theme";async function fM($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var uW="/assets";function qM($){return $===uW||$.startsWith(`${uW}/`)}function vM($){let Z=$.filter(qM);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${uW}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function gM($){let Z=H(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function mW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function yM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class t3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=yQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;assetCors;translate;csp;constructor($,Z={}){let J=ZQ();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.assetCors=$.assetCors??J.assetCors,this.translate=$.translate,this.csp=$.csp,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":sG(Z)};if(this.requiredViews=Object.fromEntries(lG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)vM(Object.keys(this.flatViewRoutes));this.routeManifest=r4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=$8(W),this.flatComponentTree=OW(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=H(e1);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)J8();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{GZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let G=new Set(Z?.preload??[]);for(let Q of W)for(let F of J?.[Q]??[])G.add(F);return[...G].map((Q)=>c1("link",{key:`modulepreload:${Q}`,rel:"modulepreload",href:Q}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,G;if(W.layout){if(G=$.viewImportMap[W.layout],!G)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let Q=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let F=dW(),V=new AbortController,B=setTimeout(()=>V.abort(),KB),U=(D)=>{if(Bun.env.NODE_ENV!=="production")console.error(D)},O=eQ(async(D,L)=>{let M=await a3(D,{signal:V.signal,identifierPrefix:L,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});return await M.allReady.catch(()=>{}),await new Response(M).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone},z);try{let D,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)D={name:L,source:await RW(L)};let M;if(W.navigation){let C=W.navigation===!0?{}:W.navigation,S=C.version?String(await J(()=>C.version(Z))):"";M={identity:[W.layout??"",$.buildId??"",D?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await a3(c1(YB.Provider,{value:O,children:c1(NB,{children:[...Q,c1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:F,rootLayout:G,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let P=FB(await new Response(T).text()),K=[],R=BB(P,O,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,D,K);return gW(X,this.csp,{nonce:hW(Z.rawRequest),inlineScripts:K}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:F,noStream:V,noTheme:B,url:U,user:O,viewData:D,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:P,appId:K,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??UW,default:this.theme.default??null,value:mM(Z,this.theme.cookie??UW)},x=M?vQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:D},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:O},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?gM(Z):null},appId:K,features:R,theme:w,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},_=this.root,k=this.routeManifest[Y];return async(H0)=>{let{bootstrapModules:j3=[],loaders:FZ,getStyles:_$,viewImportMap:c,cssManifest:g,ogMap:V0,viewModules:B1,clientEntry:I$,modulePreloadManifest:z3,assetBase:u0,resolveIsland:x$,buildId:C1}=H0,A1=I$?[]:j3,l=(y)=>[y,`window.loaders=${FZ}`,...I$?[`import(${JSON.stringify(I$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let y=null,F1=null;for(let b of k??[])if(typeof V0[b]==="function")F1=b,y=V0[b];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await a3(c1(y,Z6[F1]),{onError:()=>{}})}catch(b){let{fonts:r,...l1}=b.satoriOptions,J6=await Promise.all(r.map((W6)=>{return fM(W6.name,W6.weight,W6.style).then((AF)=>({...W6,data:AF}))})),M2=new Headers(j);M2.set("Content-Type","image/png");let[_F,IF]=await Promise.all([kM(),n4("Rendering an OG image")]),xF=await _F(b.jsx,{...l1,fonts:J6}),CF=await IF(Buffer.from(xF)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(CF),{headers:M2})}return new Response("data")}if(C&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:k,data:f.data,serverQueries:Q,headers:j,getStyles:_$,viewImportMap:c,viewModules:B1,resolveIsland:x$,buildId:C1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!c[y])throw Error(`The not-found view "${y}" (route.view.notFound) was not found. It is a view path: a file at app/views/${y}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:C,currentViews:[y],data:f.data,serverQueries:Q,headers:j,getStyles:_$,viewImportMap:{...c,"404":c[y]},viewModules:B1&&{...B1,"404":B1[y]},resolveIsland:x$,buildId:C1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=z3??{},u0&&u0!=="/")f.data.assetBase=u0;if(C1&&C1!=="dev")f.data.buildId=C1;let H8=IB(this.modulePreloadLinks({clientEntry:I$,modulePreloadManifest:z3,views:k??["404"],routeKey:Y??"404"}),S),T8=IB(await _$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let t0=new AbortController,VZ=setTimeout(()=>t0.abort(),KB),C$=I6(F)||V,u1=Bun.env.NODE_ENV!=="production"&&!C$&&Y&&this.shellReporter.shouldObserve(Y)?mQ():null,A$=dW();try{let y=await a3(c1(NB,{children:qQ(H8,[...T8,...w?[c1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:AQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],c1(_,{data:f.data,viewImportMap:c,viewModules:B1,serverQueries:Q,dictionarySink:A$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:A1,nonce:S,signal:t0.signal,...C$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),C$)await y.allReady.catch(()=>{});return new Response(Y7(y,Q,{onShell:C$?void 0:()=>Q.markShell(),onChunk:u1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(t0.signal.aborted)),u1)this.shellReporter.report(Y,u1.measure())})},A$,S),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(y){if(clearTimeout(VZ),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted))),y;let F1=await a3(c1("div"),{bootstrapScriptContent:l(`window.error= ${i0(y.message)}; window.stack_trace=${i0(y.stack)};window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...A1]:A1,nonce:S});return new Response(Y7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(t0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(E$(Z))return 404;if(Z?.kind===o1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(a1(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof a0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=bQ(this.flatViewRoutes,J.pathname),Y=EQ(this.flatViewRoutes,J.pathname),j=W?J.pathname.slice(0,-5):Y?J.pathname.slice(0,-3):J.pathname,[,z,...X]=j.split("/"),G=j,Q=null,F=null,V=H(d),B=rZ(this.flatViewRoutes,j),U=V.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(_B);if(U&&V.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,F=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&V.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&F===null&&!(F===null&&B!==null)){let _=pW(z,V.supportedLocales,V.defaultLocale);if(_){let k=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${W?".json":""}${J.search}`}})}}if(U&&!Y){let _=H(d).detectLocale(new A($,{},"view",G));if(F===null&&_!==V.defaultLocale){let k=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${k}${J.search}`}})}}G=G.replace("//","/");let D=[],L=[],M=null,T={},P=null,K=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=rZ(this.flatViewRoutes,G);if(F&&_?.route.middleware.includes(_B))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,D=_.route.exec,L=_.route.middleware,C=_.route.features,K=L.includes("no-stream"),R=L.includes(wM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(DW),H0=kQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(d).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)D=D.slice(H0.startIndex),P={from:k,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(S&&W)return new Response("Not found",{status:404});let f=new A($,T,"view",M);return this.hooks.onRequestStart(f),await N.run(f,async()=>{let _=null,k=N.getStore(),H0=$3.getStore(),j3=(g)=>$3.run(H0,()=>N.runWith(k,g));k.serverQueries=new zZ(J3($));let FZ=new Set;k.serverQueries.onQueryFail((g)=>{FZ.add(g.error);try{j3(()=>Promise.resolve(this.hooks.onRequestFail(c,g.error)).catch(()=>{}))}catch{}});let _$=qW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(F){let g=F.replaceAll("/","");N$.setLocale(g,{cookie:_$.locale})}else if(V.isLocaleAware&&!U)k.setLocale(V.defaultLocale);else N$.setLocale(void 0,{cookie:_$.locale});let c=k.req;if(_$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(d).isLocaleAware){let{supportedLocales:b,defaultLocale:r}=H(d),l1=await this.detectLocale(c,{supportedLocales:b,defaultLocale:r}),J6=typeof l1==="string"?pW(l1,b,r):null;if(J6)k.setLocale(J6)}try{await H(n1).runMiddleware(L)}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,D=[],c.routePath="";let V0=H(d),B1=V0.isEnabled,I$=V0.isLocaleAware,z3=new A($,c.params),u0={defaultLocale:V0.defaultLocale,timeZone:V0.detectTimeZone(z3)};if(I$){let b=null;if(F)b=F.replaceAll("/",""),k.setLocale(b);else if(!U)b=k.locale??V0.defaultLocale;else b=V0.detectLocale(z3),k.setLocale(b);let r=B1?V0.getPageTranslations(b,c.routePath):{};u0={...u0,supportedLocales:V0.supportedLocales,currentLocale:b,dictionary:{[b]:r},defaultLocale:V0.defaultLocale,...U?{}:{localeRouting:"off"}}}await cW(u0.currentLocale??"");let x$;try{x$=await Promise.all(D.map((b)=>b(c)))}catch(b){if(g=this.viewRefusalStatus(c,b,FZ),g===null)throw b;M=null,D=[],c.routePath="",x$=[]}let C1=void 0;if(M===null){if(C1=await this.hooks.onNotFound(c,{status:g??404}),I$&&!U&&k.locale&&k.locale!==u0.currentLocale){let b=k.locale;u0={...u0,currentLocale:b,dictionary:{[b]:B1?V0.getPageTranslations(b,c.routePath):{}}},await cW(b)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(c):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:A1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:x$,cookies:A1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:c.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(LW).id,features:await H(e1).forClient()};let{params:H8,user:T8}=_,t0={},VZ={};for(let b of x$??[]){let[r,l1]=Object.entries(b)?.[0]??[];if(!r||!l1)continue;VZ[`${r}:${M}`]=l1.breadcrumb,t0[r]=l1}let C$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(C$&&C1)t0["404"]=C1;let u1=t0.FILE;if(u1){try{await this.onRequestEnd(c,{mintSession:!1})}catch(r){GZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let b;if(u1 instanceof Response)b=W8(u1,l,A1);else{for(let r of A1)l.append("Set-Cookie",r.toString());b=await R8(u1,l)}return HB(b,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",DW),A1.forEach((r)=>l.append("Set-Cookie",r.toString())),vW(l,M),await this.hooks.onRequestEnd(c);let b={meta:P&&!k.metadata.touched?null:_.meta,data:{[G]:t0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:P};return new Response(hQ(b,k.serverQueries,void 0,({aborted:r})=>j3(()=>this.completeStream(c,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let A$=M?S:C$,y=Boolean(A$),F1=qW(A$);if(!K&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let b of A1)l.append("Set-Cookie",b.toString());if(!y||F1.csrf){let b=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${b}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(c,{mintSession:!y||F1.session})}catch(b){GZ.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}if(y&&(M||!w))OB(l,A$);vW(l,M);let Z6=y?void 0:xB($);if(!y)gW(l,this.csp,{nonce:Z6});if(hW($))MB(l,M,y);return await this.render({req:c,runInRequestScope:j3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:H8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:K,noTheme:R,url:J,user:T8,viewData:t0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:A$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===o1){let V0=W?yM(g.payload.viewData??g.payload.api):mW(g.payload.view);for(let B1 of k.cookies)V0.headers.append("Set-Cookie",B1.toString());return V0}if(!FZ.has(g))this.hooks.onRequestFail(c,g);if(a1(g))return console.error(g),W?eZ():mW(MW());if(g instanceof a0&&g.status===403)return W?eZ():mW(MW());throw g}},Z)}}function IB($,Z){return Z?$.map((J)=>RM(J,{nonce:Z})):$}function mM($,Z){let J=$.cookies?.get(Z);return CQ(J)?J:null}function hM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function iW($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?hM(z):encodeURIComponent(String(z))}`});return`${Y8}${J==="/"?"":J}`||Y8}var CB=new Map;function AB($,Z){let J=CB.get($);if(!J)J=new URLPattern({pathname:`${Y8}${$==="/"?"":$}`}),CB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;return Y?sW(Y):null}function sW($){let Z=[];try{for(let[J,W]of Object.entries($))if(W!==void 0)Z.push([J,decodeURIComponent(W)])}catch{return null}return Object.fromEntries(Z)}function nW(){let $=JSON.stringify({error:t1("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class RB extends x0{routes={"/api-routes":this.get(()=>{let $=H(j8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=H(t3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var pM=new Set([s1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),cM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,dM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function uM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(pM.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===s1)throw Error(`dispatchAs: credentials may not set the "${s1}" cookie. The access token stays the initiator's.`);if(!cM.test(Y)||!dM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function lM($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(G){Y(),z.error(G);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function SB($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function W8($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,G]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,G)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function iM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=$Q();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=a5({"/":$.rootRouter,"/auth":u5,"/__gemi__/services/i18n":l5,"/__gemi__/services/image":n5,...iM()?{"/__gemi__/services/logs":o5,"/__gemi__/debug":RB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=EB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let X=new URLPattern({pathname:j}).exec({pathname:J});if(X){let G=sW(X.pathname.groups);if(!G)break;Y=j,W=G;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await H(n1).runMiddleware(W)}catch(Y){if(Y.kind===o1)return SB(Y.payload.api);else{if(E$(Y))return nW();if(this.onRequestFail(Z,Y),console.error(Y),a1(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=N.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===o1)return SB(j.payload.api);if(E$(j))return nW();if(this.onRequestFail(J.req,j),console.error(j),a1(j))return eZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){GZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(Y&&A2($)){let X={};for(let[G,Q]of Object.entries(Y))if(G!=="OPTIONS")X[G]=Q.cors;if(Object.values(X).some(Boolean))return S2($,X)}if(!Y||!Y[$.method])return new Response(JSON.stringify({error:t1("not_found","Not found",404)}),{status:404});let j=Y[$.method].cors,z=await this.dispatchRoute($,J,W,Z);return j?C2(z,j,$):z}async dispatchRoute($,Z,J,W){let Y=this.flatRoutes[J],j=new A($,Z,"api",J);if(!this.isFrameworkRoute(J))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,J)};try{let Q=H(d);if(Q.isEnabled){let D=Q.detectLocale(j);z.setLocale(D)}z.setRequest(j),H(n1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let F=await this.runRouteMiddleware(J,j);if(F instanceof Response){let D=W8(F,z.headers,z.cookies);return await G(),D}let V=await this.getRouteData(J),B=z.headers,U=z.cookies;if(V instanceof Response){let D=W8(V,B,U);if(this.isOpenEndedBody($,D)){let L=lM(D,()=>this.endRequest(z,j,J));return X=!0,L}return await G(),D}let O=(i1(V)?V:V1.json(V)).toResponse(B,U);return await G(),O}catch(Q){if(!X)try{await G()}catch(F){console.error(F)}throw Q}},W)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let G=Y?.identity;if(G!==void 0&&(typeof G!=="object"||!G?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let Q=new Headers,F=[],V=G?null:$.cookies.get(s1);if(V)F.push(`${s1}=${V}`);if(Y?.credentials)uM(Q,F,Y.credentials,G!==void 0);if(F.length>0)Q.set("Cookie",F.join("; "));let B=G?null:$.headers.get(s1);if(B)Q.set(s1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let O;if(W instanceof FormData)O=W;else if(W!==void 0)Q.set("Content-Type","application/json"),O=JSON.stringify(W);let D=new Request(z,{method:Z,headers:Q,body:O,...Y?.signal?{signal:Y.signal}:{}});if(bB(D,LZ($),G?.grant,Y?.progress),$.domain)Z3(D,$.domain);let L=G?{user:G.user}:void 0;return N.exit(()=>B6.exit(()=>this.handleApiRequest(D,L)))}}import{timingSafeEqual as sM}from"crypto";var G8="",tW="*",nM=60000,oM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,oW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,aW="x-forwarded-host";function wB($){return $.startsWith(":")}function r3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&sM(J,W)}function aM($){if(!$)return[];if($===!0)return[{header:aW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:aW;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function tM($){if(!$||$===!0)return;if(!Array.isArray($)){kB($,"route.domains.trustProxy",aW);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);kB(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function kB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!oW.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!oW.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!oW.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<X8)throw Error(`\`${Z}.secret.value\` must be at least ${X8} characters. A guessable one lets any client name its own host.`)}function _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function rM($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function fB($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function eM($){let Z=_1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<X8)throw Error(`\`route.domains.ask.secret\` must be at least ${X8} characters. A guessable one is worse than leaving \`ask\` out.`);tM($.trustProxy),fB($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),wB(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class rW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){eM($),this.root=_1($.root),this.devHosts=fB($.devHosts),this.hostTrusts=aM($.trustProxy);for(let Z of $.groups??[])if(wB(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??nM,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||r3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:k$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&_1(Y)?rM(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:tW,params:{},custom:!0};return null}async allows($,Z){let J=_1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:G8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=oM)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=_1($);if(Z)this.cache.delete(Z)}}}var $H={kind:"none"};function aA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return $H;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function tA($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:k$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var qB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,vB=16;function rA($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!qB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!qB.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<vB)throw Error(`GEMI_PROXY_SECRET must be at least ${vB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function gB($,Z){if(!r3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:k$(J)}var ZH="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(G8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new rW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new t3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(tW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes||Y.assetCors!==$.view.assetCors)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes,assetCors:Z.assetCors}}applyClientIp($){let Z=this.clientIpTrust;if(Z)eW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?gB($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)eW($,J);let Z=Z8($)??await this.resolver.resolve($);if(!Z)return null;return Z3($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==ZH)return null;if(!r3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??G8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function Y3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var yB=600000;function mB($,Z){return[P6($,Z),P6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new Q7){a9($.oauthProviders),this.config={...M$(t9($),$),emailCode:W7($.emailCode),passwordLimits:J7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await NZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await UY(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=H().bound(Q1)?H(Q1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?H(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!n8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=Y3(J.expiresAt),j=Y3(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=N.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/yB),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let Q=P6($,j),F=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:Q,userId:F,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of mB($,j))if((await this.userProvider.findSession({token:Q,userAgent:Z}))?.user){z=Q;break}}if(!z)return null;let G=await this.getSession(z,Z);if(G)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(G.expiresAt)));return G}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(n8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/yB),W=mB($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new A;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new A,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new R$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=f9(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=null;try{z=await this.userProvider.findSession({token:Y,userAgent:W??""})}catch(X){console.error("Reading the new session back failed:",X)}return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:h9(Z),G=N6("link",$,j),Q=N6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let F=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>Y3(U.createdAt)+F>Date.now()&&U.pin!==Q&&U.token!==G);await this.userProvider.deleteMagicLinkTokensExcept($,B.map((U)=>U.id))}return await this.userProvider.createMagicLinkToken({email:$,token:G,pin:Q}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return PZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>Y3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return PZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await d9(Q.id,Y3(Q.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let G=null;for(let Q of z)if(PZ("pin",$,Q.pin,Z))G??=Q;if(!G)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,G.id))return{status:"invalid"};return{status:"ok",row:G}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return PZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(PZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(Y3(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class f0 extends h{static getFacadeAccessor(){return E}static async user(){let $=await f0.userOrNull();if($)return $;throw new R$({redirectTo:V6(N.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=N.getStore();if($?.user)return $.user;let Z=await z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=N.getStore()?.req;return U1(Z?.search.get(l0),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await f0.user();if(!await $(Z))throw new MZ}static async guardSafe($){let Z=await f0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}var $2="x-gemi-invalidate";function hB($){return encodeURIComponent(JSON.stringify([...new Set($)]))}function pB($){if(!$)return[];try{let Z=JSON.parse(decodeURIComponent($));return Array.isArray(Z)?Z.filter((J)=>typeof J==="string"):[]}catch{return[]}}class Q8{static ensure($,Z={}){let J=N.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new zZ(J3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Q8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Q8.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new zZ(J3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}static prefill($,Z,J){let W=N.getStore();if(W.req.kind==="api")throw Error("Query.prefill() cannot be called from an API request");W.serverQueries??=new zZ(J3(W.req.rawRequest)),W.serverQueries.prefill($,Z,J)}static invalidate(...$){let Z=N.getStore(),J=pB(Z.headers.get($2));Z.setHeaders($2,hB([...J,...$]))}}function cB($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=JH(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function JH($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class dB{static origin($){return Z2($)}static absolute($,...Z){return`${WZ()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=N.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):WZ();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return cB({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return iW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${Z2()}${iW(String($),Z[0]??{})}`}static matchApi($,Z){return AB(String($),Z)}}class uB{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}static htmlAttributes($){N.getStore().metadata.htmlAttributes($)}static canonical($){N.getStore().metadata.canonical($)}static alternates($){N.getStore().metadata.alternates($)}static tags($){N.getStore().metadata.tags($)}static robots($){N.getStore().metadata.robots($)}static translate($=!0){N.getStore().metadata.translate($)}static fonts($){N.getStore().metadata.fonts($)}}var WH={set($,Z,J){N.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,J),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class d1 extends h{static getFacadeAccessor(){return QZ}static get client(){return this.getFacadeRoot().client}static get($){return d1.client.get($)}static set($,Z){return d1.client.set($,Z)}static del(...$){return d1.client.del(...$)}static exists($){return d1.client.exists($)}static incr($){return d1.client.incr($)}static expire($,Z){return d1.client.expire($,Z)}static ttl($){return d1.client.ttl($)}}function oS($){return $}function lB(){return{store:"memory",ttl:null}}class J2{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var YH="500";class W2{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${jH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",YH]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=H(),Z=$.bound(QZ)?$.make(QZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function jH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var zH="k:",iB="tag:",XH="t:";class Y2{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class j2 extends Y2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=M$(lB(),$),this.config.ttl!==null&&this.config.ttl!==void 0)BZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new nB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return zH+oB($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=iB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=sB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(iB+Z,sB(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:BZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new J2(this.config.memory);if($==="redis"){let Z=this.options.application;return new W2({...this.config.redis,client:Z?{send:(J,W)=>Z.make(QZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class nB extends Y2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){oB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${XH}${Z.join(",")}:${$}`}}function oB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function sB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class aB extends h{static getFacadeAccessor(){return j2}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class tB extends h{static getFacadeAccessor(){return D1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class eB extends h{static getFacadeAccessor(){return rB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class ZF extends h{static getFacadeAccessor(){return $F}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class JF extends h{static getFacadeAccessor(){return s3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}class WF extends h{static getFacadeAccessor(){return e3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class $6 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof $6)return Z;let J=new $6($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${z2($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${z2($,Z,J)} not to have been broadcast, but it was broadcast ${X2(W.length)}: ${G2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${z2($,J,W)} to have been broadcast ${X2(Z)}, but it was broadcast ${X2(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${G2(this.sent)}.`)}matching($,Z,J){return UZ($),this.sent.filter((W)=>(W.pattern===$||c2($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${G2(this.sent)}.`}}function z2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function X2($){return`${$} ${$===1?"time":"times"}`}function G2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${GH(Z.data)})`).join(", ")}function GH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class YF extends h{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return $6.install(H())}}function fb($){return $}function jF(){return{store:"memory",sweepLimit:500}}var Q2=["completed","failed","cancelled","timed_out"],I1=["pending","running"];function x1($){return Q2.includes($)}class B2{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,F2($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(x1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(I1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function F2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class D2{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of QH(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
24
24
  INSERT INTO ${this.name(Z)}
25
25
  (id, kind, subject, owner, status, meta, version,
26
26
  created_at, started_at, updated_at, deadline_at)
27
27
  VALUES
28
28
  (${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
29
29
  ${F8($.meta)}, 1, ${J}, ${Y}, ${J}, ${W})
30
- `;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?V2(J[0]):null}async list($){let Z=this.q(),J=[Z`1 = 1`];if($.kind!==void 0)J.push(Z`kind = ${$.kind}`);if($.subject!==void 0)J.push(Z`subject = ${$.subject}`);if($.owner!==void 0)J.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)J.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${B8(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
30
+ `;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?U2(J[0]):null}async list($){let Z=this.q(),J=[Z`1 = 1`];if($.kind!==void 0)J.push(Z`kind = ${$.kind}`);if($.subject!==void 0)J.push(Z`subject = ${$.subject}`);if($.owner!==void 0)J.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)J.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${B8(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
31
31
  SELECT * FROM ${this.name(Z)}
32
32
  WHERE ${W}
33
33
  ORDER BY created_at DESC, id DESC
34
- LIMIT ${B2($.limit)}
35
- `).map(V2)}async transition($,Z,J){if(Z.length===0)return null;let W=this.q(),Y=this.clock(W),j=[W`updated_at = ${Y}`,W`version = version + 1`];if(J.status!==void 0){if(j.push(W`status = ${J.status}`),J.status!=="pending")j.push(W`started_at = COALESCE(started_at, ${Y})`);if(x1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${F8(J.progress)}`);if("result"in J)j.push(W`result = ${F8(J.result)}`);if("error"in J)j.push(W`error = ${F8(J.error)}`);let z=j.reduce((G,Q)=>W`${G}, ${Q}`),X=await W`
34
+ LIMIT ${F2($.limit)}
35
+ `).map(U2)}async transition($,Z,J){if(Z.length===0)return null;let W=this.q(),Y=this.clock(W),j=[W`updated_at = ${Y}`,W`version = version + 1`];if(J.status!==void 0){if(j.push(W`status = ${J.status}`),J.status!=="pending")j.push(W`started_at = COALESCE(started_at, ${Y})`);if(x1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${F8(J.progress)}`);if("result"in J)j.push(W`result = ${F8(J.result)}`);if("error"in J)j.push(W`error = ${F8(J.error)}`);let z=j.reduce((G,Q)=>W`${G}, ${Q}`),X=await W`
36
36
  UPDATE ${this.name(W)} SET ${z}
37
37
  WHERE id = ${$} AND status IN (${B8(W,Z)})
38
- `;if(YF(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
38
+ `;if(XF(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
39
39
  SELECT * FROM ${this.name(J)}
40
40
  WHERE status IN (${B8(J,I1)})
41
41
  AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(J,$)}
42
42
  ORDER BY deadline_at, id
43
43
  LIMIT ${Math.max(0,Math.floor(Z))}
44
- `).map(V2)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),J=await Z`
44
+ `).map(U2)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),J=await Z`
45
45
  DELETE FROM ${this.name(Z)}
46
- WHERE status IN (${B8(Z,G2)})
46
+ WHERE status IN (${B8(Z,Q2)})
47
47
  AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
48
- `;return YF(J)}joinable(){if(this.connection===void 0)return;let $=$$();if($===void 0||g$()!==this.connection)return;return $}q(){return this.joinable()??this.sql}name($){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Z){let J=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${J} AS SIGNED)`:$`CAST(${J} AS BIGINT)`}}function B8($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function F8($){return $===void 0||$===null?null:JSON.stringify($)}function V8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function F2($){return $===null||$===void 0?null:Number($)}function WF($){return $===null||$===void 0?null:String($)}function V2($){return{id:String($.id),kind:String($.kind),subject:WF($.subject),owner:WF($.owner),status:String($.status),meta:V8($.meta),progress:V8($.progress),result:V8($.result),error:V8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:F2($.started_at),updatedAt:Number($.updated_at),finishedAt:F2($.finished_at),deadlineAt:F2($.deadline_at)}}function YF($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function zH($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
48
+ `;return XF(J)}joinable(){if(this.connection===void 0)return;let $=$$();if($===void 0||g$()!==this.connection)return;return $}q(){return this.joinable()??this.sql}name($){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Z){let J=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${J} AS SIGNED)`:$`CAST(${J} AS BIGINT)`}}function B8($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function F8($){return $===void 0||$===null?null:JSON.stringify($)}function V8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function V2($){return $===null||$===void 0?null:Number($)}function zF($){return $===null||$===void 0?null:String($)}function U2($){return{id:String($.id),kind:String($.kind),subject:zF($.subject),owner:zF($.owner),status:String($.status),meta:V8($.meta),progress:V8($.progress),result:V8($.result),error:V8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:V2($.started_at),updatedAt:Number($.updated_at),finishedAt:V2($.finished_at),deadlineAt:V2($.deadline_at)}}function XF($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function QH($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
49
49
  \`id\` VARCHAR(191) NOT NULL,
50
50
  \`kind\` VARCHAR(191) NOT NULL,
51
51
  \`subject\` VARCHAR(191) NULL,
@@ -83,6 +83,6 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
83
83
  "updated_at" BIGINT NOT NULL,
84
84
  "finished_at" BIGINT,
85
85
  "deadline_at" BIGINT${W}
86
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var jF=191,zF=30000;class U8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class D8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class D2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=M$(JF(),$),this.store=QH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(e3);return this.ownFeed??=new e3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){QF("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;QF("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:QZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return GH(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:GF(Z)})}cancel($,Z){return this.change($,I1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new U8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof D8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,I1,{status:"failed",error:G instanceof D8?GF(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+QZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new U8($);let z=null;for(;;){if(x1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await XF(z,Math.min(G,X??1/0,zF),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new U8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=XH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=QZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(x1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,XF(j,Math.min(z??1/0,zF))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function XF($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function XH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function GF($){if(typeof $==="string")return{message:$};if($ instanceof D8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function QF($,Z){if(typeof Z!=="string"||Z===""||Z.length>jF)throw TypeError(`A run's ${$} is a string of 1 to ${jF} characters; got ${JSON.stringify(Z)}.`)}function GH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function QH($,Z){if($==="memory")return new Q2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(y$).connection();return new U2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class BF extends h{static getFacadeAccessor(){return D2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class FF extends h{static getFacadeAccessor(){return e1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class O2{value;constructor($){this.value=$}}var BH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function FH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!BH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class M8{bound;constructor($){this.bound=$}get name(){return this.bound??g$()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return L8(J.sql,(W)=>O8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=FH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if($$()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await L8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await OF();let G=await O8(j,()=>W(X));throw new O2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof O2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-6ttbhhnn.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return LF($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=HF($,MF(J.dialect),Z),j=this.handle();if(j===void 0&&DF()){let z=this.name;return L8(J.sql,(X)=>O8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}if(j===void 0)return J.sql.unsafe(W,Y);return j.unsafe(W,Y).catch((z)=>{throw UF(j),z})}handle(){let $=$$();if($===void 0)return;return g$()===this.name?$:void 0}connection($=this.name){return VF($),H(y$).connection($)}}var K$=new M8;class TF extends h{static getFacadeAccessor(){return y$}static connection($){return new M8($)}static get sql(){return K$.sql}static get dialect(){return K$.dialect}static query($){return K$.query($)}static execute($){return K$.execute($)}static transaction($){return K$.transaction($)}static withSettings($,Z){return K$.withSettings($,Z)}static readOnly($,Z){return K$.readOnly($,Z)}static schema(){return K$.schema()}static close(){return this.getFacadeRoot().close()}}export{V1 as Te,CF as Ue,r0 as Ve,z3 as We,_8 as Xe,x0 as Ye,z6 as Ze,s8 as _e,n8 as $e,w9 as af,r1 as bf,D1 as cf,k$ as df,Z0 as ef,F9 as ff,OZ as gf,f9 as hf,q9 as if,a8 as jf,t8 as kf,N6 as lf,TZ as mf,i9 as nf,uV as of,s9 as pf,lV as qf,qN as rf,a9 as sf,YY as tf,j7 as uf,jY as vf,zY as wf,eV as xf,XY as yf,z7 as zf,JU as Af,WU as Bf,X7 as Cf,GY as Df,QY as Ef,e1 as Ff,BY as Gf,XU as Hf,Q7 as If,f8 as Jf,U6 as Kf,S1 as Lf,R8 as Mf,b1 as Nf,N$ as Of,Q8 as Pf,hB as Qf,pB as Rf,$H as Sf,d1 as Tf,uS as Uf,cB as Vf,Z2 as Wf,J2 as Xf,Y2 as Yf,lB as Zf,sB as _f,nB as $f,aB as ag,rB as bg,eB as cg,$F as dg,i as eg,G3 as fg,y4 as gg,PK as hg,NK as ig,KK as jg,CK as kg,MG as lg,q5 as mg,PG as ng,RK as og,_G as pg,c0 as qg,c3 as rg,IG as sg,ZF as tg,bb as ug,G2 as vg,I1 as wg,x1 as xg,Q2 as yg,U2 as zg,zH as Ag,U8 as Bg,D8 as Cg,D2 as Dg,BF as Eg,FF as Fg,M8 as Gg,TF as Hg,y5 as Ig,YL as Jg,i5 as Kg,s5 as Lg,u_ as Mg,sG as Ng,tG as Og,G6 as Pg,n1 as Qg,jI as Rg,eG as Sg,$Q as Tg,SQ as Ug,LW as Vg,eZ as Wg,MW as Xg,YC as Yg,VC as Zg,UC as _g,IM as $g,vW as ah,AM as bh,uW as ch,kM as dh,mW as eh,qM as fh,t3 as gh,nW as hh,AB as ih,W8 as jh,j8 as kh,sA as lh,nA as mh,oA as nh,Q1 as oh,E as ph,f0 as qh,Q6 as rh,s2 as sh,pF as th,u2 as uh,o2 as vh,S8 as wh,F6 as xh,b8 as yh,a2 as zh,nF as Ah,oF as Bh,J9 as Ch,Y9 as Dh,z9 as Eh,U9 as Fh,D9 as Gh,O9 as Hh,y8 as Ih,ZV as Jh,j0 as Kh,C9 as Lh,MZ as Mh,R9 as Nh};
86
+ )`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var GF=191,QF=30000;class U8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class D8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class O2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=M$(jF(),$),this.store=VH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(e3);return this.ownFeed??=new e3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){VF("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;VF("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:BZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return FH(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:FF(Z)})}cancel($,Z){return this.change($,I1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new U8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof D8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,I1,{status:"failed",error:G instanceof D8?FF(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+BZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new U8($);let z=null;for(;;){if(x1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await BF(z,Math.min(G,X??1/0,QF),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new U8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=BH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=BZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(x1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,BF(j,Math.min(z??1/0,QF))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function BF($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function BH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function FF($){if(typeof $==="string")return{message:$};if($ instanceof D8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function VF($,Z){if(typeof Z!=="string"||Z===""||Z.length>GF)throw TypeError(`A run's ${$} is a string of 1 to ${GF} characters; got ${JSON.stringify(Z)}.`)}function FH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function VH($,Z){if($==="memory")return new B2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(y$).connection();return new D2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class UF extends h{static getFacadeAccessor(){return O2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class DF extends h{static getFacadeAccessor(){return e1}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class L2{value;constructor($){this.value=$}}var UH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function DH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!UH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class M8{bound;constructor($){this.bound=$}get name(){return this.bound??g$()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return L8(J.sql,(W)=>O8(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=DH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if($$()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await L8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await HF();let G=await O8(j,()=>W(X));throw new L2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof L2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-6ttbhhnn.js");return Z(this.handle()??$.sql,$.dialect)}async withSettings($,Z){let J=this.connection();if(J.dialect!=="postgres")throw Error(`DB.withSettings is supported on Postgres only, and the "${J.name}" connection is ${J.dialect}.`);return TF($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=NF($,PF(J.dialect),Z),j=this.handle();if(j===void 0&&MF()){let z=this.name;return L8(J.sql,(X)=>O8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}if(j===void 0)return J.sql.unsafe(W,Y);return j.unsafe(W,Y).catch((z)=>{throw LF(j),z})}handle(){let $=$$();if($===void 0)return;return g$()===this.name?$:void 0}connection($=this.name){return OF($),H(y$).connection($)}}var K$=new M8;class KF extends h{static getFacadeAccessor(){return y$}static connection($){return new M8($)}static get sql(){return K$.sql}static get dialect(){return K$.dialect}static query($){return K$.query($)}static execute($){return K$.execute($)}static transaction($){return K$.transaction($)}static withSettings($,Z){return K$.withSettings($,Z)}static readOnly($,Z){return K$.readOnly($,Z)}static schema(){return K$.schema()}static close(){return this.getFacadeRoot().close()}}export{V1 as Te,bF as Ue,r0 as Ve,X3 as We,_8 as Xe,x0 as Ye,z6 as Ze,s8 as _e,n8 as $e,f9 as af,r1 as bf,D1 as cf,k$ as df,Z0 as ef,V9 as ff,LZ as gf,q9 as hf,v9 as if,a8 as jf,t8 as kf,N6 as lf,PZ as mf,s9 as nf,sV as of,n9 as pf,nV as qf,yN as rf,t9 as sf,jY as tf,j7 as uf,zY as vf,XY as wf,JU as xf,GY as yf,z7 as zf,jU as Af,zU as Bf,X7 as Cf,QY as Df,BY as Ef,e1 as Ff,FY as Gf,BU as Hf,Q7 as If,f8 as Jf,U6 as Kf,S1 as Lf,R8 as Mf,b1 as Nf,N$ as Of,Q8 as Pf,dB as Qf,uB as Rf,WH as Sf,d1 as Tf,oS as Uf,lB as Vf,J2 as Wf,W2 as Xf,j2 as Yf,nB as Zf,aB as _f,tB as $f,eB as ag,ZF as bg,JF as cg,WF as dg,i as eg,Q3 as fg,y4 as gg,_K as hg,IK as ig,xK as jg,bK as kg,HG as lg,q5 as mg,NG as ng,fK as og,IG as pg,c0 as qg,d3 as rg,xG as sg,YF as tg,fb as ug,Q2 as vg,I1 as wg,x1 as xg,B2 as yg,D2 as zg,QH as Ag,U8 as Bg,D8 as Cg,O2 as Dg,UF as Eg,DF as Fg,M8 as Gg,KF as Hg,y5 as Ig,XL as Jg,i5 as Kg,s5 as Lg,s_ as Mg,nG as Ng,rG as Og,G6 as Pg,n1 as Qg,GI as Rg,$Q as Sg,ZQ as Tg,bQ as Ug,LW as Vg,eZ as Wg,MW as Xg,XC as Yg,OC as Zg,LC as _g,AM as $g,vW as ah,EM as bh,uW as ch,qM as dh,mW as eh,yM as fh,t3 as gh,nW as hh,SB as ih,W8 as jh,j8 as kh,aA as lh,tA as mh,rA as nh,Q1 as oh,E as ph,f0 as qh,Q6 as rh,n2 as sh,uF as th,l2 as uh,a2 as vh,S8 as wh,F6 as xh,b8 as yh,t2 as zh,tF as Ah,rF as Bh,W9 as Ch,j9 as Dh,X9 as Eh,D9 as Fh,O9 as Gh,L9 as Hh,y8 as Ih,YV as Jh,j0 as Kh,A9 as Lh,HZ as Mh,k9 as Nh};
87
87
 
88
- //# debugId=C044ADEC3EB1950264756E2164756E21
88
+ //# debugId=E73A9F254A3E775364756E2164756E21