gemi 0.208.0 → 0.210.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 (57) hide show
  1. package/dist/{chunk-f0sfh1r2.js → chunk-8b2421h0.js} +2 -2
  2. package/dist/{chunk-f0sfh1r2.js.map → chunk-8b2421h0.js.map} +1 -1
  3. package/dist/{chunk-rffpqhn8.js → chunk-9zatr0vt.js} +1 -1
  4. package/dist/chunk-m60st4nt.js +24 -0
  5. package/dist/{chunk-ykh78bct.js.map → chunk-m60st4nt.js.map} +6 -5
  6. package/dist/{chunk-ag5nhjcr.js → chunk-p507sdj8.js} +1 -1
  7. package/dist/{chunk-24z18t5q.js → chunk-w8cbs1kg.js} +26 -26
  8. package/dist/{chunk-24z18t5q.js.map → chunk-w8cbs1kg.js.map} +6 -5
  9. package/dist/chunks/{RealtimeClient-DIxu38Vp.js → RealtimeClient-CuTFz0v1.js} +2 -2
  10. package/dist/chunks/{RealtimeClient-DIxu38Vp.js.map → RealtimeClient-CuTFz0v1.js.map} +1 -1
  11. package/dist/chunks/{ThemeProvider-DwBG9z7t.js → ThemeProvider-BO3sQkWl.js} +212 -11
  12. package/dist/chunks/ThemeProvider-BO3sQkWl.js.map +1 -0
  13. package/dist/chunks/{fetchFileRequest-DbtCribY.js → fetchFileRequest-CrKd0rD5.js} +2 -2
  14. package/dist/chunks/{fetchFileRequest-DbtCribY.js.map → fetchFileRequest-CrKd0rD5.js.map} +1 -1
  15. package/dist/chunks/{live-Dw8WcP_Q.js → live-BCCfTb28.js} +3 -3
  16. package/dist/chunks/{live-Dw8WcP_Q.js.map → live-BCCfTb28.js.map} +1 -1
  17. package/dist/chunks/{mutationExtras-BHBySXVs.js → mutationExtras-cPXZS6Hf.js} +2 -2
  18. package/dist/chunks/{mutationExtras-BHBySXVs.js.map → mutationExtras-cPXZS6Hf.js.map} +1 -1
  19. package/dist/chunks/{subscriptionStream-CdYxY-Q6.js → subscriptionStream-CRrAISl8.js} +2 -2
  20. package/dist/chunks/{subscriptionStream-CdYxY-Q6.js.map → subscriptionStream-CRrAISl8.js.map} +1 -1
  21. package/dist/client/ClientRouter.d.ts.map +1 -1
  22. package/dist/client/ComponentContext.d.ts.map +1 -1
  23. package/dist/client/Mutation.d.ts +7 -0
  24. package/dist/client/Mutation.d.ts.map +1 -1
  25. package/dist/client/QueryManagerContext.d.ts +12 -0
  26. package/dist/client/QueryManagerContext.d.ts.map +1 -1
  27. package/dist/client/QueryResource.d.ts +54 -0
  28. package/dist/client/QueryResource.d.ts.map +1 -1
  29. package/dist/client/chunkLoadRecovery.d.ts +24 -1
  30. package/dist/client/chunkLoadRecovery.d.ts.map +1 -1
  31. package/dist/client/index.d.ts +1 -0
  32. package/dist/client/index.d.ts.map +1 -1
  33. package/dist/client/index.js +86 -16
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/queryEffects.d.ts +5 -1
  36. package/dist/client/queryEffects.d.ts.map +1 -1
  37. package/dist/client/requestTimeout.d.ts +29 -0
  38. package/dist/client/requestTimeout.d.ts.map +1 -0
  39. package/dist/client/useMutation.d.ts +8 -1
  40. package/dist/client/useMutation.d.ts.map +1 -1
  41. package/dist/client/useQuery.d.ts +15 -0
  42. package/dist/client/useQuery.d.ts.map +1 -1
  43. package/dist/facades/index.js +1 -1
  44. package/dist/http/index.js +1 -1
  45. package/dist/i18n/index.js +1 -1
  46. package/dist/kernel/index.js +1 -1
  47. package/dist/server/assetFallback.d.ts +46 -0
  48. package/dist/server/assetFallback.d.ts.map +1 -0
  49. package/dist/server/httpProd.d.ts.map +1 -1
  50. package/dist/server/index.js +1 -1
  51. package/dist/services/index.js +1 -1
  52. package/dist/testing/index.js +2 -2
  53. package/package.json +1 -1
  54. package/dist/chunk-ykh78bct.js +0 -24
  55. package/dist/chunks/ThemeProvider-DwBG9z7t.js.map +0 -1
  56. /package/dist/{chunk-rffpqhn8.js.map → chunk-9zatr0vt.js.map} +0 -0
  57. /package/dist/{chunk-ag5nhjcr.js.map → chunk-p507sdj8.js.map} +0 -0
@@ -1,26 +1,26 @@
1
1
  // @bun
2
- import{Uh as TV}from"./chunk-3wsmgdcr.js";import{mi as KV}from"./chunk-101rvvje.js";import{Ai as DB,Aj as XZ,Bi as pW,Bj as GZ,Di as Z3,Dj as oB,Ei as Z8,Fi as tW,Fj as aB,Gi as C2,Hi as u,Ji as S8,Ki as R$,Li as m2,Mi as A2,Ni as S2,Oi as X6,Pi as A,Qi as IW,Ri as o8,Si as LZ,Ti as E8,Ui as O6,Wi as w$,Xi as h,Yi as n4,fj as D6,lj as L6,ni as B3,ri as MB,si as j9,ti as z9,tj as k1,ui as A8,vi as _8,yi as I8,zi as x8,zj as nG}from"./chunk-wy87gc0b.js";import{Ij as e1,Jj as q0,Kj as Z$,Lj as G9}from"./chunk-xt90xbes.js";import{Mj as WZ,Nj as eW,Rj as t9,Sj as J8,Tj as P}from"./chunk-w92n83g2.js";import{_j as gG,bk as i3}from"./chunk-q634cwbc.js";import{fk as BY,ik as dB}from"./chunk-mxedsqbe.js";import{Ak as k$,Fk as $$}from"./chunk-r5ggnywk.js";import{Tk as HG}from"./chunk-y16vp7yf.js";import{Uk as QZ,Xk as hB}from"./chunk-n65hk6bq.js";import{Yk as _1}from"./chunk-094hbhc8.js";import{$k as f1,Zk as B6,_k as s0,al as H8,bl as DV,dl as iZ,el as sB,nl as K8,pl as LV,ql as MV,rl as HV}from"./chunk-9qyedsvw.js";import{Gl as q1}from"./chunk-h1f4f9wx.js";import{Ll as cW,Ql as uW}from"./chunk-1vnbw1d8.js";import{Xl as dW,am as c}from"./chunk-qc7x8q1q.js";import{bm as $3,em as H}from"./chunk-p608rrfc.js";import{mm as qW}from"./chunk-jggtz103.js";import{nm as tB}from"./chunk-ad0dx73f.js";import{Bm as EW}from"./chunk-mtf5kzza.js";import{Cm as B8,Em as HB}from"./chunk-vrpsgq3x.js";import{Jm as W8}from"./chunk-a76a7869.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),AV=new Set([301,302,303,307,308]);class U1{kind;body;status;headers;[N2]=!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 P2(J,"json"),new U1("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 U1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!AV.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 U1("empty",void 0,J,Y)}static noContent($={}){return new U1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new U1("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 P2($,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 a1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function SV($,Z,J={}){return U1.error($,Z,J)}function e0($){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 EV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){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":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function bV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(EV($))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 C8($,Z){if($ instanceof Response)return $;if(!$)return _2();let J=await bV($),{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 _2()}let{range:G}=Z;if(G){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=_8(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,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",I8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",j6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.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:V,headers:F})}return new Response(W,{status:V,headers:F})}function RV($){return Y6($)}function I2($,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(!RV(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 I2(Z[this.methodName].bind(Z),$)}return I2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class E2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of C2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new S8(A2($.rawRequest));throw J}}}class b2{constructor(...$){return new n(...$)}}class R2 extends n{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=A8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(a1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class k2{constructor(...$){return new R2(...$)}}class w2{__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=[];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 w2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${x2($)}.`);return kV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${x2($)}.`);return wV($)}file($,Z){return new b2("GET",$,Z)}stream($,Z){return new k2("GET",$,Z)}proxy($,Z={}){return new E2($,Z)}}function x2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function kV($){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 wV($){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 t1="access_token";function b$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=b$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var fV=/^[A-Za-z0-9_-]+$/,qV=/^:[A-Za-z_][A-Za-z0-9_]*$/,f2=/^[A-Za-z0-9_-]{1,128}$/,vV=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function q2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function FZ($){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(qV.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(!fV.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=FZ($),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"||!f2.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 b8($){if(FZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function v2($){if(typeof $!=="string"||$.length===0||$.length>64||!vV.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function g2($,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(":")&&f2.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??R$("50mb"):R$(Z);return X6(this.req.rawRequest,J),{}}}function gV($){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 yV($){return{"body-limit":G6.configure({uploadLimit:$})}}class r1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:R$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=R$($.uploadBodyLimit??"50mb"),this.builtinAliases=yV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||m2($))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 gV($).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:y2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:y2(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 mV(W.slice(j+1)),z}return Y})()}}function y2($){return $?.runsOnRefusal===!0}async function mV($){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,...e0($)],this}events(...$){return this}}class c2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{cV(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(!u2(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 P.exit(()=>B6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H(r1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await h2(X);if(!Q)return{ok:!1,code:"denied"};if(j=UZ(Q),Y.visibility==="private"&&Y.authorizer){if(await p2(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 p2(Y.authorizer,X,z):await h2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(dV(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 hV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;l2(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 u2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function h2($){if(!P.getStore().user&&b$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function p2($,Z,J){if(pV($))return new $().authorize(Z,J);return $(Z,J)}function pV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function dV($){return $?.kind===e1||$$($)||k$($)}var d2=new WeakSet;function cV($){if(d2.has($))return;l2($),d2.add($)}function l2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!u2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=FZ(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(uV(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 uV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class V6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function lV($){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 iV($,Z){let J=lV($);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 i2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new V6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...K}=Y[U],N=D??(O?iV(W,O):W);if(B.has(N))throw Error(`${Q}: the audiences "${B.get(N)}" and "${U}" are both named "${N}". Give one its own name or casing.`);B.set(N,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,...K,description:R};if(z||M)C.params={...z,...M};if(X||T)C.files={...X,...T};F[N]=new V6($,Z,C)}return F}}function O0($,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 w8 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 b1{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 w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class s2{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 b1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,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 n2{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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function o2($,Z){if(a1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class a2{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=o2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class t2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends R1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends R1{routes=J??{}}}else this.children=class extends R1{routes=Z},this.handler=()=>({})}async run($,Z){let J=o2(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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R1{middlewares=[];featureGates=[];routes={};view($,Z){return new a2($,Z)}file($){return new n2($)}redirect($){return new s2($)}layout($,Z,J){return new t2($,Z,J)}}function sV($){return $}function nV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function O1($,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 q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function oV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function aV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(b).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=oV($,!W);if(W||!aV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class r2 extends Z0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(b),J);if(!W)throw new w$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class U6 extends Z0{run(){let $=P.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(g8))return{};if(b$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new e2(`${W.pathname}${W.search}`)}}class e2 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=tV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},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 tV($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class $9 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 J9 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]};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 rV="Rate limit exceeded";class J$ extends q0{result;retryAfter;constructor($,Z=rV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...Z$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){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(W9("window",W),W9("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 J$(W,typeof J==="function"?J(W):J);return W}}function W9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function f$($){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 m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class X9 extends Z0{async run($,Z){let J=eV();if(!J)return{};let W=await J.consume(this.key(),{limit:Y9($)??this.config.limit,window:Y9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new J$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=j9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function eV(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function DZ($){let Z=z9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return f$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function Y9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class Q9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:G9("csrf","Invalid CSRF token",403)}},view:{}}}class B9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class V9{all($,Z){return!0}}class p8{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 O6}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 O6}}function $F($){return new p8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await UF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return FF(z,Z,J,$.url)}async function FF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new L6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.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 UF($){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 OF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function q$($){return $.replace(/[&<>"']/g,(Z)=>OF[Z])}var DF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function d8($){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 DF[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 c8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function F9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(d8($.slice(W)));return}if(Y>W)Z.text(d8($.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(c8($.slice(Y+2,j).trim())),W=j+1}else{let j=LF($,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=c8(z.slice(0,G));if(Q){if(Z.open(Q,MF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function LF($,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 MF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[c8(W[1])]=d8(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 M9="http://www.sitemaps.org/schemas/sitemap/0.9",HF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
3
- `,U9=`<urlset xmlns="${M9}" xmlns:xhtml="${HF}">
4
- `,O9=`</urlset>
5
- `,v$=50000,Q3=52428800,D9=2048,KF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),TF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,PF="application/xml; charset=utf-8",L9=new TextEncoder;function s8($,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>D9)throw new j0(`Sitemap: ${Z} is over ${D9} characters: "${W.slice(0,80)}\u2026".`);return W}function H9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!TF.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 NF($){let Z=s8($.loc,"loc"),J=`<url><loc>${q$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${q$(H9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!KF.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=s8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${q$(Y)}" href="${q$(j)}"/>`}return`${J}</url>
6
- `}function _F($){let Z=$.maxUrls??v$,J=$.maxBytes??Q3;if(!Number.isInteger(Z)||Z<1||Z>v$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${v$}.`);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 K9($,Z={}){let{maxUrls:J,maxBytes:W}=_F(Z),Y=L9.encode(i8+U9+O9).byteLength,j=[],z=[],X=Y,G=()=>{j.push(i8+U9+z.join("")+O9),z=[],X=Y};for(let Q of $){let V=NF(Q),F=L9.encode(V).byteLength;if(Y+F>W)throw new j0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+F>W)G();z.push(V),X+=F}if(z.length>0||j.length===0)G();return j}function T9($){let Z="",J=0;for(let W of $){if(++J>v$)throw new j0(`Sitemap: an index can list at most ${v$} sitemaps.`);let Y=s8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${q$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${q$(H9(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
- `}return`${i8}<sitemapindex xmlns="${M9}">
2
+ import{Uh as _V}from"./chunk-3wsmgdcr.js";import{mi as KV}from"./chunk-101rvvje.js";import{Ai as HB,Aj as XZ,Bi as dW,Bj as GZ,Di as Z3,Dj as rB,Ei as Z8,Fi as rW,Fj as eB,Gi as A2,Hi as u,Ji as S8,Ki as R$,Li as h2,Mi as S2,Ni as E2,Oi as X6,Pi as A,Qi as IW,Ri as o8,Si as LZ,Ti as E8,Ui as O6,Wi as w$,Xi as h,Yi as n4,fj as D6,lj as L6,ni as B3,ri as PB,si as z9,ti as X9,tj as k1,ui as A8,vi as _8,yi as I8,zi as x8,zj as oG}from"./chunk-wy87gc0b.js";import{Ij as e1,Jj as q0,Kj as Z$,Lj as Q9}from"./chunk-xt90xbes.js";import{Mj as WZ,Nj as $2,Rj as r9,Sj as J8,Tj as N}from"./chunk-w92n83g2.js";import{_j as yG,bk as i3}from"./chunk-q634cwbc.js";import{fk as VY,ik as lB}from"./chunk-mxedsqbe.js";import{Ak as k$,Fk as $$}from"./chunk-r5ggnywk.js";import{Tk as TG}from"./chunk-y16vp7yf.js";import{Uk as QZ,Xk as cB}from"./chunk-n65hk6bq.js";import{Yk as _1}from"./chunk-094hbhc8.js";import{$k as f1,Zk as B6,_k as s0,al as H8,bl as HV,dl as iZ,el as aB,nl as T8,pl as TV,ql as PV,rl as NV}from"./chunk-9qyedsvw.js";import{Gl as q1}from"./chunk-h1f4f9wx.js";import{Ll as uW,Ql as lW}from"./chunk-1vnbw1d8.js";import{Xl as cW,am as c}from"./chunk-qc7x8q1q.js";import{bm as $3,em as H}from"./chunk-p608rrfc.js";import{mm as vW}from"./chunk-jggtz103.js";import{nm as $V}from"./chunk-ad0dx73f.js";import{Bm as bW}from"./chunk-mtf5kzza.js";import{Cm as B8,Em as NB}from"./chunk-vrpsgq3x.js";import{Jm as W8}from"./chunk-a76a7869.js";function Y6($){return typeof $==="function"&&$.prototype!==void 0}var _2=Symbol.for("gemi.HttpResponse"),bV=new Set([301,302,303,307,308]);class U1{kind;body;status;headers;[_2]=!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 K2(J,"json"),new U1("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 U1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!bV.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 U1("empty",void 0,J,Y)}static noContent($={}){return new U1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return K2(J,"text"),new U1("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 K2($,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 a1($){return typeof $==="object"&&$!==null&&$[_2]===!0}function RV($,Z,J={}){return U1.error($,Z,J)}function e0($){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 kV($){return"total"in $&&"partial"in $&&"body"in $}function I2(){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":x8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function wV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(kV($))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 C8($,Z){if($ instanceof Response)return $;if(!$)return I2();let J=await wV($),{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 I2()}let{range:G}=Z;if(G){if(z<=0)return X3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=_8(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,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",I8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",j6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.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:V,headers:F})}return new Response(W,{status:V,headers:F})}function fV($){return Y6($)}function x2($,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(!fV(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 x2(Z[this.methodName].bind(Z),$)}return x2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class b2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new A,Z=$.headers.toJSON();for(let J of A2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(E2($.rawRequest))throw new S8(S2($.rawRequest));throw J}}}class R2{constructor(...$){return new n(...$)}}class k2 extends n{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),J=Z?.req?.rawRequest,W=A8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(a1(Y))return Y;return await C8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return X3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class w2{constructor(...$){return new k2(...$)}}class f2{__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=[];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 f2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${C2($)}.`);return qV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${C2($)}.`);return vV($)}file($,Z){return new R2("GET",$,Z)}stream($,Z){return new w2("GET",$,Z)}proxy($,Z={}){return new b2($,Z)}}function C2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function qV($){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 vV($){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 t1="access_token";function b$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function z6($,Z){let J=b$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var gV=/^[A-Za-z0-9_-]+$/,yV=/^:[A-Za-z_][A-Za-z0-9_]*$/,q2=/^[A-Za-z0-9_-]{1,128}$/,mV=/^[A-Za-z0-9_.:-]+$/;class i extends Error{constructor($){super($);this.name="InvalidChannelError"}}function v2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function FZ($){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(yV.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(!gV.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=FZ($),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"||!q2.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 b8($){if(FZ($).some((J)=>J.startsWith(":")))throw new i(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function g2($){if(typeof $!=="string"||$.length===0||$.length>64||!mV.test($))throw new i(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function y2($,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(":")&&q2.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??R$("50mb"):R$(Z);return X6(this.req.rawRequest,J),{}}}function hV($){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 pV($){return{"body-limit":G6.configure({uploadLimit:$})}}class r1{config;static token="middleware";defaultBodyLimit;uploadBodyLimit;builtinAliases;constructor($){this.config=$;let Z=$.bodyLimit===null||$.bodyLimit===void 0?null:R$($.bodyLimit);this.defaultBodyLimit=Z===1/0?null:Z,this.uploadBodyLimit=R$($.uploadBodyLimit??"50mb"),this.builtinAliases=pV(this.uploadBodyLimit)}get aliases(){return{...this.builtinAliases,...this.config.aliases}}applyDefaultBodyLimit($,Z){if(this.defaultBodyLimit===null||Z==="none"||h2($))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 hV($).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:m2(z)})}}else if(Y6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:m2(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 dV(W.slice(j+1)),z}return Y})()}}function m2($){return $?.runsOnRefusal===!0}async function dV($){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,...e0($)],this}events(...$){return this}}class u2{static __brand="ChannelRouter";channels={};public(){return new Q6("public")}private($){return new Q6("private",$)}async authorize($,Z,J={},W={}){try{iV(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(!l2(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(r1).runMiddleware(Y.middlewares);if(Z===U0){let Q=await p2(X);if(!Q)return{ok:!1,code:"denied"};if(j=UZ(Q),Y.visibility==="private"&&Y.authorizer){if(await d2(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 d2(Y.authorizer,X,z):await p2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(lV(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 cV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;i2(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 l2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function p2($){if(!N.getStore().user&&b$($)===null)return null;try{return await f0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function d2($,Z,J){if(uV($))return new $().authorize(Z,J);return $(Z,J)}function uV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function lV($){return $?.kind===e1||$$($)||k$($)}var c2=new WeakSet;function iV($){if(c2.has($))return;i2($),c2.add($)}function i2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!l2(Y))throw new i(`The channel "${W}" is not declared with this.public() or this.private().`);let j=FZ(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(sV(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 sV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class V6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function nV($){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 oV($,Z){let J=nV($);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 s2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new V6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...P}=Y[U],K=D??(O?oV(W,O):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};F[K]=new V6($,Z,C)}return F}}function O0($,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 w8 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 b1{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 w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class n2{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 b1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,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 o2{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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function a2($,Z){if(a1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class t2{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=a2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class r2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends R1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends R1{routes=J??{}}}else this.children=class extends R1{routes=Z},this.handler=()=>({})}async run($,Z){let J=a2(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=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class R1{middlewares=[];featureGates=[];routes={};view($,Z){return new t2($,Z)}file($){return new o2($)}redirect($){return new n2($)}layout($,Z,J){return new r2($,Z,J)}}function aV($){return $}function tV(){return{aliases:{},global:[],bodyLimit:"1mb",uploadBodyLimit:"50mb"}}var l0="redirect";function O1($,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 q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function rV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function eV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function F6($,Z){let J=Z||H(b).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=rV($,!W);if(W||!eV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class e2 extends Z0{async run($){let Z=N.getStore(),J=Z.req;if(Z.user)return{};let W=await z6(H(b),J);if(!W)throw new w$({redirectTo:F6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="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(g8))return{};if(b$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new $9(`${W.pathname}${W.search}`)}}class $9 extends q0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=$F($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},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 $F($){return $.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class Z9 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 W9 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]};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 ZF="Rate limit exceeded";class J$ extends q0{result;retryAfter;constructor($,Z=ZF){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...Z$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){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(Y9("window",W),Y9("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 J$(W,typeof J==="function"?J(W):J);return W}}function Y9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function f$($){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 m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class G9 extends Z0{async run($,Z){let J=JF();if(!J)return{};let W=await J.consume(this.key(),{limit:j9($)??this.config.limit,window:j9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new J$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=z9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${DZ(this.req)}:${this.req.routePath??"*"}`}}function JF(){try{let $=H();return $.bound(D1)?$.make(D1):null}catch{return null}}function DZ($){let Z=X9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return f$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function j9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class B9 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends q0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:Q9("csrf","Invalid CSRF token",403)}},view:{}}}class V9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class F9{all($,Z){return!0}}class p8{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 O6}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 O6}}function WF($){return new p8($)}async function M6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await LF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return DF(z,Z,J,$.url)}async function DF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new L6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.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 LF($){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 MF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function q$($){return $.replace(/[&<>"']/g,(Z)=>MF[Z])}var HF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function d8($){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 HF[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 c8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function U9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(d8($.slice(W)));return}if(Y>W)Z.text(d8($.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(c8($.slice(Y+2,j).trim())),W=j+1}else{let j=TF($,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=c8(z.slice(0,G));if(Q){if(Z.open(Q,PF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function TF($,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 PF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[c8(W[1])]=d8(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 H9="http://www.sitemaps.org/schemas/sitemap/0.9",NF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
3
+ `,O9=`<urlset xmlns="${H9}" xmlns:xhtml="${NF}">
4
+ `,D9=`</urlset>
5
+ `,v$=50000,Q3=52428800,L9=2048,KF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),_F=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,IF="application/xml; charset=utf-8",M9=new TextEncoder;function s8($,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>L9)throw new j0(`Sitemap: ${Z} is over ${L9} characters: "${W.slice(0,80)}\u2026".`);return W}function T9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new j0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!_F.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 xF($){let Z=s8($.loc,"loc"),J=`<url><loc>${q$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${q$(T9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!KF.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=s8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${q$(Y)}" href="${q$(j)}"/>`}return`${J}</url>
6
+ `}function CF($){let Z=$.maxUrls??v$,J=$.maxBytes??Q3;if(!Number.isInteger(Z)||Z<1||Z>v$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${v$}.`);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 P9($,Z={}){let{maxUrls:J,maxBytes:W}=CF(Z),Y=M9.encode(i8+O9+D9).byteLength,j=[],z=[],X=Y,G=()=>{j.push(i8+O9+z.join("")+D9),z=[],X=Y};for(let Q of $){let V=xF(Q),F=M9.encode(V).byteLength;if(Y+F>W)throw new j0(`Sitemap: the entry for ${Q.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+F>W)G();z.push(V),X+=F}if(z.length>0||j.length===0)G();return j}function N9($){let Z="",J=0;for(let W of $){if(++J>v$)throw new j0(`Sitemap: an index can list at most ${v$} sitemaps.`);let Y=s8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${q$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${q$(T9(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
7
+ `}return`${i8}<sitemapindex xmlns="${H9}">
8
8
  ${Z}</sitemapindex>
9
- `}function u8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",PF);return new Response($,{status:Z,headers:W})}function IF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function xF($,Z={}){let J=K9($,Z),W=IF(Z.page);if(W!==null){let j=J[W-1];return j?u8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return u8(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 u8(T9(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function l8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function P9($,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 D=U.trim()?l8(U):null;if(D)B.push({loc:D})}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,V="",F=()=>Y==="index"?z.length:j.length;if(F9(W,{stopped:()=>F()>=J,open(B,U){let D=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"&&D==="urlset"||Y==="index"&&B==="sitemap"&&D==="sitemapindex")G={};else if(G&&(D==="url"||D==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))Q=B,V="";else if(G&&Y==="urlset"&&D==="url"&&B==="link"){let O=U.href?l8(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&O)(G.alternates??=[]).push({hrefLang:U.hreflang,href:O})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,Q&&B===Q&&G)G[Q]=V.trim(),Q=null;else if(G&&(B==="url"||B==="sitemap")){let D=G;G=null,Q=null;let O=D.loc?l8(D.loc):null;if(!O)return;if(Y==="index"){z.push(D.lastmod?{loc:O,lastmod:D.lastmod}:{loc:O});return}let L={loc:O};if(D.lastmod)L.lastmod=D.lastmod;if(D.changefreq)L.changefreq=D.changefreq;let M=D.priority?Number(D.priority):NaN;if(Number.isFinite(M))L.priority=M;if(D.alternates)L.alternates=D.alternates;j.push(L)}},text(B){if(Q)V+=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*CF($,Z={}){let{maxUrls:J=v$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=Q3,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,V=0,F=0;while(G.length>0&&F<J&&V<W){let B=G.shift(),U=B.url.replace(/#.*$/,"");if(Q.has(U))continue;Q.add(U),V++;let D;try{let O=await k1(B.url,{...X,maxSize:j});if(!O.ok)throw O.body?.cancel().catch(()=>{}),new j0(`Sitemap: ${B.url} answered ${O.status}.`,B.url,O.status);let L=H6(await M6(O,j));D=P9(L,{maxUrls:Math.max(J-F,W-V)})}catch(O){if(B.depth===0||!z||X.signal?.aborted)throw O;z(O,B.url);continue}if(D.kind==="index"){if(B.depth>=Y)continue;G=D.sitemaps.slice(0,W-V).map((L)=>({url:L.loc,depth:B.depth+1})).concat(G);continue}for(let O of D.urls)if(yield{...O,sitemap:B.url},++F>=J)return}}var N9={response:xF,chunk:K9,index:T9,parse:P9,read:CF,MAX_URLS:v$,MAX_BYTES:Q3};var AF=512000,SF=new TextEncoder;function _9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function I9($){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 SF.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function EF($,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=_9($)||"*";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=I9(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!EF(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 bF={"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 x9($,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 V=bF[G.slice(0,Q).trim().toLowerCase()],F=G.slice(Q+1).trim();if(!V)continue;if(V==="sitemap"){if(!F||/\s/.test(F))continue;try{let B=Z.url?new URL(F,Z.url):new URL(F);if(B.protocol==="http:"||B.protocol==="https:")W.push(B.href)}catch{}continue}if(V==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let B=_9(F);if(B)Y.userAgents.push(B);continue}if(!Y)continue;if(j=!1,V==="crawl-delay"){let B=Number(F);if(Number.isFinite(B)&&B>=0)Y.crawlDelay=B;continue}if(!F)continue;Y.rules.push({type:V,path:I9(F)})}return new MZ(J,W)}async function RF($,Z={}){let{maxSize:J=AF,...W}=Z,Y=new URL("/robots.txt",$),j=await k1(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 x9(G,{url:j.url})}function n8($){return $===void 0?[]:typeof $==="string"?[$]:$}function K6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
- `}function C9($){let Z=[];for(let W of $.rules??[]){let Y=n8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>K6("User-agent",X)).join(""),z=[...n8(W.allow).map((X)=>["Allow",X]),...n8(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+=K6(X,G)}if(z.length===0)j+=`Disallow:
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+=K6("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 K6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function kF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(C9($),{status:200,headers:J})}var A9={response:kF,text:C9,parse:x9,fetch:RF};import{createHmac as S9,randomBytes as wF}from"crypto";var a8="v2.";function t8($){return $.startsWith(a8)}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 E9($){let Z=wF(16).toString("hex"),J=S9("sha256",HZ()).update(`${$}:${Z}`).digest("hex");return`${a8}${J}`}function T6($,Z){let J=S9("sha256",HZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${a8}${J}`}import{createHash as vF,createHmac as gF,randomInt as yF,timingSafeEqual as k9}from"crypto";function b9($,Z){return Math.floor($/Z)*Z}function fF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function r8($,Z,J,W){return Z*fF(J,W)+$}function qF($){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 V=Y*(1-(X-Z)/J);if(V<=Y)return Math.max(0,Math.ceil(V-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 R9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let V=r8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-V)),resetAt:Y-j+z,retryAfter:0}}let Q=qF({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 e8{}class $7 extends e8{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=b9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let V=r8(G.current,G.previous,X,W)+Y<=J;if(V)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return R9({allowed:V,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 f9="h1.";function P6($,Z,J){let W=gF("sha256",HZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${f9}${W}`}function KZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(f9),X=P6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return k9(G,G),!1;return k9(G,Q)}function q9($){let Z="";for(let J=0;J<$;J++)Z+=String(yF(0,10));return Z}var v9=320;function g$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>v9)return null;return Z.toLowerCase()}function N6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>v9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var w9=null;function g9(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(D1))return $.make(D1)}catch{}return w9??=new D1({driver:new $7,limit:1000,window:60}),w9}function Z7($){return $.length<=64?$:`sha256:${vF("sha256").update($).digest("hex")}`}function mF($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function y$($,Z,J,W,Y,j){let z=g9(),X=[["perIp",`ip:${Z7(DZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${Z7(Z)}`,W.perEmail]);for(let[G,Q,V]of X){if(!V)continue;let F=Y?await Y({req:J,scope:$,limit:G}):void 0,B=mF($),U=F?`${B}:p:${Z7(String(F))}:${Q}`:`${B}:${Q}`,[D,O]=V,L=await z.consume(U,{limit:D,window:O});if(!L.allowed)throw await j?.(G),new J$(L)}}async function y9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await g9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as W7}from"crypto";class J7 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 hF,timingSafeEqual as pF}from"crypto";function h9($){let Z=$??process.env.AUTH_FIXED_CODE;return typeof Z==="string"&&Z!==""?Z:null}function p9($){if($!==void 0&&$!==null)return $===!0;return process.env.AUTH_FIXED_CODE_ALLOW_PRODUCTION==="1"}var dF="[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 d9($={},{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=h9(J);if(Y===null)return;let j=J?"auth.emailCode.fixedCode":"AUTH_FIXED_CODE",z=Bun.env.NODE_ENV==="production";if(z&&!p9(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(dF)}function cF($={}){if(Bun.env.NODE_ENV==="production"&&!p9($.allowFixedCodeInProduction))return null;return h9($.fixedCode)}function m9($){return hF("sha256").update($).digest()}function c9($,Z={}){let J=cF(Z);if(J===null||typeof $!=="string"||$==="")return!1;return pF(m9($),m9(J))}async function w1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Y7($){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 uF($={}){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 z7($={}){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),d9($),{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 lF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function u9($){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 l9($){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 pP($){return $}function i9($={}){return uF($),{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:J7,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:lF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>W7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return W7(32).toString("hex")},generateMagicLinkToken:()=>W7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:z7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var iF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),sF=new Set(["svg","math"]);function s9($){return $===32||$===9||$===10||$===12||$===13}function n9($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function o9(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,V=()=>{if(!J&&iF.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(sF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},F=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(n9(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(n9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(s9(B)||B===47)$="inTag",z=B===47;else if(B===62)V();else Z+=String.fromCharCode(_6(B));return;case"inTag":if(B===62){V();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(s9(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;F(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)F(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 a9($){return $?`<script nonce="${$}">`:"<script>"}function nF($,Z){let J=i0([$.path,$.variantKey,$.data]);return`${a9(Z)}(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${J})</script>`}function oF($,Z){let J=i0([$.id,$.locale,$.strings]);return`${a9(Z)}(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${J})</script>`}function X7($,Z,J={},W,Y){let j=new TextEncoder,z=[],X=!1,G=!1,Q=()=>{if(G)return;G=!0,J.onClose?.()};Z.onSettle((O)=>{if(O.status!=="resolved")return;z.push(nF(O,Y))}),W?.onUse((O)=>{z.push(oF(O,Y))});let V=$.getReader(),F=o9(),B=(O,L)=>{O.enqueue(L),J.onChunk?.(L)},U=(O)=>{while(z.length>0){let L=j.encode(z.shift());F.write(L),B(O,L)}},D=(O,L)=>{if(z.length===0){F.write(L),B(O,L);return}let M=F.scanToInsertionPoint(L);if(M>0)B(O,L.subarray(0,M));if(F.isSafe())U(O);let T=L.subarray(M);if(T.length>0)F.write(T),B(O,T)};return new ReadableStream({async pull(O){let L;try{L=await V.read()}catch(K){throw Q(),K}let{done:M,value:T}=L;if(M){U(O),O.close(),Q();return}if(!X){if(X=!0,F.write(T),B(O,T),J.onShell?.(),F.isSafe())U(O);return}D(O,T)},cancel(O){return Q(),V.cancel(O)}})}var aF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return aF.test($)}async function r9($,Z=()=>{}){let J=P.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 tF($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:t9(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function e9($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function tF($,Z){if(!$.context)return{};try{let J=P.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 $Y($,Z){return`${$}:${Z}`}function G7($){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 JY($,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=eF($,Z,J,W.buckets);return ZY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function rF($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function eF($,Z,J,W){let Y=$Y(Z.salt??$,rF(J));if(!W)return G7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=G7(Y);return W.set(Y,z),z}class WY 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 Q7{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 WY(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=$U(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 $U($){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 ZU{}class JU 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 B7 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 YY 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 jY{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 W${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Q7($.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{P.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new YY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=WU(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new B7(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 jY(this,e9($))}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=JY($,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 $=P.getStore();if($?.featureContext)return $.featureContext;let Z=await r9(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=P.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=P.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 WU($){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 zY($){if($===void 0)return!0;return await H(W$).enabled($)}function XY(){try{return P.getStore()?.req??null}catch{return null}}async function TZ($,Z,J=XY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=u9($[Z]);if(!W||!await zY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await w1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function GY($,Z=XY()){let J=[];for(let W of Object.keys($))if(await TZ($,W,Z))J.push(W);return J}function V7($){if($&&typeof $==="object")delete $.password;return $}function YU(){return new Proxy({},{get:($,Z)=>BY(Z)})}var QY=new WeakMap;function VY($){if($&&typeof $==="object"){for(let Z of Object.values($))VY(Z);Object.freeze($)}return $}var jU={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},zU=VY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:jU});class F7{models;constructor($=YU()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return zU}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??f1(),W=H(q1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await s0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||s0())return Y();let z=(QY.get(W)??Promise.resolve()).then(Y,Y);return QY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return V7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return V7(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?V7(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 BL}from"crypto";function v0($,Z,J,W,Y){return $1(Z,AY($,Z),J,W,Y)}function $1($,Z,J,W,Y,j){let z=M7(Z,J,W);if(Y&&Z!==z)throw RangeError(BX($,Z,J,W,j));return z}function AY($,Z){let J=$[Z];if(J===void 0)throw TypeError(iJ(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 x7($){return d$({name:$},1)}function d$($,Z){return Y1((J)=>({value:J,configurable:1,writable:!Z}),$)}function SY($){return Y1((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 Y1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function T3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function XU($,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 C7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function A7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function EY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function bY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function RY($,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 FY($){return $[0].toUpperCase()+$.substring(1)}function P3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function Y$($,Z){return Math.sign($-Z)}function M7($,Z,J){return Math.min(Math.max($,Z),J)}function g1($,Z){return[Math.floor($/Z),U3($,Z)]}function U3($,Z){return($%Z+Z)%Z}function X$($,Z){return[p6($,Z),S7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function S7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function kY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=M1[X],V=s/Q,[F,B]=X$(G,V);W+=B*Q,Y+=F}let[j,z]=X$(W,s);return[Y+j,z]}function d6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=M1[Y];W[J[Y]]=p6($,j),$=S7($,j)}return W}function wY($){return $===v?N4:[]}function fY($){return $===v?R3:[]}function qY($){return $===v?["year","day"]:[]}function vY($){if($!==void 0)return J0($)}function gY($){if($!==void 0)return j1($)}function E7($){if($!==void 0)return N3($)}function j1($){return hY(N3($))}function N3($){return mY(rU($))}function b7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function yY($,Z){if(Z==null)throw RangeError(iJ($));return Z}function m1($){if(!L0($))throw TypeError(QX);return $}function c6($,Z,J=$){if(typeof Z!==$)throw TypeError(S3(J,Z));return Z}function mY($,Z="number"){if(!Number.isInteger($))throw RangeError(_U(Z,$));return $||0}function hY($,Z="number"){if($<=0)throw RangeError(IU(Z,$));return $}function R7($){if(typeof $=="symbol")throw TypeError(SU);return String($)}function k6($,Z){return L0($)?String($):J0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(AU($));return $}function pY($,Z="number"){if(typeof $=="bigint")throw TypeError(CU(Z));if($=Number($),!Number.isFinite($))throw RangeError(xU(Z,$));return $}function C0($,Z){return Math.trunc(pY($,Z))||0}function dY($,Z){return mY(pY($,Z),Z)}function UY($,Z){return hY(C0($,Z),Z)}function k7($,Z){let[J,W]=X$(Z,s),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*s),[Y,W]}function NZ($,Z,J=1){return k7($[0]+Z[0]*J,$[1]+Z[1]*J)}function _Z($,Z){return k7($[0],$[1]+Z)}function n0($,Z){return NZ(Z,$,-1)}function S0($,Z){return Y$($[0],Z[0])||Y$($[1],Z[1])}function cY($,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]=X$($,J);return[W,Y*Z]}function uY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=s/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function o0($,Z=1,J){let[W,Y]=$,[j,z]=X$(Y,Z);return W*(s/Z)+(j+(J?z/Z:0))}function w7($,Z,J=g1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(s/Z)+j,z]}function f7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function q7($){return v0($,"isoYear",K3,H3,1),$.isoYear===K3?v0($,"isoMonth",4,12,1):$.isoYear===H3&&v0($,"isoMonth",1,9,1),$}function j$($){return h1({...$,...W1,isoHour:12}),$}function h1($){let Z=v0($,"isoYear",K3,H3,1),J=Z===K3?1:Z===H3?-1:0;return J&&a0(A0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function a0($){if(!$||cY($,jO,YO))throw RangeError(H4);return $}function G$($){return kY($,5,Q1)[1]}function i6($){let[Z,J]=g1($,s);return[d6(J,5,Q1),Z]}function lY($){return iY($)[0]}function iY($){return w7($,J1)}function E0($){return SZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function A0($){let Z=E0($);if(Z!==void 0){let[J,W]=X$(Z,y0);return[J,W*H1+($.isoMicrosecond||0)*t$+($.isoNanosecond||0)]}}function v7($,Z){let[J,W]=i6(G$($)-Z);return a0(A0({...$,isoDay:$.isoDay+W,...J}))}function w6(...$){return SZ(...$)/PX}function SZ(...$){let[Z,J]=sY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function sY($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===K3?1:$===H3?-1:0,G=new Date;return G.setUTCHours(W,Y,j,z),G.setUTCFullYear($,Z-1,J+X),[G,X]}function B$($,Z){let[J,W]=_Z($,Z);W<0&&(W+=s,J-=1);let[Y,j]=g1(W,H1),[z,X]=g1(j,t$);return s6(J*y0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-WO)/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 nY($){return[$.isoYear,$.isoMonth,$.isoDay]}function oY(){return v1}function g7($,Z){switch(Z){case 2:return y7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function aY($){return y7($)?366:365}function y7($){return $%4==0&&($%100!=0||$%400==0)}function tY($){let[Z,J]=sY($.isoYear,$.isoMonth,$.isoDay);return U3(Z.getUTCDay()-J,7)||7}function rY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function GU($){let Z=E0($);if(Z<XO)return rY($);let J=f7(B5(xZ),Z),{era:W,eraYear:Y}=Qz(J,xZ);return[W,Y]}function n6($){return c$($),o6($,1),$}function c$($){return eY($,1),$}function OY($){return bY(J5,$,eY($))}function eY($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,oY(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,g7(J,W),Z)}}function o6($,Z){return AZ(Q1,[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:yX(m1($))}function _3($,Z=0){$=z1($);let J=mX($),W=MO($,Z);return[yX($),W,J]}function m7($){return mX(z1($))}function $j($){return $=z1($),j5($,9,6,1)}function EZ($,Z,J,W=9,Y=0,j=4){Z=z1(Z);let z=j5(Z,W,Y),X=d7(Z),G=w3(Z,j),Q=k3(Z,W,Y,1);return z==null?z=Math.max(J,Q):Yj(z,Q),X=c7(X,Q,1),$&&(G=((V)=>V<4?(V+2)%4:V)(G)),[z,Q,X,G]}function a6($,Z=6,J){let W=d7($=u7($,m6)),Y=w3($,7),j=k3($,Z);return j=yY(m6,j),W=c7(W,j,void 0,J),[j,W,Y]}function h7($){return z5(z1($))}function Zj($,Z){return p7(z1($),Z)}function p7($,Z=4){let J=Wj($);return[w3($,4),...Jj(k3($,Z),J)]}function Jj($,Z){return $!=null?[M1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function d7($){let Z=$[O3];return Z===void 0?1:C0(Z,O3)}function c7($,Z,J,W){let Y=W?s:M1[Z+1];if(Y){let j=M1[Z];if(Y%(($=$1(O3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(S3(O3,$))}else $=$1(O3,$,1,J?1e9:1,1);return $}function Wj($){let Z=$[L7];if(Z!==void 0){if(typeof Z!="number"){if(R7(Z)==="auto")return;throw RangeError(S3(L7,Z))}Z=$1(L7,Math.floor(Z),0,9,1)}return Z}function z1($){return $===void 0?{}:m1($)}function u7($,Z){return typeof $=="string"?{[Z]:$}:m1($)}function z0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(QX)}}function t6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:QO[Z]})}function l7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=R7(j),j==="auto")return Y?W:null;let z=P7[j];if(z===void 0&&(z=ZO[j]),z===void 0)throw RangeError(UX($,j,P7));return $1($,z,W,J,1,b3),z}function u$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=R7(Y),z=Z[j];if(z===void 0)throw RangeError(UX($,j,Z));return z}function Yj($,Z){if(Z>$)throw RangeError(sU)}function M0($){return{branding:C4,epochNanoseconds:$}}function P0($,Z,J){return{branding:u1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:e$,calendar:Z,...p0(fX,$)}}function G0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0(W5,$)}}function h$($,Z=$.calendar){return{branding:gZ,calendar:Z,...p0(W5,$)}}function f6($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(W5,$)}}function X1($){return{branding:x4,...p0(wX,$)}}function e($){return{branding:A4,sign:V$($),...p0(eJ,$)}}function jj($){return lY($.epochNanoseconds)}function r6($){return w7($.epochNanoseconds,H1)[0]}function zj($){return uY($.epochNanoseconds,t$)}function Xj($){return uY($.epochNanoseconds)}function Gj($){return $.epochNanoseconds}function K0($){return typeof $=="string"?$:J0($.id)}function bZ($,Z){return $===Z||K0($)===K0(Z)}function Qj($,Z,J,W,Y){let j=p$(W),[z,X]=((L,M)=>{let T=M((L=u7(L,I7))[vX]),K=LO(L);return K=yY(I7,K),[K,T]})(Y,$);if(L3(Math.max(z,j),X))return DY(W,z);if(!X)throw RangeError(K4);let[G,Q,V]=Y4(Z,J,X),F=DJ(V),B=j4(V),U=LJ(V),D=B(Q,G,W),O=U(Q,G,D,z);return L3(z,X)?DY(O,z):((L,M,T,K,N,R,C)=>{let S=V$(L),[w,x]=i7(K,Z5(T,L),T,S,N,R,C),f=s7(M,w,x);return L[p[T]]+f*S})(O,F(D),z,Q,G,F,B)}function DY($,Z){return o0(D0($),M1[Z],1)}function i7($,Z,J,W,Y,j,z){let X=p[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),V=z($,Y,G);return[j(Q),j(V)]}function s7($,Z,J){let W=o0(n0(Z,J));if(!W)throw RangeError(E3);return o0(n0(Z,$))/W}function Bj($,Z){let[J,W,Y]=a6(Z,5,1);return M0($4($.epochNanoseconds,J,W,Y,1))}function Vj($,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=((V,F,B,U)=>{let D=b0(B,F),[O,L]=V(D),M=B.epochNanoseconds,T=h0(F,O),K=h0(F,L);if(cY(M,T,K))throw RangeError(E3);return Tj(s7(M,T,K),U)?K:T})(Hj,Q,Z,G);else{let V=Q.getOffsetNanosecondsFor(W);W=i$(Q,Lj(B$(W,V),z,X,G),V,2,0,1)}return P0(W,Y,j)}function Fj($,Z){return X0(Lj($,...a6(Z)),$.calendar)}function Uj($,Z){let[J,W,Y]=a6(Z,5);var j;return X1((j=Y,n7($,I3(J,W),j)[0]))}function Oj($,Z){let J=$(Z.timeZone),W=b0(Z,J),[Y,j]=Hj(W),z=o0(n0(h0(J,Y),h0(J,j)),P4,1);if(z<=0)throw RangeError(E3);return z}function Dj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(b0(X,z))))(Kj,$(J),Z);return P0(Y,J,W)}function Lj($,Z,J,W){return Mj($,I3(Z,J),W)}function Mj($,Z,J){let[W,Y]=n7($,Z,J);return h1({...s$($,Y),...W})}function n7($,Z,J){return i6(Q$(G$($),Z,J))}function q6($){return Q$($,T4,7)}function I3($,Z){return M1[$]*Z}function Hj($){let Z=Kj($);return[Z,s$(Z,1)]}function Kj($){return JO(6,$)}function QU($,Z,J){let W=Math.min(p$($),6);return kZ(Z4(D0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let V=L3(W,X)?z4(X)&&W<6&&J>=6?VU:BU:FU,[F,B,U]=V($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(F=((D,O,L,M,T,K,N,R)=>{let C=V$(D);for(let S=M+1;S<=L;S++){if(S===7&&L!==7)continue;let w=Z5(S,D);w[p[S]]+=C;let x=o0(n0(N(R(T,K,w)),O));if(x&&Math.sign(x)!==C)break;D=w}return D})(F,B,J,Math.max(6,W),z,X,G,Q)),F}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/s)($);return[Q$(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]=g1(Q$(j,Z,J),s);return k7(Y+z,X)}function Q$($,Z,J){return Tj($/Z,J)*Z}function Tj($,Z){return TO[Z]($)}function BU($,Z,J,W,Y,j){let z=V$($),X=D0($),G=$4(X,W,Y,j),Q=n0(X,G),V=Math.sign(G[0]-X[0])===z,F=kZ(G,Math.min(J,6));return[{...$,...F},NZ(Z,Q),V]}function VU($,Z,J,W,Y,j,z,X,G,Q){let V=V$($),F=o0(D0($,5)),B=I3(W,Y),U=Q$(F,B,j),[D,O]=i7(z,{...$,...$5},6,V,X,G,Q),L=U-o0(n0(D,O)),M=0;L&&Math.sign(L)!==V?Z=_Z(D,U):(M+=V,U=Q$(L,B,j),Z=_Z(O,U));let T=G4(U);return[{...$,...T,days:$.days+M},Z,Boolean(M)]}function FU($,Z,J,W,Y,j,z,X,G,Q){let V=V$($),F=p[W],B=Z5(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=p6($[F],Y)*Y;B[F]=U;let[D,O]=i7(z,B,W,Y*V,X,G,Q),L=U+s7(Z,D,O)*V*Y,M=Q$(L,Y,j),T=Math.sign(M-L)===V;return B[F]=M,[B,T?O:D,T]}function o7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let V=p7(Q=z1(Q));return[Q.timeZone,...V]})(W),G=Y!==void 0;return((Q,V,F,B,U,D)=>{F=Z4(F,U,B,1);let O=V.getOffsetNanosecondsFor(F);return JJ(B$(F,O),D)+(Q?l$(q6(O)):"Z")})(G,Z(G?$(Y):$Z),J.epochNanoseconds,j,z,X)}function a7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=z1(Q);let V=z5(Q),F=Wj(Q),B=KO(Q),U=w3(Q,4),D=k3(Q,4);return[V,HO(Q),B,U,...Jj(D,F)]})(J);return((Q,V,F,B,U,D,O,L,M,T)=>{B=Z4(B,M,L,1);let K=Q(F).getOffsetNanosecondsFor(B);return JJ(B$(B,K),T)+l$(q6(K),O)+((N,R)=>R!==1?"["+(R===2?"!":"")+K0(N)+"]":"")(F,D)+WJ(V,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function t7($,Z){let[J,W,Y,j]=((Q)=>(Q=z1(Q),[z5(Q),...p7(Q)]))(Z);return z=$.calendar,X=J,G=j,JJ(Mj($,Y,W),G)+WJ(z,X);var z,X,G}function r7($,Z){return J=$.calendar,W=$,Y=h7(Z),v6(W)+WJ(J,Y);var J,W,Y}function e7($,Z){return Pj($.calendar,Nj,$,h7(Z))}function $J($,Z){return Pj($.calendar,UU,$,h7(Z))}function ZJ($,Z){let[J,W,Y]=Zj(Z);return j=Y,_j(n7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=Zj(Z,3);return W>1&&($={...$,...QU($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?R0(j):j,{hours:Q,minutes:V}=G,[F,B]=w7(D0(G,3),J1,X$);Rj(F);let U=YJ(B,z),D=z>=0||!X||U;return(X<0?"-":"")+"P"+LY({Y:m$(G.years),M:m$(G.months),W:m$(G.weeks),D:m$(G.days)})+(Q||V||F||D?"T"+LY({H:m$(Q),M:m$(V),S:m$(F,D)+U}):"")})($,Y)}function Pj($,Z,J,W){let Y=K0($),j=W>1||W===0&&Y!==v;return W===1?Y===v?Z(J):v6(J):j?v6(J)+Ij(Y,W===2):Z(J)}function LY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function JJ($,Z){return v6($)+"T"+_j($,Z)}function v6($){return Nj($)+"-"+Z1($.isoDay)}function Nj($){let{isoYear:Z}=$;return(Z<0||Z>9999?xj(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+Z1($.isoMonth)}function UU($){return Z1($.isoMonth)+"-"+Z1($.isoDay)}function _j($,Z){let J=[Z1($.isoHour),Z1($.isoMinute)];return Z!==-1&&J.push(Z1($.isoSecond)+((W,Y,j,z)=>YJ(W*H1+Y*t$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function l$($,Z=0){if(Z===1)return"";let[J,W]=g1(Math.abs($),P4),[Y,j]=g1(W,T4),[z,X]=g1(j,J1);return xj($)+Z1(J)+":"+Z1(Y)+(z||X?":"+Z1(z)+YJ(X):"")}function WJ($,Z){if(Z!==1){let J=K0($);if(Z>1||Z===0&&J!==v)return Ij(J,Z===2)}return""}function Ij($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function YJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(_O,""):J.slice(0,Z),J?"."+J:""}function xj($){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=B$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Cj($,Z){let J=b0(Z,$);return{calendar:Z.calendar,...p0(fX,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 v7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,V,F,B)=>{let U=A0(V);B&&(F=q6(F));for(let D of Q){let O=o0(n0(D,U));if(B&&(O=q6(O)),O===F)return D}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(pU)}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 zJ(X.getOffsetNanosecondsFor(_Z(G,s))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(B$(Y,z)))[J===2?0:W.length-1]}function jJ($){if(Math.abs($)>=s)throw RangeError(mU);return $}function zJ($){if($>s)throw RangeError(hU);return $}function XJ($,Z,J){return M0(a0(NZ(Z.epochNanoseconds,((W)=>{if(kj(W))throw RangeError(lU);return D0(W,5)})($?R0(J):J))))}function GJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...UJ(z,X,W,J?R0(Y):Y,j)}}function QJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return X0(OJ($(j),J,Z?R0(W):W,Y),j)}function BJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?R0(W):W,Y),j)}function VJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=D3(z,J);Z&&(W=X4(W)),W.sign<0&&(X=z.dateAdd(X,{...T0,months:1}),X=s$(X,-1));let G=z.dateAdd(X,W,Y);return h$(D3(z,G),j)}function FJ($,Z,J){return X1(Aj(Z,$?R0(J):J)[0])}function UJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(kj(W)){let X=b0(J,$);z=NZ(h0($,{...W4(Z,X,{...W,...$5},Y),...p0(Q1,X)}),j)}else z=NZ(z,j),m(Y);return{epochNanoseconds:a0(z)}}function OJ($,Z,J,W){let[Y,j]=Aj(Z,J);return h1({...W4($,Z,{...J,...$5,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+D0(J,5)[0];return Y?j$(s$(Z,Y)):Z}function D3($,Z,J=1){return s$(Z,J-$.day(Z))}function Aj($,Z){let[J,W]=D0(Z,5),[Y,j]=i6(G$($)+W);return[Y,J+j]}function s$($,Z){return Z?{...$,...s6(E0($)+Z*y0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...W1},W]}function DJ($){return $?Gj:A0}function j4($){return $?q(UJ,$):OJ}function LJ($){return $?q(LU,$):MU}function z4($){return $&&$.epochNanoseconds}function L3($,Z){return $<=6-(z4(Z)?1:0)}function MJ($,Z,J,W,Y,j,z){let X=$(z1(z).relativeTo),G=Math.max(p$(Y),p$(j));if(L3(G,X))return e(RZ(((O,L,M,T)=>{let K=NZ(D0(O),D0(L),T?-1:1);if(!Number.isFinite(K[0]))throw RangeError(H4);return{...T0,...kZ(K,M)}})(Y,j,G,W)));if(!X)throw RangeError(K4);W&&(j=R0(j));let[Q,V,F]=Y4(Z,J,X),B=j4(F),U=LJ(F),D=B(V,Q,Y);return e(U(V,Q,B(V,D,j),G))}function Sj($,Z,J,W,Y){let j=p$(W),[z,X,G,Q,V]=((C,S,w)=>{C=u7(C,m6);let x=j5(C),f=w(C[vX]),_=d7(C),k=w3(C,7),H0=k3(C);if(x===void 0&&H0===void 0)throw RangeError(iU);return H0==null&&(H0=0),x==null&&(x=Math.max(H0,S)),Yj(x,H0),_=c7(_,H0,1),[x,H0,_,k,f]})(Y,j,$),F=Math.max(j,z);if(!z4(V)&&F<=6)return e(RZ(((C,S,w,x,f)=>{let _=$4(D0(C),w,x,f);return{...T0,...kZ(_,S)}})(W,z,X,G,Q)));if(!V)throw RangeError(K4);let[B,U,D]=Y4(Z,J,V),O=DJ(D),L=j4(D),M=LJ(D),T=L(U,B,W),K=M(U,B,T,z),N=W.sign,R=V$(K);if(N&&R&&N!==R)throw RangeError(E3);return R&&(K=e6(K,O(T),z,X,G,Q,U,B,O,L)),e(K)}function Ej($){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 bj($){return!$.sign}function V$($,Z=p){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(uU);J=Y}}return J}function RZ($){for(let Z of $O)$1(Z,$[Z],-_Y,_Y,1);return Rj(o0(D0($),J1)),$}function Rj($){if(!Number.isSafeInteger($))throw RangeError(cU)}function D0($,Z=6){return kY($,Z,p)}function kZ($,Z=6){let[J,W]=$,Y=d6(W,Z,p);if(Y[p[Z]]+=J*(s/M1[Z]),!Number.isFinite(Y[p[Z]]))throw RangeError(H4);return Y}function G4($,Z=5){return d6($,Z,p)}function kj($){return Boolean(V$($,kX))}function p$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function DU($,Z){return[$,Z]}function MY($){let Z=Math.floor($/E6)*E6;return[Z,Z+E6]}function wj($){let Z=F$($=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&&PJ(Z.timeZone,1),M0(v7(n6(Z),J))}function fj($){let Z=F$(J0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return cj(Z,Z.offset?wZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return lj(Z)}function qj($,Z){let J=F$(J0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?wZ(W):void 0,[,j,z]=_3(Z);return cj(J,Y,j,z)}function wZ($){let Z=PJ($);if(Z===void 0)throw RangeError(g0($));return Z}function vj($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(g0($));return X0(uj(Z))}function Q4($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(g0($));return G0(Z.p?uj(Z):lj(Z))}function gj($,Z){let J=KJ(J0(Z));if(J)return HJ(J),h$(q7(c$(J)));let W=Q4(Z);return h$(D3($(W.calendar),W))}function HJ($){if($.calendar!==v)throw RangeError(y1($.calendar))}function yj($,Z){let J=TJ(J0(Z));if(J)return HJ(J),f6(c$(J));let W=Q4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,V]=j.I(z,X),[F,B]=j.N(Q,V,G);return f6(j$(j.P(F,B,G)),Y)}function mj($){let Z,J=((W)=>{let Y=SO.exec(W);return Y?(B4(Y[10]),nj(Y)):void 0})(J0($));if(!J){if(J=F$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(y1("Z"));HJ(J)}if((Z=KJ($))&&OY(Z))throw RangeError(g0($));if((Z=TJ($))&&OY(Z))throw RangeError(g0($));return X1(o6(J,1))}function hj($){let Z=((J)=>{let W=RO.exec(J);return W?((Y)=>{function j(V,F,B){let U=0,D=0;if(B&&([U,G]=g1(G,M1[B])),V!==void 0){if(X)throw RangeError(y1(V));D=((O)=>{let L=parseInt(O);if(!Number.isFinite(L))throw RangeError(y1(O));return L})(V),z=1,F&&(G=NJ(F)*(M1[B]/J1),X=1)}return U+D}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)]),...d6(G,2,p)};if(!z)throw RangeError(VX(p));return _J(Y[1])<0&&(Q=R0(Q)),Q})(W):void 0})(J0($));if(!Z)throw RangeError(g0($));return e(RZ(Z))}function pj($){let Z=F$($)||KJ($)||TJ($);return Z?Z.calendar:$}function dj($){let Z=F$($);return Z&&(Z.timeZone||Z.m&&$Z||Z.offset)||$}function cj($,Z,J=0,W=0){let Y=V4($.timeZone),j=S4(Y);return P0(i$(j,n6($),Z,J,W,!j.v,$.m),Y,x3($.calendar))}function uj($){return ij(h1(n6($)))}function lj($){return ij(j$(c$($)))}function ij($){return{...$,calendar:x3($.calendar)}}function F$($){let Z=AO.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:sj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...nj(J.slice(5)),...B4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function KJ($){let Z=xO.exec($);return Z?((J)=>({isoYear:sj(J),isoMonth:parseInt(J[4]),isoDay:1,...B4(J[5])}))(Z):void 0}function TJ($){let Z=CO.exec($);return Z?((J)=>({isoYear:CZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...B4(J[3])}))(Z):void 0}function PJ($,Z){let J=EO.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(y1(j));return jJ((PZ(W[2])*P4+PZ(W[3])*T4+PZ(W[4])*J1+NJ(W[5]||""))*_J(W[1]))})(J,Z):void 0}function sj($){let Z=_J($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(y1(-0));return Z*J}function nj($){let Z=PZ($[3]);return{...i6(NJ($[4]||""))[0],isoHour:PZ($[1]),isoMinute:PZ($[2]),isoSecond:Z===60?59:Z}}function B4($){let Z,J,W=[];if($.replace(bO,(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(y1(Y))}else{if(J)throw RangeError(y1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(y1($));return{timeZone:J,calendar:W[0]||v}}function NJ($){return parseInt($.padEnd(9,"0"))}function fZ($){return new RegExp(`^${$}$`,"i")}function _J($){return $&&$!=="+"?-1:1}function PZ($){return $===void 0?0:parseInt($)}function oj($){return V4(J0($))}function V4($){let Z=IJ($);return typeof Z=="number"?l$(Z):Z?((J)=>{if(wO.test(J))throw RangeError(yU);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?FY(j).replace(/island|noronha|murdo|rivadavia|urville/,FY):j)).join("/")})($):$Z}function HY($){let Z=IJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:$Z}function IJ($){let Z=PJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==$Z?kO($):void 0}function xJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function CJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function aj($,Z,J,W,Y,j){let z=$(z1(j).relativeTo),X=Math.max(p$(W),p$(Y));if(bY(p,W,Y))return 0;if(L3(X,z))return S0(D0(W),D0(Y));if(!z)throw RangeError(K4);let[G,Q,V]=Y4(Z,J,z),F=DJ(V),B=j4(V);return S0(F(B(Q,G,W)),F(B(Q,G,Y)))}function AJ($,Z){return n$($,Z)||F4($,Z)}function n$($,Z){return Y$(E0($),E0(Z))}function F4($,Z){return Y$(G$($),G$(Z))}function tj($,Z){return!xJ($,Z)}function rj($,Z){return!CJ($,Z)&&!!U4($.timeZone,Z.timeZone)&&bZ($.calendar,Z.calendar)}function ej($,Z){return!AJ($,Z)&&bZ($.calendar,Z.calendar)}function $z($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Zz($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Jz($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Wz($,Z){return!F4($,Z)}function U4($,Z){if($===Z)return 1;let J=K0($),W=K0(Z);if(J===W)return 1;try{return HY(J)===HY(W)}catch(Y){}}function SJ($,Z,J,W){let Y=EZ($,z0(W),3,5),j=O4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return e($?R0(j):j)}function EJ($,Z,J,W,Y,j){let z=L4(W.calendar,Y.calendar),X=z0(j),[G,Q,V,F]=EZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,D=S0(U,B),O;if(D)if(G<6)O=O4(B,U,G,Q,V,F);else{let L=Z(((T,K)=>{if(!U4(T,K))throw RangeError(MX);return T})(W.timeZone,Y.timeZone)),M=$(z);O=jz(M,L,W,Y,D,G,X),O=e6(O,U,G,Q,V,F,M,W,Gj,q(UJ,L))}else O=T0;return e(J?R0(O):O)}function bJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),[X,G,Q,V]=EZ(Z,z,6),F=A0(J),B=A0(W),U=S0(B,F),D;if(U)if(X<=6)D=O4(F,B,X,G,Q,V);else{let O=$(j);D=zz(O,J,W,U,X,z),D=e6(D,B,X,G,Q,V,O,J,A0,OJ)}else D=T0;return e(Z?R0(D):D)}function RJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y);return Yz(Z,()=>$(j),J,W,...EZ(Z,z,6,9,6),z)}function kJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),X=EZ(Z,z,9,9,8),G=$(j);return Yz(Z,()=>G,D3(G,J),D3(G,W),...X,z)}function Yz($,Z,J,W,Y,j,z,X,G){let Q=A0(J),V=A0(W),F;if(S0(V,Q))if(Y===6)F=O4(Q,V,Y,j,z,X);else{let B=Z();F=B.dateUntil(J,W,Y,G),j===6&&z===1||(F=e6(F,V,Y,j,z,X,B,J,A0,W4))}else F=T0;return e($?R0(F):F)}function wJ($,Z,J,W){let Y=z0(W),[j,z,X,G]=EZ($,Y,5,5),Q=Q$(fJ(Z,J),I3(z,X),G),V={...T0,...G4(Q,j)};return e($?R0(V):V)}function LU($,Z,J,W,Y,j){let z=S0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Xz(J.epochNanoseconds,W.epochNanoseconds,Y):jz(Z,$,J,W,z,Y,j):T0}function MU($,Z,J,W,Y){let j=A0(Z),z=A0(J),X=S0(z,j);return X?W<=6?Xz(j,z,W):zz($,Z,J,X,W,Y):T0}function jz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,D,O)=>{function L(){return S={...s$(K,R++*-O),...T},w=h0(B,S),S0(N,w)===-O}let M=b0(U,B),T=p0(Q1,M),K=b0(D,B),N=D.epochNanoseconds,R=0,C=fJ(M,K),S,w;if(Math.sign(C)===-O&&R++,L()&&(O===-1||L()))throw RangeError(E3);let x=o0(n0(w,N));return[M,S,x]})(Z,J,W,Y);var V,F;return{...j===6?(V=X,F=G,{...T0,days:Gz(V,F)}):$.dateUntil(X,G,j,z),...G4(Q)}}function zz($,Z,J,W,Y,j){let[z,X,G]=((Q,V,F)=>{let B=V,U=fJ(Q,V);return Math.sign(U)===-F&&(B=s$(V,-F),U+=s*F),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...G4(G)}}function O4($,Z,J,W,Y,j){return{...T0,...kZ($4(n0($,Z),W,Y,j),J)}}function Xz($,Z,J){return{...T0,...kZ(n0($,Z),J)}}function Gz($,Z){return D4(E0($),E0(Z))}function D4($,Z){return Math.trunc((Z-$)/y0)}function fJ($,Z){return G$(Z)-G$($)}function L4($,Z){if(!bZ($,Z))throw RangeError(oJ);return $}function HU($){function Z(Y){return((j,z)=>({...Qz(j,z),F:j.month,day:parseInt(j.day)}))(f7(J,Y),W)}let J=B5($),W=g6($);return{id:$,O:KU(Z),B:TU(Z)}}function KU($){return m0((Z)=>{let J=E0(Z);return $(J)},WeakMap)}function TU($){let Z=$(0).year-zO;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:TX(z.reverse())}})}function Qz($,Z){let J,W,Y=Bz($);if($.era){let j=EX[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=Dz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Bz($){return parseInt($.relatedYear||$.year)}function H7($){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=TY(this,$),J=TY(this,$-1),W=Z.length;if(W>J.length){let Y=Lz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function A6($){return D4(M3.call(this,$),M3.call(this,$+1))}function KY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),D4(J[Z-1],Y[W-1])}function S6($){return this.B($).k.length}function TY($,Z){return Object.keys($.B(Z).C)}function Vz($){return x3(J0($))}function x3($){if(($=$.toLowerCase())!==v&&$!==_4&&g6($)!==g6(B5($).resolvedOptions().calendar))throw RangeError(gU($));return $}function g6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Fz($){return this.R($)[0]}function Uz($){return this.R($)[1]}function qJ($){let[Z]=this.h($);return D4(this.q(Z),E0($))+1}function Oz($){let Z=qO.exec($);if(!Z)throw RangeError(qU($));return[parseInt(Z[1]),Boolean(Z[2])]}function y6($,Z,J){return $+(Z||J&&$>=J?1:0)}function K7($,Z){return $-(Z&&$>=Z?1:0)}function Dz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function T7($){return EX[Mz($)]}function Lz($){return tU[Mz($)]}function Mz($){return g6($.id||v)}function Hz($,Z,J,W){let Y=U$(J,W,G1,[],xX);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),...W1}}function Kz($,Z,J,W,Y,j){let z=U$(J,Y,G1,_X,xX),X=$(z.timeZone),[G,Q,V]=_3(j),F=J.dateFromFields(z,t6(j,G)),B=o$(z,G);return P0(i$(Z(X),{...F,...B},z.offset!==void 0?wZ(z.offset):void 0,Q,V),X,W)}function Tz($,Z,J){let W=U$($,Z,G1,[],c1),Y=m(J);return X0(h1({...$.dateFromFields(W,t6(J,Y)),...o$(W,Y)}))}function vJ($,Z,J,W=[]){let Y=U$($,Z,G1,W);return $.dateFromFields(Y,J)}function gJ($,Z,J,W){let Y=U$($,Z,rJ,W);return $.yearMonthFromFields(Y,J)}function yJ($,Z,J,W,Y=[]){let j=U$($,J,G1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=CZ),$.monthDayFromFields(j,W)}function Pz($,Z){let J=m(Z);return X1(o$(L1($,N7,[],1),J))}function Nz($){let Z=L1($,eJ);return e(RZ({...T0,...Z}))}function U$($,Z,J,W=[],Y=[]){return L1(Z,[...$.fields(J),...Y].sort(),W)}function L1($,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(sJ(X));let G=$[X];if(G!==void 0)z=1,IY[X]&&(G=IY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(iJ(X));Y[X]=SX[X]}j=X}if(W&&!z)throw TypeError(VX(Z));return Y}function o$($,Z){return o6(mO({...SX,...$}),Z)}function _z($,Z,J,W,Y,j){let z=z0(j),{calendar:X,timeZone:G}=J;return P0(((Q,V,F,B,U)=>{let D=C3(Q,F,B,G1,IX,NX),[O,L,M]=_3(U,2);return i$(V,{...Q.dateFromFields(D,t6(U,O)),...o$(D,O)},wZ(D.offset),L,M)})($(X),Z(G),W,Y,z),G,X)}function Iz($,Z,J,W,Y){let j=z0(Y);return X0(((z,X,G,Q)=>{let V=C3(z,X,G,G1,c1),F=m(Q);return h1({...z.dateFromFields(V,t6(Q,F)),...o$(V,F)})})($(Z.calendar),J,W,j))}function xz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let V=C3(z,X,G,G1);return z.dateFromFields(V,Q)})($(Z.calendar),J,W,j)}function Cz($,Z,J,W,Y){let j=z0(Y);return h$(((z,X,G,Q)=>{let V=C3(z,X,G,rJ);return z.yearMonthFromFields(V,Q)})($(Z.calendar),J,W,j))}function Az($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let V=C3(z,X,G,G1);return z.monthDayFromFields(V,Q)})($(Z.calendar),J,W,j)}function Sz($,Z,J){return X1(((W,Y,j)=>{let z=m(j);return o$({...p0(N7,W),...L1(Y,N7)},z)})($,Z,J))}function Ez($,Z){return e((J=$,W=Z,RZ({...J,...L1(W,eJ)})));var J,W}function C3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=L1(Z,z,j),G=L1(J,z);return X=$.mergeFields(X,G),L1(X,z,[])}function mJ($,Z){let J=U$($,Z,AX);return $.monthDayFromFields(J)}function hJ($,Z,J){let W=U$($,Z,CX);return $.yearMonthFromFields(W,J)}function bz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=L1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=L1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function U7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=T7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(RU);if(!j)throw RangeError(bU);let z=j[J];if(z===void 0)throw RangeError(wU(J));let X=Dz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(kU);Y=X}else if(Y===void 0)throw TypeError(fU(j));return Y}function O7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,V)=>{let F=X.U(Q),[B,U]=Oz(G),D=y6(B,U,F);if(U){let O=Lz(X);if(O===void 0)throw RangeError(F3);if(O>0){if(D>O)throw RangeError(F3);if(F===void 0){if(V===1)throw RangeError(F3);D--}}else{if(D!==-O)throw RangeError(F3);if(F===void 0&&V===1)throw RangeError(F3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(DX);Y=z,W=1}else if(Y===void 0)throw TypeError(vU);return $1("month",Y,1,$.L(J),W)}function PY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function D7($,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 Rz($){return M0(a0(l6(u6($))))}function kz($,Z,J,W,Y=v){return P0(a0(l6(u6(J))),Z(W),$(Y))}function wz($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,V=v){return X0(h1(n6(Y1(C0,AZ(I4,[Z,J,W,Y,j,z,X,G,Q])))),$(V))}function fz($,Z,J,W,Y=v){return G0(j$(c$(Y1(C0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function qz($,Z,J,W=v,Y=1){let j=C0(Z),z=C0(J),X=$(W);return h$(q7(c$({isoYear:j,isoMonth:z,isoDay:C0(Y)})),X)}function vz($,Z,J,W=v,Y=CZ){let j=C0(Z),z=C0(J),X=$(W);return f6(j$(c$({isoYear:C0(Y),isoMonth:j,isoDay:z})),X)}function gz($=0,Z=0,J=0,W=0,Y=0,j=0){return X1(o6(Y1(C0,AZ(Q1,[$,Z,J,W,Y,j])),1))}function yz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return e(RZ(Y1(dY,AZ(p,[$,Z,J,W,Y,j,z,X,G,Q]))))}function pJ($,Z,J=v){return P0($.epochNanoseconds,Z,J)}function mz($){return M0($.epochNanoseconds)}function dJ($,Z){return X0(b0(Z,$))}function cJ($,Z){return G0(b0(Z,$))}function hz($,Z,J){return hJ($(Z.calendar),J)}function pz($,Z,J){return mJ($(Z.calendar),J)}function uJ($,Z){return X1(b0(Z,$))}function dz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=m7(G);return h0(j(z),X,Q)})($,J,Z,W);return P0(a0(Y),J,Z.calendar)}function cz($,Z,J){let W=$(Z.calendar);return h$({...Z,...hJ(W,J)})}function uz($,Z,J){return mJ($(Z.calendar),J)}function lz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):W1;return P0(h0(J(j),{...W,...X}),j,W.calendar)}function iz($,Z=W1){return X0(h1({...$,...Z}))}function sz($,Z,J){return hJ($(Z.calendar),J)}function nz($,Z,J){return mJ($(Z.calendar),J)}function oz($,Z,J,W){return((Y,j,z)=>bz(Y,j,CX,m1(z),R3))($(Z.calendar),J,W)}function az($,Z,J,W){return((Y,j,z)=>bz(Y,j,AX,m1(z),N4))($(Z.calendar),J,W)}function tz($,Z,J,W,Y){let j=m1(Y),z=Z(j.plainDate),X=$(j.timeZone);return P0(h0(J(X),{...z,...W}),X,z.calendar)}function rz($,Z){return X0(h1({...$,...Z}))}function ez($){return M0(a0(IZ($,J1)))}function $X($){return M0(a0(IZ($,H1)))}function ZX($){return M0(a0(l6(u6($),t$)))}function JX($){return M0(a0(l6(u6($))))}function WX($,Z,J=W1){let W=Z.timeZone,Y=$(W),j={...b0(Z,Y),...J};return P0(i$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function YX($,Z,J){let W=Z.timeZone,Y=$(W),j={...b0(Z,Y),...J},z=GX(Z.calendar,J.calendar);return P0(i$(Y,j,j.offsetNanoseconds,2),W,z)}function jX($,Z=W1){return X0({...$,...Z})}function zX($,Z){return X0({...$,...Z},GX($.calendar,Z.calendar))}function M4($,Z){return{...$,calendar:Z}}function XX($,Z){return{...$,timeZone:Z}}function GX($,Z){if($===Z)return $;let J=K0($),W=K0(Z);if(J===W||J===v)return Z;if(W===v)return $;throw RangeError(oJ)}function PU($,Z){return(J)=>J===v?$:J===_4||J===xZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),fO(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=C7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=$Z,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function p1($,Z=lJ){let[J,,,W]=$;return(Y,j=ZD,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...NU($,G,z)]}}function lJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(nU);J.timeZone=$}return new O$(Z,J)}function NU($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==v)&&z!==X)throw RangeError(oJ)})(K0(j.calendar),Z.calendar,Y),W(j,Z)))}function qZ($){let Z=A3();return B$(Z,$.getOffsetNanosecondsFor(Z))}function A3(){return IZ(Date.now(),H1)}function d1(){return CY||(CY=new O$().resolvedOptions().timeZone)}var _U=($,Z)=>`Non-integer ${$}: ${Z}`,IU=($,Z)=>`Non-positive ${$}: ${Z}`,xU=($,Z)=>`Non-finite ${$}: ${Z}`,CU=($)=>`Cannot convert bigint to ${$}`,AU=($)=>`Invalid bigint: ${$}`,SU="Cannot convert Symbol to string",QX="Invalid object",BX=($,Z,J,W,Y)=>Y?BX($,Y[Z],Y[J],Y[W]):S3($,Z)+`; must be between ${J}-${W}`,S3=($,Z)=>`Invalid ${$}: ${Z}`,iJ=($)=>`Missing ${$}`,sJ=($)=>`Invalid field ${$}`,EU=($)=>`Duplicate field ${$}`,VX=($)=>"No valid fields: "+$.join(),FX="Invalid bag",UX=($,Z,J)=>S3($,Z)+"; must be "+Object.keys(J).join(),OX="Cannot use valueOf",nJ="Invalid calling context",bU="Forbidden era/eraYear",RU="Mismatching era/eraYear",kU="Mismatching year/eraYear",wU=($)=>`Invalid era: ${$}`,fU=($)=>"Missing year"+($?"/era/eraYear":""),qU=($)=>`Invalid monthCode: ${$}`,DX="Mismatching month/monthCode",vU="Missing month/monthCode",NY="Cannot guess year",F3="Invalid leap month",LX="Invalid protocol",E3="Invalid protocol results",oJ="Mismatching Calendars",gU=($)=>`Invalid Calendar: ${$}`,MX="Mismatching TimeZones",yU="Forbidden ICU TimeZone",mU="Out-of-bounds offset",hU="Out-of-bounds TimeZone gap",pU="Invalid TimeZone offset",dU="Ambiguous offset",H4="Out-of-bounds date",cU="Out-of-bounds duration",uU="Cannot mix duration signs",K4="Missing relativeTo",lU="Cannot use large units",iU="Required smallestUnit or largestUnit",sU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,y1=($)=>`Invalid substring: ${$}`,HX=($)=>`Cannot format ${$}`,KX="Mismatching types for formatting",nU="Cannot specify TimeZone",TX=q(T3,($,Z)=>Z),vZ=q(T3,($,Z,J)=>J),Z1=q(R6,2),P7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},b3=Object.keys(P7),y0=86400000,PX=1000,t$=1000,H1=1e6,J1=1e9,T4=60000000000,P4=3600000000000,s=86400000000000,M1=[1,t$,H1,J1,T4,P4,s],c1=b3.slice(0,6),N7=P3(c1),NX=["offset"],_X=["timeZone"],IX=c1.concat(NX),xX=IX.concat(_X),_7=["era","eraYear"],oU=_7.concat(["year"]),N4=["year"],aJ=["monthCode"],tJ=["month"].concat(aJ),R3=["day"],rJ=tJ.concat(N4),CX=aJ.concat(N4),G1=R3.concat(rJ),aU=R3.concat(tJ),AX=R3.concat(aJ),SX=vZ(c1,0),v="iso8601",_4="gregory",xZ="japanese",EX={[_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}},tU={chinese:13,dangi:13,hebrew:-6},J0=q(c6,"string"),bX=q(c6,"boolean"),rU=q(c6,"number"),RX=q(c6,"function"),p=b3.map(($)=>$+"s"),eJ=P3(p),eU=p.slice(0,6),kX=p.slice(6),$O=kX.slice(1),ZO=TX(p),T0=vZ(p,0),$5=vZ(eU,0),Z5=q(RY,p),Q1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],J5=["isoDay","isoMonth","isoYear"],I4=Q1.concat(J5),W5=P3(J5),wX=P3(Q1),fX=P3(I4),W1=vZ(wX,0),JO=q(RY,I4),O$=Intl.DateTimeFormat,qX="en-GB",Y5=1e8,WO=Y5*y0,YO=[Y5,0],jO=[-Y5,0],H3=275760,K3=-271821,zO=1970,CZ=1972,v1=12,XO=SZ(1868,9,8),GO=m0(GU,WeakMap),m6="smallestUnit",I7="unit",O3="roundingIncrement",L7="fractionalSecondDigits",vX="relativeTo",gX={constrain:0,reject:1},QO=Object.keys(gX),BO={compatible:0,reject:1,earlier:2,later:3},VO={reject:0,use:1,prefer:2,ignore:3},FO={auto:0,never:1,critical:2,always:3},UO={auto:0,never:1,critical:2},OO={auto:0,never:1},DO={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},k3=q(l7,m6),j5=q(l7,"largestUnit"),LO=q(l7,I7),yX=q(u$,"overflow",gX),mX=q(u$,"disambiguation",BO),MO=q(u$,"offset",VO),z5=q(u$,"calendarName",FO),HO=q(u$,"timeZoneName",UO),KO=q(u$,"offset",OO),w3=q(u$,"roundingMode",DO),gZ="PlainYearMonth",yZ="PlainMonthDay",r$="PlainDate",e$="PlainDateTime",x4="PlainTime",u1="ZonedDateTime",C4="Instant",A4="Duration",TO=[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",E6=5184000,PO=w6(1847),NO=w6(new Date().getUTCFullYear()+10),_O=/0+$/,b0=m0(OU,WeakMap),_Y=4294967295,S4=m0(($)=>{let Z=IJ($);return typeof Z=="object"?new pX(Z):new hX(Z||0)});class hX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[v7($,this.v)]}l(){}}class pX{constructor($){this.$=((Z)=>{function J(G){let Q=M7(G,z,X),[V,F]=MY(Q),B=Y(V),U=Y(F);return B===U?B:W(j(V,F),B,U,G)}function W(G,Q,V,F){let B,U;for(;(F===void 0||(B=F<G[0]?Q:F>=G[1]?V:void 0)===void 0)&&(U=G[1]-G[0]);){let D=G[0]+Math.floor(U/2);Z(D)===V?G[1]=D:G[0]=D+1}return B}let Y=m0(Z),j=m0(DU),z=PO,X=NO;return{G(G){let Q=J(G-86400),V=J(G+86400),F=G-Q,B=G-V;if(Q===V)return[F];let U=J(F);return U===J(B)?[G-U]:Q>V?[F,B]:[]},V:J,l(G,Q){let V=M7(G,z,X),[F,B]=MY(V),U=E6*Q,D=Q<0?()=>B>z||(z=V,0):()=>F<X||(X=V,0);for(;D();){let O=Y(F),L=Y(B);if(O!==L){let M=j(F,B);W(M,O,L);let T=M[0];if((Y$(T,G)||1)===Q)return T}F+=U,B+=U}}}})(((Z)=>(J)=>{let W=f7(Z,J*PX);return w6(Bz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(lY($))*J1}getPossibleInstantsFor($){let[Z,J]=[w6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*H1+W.isoMicrosecond*t$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>a0(_Z(IZ(Y,J1),J)))}l($,Z){let[J,W]=iY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return IZ(Y,J1)}}var X5="([+\u2212-])",b6="(?:[.,](\\d{1,9}))?",dX=`(?:(?:${X5}(\\d{6}))|(\\d{4}))-?(\\d{2})`,G5="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+b6+")?)?",Q5=X5+G5,IO=dX+"-?(\\d{2})(?:[T ]"+G5+"(Z|"+Q5+")?)?",cX="\\[(!?)([^\\]]*)\\]",E4=`((?:${cX}){0,9})`,xO=fZ(dX+E4),CO=fZ("(?:--)?(\\d{2})-?(\\d{2})"+E4),AO=fZ(IO+E4),SO=fZ("T?"+G5+"(?:"+Q5+")?"+E4),EO=fZ(Q5),bO=new RegExp(cX,"g"),RO=fZ(`${X5}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${b6}H)?(?:(\\d+)${b6}M)?(?:(\\d+)${b6}S)?)?`),kO=m0(($)=>new O$(qX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),wO=/^(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$/,fO=m0(HU),B5=m0(($)=>new O$(qX,{calendar:$,timeZone:$Z,era:"short",year:"numeric",month:"short",day:"numeric"})),qO=/^M(\d{2})(L?)$/,vO={era:k6,eraYear:C0,year:C0,month:UY,monthCode:k6,day:UY},gO=vZ(c1,C0),yO=vZ(p,dY),IY=Object.assign({},vO,gO,yO,{offset:k6}),mO=q(XU,c1,Q1),xY={dateAdd($,Z,J){let W=m(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],j||z)Y=((Q,V,F,B,U)=>{let[D,O,L]=Q.h(V);if(F){let[M,T]=Q.I(D,O);D+=F,O=y6(M,T,Q.U(D)),O=$1("month",O,1,Q.L(D),U)}return B&&([D,O]=Q._(D,O,B)),L=$1("day",L,1,Q.j(D,O),U),Q.q(D,O,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=E0($)}return Y+=(7*X+G)*y0,j$(s6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Gz({...$,...W1},{...Z,...W1});return J===7&&([G,Q]=X$(Q,7)),{...T0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,V,F,B,U,D)=>{let O=B-Q,L=U-V,M=D-F;if(O||L){let T=Math.sign(O||L),K=G.j(B,U),N=0;if(Math.sign(M)===-T){let R=K;[B,U]=G._(B,U,-T),O=B-Q,L=U-V,K=G.j(B,U),N=T<0?-R:K}if(M=D-Math.min(F,K)+N,O){let[R,C]=G.I(Q,V),[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);O=(B-=T)-Q,L=U-y6(R,C,G.U(B))+(x||G.L(B))}}}return[O,L,M]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...T0,years:j,months:z,days:X}},dateFromFields($,Z){let J=m(Z),W=U7(this,$),Y=O7(this,$,W,J),j=PY(this,$,Y,W,J);return G0(j$(this.P(W,Y,j)),this.id||v)},yearMonthFromFields($,Z){let J=m(Z),W=U7(this,$),Y=O7(this,$,W,J);return h$(q7(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,V,F;if(Y!==void 0){[X,G]=Oz(Y),F=AY($,"day");let B=this.N(X,G,F);if(!B)throw RangeError(NY);if([Q,V]=B,z!==void 0&&z!==V)throw RangeError(DX);W&&(V=$1("month",V,1,v1,1),F=$1("day",F,1,g7(j!==void 0?j:Q,V),J))}else{Q=j===void 0&&W?CZ:U7(this,$),V=O7(this,$,Q,J),F=PY(this,$,V,Q,J);let B=this.U(Q);G=V===B,X=K7(V,B);let U=this.N(X,G,F);if(!U)throw RangeError(NY);[Q,V]=U}return f6(j$(this.P(Q,V,F)),this.id||v)},fields($){return T7(this)&&$.includes("year")?[...$,..._7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return D7(J,Z,tJ),T7(this)&&(D7(J,Z,oU),this.id===xZ&&D7(J,Z,aU,_7)),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:qJ,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"+Z1(j)+(z?"L":""))(W,Y)},dayOfWeek:tY,daysInWeek(){return 7}},hO={dayOfYear:qJ,h:nY,q:SZ},pO=Object.assign({},hO,{weekOfYear:Fz,yearOfWeek:Uz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let D=aY(B+U),O=U||1,L=Z(U3(G+D*O,7));return V=(D+(L-Q)*O)/7}let W=this.id?1:4,Y=tY($),j=this.dayOfYear($),z=U3(Y-1,7),X=j-1,G=U3(z-X,7),Q=Z(G),V,F=Math.floor((X-Q)/7)+1,B=$.isoYear;return F?F>J(0)&&(F=1,B++):(F=J(-1),B--),[F,B,V]}}),dO={dayOfYear:qJ,h:H7,q:M3,weekOfYear:Fz,yearOfWeek:Uz,R(){return[]}},mZ=PU(Object.assign({},xY,pO,{h:nY,ee($){return this.id===_4?rY($):this.id===xZ?GO($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[CZ,$]},K:y7,U(){},L:oY,J:($)=>$*v1,j:g7,X:aY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:SZ,_:($,Z,J)=>($+=p6(J,v1),(Z+=S7(J,v1))<1?($--,Z+=v1):Z>v1&&($++,Z-=v1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},xY,dO,{h:H7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[K7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=H7.call(this,{isoYear:CZ,isoMonth:v1,isoDay:31}),z=C6.call(this,W),X=Y===z;(Y$($,K7(Y,z))||Y$(Number(Z),Number(X))||Y$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,V=C6.call(this,Q),F=y6($,Z,V);if(Z===(F===V)&&J<=KY.call(this,Q,F))return[Q,F]}},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:KY,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}})),z$="numeric",hZ=["timeZoneName"],uX={month:z$,day:z$},V5={year:z$,month:z$},F5=Object.assign({},V5,{day:z$}),U5={hour:z$,minute:z$,second:z$},O5=Object.assign({},F5,U5),cO=Object.assign({},O5,{timeZoneName:"short"}),uO=Object.keys(V5),lO=Object.keys(uX),iO=Object.keys(F5),sO=Object.keys(U5),D5=["dateStyle"],nO=uO.concat(D5),oO=lO.concat(D5),L5=iO.concat(D5,["weekday"]),f3=sO.concat(["dayPeriod","timeStyle"]),M5=L5.concat(f3),aO=M5.concat(hZ),tO=hZ.concat(f3),rO=hZ.concat(L5),eO=hZ.concat(["day","weekday"],f3),$D=hZ.concat(["year","weekday"],f3),ZD={},H5=[a$(M5,O5),r6],lX=[a$(aO,cO),r6,0,($,Z)=>{let J=K0($.timeZone);if(Z&&K0(Z.timeZone)!==J)throw RangeError(MX);return J}],K5=[a$(M5,O5,hZ),E0],T5=[a$(L5,F5,tO),E0],P5=[a$(f3,U5,rO),($)=>G$($)/H1],N5=[a$(nO,V5,eO),E0,1],_5=[a$(oO,uX,$D),E0,1],CY;function P1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(nJ);oX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...V){return G.call(this,X(this),...V)},x7(Q))}function X(G){let Q=I0(G);if(!Q||Q.branding!==$)throw TypeError(nJ);return Q}return Object.defineProperties(j.prototype,{...SY(Y1(z,J)),...d$(Y1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...d$(Y),...x7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return oX(Q,G),Q},X]}function rX($){return $=$.concat("id").sort(),(Z)=>{if(!EY(Z,$))throw TypeError(LX);return Z}}function uZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(FX);return $}function b4($,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 C5($){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(MD),{i:z})))[J](W);var j,z};return Z}function K$(){throw TypeError(OX)}function v3({calendar:$}){return typeof $=="string"?new q5($):$}function iX($,Z){if(Z=z0(Z),L0($)){let W=I0($);if(W&&W.branding===yZ)return m(Z),W;let Y=ZG($);return yJ(g4(Y||v),!Y,$,Z)}let J=yj(mZ,$);return m(Z),J}function eX($,Z,J){return W=Z.call($,k0(M0(J))),jJ(N3(W));var W}function R4($,Z=jG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=q(Z[Y],$,RX($[Y]));return W}function o($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return o($,x5)}function K1($){if(L0($)){let Z=I0($);if(Z)switch(Z.branding){case C4:return Z;case u1:return M0(Z.epochNanoseconds)}}return wj($)}function sX($,Z,J){let W=Z.l(K1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function t($){return L0($)?(I0($)||{}).timeZone||_D($):((Z)=>V4(dj(J0(Z))))($)}function D$($,Z){if(L0($)){let J=I0($)||{};switch(J.branding){case x4:return m(Z),J;case e$:return m(Z),X1(J);case u1:return m(Z),uJ(B0,J)}return Pz($,Z)}return m(Z),mj($)}function A5($){return $===void 0?void 0:D$($)}function pZ($,Z){if(Z=z0(Z),L0($)){let W=I0($);return W&&W.branding===gZ?(m(Z),W):gJ(q4(g3($)),$,Z)}let J=gj(mZ,$);return m(Z),J}function L$($,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,...W1});case u1:return m(Z),dJ(B0,W)}return Tz(v4(g3($)),$,Z)}let J=vj($);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 u1:return m(Z),cJ(B0,W)}return vJ(v4(g3($)),$,Z)}let J=Q4($);return m(Z),J}function $G($,Z,J){return j1(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:Nz($)}return hj($)}function q3($){if($!==void 0){if(L0($)){let Z=I0($)||{};switch(Z.branding){case u1:case r$:return Z;case e$:return G0(Z)}let J=g3($);return{...Hz(t,o,v4(J),$),calendar:J}}return fj($)}}function g3($){return ZG($)||v}function ZG($){let{calendar:Z}=$;if(Z!==void 0)return _0(Z)}function _0($){return L0($)?(I0($)||{}).calendar||yD($):((Z)=>x3(pj(J0(Z))))($)}function dZ($,Z){if(Z=z0(Z),L0($)){let J=I0($);if(J&&J.branding===u1)return _3(Z),J;let W=g3($);return Kz(t,o,v4(W),W,$,Z)}return qj($,Z)}function nX($){return Y1((Z)=>(J)=>Z(I5(J)),$)}function I5($){return b0($,B0)}function JD(){let $=O$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(O$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);v5.set(this,((z,X={})=>{let G=new O$(z,X),Q=G.resolvedOptions(),V=Q.locale,F=p0(Object.keys(X),Q),B=m0(jD),U=(...D)=>{let O,L=D.map((M,T)=>{let K=I0(M),N=(K||{}).branding;if(T&&O&&O!==N)throw TypeError(KX);return O=N,K});return O?B(O)(V,F,...L):[G,...D]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&WD(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||YD(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function WD($){return function(...Z){let J=v5.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function YD($){return function(...Z){return v5.get(this).u[$](...Z)}}function jD($){let Z=zD[$];if(!Z)throw TypeError(HX($));return p1(Z,m0(lJ))}var zD={Instant:H5,PlainDateTime:K5,PlainDate:T5,PlainTime:P5,PlainYearMonth:N5,PlainMonthDay:_5},XD=p1(H5),GD=p1(lX),QD=p1(K5),BD=p1(T5),VD=p1(P5),FD=p1(N5),UD=p1(_5),S5={era:vY,eraYear:E7,year:N3,month:j1,daysInMonth:j1,daysInYear:j1,inLeapYear:bX,monthsInYear:j1},w4={monthCode:J0},E5={day:j1},JG={dayOfWeek:j1,dayOfYear:j1,weekOfYear:gY,yearOfWeek:E7,daysInWeek:j1},WG=Object.assign({},S5,w4,E5,JG),k4=new WeakMap,I0=k4.get.bind(k4),oX=k4.set.bind(k4),OD={...b4(S5,[gZ]),...b4(JG,[]),...b4(w4,[gZ,yZ]),...b4(E5,[yZ])},b5=C5(WG),DD=C5({...S5,...w4}),LD=C5({...w4,...E5}),y3={calendarId:($)=>K0($.calendar)},MD=Y1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(G0(J,W))))},WG),HD=T3(($)=>(Z)=>Z[$],p.concat("sign")),R5=T3(($,Z)=>(J)=>J[Q1[Z]],c1),YG={epochSeconds:jj,epochMilliseconds:r6,epochMicroseconds:zj,epochNanoseconds:Xj},m3=q(C7,new Set(["branding"])),[KD,cZ,TD]=P1(yZ,q(vz,_0),{...y3,...LD},{getISOFields:m3,getCalendar:v3,with($,Z,J){return cZ(Az(qD,$,this,uZ(Z),J))},equals:($,Z)=>Jz($,iX(Z)),toPlainDate($,Z){return Y0(az(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=UD(Z,J,$);return W.format(Y)},toString:$J,toJSON:($)=>$J($),valueOf:K$},{from:($,Z)=>cZ(iX($,Z))}),jG={getOffsetNanosecondsFor:eX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,N0(X0(J,v)))].map((j)=>ND(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(S0),zJ(o0(n0(W[0],W[Y-1])))),W}},x5={getOffsetNanosecondsFor:eX},[PD,k0,ND]=P1(C4,Rz,YG,{add:($,Z)=>k0(XJ(0,$,W0(Z))),subtract:($,Z)=>k0(XJ(1,$,W0(Z))),until:($,Z,J)=>a(SJ(0,$,K1(Z),J)),since:($,Z,J)=>a(SJ(1,$,K1(Z),J)),round:($,Z)=>k0(Bj($,Z)),equals:($,Z)=>tj($,K1(Z)),toZonedDateTime($,Z){let J=m1(Z);return Q0(pJ($,t(J.timeZone),_0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(pJ($,t(Z))),toLocaleString($,Z,J){let[W,Y]=XD(Z,J,$);return W.format(Y)},toString:($,Z)=>o7(t,B0,$,Z),toJSON:($)=>o7(t,B0,$),valueOf:K$},{from:($)=>k0(K1($)),fromEpochSeconds:($)=>k0(ez($)),fromEpochMilliseconds:($)=>k0($X($)),fromEpochMicroseconds:($)=>k0(ZX($)),fromEpochNanoseconds:($)=>k0(JX($)),compare:($,Z)=>xJ(K1($),K1(Z))}),[f4,TN]=P1("TimeZone",($)=>{let Z=oj($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(L$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(K1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=K1(Z).epochNanoseconds,W=R4(this,x5).getOffsetNanosecondsFor(J);return l$(W)},getPlainDateTimeFor($,Z,J=v){let W=K1(Z).epochNanoseconds,Y=R4(this,x5).getOffsetNanosecondsFor(W);return N0(X0(B$(W,Y),_0(J)))},getInstantFor($,Z,J){let W=L$(Z),Y=m7(J),j=R4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>sX(1,$,Z),getPreviousTransition:({o:$},Z)=>sX(-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}}),_D=rX(Object.keys(jG)),[ID,M$]=P1(x4,gz,R5,{getISOFields:m3,with($,Z,J){return M$(Sz(this,uZ(Z),J))},add:($,Z)=>M$(FJ(0,$,W0(Z))),subtract:($,Z)=>M$(FJ(1,$,W0(Z))),until:($,Z,J)=>a(wJ(0,$,D$(Z),J)),since:($,Z,J)=>a(wJ(1,$,D$(Z),J)),round:($,Z)=>M$(Uj($,Z)),equals:($,Z)=>Wz($,D$(Z)),toZonedDateTime:($,Z)=>Q0(tz(t,w0,o,$,Z)),toPlainDateTime:($,Z)=>N0(rz($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=VD(Z,J,$);return W.format(Y)},toString:ZJ,toJSON:($)=>ZJ($),valueOf:K$},{from:($,Z)=>M$(D$($,Z)),compare:($,Z)=>F4(D$($),D$(Z))}),[xD,H$,CD]=P1(gZ,q(qz,_0),{...y3,...DD},{getISOFields:m3,getCalendar:v3,with($,Z,J){return H$(Cz(fD,$,this,uZ(Z),J))},add:($,Z,J)=>H$(VJ(aX,0,$,W0(Z),J)),subtract:($,Z,J)=>H$(VJ(aX,1,$,W0(Z),J)),until:($,Z,J)=>a(kJ(tX,0,$,pZ(Z),J)),since:($,Z,J)=>a(kJ(tX,1,$,pZ(Z),J)),equals:($,Z)=>Zz($,pZ(Z)),toPlainDate($,Z){return Y0(oz(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=FD(Z,J,$);return W.format(Y)},toString:e7,toJSON:($)=>e7($),valueOf:K$},{from:($,Z)=>H$(pZ($,Z)),compare:($,Z)=>n$(pZ($),pZ(Z))}),[AD,N0]=P1(e$,q(wz,_0),{...y3,...b5,...R5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return N0(Iz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>N0(M4($,_0(Z))),withPlainDate:($,Z)=>N0(zX($,w0(Z))),withPlainTime:($,Z)=>N0(jX($,A5(Z))),add:($,Z,J)=>N0(QJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>N0(QJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(bJ(T1,0,$,L$(Z),J)),since:($,Z,J)=>a(bJ(T1,1,$,L$(Z),J)),round:($,Z)=>N0(Fj($,Z)),equals:($,Z)=>ej($,L$(Z)),toZonedDateTime:($,Z,J)=>Q0(dz(o,$,t(Z),J)),toPlainDate:($)=>Y0(G0($)),toPlainTime:($)=>M$(X1($)),toPlainYearMonth($){return H$(cz(q4,$,this))},toPlainMonthDay($){return cZ(uz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=QD(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:K$},{from:($,Z)=>N0(L$($,Z)),compare:($,Z)=>AJ(L$($),L$(Z))}),[SD,Y0,zG]=P1(r$,q(fz,_0),{...y3,...b5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return Y0(xz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>Y0(M4($,_0(Z))),add:($,Z,J)=>Y0(BJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(BJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(RJ(T1,0,$,w0(Z),J)),since:($,Z,J)=>a(RJ(T1,1,$,w0(Z),J)),equals:($,Z)=>$z($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof f4?{timeZone:Z}:Z;return Q0(lz(t,D$,o,$,J))},toPlainDateTime:($,Z)=>N0(iz($,A5(Z))),toPlainYearMonth($){return H$(sz(q4,$,this))},toPlainMonthDay($){return cZ(nz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=BD(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:K$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>n$(w0($),w0(Z))}),k5={fields($,Z,J){return[...Z.call($,J)]}},XG=Object.assign({dateFromFields($,Z,J,W){return zG(Z.call($,Object.assign(Object.create(null),J),W))}},k5),GG=Object.assign({yearMonthFromFields($,Z,J,W){return CD(Z.call($,Object.assign(Object.create(null),J),W))}},k5),QG=Object.assign({monthDayFromFields($,Z,J,W){return TD(Z.call($,Object.assign(Object.create(null),J),W))}},k5),w5={mergeFields($,Z,J,W){return m1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},ED=Object.assign({},XG,w5),bD=Object.assign({},GG,w5),RD=Object.assign({},QG,w5),f5={dateAdd($,Z,J,W,Y){return zG(Z.call($,Y0(G0(J,$)),a(e(W)),Y))}},BG=Object.assign({},f5,{dateUntil($,Z,J,W,Y,j){return gD(Z.call($,Y0(G0(J,$)),Y0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:b3[Y]})))}}),kD=Object.assign({},f5,{day:$G}),wD=Object.assign({},BG,{day:$G}),q4=N1(GG),v4=N1(XG),g4=N1(QG),fD=N1(bD),h3=N1(ED),qD=N1(RD),ZZ=N1(f5),T1=N1(BG),aX=N1(kD),tX=N1(wD),[vD,a,gD]=P1(A4,yz,{...HD,blank:bj},{with:($,Z)=>a(Ez($,Z)),negated:($)=>a(X4($)),abs:($)=>a(Ej($)),add:($,Z,J)=>a(MJ(q3,T1,o,0,$,W0(Z),J)),subtract:($,Z,J)=>a(MJ(q3,T1,o,1,$,W0(Z),J)),round:($,Z)=>a(Sj(q3,T1,o,$,Z)),total:($,Z)=>Qj(q3,T1,o,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:K$},{from:($)=>a(W0($)),compare:($,Z,J)=>aj(q3,ZZ,o,W0($),W0(Z),J)}),VG={toString:($)=>$.id,toJSON:($)=>$.id,...OD,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),$j(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(vJ(Z,J,W,qY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>H$(gJ(Z,J,W,wY($))),monthDayFromFields:({id:$,o:Z},J,W)=>cZ(yJ(Z,0,J,W,fY($))),fields({o:$},Z){let J=new Set(G1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(sJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(A7(b7(Z)),A7(b7(J)))},[q5]=P1("Calendar",($)=>{let Z=Vz($);return{branding:"Calendar",id:Z,o:mZ(Z)}},{id:($)=>$.id},VG,{from($){let Z=_0($);return typeof Z=="string"?new q5(Z):Z}}),yD=rX(Object.keys(VG).slice(4)),[mD,Q0]=P1(u1,q(kz,_0,t),{...YG,...y3,...nX(b5),...nX(R5),offset:($)=>l$(I5($).offsetNanoseconds),offsetNanoseconds:($)=>I5($).offsetNanoseconds,timeZoneId:($)=>K0($.timeZone),hoursInDay:($)=>Oj(o,$)},{getISOFields:($)=>Cj(B0,$),getCalendar:v3,getTimeZone:({timeZone:$})=>typeof $=="string"?new f4($):$,with($,Z,J){return Q0(_z(h3,o,$,this,uZ(Z),J))},withCalendar:($,Z)=>Q0(M4($,_0(Z))),withTimeZone:($,Z)=>Q0(XX($,t(Z))),withPlainDate:($,Z)=>Q0(YX(o,$,w0(Z))),withPlainTime:($,Z)=>Q0(WX(o,$,A5(Z))),add:($,Z,J)=>Q0(GJ(ZZ,o,0,$,W0(Z),J)),subtract:($,Z,J)=>Q0(GJ(ZZ,o,1,$,W0(Z),J)),until:($,Z,J)=>a(e(EJ(T1,o,0,$,dZ(Z),J))),since:($,Z,J)=>a(e(EJ(T1,o,1,$,dZ(Z),J))),round:($,Z)=>Q0(Vj(o,$,Z)),startOfDay:($)=>Q0(Dj(o,$)),equals:($,Z)=>rj($,dZ(Z)),toInstant:($)=>k0(mz($)),toPlainDateTime:($)=>N0(dJ(B0,$)),toPlainDate:($)=>Y0(cJ(B0,$)),toPlainTime:($)=>M$(uJ(B0,$)),toPlainYearMonth($){return H$(hz(q4,$,this))},toPlainMonthDay($){return cZ(pz(g4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=GD(Z,J,$);return W.format(Y)},toString:($,Z)=>a7(B0,$,Z),toJSON:($)=>a7(B0,$),valueOf:K$},{from:($,Z)=>Q0(dZ($,Z)),compare:($,Z)=>CJ(dZ($),dZ(Z))}),hD=Object.defineProperties({},{...h6("Temporal.Now"),...d$({timeZoneId:()=>d1(),instant:()=>k0(M0(A3())),zonedDateTime:($,Z=d1())=>Q0(P0(A3(),t(Z),_0($))),zonedDateTimeISO:($=d1())=>Q0(P0(A3(),t($),v)),plainDateTime:($,Z=d1())=>N0(X0(qZ(B0(t(Z))),_0($))),plainDateTimeISO:($=d1())=>N0(X0(qZ(B0(t($))),v)),plainDate:($,Z=d1())=>Y0(G0(qZ(B0(t(Z))),_0($))),plainDateISO:($=d1())=>Y0(G0(qZ(B0(t($))),v)),plainTimeISO:($=d1())=>M$(X1(qZ(B0(t($)))))})}),lZ=Object.defineProperties({},{...h6("Temporal"),...d$({PlainYearMonth:xD,PlainMonthDay:KD,PlainDate:SD,PlainTime:ID,PlainDateTime:AD,ZonedDateTime:mD,Instant:PD,Calendar:q5,TimeZone:f4,Duration:vD,Now:hD})}),pD=JD(),v5=new WeakMap,dD=Object.defineProperties(Object.create(Intl),d$({DateTimeFormat:pD}));var y4="x-gemi-socket";var CN="gemi.v1",FG="/__gemi/socket",AN=/^[A-Za-z0-9_-]{1,32}$/,SN={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function kN($){return $}function UG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:FG,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 cD,randomBytes as uD}from"crypto";function lD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(cD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var iD="__control",g5=250,sD=1e4,nD=15000;class y5{config;prefix;controlChannel;instanceId=uD(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??lD(),this.controlChannel=this.prefix+iD,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 $})(),nD,"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 (${OG(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(sD,g5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(g5,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 (${OG(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??oD(Math.min(Z,g5));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 oD($){return new Promise((Z)=>setTimeout(Z,$))}function OG($){return $ instanceof Error?$.message:String($)}import{createHmac as aD,hkdfSync as tD,randomBytes as DG}from"crypto";function LG($){return aD("sha256",rD()).update($).digest("base64url").slice(0,22)}var m4=null;function rD(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from(tD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):DG(32);return m4={secret:$,key:Z},Z}function gN(){return DG(16).toString("base64url")}var eD=/^[A-Za-z0-9_-]{8,64}$/;function m5($){return typeof $==="string"&&eD.test($)}function MG($,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 KG 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 d0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=_1(UG(),$),this.driver=JL(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:UZ($),pattern:U0},null)}toOthers($){return new TG(this,ZL($))}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){v2(Z);let Y;try{Y=MG($.topic,Z,J,W?LG(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){iZ(()=>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=$L($);iZ(()=>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 KG(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 TG{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:UZ($),pattern:U0},this.except)}}function h4($,Z){if(q2($))return{topic:b8($.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:b8($)}}function $L($){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 ZL($){if($===null||$===void 0)return null;if(typeof $==="string")return m5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(y4);return m5(J)?J:null}function JL($,Z){let J=$.driver;if(J===void 0||J==="memory")return new HG;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new y5({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 h5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class WL{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 p5,createHmac as YL,randomBytes as PG,timingSafeEqual as IG}from"crypto";var u3=600,p4="gemi_oauth",jL=`__Host-${p4}`;function sZ($,Z=p4){if(Z===p4)return $?jL:p4;return $?`__Host-${Z}`:Z}function c3($){return $.toString("base64url")}function xG($){return YL("sha256",HZ()).update(`gemi-oauth-state:${$}`).digest()}function NG($,Z){let J=p5("sha256").update($).digest(),W=p5("sha256").update(Z).digest();return IG(J,W)&&$.length===Z.length}function d4($,Z=Date.now(),J={}){let W=c3(PG(32)),Y=c3(PG(32)),j=zL(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:XL(z)}}function zL($){return c3(p5("sha256").update($).digest())}function XL($){let Z=c3(Buffer.from(JSON.stringify($)));return`${Z}.${c3(xG(Z))}`}function GL($){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=xG(J);if(W.length!==Y.length||!IG(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 T$=new Map,_G=1e4;function QL($,Z,J){if(T$.size>=_G){for(let[W,Y]of T$)if(Y<=J)T$.delete(W);while(T$.size>=_G){let W=T$.keys().next().value;if(W===void 0)break;T$.delete(W)}}T$.set($,Z)}function c4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=GL($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=NG(J.state,$.returnedState),Y=NG(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(T$.has(J.state))return{ok:!1,reason:"invalid_state"};return QL(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var d5=new WeakMap;function VL($){let Z=d5.get($);if(!Z)Z=$(BL(32).toString("hex")),d5.set($,Z),Z.catch(()=>d5.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 u5 extends Error{}function c5($){return typeof $==="string"&&$!==""?$:null}function CG($){return g$($)}var FL=256;function AG($){return typeof $==="string"&&$!==""&&$.length<=FL?$:null}function SG($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function RG($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function EG($){let Z=$.cookies.get(i4);if(!Z)return null;RG($);try{return O1(decodeURIComponent(Z),"")||null}catch{return null}}class l5 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class kG extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class wG extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new q0("Not found",{status:404})}async function l1($,Z){if(!await w1(H(b).config[$],Z))l4()}async function l3($,Z,J,W){let{config:Y}=H(b),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await y$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function bG($,Z,J){let{config:W}=H(b);await l3("signIn",g$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function nZ($){return await w1(H(b).config.verifyEmail,$)}class $0 extends B3{async me(){let $=await f0.user();if(!$)throw new o8;return $}async verifyEmail($=new A){await l1("password",$);let Z=await $.input(),{userProvider:J}=H(b),W=c5(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(b),{userProvider:J}=Z;if(!await w1(Z.config.magicLink,$)&&!await w1(Z.config.emailCode.enabled,$))l4();let W=c5($.search.get("token")),Y=null;try{Y=g$(decodeURIComponent($.search.get("email")??""))}catch{}if(await y$("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(b).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 l1("magicLink",$);let Z=H(b),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=g$(W),z=AG(Y);if(await y$("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(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(b).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(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(b).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 l5){await l1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b);await bG(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(b).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,...V}=z;return V}async signIn($=new l5){await l1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b);await bG(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(b).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,...V}=z;return V}async signUp(){let $=H(b),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await l1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:SG(Y.toJSON()),req:W},V=CG(j);if(await l3("signUp",V,W),!V)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(V,!1))throw new u({email:["Email address already exists"]});let B=await J.hashPassword(z),U=H(c).detectLocale(W),D;if(G)D=await Z.findInvitation(G,V);let O,L="";if(D)O=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let M=await Z.createUser({email:V,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:D.organizationId,userId:M.id,organizationRole:D.role}),await J.onUserCreated(M,Q),M});else{if(L=await J.generateEmailVerificationToken(V),typeof J.verifyEmail==="function"&&!await nZ(W))L="";O=await Z.transaction(async()=>{let M=await Z.createUser({email:V,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(M,Q),M})}return await J.onSignUp(O,L,W.search.toJSON(),{req:W}),O}async signOut($=new A){let Z=b$($),J=H(b),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(b).accessTokenCookieOptions($,new Date(0))),H(b).cookieDomain($))$.ctx().setCookie("access_token","",{...H(b).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)UL(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new kG){await l1("password",$);let Z=await $.input(),J=CG(Z.get("email"));if(await l3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=H(b),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 wG){await l1("password",$);let{userProvider:Z,config:J}=H(b),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=c5(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 nZ($));if(!Q)throw new u({email:["User not found"]});let V=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:V}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new A){await l1("password",$);let{userProvider:Z,config:J}=H(b),W=await f0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await l3("signIn",g$(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(b).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await TZ(J,Z,$);if(!Y){if(W)throw new q0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=OZ($.rawRequest),z=O1($.search.get(l0),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else RG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:V}=d4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(sZ(j),V,{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(b),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await TZ(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 V=$.search.get("error");if(V)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");let F=c4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(F.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let x=await z.redirectUriFor($);if(x!==void 0&&x!==F.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:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(x){if(x instanceof h5)return this.oauthFailure($,x.code);return console.error("Authentication error: OAuth provider callback failed",x),this.oauthFailure($,"provider_error")}let{name:U,username:D,providerId:O,emailVerified:L}=B??{},M=typeof B?.email==="string"?B.email:void 0,T=M?N6(M):null,K=O?await W.findUserBySocialAccount(Z,O):null,N="signin",R=!K&&!T&&!M&&!!O&&z.createUsersWithoutEmail===!0;if(!K&&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{K=await this.createOAuthUserWithoutEmail({provider:Z,providerId:O,name:U,username:D,locale:H(c).detectLocale($),req:$}),N="signup"}catch(x){let f=await W.findUserBySocialAccount(Z,O);if(!f)throw x;K=f}}if(!K){if(!T)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,M?"invalid_email":O?"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(c).detectLocale($);try{let f=await this.linkOAuthAccount({provider:Z,providerId:O,email:T,rawEmail:M,name:U,username:D,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)K=f.user,N=f.action}catch(f){let _=O?await W.findUserBySocialAccount(Z,O):null;if(!_)throw f;K=_}if(!K)return this.oauthFailure($,"account_conflict")}let C=await J.createOrUpdateSessionV2({email:K.email,id:K.id});if($.ctx().setCookie("access_token",C.token,H(b).accessTokenCookieOptions($,C.expiresAt)),N==="signup")await Y.onSignUp(K,"",$.search.toJSON(),{req:$});else await Y.onSignIn(K,$.search.toJSON(),{req:$});await JZ(J.config,{session:C,user:K,isNewUser:N==="signup",method:"oauth",req:$});let S=EG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?O1(Y.oauthCompleteProfilePath,""):"";if(w&&!K.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(b);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=EG($),W=H(b).config.oauthFailurePath;if(W){let Y=O1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);b1.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(b),V=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!F&&B&&B!==W)F=await G.findUserByEmailAddress(B,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let D=await G.findSocialAccounts(F.id,Z);if(D.some((L)=>L.providerId===J))return{user:F,action:"signin"};if(D.some((L)=>L.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let O=D[0];if(O){if(!await G.claimSocialAccount(O,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(V(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(V(D.id));return await Q.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new A){await l1("magicLink",$);let Z=await $.input(),J=g$(Z.get("email")),W=H(b),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await y$("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(b),J=Z.config.emailCode;if(!await w1(J.enabled,$))l4();let W=await $.input(),Y=N6(W.get("email"));if(await y$("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(b),{userProvider:J,config:W}=Z;if(!await w1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=N6(j),Q=AG(z);if(await y$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new u({code:["invalid_code"]});let V=null;if(!c9(Q,W.emailCode)){let O=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(O.status==="too_many_attempts")throw new u({code:["too_many_attempts"]});if(O.status!=="ok")throw new u({code:["invalid_code"]});V=O.row}let F=async()=>V?await Z.claimOneTimeCode(G,V.id):!0,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await F())throw new u({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let O=H(c).detectLocale($);try{B=await J.transaction(async()=>{if(!await F())throw new u5;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:O});return await W.onUserCreated(L,{method:"email-code",input:SG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof u5)throw new u({code:["invalid_code"]});throw L}}else throw await F(),new u({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",D.token,H(b).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:D,isNewUser:U,method:"email-code",req:$}),{session:D,isNewUser:U}}}function UL($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(d0))return;J.make(d0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var fG="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=O1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=OZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=d4(qG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(sZ(z,fG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:u3}),b1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:vG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new A){let Z=String($.params.provider??""),J=H(i3),W=await f0.user(),Y=OZ($.rawRequest),j=sZ(Y,fG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=c4({provider:qG(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 V=$.search.get("error");if(V)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(V)?V:"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 F=$.search.get("code");if(!F)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:vG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await H(b).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof gG)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=$||O1(H(b).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw b1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function qG($){return`connection:${$}`}function vG($,Z,J){if(J)return J;return`${WZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function yG($){return $.magicLink!==!1||Y7($.emailCode?.enabled)}function mG($){return Object.keys($.oauthProviders??{}).length>0}function hG($={}){let Z=[];if(yG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Y7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(mG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class pG extends R1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([U6,"auth"])}}function dG($={}){let Z=yG($),J=mG($);class W extends R1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[$0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[$0,"oauthCallback"])}}return class extends R1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[$0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":pG}}}class i5 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 s5 extends x0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new A().params.locale;return await H(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new A,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class n5{}class o5 extends n5{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 a_($){return $}function cG(){return{driver:new o5,allowedHosts:[],maxSize:10485760,timeout:1e4}}class V0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var OL=new Set([301,302,303,307,308]),DL="/api/__gemi__/services/image/";async function lG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=uG($,Y);try{for(let z=0;;z++){let X=await LL(j,Z,W),G=X.headers.get("location");if(OL.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new V0(502,"The image redirects too many times");j=uG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new V0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new V0(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 HL(z,W)}}function uG($,Z){let J;try{J=new URL($,Z)}catch{throw new V0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new V0(400,"Only http(s) images can be resized");return J}async function LL($,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(DL))throw new V0(403,"This image source is not allowed");if(ML($.pathname))throw new V0(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 k1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new V0(403,"This image source is not allowed");return k1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function ML($){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 HL($,Z){if($ instanceof V0)return $;if(Z.aborted)return new V0(504,"The image took too long to load",{cause:$});if($ instanceof D6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new V0(403,"This image source is not allowed",{cause:$});case"too-large":return new V0(413,"The image is too large",{cause:$});case"timeout":return new V0(504,"The image took too long to load",{cause:$})}return new V0(502,"The image could not be loaded",{cause:$})}class a5 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 iG(400,"url query parameter is required");let X=H(sG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=WZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let V;try{V=await lG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof V0)return iG(U.status,U.message);throw U}let F=await X.resize(V.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(V.cacheControl)B.set("Cache-Control",V.cacheControl);return new Response(new Uint8Array(F),{headers:B})})}}function iG($,Z){return Response.json({error:Z},{status:$})}class sG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=cG();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 t5 extends x0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(nG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function VI($){return $}function oG(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function aG(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function KL($){return"run"in $}function TL($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function PL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function NL($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function _L($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function tG($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function IL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function r5($,Z="",J=[]){let W={};function Y(j,z,X,G,Q,V){let F=j==="/"?"":j,B=Z==="/"?"":Z,U=IL((`${B}${F}`===""?"/":`${B}${F}`).replaceAll("//","/"));if(!W[U])W[U]={};W[U][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{},...V?{bodyLimitDefault:V}:{}},W[U].OPTIONS={exec:()=>{let O=new A().ctx().headers;return new Response(null,{headers:O,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(_L(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])Y(j,G,X.run.bind(X),X.middlewares);continue}if(KL(z)){let X=z,G=X.method,Q=X.middlewares,V=X.run.bind(X);if(Y(j,G,V,Q,X.source,X.__internal_bodyLimitDefault),tG(z))Y(j,"HEAD",V,Q,X.source)}if(TL(z))for(let[X,G]of Object.entries(z)){let Q=G,V=Q.middlewares,F=Q.run.bind(Q);if(Y(j,X,F,V,Q.source,Q.__internal_bodyLimitDefault),X==="get"&&tG(Q))Y(j,"HEAD",F,V,Q.source)}if(NL(z)){let X=new z,G=r5(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[Q,V]of Object.entries(G)){let F=Q.replaceAll("//","/");W[F]={...W[F],...V}}}if(PL(z)){let{first:X,second:G}=z;for(let[Q,V]of Object.entries(X)){let F=V.middlewares,B=V.run.bind(V),[U,...D]=j.split("/").reverse();if(!U.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),Q,B,F,V.source)}for(let[Q,V]of Object.entries(G)){let F=V.middlewares,B=V.run.bind(V);Y(j,Q,B,F,V.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}var xL=Object.defineProperty,I=($,Z)=>xL($,"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 CL=/[$_\p{ID_Start}]/u,AL=/[$_\u200C\u200D\p{ID_Continue}]/u,$W=".*";function rG($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}I(rG,"isASCII");function WW($,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&&CL.test(G)||X!==W+1&&AL.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(!rG($[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(WW,"lexer");function YW($,Z={}){let J=WW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${c0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",G=new Set,Q=I((K)=>{if(z<J.length&&J[z].type===K)return J[z++].value},"tryConsume"),V=I(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),F=I((K)=>{let N=Q(K);if(N!==void 0)return N;let{type:R,index:C}=J[z];throw TypeError(`Unexpected ${R} at ${C}, expected ${K}`)},"mustConsume"),B=I(()=>{let K="",N;for(;N=Q("CHAR")??Q("ESCAPED_CHAR");)K+=N;return K},"consumeText"),U=I((K)=>K,"DefaultEncodePart"),D=Z.encodePart||U,O="",L=I((K)=>{O+=K},"appendToPendingFixedValue"),M=I(()=>{O.length&&(Y.push(new tZ(3,"","",D(O),"",3)),O="")},"maybeAddPartFromPendingFixedValue"),T=I((K,N,R,C,S)=>{let w=3;switch(S){case"?":w=1;break;case"*":w=0;break;case"+":w=2;break}if(!N&&!R&&w===3){L(K);return}if(M(),!N&&!R){if(!K)return;Y.push(new tZ(3,"","",D(K),"",w));return}let x;R?R==="*"?x=$W:x=R:x=W;let f=2;x===W?(f=1,x=""):x===$W&&(f=0,x="");let _;if(N?_=N:R&&(_=j++),G.has(_))throw TypeError(`Duplicate name '${_}'.`);G.add(_),Y.push(new tZ(f,_,D(K),x,D(C),w))},"addPart");for(;z<J.length;){let K=Q("CHAR"),N=Q("NAME"),R=Q("REGEX");if(!N&&!R&&(R=Q("ASTERISK")),N||R){let S=K??"";Z.prefixes.indexOf(S)===-1&&(L(S),S=""),M();let w=V();T(S,N,R,"",w);continue}let C=K??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();F("CLOSE");let _=V();T(S,w,x,f,_);continue}M(),F("END")}return Y}I(YW,"parse");function c0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(c0,"escapeString");function ZW($){return $&&$.ignoreCase?"ui":"u"}I(ZW,"flags");function eG($,Z,J){return jW(YW($,J),Z,J)}I(eG,"stringToRegexp");function YZ($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}I(YZ,"modifierToString");function jW($,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+=c0(X.value):W+=`(?:${c0(X.value)})${YZ(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${c0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=$W),!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+=`(?:${c0(X.prefix)}(${Q})${c0(X.suffix)})`,W+=YZ(X.modifier);continue}W+=`(?:${c0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=c0(X.suffix),W+=c0(X.prefix),W+=`(?:${Q}))*)${c0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${c0(J.endsWith)}]|$`,j=`[${c0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,ZW(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,ZW(J))}I(jW,"partsToRegexp");var N$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},SL={delimiter:".",prefixes:"",sensitive:!0,strict:!0},EL={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function $Q($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}I($Q,"isAbsolutePathname");function zW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}I(zW,"maybeStripPrefix");function ZQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}I(ZQ,"maybeStripSuffix");function XW($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}I(XW,"treatAsIPv6Hostname");var JQ=["ftp","file","http","https","ws","wss"];function GW($){if(!$)return!0;for(let Z of JQ)if($.test(Z))return!0;return!1}I(GW,"isSpecialScheme");function WQ($,Z){if($=zW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}I(WQ,"canonicalizeHash");function YQ($,Z){if($=zW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}I(YQ,"canonicalizeSearch");function jQ($,Z){return Z||$===""?$:XW($)?VW($):BW($)}I(jQ,"canonicalizeHostname");function zQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}I(zQ,"canonicalizePassword");function XQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}I(XQ,"canonicalizeUsername");function GQ($,Z,J){if(J||$==="")return $;if(Z&&!JQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}I(GQ,"canonicalizePathname");function QQ($,Z,J){return QW(Z)===$&&($=""),J||$===""?$:FW($)}I(QQ,"canonicalizePort");function BQ($,Z){return $=ZQ($,":"),Z||$===""?$:o4($)}I(BQ,"canonicalizeProtocol");function QW($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}I(QW,"defaultPortForProtocol");function o4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}I(o4,"protocolEncodeCallback");function VQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}I(VQ,"usernameEncodeCallback");function FQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}I(FQ,"passwordEncodeCallback");function BW($){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(BW,"hostnameEncodeCallback");function VW($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}I(VW,"ipv6HostnameEncodeCallback");function FW($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}I(FW,"portEncodeCallback");function UQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}I(UQ,"standardURLPathnameEncodeCallback");function OQ($){return $===""?$:new URL(`data:${$}`).pathname}I(OQ,"pathURLPathnameEncodeCallback");function DQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}I(DQ,"searchEncodeCallback");function LQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}I(LQ,"hashEncodeCallback");var MQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#Q=0;#X=0;#U=0;#O=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=WW(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#K(),this.#B()?this.#J(9,1):this.#V()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#F(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.#T()&&this.#F(1);break;case 1:if(this.#T()){this.#E();let $=7,Z=1;this.#N()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#M()?this.#F(3):(this.#H()||this.#V()||this.#B())&&this.#F(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.#O+=1:this.#S()&&(this.#O-=1),this.#I()&&!this.#O?this.#J(6,1):this.#H()?this.#J(7,0):this.#V()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#V()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 7:this.#V()?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.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#P($,Z)}#P($,Z){this.#X=$,this.#Q=this.#$+Z,this.#$+=Z,this.#Y=0}#K(){this.#$=this.#Q,this.#Y=0}#F($){this.#K(),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")}#T(){return this.#z(this.#$,":")}#N(){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.#$,"/")}#V(){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)}#E(){let $={};Object.assign($,N$),$.encodePart=o4;let Z=eG(this.#G(),void 0,$);this.#D=GW(Z)}};I(MQ,"Parser");var e5=["protocol","username","password","hostname","port","pathname","search","hash"],P$="*";function JW($,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(JW,"extractValues");function I1($,Z){return Z?aZ($):$}I(I1,"processBaseURLString");function oZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=I1(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=I1(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=I1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=I1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=I1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=I1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=I1(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=I1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=BQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=XQ(Z.username,J)),typeof Z.password=="string"&&($.password=zQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=jQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=QQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!$Q($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=I1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=GQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=YQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=WQ(Z.hash,J)),$}I(oZ,"applyInit");function aZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}I(aZ,"escapePatternString");function HQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(HQ,"escapeRegexpString");function KQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${HQ(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)),V=z>0?$[z-1]:null,F=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&F&&!F.prefix.length&&!F.suffix.length)if(F.type===3){let B=F.value.length>0?F.value[0]:"";Q=Y.test(B)}else Q=!F.hasCustomName();if(!Q&&!X.prefix.length&&V&&V.type===3){let B=V.value[V.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&&(!V||V.type===3||V.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(KQ,"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 MQ($);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:P$,protocol:P$,username:P$,password:P$,hostname:P$,port:P$,search:P$,hash:P$};this.#j=oZ(j,$,!0),QW(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of e5){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,N$),X.encodePart=o4;break;case"username":Object.assign(X,N$),X.encodePart=VQ;break;case"password":Object.assign(X,N$),X.encodePart=FQ;break;case"hostname":Object.assign(X,SL),XW(G)?X.encodePart=VW:X.encodePart=BW;break;case"port":Object.assign(X,N$),X.encodePart=FW;break;case"pathname":GW(this.#W.protocol)?(Object.assign(X,EL,Y),X.encodePart=UQ):(Object.assign(X,N$,Y),X.encodePart=OQ);break;case"search":Object.assign(X,N$,Y),X.encodePart=DQ;break;case"hash":Object.assign(X,N$,Y),X.encodePart=LQ;break}try{this.#Y[z]=YW(G,X),this.#W[z]=jW(this.#Y[z],this.#Z[z],X),this.#$[z]=KQ(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,JW($,Z),!1)}catch{return!1}let W;for(W of e5)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,JW($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of e5){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 V=W(X[Q],G[Q]);if(V)return V}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 UW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function OW($){let Z=a4($);return Z.length>1?Z.replace(/\/$/,""):Z}function TQ($,Z){return Z.map((J)=>({...J,path:OW(UW($,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:V,features:F,static:B}]of Object.entries(z)){let U=UW(J,X),D=(O)=>Y.run.call(Y,O,J);Z[a4(U)]={exec:[D,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:OW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...TQ(J,V)],...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:OW(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:V,features:F,static:B}]of Object.entries(j)){let U=UW(J,z);Z[a4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Q,segments:TQ(J,V),...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 DW="theme";function PQ($){return $==="light"||$==="dark"||$==="system"}function NQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
9
+ `}function u8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",IF);return new Response($,{status:Z,headers:W})}function AF($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function SF($,Z={}){let J=P9($,Z),W=AF(Z.page);if(W!==null){let j=J[W-1];return j?u8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return u8(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 u8(N9(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function l8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function K9($,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 D=U.trim()?l8(U):null;if(D)B.push({loc:D})}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,V="",F=()=>Y==="index"?z.length:j.length;if(U9(W,{stopped:()=>F()>=J,open(B,U){let D=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"&&D==="urlset"||Y==="index"&&B==="sitemap"&&D==="sitemapindex")G={};else if(G&&(D==="url"||D==="sitemap")&&(B==="loc"||B==="lastmod"||B==="changefreq"||B==="priority"))Q=B,V="";else if(G&&Y==="urlset"&&D==="url"&&B==="link"){let O=U.href?l8(U.href):null;if(U.rel?.toLowerCase()==="alternate"&&U.hreflang&&O)(G.alternates??=[]).push({hrefLang:U.hreflang,href:O})}},close(B){let U=X.lastIndexOf(B);if(U===-1)return;if(X.length=U,Q&&B===Q&&G)G[Q]=V.trim(),Q=null;else if(G&&(B==="url"||B==="sitemap")){let D=G;G=null,Q=null;let O=D.loc?l8(D.loc):null;if(!O)return;if(Y==="index"){z.push(D.lastmod?{loc:O,lastmod:D.lastmod}:{loc:O});return}let L={loc:O};if(D.lastmod)L.lastmod=D.lastmod;if(D.changefreq)L.changefreq=D.changefreq;let M=D.priority?Number(D.priority):NaN;if(Number.isFinite(M))L.priority=M;if(D.alternates)L.alternates=D.alternates;j.push(L)}},text(B){if(Q)V+=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*EF($,Z={}){let{maxUrls:J=v$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=Q3,onError:z,...X}=Z,G=[{url:String($),depth:0}],Q=new Set,V=0,F=0;while(G.length>0&&F<J&&V<W){let B=G.shift(),U=B.url.replace(/#.*$/,"");if(Q.has(U))continue;Q.add(U),V++;let D;try{let O=await k1(B.url,{...X,maxSize:j});if(!O.ok)throw O.body?.cancel().catch(()=>{}),new j0(`Sitemap: ${B.url} answered ${O.status}.`,B.url,O.status);let L=H6(await M6(O,j));D=K9(L,{maxUrls:Math.max(J-F,W-V)})}catch(O){if(B.depth===0||!z||X.signal?.aborted)throw O;z(O,B.url);continue}if(D.kind==="index"){if(B.depth>=Y)continue;G=D.sitemaps.slice(0,W-V).map((L)=>({url:L.loc,depth:B.depth+1})).concat(G);continue}for(let O of D.urls)if(yield{...O,sitemap:B.url},++F>=J)return}}var _9={response:SF,chunk:P9,index:N9,parse:K9,read:EF,MAX_URLS:v$,MAX_BYTES:Q3};var bF=512000,RF=new TextEncoder;function I9($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function x9($){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 RF.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function kF($,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=I9($)||"*";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=x9(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!kF(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 wF={"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 C9($,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 V=wF[G.slice(0,Q).trim().toLowerCase()],F=G.slice(Q+1).trim();if(!V)continue;if(V==="sitemap"){if(!F||/\s/.test(F))continue;try{let B=Z.url?new URL(F,Z.url):new URL(F);if(B.protocol==="http:"||B.protocol==="https:")W.push(B.href)}catch{}continue}if(V==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let B=I9(F);if(B)Y.userAgents.push(B);continue}if(!Y)continue;if(j=!1,V==="crawl-delay"){let B=Number(F);if(Number.isFinite(B)&&B>=0)Y.crawlDelay=B;continue}if(!F)continue;Y.rules.push({type:V,path:x9(F)})}return new MZ(J,W)}async function fF($,Z={}){let{maxSize:J=bF,...W}=Z,Y=new URL("/robots.txt",$),j=await k1(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 C9(G,{url:j.url})}function n8($){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 A9($){let Z=[];for(let W of $.rules??[]){let Y=n8(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=[...n8(W.allow).map((X)=>["Allow",X]),...n8(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
+ `;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 qF($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(A9($),{status:200,headers:J})}var S9={response:qF,text:A9,parse:C9,fetch:fF};import{createHmac as E9,randomBytes as vF}from"crypto";var a8="v2.";function t8($){return $.startsWith(a8)}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 b9($){let Z=vF(16).toString("hex"),J=E9("sha256",HZ()).update(`${$}:${Z}`).digest("hex");return`${a8}${J}`}function P6($,Z){let J=E9("sha256",HZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${a8}${J}`}import{createHash as mF,createHmac as hF,randomInt as pF,timingSafeEqual as w9}from"crypto";function R9($,Z){return Math.floor($/Z)*Z}function gF($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function r8($,Z,J,W){return Z*gF(J,W)+$}function yF($){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 V=Y*(1-(X-Z)/J);if(V<=Y)return Math.max(0,Math.ceil(V-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 k9($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:G}=$;if(Z){let V=r8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-V)),resetAt:Y-j+z,retryAfter:0}}let Q=yF({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 e8{}class $7 extends e8{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=R9(j,W),X=j-z,G=this.roll(Z,W,z);G.limit=J;let V=r8(G.current,G.previous,X,W)+Y<=J;if(V)G.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,G),this.buckets.size>this.maxKeys)this.evict(j);return k9({allowed:V,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 q9="h1.";function N6($,Z,J){let W=hF("sha256",HZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${q9}${W}`}function TZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(q9),X=N6($,Z,Y),G=Buffer.from(z?X:Y),Q=Buffer.from(j);if(G.length!==Q.length||Y===""||j==="")return w9(G,G),!1;return w9(G,Q)}function v9($){let Z="";for(let J=0;J<$;J++)Z+=String(pF(0,10));return Z}var g9=320;function g$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>g9)return null;return Z.toLowerCase()}function K6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>g9)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var f9=null;function y9(){try{let $=H();if(typeof $?.bound==="function"&&$.bound(D1))return $.make(D1)}catch{}return f9??=new D1({driver:new $7,limit:1000,window:60}),f9}function Z7($){return $.length<=64?$:`sha256:${mF("sha256").update($).digest("hex")}`}function dF($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function y$($,Z,J,W,Y,j){let z=y9(),X=[["perIp",`ip:${Z7(DZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${Z7(Z)}`,W.perEmail]);for(let[G,Q,V]of X){if(!V)continue;let F=Y?await Y({req:J,scope:$,limit:G}):void 0,B=dF($),U=F?`${B}:p:${Z7(String(F))}:${Q}`:`${B}:${Q}`,[D,O]=V,L=await z.consume(U,{limit:D,window:O});if(!L.allowed)throw await j?.(G),new J$(L)}}async function m9($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await y9().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as W7}from"crypto";class J7 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 cF,timingSafeEqual as uF}from"crypto";function p9($){let Z=$??process.env.AUTH_FIXED_CODE;return typeof Z==="string"&&Z!==""?Z:null}function d9($){if($!==void 0&&$!==null)return $===!0;return process.env.AUTH_FIXED_CODE_ALLOW_PRODUCTION==="1"}var lF="[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 c9($={},{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=p9(J);if(Y===null)return;let j=J?"auth.emailCode.fixedCode":"AUTH_FIXED_CODE",z=Bun.env.NODE_ENV==="production";if(z&&!d9(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(lF)}function iF($={}){if(Bun.env.NODE_ENV==="production"&&!d9($.allowFixedCodeInProduction))return null;return p9($.fixedCode)}function h9($){return cF("sha256").update($).digest()}function u9($,Z={}){let J=iF(Z);if(J===null||typeof $!=="string"||$==="")return!1;return uF(h9($),h9(J))}async function w1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Y7($){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 sF($={}){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 z7($={}){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),c9($),{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 nF($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function l9($){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 i9($){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 uN($){return $}function s9($={}){return sF($),{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:J7,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:nF,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>W7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return W7(32).toString("hex")},generateMagicLinkToken:()=>W7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:z7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var oF=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),aF=new Set(["svg","math"]);function n9($){return $===32||$===9||$===10||$===12||$===13}function o9($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function a9(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,G=0,Q=()=>$==="data"&&X===0&&G===0,V=()=>{if(!J&&oF.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(aF.has(Z)){if(J)G=Math.max(0,G-1);else if(!z)G+=1}Z=""},F=(B)=>{switch($){case"data":if(B===60)$="tagOpen";return;case"tagOpen":if(B===33)$="bang",j=0;else if(B===47)$="endTagOpen";else if(o9(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(o9(B))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(B));else if(B===62)$="data";else $="bogus";return;case"tagName":if(n9(B)||B===47)$="inTag",z=B===47;else if(B===62)V();else Z+=String.fromCharCode(_6(B));return;case"inTag":if(B===62){V();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(n9(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;F(B[U])}return B.length},write(B){for(let U=0;U<B.length;U++)F(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 t9($){return $?`<script nonce="${$}">`:"<script>"}function tF($,Z){let J=i0([$.path,$.variantKey,$.data]);return`${t9(Z)}(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${J})</script>`}function rF($,Z){let J=i0([$.id,$.locale,$.strings]);return`${t9(Z)}(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${J})</script>`}function X7($,Z,J={},W,Y){let j=new TextEncoder,z=[],X=!1,G=!1,Q=()=>{if(G)return;G=!0,J.onClose?.()};Z.onSettle((O)=>{if(O.status!=="resolved")return;z.push(tF(O,Y))}),W?.onUse((O)=>{z.push(rF(O,Y))});let V=$.getReader(),F=a9(),B=(O,L)=>{O.enqueue(L),J.onChunk?.(L)},U=(O)=>{while(z.length>0){let L=j.encode(z.shift());F.write(L),B(O,L)}},D=(O,L)=>{if(z.length===0){F.write(L),B(O,L);return}let M=F.scanToInsertionPoint(L);if(M>0)B(O,L.subarray(0,M));if(F.isSafe())U(O);let T=L.subarray(M);if(T.length>0)F.write(T),B(O,T)};return new ReadableStream({async pull(O){let L;try{L=await V.read()}catch(P){throw Q(),P}let{done:M,value:T}=L;if(M){U(O),O.close(),Q();return}if(!X){if(X=!0,F.write(T),B(O,T),J.onShell?.(),F.isSafe())U(O);return}D(O,T)},cancel(O){return Q(),V.cancel(O)}})}var eF=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return eF.test($)}async function e9($,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 $U($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:r9(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function $Y($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function $U($,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 ZY($,Z){return`${$}:${Z}`}function G7($){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 WY($,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=JU($,Z,J,W.buckets);return JY(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function ZU($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function JU($,Z,J,W){let Y=ZY(Z.salt??$,ZU(J));if(!W)return G7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=G7(Y);return W.set(Y,z),z}class YY 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 Q7{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 YY(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=WU(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 WU($){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 YU{}class jU 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 B7 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 jY 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 zY{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 W${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new Q7($.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 jY(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=zU(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new B7(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 zY(this,$Y($))}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=WY($,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 e9(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 zU($){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 XY($){if($===void 0)return!0;return await H(W$).enabled($)}function GY(){try{return N.getStore()?.req??null}catch{return null}}async function PZ($,Z,J=GY()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=l9($[Z]);if(!W||!await XY(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await w1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function QY($,Z=GY()){let J=[];for(let W of Object.keys($))if(await PZ($,W,Z))J.push(W);return J}function V7($){if($&&typeof $==="object")delete $.password;return $}function XU(){return new Proxy({},{get:($,Z)=>VY(Z)})}var BY=new WeakMap;function FY($){if($&&typeof $==="object"){for(let Z of Object.values($))FY(Z);Object.freeze($)}return $}var GU={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},QU=FY({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:GU});class F7{models;constructor($=XU()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return QU}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??f1(),W=H(q1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await s0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||s0())return Y();let z=(BY.get(W)??Promise.resolve()).then(Y,Y);return BY.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return V7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return V7(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?V7(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 UL}from"crypto";function v0($,Z,J,W,Y){return $1(Z,SY($,Z),J,W,Y)}function $1($,Z,J,W,Y,j){let z=M7(Z,J,W);if(Y&&Z!==z)throw RangeError(VX($,Z,J,W,j));return z}function SY($,Z){let J=$[Z];if(J===void 0)throw TypeError(iJ(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 x7($){return d$({name:$},1)}function d$($,Z){return Y1((J)=>({value:J,configurable:1,writable:!Z}),$)}function EY($){return Y1((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 Y1($,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 BU($,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 C7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function A7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function bY($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function RY($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function kY($,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 UY($){return $[0].toUpperCase()+$.substring(1)}function N3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function Y$($,Z){return Math.sign($-Z)}function M7($,Z,J){return Math.min(Math.max($,Z),J)}function g1($,Z){return[Math.floor($/Z),U3($,Z)]}function U3($,Z){return($%Z+Z)%Z}function X$($,Z){return[p6($,Z),S7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function S7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function wY($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let G=$[J[X]],Q=M1[X],V=s/Q,[F,B]=X$(G,V);W+=B*Q,Y+=F}let[j,z]=X$(W,s);return[Y+j,z]}function d6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=M1[Y];W[J[Y]]=p6($,j),$=S7($,j)}return W}function fY($){return $===v?K4:[]}function qY($){return $===v?R3:[]}function vY($){return $===v?["year","day"]:[]}function gY($){if($!==void 0)return J0($)}function yY($){if($!==void 0)return j1($)}function E7($){if($!==void 0)return K3($)}function j1($){return pY(K3($))}function K3($){return hY(ZO($))}function b7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function mY($,Z){if(Z==null)throw RangeError(iJ($));return Z}function m1($){if(!L0($))throw TypeError(BX);return $}function c6($,Z,J=$){if(typeof Z!==$)throw TypeError(S3(J,Z));return Z}function hY($,Z="number"){if(!Number.isInteger($))throw RangeError(CU(Z,$));return $||0}function pY($,Z="number"){if($<=0)throw RangeError(AU(Z,$));return $}function R7($){if(typeof $=="symbol")throw TypeError(RU);return String($)}function k6($,Z){return L0($)?String($):J0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(bU($));return $}function dY($,Z="number"){if(typeof $=="bigint")throw TypeError(EU(Z));if($=Number($),!Number.isFinite($))throw RangeError(SU(Z,$));return $}function C0($,Z){return Math.trunc(dY($,Z))||0}function cY($,Z){return hY(dY($,Z),Z)}function OY($,Z){return pY(C0($,Z),Z)}function k7($,Z){let[J,W]=X$(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 k7($[0]+Z[0]*J,$[1]+Z[1]*J)}function _Z($,Z){return k7($[0],$[1]+Z)}function n0($,Z){return KZ(Z,$,-1)}function S0($,Z){return Y$($[0],Z[0])||Y$($[1],Z[1])}function uY($,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]=X$($,J);return[W,Y*Z]}function lY($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=s/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function o0($,Z=1,J){let[W,Y]=$,[j,z]=X$(Y,Z);return W*(s/Z)+(j+(J?z/Z:0))}function w7($,Z,J=g1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(s/Z)+j,z]}function f7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function q7($){return v0($,"isoYear",T3,H3,1),$.isoYear===T3?v0($,"isoMonth",4,12,1):$.isoYear===H3&&v0($,"isoMonth",1,9,1),$}function j$($){return h1({...$,...W1,isoHour:12}),$}function h1($){let Z=v0($,"isoYear",T3,H3,1),J=Z===T3?1:Z===H3?-1:0;return J&&a0(A0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function a0($){if(!$||uY($,GO,XO))throw RangeError(H4);return $}function G$($){return wY($,5,Q1)[1]}function i6($){let[Z,J]=g1($,s);return[d6(J,5,Q1),Z]}function iY($){return sY($)[0]}function sY($){return w7($,J1)}function E0($){return SZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function A0($){let Z=E0($);if(Z!==void 0){let[J,W]=X$(Z,y0);return[J,W*H1+($.isoMicrosecond||0)*t$+($.isoNanosecond||0)]}}function v7($,Z){let[J,W]=i6(G$($)-Z);return a0(A0({...$,isoDay:$.isoDay+W,...J}))}function w6(...$){return SZ(...$)/KX}function SZ(...$){let[Z,J]=nY(...$),W=Z.valueOf();if(!isNaN(W))return W-J*y0}function nY($,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 B$($,Z){let[J,W]=_Z($,Z);W<0&&(W+=s,J-=1);let[Y,j]=g1(W,H1),[z,X]=g1(j,t$);return s6(J*y0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-zO)/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 oY($){return[$.isoYear,$.isoMonth,$.isoDay]}function aY(){return v1}function g7($,Z){switch(Z){case 2:return y7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function tY($){return y7($)?366:365}function y7($){return $%4==0&&($%100!=0||$%400==0)}function rY($){let[Z,J]=nY($.isoYear,$.isoMonth,$.isoDay);return U3(Z.getUTCDay()-J,7)||7}function eY({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function VU($){let Z=E0($);if(Z<BO)return eY($);let J=f7(B5(xZ),Z),{era:W,eraYear:Y}=Bz(J,xZ);return[W,Y]}function n6($){return c$($),o6($,1),$}function c$($){return $j($,1),$}function DY($){return RY(J5,$,$j($))}function $j($,Z){let{isoYear:J}=$,W=v0($,"isoMonth",1,aY(),Z);return{isoYear:J,isoMonth:W,isoDay:v0($,"isoDay",1,g7(J,W),Z)}}function o6($,Z){return AZ(Q1,[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:mX(m1($))}function _3($,Z=0){$=z1($);let J=hX($),W=PO($,Z);return[mX($),W,J]}function m7($){return hX(z1($))}function Zj($){return $=z1($),j5($,9,6,1)}function EZ($,Z,J,W=9,Y=0,j=4){Z=z1(Z);let z=j5(Z,W,Y),X=d7(Z),G=w3(Z,j),Q=k3(Z,W,Y,1);return z==null?z=Math.max(J,Q):jj(z,Q),X=c7(X,Q,1),$&&(G=((V)=>V<4?(V+2)%4:V)(G)),[z,Q,X,G]}function a6($,Z=6,J){let W=d7($=u7($,m6)),Y=w3($,7),j=k3($,Z);return j=mY(m6,j),W=c7(W,j,void 0,J),[j,W,Y]}function h7($){return z5(z1($))}function Jj($,Z){return p7(z1($),Z)}function p7($,Z=4){let J=Yj($);return[w3($,4),...Wj(k3($,Z),J)]}function Wj($,Z){return $!=null?[M1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function d7($){let Z=$[O3];return Z===void 0?1:C0(Z,O3)}function c7($,Z,J,W){let Y=W?s:M1[Z+1];if(Y){let j=M1[Z];if(Y%(($=$1(O3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(S3(O3,$))}else $=$1(O3,$,1,J?1e9:1,1);return $}function Yj($){let Z=$[L7];if(Z!==void 0){if(typeof Z!="number"){if(R7(Z)==="auto")return;throw RangeError(S3(L7,Z))}Z=$1(L7,Math.floor(Z),0,9,1)}return Z}function z1($){return $===void 0?{}:m1($)}function u7($,Z){return typeof $=="string"?{[Z]:$}:m1($)}function z0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(BX)}}function t6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:FO[Z]})}function l7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=R7(j),j==="auto")return Y?W:null;let z=N7[j];if(z===void 0&&(z=YO[j]),z===void 0)throw RangeError(OX($,j,N7));return $1($,z,W,J,1,b3),z}function u$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=R7(Y),z=Z[j];if(z===void 0)throw RangeError(OX($,j,Z));return z}function jj($,Z){if(Z>$)throw RangeError(aU)}function M0($){return{branding:C4,epochNanoseconds:$}}function N0($,Z,J){return{branding:u1,calendar:J,timeZone:Z,epochNanoseconds:$}}function X0($,Z=$.calendar){return{branding:e$,calendar:Z,...p0(qX,$)}}function G0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0(W5,$)}}function h$($,Z=$.calendar){return{branding:gZ,calendar:Z,...p0(W5,$)}}function f6($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(W5,$)}}function X1($){return{branding:x4,...p0(fX,$)}}function e($){return{branding:A4,sign:V$($),...p0(eJ,$)}}function zj($){return iY($.epochNanoseconds)}function r6($){return w7($.epochNanoseconds,H1)[0]}function Xj($){return lY($.epochNanoseconds,t$)}function Gj($){return lY($.epochNanoseconds)}function Qj($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:J0($.id)}function bZ($,Z){return $===Z||T0($)===T0(Z)}function Bj($,Z,J,W,Y){let j=p$(W),[z,X]=((L,M)=>{let T=M((L=u7(L,I7))[gX]),P=TO(L);return P=mY(I7,P),[P,T]})(Y,$);if(L3(Math.max(z,j),X))return LY(W,z);if(!X)throw RangeError(T4);let[G,Q,V]=Y4(Z,J,X),F=DJ(V),B=j4(V),U=LJ(V),D=B(Q,G,W),O=U(Q,G,D,z);return L3(z,X)?LY(O,z):((L,M,T,P,K,R,C)=>{let S=V$(L),[w,x]=i7(P,Z5(T,L),T,S,K,R,C),f=s7(M,w,x);return L[p[T]]+f*S})(O,F(D),z,Q,G,F,B)}function LY($,Z){return o0(D0($),M1[Z],1)}function i7($,Z,J,W,Y,j,z){let X=p[J],G={...Z,[X]:Z[X]+W},Q=z($,Y,Z),V=z($,Y,G);return[j(Q),j(V)]}function s7($,Z,J){let W=o0(n0(Z,J));if(!W)throw RangeError(E3);return o0(n0(Z,$))/W}function Vj($,Z){let[J,W,Y]=a6(Z,5,1);return M0($4($.epochNanoseconds,J,W,Y,1))}function Fj($,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=((V,F,B,U)=>{let D=b0(B,F),[O,L]=V(D),M=B.epochNanoseconds,T=h0(F,O),P=h0(F,L);if(uY(M,T,P))throw RangeError(E3);return Nj(s7(M,T,P),U)?P:T})(Tj,Q,Z,G);else{let V=Q.getOffsetNanosecondsFor(W);W=i$(Q,Mj(B$(W,V),z,X,G),V,2,0,1)}return N0(W,Y,j)}function Uj($,Z){return X0(Mj($,...a6(Z)),$.calendar)}function Oj($,Z){let[J,W,Y]=a6(Z,5);var j;return X1((j=Y,n7($,I3(J,W),j)[0]))}function Dj($,Z){let J=$(Z.timeZone),W=b0(Z,J),[Y,j]=Tj(W),z=o0(n0(h0(J,Y),h0(J,j)),N4,1);if(z<=0)throw RangeError(E3);return z}function Lj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(b0(X,z))))(Pj,$(J),Z);return N0(Y,J,W)}function Mj($,Z,J,W){return Hj($,I3(Z,J),W)}function Hj($,Z,J){let[W,Y]=n7($,Z,J);return h1({...s$($,Y),...W})}function n7($,Z,J){return i6(Q$(G$($),Z,J))}function q6($){return Q$($,P4,7)}function I3($,Z){return M1[$]*Z}function Tj($){let Z=Pj($);return[Z,s$(Z,1)]}function Pj($){return jO(6,$)}function FU($,Z,J){let W=Math.min(p$($),6);return kZ(Z4(D0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,G,Q){if(W===0&&Y===1)return $;let V=L3(W,X)?z4(X)&&W<6&&J>=6?OU:UU:DU,[F,B,U]=V($,Z,J,W,Y,j,z,X,G,Q);return U&&W!==7&&(F=((D,O,L,M,T,P,K,R)=>{let C=V$(D);for(let S=M+1;S<=L;S++){if(S===7&&L!==7)continue;let w=Z5(S,D);w[p[S]]+=C;let x=o0(n0(K(R(T,P,w)),O));if(x&&Math.sign(x)!==C)break;D=w}return D})(F,B,J,Math.max(6,W),z,X,G,Q)),F}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/s)($);return[Q$(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]=g1(Q$(j,Z,J),s);return k7(Y+z,X)}function Q$($,Z,J){return Nj($/Z,J)*Z}function Nj($,Z){return _O[Z]($)}function UU($,Z,J,W,Y,j){let z=V$($),X=D0($),G=$4(X,W,Y,j),Q=n0(X,G),V=Math.sign(G[0]-X[0])===z,F=kZ(G,Math.min(J,6));return[{...$,...F},KZ(Z,Q),V]}function OU($,Z,J,W,Y,j,z,X,G,Q){let V=V$($),F=o0(D0($,5)),B=I3(W,Y),U=Q$(F,B,j),[D,O]=i7(z,{...$,...$5},6,V,X,G,Q),L=U-o0(n0(D,O)),M=0;L&&Math.sign(L)!==V?Z=_Z(D,U):(M+=V,U=Q$(L,B,j),Z=_Z(O,U));let T=G4(U);return[{...$,...T,days:$.days+M},Z,Boolean(M)]}function DU($,Z,J,W,Y,j,z,X,G,Q){let V=V$($),F=p[W],B=Z5(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let U=p6($[F],Y)*Y;B[F]=U;let[D,O]=i7(z,B,W,Y*V,X,G,Q),L=U+s7(Z,D,O)*V*Y,M=Q$(L,Y,j),T=Math.sign(M-L)===V;return B[F]=M,[B,T?O:D,T]}function o7($,Z,J,W){let[Y,j,z,X]=((Q)=>{let V=p7(Q=z1(Q));return[Q.timeZone,...V]})(W),G=Y!==void 0;return((Q,V,F,B,U,D)=>{F=Z4(F,U,B,1);let O=V.getOffsetNanosecondsFor(F);return JJ(B$(F,O),D)+(Q?l$(q6(O)):"Z")})(G,Z(G?$(Y):$Z),J.epochNanoseconds,j,z,X)}function a7($,Z,J){let[W,Y,j,z,X,G]=((Q)=>{Q=z1(Q);let V=z5(Q),F=Yj(Q),B=KO(Q),U=w3(Q,4),D=k3(Q,4);return[V,NO(Q),B,U,...Wj(D,F)]})(J);return((Q,V,F,B,U,D,O,L,M,T)=>{B=Z4(B,M,L,1);let P=Q(F).getOffsetNanosecondsFor(B);return JJ(B$(B,P),T)+l$(q6(P),O)+((K,R)=>R!==1?"["+(R===2?"!":"")+T0(K)+"]":"")(F,D)+WJ(V,U)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,G)}function t7($,Z){let[J,W,Y,j]=((Q)=>(Q=z1(Q),[z5(Q),...p7(Q)]))(Z);return z=$.calendar,X=J,G=j,JJ(Hj($,Y,W),G)+WJ(z,X);var z,X,G}function r7($,Z){return J=$.calendar,W=$,Y=h7(Z),v6(W)+WJ(J,Y);var J,W,Y}function e7($,Z){return Kj($.calendar,_j,$,h7(Z))}function $J($,Z){return Kj($.calendar,LU,$,h7(Z))}function ZJ($,Z){let[J,W,Y]=Jj(Z);return j=Y,Ij(n7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=Jj(Z,3);return W>1&&($={...$,...FU($,W,J)}),((j,z)=>{let{sign:X}=j,G=X===-1?R0(j):j,{hours:Q,minutes:V}=G,[F,B]=w7(D0(G,3),J1,X$);kj(F);let U=YJ(B,z),D=z>=0||!X||U;return(X<0?"-":"")+"P"+MY({Y:m$(G.years),M:m$(G.months),W:m$(G.weeks),D:m$(G.days)})+(Q||V||F||D?"T"+MY({H:m$(Q),M:m$(V),S:m$(F,D)+U}):"")})($,Y)}function Kj($,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)+xj(Y,W===2):Z(J)}function MY($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function JJ($,Z){return v6($)+"T"+Ij($,Z)}function v6($){return _j($)+"-"+Z1($.isoDay)}function _j($){let{isoYear:Z}=$;return(Z<0||Z>9999?Cj(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+Z1($.isoMonth)}function LU($){return Z1($.isoMonth)+"-"+Z1($.isoDay)}function Ij($,Z){let J=[Z1($.isoHour),Z1($.isoMinute)];return Z!==-1&&J.push(Z1($.isoSecond)+((W,Y,j,z)=>YJ(W*H1+Y*t$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function l$($,Z=0){if(Z===1)return"";let[J,W]=g1(Math.abs($),N4),[Y,j]=g1(W,P4),[z,X]=g1(j,J1);return Cj($)+Z1(J)+":"+Z1(Y)+(z||X?":"+Z1(z)+YJ(X):"")}function WJ($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==v)return xj(J,Z===2)}return""}function xj($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function YJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(CO,""):J.slice(0,Z),J?"."+J:""}function Cj($){return $<0?"-":"+"}function m$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function MU($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=B$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Aj($,Z){let J=b0(Z,$);return{calendar:Z.calendar,...p0(qX,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 v7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let G=((Q,V,F,B)=>{let U=A0(V);B&&(F=q6(F));for(let D of Q){let O=o0(n0(D,U));if(B&&(O=q6(O)),O===F)return D}})(X,Z,J,j);if(G!==void 0)return G;if(W===0)throw RangeError(uU)}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(lU);if(W.length)return W[J===3?1:0];let Y=A0(Z),j=((X,G)=>{let Q=X.getOffsetNanosecondsFor(_Z(G,-s));return zJ(X.getOffsetNanosecondsFor(_Z(G,s))-Q)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(B$(Y,z)))[J===2?0:W.length-1]}function jJ($){if(Math.abs($)>=s)throw RangeError(dU);return $}function zJ($){if($>s)throw RangeError(cU);return $}function XJ($,Z,J){return M0(a0(KZ(Z.epochNanoseconds,((W)=>{if(wj(W))throw RangeError(nU);return D0(W,5)})($?R0(J):J))))}function GJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...UJ(z,X,W,J?R0(Y):Y,j)}}function QJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return X0(OJ($(j),J,Z?R0(W):W,Y),j)}function BJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?R0(W):W,Y),j)}function VJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=D3(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$(D3(z,G),j)}function FJ($,Z,J){return X1(Sj(Z,$?R0(J):J)[0])}function UJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(wj(W)){let X=b0(J,$);z=KZ(h0($,{...W4(Z,X,{...W,...$5},Y),...p0(Q1,X)}),j)}else z=KZ(z,j),m(Y);return{epochNanoseconds:a0(z)}}function OJ($,Z,J,W){let[Y,j]=Sj(Z,J);return h1({...W4($,Z,{...J,...$5,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+D0(J,5)[0];return Y?j$(s$(Z,Y)):Z}function D3($,Z,J=1){return s$(Z,J-$.day(Z))}function Sj($,Z){let[J,W]=D0(Z,5),[Y,j]=i6(G$($)+W);return[Y,J+j]}function s$($,Z){return Z?{...$,...s6(E0($)+Z*y0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...W1},W]}function DJ($){return $?Qj:A0}function j4($){return $?q(UJ,$):OJ}function LJ($){return $?q(TU,$):PU}function z4($){return $&&$.epochNanoseconds}function L3($,Z){return $<=6-(z4(Z)?1:0)}function MJ($,Z,J,W,Y,j,z){let X=$(z1(z).relativeTo),G=Math.max(p$(Y),p$(j));if(L3(G,X))return e(RZ(((O,L,M,T)=>{let P=KZ(D0(O),D0(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,V,F]=Y4(Z,J,X),B=j4(F),U=LJ(F),D=B(V,Q,Y);return e(U(V,Q,B(V,D,j),G))}function Ej($,Z,J,W,Y){let j=p$(W),[z,X,G,Q,V]=((C,S,w)=>{C=u7(C,m6);let x=j5(C),f=w(C[gX]),_=d7(C),k=w3(C,7),H0=k3(C);if(x===void 0&&H0===void 0)throw RangeError(oU);return H0==null&&(H0=0),x==null&&(x=Math.max(H0,S)),jj(x,H0),_=c7(_,H0,1),[x,H0,_,k,f]})(Y,j,$),F=Math.max(j,z);if(!z4(V)&&F<=6)return e(RZ(((C,S,w,x,f)=>{let _=$4(D0(C),w,x,f);return{...P0,...kZ(_,S)}})(W,z,X,G,Q)));if(!V)throw RangeError(T4);let[B,U,D]=Y4(Z,J,V),O=DJ(D),L=j4(D),M=LJ(D),T=L(U,B,W),P=M(U,B,T,z),K=W.sign,R=V$(P);if(K&&R&&K!==R)throw RangeError(E3);return R&&(P=e6(P,O(T),z,X,G,Q,U,B,O,L)),e(P)}function bj($){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 Rj($){return!$.sign}function V$($,Z=p){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(sU);J=Y}}return J}function RZ($){for(let Z of WO)$1(Z,$[Z],-IY,IY,1);return kj(o0(D0($),J1)),$}function kj($){if(!Number.isSafeInteger($))throw RangeError(iU)}function D0($,Z=6){return wY($,Z,p)}function kZ($,Z=6){let[J,W]=$,Y=d6(W,Z,p);if(Y[p[Z]]+=J*(s/M1[Z]),!Number.isFinite(Y[p[Z]]))throw RangeError(H4);return Y}function G4($,Z=5){return d6($,Z,p)}function wj($){return Boolean(V$($,wX))}function p$($){let Z=9;for(;Z>0&&!$[p[Z]];Z--);return Z}function HU($,Z){return[$,Z]}function HY($){let Z=Math.floor($/E6)*E6;return[Z,Z+E6]}function fj($){let Z=F$($=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&&NJ(Z.timeZone,1),M0(v7(n6(Z),J))}function qj($){let Z=F$(J0($));if(!Z)throw RangeError(g0($));if(Z.timeZone)return uj(Z,Z.offset?wZ(Z.offset):void 0);if(Z.m)throw RangeError(g0($));return ij(Z)}function vj($,Z){let J=F$(J0($));if(!J||!J.timeZone)throw RangeError(g0($));let{offset:W}=J,Y=W?wZ(W):void 0,[,j,z]=_3(Z);return uj(J,Y,j,z)}function wZ($){let Z=NJ($);if(Z===void 0)throw RangeError(g0($));return Z}function gj($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(g0($));return X0(lj(Z))}function Q4($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(g0($));return G0(Z.p?lj(Z):ij(Z))}function yj($,Z){let J=TJ(J0(Z));if(J)return HJ(J),h$(q7(c$(J)));let W=Q4(Z);return h$(D3($(W.calendar),W))}function HJ($){if($.calendar!==v)throw RangeError(y1($.calendar))}function mj($,Z){let J=PJ(J0(Z));if(J)return HJ(J),f6(c$(J));let W=Q4(Z),{calendar:Y}=W,j=$(Y),[z,X,G]=j.h(W),[Q,V]=j.I(z,X),[F,B]=j.N(Q,V,G);return f6(j$(j.P(F,B,G)),Y)}function hj($){let Z,J=((W)=>{let Y=RO.exec(W);return Y?(B4(Y[10]),oj(Y)):void 0})(J0($));if(!J){if(J=F$($),!J)throw RangeError(g0($));if(!J.p)throw RangeError(g0($));if(J.m)throw RangeError(y1("Z"));HJ(J)}if((Z=TJ($))&&DY(Z))throw RangeError(g0($));if((Z=PJ($))&&DY(Z))throw RangeError(g0($));return X1(o6(J,1))}function pj($){let Z=((J)=>{let W=fO.exec(J);return W?((Y)=>{function j(V,F,B){let U=0,D=0;if(B&&([U,G]=g1(G,M1[B])),V!==void 0){if(X)throw RangeError(y1(V));D=((O)=>{let L=parseInt(O);if(!Number.isFinite(L))throw RangeError(y1(O));return L})(V),z=1,F&&(G=KJ(F)*(M1[B]/J1),X=1)}return U+D}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)]),...d6(G,2,p)};if(!z)throw RangeError(FX(p));return _J(Y[1])<0&&(Q=R0(Q)),Q})(W):void 0})(J0($));if(!Z)throw RangeError(g0($));return e(RZ(Z))}function dj($){let Z=F$($)||TJ($)||PJ($);return Z?Z.calendar:$}function cj($){let Z=F$($);return Z&&(Z.timeZone||Z.m&&$Z||Z.offset)||$}function uj($,Z,J=0,W=0){let Y=V4($.timeZone),j=S4(Y);return N0(i$(j,n6($),Z,J,W,!j.v,$.m),Y,x3($.calendar))}function lj($){return sj(h1(n6($)))}function ij($){return sj(j$(c$($)))}function sj($){return{...$,calendar:x3($.calendar)}}function F$($){let Z=bO.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:nj(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...oj(J.slice(5)),...B4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function TJ($){let Z=SO.exec($);return Z?((J)=>({isoYear:nj(J),isoMonth:parseInt(J[4]),isoDay:1,...B4(J[5])}))(Z):void 0}function PJ($){let Z=EO.exec($);return Z?((J)=>({isoYear:CZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...B4(J[3])}))(Z):void 0}function NJ($,Z){let J=kO.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(y1(j));return jJ((NZ(W[2])*N4+NZ(W[3])*P4+NZ(W[4])*J1+KJ(W[5]||""))*_J(W[1]))})(J,Z):void 0}function nj($){let Z=_J($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(y1(-0));return Z*J}function oj($){let Z=NZ($[3]);return{...i6(KJ($[4]||""))[0],isoHour:NZ($[1]),isoMinute:NZ($[2]),isoSecond:Z===60?59:Z}}function B4($){let Z,J,W=[];if($.replace(wO,(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(y1(Y))}else{if(J)throw RangeError(y1(Y));J=G}return""}),W.length>1&&Z)throw RangeError(y1($));return{timeZone:J,calendar:W[0]||v}}function KJ($){return parseInt($.padEnd(9,"0"))}function fZ($){return new RegExp(`^${$}$`,"i")}function _J($){return $&&$!=="+"?-1:1}function NZ($){return $===void 0?0:parseInt($)}function aj($){return V4(J0($))}function V4($){let Z=IJ($);return typeof Z=="number"?l$(Z):Z?((J)=>{if(vO.test(J))throw RangeError(pU);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?UY(j).replace(/island|noronha|murdo|rivadavia|urville/,UY):j)).join("/")})($):$Z}function TY($){let Z=IJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:$Z}function IJ($){let Z=NJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==$Z?qO($):void 0}function xJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function CJ($,Z){return S0($.epochNanoseconds,Z.epochNanoseconds)}function tj($,Z,J,W,Y,j){let z=$(z1(j).relativeTo),X=Math.max(p$(W),p$(Y));if(RY(p,W,Y))return 0;if(L3(X,z))return S0(D0(W),D0(Y));if(!z)throw RangeError(T4);let[G,Q,V]=Y4(Z,J,z),F=DJ(V),B=j4(V);return S0(F(B(Q,G,W)),F(B(Q,G,Y)))}function AJ($,Z){return n$($,Z)||F4($,Z)}function n$($,Z){return Y$(E0($),E0(Z))}function F4($,Z){return Y$(G$($),G$(Z))}function rj($,Z){return!xJ($,Z)}function ej($,Z){return!CJ($,Z)&&!!U4($.timeZone,Z.timeZone)&&bZ($.calendar,Z.calendar)}function $z($,Z){return!AJ($,Z)&&bZ($.calendar,Z.calendar)}function Zz($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Jz($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Wz($,Z){return!n$($,Z)&&bZ($.calendar,Z.calendar)}function Yz($,Z){return!F4($,Z)}function U4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return TY(J)===TY(W)}catch(Y){}}function SJ($,Z,J,W){let Y=EZ($,z0(W),3,5),j=O4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return e($?R0(j):j)}function EJ($,Z,J,W,Y,j){let z=L4(W.calendar,Y.calendar),X=z0(j),[G,Q,V,F]=EZ(J,X,5),B=W.epochNanoseconds,U=Y.epochNanoseconds,D=S0(U,B),O;if(D)if(G<6)O=O4(B,U,G,Q,V,F);else{let L=Z(((T,P)=>{if(!U4(T,P))throw RangeError(HX);return T})(W.timeZone,Y.timeZone)),M=$(z);O=zz(M,L,W,Y,D,G,X),O=e6(O,U,G,Q,V,F,M,W,Qj,q(UJ,L))}else O=P0;return e(J?R0(O):O)}function bJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),[X,G,Q,V]=EZ(Z,z,6),F=A0(J),B=A0(W),U=S0(B,F),D;if(U)if(X<=6)D=O4(F,B,X,G,Q,V);else{let O=$(j);D=Xz(O,J,W,U,X,z),D=e6(D,B,X,G,Q,V,O,J,A0,OJ)}else D=P0;return e(Z?R0(D):D)}function RJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y);return jz(Z,()=>$(j),J,W,...EZ(Z,z,6,9,6),z)}function kJ($,Z,J,W,Y){let j=L4(J.calendar,W.calendar),z=z0(Y),X=EZ(Z,z,9,9,8),G=$(j);return jz(Z,()=>G,D3(G,J),D3(G,W),...X,z)}function jz($,Z,J,W,Y,j,z,X,G){let Q=A0(J),V=A0(W),F;if(S0(V,Q))if(Y===6)F=O4(Q,V,Y,j,z,X);else{let B=Z();F=B.dateUntil(J,W,Y,G),j===6&&z===1||(F=e6(F,V,Y,j,z,X,B,J,A0,W4))}else F=P0;return e($?R0(F):F)}function wJ($,Z,J,W){let Y=z0(W),[j,z,X,G]=EZ($,Y,5,5),Q=Q$(fJ(Z,J),I3(z,X),G),V={...P0,...G4(Q,j)};return e($?R0(V):V)}function TU($,Z,J,W,Y,j){let z=S0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?Gz(J.epochNanoseconds,W.epochNanoseconds,Y):zz(Z,$,J,W,z,Y,j):P0}function PU($,Z,J,W,Y){let j=A0(Z),z=A0(J),X=S0(z,j);return X?W<=6?Gz(j,z,W):Xz($,Z,J,X,W,Y):P0}function zz($,Z,J,W,Y,j,z){let[X,G,Q]=((B,U,D,O)=>{function L(){return S={...s$(P,R++*-O),...T},w=h0(B,S),S0(K,w)===-O}let M=b0(U,B),T=p0(Q1,M),P=b0(D,B),K=D.epochNanoseconds,R=0,C=fJ(M,P),S,w;if(Math.sign(C)===-O&&R++,L()&&(O===-1||L()))throw RangeError(E3);let x=o0(n0(w,K));return[M,S,x]})(Z,J,W,Y);var V,F;return{...j===6?(V=X,F=G,{...P0,days:Qz(V,F)}):$.dateUntil(X,G,j,z),...G4(Q)}}function Xz($,Z,J,W,Y,j){let[z,X,G]=((Q,V,F)=>{let B=V,U=fJ(Q,V);return Math.sign(U)===-F&&(B=s$(V,-F),U+=s*F),[Q,B,U]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...G4(G)}}function O4($,Z,J,W,Y,j){return{...P0,...kZ($4(n0($,Z),W,Y,j),J)}}function Gz($,Z,J){return{...P0,...kZ(n0($,Z),J)}}function Qz($,Z){return D4(E0($),E0(Z))}function D4($,Z){return Math.trunc((Z-$)/y0)}function fJ($,Z){return G$(Z)-G$($)}function L4($,Z){if(!bZ($,Z))throw RangeError(oJ);return $}function NU($){function Z(Y){return((j,z)=>({...Bz(j,z),F:j.month,day:parseInt(j.day)}))(f7(J,Y),W)}let J=B5($),W=g6($);return{id:$,O:KU(Z),B:_U(Z)}}function KU($){return m0((Z)=>{let J=E0(Z);return $(J)},WeakMap)}function _U($){let Z=$(0).year-QO;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:NX(z.reverse())}})}function Bz($,Z){let J,W,Y=Vz($);if($.era){let j=bX[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=Lz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function Vz($){return parseInt($.relatedYear||$.year)}function H7($){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=NY(this,$),J=NY(this,$-1),W=Z.length;if(W>J.length){let Y=Mz(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function A6($){return D4(M3.call(this,$),M3.call(this,$+1))}function PY($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),D4(J[Z-1],Y[W-1])}function S6($){return this.B($).k.length}function NY($,Z){return Object.keys($.B(Z).C)}function Fz($){return x3(J0($))}function x3($){if(($=$.toLowerCase())!==v&&$!==_4&&g6($)!==g6(B5($).resolvedOptions().calendar))throw RangeError(hU($));return $}function g6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function Uz($){return this.R($)[0]}function Oz($){return this.R($)[1]}function qJ($){let[Z]=this.h($);return D4(this.q(Z),E0($))+1}function Dz($){let Z=yO.exec($);if(!Z)throw RangeError(yU($));return[parseInt(Z[1]),Boolean(Z[2])]}function y6($,Z,J){return $+(Z||J&&$>=J?1:0)}function T7($,Z){return $-(Z&&$>=Z?1:0)}function Lz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function P7($){return bX[Hz($)]}function Mz($){return $O[Hz($)]}function Hz($){return g6($.id||v)}function Tz($,Z,J,W){let Y=U$(J,W,G1,[],CX);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),...W1}}function Pz($,Z,J,W,Y,j){let z=U$(J,Y,G1,IX,CX),X=$(z.timeZone),[G,Q,V]=_3(j),F=J.dateFromFields(z,t6(j,G)),B=o$(z,G);return N0(i$(Z(X),{...F,...B},z.offset!==void 0?wZ(z.offset):void 0,Q,V),X,W)}function Nz($,Z,J){let W=U$($,Z,G1,[],c1),Y=m(J);return X0(h1({...$.dateFromFields(W,t6(J,Y)),...o$(W,Y)}))}function vJ($,Z,J,W=[]){let Y=U$($,Z,G1,W);return $.dateFromFields(Y,J)}function gJ($,Z,J,W){let Y=U$($,Z,rJ,W);return $.yearMonthFromFields(Y,J)}function yJ($,Z,J,W,Y=[]){let j=U$($,J,G1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=CZ),$.monthDayFromFields(j,W)}function Kz($,Z){let J=m(Z);return X1(o$(L1($,K7,[],1),J))}function _z($){let Z=L1($,eJ);return e(RZ({...P0,...Z}))}function U$($,Z,J,W=[],Y=[]){return L1(Z,[...$.fields(J),...Y].sort(),W)}function L1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(kU(X));if(X==="constructor"||X==="__proto__")throw RangeError(sJ(X));let G=$[X];if(G!==void 0)z=1,xY[X]&&(G=xY[X](G,X)),Y[X]=G;else if(J){if(J.includes(X))throw TypeError(iJ(X));Y[X]=EX[X]}j=X}if(W&&!z)throw TypeError(FX(Z));return Y}function o$($,Z){return o6(dO({...EX,...$}),Z)}function Iz($,Z,J,W,Y,j){let z=z0(j),{calendar:X,timeZone:G}=J;return N0(((Q,V,F,B,U)=>{let D=C3(Q,F,B,G1,xX,_X),[O,L,M]=_3(U,2);return i$(V,{...Q.dateFromFields(D,t6(U,O)),...o$(D,O)},wZ(D.offset),L,M)})($(X),Z(G),W,Y,z),G,X)}function xz($,Z,J,W,Y){let j=z0(Y);return X0(((z,X,G,Q)=>{let V=C3(z,X,G,G1,c1),F=m(Q);return h1({...z.dateFromFields(V,t6(Q,F)),...o$(V,F)})})($(Z.calendar),J,W,j))}function Cz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let V=C3(z,X,G,G1);return z.dateFromFields(V,Q)})($(Z.calendar),J,W,j)}function Az($,Z,J,W,Y){let j=z0(Y);return h$(((z,X,G,Q)=>{let V=C3(z,X,G,rJ);return z.yearMonthFromFields(V,Q)})($(Z.calendar),J,W,j))}function Sz($,Z,J,W,Y){let j=z0(Y);return((z,X,G,Q)=>{let V=C3(z,X,G,G1);return z.monthDayFromFields(V,Q)})($(Z.calendar),J,W,j)}function Ez($,Z,J){return X1(((W,Y,j)=>{let z=m(j);return o$({...p0(K7,W),...L1(Y,K7)},z)})($,Z,J))}function bz($,Z){return e((J=$,W=Z,RZ({...J,...L1(W,eJ)})));var J,W}function C3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=L1(Z,z,j),G=L1(J,z);return X=$.mergeFields(X,G),L1(X,z,[])}function mJ($,Z){let J=U$($,Z,SX);return $.monthDayFromFields(J)}function hJ($,Z,J){let W=U$($,Z,AX);return $.yearMonthFromFields(W,J)}function Rz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=L1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=L1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function U7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=P7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(fU);if(!j)throw RangeError(wU);let z=j[J];if(z===void 0)throw RangeError(vU(J));let X=Lz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(qU);Y=X}else if(Y===void 0)throw TypeError(gU(j));return Y}function O7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,G,Q,V)=>{let F=X.U(Q),[B,U]=Dz(G),D=y6(B,U,F);if(U){let O=Mz(X);if(O===void 0)throw RangeError(F3);if(O>0){if(D>O)throw RangeError(F3);if(F===void 0){if(V===1)throw RangeError(F3);D--}}else{if(D!==-O)throw RangeError(F3);if(F===void 0&&V===1)throw RangeError(F3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(LX);Y=z,W=1}else if(Y===void 0)throw TypeError(mU);return $1("month",Y,1,$.L(J),W)}function KY($,Z,J,W,Y){return v0(Z,"day",1,$.j(W,J),Y)}function D7($,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 kz($){return M0(a0(l6(u6($))))}function wz($,Z,J,W,Y=v){return N0(a0(l6(u6(J))),Z(W),$(Y))}function fz($,Z,J,W,Y=0,j=0,z=0,X=0,G=0,Q=0,V=v){return X0(h1(n6(Y1(C0,AZ(I4,[Z,J,W,Y,j,z,X,G,Q])))),$(V))}function qz($,Z,J,W,Y=v){return G0(j$(c$(Y1(C0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function vz($,Z,J,W=v,Y=1){let j=C0(Z),z=C0(J),X=$(W);return h$(q7(c$({isoYear:j,isoMonth:z,isoDay:C0(Y)})),X)}function gz($,Z,J,W=v,Y=CZ){let j=C0(Z),z=C0(J),X=$(W);return f6(j$(c$({isoYear:C0(Y),isoMonth:j,isoDay:z})),X)}function yz($=0,Z=0,J=0,W=0,Y=0,j=0){return X1(o6(Y1(C0,AZ(Q1,[$,Z,J,W,Y,j])),1))}function mz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,G=0,Q=0){return e(RZ(Y1(cY,AZ(p,[$,Z,J,W,Y,j,z,X,G,Q]))))}function pJ($,Z,J=v){return N0($.epochNanoseconds,Z,J)}function hz($){return M0($.epochNanoseconds)}function dJ($,Z){return X0(b0(Z,$))}function cJ($,Z){return G0(b0(Z,$))}function pz($,Z,J){return hJ($(Z.calendar),J)}function dz($,Z,J){return mJ($(Z.calendar),J)}function uJ($,Z){return X1(b0(Z,$))}function cz($,Z,J,W){let Y=((j,z,X,G)=>{let Q=m7(G);return h0(j(z),X,Q)})($,J,Z,W);return N0(a0(Y),J,Z.calendar)}function uz($,Z,J){let W=$(Z.calendar);return h$({...Z,...hJ(W,J)})}function lz($,Z,J){return mJ($(Z.calendar),J)}function iz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):W1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function sz($,Z=W1){return X0(h1({...$,...Z}))}function nz($,Z,J){return hJ($(Z.calendar),J)}function oz($,Z,J){return mJ($(Z.calendar),J)}function az($,Z,J,W){return((Y,j,z)=>Rz(Y,j,AX,m1(z),R3))($(Z.calendar),J,W)}function tz($,Z,J,W){return((Y,j,z)=>Rz(Y,j,SX,m1(z),K4))($(Z.calendar),J,W)}function rz($,Z,J,W,Y){let j=m1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function ez($,Z){return X0(h1({...$,...Z}))}function $X($){return M0(a0(IZ($,J1)))}function ZX($){return M0(a0(IZ($,H1)))}function JX($){return M0(a0(l6(u6($),t$)))}function WX($){return M0(a0(l6(u6($))))}function YX($,Z,J=W1){let W=Z.timeZone,Y=$(W),j={...b0(Z,Y),...J};return N0(i$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function jX($,Z,J){let W=Z.timeZone,Y=$(W),j={...b0(Z,Y),...J},z=QX(Z.calendar,J.calendar);return N0(i$(Y,j,j.offsetNanoseconds,2),W,z)}function zX($,Z=W1){return X0({...$,...Z})}function XX($,Z){return X0({...$,...Z},QX($.calendar,Z.calendar))}function M4($,Z){return{...$,calendar:Z}}function GX($,Z){return{...$,timeZone:Z}}function QX($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===v)return Z;if(W===v)return $;throw RangeError(oJ)}function IU($,Z){return(J)=>J===v?$:J===_4||J===xZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),gO(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=C7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=$Z,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function p1($,Z=lJ){let[J,,,W]=$;return(Y,j=YD,...z)=>{let X=Z(W&&W(...z),Y,j,J),G=X.resolvedOptions();return[X,...xU($,G,z)]}}function lJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(tU);J.timeZone=$}return new O$(Z,J)}function xU($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,G)=>{if((G||z!==v)&&z!==X)throw RangeError(oJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function qZ($){let Z=A3();return B$(Z,$.getOffsetNanosecondsFor(Z))}function A3(){return IZ(Date.now(),H1)}function d1(){return AY||(AY=new O$().resolvedOptions().timeZone)}var CU=($,Z)=>`Non-integer ${$}: ${Z}`,AU=($,Z)=>`Non-positive ${$}: ${Z}`,SU=($,Z)=>`Non-finite ${$}: ${Z}`,EU=($)=>`Cannot convert bigint to ${$}`,bU=($)=>`Invalid bigint: ${$}`,RU="Cannot convert Symbol to string",BX="Invalid object",VX=($,Z,J,W,Y)=>Y?VX($,Y[Z],Y[J],Y[W]):S3($,Z)+`; must be between ${J}-${W}`,S3=($,Z)=>`Invalid ${$}: ${Z}`,iJ=($)=>`Missing ${$}`,sJ=($)=>`Invalid field ${$}`,kU=($)=>`Duplicate field ${$}`,FX=($)=>"No valid fields: "+$.join(),UX="Invalid bag",OX=($,Z,J)=>S3($,Z)+"; must be "+Object.keys(J).join(),DX="Cannot use valueOf",nJ="Invalid calling context",wU="Forbidden era/eraYear",fU="Mismatching era/eraYear",qU="Mismatching year/eraYear",vU=($)=>`Invalid era: ${$}`,gU=($)=>"Missing year"+($?"/era/eraYear":""),yU=($)=>`Invalid monthCode: ${$}`,LX="Mismatching month/monthCode",mU="Missing month/monthCode",_Y="Cannot guess year",F3="Invalid leap month",MX="Invalid protocol",E3="Invalid protocol results",oJ="Mismatching Calendars",hU=($)=>`Invalid Calendar: ${$}`,HX="Mismatching TimeZones",pU="Forbidden ICU TimeZone",dU="Out-of-bounds offset",cU="Out-of-bounds TimeZone gap",uU="Invalid TimeZone offset",lU="Ambiguous offset",H4="Out-of-bounds date",iU="Out-of-bounds duration",sU="Cannot mix duration signs",T4="Missing relativeTo",nU="Cannot use large units",oU="Required smallestUnit or largestUnit",aU="smallestUnit > largestUnit",g0=($)=>`Cannot parse: ${$}`,y1=($)=>`Invalid substring: ${$}`,TX=($)=>`Cannot format ${$}`,PX="Mismatching types for formatting",tU="Cannot specify TimeZone",NX=q(P3,($,Z)=>Z),vZ=q(P3,($,Z,J)=>J),Z1=q(R6,2),N7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},b3=Object.keys(N7),y0=86400000,KX=1000,t$=1000,H1=1e6,J1=1e9,P4=60000000000,N4=3600000000000,s=86400000000000,M1=[1,t$,H1,J1,P4,N4,s],c1=b3.slice(0,6),K7=N3(c1),_X=["offset"],IX=["timeZone"],xX=c1.concat(_X),CX=xX.concat(IX),_7=["era","eraYear"],rU=_7.concat(["year"]),K4=["year"],aJ=["monthCode"],tJ=["month"].concat(aJ),R3=["day"],rJ=tJ.concat(K4),AX=aJ.concat(K4),G1=R3.concat(rJ),eU=R3.concat(tJ),SX=R3.concat(aJ),EX=vZ(c1,0),v="iso8601",_4="gregory",xZ="japanese",bX={[_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}},$O={chinese:13,dangi:13,hebrew:-6},J0=q(c6,"string"),RX=q(c6,"boolean"),ZO=q(c6,"number"),kX=q(c6,"function"),p=b3.map(($)=>$+"s"),eJ=N3(p),JO=p.slice(0,6),wX=p.slice(6),WO=wX.slice(1),YO=NX(p),P0=vZ(p,0),$5=vZ(JO,0),Z5=q(kY,p),Q1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],J5=["isoDay","isoMonth","isoYear"],I4=Q1.concat(J5),W5=N3(J5),fX=N3(Q1),qX=N3(I4),W1=vZ(fX,0),jO=q(kY,I4),O$=Intl.DateTimeFormat,vX="en-GB",Y5=1e8,zO=Y5*y0,XO=[Y5,0],GO=[-Y5,0],H3=275760,T3=-271821,QO=1970,CZ=1972,v1=12,BO=SZ(1868,9,8),VO=m0(VU,WeakMap),m6="smallestUnit",I7="unit",O3="roundingIncrement",L7="fractionalSecondDigits",gX="relativeTo",yX={constrain:0,reject:1},FO=Object.keys(yX),UO={compatible:0,reject:1,earlier:2,later:3},OO={reject:0,use:1,prefer:2,ignore:3},DO={auto:0,never:1,critical:2,always:3},LO={auto:0,never:1,critical:2},MO={auto:0,never:1},HO={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},k3=q(l7,m6),j5=q(l7,"largestUnit"),TO=q(l7,I7),mX=q(u$,"overflow",yX),hX=q(u$,"disambiguation",UO),PO=q(u$,"offset",OO),z5=q(u$,"calendarName",DO),NO=q(u$,"timeZoneName",LO),KO=q(u$,"offset",MO),w3=q(u$,"roundingMode",HO),gZ="PlainYearMonth",yZ="PlainMonthDay",r$="PlainDate",e$="PlainDateTime",x4="PlainTime",u1="ZonedDateTime",C4="Instant",A4="Duration",_O=[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",E6=5184000,IO=w6(1847),xO=w6(new Date().getUTCFullYear()+10),CO=/0+$/,b0=m0(MU,WeakMap),IY=4294967295,S4=m0(($)=>{let Z=IJ($);return typeof Z=="object"?new dX(Z):new pX(Z||0)});class pX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[v7($,this.v)]}l(){}}class dX{constructor($){this.$=((Z)=>{function J(G){let Q=M7(G,z,X),[V,F]=HY(Q),B=Y(V),U=Y(F);return B===U?B:W(j(V,F),B,U,G)}function W(G,Q,V,F){let B,U;for(;(F===void 0||(B=F<G[0]?Q:F>=G[1]?V:void 0)===void 0)&&(U=G[1]-G[0]);){let D=G[0]+Math.floor(U/2);Z(D)===V?G[1]=D:G[0]=D+1}return B}let Y=m0(Z),j=m0(HU),z=IO,X=xO;return{G(G){let Q=J(G-86400),V=J(G+86400),F=G-Q,B=G-V;if(Q===V)return[F];let U=J(F);return U===J(B)?[G-U]:Q>V?[F,B]:[]},V:J,l(G,Q){let V=M7(G,z,X),[F,B]=HY(V),U=E6*Q,D=Q<0?()=>B>z||(z=V,0):()=>F<X||(X=V,0);for(;D();){let O=Y(F),L=Y(B);if(O!==L){let M=j(F,B);W(M,O,L);let T=M[0];if((Y$(T,G)||1)===Q)return T}F+=U,B+=U}}}})(((Z)=>(J)=>{let W=f7(Z,J*KX);return w6(Vz(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(iY($))*J1}getPossibleInstantsFor($){let[Z,J]=[w6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*H1+W.isoMicrosecond*t$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>a0(_Z(IZ(Y,J1),J)))}l($,Z){let[J,W]=sY($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return IZ(Y,J1)}}var X5="([+\u2212-])",b6="(?:[.,](\\d{1,9}))?",cX=`(?:(?:${X5}(\\d{6}))|(\\d{4}))-?(\\d{2})`,G5="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+b6+")?)?",Q5=X5+G5,AO=cX+"-?(\\d{2})(?:[T ]"+G5+"(Z|"+Q5+")?)?",uX="\\[(!?)([^\\]]*)\\]",E4=`((?:${uX}){0,9})`,SO=fZ(cX+E4),EO=fZ("(?:--)?(\\d{2})-?(\\d{2})"+E4),bO=fZ(AO+E4),RO=fZ("T?"+G5+"(?:"+Q5+")?"+E4),kO=fZ(Q5),wO=new RegExp(uX,"g"),fO=fZ(`${X5}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${b6}H)?(?:(\\d+)${b6}M)?(?:(\\d+)${b6}S)?)?`),qO=m0(($)=>new O$(vX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),vO=/^(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$/,gO=m0(NU),B5=m0(($)=>new O$(vX,{calendar:$,timeZone:$Z,era:"short",year:"numeric",month:"short",day:"numeric"})),yO=/^M(\d{2})(L?)$/,mO={era:k6,eraYear:C0,year:C0,month:OY,monthCode:k6,day:OY},hO=vZ(c1,C0),pO=vZ(p,cY),xY=Object.assign({},mO,hO,pO,{offset:k6}),dO=q(BU,c1,Q1),CY={dateAdd($,Z,J){let W=m(J),Y,{years:j,months:z,weeks:X,days:G}=Z;if(G+=D0(Z,5)[0],j||z)Y=((Q,V,F,B,U)=>{let[D,O,L]=Q.h(V);if(F){let[M,T]=Q.I(D,O);D+=F,O=y6(M,T,Q.U(D)),O=$1("month",O,1,Q.L(D),U)}return B&&([D,O]=Q._(D,O,B)),L=$1("day",L,1,Q.j(D,O),U),Q.q(D,O,L)})(this,$,j,z,W);else{if(!X&&!G)return $;Y=E0($)}return Y+=(7*X+G)*y0,j$(s6(Y))},dateUntil($,Z,J){if(J<=7){let G=0,Q=Qz({...$,...W1},{...Z,...W1});return J===7&&([G,Q]=X$(Q,7)),{...P0,weeks:G,days:Q}}let W=this.h($),Y=this.h(Z),[j,z,X]=((G,Q,V,F,B,U,D)=>{let O=B-Q,L=U-V,M=D-F;if(O||L){let T=Math.sign(O||L),P=G.j(B,U),K=0;if(Math.sign(M)===-T){let R=P;[B,U]=G._(B,U,-T),O=B-Q,L=U-V,P=G.j(B,U),K=T<0?-R:P}if(M=D-Math.min(F,P)+K,O){let[R,C]=G.I(Q,V),[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);O=(B-=T)-Q,L=U-y6(R,C,G.U(B))+(x||G.L(B))}}}return[O,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=U7(this,$),Y=O7(this,$,W,J),j=KY(this,$,Y,W,J);return G0(j$(this.P(W,Y,j)),this.id||v)},yearMonthFromFields($,Z){let J=m(Z),W=U7(this,$),Y=O7(this,$,W,J);return h$(q7(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,V,F;if(Y!==void 0){[X,G]=Dz(Y),F=SY($,"day");let B=this.N(X,G,F);if(!B)throw RangeError(_Y);if([Q,V]=B,z!==void 0&&z!==V)throw RangeError(LX);W&&(V=$1("month",V,1,v1,1),F=$1("day",F,1,g7(j!==void 0?j:Q,V),J))}else{Q=j===void 0&&W?CZ:U7(this,$),V=O7(this,$,Q,J),F=KY(this,$,V,Q,J);let B=this.U(Q);G=V===B,X=T7(V,B);let U=this.N(X,G,F);if(!U)throw RangeError(_Y);[Q,V]=U}return f6(j$(this.P(Q,V,F)),this.id||v)},fields($){return P7(this)&&$.includes("year")?[...$,..._7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return D7(J,Z,tJ),P7(this)&&(D7(J,Z,rU),this.id===xZ&&D7(J,Z,eU,_7)),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:qJ,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"+Z1(j)+(z?"L":""))(W,Y)},dayOfWeek:rY,daysInWeek(){return 7}},cO={dayOfYear:qJ,h:oY,q:SZ},uO=Object.assign({},cO,{weekOfYear:Uz,yearOfWeek:Oz,R($){function Z(U){return(7-U<W?7:0)-U}function J(U){let D=tY(B+U),O=U||1,L=Z(U3(G+D*O,7));return V=(D+(L-Q)*O)/7}let W=this.id?1:4,Y=rY($),j=this.dayOfYear($),z=U3(Y-1,7),X=j-1,G=U3(z-X,7),Q=Z(G),V,F=Math.floor((X-Q)/7)+1,B=$.isoYear;return F?F>J(0)&&(F=1,B++):(F=J(-1),B--),[F,B,V]}}),lO={dayOfYear:qJ,h:H7,q:M3,weekOfYear:Uz,yearOfWeek:Oz,R(){return[]}},mZ=IU(Object.assign({},CY,uO,{h:oY,ee($){return this.id===_4?eY($):this.id===xZ?VO($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[CZ,$]},K:y7,U(){},L:aY,J:($)=>$*v1,j:g7,X:tY,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:SZ,_:($,Z,J)=>($+=p6(J,v1),(Z+=S7(J,v1))<1?($--,Z+=v1):Z>v1&&($++,Z-=v1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},CY,lO,{h:H7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[T7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=H7.call(this,{isoYear:CZ,isoMonth:v1,isoDay:31}),z=C6.call(this,W),X=Y===z;(Y$($,T7(Y,z))||Y$(Number(Z),Number(X))||Y$(J,j))===1&&W--;for(let G=0;G<100;G++){let Q=W-G,V=C6.call(this,Q),F=y6($,Z,V);if(Z===(F===V)&&J<=PY.call(this,Q,F))return[Q,F]}},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:PY,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}})),z$="numeric",hZ=["timeZoneName"],lX={month:z$,day:z$},V5={year:z$,month:z$},F5=Object.assign({},V5,{day:z$}),U5={hour:z$,minute:z$,second:z$},O5=Object.assign({},F5,U5),iO=Object.assign({},O5,{timeZoneName:"short"}),sO=Object.keys(V5),nO=Object.keys(lX),oO=Object.keys(F5),aO=Object.keys(U5),D5=["dateStyle"],tO=sO.concat(D5),rO=nO.concat(D5),L5=oO.concat(D5,["weekday"]),f3=aO.concat(["dayPeriod","timeStyle"]),M5=L5.concat(f3),eO=M5.concat(hZ),$D=hZ.concat(f3),ZD=hZ.concat(L5),JD=hZ.concat(["day","weekday"],f3),WD=hZ.concat(["year","weekday"],f3),YD={},H5=[a$(M5,O5),r6],iX=[a$(eO,iO),r6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(HX);return J}],T5=[a$(M5,O5,hZ),E0],P5=[a$(L5,F5,$D),E0],N5=[a$(f3,U5,ZD),($)=>G$($)/H1],K5=[a$(tO,V5,JD),E0,1],_5=[a$(rO,lX,WD),E0,1],AY;function N1($,Z,J,W,Y){function j(...G){if(!(this instanceof j))throw TypeError(nJ);aX(this,Z(...G))}function z(G,Q){return Object.defineProperties(function(...V){return G.call(this,X(this),...V)},x7(Q))}function X(G){let Q=I0(G);if(!Q||Q.branding!==$)throw TypeError(nJ);return Q}return Object.defineProperties(j.prototype,{...EY(Y1(z,J)),...d$(Y1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...d$(Y),...x7($)}),[j,(G)=>{let Q=Object.create(j.prototype);return aX(Q,G),Q},X]}function eX($){return $=$.concat("id").sort(),(Z)=>{if(!bY(Z,$))throw TypeError(MX);return Z}}function uZ($){if(I0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(UX);return $}function b4($,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 C5($){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(PD),{i:z})))[J](W);var j,z};return Z}function T$(){throw TypeError(DX)}function v3({calendar:$}){return typeof $=="string"?new q5($):$}function sX($,Z){if(Z=z0(Z),L0($)){let W=I0($);if(W&&W.branding===yZ)return m(Z),W;let Y=JG($);return yJ(g4(Y||v),!Y,$,Z)}let J=mj(mZ,$);return m(Z),J}function $G($,Z,J){return W=Z.call($,k0(M0(J))),jJ(K3(W));var W}function R4($,Z=zG){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=q(Z[Y],$,kX($[Y]));return W}function o($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return o($,x5)}function T1($){if(L0($)){let Z=I0($);if(Z)switch(Z.branding){case C4:return Z;case u1:return M0(Z.epochNanoseconds)}}return fj($)}function nX($,Z,J){let W=Z.l(T1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function t($){return L0($)?(I0($)||{}).timeZone||CD($):((Z)=>V4(cj(J0(Z))))($)}function D$($,Z){if(L0($)){let J=I0($)||{};switch(J.branding){case x4:return m(Z),J;case e$:return m(Z),X1(J);case u1:return m(Z),uJ(B0,J)}return Kz($,Z)}return m(Z),hj($)}function A5($){return $===void 0?void 0:D$($)}function pZ($,Z){if(Z=z0(Z),L0($)){let W=I0($);return W&&W.branding===gZ?(m(Z),W):gJ(q4(g3($)),$,Z)}let J=yj(mZ,$);return m(Z),J}function L$($,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,...W1});case u1:return m(Z),dJ(B0,W)}return Nz(v4(g3($)),$,Z)}let J=gj($);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 u1:return m(Z),cJ(B0,W)}return vJ(v4(g3($)),$,Z)}let J=Q4($);return m(Z),J}function ZG($,Z,J){return j1(Z.call($,Y0(G0(J,$))))}function K1($){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:_z($)}return pj($)}function q3($){if($!==void 0){if(L0($)){let Z=I0($)||{};switch(Z.branding){case u1:case r$:return Z;case e$:return G0(Z)}let J=g3($);return{...Tz(t,o,v4(J),$),calendar:J}}return qj($)}}function g3($){return JG($)||v}function JG($){let{calendar:Z}=$;if(Z!==void 0)return _0(Z)}function _0($){return L0($)?(I0($)||{}).calendar||pD($):((Z)=>x3(dj(J0(Z))))($)}function dZ($,Z){if(Z=z0(Z),L0($)){let J=I0($);if(J&&J.branding===u1)return _3(Z),J;let W=g3($);return Pz(t,o,v4(W),W,$,Z)}return vj($,Z)}function oX($){return Y1((Z)=>(J)=>Z(I5(J)),$)}function I5($){return b0($,B0)}function jD(){let $=O$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(O$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);v5.set(this,((z,X={})=>{let G=new O$(z,X),Q=G.resolvedOptions(),V=Q.locale,F=p0(Object.keys(X),Q),B=m0(GD),U=(...D)=>{let O,L=D.map((M,T)=>{let P=I0(M),K=(P||{}).branding;if(T&&O&&O!==K)throw TypeError(PX);return O=K,P});return O?B(O)(V,F,...L):[G,...D]};return U.u=G,U})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&zD(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||XD(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function zD($){return function(...Z){let J=v5.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function XD($){return function(...Z){return v5.get(this).u[$](...Z)}}function GD($){let Z=QD[$];if(!Z)throw TypeError(TX($));return p1(Z,m0(lJ))}var QD={Instant:H5,PlainDateTime:T5,PlainDate:P5,PlainTime:N5,PlainYearMonth:K5,PlainMonthDay:_5},BD=p1(H5),VD=p1(iX),FD=p1(T5),UD=p1(P5),OD=p1(N5),DD=p1(K5),LD=p1(_5),S5={era:gY,eraYear:E7,year:K3,month:j1,daysInMonth:j1,daysInYear:j1,inLeapYear:RX,monthsInYear:j1},w4={monthCode:J0},E5={day:j1},WG={dayOfWeek:j1,dayOfYear:j1,weekOfYear:yY,yearOfWeek:E7,daysInWeek:j1},YG=Object.assign({},S5,w4,E5,WG),k4=new WeakMap,I0=k4.get.bind(k4),aX=k4.set.bind(k4),MD={...b4(S5,[gZ]),...b4(WG,[]),...b4(w4,[gZ,yZ]),...b4(E5,[yZ])},b5=C5(YG),HD=C5({...S5,...w4}),TD=C5({...w4,...E5}),y3={calendarId:($)=>T0($.calendar)},PD=Y1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(G0(J,W))))},YG),ND=P3(($)=>(Z)=>Z[$],p.concat("sign")),R5=P3(($,Z)=>(J)=>J[Q1[Z]],c1),jG={epochSeconds:zj,epochMilliseconds:r6,epochMicroseconds:Xj,epochNanoseconds:Gj},m3=q(C7,new Set(["branding"])),[KD,cZ,_D]=N1(yZ,q(gz,_0),{...y3,...TD},{getISOFields:m3,getCalendar:v3,with($,Z,J){return cZ(Sz(yD,$,this,uZ(Z),J))},equals:($,Z)=>Wz($,sX(Z)),toPlainDate($,Z){return Y0(tz(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=LD(Z,J,$);return W.format(Y)},toString:$J,toJSON:($)=>$J($),valueOf:T$},{from:($,Z)=>cZ(sX($,Z))}),zG={getOffsetNanosecondsFor:$G,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,K0(X0(J,v)))].map((j)=>xD(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(S0),zJ(o0(n0(W[0],W[Y-1])))),W}},x5={getOffsetNanosecondsFor:$G},[ID,k0,xD]=N1(C4,kz,jG,{add:($,Z)=>k0(XJ(0,$,W0(Z))),subtract:($,Z)=>k0(XJ(1,$,W0(Z))),until:($,Z,J)=>a(SJ(0,$,T1(Z),J)),since:($,Z,J)=>a(SJ(1,$,T1(Z),J)),round:($,Z)=>k0(Vj($,Z)),equals:($,Z)=>rj($,T1(Z)),toZonedDateTime($,Z){let J=m1(Z);return Q0(pJ($,t(J.timeZone),_0(J.calendar)))},toZonedDateTimeISO:($,Z)=>Q0(pJ($,t(Z))),toLocaleString($,Z,J){let[W,Y]=BD(Z,J,$);return W.format(Y)},toString:($,Z)=>o7(t,B0,$,Z),toJSON:($)=>o7(t,B0,$),valueOf:T$},{from:($)=>k0(T1($)),fromEpochSeconds:($)=>k0($X($)),fromEpochMilliseconds:($)=>k0(ZX($)),fromEpochMicroseconds:($)=>k0(JX($)),fromEpochNanoseconds:($)=>k0(WX($)),compare:($,Z)=>xJ(T1($),T1(Z))}),[f4,_K]=N1("TimeZone",($)=>{let Z=aj($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(L$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(T1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=T1(Z).epochNanoseconds,W=R4(this,x5).getOffsetNanosecondsFor(J);return l$(W)},getPlainDateTimeFor($,Z,J=v){let W=T1(Z).epochNanoseconds,Y=R4(this,x5).getOffsetNanosecondsFor(W);return K0(X0(B$(W,Y),_0(J)))},getInstantFor($,Z,J){let W=L$(Z),Y=m7(J),j=R4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>nX(1,$,Z),getPreviousTransition:({o:$},Z)=>nX(-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}}),CD=eX(Object.keys(zG)),[AD,M$]=N1(x4,yz,R5,{getISOFields:m3,with($,Z,J){return M$(Ez(this,uZ(Z),J))},add:($,Z)=>M$(FJ(0,$,W0(Z))),subtract:($,Z)=>M$(FJ(1,$,W0(Z))),until:($,Z,J)=>a(wJ(0,$,D$(Z),J)),since:($,Z,J)=>a(wJ(1,$,D$(Z),J)),round:($,Z)=>M$(Oj($,Z)),equals:($,Z)=>Yz($,D$(Z)),toZonedDateTime:($,Z)=>Q0(rz(t,w0,o,$,Z)),toPlainDateTime:($,Z)=>K0(ez($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=OD(Z,J,$);return W.format(Y)},toString:ZJ,toJSON:($)=>ZJ($),valueOf:T$},{from:($,Z)=>M$(D$($,Z)),compare:($,Z)=>F4(D$($),D$(Z))}),[SD,H$,ED]=N1(gZ,q(vz,_0),{...y3,...HD},{getISOFields:m3,getCalendar:v3,with($,Z,J){return H$(Az(gD,$,this,uZ(Z),J))},add:($,Z,J)=>H$(VJ(tX,0,$,W0(Z),J)),subtract:($,Z,J)=>H$(VJ(tX,1,$,W0(Z),J)),until:($,Z,J)=>a(kJ(rX,0,$,pZ(Z),J)),since:($,Z,J)=>a(kJ(rX,1,$,pZ(Z),J)),equals:($,Z)=>Jz($,pZ(Z)),toPlainDate($,Z){return Y0(az(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=DD(Z,J,$);return W.format(Y)},toString:e7,toJSON:($)=>e7($),valueOf:T$},{from:($,Z)=>H$(pZ($,Z)),compare:($,Z)=>n$(pZ($),pZ(Z))}),[bD,K0]=N1(e$,q(fz,_0),{...y3,...b5,...R5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return K0(xz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>K0(M4($,_0(Z))),withPlainDate:($,Z)=>K0(XX($,w0(Z))),withPlainTime:($,Z)=>K0(zX($,A5(Z))),add:($,Z,J)=>K0(QJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>K0(QJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(bJ(P1,0,$,L$(Z),J)),since:($,Z,J)=>a(bJ(P1,1,$,L$(Z),J)),round:($,Z)=>K0(Uj($,Z)),equals:($,Z)=>$z($,L$(Z)),toZonedDateTime:($,Z,J)=>Q0(cz(o,$,t(Z),J)),toPlainDate:($)=>Y0(G0($)),toPlainTime:($)=>M$(X1($)),toPlainYearMonth($){return H$(uz(q4,$,this))},toPlainMonthDay($){return cZ(lz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=FD(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:T$},{from:($,Z)=>K0(L$($,Z)),compare:($,Z)=>AJ(L$($),L$(Z))}),[RD,Y0,XG]=N1(r$,q(qz,_0),{...y3,...b5},{getISOFields:m3,getCalendar:v3,with($,Z,J){return Y0(Cz(h3,$,this,uZ(Z),J))},withCalendar:($,Z)=>Y0(M4($,_0(Z))),add:($,Z,J)=>Y0(BJ(ZZ,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(BJ(ZZ,1,$,W0(Z),J)),until:($,Z,J)=>a(RJ(P1,0,$,w0(Z),J)),since:($,Z,J)=>a(RJ(P1,1,$,w0(Z),J)),equals:($,Z)=>Zz($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof f4?{timeZone:Z}:Z;return Q0(iz(t,D$,o,$,J))},toPlainDateTime:($,Z)=>K0(sz($,A5(Z))),toPlainYearMonth($){return H$(nz(q4,$,this))},toPlainMonthDay($){return cZ(oz(g4,$,this))},toLocaleString($,Z,J){let[W,Y]=UD(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:T$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>n$(w0($),w0(Z))}),k5={fields($,Z,J){return[...Z.call($,J)]}},GG=Object.assign({dateFromFields($,Z,J,W){return XG(Z.call($,Object.assign(Object.create(null),J),W))}},k5),QG=Object.assign({yearMonthFromFields($,Z,J,W){return ED(Z.call($,Object.assign(Object.create(null),J),W))}},k5),BG=Object.assign({monthDayFromFields($,Z,J,W){return _D(Z.call($,Object.assign(Object.create(null),J),W))}},k5),w5={mergeFields($,Z,J,W){return m1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},kD=Object.assign({},GG,w5),wD=Object.assign({},QG,w5),fD=Object.assign({},BG,w5),f5={dateAdd($,Z,J,W,Y){return XG(Z.call($,Y0(G0(J,$)),a(e(W)),Y))}},VG=Object.assign({},f5,{dateUntil($,Z,J,W,Y,j){return hD(Z.call($,Y0(G0(J,$)),Y0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:b3[Y]})))}}),qD=Object.assign({},f5,{day:ZG}),vD=Object.assign({},VG,{day:ZG}),q4=K1(QG),v4=K1(GG),g4=K1(BG),gD=K1(wD),h3=K1(kD),yD=K1(fD),ZZ=K1(f5),P1=K1(VG),tX=K1(qD),rX=K1(vD),[mD,a,hD]=N1(A4,mz,{...ND,blank:Rj},{with:($,Z)=>a(bz($,Z)),negated:($)=>a(X4($)),abs:($)=>a(bj($)),add:($,Z,J)=>a(MJ(q3,P1,o,0,$,W0(Z),J)),subtract:($,Z,J)=>a(MJ(q3,P1,o,1,$,W0(Z),J)),round:($,Z)=>a(Ej(q3,P1,o,$,Z)),total:($,Z)=>Bj(q3,P1,o,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:T$},{from:($)=>a(W0($)),compare:($,Z,J)=>tj(q3,ZZ,o,W0($),W0(Z),J)}),FG={toString:($)=>$.id,toJSON:($)=>$.id,...MD,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),Zj(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(vJ(Z,J,W,vY($))),yearMonthFromFields:({id:$,o:Z},J,W)=>H$(gJ(Z,J,W,fY($))),monthDayFromFields:({id:$,o:Z},J,W)=>cZ(yJ(Z,0,J,W,qY($))),fields({o:$},Z){let J=new Set(G1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(sJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(A7(b7(Z)),A7(b7(J)))},[q5]=N1("Calendar",($)=>{let Z=Fz($);return{branding:"Calendar",id:Z,o:mZ(Z)}},{id:($)=>$.id},FG,{from($){let Z=_0($);return typeof Z=="string"?new q5(Z):Z}}),pD=eX(Object.keys(FG).slice(4)),[dD,Q0]=N1(u1,q(wz,_0,t),{...jG,...y3,...oX(b5),...oX(R5),offset:($)=>l$(I5($).offsetNanoseconds),offsetNanoseconds:($)=>I5($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Dj(o,$)},{getISOFields:($)=>Aj(B0,$),getCalendar:v3,getTimeZone:({timeZone:$})=>typeof $=="string"?new f4($):$,with($,Z,J){return Q0(Iz(h3,o,$,this,uZ(Z),J))},withCalendar:($,Z)=>Q0(M4($,_0(Z))),withTimeZone:($,Z)=>Q0(GX($,t(Z))),withPlainDate:($,Z)=>Q0(jX(o,$,w0(Z))),withPlainTime:($,Z)=>Q0(YX(o,$,A5(Z))),add:($,Z,J)=>Q0(GJ(ZZ,o,0,$,W0(Z),J)),subtract:($,Z,J)=>Q0(GJ(ZZ,o,1,$,W0(Z),J)),until:($,Z,J)=>a(e(EJ(P1,o,0,$,dZ(Z),J))),since:($,Z,J)=>a(e(EJ(P1,o,1,$,dZ(Z),J))),round:($,Z)=>Q0(Fj(o,$,Z)),startOfDay:($)=>Q0(Lj(o,$)),equals:($,Z)=>ej($,dZ(Z)),toInstant:($)=>k0(hz($)),toPlainDateTime:($)=>K0(dJ(B0,$)),toPlainDate:($)=>Y0(cJ(B0,$)),toPlainTime:($)=>M$(uJ(B0,$)),toPlainYearMonth($){return H$(pz(q4,$,this))},toPlainMonthDay($){return cZ(dz(g4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=VD(Z,J,$);return W.format(Y)},toString:($,Z)=>a7(B0,$,Z),toJSON:($)=>a7(B0,$),valueOf:T$},{from:($,Z)=>Q0(dZ($,Z)),compare:($,Z)=>CJ(dZ($),dZ(Z))}),cD=Object.defineProperties({},{...h6("Temporal.Now"),...d$({timeZoneId:()=>d1(),instant:()=>k0(M0(A3())),zonedDateTime:($,Z=d1())=>Q0(N0(A3(),t(Z),_0($))),zonedDateTimeISO:($=d1())=>Q0(N0(A3(),t($),v)),plainDateTime:($,Z=d1())=>K0(X0(qZ(B0(t(Z))),_0($))),plainDateTimeISO:($=d1())=>K0(X0(qZ(B0(t($))),v)),plainDate:($,Z=d1())=>Y0(G0(qZ(B0(t(Z))),_0($))),plainDateISO:($=d1())=>Y0(G0(qZ(B0(t($))),v)),plainTimeISO:($=d1())=>M$(X1(qZ(B0(t($)))))})}),lZ=Object.defineProperties({},{...h6("Temporal"),...d$({PlainYearMonth:SD,PlainMonthDay:KD,PlainDate:RD,PlainTime:AD,PlainDateTime:bD,ZonedDateTime:dD,Instant:ID,Calendar:q5,TimeZone:f4,Duration:mD,Now:cD})}),uD=jD(),v5=new WeakMap,lD=Object.defineProperties(Object.create(Intl),d$({DateTimeFormat:uD}));var y4="x-gemi-socket";var EK="gemi.v1",UG="/__gemi/socket",bK=/^[A-Za-z0-9_-]{1,32}$/,RK={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function qK($){return $}function OG(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:UG,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 iD,randomBytes as sD}from"crypto";function nD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(iD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var oD="__control",g5=250,aD=1e4,tD=15000;class y5{config;prefix;controlChannel;instanceId=sD(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??nD(),this.controlChannel=this.prefix+oD,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 $})(),tD,"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 (${DG(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(aD,g5*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(g5,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 (${DG(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??rD(Math.min(Z,g5));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 rD($){return new Promise((Z)=>setTimeout(Z,$))}function DG($){return $ instanceof Error?$.message:String($)}import{createHmac as eD,hkdfSync as $L,randomBytes as LG}from"crypto";function MG($){return eD("sha256",ZL()).update($).digest("base64url").slice(0,22)}var m4=null;function ZL(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from($L("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):LG(32);return m4={secret:$,key:Z},Z}function hK(){return LG(16).toString("base64url")}var JL=/^[A-Za-z0-9_-]{8,64}$/;function m5($){return typeof $==="string"&&JL.test($)}function HG($,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 PG 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 d0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=_1(OG(),$),this.driver=jL(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:UZ($),pattern:U0},null)}toOthers($){return new NG(this,YL($))}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){g2(Z);let Y;try{Y=HG($.topic,Z,J,W?MG(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){iZ(()=>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=WL($);iZ(()=>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 PG(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 NG{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:UZ($),pattern:U0},this.except)}}function h4($,Z){if(v2($))return{topic:b8($.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:b8($)}}function WL($){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 YL($){if($===null||$===void 0)return null;if(typeof $==="string")return m5($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(y4);return m5(J)?J:null}function jL($,Z){let J=$.driver;if(J===void 0||J==="memory")return new TG;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new y5({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 h5 extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class zL{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 p5,createHmac as XL,randomBytes as KG,timingSafeEqual as xG}from"crypto";var u3=600,p4="gemi_oauth",GL=`__Host-${p4}`;function sZ($,Z=p4){if(Z===p4)return $?GL:p4;return $?`__Host-${Z}`:Z}function c3($){return $.toString("base64url")}function CG($){return XL("sha256",HZ()).update(`gemi-oauth-state:${$}`).digest()}function _G($,Z){let J=p5("sha256").update($).digest(),W=p5("sha256").update(Z).digest();return xG(J,W)&&$.length===Z.length}function d4($,Z=Date.now(),J={}){let W=c3(KG(32)),Y=c3(KG(32)),j=QL(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:BL(z)}}function QL($){return c3(p5("sha256").update($).digest())}function BL($){let Z=c3(Buffer.from(JSON.stringify($)));return`${Z}.${c3(CG(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=CG(J);if(W.length!==Y.length||!xG(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 P$=new Map,IG=1e4;function FL($,Z,J){if(P$.size>=IG){for(let[W,Y]of P$)if(Y<=J)P$.delete(W);while(P$.size>=IG){let W=P$.keys().next().value;if(W===void 0)break;P$.delete(W)}}P$.set($,Z)}function c4($){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=_G(J.state,$.returnedState),Y=_G(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(P$.has(J.state))return{ok:!1,reason:"invalid_state"};return FL(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var d5=new WeakMap;function OL($){let Z=d5.get($);if(!Z)Z=$(UL(32).toString("hex")),d5.set($,Z),Z.catch(()=>d5.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 u5 extends Error{}function c5($){return typeof $==="string"&&$!==""?$:null}function AG($){return g$($)}var DL=256;function SG($){return typeof $==="string"&&$!==""&&$.length<=DL?$:null}function EG($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function kG($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function bG($){let Z=$.cookies.get(i4);if(!Z)return null;kG($);try{return O1(decodeURIComponent(Z),"")||null}catch{return null}}class l5 extends A{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class wG extends A{schema={email:{required:"Email is required",email:"Invalid email"}}}class fG extends A{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new q0("Not found",{status:404})}async function l1($,Z){if(!await w1(H(b).config[$],Z))l4()}async function l3($,Z,J,W){let{config:Y}=H(b),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await y$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function RG($,Z,J){let{config:W}=H(b);await l3("signIn",g$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function nZ($){return await w1(H(b).config.verifyEmail,$)}class $0 extends B3{async me(){let $=await f0.user();if(!$)throw new o8;return $}async verifyEmail($=new A){await l1("password",$);let Z=await $.input(),{userProvider:J}=H(b),W=c5(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(b),{userProvider:J}=Z;if(!await w1(Z.config.magicLink,$)&&!await w1(Z.config.emailCode.enabled,$))l4();let W=c5($.search.get("token")),Y=null;try{Y=g$(decodeURIComponent($.search.get("email")??""))}catch{}if(await y$("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(b).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 l1("magicLink",$);let Z=H(b),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=g$(W),z=SG(Y);if(await y$("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(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,H(b).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(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,H(b).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 l5){await l1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b);await RG(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(b).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,...V}=z;return V}async signIn($=new l5){await l1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=H(b);await RG(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(b).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,...V}=z;return V}async signUp(){let $=H(b),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await l1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:G}=Y.toJSON(),Q={method:"password",input:EG(Y.toJSON()),req:W},V=AG(j);if(await l3("signUp",V,W),!V)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(V,!1))throw new u({email:["Email address already exists"]});let B=await J.hashPassword(z),U=H(c).detectLocale(W),D;if(G)D=await Z.findInvitation(G,V);let O,L="";if(D)O=await Z.transaction(async()=>{await Z.deleteInvitationById(G);let M=await Z.createUser({email:V,name:X,password:B,emailVerifiedAt:new Date,locale:U});return await Z.createAccount({organizationId:D.organizationId,userId:M.id,organizationRole:D.role}),await J.onUserCreated(M,Q),M});else{if(L=await J.generateEmailVerificationToken(V),typeof J.verifyEmail==="function"&&!await nZ(W))L="";O=await Z.transaction(async()=>{let M=await Z.createUser({email:V,name:X,password:B,verificationToken:L,locale:U});return await J.onUserCreated(M,Q),M})}return await J.onSignUp(O,L,W.search.toJSON(),{req:W}),O}async signOut($=new A){let Z=b$($),J=H(b),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",H(b).accessTokenCookieOptions($,new Date(0))),H(b).cookieDomain($))$.ctx().setCookie("access_token","",{...H(b).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)LL(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new wG){await l1("password",$);let Z=await $.input(),J=AG(Z.get("email"));if(await l3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=H(b),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 fG){await l1("password",$);let{userProvider:Z,config:J}=H(b),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=c5(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 nZ($));if(!Q)throw new u({email:["User not found"]});let V=await J.hashPassword(Y);return await Z.updateUserPassword({id:Q.id,password:V}),await Z.deleteAllUserSessions(Q.id),await J.onResetPassword(Q,{req:$}),{}}async changePassword($=new A){await l1("password",$);let{userProvider:Z,config:J}=H(b),W=await f0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await l3("signIn",g$(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(b).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=OZ($.rawRequest),z=O1($.search.get(l0),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else kG($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:G,codeChallenge:Q,cookieValue:V}=d4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(sZ(j),V,{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(b),{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=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 V=$.search.get("error");if(V)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(V)?V:"provider_error");let F=c4({provider:Z,cookieValue:Q,returnedState:$.search.get("state")});if("reason"in F)return console.error(`Authentication error: OAuth callback refused (${F.reason})`),this.oauthFailure($,F.reason);if(F.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let x=await z.redirectUriFor($);if(x!==void 0&&x!==F.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:F.payload.state,codeVerifier:F.payload.codeVerifier})}catch(x){if(x instanceof h5)return this.oauthFailure($,x.code);return console.error("Authentication error: OAuth provider callback failed",x),this.oauthFailure($,"provider_error")}let{name:U,username:D,providerId:O,emailVerified:L}=B??{},M=typeof B?.email==="string"?B.email:void 0,T=M?K6(M):null,P=O?await W.findUserBySocialAccount(Z,O):null,K="signin",R=!P&&!T&&!M&&!!O&&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:O,name:U,username:D,locale:H(c).detectLocale($),req:$}),K="signup"}catch(x){let f=await W.findUserBySocialAccount(Z,O);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":O?"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(c).detectLocale($);try{let f=await this.linkOAuthAccount({provider:Z,providerId:O,email:T,rawEmail:M,name:U,username:D,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 _=O?await W.findUserBySocialAccount(Z,O):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(b).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=bG($)??Y.redirectPath,w=Y.oauthCompleteProfilePath?O1(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(b);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=bG($),W=H(b).config.oauthFailurePath;if(W){let Y=O1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(l0,J);b1.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(b),V=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),F=await G.findUserByEmailAddress(W,!1),B=Y?.trim();if(!F&&B&&B!==W)F=await G.findUserByEmailAddress(B,!1);if(F){if($.linkExisting===!1)return"account_exists";if(!J)return{user:F,action:"signin"};let D=await G.findSocialAccounts(F.id,Z);if(D.some((L)=>L.providerId===J))return{user:F,action:"signin"};if(D.some((L)=>L.providerId))return console.error(`Authentication error: user ${F.id} is already linked to a different ${Z} account`),null;let O=D[0];if(O){if(!await G.claimSocialAccount(O,J))throw Error(`${Z} account link changed concurrently`)}else await G.createSocialAccount(V(F.id));return{user:F,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await G.transaction(async()=>{let D=await G.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await G.createSocialAccount(V(D.id));return await Q.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new A){await l1("magicLink",$);let Z=await $.input(),J=g$(Z.get("email")),W=H(b),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await y$("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(b),J=Z.config.emailCode;if(!await w1(J.enabled,$))l4();let W=await $.input(),Y=K6(W.get("email"));if(await y$("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(b),{userProvider:J,config:W}=Z;if(!await w1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),G=K6(j),Q=SG(z);if(await y$("verify",G,$,W.emailCode.verifyLimit,W.rateLimitKey),!G||!Q)throw new u({code:["invalid_code"]});let V=null;if(!u9(Q,W.emailCode)){let O=await Z.verifyOneTimeCode(G,Q,{claim:!1});if(O.status==="too_many_attempts")throw new u({code:["too_many_attempts"]});if(O.status!=="ok")throw new u({code:["invalid_code"]});V=O.row}let F=async()=>V?await Z.claimOneTimeCode(G,V.id):!0,B=await J.findUserByEmailAddress(G,!1),U=!1;if(B){if(!await F())throw new u({code:["invalid_code"]});await J.verifyUser(G)}else if(W.emailCode.createUser){let O=H(c).detectLocale($);try{B=await J.transaction(async()=>{if(!await F())throw new u5;let L=await J.createUser({email:G,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:O});return await W.onUserCreated(L,{method:"email-code",input:EG(Y.toJSON()),req:$}),L}),U=!0}catch(L){if(L instanceof u5)throw new u({code:["invalid_code"]});throw L}}else throw await F(),new u({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:G,id:B.id});return $.ctx().setCookie("access_token",D.token,H(b).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await JZ(Z.config,{session:D,isNewUser:U,method:"email-code",req:$}),{session:D,isNewUser:U}}}function LL($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=H();if(typeof J?.bound!=="function"||!J.bound(d0))return;J.make(d0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var qG="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=O1($.search.get(l0),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=OZ($.rawRequest),{state:X,codeChallenge:G,cookieValue:Q}=d4(vG(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(sZ(z,qG),Q,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:u3}),b1.external(W.authorizationUrl({state:X,codeChallenge:G,redirectUri:gG($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new A){let Z=String($.params.provider??""),J=H(i3),W=await f0.user(),Y=OZ($.rawRequest),j=sZ(Y,qG),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=c4({provider:vG(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 V=$.search.get("error");if(V)return this.finish(G,Z,/^[a-z0-9_]{1,64}$/.test(V)?V:"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 F=$.search.get("code");if(!F)return this.finish(G,Z,"missing_code");try{let B=await Q.exchangeCode({code:F,codeVerifier:X.payload.codeVerifier,redirectUri:gG($,Z,Q.config.redirectUri)}),U=await J.save(W,Z,B);await H(b).config.onConnected({user:W,provider:Z,connection:U,profile:B.profile??null,req:$})}catch(B){if(B instanceof yG)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=$||O1(H(b).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw b1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function vG($){return`connection:${$}`}function gG($,Z,J){if(J)return J;return`${WZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function mG($){return $.magicLink!==!1||Y7($.emailCode?.enabled)}function hG($){return Object.keys($.oauthProviders??{}).length>0}function pG($={}){let Z=[];if(mG($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Y7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(hG($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class dG extends R1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([U6,"auth"])}}function cG($={}){let Z=mG($),J=hG($);class W extends R1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[$0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[$0,"oauthCallback"])}}return class extends R1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[$0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":dG}}}class i5 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 s5 extends x0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new A().params.locale;return await H(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new A,Z=`/${$.params.scope??""}`,J=$.params.locale,W=H(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class n5{}class o5 extends n5{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 e_($){return $}function uG(){return{driver:new o5,allowedHosts:[],maxSize:10485760,timeout:1e4}}class V0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var ML=new Set([301,302,303,307,308]),HL="/api/__gemi__/services/image/";async function iG($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=lG($,Y);try{for(let z=0;;z++){let X=await TL(j,Z,W),G=X.headers.get("location");if(ML.has(X.status)&&G){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new V0(502,"The image redirects too many times");j=lG(G,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new V0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new V0(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 NL(z,W)}}function lG($,Z){let J;try{J=new URL($,Z)}catch{throw new V0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new V0(400,"Only http(s) images can be resized");return J}async function TL($,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(HL))throw new V0(403,"This image source is not allowed");if(PL($.pathname))throw new V0(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 k1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new V0(403,"This image source is not allowed");return k1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function PL($){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 NL($,Z){if($ instanceof V0)return $;if(Z.aborted)return new V0(504,"The image took too long to load",{cause:$});if($ instanceof D6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new V0(403,"This image source is not allowed",{cause:$});case"too-large":return new V0(413,"The image is too large",{cause:$});case"timeout":return new V0(504,"The image took too long to load",{cause:$})}return new V0(502,"The image could not be loaded",{cause:$})}class a5 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 sG(400,"url query parameter is required");let X=H(nG),G=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],Q=WZ();if(Q&&URL.canParse(Q))G.push(new URL(Q).origin);let V;try{V=await iG(J,{ownOrigins:G,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(U){if(U instanceof V0)return sG(U.status,U.message);throw U}let F=await X.resize(V.bytes,{height:Y,width:W,fit:j,quality:z}),B=new Headers({"Content-Type":"image/webp","Content-Length":`${F.byteLength}`});if(V.cacheControl)B.set("Cache-Control",V.cacheControl);return new Response(new Uint8Array(F),{headers:B})})}}function sG($,Z){return Response.json({error:Z},{status:$})}class nG{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=uG();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 t5 extends x0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(H(oG).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function OI($){return $}function aG(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function tG(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function KL($){return"run"in $}function _L($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function IL($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function xL($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function CL($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function rG($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function AL($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function r5($,Z="",J=[]){let W={};function Y(j,z,X,G,Q,V){let F=j==="/"?"":j,B=Z==="/"?"":Z,U=AL((`${B}${F}`===""?"/":`${B}${F}`).replaceAll("//","/"));if(!W[U])W[U]={};W[U][z.toUpperCase()]={exec:X,middleware:[...J,...G],...Q?{source:Q}:{},...V?{bodyLimitDefault:V}:{}},W[U].OPTIONS={exec:()=>{let O=new A().ctx().headers;return new Response(null,{headers:O,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(CL(z)){let X=z;for(let G of["GET","POST","PUT","DELETE"])Y(j,G,X.run.bind(X),X.middlewares);continue}if(KL(z)){let X=z,G=X.method,Q=X.middlewares,V=X.run.bind(X);if(Y(j,G,V,Q,X.source,X.__internal_bodyLimitDefault),rG(z))Y(j,"HEAD",V,Q,X.source)}if(_L(z))for(let[X,G]of Object.entries(z)){let Q=G,V=Q.middlewares,F=Q.run.bind(Q);if(Y(j,X,F,V,Q.source,Q.__internal_bodyLimitDefault),X==="get"&&rG(Q))Y(j,"HEAD",F,V,Q.source)}if(xL(z)){let X=new z,G=r5(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[Q,V]of Object.entries(G)){let F=Q.replaceAll("//","/");W[F]={...W[F],...V}}}if(IL(z)){let{first:X,second:G}=z;for(let[Q,V]of Object.entries(X)){let F=V.middlewares,B=V.run.bind(V),[U,...D]=j.split("/").reverse();if(!U.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),Q,B,F,V.source)}for(let[Q,V]of Object.entries(G)){let F=V.middlewares,B=V.run.bind(V);Y(j,Q,B,F,V.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,G=z.split("/").length+z.split(":").length;return X-G}))}var SL=Object.defineProperty,I=($,Z)=>SL($,"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,bL=/[$_\u200C\u200D\p{ID_Continue}]/u,$W=".*";function eG($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}I(eG,"isASCII");function WW($,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&&bL.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(!eG($[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(WW,"lexer");function YW($,Z={}){let J=WW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${c0(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"),V=I(()=>Q("OTHER_MODIFIER")??Q("ASTERISK"),"tryConsumeModifier"),F=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"),D=Z.encodePart||U,O="",L=I((P)=>{O+=P},"appendToPendingFixedValue"),M=I(()=>{O.length&&(Y.push(new tZ(3,"","",D(O),"",3)),O="")},"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,"","",D(P),"",w));return}let x;R?R==="*"?x=$W:x=R:x=W;let f=2;x===W?(f=1,x=""):x===$W&&(f=0,x="");let _;if(K?_=K:R&&(_=j++),G.has(_))throw TypeError(`Duplicate name '${_}'.`);G.add(_),Y.push(new tZ(f,_,D(P),x,D(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=V();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();F("CLOSE");let _=V();T(S,w,x,f,_);continue}M(),F("END")}return Y}I(YW,"parse");function c0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(c0,"escapeString");function ZW($){return $&&$.ignoreCase?"ui":"u"}I(ZW,"flags");function $Q($,Z,J){return jW(YW($,J),Z,J)}I($Q,"stringToRegexp");function YZ($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}I(YZ,"modifierToString");function jW($,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+=c0(X.value):W+=`(?:${c0(X.value)})${YZ(X.modifier)}`;continue}Z&&Z.push(X.name);let G=`[^${c0(J.delimiter)}]+?`,Q=X.value;if(X.type===1?Q=G:X.type===0&&(Q=$W),!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+=`(?:${c0(X.prefix)}(${Q})${c0(X.suffix)})`,W+=YZ(X.modifier);continue}W+=`(?:${c0(X.prefix)}`,W+=`((?:${Q})(?:`,W+=c0(X.suffix),W+=c0(X.prefix),W+=`(?:${Q}))*)${c0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${c0(J.endsWith)}]|$`,j=`[${c0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,ZW(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,ZW(J))}I(jW,"partsToRegexp");var K$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},RL={delimiter:".",prefixes:"",sensitive:!0,strict:!0},kL={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function ZQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}I(ZQ,"isAbsolutePathname");function zW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}I(zW,"maybeStripPrefix");function JQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}I(JQ,"maybeStripSuffix");function XW($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}I(XW,"treatAsIPv6Hostname");var WQ=["ftp","file","http","https","ws","wss"];function GW($){if(!$)return!0;for(let Z of WQ)if($.test(Z))return!0;return!1}I(GW,"isSpecialScheme");function YQ($,Z){if($=zW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}I(YQ,"canonicalizeHash");function jQ($,Z){if($=zW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}I(jQ,"canonicalizeSearch");function zQ($,Z){return Z||$===""?$:XW($)?VW($):BW($)}I(zQ,"canonicalizeHostname");function XQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}I(XQ,"canonicalizePassword");function GQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}I(GQ,"canonicalizeUsername");function QQ($,Z,J){if(J||$==="")return $;if(Z&&!WQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}I(QQ,"canonicalizePathname");function BQ($,Z,J){return QW(Z)===$&&($=""),J||$===""?$:FW($)}I(BQ,"canonicalizePort");function VQ($,Z){return $=JQ($,":"),Z||$===""?$:o4($)}I(VQ,"canonicalizeProtocol");function QW($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}I(QW,"defaultPortForProtocol");function o4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}I(o4,"protocolEncodeCallback");function FQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}I(FQ,"usernameEncodeCallback");function UQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}I(UQ,"passwordEncodeCallback");function BW($){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(BW,"hostnameEncodeCallback");function VW($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}I(VW,"ipv6HostnameEncodeCallback");function FW($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}I(FW,"portEncodeCallback");function OQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}I(OQ,"standardURLPathnameEncodeCallback");function DQ($){return $===""?$:new URL(`data:${$}`).pathname}I(DQ,"pathURLPathnameEncodeCallback");function LQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}I(LQ,"searchEncodeCallback");function MQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}I(MQ,"hashEncodeCallback");var HQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#Q=0;#X=0;#U=0;#O=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=WW(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.#V()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#F(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.#F(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#K()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#M()?this.#F(3):(this.#H()||this.#V()||this.#B())&&this.#F(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.#O+=1:this.#S()&&(this.#O-=1),this.#I()&&!this.#O?this.#J(6,1):this.#H()?this.#J(7,0):this.#V()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 6:this.#H()?this.#J(7,0):this.#V()?this.#J(8,1):this.#B()&&this.#J(9,1);break;case 7:this.#V()?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.#D?"/":""),[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}#F($){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.#$,"/")}#V(){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)}#E(){let $={};Object.assign($,K$),$.encodePart=o4;let Z=$Q(this.#G(),void 0,$);this.#D=GW(Z)}};I(HQ,"Parser");var e5=["protocol","username","password","hostname","port","pathname","search","hash"],N$="*";function JW($,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(JW,"extractValues");function I1($,Z){return Z?aZ($):$}I(I1,"processBaseURLString");function oZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=I1(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=I1(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=I1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=I1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=I1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=I1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=I1(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=I1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=VQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=GQ(Z.username,J)),typeof Z.password=="string"&&($.password=XQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=zQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=BQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!ZQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=I1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=QQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=jQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=YQ(Z.hash,J)),$}I(oZ,"applyInit");function aZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}I(aZ,"escapePatternString");function TQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}I(TQ,"escapeRegexpString");function PQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${TQ(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)),V=z>0?$[z-1]:null,F=z<$.length-1?$[z+1]:null;if(!Q&&G&&X.type===1&&X.modifier===3&&F&&!F.prefix.length&&!F.suffix.length)if(F.type===3){let B=F.value.length>0?F.value[0]:"";Q=Y.test(B)}else Q=!F.hasCustomName();if(!Q&&!X.prefix.length&&V&&V.type===3){let B=V.value[V.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&&(!V||V.type===3||V.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(PQ,"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 HQ($);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:N$,protocol:N$,username:N$,password:N$,hostname:N$,port:N$,search:N$,hash:N$};this.#j=oZ(j,$,!0),QW(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of e5){if(!(z in this.#j))continue;let X={},G=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,K$),X.encodePart=o4;break;case"username":Object.assign(X,K$),X.encodePart=FQ;break;case"password":Object.assign(X,K$),X.encodePart=UQ;break;case"hostname":Object.assign(X,RL),XW(G)?X.encodePart=VW:X.encodePart=BW;break;case"port":Object.assign(X,K$),X.encodePart=FW;break;case"pathname":GW(this.#W.protocol)?(Object.assign(X,kL,Y),X.encodePart=OQ):(Object.assign(X,K$,Y),X.encodePart=DQ);break;case"search":Object.assign(X,K$,Y),X.encodePart=LQ;break;case"hash":Object.assign(X,K$,Y),X.encodePart=MQ;break}try{this.#Y[z]=YW(G,X),this.#W[z]=jW(this.#Y[z],this.#Z[z],X),this.#$[z]=PQ(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,JW($,Z),!1)}catch{return!1}let W;for(W of e5)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,JW($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of e5){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 V=W(X[Q],G[Q]);if(V)return V}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 UW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function OW($){let Z=a4($);return Z.length>1?Z.replace(/\/$/,""):Z}function NQ($,Z){return Z.map((J)=>({...J,path:OW(UW($,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:V,features:F,static:B}]of Object.entries(z)){let U=UW(J,X),D=(O)=>Y.run.call(Y,O,J);Z[a4(U)]={exec:[D,...G],middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...F],viewPath:Y.viewPath,segments:[{path:OW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...NQ(J,V)],...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:OW(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:V,features:F,static:B}]of Object.entries(j)){let U=UW(J,z);Z[a4(U)]={exec:X,middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...F],viewPath:Q,segments:NQ(J,V),...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 DW="theme";function KQ($){return $==="light"||$==="dark"||$==="system"}function _Q($){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 n3($,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}var jZ={startIndex:0,carriedViews:[]};function _Q($,Z){let J=O0($.path,Z);return J.includes("*")?null:J}function bL($,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=_Q(Y,$.params),X=_Q(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 RL($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function IQ($){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=n3(Z,RL(z.pathname,J));if(!X)return jZ;return bL({segments:X.route.segments,params:X.params,search:z.search},j)}var LW="x-gemi-from";import{cloneElement as AM,createElement as i1,Fragment as VB}from"react";import{createElement as xQ,Fragment as CQ}from"react";function AQ($,Z,J){return[xQ(CQ,{key:"preloads"},...$),xQ(CQ,{key:"head"},...Z),J]}function kL($){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}`,V=X==="/"&&J!=="/"?J:Q;Z[V]=[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])=>[kL(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 MW($){let Z=[];for(let[J,W]of $)Z.push(J,...MW(W).flat());return Array.from(new Set(Z))}function SQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class _$ extends h{static getFacadeAccessor(){return c}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=P.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(P.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??_$.locale(),$.timeZone??_$.timeZone())}static setLocale($=_$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=P.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 HW{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function EQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var wL=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(EQ(Z.search??{}));W.delete("json"),W.sort();let Y=O0($,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>wL)Q=U}let V,F=new Promise((U)=>{V=U}),B={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:F,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);V()}),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 t0 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:Z$("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function KW(){return{status:403,error:{message:"Forbidden"}}}function o3($){let Z=$3.getStore(),J=P.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[O0(W,Y),j.toString()].filter((F)=>F.length>0).join("?"),G=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),Q=Z8($);if(Q)Z3(G,Q);let V=new A(G,Y);return $3.run(Z,()=>P.run(V,async()=>{let F=J?.locale;if(F&&H(c).isLocaleAware)P.getStore().setLocale(F);try{let B=H(B1).dispatchers(Q).api,U=await B.runRouteMiddleware(W,V)??await B.getRouteData(W);if(a1(U)){if(!U.ok)throw new t0(O0(W,Y),j.toString(),U.status,U.body);return U.body}if(U instanceof Response){let D=await U.json().catch(()=>null);if(!U.ok)throw new t0(O0(W,Y),j.toString(),U.status,D);return D}return U}catch(B){if(B instanceof t0)throw B;let U=new t0(O0(W,Y),j.toString(),500,{message:B instanceof Error?B.message:String(B)});throw U.cause=B,U}}))}}var fL=new Set(["script","style","template","title"]),qL=/\shidden([\s=/]|$)/i,vL=/"[^"]*"|'[^']*'/g;function gL($){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 F=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=F;else Z+=F}if(j===-1)break;if($.startsWith("<!--",j)){let F=$.indexOf("-->",j+4);Y=F===-1?$.length:F+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 V=G.startsWith("/");if(!V&&fL.has(Q)&&!G.endsWith("/")){let F=$.indexOf(`</${Q}`,Y);Y=F===-1?$.length:F;continue}if(Q!=="div")continue;if(V){if(W>0)W-=1}else if(W>0)W+=1;else if(qL.test(G.replace(vL,'""')))W=1}return{shellChars:Z,deferredChars:J}}var yL=1000,mL=64;function hL($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function pL($,Z){if(Z.deferredChars<yL)return null;if(Z.shellChars>=mL)return null;return`[gemi] GET ${$} streams ${hL(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 bQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=pL(J,W);if(!Y)return;Z.add(J),$(Y)}}}function RQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),gL(Z)}}}function kQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(V)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:V})};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 n3($,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}var jZ={startIndex:0,carriedViews:[]};function IQ($,Z){let J=O0($.path,Z);return J.includes("*")?null:J}function wL($,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=IQ(Y,$.params),X=IQ(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 fL($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function xQ($){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=n3(Z,fL(z.pathname,J));if(!X)return jZ;return wL({segments:X.route.segments,params:X.params,search:z.search},j)}var LW="x-gemi-from";import{cloneElement as bM,createElement as i1,Fragment as OB}from"react";import{createElement as CQ,Fragment as AQ}from"react";function SQ($,Z,J){return[CQ(AQ,{key:"preloads"},...$),CQ(AQ,{key:"head"},...Z),J]}function qL($){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}`,V=X==="/"&&J!=="/"?J:Q;Z[V]=[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])=>[qL(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 MW($){let Z=[];for(let[J,W]of $)Z.push(J,...MW(W).flat());return Array.from(new Set(Z))}function EQ($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class _$ extends h{static getFacadeAccessor(){return c}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??_$.locale(),$.timeZone??_$.timeZone())}static setLocale($=_$.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 HW{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function bQ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var vL=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(bQ(Z.search??{}));W.delete("json"),W.sort();let Y=O0($,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>vL)Q=U}let V,F=new Promise((U)=>{V=U}),B={path:j,patternPath:$,variantKey:z,lateBy:Q,status:"pending",promise:F,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);V()}),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 t0 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:Z$("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function TW(){return{status:403,error:{message:"Forbidden"}}}function o3($){let Z=$3.getStore(),J=N.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[O0(W,Y),j.toString()].filter((F)=>F.length>0).join("?"),G=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),Q=Z8($);if(Q)Z3(G,Q);let V=new A(G,Y);return $3.run(Z,()=>N.run(V,async()=>{let F=J?.locale;if(F&&H(c).isLocaleAware)N.getStore().setLocale(F);try{let B=H(B1).dispatchers(Q).api,U=await B.runRouteMiddleware(W,V)??await B.getRouteData(W);if(a1(U)){if(!U.ok)throw new t0(O0(W,Y),j.toString(),U.status,U.body);return U.body}if(U instanceof Response){let D=await U.json().catch(()=>null);if(!U.ok)throw new t0(O0(W,Y),j.toString(),U.status,D);return D}return U}catch(B){if(B instanceof t0)throw B;let U=new t0(O0(W,Y),j.toString(),500,{message:B instanceof Error?B.message:String(B)});throw U.cause=B,U}}))}}var gL=new Set(["script","style","template","title"]),yL=/\shidden([\s=/]|$)/i,mL=/"[^"]*"|'[^']*'/g;function hL($){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 F=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=F;else Z+=F}if(j===-1)break;if($.startsWith("<!--",j)){let F=$.indexOf("-->",j+4);Y=F===-1?$.length:F+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 V=G.startsWith("/");if(!V&&gL.has(Q)&&!G.endsWith("/")){let F=$.indexOf(`</${Q}`,Y);Y=F===-1?$.length:F;continue}if(Q!=="div")continue;if(V){if(W>0)W-=1}else if(W>0)W+=1;else if(yL.test(G.replace(mL,'""')))W=1}return{shellChars:Z,deferredChars:J}}var pL=1000,dL=64;function cL($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function uL($,Z){if(Z.deferredChars<pL)return null;if(Z.shellChars>=dL)return null;return`[gemi] GET ${$} streams ${cL(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 RQ($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=uL(J,W);if(!Y)return;Z.add(J),$(Y)}}}function kQ(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),hL(Z)}}}function wQ($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,G=(V)=>{if(X)return;X=!0,clearTimeout(Q);try{z.close()}catch{}W?.({aborted:V})};j=G,z.enqueue(Y.encode(`${JSON.stringify($)}
20
20
  `)),Z.onSettle((V)=>{if(X||V.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([V.path,V.variantKey,V.data])}
21
- `))});let Q=setTimeout(()=>G(!0),J);Z.allSettled().then(()=>G(!1),()=>G(!1))},cancel(){j(!1)}})}import{Fragment as lx,createContext as XM,createElement as ix,lazy as sx,use as nx,useContext as ox}from"react";import{createContext as dL}from"react";var cL=dL(null);import{createContext as iL,useContext as Kx}from"react";import{useContext as Ox}from"react";import{createContext as uL}from"react";import{jsx as Vx}from"react/jsx-runtime";var lL=uL({});var sL="gemi.islandI18n",nL=globalThis[Symbol.for(sL)]??=iL(null);import{createContext as pQ,useMemo as vx,useRef as gx}from"react";class TW{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 wQ($,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 fQ($){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 qQ="/auth/sign-in",oL=1000,aL=2,PW,NW=null,J3="idle",vQ=0,_W=[];function yQ($,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 tL($){let Z=$?.get?.(IW);if(typeof Z!=="string"||Z==="")return qQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return qQ}function rL(){let $=NW?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var gQ=($)=>$.replace(/\/+$/,"")||"/";function eL($,Z){let J=q8($),W=new URL($,"http://gemi.invalid");if(!J&&gQ(W.pathname)===gQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function $M($){if(!q8($)&&NW)NW.replace($);else window.location.replace($)}function mQ($){if(!PW||typeof window>"u")return;if(!yQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(J3==="handled")return;if(J3==="idle"&&vQ>=aL)return;if($.refetch)_W.push($.refetch);if(J3==="checking")return;J3="checking",vQ++;let Z=$;setTimeout(()=>{ZM(Z)},oL)}async function ZM($){let Z=!1,J=$.headers?.get?.(IW)?$.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=yQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=_W;if(_W=[],!Z){J3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}J3="handled";let Y=rL();if(!Y)return;let j=eL(tL(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>$M(j)};try{if(PW==="redirect")z.redirect();else PW?.(z)}catch(X){console.error(X)}}var xW=5000,JM=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;constructor($,Z){this.key=$,this.store=new TW(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($)}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=xW){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=xW){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=xW){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}),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.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.retryTimers.has($)||this.inflight.has($))return;let J=Math.min(Math.max(0,Z||0),JM),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)}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}));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 F=this.controllers.get($);if(!F)F=new Set,this.controllers.set($,F);F.add(j)}let z=()=>this.issued.get($)===Y,X=()=>(this.applied.get($)??0)>=Y,G=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},Q=this.store.getValue(),V=(F)=>{if(!z())return;G();let B=Q.get($);this.store.next(Q.set($,{loading:!1,data:B?.data,hasData:B?.hasData??!1,error:F,version:B?.version}))};try{let F=Q.get($);if(!Z)Q.set($,{loading:!0,data:F?.data,hasData:F?.hasData??!1,error:F?.error,version:F?.version});let B=null,U=null,D=[this.key,$].filter((O)=>O.length).join("?");try{U=await fetch(`/api${D}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{B=await fQ(U)}catch(O){if(U.ok)throw O;B=null}}catch(O){if(j?.signal.aborted){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}console.error(`Error fetching url /api${D}`,O),V(O);return}if(U.ok){if(X()){let L=Q.get($);if(z()&&L?.loading)this.store.next(Q.set($,{...L,loading:!1}));return}this.applied.set($,Y);let O=Q.get($);this.store.next(Q.set($,{loading:z()?!1:O?.loading??!1,data:B,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let O=new t0(this.key,$,U.status,B,wQ(U.headers?.get?.("retry-after")));if(V(O),z())mQ({source:"query",path:this.key,status:U.status,body:B,headers:U.headers,error:O,refetch:()=>this.resolveVariant($,!0,!1)})}}finally{if(j){let F=this.controllers.get($);if(F?.delete(j),F?.size===0)this.controllers.delete($)}if(z())this.inflight.delete($);this.settle($)}}}import{jsx as YM}from"react/jsx-runtime";var mx=pQ(null);var dQ=pQ({getResource:($,Z={})=>{return new zZ($,Z)},hydrate:()=>{},clearErrors:()=>{}});function WM(){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 hQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(hQ)]){let Z=WM(),J={seed:Z.hydrate,Provider:({children:W})=>YM(dQ.Provider,{value:Z,children:W})};$[Symbol.for(hQ)]=J}}import{createContext as jM}from"react";var zM=jM(null);function cQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,V){let F=J.find(Q,V);if(!F||F.source!=="prefetch"||F.status==="rejected")return null;return z(F),F}}: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(V,F){let B=Q.get(V);if(!B){let U=new Map(J.entriesFor(V).filter((O)=>O.source==="prefetch"&&O.status==="resolved").map((O)=>[O.variantKey,O]));B=new zZ(V,U.size>0?Object.fromEntries(Array.from(U,([O,L])=>[O,L.data])):F??{});let D=B.peek.bind(B);B.peek=(O)=>{let L=U.get(O);if(L)z(L);return D(O)},Q.set(V,B)}return B},hydrate(){},clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,V,F){let B=`${Q} ${V}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,V,F])},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 uQ($){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 lQ($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var a3="gemi-slot",iQ="data-slot",sQ="data-gemi-slot";var GM=Symbol.for("gemi.staticRender"),nQ=globalThis[GM]??=XM(null);import{createHash as eQ}from"crypto";var CW='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 QM}from"crypto";import{existsSync as aQ,readFileSync as BM}from"fs";import{join as bW}from"path";var tQ=".script",VM=[".ts",".js"],FM="document-scripts.json",rQ="data-gemi-script",UM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function OM($){if(typeof $!=="string"||!UM.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 DM($,Z){for(let J of VM){let W=bW($,"views",`${Z}${tQ}${J}`);if(aQ(W))return W}return null}async function oQ($){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 ax,createContext as BM,createElement as tx,lazy as rx,use as ex,useContext as $C}from"react";import{createContext as lL}from"react";var iL=lL(null);import{createContext as oL,useContext as Kx}from"react";import{useContext as Mx}from"react";import{createContext as sL}from"react";import{jsx as Ox}from"react/jsx-runtime";var nL=sL({});var aL="gemi.islandI18n",tL=globalThis[Symbol.for(aL)]??=oL(null);import{createContext as uQ,useMemo as px,useRef as dx}from"react";class PW{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 fQ($,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 qQ($){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 vQ="/auth/sign-in",rL=1000,eL=2,NW,KW=null,J3="idle",gQ=0,_W=[];function mQ($,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 $M($){let Z=$?.get?.(IW);if(typeof Z!=="string"||Z==="")return vQ;if(/^https?:\/\//i.test(Z))return Z;if(Z.startsWith("/")&&!Z.startsWith("//")&&!Z.includes("\\"))return Z;return vQ}function ZM(){let $=KW?.current();if($)return $;if(typeof window>"u")return null;return{pathname:window.location.pathname,search:window.location.search}}var yQ=($)=>$.replace(/\/+$/,"")||"/";function JM($,Z){let J=q8($),W=new URL($,"http://gemi.invalid");if(!J&&yQ(W.pathname)===yQ(Z.pathname))return null;return W.searchParams.set(l0,J?Z.pathname:`${Z.pathname}${Z.search}`),J?W.href:`${W.pathname}${W.search}`}function WM($){if(!q8($)&&KW)KW.replace($);else window.location.replace($)}function hQ($){if(!NW||typeof window>"u")return;if(!mQ($.status,$.body))return;if($.path.split("?")[0]==="/auth/me")return;if(J3==="handled")return;if(J3==="idle"&&gQ>=eL)return;if($.refetch)_W.push($.refetch);if(J3==="checking")return;J3="checking",gQ++;let Z=$;setTimeout(()=>{YM(Z)},rL)}async function YM($){let Z=!1,J=$.headers?.get?.(IW)?$.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=mQ(X.status,G),Z&&!J)J=X.headers}catch{}let W=_W;if(_W=[],!Z){J3="idle";for(let X of W)try{X()}catch(G){console.error(G)}return}J3="handled";let Y=ZM();if(!Y)return;let j=JM($M(J),Y);if(!j)return;let z={source:$.source,path:$.path,error:$.error,signInUrl:j,redirect:()=>WM(j)};try{if(NW==="redirect")z.redirect();else NW?.(z)}catch(X){console.error(X)}}class xW extends Error{url;timeout;constructor($,Z){super(`Request to ${$} timed out after ${Z}ms`);this.url=$;this.timeout=Z;this.name="TimeoutError"}}function pQ($,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 CW=5000,jM=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 PW(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(!dQ(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(!dQ(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=CW){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=CW){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=CW){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),jM),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=pQ(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,V=()=>{this.failures.set($,W?(this.failures.get($)??0)+1:1)},F=this.store.getValue(),B=(U)=>{if(!G())return;V();let D=F.get($);this.store.next(F.set($,{loading:!1,data:D?.data,hasData:D?.hasData??!1,error:U,version:D?.version,reconnecting:D?.reconnecting}))};try{let U=F.get($);if(!Z)F.set($,{loading:!0,data:U?.data,hasData:U?.hasData??!1,error:U?.error,version:U?.version,reconnecting:U?.reconnecting});let D=null,O=null,L=[this.key,$].filter((M)=>M.length).join("?");try{O=await fetch(`/api${L}`,{cache:J&&!this.staleVariants.has($)?"default":"reload",signal:j?.signal});try{D=await qQ(O)}catch(M){if(O.ok||z.timedOut())throw M;D=null}}catch(M){if(z.timedOut()){B(new xW(`/api${L}`,z.timeout()));return}if(j?.signal.aborted){let T=F.get($);if(G()&&T?.loading)this.store.next(F.set($,{...T,loading:!1}));return}console.error(`Error fetching url /api${L}`,M),B(M);return}if(O.ok){if(Q()){let T=F.get($);if(G()&&T?.loading)this.store.next(F.set($,{...T,loading:!1}));return}this.applied.set($,Y);let M=F.get($);this.store.next(F.set($,{loading:G()?!1:M?.loading??!1,data:D,hasData:!0,error:null,version:Date.now()})),this.staleVariants.delete($),this.lastFetchRecord.set($,Date.now()),this.failures.delete($)}else{let M=new t0(this.key,$,O.status,D,fQ(O.headers?.get?.("retry-after")));if(B(M),G())hQ({source:"query",path:this.key,status:O.status,body:D,headers:O.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 D=this.controllers.get($);if(D?.delete(j),D?.size===0)this.controllers.delete($)}if(G())this.inflight.delete($);this.settle($)}}}function dQ($){return typeof $==="number"&&$>0}import{jsx as XM}from"react/jsx-runtime";var ux=uQ(null);var lQ=uQ({getResource:($,Z={})=>{return new zZ($,Z)},hydrate:()=>{},clearErrors:()=>{}});function zM(){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 cQ="gemi.islandQueries";if(typeof window<"u"){let $=globalThis;if(!$[Symbol.for(cQ)]){let Z=zM(),J={seed:Z.hydrate,Provider:({children:W})=>XM(lQ.Provider,{value:Z,children:W})};$[Symbol.for(cQ)]=J}}import{createContext as GM}from"react";var QM=GM(null);function iQ($,Z={},J){let W=new Set,Y=new Map,j=J?{ensure(Q,V){let F=J.find(Q,V);if(!F||F.source!=="prefetch"||F.status==="rejected")return null;return z(F),F}}: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(V,F){let B=Q.get(V);if(!B){let U=new Map(J.entriesFor(V).filter((O)=>O.source==="prefetch"&&O.status==="resolved").map((O)=>[O.variantKey,O]));B=new zZ(V,U.size>0?Object.fromEntries(Array.from(U,([O,L])=>[O,L.data])):F??{});let D=B.peek.bind(B);B.peek=(O)=>{let L=U.get(O);if(L)z(L);return D(O)},Q.set(V,B)}return B},hydrate(){},clearErrors(){}}},islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Q,V,F){let B=`${Q} ${V}`;if(W.has(B))return;W.add(B),G.dictionaries.push([Q,V,F])},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 sQ($){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 nQ($){let Z;for(let J of $.queriesRead.values()){if(J.status!=="resolved")continue;Z??={},(Z[J.path]??={})[J.variantKey]=J.data}return Z}var a3="gemi-slot",oQ="data-slot",aQ="data-gemi-slot";var VM=Symbol.for("gemi.staticRender"),tQ=globalThis[VM]??=BM(null);import{createHash as JB}from"crypto";var AW='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 FM}from"crypto";import{existsSync as eQ,readFileSync as UM}from"fs";import{join as RW}from"path";var $B=".script",OM=[".ts",".js"],DM="document-scripts.json",ZB="data-gemi-script",LM=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function MM($){if(typeof $!=="string"||!LM.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 HM($,Z){for(let J of OM){let W=RW($,"views",`${Z}${$B}${J}`);if(eQ(W))return W}return null}async function rQ($){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 RW($){return`'sha256-${QM("sha256").update($).digest("base64")}'`}var AW,SW=new Map;function LM(){if(AW===void 0){let $=bW(EW(),"dist","server",FM);AW=aQ($)?JSON.parse(BM($,"utf8")):null}return AW??null}async function kW($){OM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=LM()?.[$];if(j!==void 0)return j;let z=SW.get($);if(z)return z}let J=bW(EW(),"app"),W=DM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${tQ}.ts (or .js).`);if(!Z)return oQ(W);let Y=oQ(W);return SW.set($,Y),Y.catch(()=>SW.delete($)),Y}async function XC($){return RW(await kW($))}var MM="gemi-islands",HM="gemi-island-i18n",KM="gemi-island-queries",DC=`'sha256-${eQ("sha256").update(qW).digest("base64")}'`;function wW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var fW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),LC=`'sha256-${eQ("sha256").update(CW).digest("base64")}'`,TM='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',PM="gemi-static";function $B($,Z,J,W,Y,j,z){let X=new Set,G=[];if(J)G=Z.islands.map((T)=>{let K=T.module?J(T.module):void 0;if(!K)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 N of K.preload)X.add(N);if(T.preloadDynamic)for(let N of K.dynamicPreload??[])X.add(N)}return{s:K.src,e:T.export,l:T.load}});let Q=G.some((T)=>T!==null),V=j?`<script type="module" ${rQ}="${fW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return wW($,"</head>",V,!1);let B=(Y?`<meta name="${PM}" content="${fW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${fW(T)}"/>`).join("")+V,U=Y?CW:qW,D=W?TM+U:U;z?.push(D);let O=Q?uQ(Z):void 0,L=Q?lQ(Z):void 0,M=(Q?`<script type="application/json" id="${MM}">${i0({i:G})}</script>`:"")+(O?`<script type="application/json" id="${HM}">${i0(O)}</script>`:"")+(L?`<script type="application/json" id="${KM}">${i0(L)}</script>`:"")+`<script type="module">${D}</script>`;return wW(wW($,"</head>",B,!1),"</body>",M,!0)}function NM($,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 ZB($){let Z=`<template ${sQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=NM($,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=`<${a3} ${iQ}="${j}" style="display:contents"></${a3}>`;$=$.split(G).join(`<${a3} style="display:contents">${X}</${a3}>`)}return $}function vW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function jB($,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 _M($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var JB=new Set,IM=new Set(["public","private","s-maxage","proxy-revalidate"]);function gW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=zB(J);if(Bun.env.NODE_ENV!=="production"&&!JB.has(Z)){JB.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 zB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!IM.has(W)})].join(", ")}var WB=new Set;function XB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=zB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!WB.has(Z))WB.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 YB=new Set;function GB($,Z){if(!_M($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!YB.has(Z))YB.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 xM="'strict-dynamic' 'self' https: 'unsafe-inline'",QB="Content-Security-Policy",BB="Content-Security-Policy-Report-Only";function CM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${xM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function yW($,Z,J){if(!Z)return;if($.has(QB)||$.has(BB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?BB:QB,CM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(RW)},W))}var SM=async()=>(await import("./chunk-3rgf7rsy.js")).default,mW,t3=async(...$)=>{return mW??=import("react-dom/server.browser").catch((Z)=>{throw mW=void 0,Z}),(await mW).renderToReadableStream(...$)},FB=1e4,UB="no-locale",EM="no-theme";async function bM($,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 lW="/assets";function RM($){return $===lW||$.startsWith(`${lW}/`)}function kM($){let Z=$.filter(RM);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 "${lW}" 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 wM($){let Z=H(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function hW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function fM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class r3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=bQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;csp;constructor($,Z={}){let J=aG();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.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":dG(Z)};if(this.requiredViews=Object.fromEntries(hG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)kM(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=MW(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(W$);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 V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>i1("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 V=uW(),F=new AbortController,B=setTimeout(()=>F.abort(),FB),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=cQ(async(O,L)=>{let M=await t3(O,{signal:F.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 O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await kW(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??"",O?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await t3(i1(nQ.Provider,{value:D,children:i1(VB,{children:[...Q,i1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let K=ZB(await new Response(T).text()),N=[],R=$B(K,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,O,N);return yW(X,this.csp,{nonce:pW(Z.rawRequest),inlineScripts:N}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,breadcrumbs:L,urlLocaleSegment:M,meta:T,isOgRequest:K,appId:N,features:R,staticView:C,cspNonce:S}=$,w=this.theme===!1||B||C?null:{cookie:this.theme.cookie??DW,default:this.theme.default??null,value:qM(Z,this.theme.cookie??DW)},x=M?SQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?wM(Z):null},appId:N,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:BZ,getStyles:x$,viewImportMap:d,cssManifest:g,ogMap:F0,viewModules:V1,clientEntry:C$,modulePreloadManifest:z3,assetBase:u0,resolveIsland:A$,buildId:S1}=H0,E1=C$?[]:j3,l=(y)=>[y,`window.loaders=${BZ}`,...C$?[`import(${JSON.stringify(C$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(K){let y=null,F1=null;for(let E of k??[])if(typeof F0[E]==="function")F1=E,y=F0[E];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await t3(i1(y,Z6[F1]),{onError:()=>{}})}catch(E){let{fonts:r,...o1}=E.satoriOptions,J6=await Promise.all(r.map((W6)=>{return bM(W6.name,W6.weight,W6.style).then((CV)=>({...W6,data:CV}))})),T2=new Headers(j);T2.set("Content-Type","image/png");let[NV,_V]=await Promise.all([SM(),n4("Rendering an OG image")]),IV=await NV(E.jsx,{...o1,fonts:J6}),xV=await _V(Buffer.from(IV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(xV),{headers:T2})}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:x$,viewImportMap:d,viewModules:V1,resolveIsland:A$,buildId:S1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!d[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:x$,viewImportMap:{...d,"404":d[y]},viewModules:V1&&{...V1,"404":V1[y]},resolveIsland:A$,buildId:S1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=z3??{},u0&&u0!=="/")f.data.assetBase=u0;if(S1&&S1!=="dev")f.data.buildId=S1;let P8=OB(this.modulePreloadLinks({clientEntry:C$,modulePreloadManifest:z3,views:k??["404"],routeKey:Y??"404"}),S),N8=OB(await x$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let r0=new AbortController,VZ=setTimeout(()=>r0.abort(),FB),S$=I6(V)||F,n1=Bun.env.NODE_ENV!=="production"&&!S$&&Y&&this.shellReporter.shouldObserve(Y)?RQ():null,E$=uW();try{let y=await t3(i1(VB,{children:AQ(P8,[...N8,...w?[i1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:NQ(i0({cookie:w.cookie,default:w.default}))}})]:[]],i1(_,{data:f.data,viewImportMap:d,viewModules:V1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:E1,nonce:S,signal:r0.signal,...S$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),S$)await y.allReady.catch(()=>{});return new Response(X7(y,Q,{onShell:S$?void 0:()=>Q.markShell(),onChunk:n1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(r0.signal.aborted)),n1)this.shellReporter.report(Y,n1.measure())})},E$,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(r0.signal.aborted))),y;let F1=await t3(i1("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",...E1]:E1,nonce:S});return new Response(X7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(k$(Z))return 404;if(Z?.kind===e1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if($$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=H(c),B=n3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(UB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=dW(z,F.supportedLocales,F.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(c).detectLocale(new A($,{},"view",G));if(V===null&&_!==F.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 O=[],L=[],M=null,T={},K=null,N=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=n3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(UB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,C=_.route.features,N=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(LW),H0=IQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)O=O.slice(H0.startIndex),K={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 P.run(f,async()=>{let _=null,k=P.getStore(),H0=$3.getStore(),j3=(g)=>$3.run(H0,()=>P.runWith(k,g));k.serverQueries=new rZ(o3($));let BZ=new Set;k.serverQueries.onQueryFail((g)=>{BZ.add(g.error);try{j3(()=>Promise.resolve(this.hooks.onRequestFail(d,g.error)).catch(()=>{}))}catch{}});let x$=vW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(V){let g=V.replaceAll("/","");_$.setLocale(g,{cookie:x$.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else _$.setLocale(void 0,{cookie:x$.locale});let d=k.req;if(x$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(c).isLocaleAware){let{supportedLocales:E,defaultLocale:r}=H(c),o1=await this.detectLocale(d,{supportedLocales:E,defaultLocale:r}),J6=typeof o1==="string"?dW(o1,E,r):null;if(J6)k.setLocale(J6)}try{await H(r1).runMiddleware(L)}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,O=[],d.routePath="";let F0=H(c),V1=F0.isEnabled,C$=F0.isLocaleAware,z3=new A($,d.params),u0={defaultLocale:F0.defaultLocale,timeZone:F0.detectTimeZone(z3)};if(C$){let E=null;if(V)E=V.replaceAll("/",""),k.setLocale(E);else if(!U)E=k.locale??F0.defaultLocale;else E=F0.detectLocale(z3),k.setLocale(E);let r=V1?F0.getPageTranslations(E,d.routePath):{};u0={...u0,supportedLocales:F0.supportedLocales,currentLocale:E,dictionary:{[E]:r},defaultLocale:F0.defaultLocale,...U?{}:{localeRouting:"off"}}}await cW(u0.currentLocale??"");let A$;try{A$=await Promise.all(O.map((E)=>E(d)))}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E;M=null,O=[],d.routePath="",A$=[]}let S1=void 0;if(M===null){if(S1=await this.hooks.onNotFound(d,{status:g??404}),C$&&!U&&k.locale&&k.locale!==u0.currentLocale){let E=k.locale;u0={...u0,currentLocale:E,dictionary:{[E]:V1?F0.getPageTranslations(E,d.routePath):{}}},await cW(E)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(d):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:E1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:A$,cookies:E1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:d.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(HW).id,features:await H(W$).forClient()};let{params:P8,user:N8}=_,r0={},VZ={};for(let E of A$??[]){let[r,o1]=Object.entries(E)?.[0]??[];if(!r||!o1)continue;VZ[`${r}:${M}`]=o1.breadcrumb,r0[r]=o1}let S$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(S$&&S1)r0["404"]=S1;let n1=r0.FILE;if(n1){try{await this.onRequestEnd(d,{mintSession:!1})}catch(r){XZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let E;if(n1 instanceof Response)E=Y8(n1,l,E1);else{for(let r of E1)l.append("Set-Cookie",r.toString());E=await f8(n1,l)}return GB(E,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",LW),E1.forEach((r)=>l.append("Set-Cookie",r.toString())),gW(l,M),await this.hooks.onRequestEnd(d);let E={meta:K&&!k.metadata.touched?null:_.meta,data:{[G]:r0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:K};return new Response(kQ(E,k.serverQueries,void 0,({aborted:r})=>j3(()=>this.completeStream(d,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:S$,y=Boolean(E$),F1=vW(E$);if(!N&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let E of E1)l.append("Set-Cookie",E.toString());if(!y||F1.csrf){let E=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${E}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(d,{mintSession:!y||F1.session})}catch(E){XZ.error(E?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(E)})}if(y&&(M||!w))jB(l,E$);gW(l,M);let Z6=y?void 0:DB($);if(!y)yW(l,this.csp,{nonce:Z6});if(pW($))XB(l,M,y);return await this.render({req:d,runInRequestScope:j3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:P8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:N,noTheme:R,url:J,user:N8,viewData:r0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===e1){let F0=W?fM(g.payload.viewData??g.payload.api):hW(g.payload.view);for(let V1 of k.cookies)F0.headers.append("Set-Cookie",V1.toString());return F0}if(!BZ.has(g))this.hooks.onRequestFail(d,g);if($$(g))return console.error(g),W?eZ():hW(KW());if(g instanceof t0&&g.status===403)return W?eZ():hW(KW());throw g}},Z)}}function OB($,Z){return Z?$.map((J)=>AM(J,{nonce:Z})):$}function qM($,Z){let J=$.cookies?.get(Z);return PQ(J)?J:null}function iW(){let $=JSON.stringify({error:Z$("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 KB 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(r3).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 vM=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),gM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,yM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function mM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(vM.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===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!gM.test(Y)||!yM.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function hM($,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 LB($){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 Y8($,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 pM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=oG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r5({"/":$.rootRouter,"/auth":i5,"/__gemi__/services/i18n":s5,"/__gemi__/services/image":a5,...pM()?{"/__gemi__/services/logs":t5,"/__gemi__/debug":KB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=HB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;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(r1).runMiddleware(W)}catch(Y){if(Y.kind===e1)return LB(Y.payload.api);else{if(k$(Y))return iW();if(this.onRequestFail(Z,Y),console.error(Y),$$(Y))return eZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=P.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===e1)return LB(j.payload.api);if(k$(j))return iW();if(this.onRequestFail(J.req,j),console.error(j),$$(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||!Y[$.method])return new Response(JSON.stringify({error:Z$("not_found","Not found",404)}),{status:404});let j=new A($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await P.run(j,async()=>{let z=P.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=H(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),H(r1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=Y8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=Y8(F,B,U);if(this.isOpenEndedBody($,O)){let L=hM(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(a1(F)?F:U1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}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,V=[],F=G?null:$.cookies.get(t1);if(F)V.push(`${t1}=${F}`);if(Y?.credentials)mM(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(t1);if(B)Q.set(t1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(MB(O,DZ($),G?.grant,Y?.progress),$.domain)Z3(O,$.domain);let L=G?{user:G.user}:void 0;return P.exit(()=>B6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as dM}from"crypto";var G8="",oW="*",cM=60000,uM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,sW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,nW="x-forwarded-host";function PB($){return $.startsWith(":")}function e3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&dM(J,W)}function lM($){if(!$)return[];if($===!0)return[{header:nW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:nW;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 iM($){if(!$||$===!0)return;if(!Array.isArray($)){TB($,"route.domains.trustProxy",nW);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.`);TB(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 TB($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!sW.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"||!sW.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"||!sW.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 x1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function sM($){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 NB($){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 nM($){let Z=x1($.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.`);iM($.trustProxy),NB($.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),PB(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 aW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){nM($),this.root=x1($.root),this.devHosts=NB($.devHosts),this.hostTrusts=lM($.trustProxy);for(let Z of $.groups??[])if(PB(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??cM,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||e3($.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:f$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return x1(this.forwardedHost($))??x1(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&&x1(Y)?sM(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:oW,params:{},custom:!0};return null}async allows($,Z){let J=x1($);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>=uM)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=x1($);if(Z)this.cache.delete(Z)}}}var oM={kind:"none"};function iA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return oM;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 sA($,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:f$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var _B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,IB=16;function nA($){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(!_B.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!_B.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<IB)throw Error(`GEMI_PROXY_SECRET must be at least ${IB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function xB($,Z){if(!e3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:f$(J)}var aM="/__gemi__/domains/ask";class B1{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 aW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new r3({...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(oW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)tW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?xB($.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)tW($,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!==aM)return null;if(!e3(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 CB=600000;function AB($,Z){return[T6($,Z),T6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new F7){l9($.oauthProviders),this.config={..._1(i9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await TZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await GY(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(B1)?H(B1).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(B1).resolver?.root:x1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??x1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))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=P.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/CB),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=T6($,j),V=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:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of AB($,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(t8($)||!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()/CB),W=AB($,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=P.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 w$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=E9(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:q9(Z),G=P6("link",$,j),Q=P6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+V>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 KZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((Q)=>W3(Q.createdAt)+W*60000>Date.now());if(z.length===0)return KZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let Q of z)if(!await y9(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(KZ("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 KZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(KZ("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 b}static async user(){let $=await f0.userOrNull();if($)return $;throw new w$({redirectTo:F6(P.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=P.getStore();if($?.user)return $.user;let Z=await z6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=P.getStore()?.req;return O1(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=P.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new rZ(o3(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 $=P.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new rZ(o3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function tM($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function rW($,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==="*"?tM(z):encodeURIComponent(String(z))}`});return`${B8}${J==="/"?"":J}`||B8}var SB=new Map;function EB($,Z){let J=SB.get($);if(!J)J=new URLPattern({pathname:`${B8}${$==="/"?"":$}`}),SB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function bB($,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=rM(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 rM($){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 RB{static origin($){return eW($)}static absolute($,...Z){return`${WZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(B1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=P.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 bB({root:W.root,origin:j},$,O0(String(Z),J[0]??{}))}static api($,...Z){return rW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${eW()}${rW(String($),Z[0]??{})}`}static matchApi($,Z){return EB(String($),Z)}}class kB{name="Meta";static description($){P.getStore().metadata.description($)}static title($){P.getStore().metadata.title($)}static openGraph($){P.getStore().metadata.openGraph($)}static htmlAttributes($){P.getStore().metadata.htmlAttributes($)}static canonical($){P.getStore().metadata.canonical($)}static alternates($){P.getStore().metadata.alternates($)}static tags($){P.getStore().metadata.tags($)}static robots($){P.getStore().metadata.robots($)}static translate($=!0){P.getStore().metadata.translate($)}static fonts($){P.getStore().metadata.fonts($)}}var eM={set($,Z,J){P.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(P.getStore().req.cookies.has($))return!1;return P.getStore().setCookie($,Z,J),!0},delete($,Z){P.getStore().deleteCookie($,Z)}};class s1 extends h{static getFacadeAccessor(){return GZ}static get client(){return this.getFacadeRoot().client}static get($){return s1.client.get($)}static set($,Z){return s1.client.set($,Z)}static del(...$){return s1.client.del(...$)}static exists($){return s1.client.exists($)}static incr($){return s1.client.incr($)}static expire($,Z){return s1.client.expire($,Z)}static ttl($){return s1.client.ttl($)}}function lS($){return $}function wB(){return{store:"memory",ttl:null}}class $2{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 $H="500";class Z2{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=`${ZH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",$H]),[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 ZH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var JH="k:",fB="tag:",WH="t:";class J2{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 W2 extends J2{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=_1(wB(),$),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 vB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return JH+gB($)}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=fB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=qB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(fB+Z,qB(),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 $2(this.config.memory);if($==="redis"){let Z=this.options.application;return new Z2({...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 vB extends J2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){gB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${WH}${Z.join(",")}:${$}`}}function gB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function qB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class yB extends h{static getFacadeAccessor(){return W2}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 mB 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 pB extends h{static getFacadeAccessor(){return hB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class cB extends h{static getFacadeAccessor(){return dB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class uB 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()}}function KE($){return $}function lB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function V8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function Y2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:YH}=globalThis.Bun;function jH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var zH=async($)=>{let Z=new YH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},XH=async($)=>{let Z;try{Z=(await import("./chunk-12gthjxx.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},iB=($)=>jH()?zH($):XH($);var GH=/^[A-Za-z_][A-Za-z0-9_]*$/;class j2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!GH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??iB}async createTable(){for(let $ of QH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return sB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
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 kW($){return`'sha256-${FM("sha256").update($).digest("base64")}'`}var SW,EW=new Map;function TM(){if(SW===void 0){let $=RW(bW(),"dist","server",DM);SW=eQ($)?JSON.parse(UM($,"utf8")):null}return SW??null}async function wW($){MM($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=TM()?.[$];if(j!==void 0)return j;let z=EW.get($);if(z)return z}let J=RW(bW(),"app"),W=HM(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${$B}.ts (or .js).`);if(!Z)return rQ(W);let Y=rQ(W);return EW.set($,Y),Y.catch(()=>EW.delete($)),Y}async function FC($){return kW(await wW($))}var PM="gemi-islands",NM="gemi-island-i18n",KM="gemi-island-queries",PC=`'sha256-${JB("sha256").update(vW).digest("base64")}'`;function fW($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var qW=($)=>$.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;"),NC=`'sha256-${JB("sha256").update(AW).digest("base64")}'`,_M='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',IM="gemi-static";function WB($,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),V=j?`<script type="module" ${ZB}="${qW(j.name)}">${j.source}</script>`:"";if(j)z?.push(j.source);if(!Q&&!Y)return fW($,"</head>",V,!1);let B=(Y?`<meta name="${IM}" content="${qW(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...X].map((T)=>`<link rel="modulepreload" href="${qW(T)}"/>`).join("")+V,U=Y?AW:vW,D=W?_M+U:U;z?.push(D);let O=Q?sQ(Z):void 0,L=Q?nQ(Z):void 0,M=(Q?`<script type="application/json" id="${PM}">${i0({i:G})}</script>`:"")+(O?`<script type="application/json" id="${NM}">${i0(O)}</script>`:"")+(L?`<script type="application/json" id="${KM}">${i0(L)}</script>`:"")+`<script type="module">${D}</script>`;return fW(fW($,"</head>",B,!1),"</body>",M,!0)}function xM($,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 YB($){let Z=`<template ${aQ}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=xM($,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=`<${a3} ${oQ}="${j}" style="display:contents"></${a3}>`;$=$.split(G).join(`<${a3} style="display:contents">${X}</${a3}>`)}return $}function gW($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function GB($,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 CM($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var jB=new Set,AM=new Set(["public","private","s-maxage","proxy-revalidate"]);function yW($,Z){let J=$.get("Cache-Control");if(!J||$.getSetCookie().length===0)return;if(!/(^|[\s,])(public|s-maxage)\b/i.test(J))return;let W=QB(J);if(Bun.env.NODE_ENV!=="production"&&!jB.has(Z)){jB.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 QB($){return["private",...$.split(",").map((J)=>J.trim()).filter((J)=>{let W=J.split("=")[0].trim().toLowerCase();return W!==""&&!AM.has(W)})].join(", ")}var zB=new Set;function BB($,Z,J){let W=$.get("Cache-Control");if(!W||!/(^|[\s,])(public|s-maxage)\b/i.test(W))return;let Y=QB(W);if(J&&Bun.env.NODE_ENV!=="production"&&!zB.has(Z))zB.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 XB=new Set;function VB($,Z){if(!CM($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!XB.has(Z))XB.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 SM="'strict-dynamic' 'self' https: 'unsafe-inline'",FB="Content-Security-Policy",UB="Content-Security-Policy-Report-Only";function EM($,Z={}){let J=[...$.nonce?[`'nonce-${$.nonce}'`]:[],...$.hashes??[]],W=[J.length>0?`script-src ${J.join(" ")} ${SM}`:"script-src 'none'","object-src 'none'","base-uri 'self'"];if(Z.reportUri)W.push(`report-uri ${Z.reportUri}`);return W.join("; ")}function mW($,Z,J){if(!Z)return;if($.has(FB)||$.has(UB))return;let W=Z===!0?{}:Z;$.set(W.reportOnly?UB:FB,EM({nonce:J.nonce,hashes:[...new Set(J.inlineScripts??[])].map(kW)},W))}var RM=async()=>(await import("./chunk-3rgf7rsy.js")).default,hW,t3=async(...$)=>{return hW??=import("react-dom/server.browser").catch((Z)=>{throw hW=void 0,Z}),(await hW).renderToReadableStream(...$)},DB=1e4,LB="no-locale",kM="no-theme";async function wM($,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 iW="/assets";function fM($){return $===iW||$.startsWith(`${iW}/`)}function qM($){let Z=$.filter(fM);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 "${iW}" 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 vM($){let Z=H(B1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function pW($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function gM($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class r3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=RQ();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;csp;constructor($,Z={}){let J=tG();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.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":cG(Z)};if(this.requiredViews=Object.fromEntries(pG(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=t4(W),!this.assetRoutes)qM(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=MW(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(W$);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 V of J?.[Q]??[])G.add(V);return[...G].map((Q)=>i1("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 V=lW(),F=new AbortController,B=setTimeout(()=>F.abort(),DB),U=(O)=>{if(Bun.env.NODE_ENV!=="production")console.error(O)},D=iQ(async(O,L)=>{let M=await t3(O,{signal:F.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 O,L=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(L)O={name:L,source:await wW(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??"",O?.name??"",S].join("|"),prefetch:C.prefetch==="none"?"none":"intent"}}let T=await t3(i1(tQ.Provider,{value:D,children:i1(OB,{children:[...Q,i1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:V,rootLayout:G,key:"root"})]})}),{signal:F.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:U});await T.allReady.catch(()=>{});let P=YB(await new Response(T).text()),K=[],R=WB(P,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",M,O,K);return mW(X,this.csp,{nonce:dW(Z.rawRequest),inlineScripts:K}),new Response(R,{status:$.status,headers:X})}finally{clearTimeout(B),J(()=>this.completeStream(Z,z.summarize(F.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:G,serverQueries:Q,userAgent:V,noStream:F,noTheme:B,url:U,user:D,viewData:O,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??DW,default:this.theme.default??null,value:yM(Z,this.theme.cookie??DW)},x=M?EQ(G,[M]).pathname:G,f={kind:"view",data:{meta:T,pageData:{[x]:O},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:L,router:{urlLocaleSegment:M,pathname:Y,params:X,currentPath:G,searchParams:U.search,is404:!Y?!0:!1,domain:Z.domain?vM(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:BZ,getStyles:x$,viewImportMap:d,cssManifest:g,ogMap:F0,viewModules:V1,clientEntry:C$,modulePreloadManifest:z3,assetBase:u0,resolveIsland:A$,buildId:S1}=H0,E1=C$?[]:j3,l=(y)=>[y,`window.loaders=${BZ}`,...C$?[`import(${JSON.stringify(C$.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(P){let y=null,F1=null;for(let E of k??[])if(typeof F0[E]==="function")F1=E,y=F0[E];if(!y)return new Response("Not found",{status:404});let Z6=Object.values(f.data.pageData)[0];try{await t3(i1(y,Z6[F1]),{onError:()=>{}})}catch(E){let{fonts:r,...o1}=E.satoriOptions,J6=await Promise.all(r.map((W6)=>{return wM(W6.name,W6.weight,W6.style).then((EV)=>({...W6,data:EV}))})),N2=new Headers(j);N2.set("Content-Type","image/png");let[xV,CV]=await Promise.all([RM(),n4("Rendering an OG image")]),AV=await xV(E.jsx,{...o1,fonts:J6}),SV=await CV(Buffer.from(AV)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(SV),{headers:N2})}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:x$,viewImportMap:d,viewModules:V1,resolveIsland:A$,buildId:S1,status:200});if(C&&!Y&&this.notFound){let y=this.notFound.view;if(!d[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:x$,viewImportMap:{...d,"404":d[y]},viewModules:V1&&{...V1,"404":V1[y]},resolveIsland:A$,buildId:S1,status:$.refusedStatus??404})}if(f.data.cssManifest=g,f.data.modulePreloadManifest=z3??{},u0&&u0!=="/")f.data.assetBase=u0;if(S1&&S1!=="dev")f.data.buildId=S1;let N8=MB(this.modulePreloadLinks({clientEntry:C$,modulePreloadManifest:z3,views:k??["404"],routeKey:Y??"404"}),S),K8=MB(await x$(k??["404"]),S);f.data.prefetchedData=Q.snapshotResolved(),Q.markRenderStart();let r0=new AbortController,VZ=setTimeout(()=>r0.abort(),DB),S$=I6(V)||F,n1=Bun.env.NODE_ENV!=="production"&&!S$&&Y&&this.shellReporter.shouldObserve(Y)?kQ():null,E$=lW();try{let y=await t3(i1(OB,{children:SQ(N8,[...K8,...w?[i1("script",{key:"theme-script",nonce:S,dangerouslySetInnerHTML:{__html:_Q(i0({cookie:w.cookie,default:w.default}))}})]:[]],i1(_,{data:f.data,viewImportMap:d,viewModules:V1,serverQueries:Q,dictionarySink:E$,cspNonce:S,key:"root"}))}),{bootstrapScriptContent:l(`window.__GEMI_DATA__ = ${i0(f.data)}`),bootstrapModules:E1,nonce:S,signal:r0.signal,...S$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(F1){if(Bun.env.NODE_ENV!=="production")console.error(F1)}});if(y.allReady.catch(()=>{}).finally(()=>clearTimeout(VZ)),S$)await y.allReady.catch(()=>{});return new Response(X7(y,Q,{onShell:S$?void 0:()=>Q.markShell(),onChunk:n1?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,Q.summarize(r0.signal.aborted)),n1)this.shellReporter.report(Y,n1.measure())})},E$,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(r0.signal.aborted))),y;let F1=await t3(i1("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",...E1]:E1,nonce:S});return new Response(X7(F1,Q,{onClose:()=>J(()=>this.completeStream(Z,Q.summarize(r0.signal.aborted)))},void 0,S),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(k$(Z))return 404;if(Z?.kind===e1){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if($$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof t0&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),G=j,Q=null,V=null,F=H(c),B=n3(this.flatViewRoutes,j),U=F.isLocaleAware&&this.localeRouting==="prefix"&&!B?.route.middleware.includes(LB);if(U&&F.supportedLocales.includes(z))G=`/${X.join("/")}`,Q=z,V=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&B===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),k=U&&F.supportedLocales.includes(_.slice(1));if(_&&!k)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(U&&!Y&&V===null&&!(V===null&&B!==null)){let _=cW(z,F.supportedLocales,F.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(c).detectLocale(new A($,{},"view",G));if(V===null&&_!==F.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 O=[],L=[],M=null,T={},P=null,K=!1,R=!1,C=[],S,w=!1,x=!1;try{let _=n3(this.flatViewRoutes,G);if(V&&_?.route.middleware.includes(LB))_=null;if(_){if(w=!0,M=_.routePath,T=_.params,O=_.route.exec,L=_.route.middleware,C=_.route.features,K=L.includes("no-stream"),R=L.includes(kM),S=_.route.static,x=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let k=$.headers.get(LW),H0=xQ({flatViewRoutes:this.flatViewRoutes,supportedLocales:H(c).supportedLocales,from:k,origin:J.origin,to:{segments:_.route.segments,params:T,search:J.search}});if(H0.startIndex>0)O=O.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 rZ(o3($));let BZ=new Set;k.serverQueries.onQueryFail((g)=>{BZ.add(g.error);try{j3(()=>Promise.resolve(this.hooks.onRequestFail(d,g.error)).catch(()=>{}))}catch{}});let x$=gW(x?{}:S??(M===null&&!W?this.notFound?.static:void 0));if(V){let g=V.replaceAll("/","");_$.setLocale(g,{cookie:x$.locale})}else if(F.isLocaleAware&&!U)k.setLocale(F.defaultLocale);else _$.setLocale(void 0,{cookie:x$.locale});let d=k.req;if(x$.session)J8();try{let g=null;if(this.detectLocale&&!U&&H(c).isLocaleAware){let{supportedLocales:E,defaultLocale:r}=H(c),o1=await this.detectLocale(d,{supportedLocales:E,defaultLocale:r}),J6=typeof o1==="string"?cW(o1,E,r):null;if(J6)k.setLocale(J6)}try{await H(r1).runMiddleware(L)}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E}if(g!==null||C.length>0&&!await this.passesFeatureGates(C))M=null,O=[],d.routePath="";let F0=H(c),V1=F0.isEnabled,C$=F0.isLocaleAware,z3=new A($,d.params),u0={defaultLocale:F0.defaultLocale,timeZone:F0.detectTimeZone(z3)};if(C$){let E=null;if(V)E=V.replaceAll("/",""),k.setLocale(E);else if(!U)E=k.locale??F0.defaultLocale;else E=F0.detectLocale(z3),k.setLocale(E);let r=V1?F0.getPageTranslations(E,d.routePath):{};u0={...u0,supportedLocales:F0.supportedLocales,currentLocale:E,dictionary:{[E]:r},defaultLocale:F0.defaultLocale,...U?{}:{localeRouting:"off"}}}await uW(u0.currentLocale??"");let A$;try{A$=await Promise.all(O.map((E)=>E(d)))}catch(E){if(g=this.viewRefusalStatus(d,E,BZ),g===null)throw E;M=null,O=[],d.routePath="",A$=[]}let S1=void 0;if(M===null){if(S1=await this.hooks.onNotFound(d,{status:g??404}),C$&&!U&&k.locale&&k.locale!==u0.currentLocale){let E=k.locale;u0={...u0,currentLocale:E,dictionary:{[E]:V1?F0.getPageTranslations(E,d.routePath):{}}},await uW(E)}}if(this.defaultMeta&&!k.metadata.hasAllDefaultFields)k.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(d):this.defaultMeta);if(this.translate!==void 0)k.metadata.applyTranslateDefault(this.translate);let{cookies:E1,headers:l}=k;if(g!==null)l.set("Cache-Control","no-store");_={data:A$,cookies:E1,headers:l,user:k.user,prefetchedData:k.serverQueries.snapshotResolved(),currentPathName:M,params:d.params,urlLocaleSegment:Q,meta:k.renderMeta(),appId:H(HW).id,features:await H(W$).forClient()};let{params:N8,user:K8}=_,r0={},VZ={};for(let E of A$??[]){let[r,o1]=Object.entries(E)?.[0]??[];if(!r||!o1)continue;VZ[`${r}:${M}`]=o1.breadcrumb,r0[r]=o1}let S$=M===null&&this.notFound&&!W?this.notFound.static:void 0;if(S$&&S1)r0["404"]=S1;let n1=r0.FILE;if(n1){try{await this.onRequestEnd(d,{mintSession:!1})}catch(r){XZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let E;if(n1 instanceof Response)E=Y8(n1,l,E1);else{for(let r of E1)l.append("Set-Cookie",r.toString());E=await f8(n1,l)}return VB(E,M)}if(W){l.set("Content-Type","application/x-ndjson; charset=utf-8"),l.append("Vary",LW),E1.forEach((r)=>l.append("Set-Cookie",r.toString())),yW(l,M),await this.hooks.onRequestEnd(d);let E={meta:P&&!k.metadata.touched?null:_.meta,data:{[G]:r0},breadcrumbs:VZ,prefetchedData:k.serverQueries.snapshotResolved(),i18n:u0,features:_.features,is404:!M,appId:_.appId,partial:P};return new Response(wQ(E,k.serverQueries,void 0,({aborted:r})=>j3(()=>this.completeStream(d,k.serverQueries.summarize(r)))),{headers:l})}l.set("Content-Type","text/html; charset=utf-8");let E$=M?S:S$,y=Boolean(E$),F1=gW(E$);if(!K&&!y)l.append("Vary","User-Agent");if(!y||F1.session)J8();for(let E of E1)l.append("Set-Cookie",E.toString());if(!y||F1.csrf){let E=Bun.CSRF.generate(process.env.SECRET);l.append("Set-Cookie",`csrf_token=${E}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(d,{mintSession:!y||F1.session})}catch(E){XZ.error(E?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(E)})}if(y&&(M||!w))GB(l,E$);yW(l,M);let Z6=y?void 0:HB($);if(!y)mW(l,this.csp,{nonce:Z6});if(dW($))BB(l,M,y);return await this.render({req:d,runInRequestScope:j3,csrfTokenHMAC:Buffer.from(""),currentPathName:M,headers:l,i18n:u0,params:N8,pathname:J.pathname,serverQueries:k.serverQueries,userAgent:$.headers.get("user-agent"),noStream:K,noTheme:R,url:J,user:K8,viewData:r0,breadcrumbs:VZ,urlLocaleSegment:Q,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:E$,refusedStatus:g??void 0,cspNonce:Z6})}catch(g){if(g.kind===e1){let F0=W?gM(g.payload.viewData??g.payload.api):pW(g.payload.view);for(let V1 of k.cookies)F0.headers.append("Set-Cookie",V1.toString());return F0}if(!BZ.has(g))this.hooks.onRequestFail(d,g);if($$(g))return console.error(g),W?eZ():pW(TW());if(g instanceof t0&&g.status===403)return W?eZ():pW(TW());throw g}},Z)}}function MB($,Z){return Z?$.map((J)=>bM(J,{nonce:Z})):$}function yM($,Z){let J=$.cookies?.get(Z);return KQ(J)?J:null}function sW(){let $=JSON.stringify({error:Z$("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 KB 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(r3).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 mM=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),hM=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,pM=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function dM($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(mM.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===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!hM.test(Y)||!pM.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 TB($){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 Y8($,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 uM(){return Bun.env.NODE_ENV==="development"}class j8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=aG();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=r5({"/":$.rootRouter,"/auth":i5,"/__gemi__/services/i18n":s5,"/__gemi__/services/image":a5,...uM()?{"/__gemi__/services/logs":t5,"/__gemi__/debug":KB}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=NB(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;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(r1).runMiddleware(W)}catch(Y){if(Y.kind===e1)return TB(Y.payload.api);else{if(k$(Y))return sW();if(this.onRequestFail(Z,Y),console.error(Y),$$(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===e1)return TB(j.payload.api);if(k$(j))return sW();if(this.onRequestFail(J.req,j),console.error(j),$$(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||!Y[$.method])return new Response(JSON.stringify({error:Z$("not_found","Not found",404)}),{status:404});let j=new A($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await N.run(j,async()=>{let z=N.getStore(),X=!1,G=async()=>{X=!0,await this.endRequest(z,j,W)};try{let Q=H(c);if(Q.isEnabled){let O=Q.detectLocale(j);z.setLocale(O)}z.setRequest(j),H(r1).applyDefaultBodyLimit($,Y[$.method].bodyLimitDefault);let V=await this.runRouteMiddleware(W,j);if(V instanceof Response){let O=Y8(V,z.headers,z.cookies);return await G(),O}let F=await this.getRouteData(W),B=z.headers,U=z.cookies;if(F instanceof Response){let O=Y8(F,B,U);if(this.isOpenEndedBody($,O)){let L=cM(O,()=>this.endRequest(z,j,W));return X=!0,L}return await G(),O}let D=(a1(F)?F:U1.json(F)).toResponse(B,U);return await G(),D}catch(Q){if(!X)try{await G()}catch(V){console.error(V)}throw Q}},Z)}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,V=[],F=G?null:$.cookies.get(t1);if(F)V.push(`${t1}=${F}`);if(Y?.credentials)dM(Q,V,Y.credentials,G!==void 0);if(V.length>0)Q.set("Cookie",V.join("; "));let B=G?null:$.headers.get(t1);if(B)Q.set(t1,B);let U=$.headers.get("User-Agent");if(U)Q.set("User-Agent",U);let D;if(W instanceof FormData)D=W;else if(W!==void 0)Q.set("Content-Type","application/json"),D=JSON.stringify(W);let O=new Request(z,{method:Z,headers:Q,body:D,...Y?.signal?{signal:Y.signal}:{}});if(PB(O,DZ($),G?.grant,Y?.progress),$.domain)Z3(O,$.domain);let L=G?{user:G.user}:void 0;return N.exit(()=>B6.exit(()=>this.handleApiRequest(O,L)))}}import{timingSafeEqual as lM}from"crypto";var G8="",aW="*",iM=60000,sM=1e4,z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,X8=16,nW=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,oW="x-forwarded-host";function IB($){return $.startsWith(":")}function e3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&lM(J,W)}function nM($){if(!$)return[];if($===!0)return[{header:oW,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:oW;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 oM($){if(!$||$===!0)return;if(!Array.isArray($)){_B($,"route.domains.trustProxy",oW);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.`);_B(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 _B($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!nW.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"||!nW.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"||!nW.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 x1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function aM($){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 xB($){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 tM($){let Z=x1($.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.`);oM($.trustProxy),xB($.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),IB(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 tW{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){tM($),this.root=x1($.root),this.devHosts=xB($.devHosts),this.hostTrusts=nM($.trustProxy);for(let Z of $.groups??[])if(IB(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??iM,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||e3($.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:f$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return x1(this.forwardedHost($))??x1(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&&x1(Y)?aM(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:aW,params:{},custom:!0};return null}async allows($,Z){let J=x1($);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>=sM)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=x1($);if(Z)this.cache.delete(Z)}}}var rM={kind:"none"};function tA($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return rM;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 rA($,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:f$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var CB=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,AB=16;function eA($){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(!CB.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!CB.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<AB)throw Error(`GEMI_PROXY_SECRET must be at least ${AB} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function SB($,Z){if(!e3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:f$(J)}var eM="/__gemi__/domains/ask";class B1{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 tW(J);let W=(Y)=>({api:Y.api?new j8({...Z.api,...Y.api}):$.api,view:Y.view?new r3({...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(aW,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)rW($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?SB($.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)rW($,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!==eM)return null;if(!e3(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 EB=600000;function bB($,Z){return[P6($,Z),P6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new F7){i9($.oauthProviders),this.config={..._1(s9($),$),emailCode:z7($.emailCode),passwordLimits:j7($.passwordLimits)},this.provider=Z}async oauthProvider($){return await PZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await QY(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(B1)?H(B1).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(B1).resolver?.root:x1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??x1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!t8($))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/EB),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),V=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:V,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=Q}if(!z){for(let Q of bB($,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(t8($)||!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()/EB),W=bB($,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 w$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=b9(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:v9(Z),G=N6("link",$,j),Q=N6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let V=Math.max(W,Y)*60000,B=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((U)=>W3(U.createdAt)+V>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 m9(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 b}static async user(){let $=await f0.userOrNull();if($)return $;throw new w$({redirectTo:F6(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 O1(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(o3(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(o3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function $H($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function eW($,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==="*"?$H(z):encodeURIComponent(String(z))}`});return`${B8}${J==="/"?"":J}`||B8}var RB=new Map;function kB($,Z){let J=RB.get($);if(!J)J=new URLPattern({pathname:`${B8}${$==="/"?"":$}`}),RB.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function wB($,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=ZH(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 ZH($){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 fB{static origin($){return $2($)}static absolute($,...Z){return`${WZ()}${O0(String($),Z[0]??{})}`}static relative($,...Z){return O0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=H(B1).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 wB({root:W.root,origin:j},$,O0(String(Z),J[0]??{}))}static api($,...Z){return eW(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${$2()}${eW(String($),Z[0]??{})}`}static matchApi($,Z){return kB(String($),Z)}}class qB{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 JH={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 s1 extends h{static getFacadeAccessor(){return GZ}static get client(){return this.getFacadeRoot().client}static get($){return s1.client.get($)}static set($,Z){return s1.client.set($,Z)}static del(...$){return s1.client.del(...$)}static exists($){return s1.client.exists($)}static incr($){return s1.client.incr($)}static expire($,Z){return s1.client.expire($,Z)}static ttl($){return s1.client.ttl($)}}function aS($){return $}function vB(){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 WH="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=`${YH(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",WH]),[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 YH($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var jH="k:",gB="tag:",zH="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=_1(vB(),$),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 mB(this,Z)}async flush(){await this.store.flush()}async storeKey($){return jH+hB($)}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=gB+Z,W=await this.store.get(J);if(W!==null)return W;let Y=yB();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(gB+Z,yB(),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 mB extends W2{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){hB($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${zH}${Z.join(",")}:${$}`}}function hB($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function yB(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class pB 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 dB 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 uB extends h{static getFacadeAccessor(){return cB}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class iB extends h{static getFacadeAccessor(){return lB}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class sB 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()}}function IE($){return $}function nB(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function V8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function j2($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:XH}=globalThis.Bun;function GH(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var QH=async($)=>{let Z=new XH($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},BH=async($)=>{let Z;try{Z=(await import("./chunk-12gthjxx.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},oB=($)=>GH()?QH($):BH($);var VH=/^[A-Za-z_][A-Za-z0-9_]*$/;class z2{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!VH.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??oB}async createTable(){for(let $ of FH(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return aB(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
24
24
  INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
25
25
  ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
26
26
  RETURNING seq
@@ -37,7 +37,7 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
37
37
  WHERE channel = ${$} AND seq > ${Z}
38
38
  ORDER BY seq
39
39
  LIMIT ${J}
40
- `;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=s0();if($===void 0||f1()!==this.connection)return;return $}}function QH($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
40
+ `;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=s0();if($===void 0||f1()!==this.connection)return;return $}}function FH($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
41
41
  "channel" TEXT NOT NULL PRIMARY KEY,
42
42
  "seq" BIGINT NOT NULL
43
43
  )`,`CREATE TABLE IF NOT EXISTS "${Z}" (
@@ -46,35 +46,35 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
46
46
  "data" TEXT NOT NULL,
47
47
  "created_at" BIGINT NOT NULL,
48
48
  PRIMARY KEY ("channel", "seq")
49
- )`]}class z2{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var rB=new TextEncoder;function nB($,Z){return rB.encode(`id: ${$}
49
+ )`]}class X2{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var ZV=new TextEncoder;function tB($,Z){return ZV.encode(`id: ${$}
50
50
  data: ${JSON.stringify(Z)}
51
51
 
52
- `)}function eB($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(B){if(!(B instanceof F8))throw B;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,G=!1,Q=!1,V=(B)=>{if(X)clearInterval(X);if(X=null,z.close(),Q)return;Q=!0;try{B.close()}catch{}},F=new ReadableStream({start(B){X=setInterval(()=>{if(tB())return V(B);try{B.enqueue(rB.encode(oB))}catch{V(B)}},$.config.keepaliveInterval)},async pull(B){try{if(!G){if(await z.ready(),G=!0,!Q)B.enqueue(nB(z.cursor,{type:"ready"}));return}let U=await z.next();if(U.done||Q)return V(B);B.enqueue(nB(z.cursor,U.value))}catch(U){if(!Q)console.error("[gemi] A change feed stream failed.",U);V(B)}},cancel(){if(Q=!0,X)clearInterval(X);X=null,z.close()}});return new Response(F,{headers:aB()})}var $V=255,ZV=500,BH=30000;class F8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Y3{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=ZV;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=_1(lB(),$),this.driver=FH(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){G2($);let J=Z===void 0?null:Z;if(s0()!==void 0&&!this.driver.joinsTransaction?.())return iZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return iZ(()=>this.wake($,W)),W}async head($){return G2($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=X2($);return V8(await this.driver.heads(Z))}subscribe($,Z={}){let J=X2($);if(this.all.size>=this.config.maxSubscriptions)throw new F8(this.config.maxSubscriptions);let W=new JV(this,J,VH(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return eB(this,$,X2(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=ZV,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,BH)}}}class JV{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return V8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function G2($){if(typeof $!=="string"||$===""||$.length>$V)throw Error(`A change feed channel is a string of 1 to ${$V} characters; got ${JSON.stringify($)}.`)}function X2($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)G2(J);return Z}function VH($){if($===void 0||$===null)return new Map;if(typeof $==="string")return Y2($);let Z=$ instanceof Map?[...$]:Object.entries($);return Y2(V8(new Map(Z)))}function FH($,Z){if($==="memory")return new z2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new j2(Z.make(q1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class WV extends h{static getFacadeAccessor(){return Y3}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 d0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(d0)?$.make(d0):void 0;if(Z instanceof $6)return Z;let J=new $6($,Z);return $.instance(d0,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(d0,this.previous);return}this.application.forget(d0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${Q2($,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 ${Q2($,Z,J)} not to have been broadcast, but it was broadcast ${B2(W.length)}: ${V2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${Q2($,J,W)} to have been broadcast ${B2(Z)}, but it was broadcast ${B2(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"}: ${V2(this.sent)}.`)}matching($,Z,J){return FZ($),this.sent.filter((W)=>(W.pattern===$||g2($,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: ${V2(this.sent)}.`}}function Q2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function B2($){return`${$} ${$===1?"time":"times"}`}function V2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${UH(Z.data)})`).join(", ")}function UH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class YV extends h{static getFacadeAccessor(){return d0}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 rE($){return $}function jV(){return{store:"memory",sweepLimit:500}}var F2=["completed","failed","cancelled","timed_out"],C1=["pending","running"];function A1($){return F2.includes($)}class U2{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,O2($.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(A1(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(C1.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 O2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class M2{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 OH(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`
52
+ `)}function JV($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(B){if(!(B instanceof F8))throw B;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,G=!1,Q=!1,V=(B)=>{if(X)clearInterval(X);if(X=null,z.close(),Q)return;Q=!0;try{B.close()}catch{}},F=new ReadableStream({start(B){X=setInterval(()=>{if($V())return V(B);try{B.enqueue(ZV.encode(rB))}catch{V(B)}},$.config.keepaliveInterval)},async pull(B){try{if(!G){if(await z.ready(),G=!0,!Q)B.enqueue(tB(z.cursor,{type:"ready"}));return}let U=await z.next();if(U.done||Q)return V(B);B.enqueue(tB(z.cursor,U.value))}catch(U){if(!Q)console.error("[gemi] A change feed stream failed.",U);V(B)}},cancel(){if(Q=!0,X)clearInterval(X);X=null,z.close()}});return new Response(F,{headers:eB()})}var WV=255,YV=500,UH=30000;class F8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class Y3{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=YV;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=_1(nB(),$),this.driver=DH(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){Q2($);let J=Z===void 0?null:Z;if(s0()!==void 0&&!this.driver.joinsTransaction?.())return iZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return iZ(()=>this.wake($,W)),W}async head($){return Q2($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=G2($);return V8(await this.driver.heads(Z))}subscribe($,Z={}){let J=G2($);if(this.all.size>=this.config.maxSubscriptions)throw new F8(this.config.maxSubscriptions);let W=new jV(this,J,OH(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return JV(this,$,G2(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=YV,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,UH)}}}class jV{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return V8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function Q2($){if(typeof $!=="string"||$===""||$.length>WV)throw Error(`A change feed channel is a string of 1 to ${WV} characters; got ${JSON.stringify($)}.`)}function G2($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)Q2(J);return Z}function OH($){if($===void 0||$===null)return new Map;if(typeof $==="string")return j2($);let Z=$ instanceof Map?[...$]:Object.entries($);return j2(V8(new Map(Z)))}function DH($,Z){if($==="memory")return new X2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new z2(Z.make(q1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class zV extends h{static getFacadeAccessor(){return Y3}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 d0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(d0)?$.make(d0):void 0;if(Z instanceof $6)return Z;let J=new $6($,Z);return $.instance(d0,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(d0,this.previous);return}this.application.forget(d0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${B2($,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 ${B2($,Z,J)} not to have been broadcast, but it was broadcast ${V2(W.length)}: ${F2(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${B2($,J,W)} to have been broadcast ${V2(Z)}, but it was broadcast ${V2(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"}: ${F2(this.sent)}.`)}matching($,Z,J){return FZ($),this.sent.filter((W)=>(W.pattern===$||y2($,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: ${F2(this.sent)}.`}}function B2($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function V2($){return`${$} ${$===1?"time":"times"}`}function F2($){return $.map((Z)=>`${Z.topic} ${Z.event}(${LH(Z.data)})`).join(", ")}function LH($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class XV extends h{static getFacadeAccessor(){return d0}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 Wb($){return $}function GV(){return{store:"memory",sweepLimit:500}}var U2=["completed","failed","cancelled","timed_out"],C1=["pending","running"];function A1($){return U2.includes($)}class O2{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,D2($.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(A1(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(C1.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 D2($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class H2{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 MH(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`
53
53
  INSERT INTO ${this.name(Z)}
54
54
  (id, kind, subject, owner, status, meta, version,
55
55
  created_at, started_at, updated_at, deadline_at)
56
56
  VALUES
57
57
  (${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
58
58
  ${O8($.meta)}, 1, ${J}, ${Y}, ${J}, ${W})
59
- `;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]?L2(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 (${U8(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
59
+ `;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]?M2(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 (${U8(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
60
60
  SELECT * FROM ${this.name(Z)}
61
61
  WHERE ${W}
62
62
  ORDER BY created_at DESC, id DESC
63
- LIMIT ${O2($.limit)}
64
- `).map(L2)}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(A1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${O8(J.progress)}`);if("result"in J)j.push(W`result = ${O8(J.result)}`);if("error"in J)j.push(W`error = ${O8(J.error)}`);let z=j.reduce((G,Q)=>W`${G}, ${Q}`),X=await W`
63
+ LIMIT ${D2($.limit)}
64
+ `).map(M2)}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(A1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${O8(J.progress)}`);if("result"in J)j.push(W`result = ${O8(J.result)}`);if("error"in J)j.push(W`error = ${O8(J.error)}`);let z=j.reduce((G,Q)=>W`${G}, ${Q}`),X=await W`
65
65
  UPDATE ${this.name(W)} SET ${z}
66
66
  WHERE id = ${$} AND status IN (${U8(W,Z)})
67
- `;if(XV(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
67
+ `;if(BV(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
68
68
  SELECT * FROM ${this.name(J)}
69
69
  WHERE status IN (${U8(J,C1)})
70
70
  AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(J,$)}
71
71
  ORDER BY deadline_at, id
72
72
  LIMIT ${Math.max(0,Math.floor(Z))}
73
- `).map(L2)}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`
73
+ `).map(M2)}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`
74
74
  DELETE FROM ${this.name(Z)}
75
- WHERE status IN (${U8(Z,F2)})
75
+ WHERE status IN (${U8(Z,U2)})
76
76
  AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
77
- `;return XV(J)}joinable(){if(this.connection===void 0)return;let $=s0();if($===void 0||f1()!==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 U8($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function O8($){return $===void 0||$===null?null:JSON.stringify($)}function D8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function D2($){return $===null||$===void 0?null:Number($)}function zV($){return $===null||$===void 0?null:String($)}function L2($){return{id:String($.id),kind:String($.kind),subject:zV($.subject),owner:zV($.owner),status:String($.status),meta:D8($.meta),progress:D8($.progress),result:D8($.result),error:D8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:D2($.started_at),updatedAt:Number($.updated_at),finishedAt:D2($.finished_at),deadlineAt:D2($.deadline_at)}}function XV($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function OH($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
77
+ `;return BV(J)}joinable(){if(this.connection===void 0)return;let $=s0();if($===void 0||f1()!==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 U8($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function O8($){return $===void 0||$===null?null:JSON.stringify($)}function D8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function L2($){return $===null||$===void 0?null:Number($)}function QV($){return $===null||$===void 0?null:String($)}function M2($){return{id:String($.id),kind:String($.kind),subject:QV($.subject),owner:QV($.owner),status:String($.status),meta:D8($.meta),progress:D8($.progress),result:D8($.result),error:D8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:L2($.started_at),updatedAt:Number($.updated_at),finishedAt:L2($.finished_at),deadlineAt:L2($.deadline_at)}}function BV($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function MH($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
78
78
  \`id\` VARCHAR(191) NOT NULL,
79
79
  \`kind\` VARCHAR(191) NOT NULL,
80
80
  \`subject\` VARCHAR(191) NULL,
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
112
112
  "updated_at" BIGINT NOT NULL,
113
113
  "finished_at" BIGINT,
114
114
  "deadline_at" BIGINT${W}
115
- )`,`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 GV=191,QV=30000;class L8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class M8 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 H2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=_1(jV(),$),this.store=MH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(Y3);return this.ownFeed??=new Y3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){FV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;FV("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 LH(Z),this.change($,C1,{status:"running",progress:Z})}complete($,Z){return this.change($,C1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,C1,{status:"failed",error:VV(Z)})}cancel($,Z){return this.change($,C1,{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 L8($);if(A1(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 M8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,C1,{status:"failed",error:G instanceof M8?VV(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 L8($);let z=null;for(;;){if(A1(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 BV(z,Math.min(G,X??1/0,QV),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 L8($);if(yield W,A1(W.status))return;for await(let Y of J){let j=DH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,A1(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||A1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,C1,{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(A1(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,BV(j,Math.min(z??1/0,QV))]);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 BV($,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 DH($,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 VV($){if(typeof $==="string")return{message:$};if($ instanceof M8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function FV($,Z){if(typeof Z!=="string"||Z===""||Z.length>GV)throw TypeError(`A run's ${$} is a string of 1 to ${GV} characters; got ${JSON.stringify(Z)}.`)}function LH($){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 MH($,Z){if($==="memory")return new U2;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(q1).connection();return new M2(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 UV extends h{static getFacadeAccessor(){return H2}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 OV extends h{static getFacadeAccessor(){return W$}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 K2{value;constructor($){this.value=$}}var HH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function KH($){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"||!HH.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 T8{bound;constructor($){this.bound=$}get name(){return this.bound??f1()}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 K8(J.sql,(W)=>H8(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=KH(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(s0()!==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 K8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await MV();let G=await H8(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof K2)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-9d8tz60r.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 HV($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=TV($,KV(J.dialect),Z),j=this.handle();if(j===void 0&&LV()){let z=this.name;return K8(J.sql,(X)=>H8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}return(j??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return f1()===this.name?$:void 0}connection($=this.name){return DV($),H(q1).connection($)}}var I$=new T8;class PV extends h{static getFacadeAccessor(){return q1}static connection($){return new T8($)}static get sql(){return I$.sql}static get dialect(){return I$.dialect}static query($){return I$.query($)}static execute($){return I$.execute($)}static transaction($){return I$.transaction($)}static withSettings($,Z){return I$.withSettings($,Z)}static readOnly($,Z){return I$.readOnly($,Z)}static schema(){return I$.schema()}static close(){return this.getFacadeRoot().close()}}export{U1 as Ne,SV as Oe,e0 as Pe,X3 as Qe,C8 as Re,x0 as Se,z6 as Te,a8 as Ue,t8 as Ve,E9 as We,J$ as Xe,D1 as Ye,f$ as Ze,Z0 as _e,X9 as $e,DZ as af,b9 as bf,R9 as cf,e8 as df,$7 as ef,P6 as ff,KZ as gf,d9 as hf,cF as if,c9 as jf,uF as kf,pP as lf,i9 as mf,$Y as nf,G7 as of,ZY as pf,JY as qf,rF as rf,WY as sf,Q7 as tf,ZU as uf,JU as vf,B7 as wf,YY as xf,jY as yf,W$ as zf,zY as Af,zU as Bf,F7 as Cf,g8 as Df,U6 as Ef,b1 as Ff,f8 as Gf,R1 as Hf,_$ as If,Q8 as Jf,RB as Kf,kB as Lf,eM as Mf,s1 as Nf,lS as Of,wB as Pf,$2 as Qf,Z2 as Rf,W2 as Sf,vB as Tf,yB as Uf,mB as Vf,pB as Wf,cB as Xf,uB as Yf,KE as Zf,lB as _f,V8 as $f,Y2 as ag,j2 as bg,z2 as cg,F8 as dg,Y3 as eg,JV as fg,WV as gg,i as hg,G3 as ig,y4 as jg,CN as kg,AN as lg,SN as mg,kN as ng,UG as og,y5 as pg,LG as qg,gN as rg,KG as sg,d0 as tg,d3 as ug,TG as vg,YV as wg,rE as xg,F2 as yg,C1 as zg,A1 as Ag,U2 as Bg,M2 as Cg,OH as Dg,L8 as Eg,M8 as Fg,H2 as Gg,UV as Hg,OV as Ig,T8 as Jg,PV as Kg,h5 as Lg,WL as Mg,n5 as Ng,o5 as Og,a_ as Pg,cG as Qg,sG as Rg,G6 as Sg,r1 as Tg,VI as Ug,oG as Vg,aG as Wg,HW as Xg,eZ as Yg,KW as Zg,XC as _g,DC as $g,LC as ah,_M as bh,gW as ch,CM as dh,lW as eh,RM as fh,hW as gh,fM as hh,r3 as ih,iW as jh,LB as kh,Y8 as lh,j8 as mh,iA as nh,sA as oh,nA as ph,B1 as qh,b as rh,f0 as sh,Q6 as th,c2 as uh,hV as vh,h2 as wh,l2 as xh,R8 as yh,V6 as zh,k8 as Ah,i2 as Bh,sV as Ch,nV as Dh,r2 as Eh,$9 as Fh,J9 as Gh,Q9 as Hh,B9 as Ih,V9 as Jh,p8 as Kh,$F as Lh,j0 as Mh,N9 as Nh,MZ as Oh,A9 as Ph};
115
+ )`,`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 VV=191,FV=30000;class L8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class M8 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 T2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=_1(GV(),$),this.store=PH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(Y3);return this.ownFeed??=new Y3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){DV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;DV("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 TH(Z),this.change($,C1,{status:"running",progress:Z})}complete($,Z){return this.change($,C1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,C1,{status:"failed",error:OV(Z)})}cancel($,Z){return this.change($,C1,{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 L8($);if(A1(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 M8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,C1,{status:"failed",error:G instanceof M8?OV(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 L8($);let z=null;for(;;){if(A1(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 UV(z,Math.min(G,X??1/0,FV),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 L8($);if(yield W,A1(W.status))return;for await(let Y of J){let j=HH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,A1(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||A1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,C1,{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(A1(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,UV(j,Math.min(z??1/0,FV))]);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 UV($,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 HH($,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 OV($){if(typeof $==="string")return{message:$};if($ instanceof M8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function DV($,Z){if(typeof Z!=="string"||Z===""||Z.length>VV)throw TypeError(`A run's ${$} is a string of 1 to ${VV} characters; got ${JSON.stringify(Z)}.`)}function TH($){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 PH($,Z){if($==="memory")return new O2;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(q1).connection();return new H2(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 LV extends h{static getFacadeAccessor(){return T2}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 MV extends h{static getFacadeAccessor(){return W$}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 P2{value;constructor($){this.value=$}}var NH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function KH($){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"||!NH.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 P8{bound;constructor($){this.bound=$}get name(){return this.bound??f1()}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 T8(J.sql,(W)=>H8(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=KH(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(s0()!==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 T8(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);await PV();let G=await H8(j,()=>W(X));throw new P2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j,deferSettings:!0})}catch(X){if(X instanceof P2)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-9d8tz60r.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 NV($,Z)}run($,Z){let J=this.connection(),{text:W,values:Y}=_V($,KV(J.dialect),Z),j=this.handle();if(j===void 0&&TV()){let z=this.name;return T8(J.sql,(X)=>H8(z,()=>X.unsafe(W,Y)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:z})}return(j??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return f1()===this.name?$:void 0}connection($=this.name){return HV($),H(q1).connection($)}}var I$=new P8;class IV extends h{static getFacadeAccessor(){return q1}static connection($){return new P8($)}static get sql(){return I$.sql}static get dialect(){return I$.dialect}static query($){return I$.query($)}static execute($){return I$.execute($)}static transaction($){return I$.transaction($)}static withSettings($,Z){return I$.withSettings($,Z)}static readOnly($,Z){return I$.readOnly($,Z)}static schema(){return I$.schema()}static close(){return this.getFacadeRoot().close()}}export{U1 as Ne,RV as Oe,e0 as Pe,X3 as Qe,C8 as Re,x0 as Se,z6 as Te,a8 as Ue,t8 as Ve,b9 as We,J$ as Xe,D1 as Ye,f$ as Ze,Z0 as _e,G9 as $e,DZ as af,R9 as bf,k9 as cf,e8 as df,$7 as ef,N6 as ff,TZ as gf,c9 as hf,iF as if,u9 as jf,sF as kf,uN as lf,s9 as mf,ZY as nf,G7 as of,JY as pf,WY as qf,ZU as rf,YY as sf,Q7 as tf,YU as uf,jU as vf,B7 as wf,jY as xf,zY as yf,W$ as zf,XY as Af,QU as Bf,F7 as Cf,g8 as Df,U6 as Ef,b1 as Ff,f8 as Gf,R1 as Hf,_$ as If,Q8 as Jf,fB as Kf,qB as Lf,JH as Mf,s1 as Nf,aS as Of,vB as Pf,Z2 as Qf,J2 as Rf,Y2 as Sf,mB as Tf,pB as Uf,dB as Vf,uB as Wf,iB as Xf,sB as Yf,IE as Zf,nB as _f,V8 as $f,j2 as ag,z2 as bg,X2 as cg,F8 as dg,Y3 as eg,jV as fg,zV as gg,i as hg,G3 as ig,y4 as jg,EK as kg,bK as lg,RK as mg,qK as ng,OG as og,y5 as pg,MG as qg,hK as rg,PG as sg,d0 as tg,d3 as ug,NG as vg,XV as wg,Wb as xg,U2 as yg,C1 as zg,A1 as Ag,O2 as Bg,H2 as Cg,MH as Dg,L8 as Eg,M8 as Fg,T2 as Gg,LV as Hg,MV as Ig,P8 as Jg,IV as Kg,h5 as Lg,zL as Mg,n5 as Ng,o5 as Og,e_ as Pg,uG as Qg,nG as Rg,G6 as Sg,r1 as Tg,OI as Ug,aG as Vg,tG as Wg,HW as Xg,eZ as Yg,TW as Zg,FC as _g,PC as $g,NC as ah,CM as bh,yW as ch,EM as dh,iW as eh,fM as fh,pW as gh,gM as hh,r3 as ih,sW as jh,TB as kh,Y8 as lh,j8 as mh,tA as nh,rA as oh,eA as ph,B1 as qh,b as rh,f0 as sh,Q6 as th,u2 as uh,cV as vh,p2 as wh,i2 as xh,R8 as yh,V6 as zh,k8 as Ah,s2 as Bh,aV as Ch,tV as Dh,e2 as Eh,Z9 as Fh,W9 as Gh,B9 as Hh,V9 as Ih,F9 as Jh,p8 as Kh,WF as Lh,j0 as Mh,_9 as Nh,MZ as Oh,S9 as Ph};
116
116
 
117
- //# debugId=F13E01C18F11BC2B64756E2164756E21
117
+ //# debugId=5F9D45F2D8294F3864756E2164756E21