gemi 0.183.0 → 0.184.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 (61) hide show
  1. package/dist/auth/AuthController.d.ts.map +1 -1
  2. package/dist/auth/oauth/GitHubOAuthProvider.d.ts +60 -0
  3. package/dist/auth/oauth/GitHubOAuthProvider.d.ts.map +1 -0
  4. package/dist/auth/oauth/GoogleOAuthProvider.d.ts +18 -3
  5. package/dist/auth/oauth/GoogleOAuthProvider.d.ts.map +1 -1
  6. package/dist/auth/oauth/InstagramOAuthProvider.d.ts +12 -1
  7. package/dist/auth/oauth/InstagramOAuthProvider.d.ts.map +1 -1
  8. package/dist/auth/oauth/OAuthProvider.d.ts +23 -0
  9. package/dist/auth/oauth/OAuthProvider.d.ts.map +1 -1
  10. package/dist/auth/oauth/XOAuthProvider.d.ts +12 -1
  11. package/dist/auth/oauth/XOAuthProvider.d.ts.map +1 -1
  12. package/dist/auth/oauth/client.d.ts +69 -0
  13. package/dist/auth/oauth/client.d.ts.map +1 -0
  14. package/dist/auth/oauth/oauthState.d.ts +7 -1
  15. package/dist/auth/oauth/oauthState.d.ts.map +1 -1
  16. package/dist/auth/oauth/providers.d.ts +3 -2
  17. package/dist/auth/oauth/providers.d.ts.map +1 -1
  18. package/dist/{chunk-0hr6k996.js → chunk-eyehyb9v.js} +1 -1
  19. package/dist/{chunk-f54p1qc9.js → chunk-g06f1xf3.js} +2 -2
  20. package/dist/{chunk-f54p1qc9.js.map → chunk-g06f1xf3.js.map} +7 -7
  21. package/dist/{chunk-qzycygkz.js → chunk-neh2zrp0.js} +1 -1
  22. package/dist/{chunk-jmjq2cjx.js → chunk-nhyx0gec.js} +2 -2
  23. package/dist/{chunk-jmjq2cjx.js.map → chunk-nhyx0gec.js.map} +1 -1
  24. package/dist/{chunk-synh1gad.js → chunk-yantbc9e.js} +1 -1
  25. package/dist/chunks/{RealtimeClient-v3orUDdN.js → RealtimeClient-C7VTiRUv.js} +2 -2
  26. package/dist/chunks/{RealtimeClient-v3orUDdN.js.map → RealtimeClient-C7VTiRUv.js.map} +1 -1
  27. package/dist/chunks/{ThemeProvider-CDm5TXZC.js → ThemeProvider-Ddumzd7S.js} +12 -6
  28. package/dist/chunks/ThemeProvider-Ddumzd7S.js.map +1 -0
  29. package/dist/chunks/{fetchFileRequest-B6tFA-uV.js → fetchFileRequest-ClV8HU3g.js} +2 -2
  30. package/dist/chunks/{fetchFileRequest-B6tFA-uV.js.map → fetchFileRequest-ClV8HU3g.js.map} +1 -1
  31. package/dist/chunks/{live-JhGCkWuM.js → live-BAFgp_WN.js} +3 -3
  32. package/dist/chunks/{live-JhGCkWuM.js.map → live-BAFgp_WN.js.map} +1 -1
  33. package/dist/chunks/{mutationExtras-BnDYKenf.js → mutationExtras-ozY1Rd1R.js} +2 -2
  34. package/dist/chunks/{mutationExtras-BnDYKenf.js.map → mutationExtras-ozY1Rd1R.js.map} +1 -1
  35. package/dist/chunks/{subscriptionStream-BdxPsTI_.js → subscriptionStream-CTiRok5u.js} +2 -2
  36. package/dist/chunks/{subscriptionStream-BdxPsTI_.js.map → subscriptionStream-CTiRok5u.js.map} +1 -1
  37. package/dist/chunks/useParams-BN3XXfmG.js.map +1 -1
  38. package/dist/client/ClientRouterContext.d.ts.map +1 -1
  39. package/dist/client/RouteStateContext.d.ts +5 -0
  40. package/dist/client/RouteStateContext.d.ts.map +1 -1
  41. package/dist/client/index.js +4 -4
  42. package/dist/client/useRoute.d.ts +5 -0
  43. package/dist/client/useRoute.d.ts.map +1 -1
  44. package/dist/facades/index.js +1 -1
  45. package/dist/http/index.js +1 -1
  46. package/dist/i18n/index.js +1 -1
  47. package/dist/kernel/index.js +1 -1
  48. package/dist/server/index.js +1 -1
  49. package/dist/services/index.d.ts +3 -0
  50. package/dist/services/index.d.ts.map +1 -1
  51. package/dist/services/index.js +13 -13
  52. package/dist/services/index.js.map +8 -6
  53. package/dist/testing/Page.d.ts +4 -0
  54. package/dist/testing/Page.d.ts.map +1 -1
  55. package/dist/testing/index.js +6 -6
  56. package/dist/testing/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunks/ThemeProvider-CDm5TXZC.js.map +0 -1
  59. /package/dist/{chunk-0hr6k996.js.map → chunk-eyehyb9v.js.map} +0 -0
  60. /package/dist/{chunk-qzycygkz.js.map → chunk-neh2zrp0.js.map} +0 -0
  61. /package/dist/{chunk-synh1gad.js.map → chunk-yantbc9e.js.map} +0 -0
@@ -10,7 +10,7 @@ ${Z}</sitemapindex>
10
10
  `)));return Mj(Q,{url:j.url})}function l8($){return $===void 0?[]:typeof $==="string"?[$]:$}function H6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
11
11
  `}function Hj($){let Z=[];for(let W of $.rules??[]){let Y=l8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>H6("User-agent",X)).join(""),z=[...l8(W.allow).map((X)=>["Allow",X]),...l8(W.disallow).map((X)=>["Disallow",X])];for(let[X,Q]of z){if(!Q.startsWith("/")&&!Q.startsWith("*"))throw TypeError(`Robots: ${X} "${Q}" must start with "/" or "*".`);j+=H6(X,Q)}if(z.length===0)j+=`Disallow:
12
12
  `;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);j+=H6("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 H6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
13
- `)}function tB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(Hj($),{status:200,headers:J})}var Tj={response:tB,text:Hj,parse:Mj,fetch:rB};import{createHmac as Pj,randomBytes as eB}from"crypto";var s8="v2.";function n8($){return $.startsWith(s8)}function MZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function Nj($){let Z=eB(16).toString("hex"),J=Pj("sha256",MZ()).update(`${$}:${Z}`).digest("hex");return`${s8}${J}`}function T6($,Z){let J=Pj("sha256",MZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${s8}${J}`}import{createHash as JV,createHmac as WV,randomInt as YV,timingSafeEqual as xj}from"crypto";function _j($,Z){return Math.floor($/Z)*Z}function $V($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function o8($,Z,J,W){return Z*$V(J,W)+$}function ZV($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let B=Y*(1-(X-Z)/J);if(B<=Y)return Math.max(0,Math.ceil(B-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function Ij($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let B=o8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-B)),resetAt:Y-j+z,retryAfter:0}}let G=ZV({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class a8{}class r8 extends a8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=_j(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let B=o8(Q.current,Q.previous,X,W)+Y<=J;if(B)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return Ij({allowed:B,current:Q.current,previous:Q.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 Aj="h1.";function P6($,Z,J){let W=WV("sha256",MZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${Aj}${W}`}function HZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(Aj),X=P6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return xj(Q,Q),!1;return xj(Q,G)}function Sj($){let Z="";for(let J=0;J<$;J++)Z+=String(YV(0,10));return Z}var Ej=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>Ej)return null;return Z.toLowerCase()}function N6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>Ej)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var Cj=null;function bj(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(F1))return $.make(F1)}catch{}return Cj??=new F1({driver:new r8,limit:1000,window:60}),Cj}function t8($){return $.length<=64?$:`sha256:${JV("sha256").update($).digest("hex")}`}function jV($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function y$($,Z,J,W,Y,j){let z=bj(),X=[["perIp",`ip:${t8(DZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${t8(Z)}`,W.perEmail]);for(let[Q,G,B]of X){if(!B)continue;let V=Y?await Y({req:J,scope:$,limit:Q}):void 0,K=jV($),F=V?`${K}:p:${t8(String(V))}:${G}`:`${K}:${G}`,[D,U]=B,O=await z.consume(F,{limit:D,window:U});if(!O.allowed)throw await j?.(Q),new Y$(O)}}async function Rj($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await bj().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as $7}from"crypto";class e8 extends C{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"}}}async function R1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Z7($){return $===!0||typeof $==="function"}function J7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function F3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function zV($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function W7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return F3("length",Z,4,12),F3("expiresInMinutes",J,1),F3("linkExpiresInMinutes",W,1),F3("maxAttempts",Y,1),F3("activeCodes",j,1,5),{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)`)})}}async function XV($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function kj($){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 fj($){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 mT($){return $}function wj($={}){return zV($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:J7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:e8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:XV,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>$7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return $7(32).toString("hex")},generateMagicLinkToken:()=>$7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:W7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var QV=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),GV=new Set(["svg","math"]);function qj($){return $===32||$===9||$===10||$===12||$===13}function yj($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function vj(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,B=()=>{if(!J&&QV.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(GV.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},V=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",j=0;else if(K===47)$="endTagOpen";else if(yj(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(_6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(yj(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(qj(K)||K===47)$="inTag",z=K===47;else if(K===62)B();else Z+=String.fromCharCode(_6(K));return;case"inTag":if(K===62){B();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(j+=1,j===2)$="comment",j=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)j=j<2?j+1:2;else if(K===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(_6(K)===W.charCodeAt(Y))Y+=1;else Y=K===60?1:0;return}if(K===62)$="data",Z="";else if(qj(K)||K===47)$="inTag",Z="";else Y=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let F=0;F<K.length;F++){if(G())return F;V(K[F])}return K.length},write(K){for(let F=0;F<K.length;F++)V(K[F])},isSafe:G}}function r0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function KV($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${r0([$.path,$.variantKey,$.data])})</script>`}function BV($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${r0([$.id,$.locale,$.strings])})</script>`}function Y7($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(KV(D))}),W?.onUse((D)=>{j.push(BV(D))});let G=$.getReader(),B=vj(),V=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(j.length>0){let U=Y.encode(j.shift());B.write(U),V(D,U)}},F=(D,U)=>{if(j.length===0){B.write(U),V(D,U);return}let O=B.scanToInsertionPoint(U);if(O>0)V(D,U.subarray(0,O));if(B.isSafe())K(D);let L=U.subarray(O);if(L.length>0)B.write(L),V(D,L)};return new ReadableStream({async pull(D){let U;try{U=await G.read()}catch(P){throw Q(),P}let{done:O,value:L}=U;if(O){K(D),D.close(),Q();return}if(!z){if(z=!0,B.write(L),V(D,L),J.onShell?.(),B.isSafe())K(D);return}F(D,L)},cancel(D){return Q(),G.cancel(D)}})}var VV=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return VV.test($)}async function mj($,Z=()=>{}){let J=T.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 FV($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:gj(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function hj($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function FV($,Z){if(!$.context)return{};try{let J=T.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 pj($,Z){return`${$}:${Z}`}function j7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function cj($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function dj($,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=DV($,Z,J,W.buckets);return cj(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function UV($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function DV($,Z,J,W){let Y=pj(Z.salt??$,UV(J));if(!W)return j7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=j7(Y);return W.set(Y,z),z}class uj extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class z7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new uj(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=OV(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 OV($){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 LV{}class MV extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class X7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class lj 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 ij{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 j${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new z7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{T.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new lj(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=HV(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new X7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new ij(this,hj($))}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($),Q=dj($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}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 $=T.getStore();if($?.featureContext)return $.featureContext;let Z=await mj(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=T.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=T.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 HV($){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 sj($){if($===void 0)return!0;return await M(j$).enabled($)}function nj(){try{return T.getStore()?.req??null}catch{return null}}async function TZ($,Z,J=nj()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=kj($[Z]);if(!W||!await sj(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await R1(W.enabled,J))return null}return W.provider}async function oj($,Z=nj()){let J=[];for(let W of Object.keys($))if(await TZ($,W,Z))J.push(W);return J}function Q7($){if($&&typeof $==="object")delete $.password;return $}function TV(){return new Proxy({},{get:($,Z)=>rj(Z)})}var aj=new WeakMap;function tj($){if($&&typeof $==="object"){for(let Z of Object.values($))tj(Z);Object.freeze($)}return $}var PV={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},NV=tj({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:PV});class G7{models;constructor($=TV()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return NV}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??k1(),W=M(f1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await l0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||l0())return Y();let z=(aj.get(W)??Promise.resolve()).then(Y,Y);return aj.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return Q7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return Q7(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?Q7(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 CD}from"crypto";function y0($,Z,J,W,Y){return t0(Z,U2($,Z),J,W,Y)}function t0($,Z,J,W,Y,j){let z=U7(Z,J,W);if(Y&&Z!==z)throw RangeError(rz($,Z,J,W,j));return z}function U2($,Z){let J=$[Z];if(J===void 0)throw TypeError(dJ(Z));return J}function O0($){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 N7($){return h$({name:$},1)}function h$($,Z){return J1((J)=>({value:J,configurable:1,writable:!Z}),$)}function D2($){return J1((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 J1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function N3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function _V($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function _7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function I7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function O2($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function L2($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function M2($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function w($,...Z){return(...J)=>$(...Z,...J)}function ej($){return $[0].toUpperCase()+$.substring(1)}function _3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function z$($,Z){return Math.sign($-Z)}function U7($,Z,J){return Math.min(Math.max($,Z),J)}function q1($,Z){return[Math.floor($/Z),D3($,Z)]}function D3($,Z){return($%Z+Z)%Z}function G$($,Z){return[p6($,Z),x7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function x7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function H2($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=D1[X],B=l/G,[V,K]=G$(Q,B);W+=K*G,Y+=V}let[j,z]=G$(W,l);return[Y+j,z]}function c6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=D1[Y];W[J[Y]]=p6($,j),$=x7($,j)}return W}function T2($){return $===q?N4:[]}function P2($){return $===q?f3:[]}function N2($){return $===q?["year","day"]:[]}function _2($){if($!==void 0)return W0($)}function I2($){if($!==void 0)return W1($)}function C7($){if($!==void 0)return I3($)}function W1($){return A2(I3($))}function I3($){return C2(UF($))}function A7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function x2($,Z){if(Z==null)throw RangeError(dJ($));return Z}function v1($){if(!O0($))throw TypeError(az);return $}function d6($,Z,J=$){if(typeof Z!==$)throw TypeError(b3(J,Z));return Z}function C2($,Z="number"){if(!Number.isInteger($))throw RangeError(mV(Z,$));return $||0}function A2($,Z="number"){if($<=0)throw RangeError(hV(Z,$));return $}function S7($){if(typeof $=="symbol")throw TypeError(uV);return String($)}function k6($,Z){return O0($)?String($):W0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(dV($));return $}function S2($,Z="number"){if(typeof $=="bigint")throw TypeError(cV(Z));if($=Number($),!Number.isFinite($))throw RangeError(pV(Z,$));return $}function A0($,Z){return Math.trunc(S2($,Z))||0}function E2($,Z){return C2(S2($,Z),Z)}function $2($,Z){return A2(A0($,Z),Z)}function E7($,Z){let[J,W]=G$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function NZ($,Z,J=1){return E7($[0]+Z[0]*J,$[1]+Z[1]*J)}function _Z($,Z){return E7($[0],$[1]+Z)}function i0($,Z){return NZ(Z,$,-1)}function E0($,Z){return z$($[0],Z[0])||z$($[1],Z[1])}function b2($,Z,J){return E0($,Z)===-1||E0($,J)===1}function l6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function IZ($,Z=1){let J=l/Z,[W,Y]=G$($,J);return[W,Y*Z]}function R2($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function s0($,Z=1,J){let[W,Y]=$,[j,z]=G$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function b7($,Z,J=q1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function R7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function k7($){return y0($,"isoYear",P3,T3,1),$.isoYear===P3?y0($,"isoMonth",4,12,1):$.isoYear===T3&&y0($,"isoMonth",1,9,1),$}function X$($){return g1({...$,...Z1,isoHour:12}),$}function g1($){let Z=y0($,"isoYear",P3,T3,1),J=Z===P3?1:Z===T3?-1:0;return J&&n0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function n0($){if(!$||b2($,PF,TF))throw RangeError(M4);return $}function K$($){return H2($,5,X1)[1]}function i6($){let[Z,J]=q1($,l);return[c6(J,5,X1),Z]}function k2($){return f2($)[0]}function f2($){return b7($,$1)}function b0($){return SZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=G$(Z,g0);return[J,W*O1+($.isoMicrosecond||0)*o$+($.isoNanosecond||0)]}}function f7($,Z){let[J,W]=i6(K$($)-Z);return n0(S0({...$,isoDay:$.isoDay+W,...J}))}function f6(...$){return SZ(...$)/QX}function SZ(...$){let[Z,J]=w2(...$),W=Z.valueOf();if(!isNaN(W))return W-J*g0}function w2($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===P3?1:$===T3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function V$($,Z){let[J,W]=_Z($,Z);W<0&&(W+=l,J-=1);let[Y,j]=q1(W,O1),[z,X]=q1(j,o$);return s6(J*g0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-HF)/g0)*Math.sign($),Y=new Date($-W*g0);return AZ(I4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function q2($){return[$.isoYear,$.isoMonth,$.isoDay]}function y2(){return w1}function w7($,Z){switch(Z){case 2:return q7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function v2($){return q7($)?366:365}function q7($){return $%4==0&&($%100!=0||$%400==0)}function g2($){let[Z,J]=w2($.isoYear,$.isoMonth,$.isoDay);return D3(Z.getUTCDay()-J,7)||7}function m2({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function IV($){let Z=b0($);if(Z<_F)return m2($);let J=R7(XW(xZ),Z),{era:W,eraYear:Y}=a9(J,xZ);return[W,Y]}function n6($){return p$($),o6($,1),$}function p$($){return h2($,1),$}function Z2($){return L2(eJ,$,h2($))}function h2($,Z){let{isoYear:J}=$,W=y0($,"isoMonth",1,y2(),Z);return{isoYear:J,isoMonth:W,isoDay:y0($,"isoDay",1,w7(J,W),Z)}}function o6($,Z){return AZ(X1,[y0($,"isoHour",0,23,Z),y0($,"isoMinute",0,59,Z),y0($,"isoSecond",0,59,Z),y0($,"isoMillisecond",0,999,Z),y0($,"isoMicrosecond",0,999,Z),y0($,"isoNanosecond",0,999,Z)])}function g($){return $===void 0?0:xX(v1($))}function x3($,Z=0){$=Y1($);let J=CX($),W=fF($,Z);return[xX($),W,J]}function y7($){return CX(Y1($))}function p2($){return $=Y1($),JW($,9,6,1)}function EZ($,Z,J,W=9,Y=0,j=4){Z=Y1(Z);let z=JW(Z,W,Y),X=m7(Z),Q=q3(Z,j),G=w3(Z,W,Y,1);return z==null?z=Math.max(J,G):l2(z,G),X=h7(X,G,1),$&&(Q=((B)=>B<4?(B+2)%4:B)(Q)),[z,G,X,Q]}function a6($,Z=6,J){let W=m7($=p7($,m6)),Y=q3($,7),j=w3($,Z);return j=x2(m6,j),W=h7(W,j,void 0,J),[j,W,Y]}function v7($){return WW(Y1($))}function c2($,Z){return g7(Y1($),Z)}function g7($,Z=4){let J=u2($);return[q3($,4),...d2(w3($,Z),J)]}function d2($,Z){return $!=null?[D1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function m7($){let Z=$[O3];return Z===void 0?1:A0(Z,O3)}function h7($,Z,J,W){let Y=W?l:D1[Z+1];if(Y){let j=D1[Z];if(Y%(($=t0(O3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(b3(O3,$))}else $=t0(O3,$,1,J?1e9:1,1);return $}function u2($){let Z=$[F7];if(Z!==void 0){if(typeof Z!="number"){if(S7(Z)==="auto")return;throw RangeError(b3(F7,Z))}Z=t0(F7,Math.floor(Z),0,9,1)}return Z}function Y1($){return $===void 0?{}:v1($)}function p7($,Z){return typeof $=="string"?{[Z]:$}:v1($)}function X0($){if($!==void 0){if(O0($))return Object.assign(Object.create(null),$);throw TypeError(az)}}function r6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:xF[Z]})}function c7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=S7(j),j==="auto")return Y?W:null;let z=M7[j];if(z===void 0&&(z=LF[j]),z===void 0)throw RangeError($X($,j,M7));return t0($,z,W,J,1,k3),z}function c$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=S7(Y),z=Z[j];if(z===void 0)throw RangeError($X($,j,Z));return z}function l2($,Z){if(Z>$)throw RangeError(GF)}function L0($){return{branding:C4,epochNanoseconds:$}}function N0($,Z,J){return{branding:c1,calendar:J,timeZone:Z,epochNanoseconds:$}}function Q0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0(PX,$)}}function G0($,Z=$.calendar){return{branding:a$,calendar:Z,...p0($W,$)}}function g$($,Z=$.calendar){return{branding:vZ,calendar:Z,...p0($W,$)}}function w6($,Z=$.calendar){return{branding:gZ,calendar:Z,...p0($W,$)}}function j1($){return{branding:x4,...p0(TX,$)}}function $0($){return{branding:A4,sign:F$($),...p0(aJ,$)}}function i2($){return k2($.epochNanoseconds)}function t6($){return b7($.epochNanoseconds,O1)[0]}function s2($){return R2($.epochNanoseconds,o$)}function n2($){return R2($.epochNanoseconds)}function o2($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:W0($.id)}function bZ($,Z){return $===Z||T0($)===T0(Z)}function a2($,Z,J,W,Y){let j=m$(W),[z,X]=((O,L)=>{let P=L((O=p7(O,P7))[_X]),H=kF(O);return H=x2(P7,H),[H,P]})(Y,$);if(M3(Math.max(z,j),X))return J2(W,z);if(!X)throw RangeError(H4);let[Q,G,B]=Y4(Z,J,X),V=VJ(B),K=j4(B),F=FJ(B),D=K(G,Q,W),U=F(G,Q,D,z);return M3(z,X)?J2(U,z):((O,L,P,H,I,b,S)=>{let R=F$(O),[f,N]=d7(H,tJ(P,O),P,R,I,b,S),v=u7(L,f,N);return O[h[P]]+v*R})(U,V(D),z,G,Q,V,K)}function J2($,Z){return s0(D0($),D1[Z],1)}function d7($,Z,J,W,Y,j,z){let X=h[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),B=z($,Y,Q);return[j(G),j(B)]}function u7($,Z,J){let W=s0(i0(Z,J));if(!W)throw RangeError(R3);return s0(i0(Z,$))/W}function r2($,Z){let[J,W,Y]=a6(Z,5,1);return L0($4($.epochNanoseconds,J,W,Y,1))}function t2($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=a6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((B,V,K,F)=>{let D=R0(K,V),[U,O]=B(D),L=K.epochNanoseconds,P=h0(V,U),H=h0(V,O);if(b2(L,P,H))throw RangeError(R3);return X9(u7(L,P,H),F)?H:P})(j9,G,Z,Q);else{let B=G.getOffsetNanosecondsFor(W);W=u$(G,W9(V$(W,B),z,X,Q),B,2,0,1)}return N0(W,Y,j)}function e2($,Z){return Q0(W9($,...a6(Z)),$.calendar)}function $9($,Z){let[J,W,Y]=a6(Z,5);var j;return j1((j=Y,l7($,C3(J,W),j)[0]))}function Z9($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=j9(W),z=s0(i0(h0(J,Y),h0(J,j)),P4,1);if(z<=0)throw RangeError(R3);return z}function J9($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(z9,$(J),Z);return N0(Y,J,W)}function W9($,Z,J,W){return Y9($,C3(Z,J),W)}function Y9($,Z,J){let[W,Y]=l7($,Z,J);return g1({...l$($,Y),...W})}function l7($,Z,J){return i6(B$(K$($),Z,J))}function q6($){return B$($,T4,7)}function C3($,Z){return D1[$]*Z}function j9($){let Z=z9($);return[Z,l$(Z,1)]}function z9($){return MF(6,$)}function xV($,Z,J){let W=Math.min(m$($),6);return kZ(Z4(D0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let B=M3(W,X)?z4(X)&&W<6&&J>=6?AV:CV:SV,[V,K,F]=B($,Z,J,W,Y,j,z,X,Q,G);return F&&W!==7&&(V=((D,U,O,L,P,H,I,b)=>{let S=F$(D);for(let R=L+1;R<=O;R++){if(R===7&&O!==7)continue;let f=tJ(R,D);f[h[R]]+=S;let N=s0(i0(I(b(P,H,f)),U));if(N&&Math.sign(N)!==S)break;D=f}return D})(V,K,J,Math.max(6,W),z,X,Q,G)),V}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[B$(j,J,W),0]}return Z4($,C3(Z,J),W,Y)}function Z4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=q1(B$(j,Z,J),l);return E7(Y+z,X)}function B$($,Z,J){return X9($/Z,J)*Z}function X9($,Z){return yF[Z]($)}function CV($,Z,J,W,Y,j){let z=F$($),X=D0($),Q=$4(X,W,Y,j),G=i0(X,Q),B=Math.sign(Q[0]-X[0])===z,V=kZ(Q,Math.min(J,6));return[{...$,...V},NZ(Z,G),B]}function AV($,Z,J,W,Y,j,z,X,Q,G){let B=F$($),V=s0(D0($,5)),K=C3(W,Y),F=B$(V,K,j),[D,U]=d7(z,{...$,...rJ},6,B,X,Q,G),O=F-s0(i0(D,U)),L=0;O&&Math.sign(O)!==B?Z=_Z(D,F):(L+=B,F=B$(O,K,j),Z=_Z(U,F));let P=Q4(F);return[{...$,...P,days:$.days+L},Z,Boolean(L)]}function SV($,Z,J,W,Y,j,z,X,Q,G){let B=F$($),V=h[W],K=tJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let F=p6($[V],Y)*Y;K[V]=F;let[D,U]=d7(z,K,W,Y*B,X,Q,G),O=F+u7(Z,D,U)*B*Y,L=B$(O,Y,j),P=Math.sign(L-O)===B;return K[V]=L,[K,P?U:D,P]}function i7($,Z,J,W){let[Y,j,z,X]=((G)=>{let B=g7(G=Y1(G));return[G.timeZone,...B]})(W),Q=Y!==void 0;return((G,B,V,K,F,D)=>{V=Z4(V,F,K,1);let U=B.getOffsetNanosecondsFor(V);return e7(V$(V,U),D)+(G?d$(q6(U)):"Z")})(Q,Z(Q?$(Y):t$),J.epochNanoseconds,j,z,X)}function s7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=Y1(G);let B=WW(G),V=u2(G),K=qF(G),F=q3(G,4),D=w3(G,4);return[B,wF(G),K,F,...d2(D,V)]})(J);return((G,B,V,K,F,D,U,O,L,P)=>{K=Z4(K,L,O,1);let H=G(V).getOffsetNanosecondsFor(K);return e7(V$(K,H),P)+d$(q6(H),U)+((I,b)=>b!==1?"["+(b===2?"!":"")+T0(I)+"]":"")(V,D)+$J(B,F)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function n7($,Z){let[J,W,Y,j]=((G)=>(G=Y1(G),[WW(G),...g7(G)]))(Z);return z=$.calendar,X=J,Q=j,e7(Y9($,Y,W),Q)+$J(z,X);var z,X,Q}function o7($,Z){return J=$.calendar,W=$,Y=v7(Z),y6(W)+$J(J,Y);var J,W,Y}function a7($,Z){return Q9($.calendar,G9,$,v7(Z))}function r7($,Z){return Q9($.calendar,EV,$,v7(Z))}function t7($,Z){let[J,W,Y]=c2(Z);return j=Y,K9(l7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=c2(Z,3);return W>1&&($={...$,...xV($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?k0(j):j,{hours:G,minutes:B}=Q,[V,K]=b7(D0(Q,3),$1,G$);M9(V);let F=ZJ(K,z),D=z>=0||!X||F;return(X<0?"-":"")+"P"+W2({Y:v$(Q.years),M:v$(Q.months),W:v$(Q.weeks),D:v$(Q.days)})+(G||B||V||D?"T"+W2({H:v$(G),M:v$(B),S:v$(V,D)+F}):"")})($,Y)}function Q9($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):y6(J):j?y6(J)+B9(Y,W===2):Z(J)}function W2($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function e7($,Z){return y6($)+"T"+K9($,Z)}function y6($){return G9($)+"-"+e0($.isoDay)}function G9($){let{isoYear:Z}=$;return(Z<0||Z>9999?V9(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+e0($.isoMonth)}function EV($){return e0($.isoMonth)+"-"+e0($.isoDay)}function K9($,Z){let J=[e0($.isoHour),e0($.isoMinute)];return Z!==-1&&J.push(e0($.isoSecond)+((W,Y,j,z)=>ZJ(W*O1+Y*o$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function d$($,Z=0){if(Z===1)return"";let[J,W]=q1(Math.abs($),P4),[Y,j]=q1(W,T4),[z,X]=q1(j,$1);return V9($)+e0(J)+":"+e0(Y)+(z||X?":"+e0(z)+ZJ(X):"")}function $J($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==q)return B9(J,Z===2)}return""}function B9($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function ZJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(mF,""):J.slice(0,Z),J?"."+J:""}function V9($){return $<0?"-":"+"}function v$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function bV($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=V$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function F9($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(PX,J),offset:d$(J.offsetNanoseconds),timeZone:Z.timeZone}}function u$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return f7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,B,V,K)=>{let F=S0(B);K&&(V=q6(V));for(let D of G){let U=s0(i0(D,F));if(K&&(U=q6(U)),U===V)return D}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(WF)}return z?S0(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(YF);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(_Z(Q,-l));return WJ(X.getOffsetNanosecondsFor(_Z(Q,l))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(V$(Y,z)))[J===2?0:W.length-1]}function JJ($){if(Math.abs($)>=l)throw RangeError(ZF);return $}function WJ($){if($>l)throw RangeError(JF);return $}function YJ($,Z,J){return L0(n0(NZ(Z.epochNanoseconds,((W)=>{if(H9(W))throw RangeError(XF);return D0(W,5)})($?k0(J):J))))}function jJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...KJ(z,X,W,J?k0(Y):Y,j)}}function zJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return Q0(BJ($(j),J,Z?k0(W):W,Y),j)}function XJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?k0(W):W,Y),j)}function QJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=L3(z,J);Z&&(W=X4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=l$(X,-1));let Q=z.dateAdd(X,W,Y);return g$(L3(z,Q),j)}function GJ($,Z,J){return j1(U9(Z,$?k0(J):J)[0])}function KJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(H9(W)){let X=R0(J,$);z=NZ(h0($,{...W4(Z,X,{...W,...rJ},Y),...p0(X1,X)}),j)}else z=NZ(z,j),g(Y);return{epochNanoseconds:n0(z)}}function BJ($,Z,J,W){let[Y,j]=U9(Z,J);return g1({...W4($,Z,{...J,...rJ,days:J.days+j},W),...Y})}function W4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);g(W);let Y=J.days+D0(J,5)[0];return Y?X$(l$(Z,Y)):Z}function L3($,Z,J=1){return l$(Z,J-$.day(Z))}function U9($,Z){let[J,W]=D0(Z,5),[Y,j]=i6(K$($)+W);return[Y,J+j]}function l$($,Z){return Z?{...$,...s6(b0($)+Z*g0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...Z1},W]}function VJ($){return $?o2:S0}function j4($){return $?w(KJ,$):BJ}function FJ($){return $?w(kV,$):fV}function z4($){return $&&$.epochNanoseconds}function M3($,Z){return $<=6-(z4(Z)?1:0)}function UJ($,Z,J,W,Y,j,z){let X=$(Y1(z).relativeTo),Q=Math.max(m$(Y),m$(j));if(M3(Q,X))return $0(RZ(((U,O,L,P)=>{let H=NZ(D0(U),D0(O),P?-1:1);if(!Number.isFinite(H[0]))throw RangeError(M4);return{...P0,...kZ(H,L)}})(Y,j,Q,W)));if(!X)throw RangeError(H4);W&&(j=k0(j));let[G,B,V]=Y4(Z,J,X),K=j4(V),F=FJ(V),D=K(B,G,Y);return $0(F(B,G,K(B,D,j),Q))}function D9($,Z,J,W,Y){let j=m$(W),[z,X,Q,G,B]=((S,R,f)=>{S=p7(S,m6);let N=JW(S),v=f(S[_X]),_=m7(S),k=q3(S,7),M0=w3(S);if(N===void 0&&M0===void 0)throw RangeError(QF);return M0==null&&(M0=0),N==null&&(N=Math.max(M0,R)),l2(N,M0),_=h7(_,M0,1),[N,M0,_,k,v]})(Y,j,$),V=Math.max(j,z);if(!z4(B)&&V<=6)return $0(RZ(((S,R,f,N,v)=>{let _=$4(D0(S),f,N,v);return{...P0,...kZ(_,R)}})(W,z,X,Q,G)));if(!B)throw RangeError(H4);let[K,F,D]=Y4(Z,J,B),U=VJ(D),O=j4(D),L=FJ(D),P=O(F,K,W),H=L(F,K,P,z),I=W.sign,b=F$(H);if(I&&b&&I!==b)throw RangeError(R3);return b&&(H=e6(H,U(P),z,X,Q,G,F,K,U,O)),$0(H)}function O9($){return $.sign===-1?X4($):$}function X4($){return $0(k0($))}function k0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function L9($){return!$.sign}function F$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(zF);J=Y}}return J}function RZ($){for(let Z of OF)t0(Z,$[Z],-K2,K2,1);return M9(s0(D0($),$1)),$}function M9($){if(!Number.isSafeInteger($))throw RangeError(jF)}function D0($,Z=6){return H2($,Z,h)}function kZ($,Z=6){let[J,W]=$,Y=c6(W,Z,h);if(Y[h[Z]]+=J*(l/D1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(M4);return Y}function Q4($,Z=5){return c6($,Z,h)}function H9($){return Boolean(F$($,HX))}function m$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function RV($,Z){return[$,Z]}function Y2($){let Z=Math.floor($/E6)*E6;return[Z,Z+E6]}function T9($){let Z=U$($=k6($));if(!Z)throw RangeError(v0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(v0($));J=fZ(Z.offset)}return Z.timeZone&&MJ(Z.timeZone,1),L0(f7(n6(Z),J))}function P9($){let Z=U$(W0($));if(!Z)throw RangeError(v0($));if(Z.timeZone)return b9(Z,Z.offset?fZ(Z.offset):void 0);if(Z.m)throw RangeError(v0($));return k9(Z)}function N9($,Z){let J=U$(W0($));if(!J||!J.timeZone)throw RangeError(v0($));let{offset:W}=J,Y=W?fZ(W):void 0,[,j,z]=x3(Z);return b9(J,Y,j,z)}function fZ($){let Z=MJ($);if(Z===void 0)throw RangeError(v0($));return Z}function _9($){let Z=U$(W0($));if(!Z||Z.m)throw RangeError(v0($));return Q0(R9(Z))}function G4($){let Z=U$(W0($));if(!Z||Z.m)throw RangeError(v0($));return G0(Z.p?R9(Z):k9(Z))}function I9($,Z){let J=OJ(W0(Z));if(J)return DJ(J),g$(k7(p$(J)));let W=G4(Z);return g$(L3($(W.calendar),W))}function DJ($){if($.calendar!==q)throw RangeError(y1($.calendar))}function x9($,Z){let J=LJ(W0(Z));if(J)return DJ(J),w6(p$(J));let W=G4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,B]=j.I(z,X),[V,K]=j.N(G,B,Q);return w6(X$(j.P(V,K,Q)),Y)}function C9($){let Z,J=((W)=>{let Y=uF.exec(W);return Y?(K4(Y[10]),q9(Y)):void 0})(W0($));if(!J){if(J=U$($),!J)throw RangeError(v0($));if(!J.p)throw RangeError(v0($));if(J.m)throw RangeError(y1("Z"));DJ(J)}if((Z=OJ($))&&Z2(Z))throw RangeError(v0($));if((Z=LJ($))&&Z2(Z))throw RangeError(v0($));return j1(o6(J,1))}function A9($){let Z=((J)=>{let W=sF.exec(J);return W?((Y)=>{function j(B,V,K){let F=0,D=0;if(K&&([F,Q]=q1(Q,D1[K])),B!==void 0){if(X)throw RangeError(y1(B));D=((U)=>{let O=parseInt(U);if(!Number.isFinite(O))throw RangeError(y1(U));return O})(B),z=1,V&&(Q=HJ(V)*(D1[K]/$1),X=1)}return F+D}let z=0,X=0,Q=0,G={...AZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...c6(Q,2,h)};if(!z)throw RangeError(tz(h));return TJ(Y[1])<0&&(G=k0(G)),G})(W):void 0})(W0($));if(!Z)throw RangeError(v0($));return $0(RZ(Z))}function S9($){let Z=U$($)||OJ($)||LJ($);return Z?Z.calendar:$}function E9($){let Z=U$($);return Z&&(Z.timeZone||Z.m&&t$||Z.offset)||$}function b9($,Z,J=0,W=0){let Y=B4($.timeZone),j=S4(Y);return N0(u$(j,n6($),Z,J,W,!j.v,$.m),Y,A3($.calendar))}function R9($){return f9(g1(n6($)))}function k9($){return f9(X$(p$($)))}function f9($){return{...$,calendar:A3($.calendar)}}function U$($){let Z=dF.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:w9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...q9(J.slice(5)),...K4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function OJ($){let Z=pF.exec($);return Z?((J)=>({isoYear:w9(J),isoMonth:parseInt(J[4]),isoDay:1,...K4(J[5])}))(Z):void 0}function LJ($){let Z=cF.exec($);return Z?((J)=>({isoYear:CZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...K4(J[3])}))(Z):void 0}function MJ($,Z){let J=lF.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])*$1+HJ(W[5]||""))*TJ(W[1]))})(J,Z):void 0}function w9($){let Z=TJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(y1(-0));return Z*J}function q9($){let Z=PZ($[3]);return{...i6(HJ($[4]||""))[0],isoHour:PZ($[1]),isoMinute:PZ($[2]),isoSecond:Z===60?59:Z}}function K4($){let Z,J,W=[];if($.replace(iF,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(y1(Y))}else{if(J)throw RangeError(y1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(y1($));return{timeZone:J,calendar:W[0]||q}}function HJ($){return parseInt($.padEnd(9,"0"))}function wZ($){return new RegExp(`^${$}$`,"i")}function TJ($){return $&&$!=="+"?-1:1}function PZ($){return $===void 0?0:parseInt($)}function y9($){return B4(W0($))}function B4($){let Z=PJ($);return typeof Z=="number"?d$(Z):Z?((J)=>{if(oF.test(J))throw RangeError($F);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?ej(j).replace(/island|noronha|murdo|rivadavia|urville/,ej):j)).join("/")})($):t$}function j2($){let Z=PJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:t$}function PJ($){let Z=MJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==t$?nF($):void 0}function NJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function _J($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function v9($,Z,J,W,Y,j){let z=$(Y1(j).relativeTo),X=Math.max(m$(W),m$(Y));if(L2(h,W,Y))return 0;if(M3(X,z))return E0(D0(W),D0(Y));if(!z)throw RangeError(H4);let[Q,G,B]=Y4(Z,J,z),V=VJ(B),K=j4(B);return E0(V(K(G,Q,W)),V(K(G,Q,Y)))}function IJ($,Z){return i$($,Z)||V4($,Z)}function i$($,Z){return z$(b0($),b0(Z))}function V4($,Z){return z$(K$($),K$(Z))}function g9($,Z){return!NJ($,Z)}function m9($,Z){return!_J($,Z)&&!!F4($.timeZone,Z.timeZone)&&bZ($.calendar,Z.calendar)}function h9($,Z){return!IJ($,Z)&&bZ($.calendar,Z.calendar)}function p9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function c9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function d9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function u9($,Z){return!V4($,Z)}function F4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return j2(J)===j2(W)}catch(Y){}}function xJ($,Z,J,W){let Y=EZ($,X0(W),3,5),j=U4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return $0($?k0(j):j)}function CJ($,Z,J,W,Y,j){let z=O4(W.calendar,Y.calendar),X=X0(j),[Q,G,B,V]=EZ(J,X,5),K=W.epochNanoseconds,F=Y.epochNanoseconds,D=E0(F,K),U;if(D)if(Q<6)U=U4(K,F,Q,G,B,V);else{let O=Z(((P,H)=>{if(!F4(P,H))throw RangeError(YX);return P})(W.timeZone,Y.timeZone)),L=$(z);U=i9(L,O,W,Y,D,Q,X),U=e6(U,F,Q,G,B,V,L,W,o2,w(KJ,O))}else U=P0;return $0(J?k0(U):U)}function AJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y),[X,Q,G,B]=EZ(Z,z,6),V=S0(J),K=S0(W),F=E0(K,V),D;if(F)if(X<=6)D=U4(V,K,X,Q,G,B);else{let U=$(j);D=s9(U,J,W,F,X,z),D=e6(D,K,X,Q,G,B,U,J,S0,BJ)}else D=P0;return $0(Z?k0(D):D)}function SJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y);return l9(Z,()=>$(j),J,W,...EZ(Z,z,6,9,6),z)}function EJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y),X=EZ(Z,z,9,9,8),Q=$(j);return l9(Z,()=>Q,L3(Q,J),L3(Q,W),...X,z)}function l9($,Z,J,W,Y,j,z,X,Q){let G=S0(J),B=S0(W),V;if(E0(B,G))if(Y===6)V=U4(G,B,Y,j,z,X);else{let K=Z();V=K.dateUntil(J,W,Y,Q),j===6&&z===1||(V=e6(V,B,Y,j,z,X,K,J,S0,W4))}else V=P0;return $0($?k0(V):V)}function bJ($,Z,J,W){let Y=X0(W),[j,z,X,Q]=EZ($,Y,5,5),G=B$(RJ(Z,J),C3(z,X),Q),B={...P0,...Q4(G,j)};return $0($?k0(B):B)}function kV($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?n9(J.epochNanoseconds,W.epochNanoseconds,Y):i9(Z,$,J,W,z,Y,j):P0}function fV($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?n9(j,z,W):s9($,Z,J,X,W,Y):P0}function i9($,Z,J,W,Y,j,z){let[X,Q,G]=((K,F,D,U)=>{function O(){return R={...l$(H,b++*-U),...P},f=h0(K,R),E0(I,f)===-U}let L=R0(F,K),P=p0(X1,L),H=R0(D,K),I=D.epochNanoseconds,b=0,S=RJ(L,H),R,f;if(Math.sign(S)===-U&&b++,O()&&(U===-1||O()))throw RangeError(R3);let N=s0(i0(f,I));return[L,R,N]})(Z,J,W,Y);var B,V;return{...j===6?(B=X,V=Q,{...P0,days:o9(B,V)}):$.dateUntil(X,Q,j,z),...Q4(G)}}function s9($,Z,J,W,Y,j){let[z,X,Q]=((G,B,V)=>{let K=B,F=RJ(G,B);return Math.sign(F)===-V&&(K=l$(B,-V),F+=l*V),[G,K,F]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...Q4(Q)}}function U4($,Z,J,W,Y,j){return{...P0,...kZ($4(i0($,Z),W,Y,j),J)}}function n9($,Z,J){return{...P0,...kZ(i0($,Z),J)}}function o9($,Z){return D4(b0($),b0(Z))}function D4($,Z){return Math.trunc((Z-$)/g0)}function RJ($,Z){return K$(Z)-K$($)}function O4($,Z){if(!bZ($,Z))throw RangeError(iJ);return $}function wV($){function Z(Y){return((j,z)=>({...a9(j,z),F:j.month,day:parseInt(j.day)}))(R7(J,Y),W)}let J=XW($),W=v6($);return{id:$,O:qV(Z),B:yV(Z)}}function qV($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function yV($){let Z=$(0).year-NF;return m0((J)=>{let W,Y=SZ(J-Z),j=[],z=[];do Y+=400*g0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*g0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=g0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:XX(z.reverse())}})}function a9($,Z){let J,W,Y=r9($);if($.era){let j=OX[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=Jz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function r9($){return parseInt($.relatedYear||$.year)}function D7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function H3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*g0}function C6($){let Z=X2(this,$),J=X2(this,$-1),W=Z.length;if(W>J.length){let Y=Wz(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(H3.call(this,$),H3.call(this,$+1))}function z2($,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 X2($,Z){return Object.keys($.B(Z).C)}function t9($){return A3(W0($))}function A3($){if(($=$.toLowerCase())!==q&&$!==_4&&v6($)!==v6(XW($).resolvedOptions().calendar))throw RangeError(eV($));return $}function v6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function e9($){return this.R($)[0]}function $z($){return this.R($)[1]}function kJ($){let[Z]=this.h($);return D4(this.q(Z),b0($))+1}function Zz($){let Z=rF.exec($);if(!Z)throw RangeError(rV($));return[parseInt(Z[1]),Boolean(Z[2])]}function g6($,Z,J){return $+(Z||J&&$>=J?1:0)}function O7($,Z){return $-(Z&&$>=Z?1:0)}function Jz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function L7($){return OX[Yz($)]}function Wz($){return FF[Yz($)]}function Yz($){return v6($.id||q)}function jz($,Z,J,W){let Y=D$(J,W,z1,[],VX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=s$(Y),X=$(Y.timeZone);return{epochNanoseconds:u$(Z(X),{...j,...z},Y.offset!==void 0?fZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...Z1}}function zz($,Z,J,W,Y,j){let z=D$(J,Y,z1,KX,VX),X=$(z.timeZone),[Q,G,B]=x3(j),V=J.dateFromFields(z,r6(j,Q)),K=s$(z,Q);return N0(u$(Z(X),{...V,...K},z.offset!==void 0?fZ(z.offset):void 0,G,B),X,W)}function Xz($,Z,J){let W=D$($,Z,z1,[],p1),Y=g(J);return Q0(g1({...$.dateFromFields(W,r6(J,Y)),...s$(W,Y)}))}function fJ($,Z,J,W=[]){let Y=D$($,Z,z1,W);return $.dateFromFields(Y,J)}function wJ($,Z,J,W){let Y=D$($,Z,oJ,W);return $.yearMonthFromFields(Y,J)}function qJ($,Z,J,W,Y=[]){let j=D$($,J,z1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=CZ),$.monthDayFromFields(j,W)}function Qz($,Z){let J=g(Z);return j1(s$(U1($,H7,[],1),J))}function Gz($){let Z=U1($,aJ);return $0(RZ({...P0,...Z}))}function D$($,Z,J,W=[],Y=[]){return U1(Z,[...$.fields(J),...Y].sort(),W)}function U1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(lV(X));if(X==="constructor"||X==="__proto__")throw RangeError(uJ(X));let Q=$[X];if(Q!==void 0)z=1,B2[X]&&(Q=B2[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(dJ(X));Y[X]=DX[X]}j=X}if(W&&!z)throw TypeError(tz(Z));return Y}function s$($,Z){return o6(ZU({...DX,...$}),Z)}function Kz($,Z,J,W,Y,j){let z=X0(j),{calendar:X,timeZone:Q}=J;return N0(((G,B,V,K,F)=>{let D=S3(G,V,K,z1,BX,GX),[U,O,L]=x3(F,2);return u$(B,{...G.dateFromFields(D,r6(F,U)),...s$(D,U)},fZ(D.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function Bz($,Z,J,W,Y){let j=X0(Y);return Q0(((z,X,Q,G)=>{let B=S3(z,X,Q,z1,p1),V=g(G);return g1({...z.dateFromFields(B,r6(G,V)),...s$(B,V)})})($(Z.calendar),J,W,j))}function Vz($,Z,J,W,Y){let j=X0(Y);return((z,X,Q,G)=>{let B=S3(z,X,Q,z1);return z.dateFromFields(B,G)})($(Z.calendar),J,W,j)}function Fz($,Z,J,W,Y){let j=X0(Y);return g$(((z,X,Q,G)=>{let B=S3(z,X,Q,oJ);return z.yearMonthFromFields(B,G)})($(Z.calendar),J,W,j))}function Uz($,Z,J,W,Y){let j=X0(Y);return((z,X,Q,G)=>{let B=S3(z,X,Q,z1);return z.monthDayFromFields(B,G)})($(Z.calendar),J,W,j)}function Dz($,Z,J){return j1(((W,Y,j)=>{let z=g(j);return s$({...p0(H7,W),...U1(Y,H7)},z)})($,Z,J))}function Oz($,Z){return $0((J=$,W=Z,RZ({...J,...U1(W,aJ)})));var J,W}function S3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=U1(Z,z,j),Q=U1(J,z);return X=$.mergeFields(X,Q),U1(X,z,[])}function yJ($,Z){let J=D$($,Z,UX);return $.monthDayFromFields(J)}function vJ($,Z,J){let W=D$($,Z,FX);return $.yearMonthFromFields(W,J)}function Lz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=U1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=U1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function K7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=L7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(sV);if(!j)throw RangeError(iV);let z=j[J];if(z===void 0)throw RangeError(oV(J));let X=Jz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(nV);Y=X}else if(Y===void 0)throw TypeError(aV(j));return Y}function B7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,B)=>{let V=X.U(G),[K,F]=Zz(Q),D=g6(K,F,V);if(F){let U=Wz(X);if(U===void 0)throw RangeError(U3);if(U>0){if(D>U)throw RangeError(U3);if(V===void 0){if(B===1)throw RangeError(U3);D--}}else{if(D!==-U)throw RangeError(U3);if(V===void 0&&B===1)throw RangeError(U3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(JX);Y=z,W=1}else if(Y===void 0)throw TypeError(tV);return t0("month",Y,1,$.L(J),W)}function Q2($,Z,J,W,Y){return y0(Z,"day",1,$.j(W,J),Y)}function V7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Mz($){return L0(n0(l6(u6($))))}function Hz($,Z,J,W,Y=q){return N0(n0(l6(u6(J))),Z(W),$(Y))}function Tz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,B=q){return Q0(g1(n6(J1(A0,AZ(I4,[Z,J,W,Y,j,z,X,Q,G])))),$(B))}function Pz($,Z,J,W,Y=q){return G0(X$(p$(J1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Nz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return g$(k7(p$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function _z($,Z,J,W=q,Y=CZ){let j=A0(Z),z=A0(J),X=$(W);return w6(X$(p$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function Iz($=0,Z=0,J=0,W=0,Y=0,j=0){return j1(o6(J1(A0,AZ(X1,[$,Z,J,W,Y,j])),1))}function xz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return $0(RZ(J1(E2,AZ(h,[$,Z,J,W,Y,j,z,X,Q,G]))))}function gJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function Cz($){return L0($.epochNanoseconds)}function mJ($,Z){return Q0(R0(Z,$))}function hJ($,Z){return G0(R0(Z,$))}function Az($,Z,J){return vJ($(Z.calendar),J)}function Sz($,Z,J){return yJ($(Z.calendar),J)}function pJ($,Z){return j1(R0(Z,$))}function Ez($,Z,J,W){let Y=((j,z,X,Q)=>{let G=y7(Q);return h0(j(z),X,G)})($,J,Z,W);return N0(n0(Y),J,Z.calendar)}function bz($,Z,J){let W=$(Z.calendar);return g$({...Z,...vJ(W,J)})}function Rz($,Z,J){return yJ($(Z.calendar),J)}function kz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):Z1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function fz($,Z=Z1){return Q0(g1({...$,...Z}))}function wz($,Z,J){return vJ($(Z.calendar),J)}function qz($,Z,J){return yJ($(Z.calendar),J)}function yz($,Z,J,W){return((Y,j,z)=>Lz(Y,j,FX,v1(z),f3))($(Z.calendar),J,W)}function vz($,Z,J,W){return((Y,j,z)=>Lz(Y,j,UX,v1(z),N4))($(Z.calendar),J,W)}function gz($,Z,J,W,Y){let j=v1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function mz($,Z){return Q0(g1({...$,...Z}))}function hz($){return L0(n0(IZ($,$1)))}function pz($){return L0(n0(IZ($,O1)))}function cz($){return L0(n0(l6(u6($),o$)))}function dz($){return L0(n0(l6(u6($))))}function uz($,Z,J=Z1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(u$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function lz($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=oz(Z.calendar,J.calendar);return N0(u$(Y,j,j.offsetNanoseconds,2),W,z)}function iz($,Z=Z1){return Q0({...$,...Z})}function sz($,Z){return Q0({...$,...Z},oz($.calendar,Z.calendar))}function L4($,Z){return{...$,calendar:Z}}function nz($,Z){return{...$,timeZone:Z}}function oz($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(iJ)}function vV($,Z){return(J)=>J===q?$:J===_4||J===xZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),aF(J))}function n$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=_7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=t$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function m1($,Z=cJ){let[J,,,W]=$;return(Y,j=LU,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...gV($,Q,z)]}}function cJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(KF);J.timeZone=$}return new O$(Z,J)}function gV($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==q)&&z!==X)throw RangeError(iJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function qZ($){let Z=E3();return V$(Z,$.getOffsetNanosecondsFor(Z))}function E3(){return IZ(Date.now(),O1)}function h1(){return F2||(F2=new O$().resolvedOptions().timeZone)}var mV=($,Z)=>`Non-integer ${$}: ${Z}`,hV=($,Z)=>`Non-positive ${$}: ${Z}`,pV=($,Z)=>`Non-finite ${$}: ${Z}`,cV=($)=>`Cannot convert bigint to ${$}`,dV=($)=>`Invalid bigint: ${$}`,uV="Cannot convert Symbol to string",az="Invalid object",rz=($,Z,J,W,Y)=>Y?rz($,Y[Z],Y[J],Y[W]):b3($,Z)+`; must be between ${J}-${W}`,b3=($,Z)=>`Invalid ${$}: ${Z}`,dJ=($)=>`Missing ${$}`,uJ=($)=>`Invalid field ${$}`,lV=($)=>`Duplicate field ${$}`,tz=($)=>"No valid fields: "+$.join(),ez="Invalid bag",$X=($,Z,J)=>b3($,Z)+"; must be "+Object.keys(J).join(),ZX="Cannot use valueOf",lJ="Invalid calling context",iV="Forbidden era/eraYear",sV="Mismatching era/eraYear",nV="Mismatching year/eraYear",oV=($)=>`Invalid era: ${$}`,aV=($)=>"Missing year"+($?"/era/eraYear":""),rV=($)=>`Invalid monthCode: ${$}`,JX="Mismatching month/monthCode",tV="Missing month/monthCode",G2="Cannot guess year",U3="Invalid leap month",WX="Invalid protocol",R3="Invalid protocol results",iJ="Mismatching Calendars",eV=($)=>`Invalid Calendar: ${$}`,YX="Mismatching TimeZones",$F="Forbidden ICU TimeZone",ZF="Out-of-bounds offset",JF="Out-of-bounds TimeZone gap",WF="Invalid TimeZone offset",YF="Ambiguous offset",M4="Out-of-bounds date",jF="Out-of-bounds duration",zF="Cannot mix duration signs",H4="Missing relativeTo",XF="Cannot use large units",QF="Required smallestUnit or largestUnit",GF="smallestUnit > largestUnit",v0=($)=>`Cannot parse: ${$}`,y1=($)=>`Invalid substring: ${$}`,jX=($)=>`Cannot format ${$}`,zX="Mismatching types for formatting",KF="Cannot specify TimeZone",XX=w(N3,($,Z)=>Z),yZ=w(N3,($,Z,J)=>J),e0=w(R6,2),M7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},k3=Object.keys(M7),g0=86400000,QX=1000,o$=1000,O1=1e6,$1=1e9,T4=60000000000,P4=3600000000000,l=86400000000000,D1=[1,o$,O1,$1,T4,P4,l],p1=k3.slice(0,6),H7=_3(p1),GX=["offset"],KX=["timeZone"],BX=p1.concat(GX),VX=BX.concat(KX),T7=["era","eraYear"],BF=T7.concat(["year"]),N4=["year"],sJ=["monthCode"],nJ=["month"].concat(sJ),f3=["day"],oJ=nJ.concat(N4),FX=sJ.concat(N4),z1=f3.concat(oJ),VF=f3.concat(nJ),UX=f3.concat(sJ),DX=yZ(p1,0),q="iso8601",_4="gregory",xZ="japanese",OX={[_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}},FF={chinese:13,dangi:13,hebrew:-6},W0=w(d6,"string"),LX=w(d6,"boolean"),UF=w(d6,"number"),MX=w(d6,"function"),h=k3.map(($)=>$+"s"),aJ=_3(h),DF=h.slice(0,6),HX=h.slice(6),OF=HX.slice(1),LF=XX(h),P0=yZ(h,0),rJ=yZ(DF,0),tJ=w(M2,h),X1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],eJ=["isoDay","isoMonth","isoYear"],I4=X1.concat(eJ),$W=_3(eJ),TX=_3(X1),PX=_3(I4),Z1=yZ(TX,0),MF=w(M2,I4),O$=Intl.DateTimeFormat,NX="en-GB",ZW=1e8,HF=ZW*g0,TF=[ZW,0],PF=[-ZW,0],T3=275760,P3=-271821,NF=1970,CZ=1972,w1=12,_F=SZ(1868,9,8),IF=m0(IV,WeakMap),m6="smallestUnit",P7="unit",O3="roundingIncrement",F7="fractionalSecondDigits",_X="relativeTo",IX={constrain:0,reject:1},xF=Object.keys(IX),CF={compatible:0,reject:1,earlier:2,later:3},AF={reject:0,use:1,prefer:2,ignore:3},SF={auto:0,never:1,critical:2,always:3},EF={auto:0,never:1,critical:2},bF={auto:0,never:1},RF={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},w3=w(c7,m6),JW=w(c7,"largestUnit"),kF=w(c7,P7),xX=w(c$,"overflow",IX),CX=w(c$,"disambiguation",CF),fF=w(c$,"offset",AF),WW=w(c$,"calendarName",SF),wF=w(c$,"timeZoneName",EF),qF=w(c$,"offset",bF),q3=w(c$,"roundingMode",RF),vZ="PlainYearMonth",gZ="PlainMonthDay",a$="PlainDate",r$="PlainDateTime",x4="PlainTime",c1="ZonedDateTime",C4="Instant",A4="Duration",yF=[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($)],t$="UTC",E6=5184000,vF=f6(1847),gF=f6(new Date().getUTCFullYear()+10),mF=/0+$/,R0=m0(bV,WeakMap),K2=4294967295,S4=m0(($)=>{let Z=PJ($);return typeof Z=="object"?new SX(Z):new AX(Z||0)});class AX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[f7($,this.v)]}l(){}}class SX{constructor($){this.$=((Z)=>{function J(Q){let G=U7(Q,z,X),[B,V]=Y2(G),K=Y(B),F=Y(V);return K===F?K:W(j(B,V),K,F,Q)}function W(Q,G,B,V){let K,F;for(;(V===void 0||(K=V<Q[0]?G:V>=Q[1]?B:void 0)===void 0)&&(F=Q[1]-Q[0]);){let D=Q[0]+Math.floor(F/2);Z(D)===B?Q[1]=D:Q[0]=D+1}return K}let Y=m0(Z),j=m0(RV),z=vF,X=gF;return{G(Q){let G=J(Q-86400),B=J(Q+86400),V=Q-G,K=Q-B;if(G===B)return[V];let F=J(V);return F===J(K)?[Q-F]:G>B?[V,K]:[]},V:J,l(Q,G){let B=U7(Q,z,X),[V,K]=Y2(B),F=E6*G,D=G<0?()=>K>z||(z=B,0):()=>V<X||(X=B,0);for(;D();){let U=Y(V),O=Y(K);if(U!==O){let L=j(V,K);W(L,U,O);let P=L[0];if((z$(P,Q)||1)===G)return P}V+=F,K+=F}}}})(((Z)=>(J)=>{let W=R7(Z,J*QX);return f6(r9(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(k2($))*$1}getPossibleInstantsFor($){let[Z,J]=[f6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*O1+W.isoMicrosecond*o$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>n0(_Z(IZ(Y,$1),J)))}l($,Z){let[J,W]=f2($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return IZ(Y,$1)}}var YW="([+\u2212-])",b6="(?:[.,](\\d{1,9}))?",EX=`(?:(?:${YW}(\\d{6}))|(\\d{4}))-?(\\d{2})`,jW="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+b6+")?)?",zW=YW+jW,hF=EX+"-?(\\d{2})(?:[T ]"+jW+"(Z|"+zW+")?)?",bX="\\[(!?)([^\\]]*)\\]",E4=`((?:${bX}){0,9})`,pF=wZ(EX+E4),cF=wZ("(?:--)?(\\d{2})-?(\\d{2})"+E4),dF=wZ(hF+E4),uF=wZ("T?"+jW+"(?:"+zW+")?"+E4),lF=wZ(zW),iF=new RegExp(bX,"g"),sF=wZ(`${YW}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${b6}H)?(?:(\\d+)${b6}M)?(?:(\\d+)${b6}S)?)?`),nF=m0(($)=>new O$(NX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),oF=/^(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$/,aF=m0(wV),XW=m0(($)=>new O$(NX,{calendar:$,timeZone:t$,era:"short",year:"numeric",month:"short",day:"numeric"})),rF=/^M(\d{2})(L?)$/,tF={era:k6,eraYear:A0,year:A0,month:$2,monthCode:k6,day:$2},eF=yZ(p1,A0),$U=yZ(h,E2),B2=Object.assign({},tF,eF,$U,{offset:k6}),ZU=w(_V,p1,X1),V2={dateAdd($,Z,J){let W=g(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=D0(Z,5)[0],j||z)Y=((G,B,V,K,F)=>{let[D,U,O]=G.h(B);if(V){let[L,P]=G.I(D,U);D+=V,U=g6(L,P,G.U(D)),U=t0("month",U,1,G.L(D),F)}return K&&([D,U]=G._(D,U,K)),O=t0("day",O,1,G.j(D,U),F),G.q(D,U,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=b0($)}return Y+=(7*X+Q)*g0,X$(s6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=o9({...$,...Z1},{...Z,...Z1});return J===7&&([Q,G]=G$(G,7)),{...P0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,B,V,K,F,D)=>{let U=K-G,O=F-B,L=D-V;if(U||O){let P=Math.sign(U||O),H=Q.j(K,F),I=0;if(Math.sign(L)===-P){let b=H;[K,F]=Q._(K,F,-P),U=K-G,O=F-B,H=Q.j(K,F),I=P<0?-b:H}if(L=D-Math.min(V,H)+I,U){let[b,S]=Q.I(G,B),[R,f]=Q.I(K,F);if(O=R-b||Number(f)-Number(S),Math.sign(O)===-P){let N=P<0&&-Q.L(K);U=(K-=P)-G,O=F-g6(b,S,Q.U(K))+(N||Q.L(K))}}}return[U,O,L]})(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=g(Z),W=K7(this,$),Y=B7(this,$,W,J),j=Q2(this,$,Y,W,J);return G0(X$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=g(Z),W=K7(this,$),Y=B7(this,$,W,J);return g$(k7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=g(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,B,V;if(Y!==void 0){[X,Q]=Zz(Y),V=U2($,"day");let K=this.N(X,Q,V);if(!K)throw RangeError(G2);if([G,B]=K,z!==void 0&&z!==B)throw RangeError(JX);W&&(B=t0("month",B,1,w1,1),V=t0("day",V,1,w7(j!==void 0?j:G,B),J))}else{G=j===void 0&&W?CZ:K7(this,$),B=B7(this,$,G,J),V=Q2(this,$,B,G,J);let K=this.U(G);Q=B===K,X=O7(B,K);let F=this.N(X,Q,V);if(!F)throw RangeError(G2);[G,B]=F}return w6(X$(this.P(G,B,V)),this.id||q)},fields($){return L7(this)&&$.includes("year")?[...$,...T7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return V7(J,Z,nJ),L7(this)&&(V7(J,Z,BF),this.id===xZ&&V7(J,Z,VF,T7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:kJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+e0(j)+(z?"L":""))(W,Y)},dayOfWeek:g2,daysInWeek(){return 7}},JU={dayOfYear:kJ,h:q2,q:SZ},WU=Object.assign({},JU,{weekOfYear:e9,yearOfWeek:$z,R($){function Z(F){return(7-F<W?7:0)-F}function J(F){let D=v2(K+F),U=F||1,O=Z(D3(Q+D*U,7));return B=(D+(O-G)*U)/7}let W=this.id?1:4,Y=g2($),j=this.dayOfYear($),z=D3(Y-1,7),X=j-1,Q=D3(z-X,7),G=Z(Q),B,V=Math.floor((X-G)/7)+1,K=$.isoYear;return V?V>J(0)&&(V=1,K++):(V=J(-1),K--),[V,K,B]}}),YU={dayOfYear:kJ,h:D7,q:H3,weekOfYear:e9,yearOfWeek:$z,R(){return[]}},mZ=vV(Object.assign({},V2,WU,{h:q2,ee($){return this.id===_4?m2($):this.id===xZ?IF($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[CZ,$]},K:q7,U(){},L:y2,J:($)=>$*w1,j:w7,X:v2,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:SZ,_:($,Z,J)=>($+=p6(J,w1),(Z+=x7(J,w1))<1?($--,Z+=w1):Z>w1&&($++,Z-=w1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},V2,YU,{h:D7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[O7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=D7.call(this,{isoYear:CZ,isoMonth:w1,isoDay:31}),z=C6.call(this,W),X=Y===z;(z$($,O7(Y,z))||z$(Number(Z),Number(X))||z$(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,B=C6.call(this,G),V=g6($,Z,B);if(Z===(V===B)&&J<=z2.call(this,G,V))return[G,V]}},K($){let Z=A6.call(this,$);return Z>A6.call(this,$-1)&&Z>A6.call(this,$+1)},U:C6,L:S6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=S6.call(this,z+Y);return j},j:z2,X:A6,P($,Z,J){return s6(H3.call(this,$,Z,J))},q:H3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(M4);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}})),Q$="numeric",hZ=["timeZoneName"],RX={month:Q$,day:Q$},QW={year:Q$,month:Q$},GW=Object.assign({},QW,{day:Q$}),KW={hour:Q$,minute:Q$,second:Q$},BW=Object.assign({},GW,KW),jU=Object.assign({},BW,{timeZoneName:"short"}),zU=Object.keys(QW),XU=Object.keys(RX),QU=Object.keys(GW),GU=Object.keys(KW),VW=["dateStyle"],KU=zU.concat(VW),BU=XU.concat(VW),FW=QU.concat(VW,["weekday"]),y3=GU.concat(["dayPeriod","timeStyle"]),UW=FW.concat(y3),VU=UW.concat(hZ),FU=hZ.concat(y3),UU=hZ.concat(FW),DU=hZ.concat(["day","weekday"],y3),OU=hZ.concat(["year","weekday"],y3),LU={},DW=[n$(UW,BW),t6],kX=[n$(VU,jU),t6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(YX);return J}],OW=[n$(UW,BW,hZ),b0],LW=[n$(FW,GW,FU),b0],MW=[n$(y3,KW,UU),($)=>K$($)/O1],HW=[n$(KU,QW,DU),b0,1],TW=[n$(BU,RX,OU),b0,1],F2;function H1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(lJ);yX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...B){return Q.call(this,X(this),...B)},N7(G))}function X(Q){let G=x0(Q);if(!G||G.branding!==$)throw TypeError(lJ);return G}return Object.defineProperties(j.prototype,{...D2(J1(z,J)),...h$(J1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...h$(Y),...N7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return yX(G,Q),G},X]}function mX($){return $=$.concat("id").sort(),(Z)=>{if(!O2(Z,$))throw TypeError(WX);return Z}}function uZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(ez);return $}function b4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,Q=X===a$||Z.includes(X)?z:w0(j);return Y[W](Q)};return J}function _W($){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(fU),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(ZX)}function g3({calendar:$}){return typeof $=="string"?new kW($):$}function fX($,Z){if(Z=X0(Z),O0($)){let W=x0($);if(W&&W.branding===gZ)return g(Z),W;let Y=cX($);return qJ(v4(Y||q),!Y,$,Z)}let J=x9(mZ,$);return g(Z),J}function hX($,Z,J){return W=Z.call($,f0(L0(J))),JJ(I3(W));var W}function R4($,Z=iX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=w(Z[Y],$,MX($[Y]));return W}function s($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return s($,NW)}function L1($){if(O0($)){let Z=x0($);if(Z)switch(Z.branding){case C4:return Z;case c1:return L0(Z.epochNanoseconds)}}return T9($)}function wX($,Z,J){let W=Z.l(L1(J).epochNanoseconds,$);return W?f0(L0(W)):null}function a($){return O0($)?(x0($)||{}).timeZone||mU($):((Z)=>B4(E9(W0(Z))))($)}function L$($,Z){if(O0($)){let J=x0($)||{};switch(J.branding){case x4:return g(Z),J;case r$:return g(Z),j1(J);case c1:return g(Z),pJ(B0,J)}return Qz($,Z)}return g(Z),C9($)}function IW($){return $===void 0?void 0:L$($)}function pZ($,Z){if(Z=X0(Z),O0($)){let W=x0($);return W&&W.branding===vZ?(g(Z),W):wJ(q4(m3($)),$,Z)}let J=I9(mZ,$);return g(Z),J}function M$($,Z){if(Z=X0(Z),O0($)){let W=x0($)||{};switch(W.branding){case r$:return g(Z),W;case a$:return g(Z),Q0({...W,...Z1});case c1:return g(Z),mJ(B0,W)}return Xz(y4(m3($)),$,Z)}let J=_9($);return g(Z),J}function w0($,Z){if(Z=X0(Z),O0($)){let W=x0($)||{};switch(W.branding){case a$:return g(Z),W;case r$:return g(Z),G0(W);case c1:return g(Z),hJ(B0,W)}return fJ(y4(m3($)),$,Z)}let J=G4($);return g(Z),J}function pX($,Z,J){return W1(Z.call($,j0(G0(J,$))))}function T1($){return(Z)=>typeof Z=="string"?mZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=w(W[z],J,J[z]);return j})(Z,$)}function Y0($){if(O0($)){let Z=x0($);return Z&&Z.branding===A4?Z:Gz($)}return A9($)}function v3($){if($!==void 0){if(O0($)){let Z=x0($)||{};switch(Z.branding){case c1:case a$:return Z;case r$:return G0(Z)}let J=m3($);return{...jz(a,s,y4(J),$),calendar:J}}return P9($)}}function m3($){return cX($)||q}function cX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return O0($)?(x0($)||{}).calendar||$D($):((Z)=>A3(S9(W0(Z))))($)}function cZ($,Z){if(Z=X0(Z),O0($)){let J=x0($);if(J&&J.branding===c1)return x3(Z),J;let W=m3($);return zz(a,s,y4(W),W,$,Z)}return N9($,Z)}function qX($){return J1((Z)=>(J)=>Z(PW(J)),$)}function PW($){return R0($,B0)}function MU(){let $=O$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(O$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);fW.set(this,((z,X={})=>{let Q=new O$(z,X),G=Q.resolvedOptions(),B=G.locale,V=p0(Object.keys(X),G),K=m0(PU),F=(...D)=>{let U,O=D.map((L,P)=>{let H=x0(L),I=(H||{}).branding;if(P&&U&&U!==I)throw TypeError(zX);return U=I,H});return U?K(U)(B,V,...O):[Q,...D]};return F.u=Q,F})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&HU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||TU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function HU($){return function(...Z){let J=fW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function TU($){return function(...Z){return fW.get(this).u[$](...Z)}}function PU($){let Z=NU[$];if(!Z)throw TypeError(jX($));return m1(Z,m0(cJ))}var NU={Instant:DW,PlainDateTime:OW,PlainDate:LW,PlainTime:MW,PlainYearMonth:HW,PlainMonthDay:TW},_U=m1(DW),IU=m1(kX),xU=m1(OW),CU=m1(LW),AU=m1(MW),SU=m1(HW),EU=m1(TW),xW={era:_2,eraYear:C7,year:I3,month:W1,daysInMonth:W1,daysInYear:W1,inLeapYear:LX,monthsInYear:W1},f4={monthCode:W0},CW={day:W1},dX={dayOfWeek:W1,dayOfYear:W1,weekOfYear:I2,yearOfWeek:C7,daysInWeek:W1},uX=Object.assign({},xW,f4,CW,dX),k4=new WeakMap,x0=k4.get.bind(k4),yX=k4.set.bind(k4),bU={...b4(xW,[vZ]),...b4(dX,[]),...b4(f4,[vZ,gZ]),...b4(CW,[gZ])},AW=_W(uX),RU=_W({...xW,...f4}),kU=_W({...f4,...CW}),h3={calendarId:($)=>T0($.calendar)},fU=J1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](j0(G0(J,W))))},uX),wU=N3(($)=>(Z)=>Z[$],h.concat("sign")),SW=N3(($,Z)=>(J)=>J[X1[Z]],p1),lX={epochSeconds:i2,epochMilliseconds:t6,epochMicroseconds:s2,epochNanoseconds:n2},p3=w(_7,new Set(["branding"])),[qU,dZ,yU]=H1(gZ,w(_z,I0),{...h3,...kU},{getISOFields:p3,getCalendar:g3,with($,Z,J){return dZ(Uz(rU,$,this,uZ(Z),J))},equals:($,Z)=>d9($,fX(Z)),toPlainDate($,Z){return j0(vz(c3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=EU(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:P$},{from:($,Z)=>dZ(fX($,Z))}),iX={getOffsetNanosecondsFor:hX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(Q0(J,q)))].map((j)=>gU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),WJ(s0(i0(W[0],W[Y-1])))),W}},NW={getOffsetNanosecondsFor:hX},[vU,f0,gU]=H1(C4,Mz,lX,{add:($,Z)=>f0(YJ(0,$,Y0(Z))),subtract:($,Z)=>f0(YJ(1,$,Y0(Z))),until:($,Z,J)=>n(xJ(0,$,L1(Z),J)),since:($,Z,J)=>n(xJ(1,$,L1(Z),J)),round:($,Z)=>f0(r2($,Z)),equals:($,Z)=>g9($,L1(Z)),toZonedDateTime($,Z){let J=v1(Z);return K0(gJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>K0(gJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=_U(Z,J,$);return W.format(Y)},toString:($,Z)=>i7(a,B0,$,Z),toJSON:($)=>i7(a,B0,$),valueOf:P$},{from:($)=>f0(L1($)),fromEpochSeconds:($)=>f0(hz($)),fromEpochMilliseconds:($)=>f0(pz($)),fromEpochMicroseconds:($)=>f0(cz($)),fromEpochNanoseconds:($)=>f0(dz($)),compare:($,Z)=>NJ(L1($),L1(Z))}),[w4,MP]=H1("TimeZone",($)=>{let Z=y9($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(M$(Z)).map((J)=>f0(L0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(L1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=L1(Z).epochNanoseconds,W=R4(this,NW).getOffsetNanosecondsFor(J);return d$(W)},getPlainDateTimeFor($,Z,J=q){let W=L1(Z).epochNanoseconds,Y=R4(this,NW).getOffsetNanosecondsFor(W);return _0(Q0(V$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=M$(Z),Y=y7(J),j=R4(this);return f0(L0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>wX(1,$,Z),getPreviousTransition:({o:$},Z)=>wX(-1,$,Z),equals($,Z){return!!F4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new w4(Z):Z}}),mU=mX(Object.keys(iX)),[hU,H$]=H1(x4,Iz,SW,{getISOFields:p3,with($,Z,J){return H$(Dz(this,uZ(Z),J))},add:($,Z)=>H$(GJ(0,$,Y0(Z))),subtract:($,Z)=>H$(GJ(1,$,Y0(Z))),until:($,Z,J)=>n(bJ(0,$,L$(Z),J)),since:($,Z,J)=>n(bJ(1,$,L$(Z),J)),round:($,Z)=>H$($9($,Z)),equals:($,Z)=>u9($,L$(Z)),toZonedDateTime:($,Z)=>K0(gz(a,w0,s,$,Z)),toPlainDateTime:($,Z)=>_0(mz($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=AU(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:P$},{from:($,Z)=>H$(L$($,Z)),compare:($,Z)=>V4(L$($),L$(Z))}),[pU,T$,cU]=H1(vZ,w(Nz,I0),{...h3,...RU},{getISOFields:p3,getCalendar:g3,with($,Z,J){return T$(Fz(aU,$,this,uZ(Z),J))},add:($,Z,J)=>T$(QJ(vX,0,$,Y0(Z),J)),subtract:($,Z,J)=>T$(QJ(vX,1,$,Y0(Z),J)),until:($,Z,J)=>n(EJ(gX,0,$,pZ(Z),J)),since:($,Z,J)=>n(EJ(gX,1,$,pZ(Z),J)),equals:($,Z)=>c9($,pZ(Z)),toPlainDate($,Z){return j0(yz(c3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=SU(Z,J,$);return W.format(Y)},toString:a7,toJSON:($)=>a7($),valueOf:P$},{from:($,Z)=>T$(pZ($,Z)),compare:($,Z)=>i$(pZ($),pZ(Z))}),[dU,_0]=H1(r$,w(Tz,I0),{...h3,...AW,...SW},{getISOFields:p3,getCalendar:g3,with($,Z,J){return _0(Bz(c3,$,this,uZ(Z),J))},withCalendar:($,Z)=>_0(L4($,I0(Z))),withPlainDate:($,Z)=>_0(sz($,w0(Z))),withPlainTime:($,Z)=>_0(iz($,IW(Z))),add:($,Z,J)=>_0(zJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>_0(zJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(AJ(M1,0,$,M$(Z),J)),since:($,Z,J)=>n(AJ(M1,1,$,M$(Z),J)),round:($,Z)=>_0(e2($,Z)),equals:($,Z)=>h9($,M$(Z)),toZonedDateTime:($,Z,J)=>K0(Ez(s,$,a(Z),J)),toPlainDate:($)=>j0(G0($)),toPlainTime:($)=>H$(j1($)),toPlainYearMonth($){return T$(bz(q4,$,this))},toPlainMonthDay($){return dZ(Rz(v4,$,this))},toLocaleString($,Z,J){let[W,Y]=xU(Z,J,$);return W.format(Y)},toString:n7,toJSON:($)=>n7($),valueOf:P$},{from:($,Z)=>_0(M$($,Z)),compare:($,Z)=>IJ(M$($),M$(Z))}),[uU,j0,sX]=H1(a$,w(Pz,I0),{...h3,...AW},{getISOFields:p3,getCalendar:g3,with($,Z,J){return j0(Vz(c3,$,this,uZ(Z),J))},withCalendar:($,Z)=>j0(L4($,I0(Z))),add:($,Z,J)=>j0(XJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>j0(XJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(SJ(M1,0,$,w0(Z),J)),since:($,Z,J)=>n(SJ(M1,1,$,w0(Z),J)),equals:($,Z)=>p9($,w0(Z)),toZonedDateTime($,Z){let J=!O0(Z)||Z instanceof w4?{timeZone:Z}:Z;return K0(kz(a,L$,s,$,J))},toPlainDateTime:($,Z)=>_0(fz($,IW(Z))),toPlainYearMonth($){return T$(wz(q4,$,this))},toPlainMonthDay($){return dZ(qz(v4,$,this))},toLocaleString($,Z,J){let[W,Y]=CU(Z,J,$);return W.format(Y)},toString:o7,toJSON:($)=>o7($),valueOf:P$},{from:($,Z)=>j0(w0($,Z)),compare:($,Z)=>i$(w0($),w0(Z))}),EW={fields($,Z,J){return[...Z.call($,J)]}},nX=Object.assign({dateFromFields($,Z,J,W){return sX(Z.call($,Object.assign(Object.create(null),J),W))}},EW),oX=Object.assign({yearMonthFromFields($,Z,J,W){return cU(Z.call($,Object.assign(Object.create(null),J),W))}},EW),aX=Object.assign({monthDayFromFields($,Z,J,W){return yU(Z.call($,Object.assign(Object.create(null),J),W))}},EW),bW={mergeFields($,Z,J,W){return v1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},lU=Object.assign({},nX,bW),iU=Object.assign({},oX,bW),sU=Object.assign({},aX,bW),RW={dateAdd($,Z,J,W,Y){return sX(Z.call($,j0(G0(J,$)),n($0(W)),Y))}},rX=Object.assign({},RW,{dateUntil($,Z,J,W,Y,j){return eU(Z.call($,j0(G0(J,$)),j0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:k3[Y]})))}}),nU=Object.assign({},RW,{day:pX}),oU=Object.assign({},rX,{day:pX}),q4=T1(oX),y4=T1(nX),v4=T1(aX),aU=T1(iU),c3=T1(lU),rU=T1(sU),e$=T1(RW),M1=T1(rX),vX=T1(nU),gX=T1(oU),[tU,n,eU]=H1(A4,xz,{...wU,blank:L9},{with:($,Z)=>n(Oz($,Z)),negated:($)=>n(X4($)),abs:($)=>n(O9($)),add:($,Z,J)=>n(UJ(v3,M1,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>n(UJ(v3,M1,s,1,$,Y0(Z),J)),round:($,Z)=>n(D9(v3,M1,s,$,Z)),total:($,Z)=>a2(v3,M1,s,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:P$},{from:($)=>n(Y0($)),compare:($,Z,J)=>v9(v3,e$,s,Y0($),Y0(Z),J)}),tX={toString:($)=>$.id,toJSON:($)=>$.id,...bU,dateAdd:({id:$,o:Z},J,W,Y)=>j0(G0(Z.dateAdd(w0(J),Y0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>n($0($.dateUntil(w0(Z),w0(J),p2(W)))),dateFromFields:({id:$,o:Z},J,W)=>j0(fJ(Z,J,W,N2($))),yearMonthFromFields:({id:$,o:Z},J,W)=>T$(wJ(Z,J,W,T2($))),monthDayFromFields:({id:$,o:Z},J,W)=>dZ(qJ(Z,0,J,W,P2($))),fields({o:$},Z){let J=new Set(z1),W=[];for(let Y of Z){if(W0(Y),!J.has(Y))throw RangeError(uJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(I7(A7(Z)),I7(A7(J)))},[kW]=H1("Calendar",($)=>{let Z=t9($);return{branding:"Calendar",id:Z,o:mZ(Z)}},{id:($)=>$.id},tX,{from($){let Z=I0($);return typeof Z=="string"?new kW(Z):Z}}),$D=mX(Object.keys(tX).slice(4)),[ZD,K0]=H1(c1,w(Hz,I0,a),{...lX,...h3,...qX(AW),...qX(SW),offset:($)=>d$(PW($).offsetNanoseconds),offsetNanoseconds:($)=>PW($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Z9(s,$)},{getISOFields:($)=>F9(B0,$),getCalendar:g3,getTimeZone:({timeZone:$})=>typeof $=="string"?new w4($):$,with($,Z,J){return K0(Kz(c3,s,$,this,uZ(Z),J))},withCalendar:($,Z)=>K0(L4($,I0(Z))),withTimeZone:($,Z)=>K0(nz($,a(Z))),withPlainDate:($,Z)=>K0(lz(s,$,w0(Z))),withPlainTime:($,Z)=>K0(uz(s,$,IW(Z))),add:($,Z,J)=>K0(jJ(e$,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>K0(jJ(e$,s,1,$,Y0(Z),J)),until:($,Z,J)=>n($0(CJ(M1,s,0,$,cZ(Z),J))),since:($,Z,J)=>n($0(CJ(M1,s,1,$,cZ(Z),J))),round:($,Z)=>K0(t2(s,$,Z)),startOfDay:($)=>K0(J9(s,$)),equals:($,Z)=>m9($,cZ(Z)),toInstant:($)=>f0(Cz($)),toPlainDateTime:($)=>_0(mJ(B0,$)),toPlainDate:($)=>j0(hJ(B0,$)),toPlainTime:($)=>H$(pJ(B0,$)),toPlainYearMonth($){return T$(Az(q4,$,this))},toPlainMonthDay($){return dZ(Sz(v4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=IU(Z,J,$);return W.format(Y)},toString:($,Z)=>s7(B0,$,Z),toJSON:($)=>s7(B0,$),valueOf:P$},{from:($,Z)=>K0(cZ($,Z)),compare:($,Z)=>_J(cZ($),cZ(Z))}),JD=Object.defineProperties({},{...h6("Temporal.Now"),...h$({timeZoneId:()=>h1(),instant:()=>f0(L0(E3())),zonedDateTime:($,Z=h1())=>K0(N0(E3(),a(Z),I0($))),zonedDateTimeISO:($=h1())=>K0(N0(E3(),a($),q)),plainDateTime:($,Z=h1())=>_0(Q0(qZ(B0(a(Z))),I0($))),plainDateTimeISO:($=h1())=>_0(Q0(qZ(B0(a($))),q)),plainDate:($,Z=h1())=>j0(G0(qZ(B0(a(Z))),I0($))),plainDateISO:($=h1())=>j0(G0(qZ(B0(a($))),q)),plainTimeISO:($=h1())=>H$(j1(qZ(B0(a($)))))})}),lZ=Object.defineProperties({},{...h6("Temporal"),...h$({PlainYearMonth:pU,PlainMonthDay:qU,PlainDate:uU,PlainTime:hU,PlainDateTime:dU,ZonedDateTime:ZD,Instant:vU,Calendar:kW,TimeZone:w4,Duration:tU,Now:JD})}),WD=MU(),fW=new WeakMap,YD=Object.defineProperties(Object.create(Intl),h$({DateTimeFormat:WD}));var g4="x-gemi-socket";var IP="gemi.v1",eX="/__gemi/socket",xP=/^[A-Za-z0-9_-]{1,32}$/,CP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function bP($){return $}function $Q(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:eX,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 jD,randomBytes as zD}from"crypto";function XD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(jD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var QD="__control",wW=250,GD=1e4,KD=15000;class qW{config;prefix;controlChannel;instanceId=zD(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??XD(),this.controlChannel=this.prefix+QD,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=d3((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 $})(),KD,"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 (${ZQ(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(GD,wW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(wW,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;d3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${ZQ(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??BD(Math.min(Z,wW));await d3(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 d3(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 d3(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 d3($,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 BD($){return new Promise((Z)=>setTimeout(Z,$))}function ZQ($){return $ instanceof Error?$.message:String($)}import{createHmac as VD,hkdfSync as FD,randomBytes as JQ}from"crypto";function WQ($){return VD("sha256",UD()).update($).digest("base64url").slice(0,22)}var m4=null;function UD(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from(FD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):JQ(32);return m4={secret:$,key:Z},Z}function qP(){return JQ(16).toString("base64url")}var DD=/^[A-Za-z0-9_-]{8,64}$/;function yW($){return typeof $==="string"&&DD.test($)}function YQ($,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 zQ extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=P1($Q(),$),this.driver=MD(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 u3(this,h4($,Z[0]),null)}toUser($){return new u3(this,{topic:FZ($),pattern:F0},null)}toOthers($){return new XQ(this,LD($))}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){b5(Z);let Y;try{Y=YQ($.topic,Z,J,W?WQ(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=OD($);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 zQ(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 u3{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 XQ{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new u3(this.manager,h4($,Z[0]),this.except)}toUser($){return new u3(this.manager,{topic:FZ($),pattern:F0},this.except)}}function h4($,Z){if(E5($))return{topic:S8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:K3($,Z??{}),pattern:$};if($===F0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:S8($)}}function OD($){if($&&typeof $==="object"&&"user"in $)return{user:FZ($.user).slice(F0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:h4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function LD($){if($===null||$===void 0)return null;if(typeof $==="string")return yW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(g4);return yW(J)?J:null}function MD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new jQ;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new qW({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 vW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class HD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as gW,createHmac as TD,randomBytes as QQ,timingSafeEqual as BQ}from"crypto";var i3=600,p4="gemi_oauth",PD=`__Host-${p4}`;function sZ($,Z=p4){if(Z===p4)return $?PD:p4;return $?`__Host-${Z}`:Z}function l3($){return $.toString("base64url")}function VQ($){return TD("sha256",MZ()).update(`gemi-oauth-state:${$}`).digest()}function GQ($,Z){let J=gW("sha256").update($).digest(),W=gW("sha256").update(Z).digest();return BQ(J,W)&&$.length===Z.length}function c4($,Z=Date.now(),J={}){let W=l3(QQ(32)),Y=l3(QQ(32)),j=ND(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+i3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:_D(z)}}function ND($){return l3(gW("sha256").update($).digest())}function _D($){let Z=l3(Buffer.from(JSON.stringify($)));return`${Z}.${l3(VQ(Z))}`}function ID($){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=VQ(J);if(W.length!==Y.length||!BQ(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")return null;return j}catch{return null}}var N$=new Map,KQ=1e4;function xD($,Z,J){if(N$.size>=KQ){for(let[W,Y]of N$)if(Y<=J)N$.delete(W);while(N$.size>=KQ){let W=N$.keys().next().value;if(W===void 0)break;N$.delete(W)}}N$.set($,Z)}function d4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=ID($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=GQ(J.state,$.returnedState),Y=GQ(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(N$.has(J.state))return{ok:!1,reason:"invalid_state"};return xD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var mW=new WeakMap;function AD($){let Z=mW.get($);if(!Z)Z=$(CD(32).toString("hex")),mW.set($,Z),Z.catch(()=>mW.delete($));return Z}async function u4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await AD($.hashPassword))}catch{}return!1}async function $Z($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class pW extends Error{}function hW($){return typeof $==="string"&&$!==""?$:null}function FQ($){return q$($)}var SD=256;function UQ($){return typeof $==="string"&&$!==""&&$.length<=SD?$:null}function DQ($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function MQ($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function OQ($){let Z=$.cookies.get(i4);if(!Z)return null;MQ($);try{return V1(decodeURIComponent(Z),"")||null}catch{return null}}class cW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class HQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class TQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new H0("Not found",{status:404})}async function d1($,Z){if(!await R1(M(E).config[$],Z))l4()}async function s3($,Z,J,W){let{config:Y}=M(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await y$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function LQ($,Z,J){let{config:W}=M(E);await s3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function nZ($){return await R1(M(E).config.verifyEmail,$)}class Z0 extends V3{async me(){let $=await q0.user();if(!$)throw new i8;return $}async verifyEmail($=new C){await d1("password",$);let Z=await $.input(),{userProvider:J}=M(E),W=hW(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 C){let Z=M(E),{userProvider:J}=Z;if(!await R1(Z.config.magicLink,$)&&!await R1(Z.config.emailCode.enabled,$))l4();let W=hW($.search.get("token")),Y=null;try{Y=q$(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,M(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await d1("magicLink",$);let Z=M(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=UQ(Y);if(await y$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new cW){await d1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await LQ(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 d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signIn($=new cW){await d1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await LQ(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 d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signUp(){let $=M(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await d1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:DQ(Y.toJSON()),req:W},B=FQ(j);if(await s3("signUp",B,W),!B)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(B,!1))throw new d({email:["Email address already exists"]});let K=await J.hashPassword(z),F=M(c).detectLocale(W),D;if(Q)D=await Z.findInvitation(Q,B);let U,O="";if(D)U=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:B,name:X,password:K,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:D.organizationId,userId:L.id,organizationRole:D.role}),await J.onUserCreated(L,G),L});else{if(O=await J.generateEmailVerificationToken(B),typeof J.verifyEmail==="function"&&!await nZ(W))O="";U=await Z.transaction(async()=>{let L=await Z.createUser({email:B,name:X,password:K,verificationToken:O,locale:F});return await J.onUserCreated(L,G),L})}return await J.onSignUp(U,O,W.search.toJSON(),{req:W}),U}async signOut($=new C){let Z=E$($),J=M(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(E).accessTokenCookieOptions($,new Date(0))),M(E).cookieDomain($))$.ctx().setCookie("access_token","",{...M(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)ED(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new HQ){await d1("password",$);let Z=await $.input(),J=FQ(Z.get("email"));if(await s3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=M(E),j=await W.findUserByEmailAddress(J,await nZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new TQ){await d1("password",$);let{userProvider:Z,config:J}=M(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=hW(j);await s3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(lZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(lZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,await nZ($));if(!G)throw new d({email:["User not found"]});let B=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:B}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G,{req:$}),{}}async changePassword($=new C){await d1("password",$);let{userProvider:Z,config:J}=M(E),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await s3("signIn",q$(W?.email),$),typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await nZ($));if(!(typeof j==="string"&&await u4(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await TZ(J,Z,$);if(!Y){if(W)throw new H0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=UZ($.rawRequest),z=V1($.search.get(B1),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else MQ($);let{state:X,codeChallenge:Q,cookieValue:G}=c4(Z);return $.ctx().setCookie(sZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:i3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await TZ(Y.oauthProviders,Z,$);if(j&&!z)throw new H0("Not found",{status:404});let X=UZ($.rawRequest),Q=sZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let B=$.search.get("error");if(B)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");let V=d4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(N){if(N instanceof vW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:F,username:D,providerId:U,emailVerified:O}=K??{},L=typeof K?.email==="string"?K.email:void 0,P=L?N6(L):null,H=U?await W.findUserBySocialAccount(Z,U):null,I="signin",b=!H&&!P&&!L&&!!U&&z.createUsersWithoutEmail===!0;if(!H&&b){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{H=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:F,username:D,locale:M(c).detectLocale($),req:$}),I="signup"}catch(N){let v=await W.findUserBySocialAccount(Z,U);if(!v)throw N;H=v}}if(!H){if(!P)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":U?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let v=await this.linkOAuthAccount({provider:Z,providerId:U,email:P,rawEmail:L,name:F,username:D,locale:N,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(v==="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(v==="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(v)H=v.user,I=v.action}catch(v){let _=U?await W.findUserBySocialAccount(Z,U):null;if(!_)throw v;H=_}if(!H)return this.oauthFailure($,"account_conflict")}let S=await J.createOrUpdateSessionV2({email:H.email,id:H.id});if($.ctx().setCookie("access_token",S.token,M(E).accessTokenCookieOptions($,S.expiresAt)),I==="signup")await Y.onSignUp(H,"",$.search.toJSON(),{req:$});else await Y.onSignIn(H,$.search.toJSON(),{req:$});await $Z(J.config,{session:S,user:H,isNewUser:I==="signup",method:"oauth",req:$});let R=OQ($)??Y.redirectPath,f=Y.oauthCompleteProfilePath?V1(Y.oauthCompleteProfilePath,""):"";if(f&&!H.email){let N=new URL(f,"http://gemi.invalid");N.searchParams.set(B1,R),R=`${N.pathname}${N.search}${N.hash}`}return{session:S,redirectTo:R}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=OQ($),W=M(E).config.oauthFailurePath;if(W){let Y=V1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(B1,J);S1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=M(E),B=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await Q.findUserByEmailAddress(W,!1),K=Y?.trim();if(!V&&K&&K!==W)V=await Q.findUserByEmailAddress(K,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let D=await Q.findSocialAccounts(V.id,Z);if(D.some((O)=>O.providerId===J))return{user:V,action:"signin"};if(D.some((O)=>O.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await Q.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(B(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let D=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(B(D.id));return await G.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new C){await d1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=M(E),{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:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(E),J=Z.config.emailCode;if(!await R1(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 d({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 C){let Z=M(E),{userProvider:J,config:W}=Z;if(!await R1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=N6(j),G=UQ(z);if(await y$("verify",Q,$,W.emailCode.verifyLimit,W.rateLimitKey),!Q||!G)throw new d({code:["invalid_code"]});let B=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(B.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(B.status!=="ok")throw new d({code:["invalid_code"]});let V=B.row,K=await J.findUserByEmailAddress(Q,!1),F=!1;if(K){if(!await Z.claimOneTimeCode(Q,V.id))throw new d({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let U=M(c).detectLocale($);try{K=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,V.id))throw new pW;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(O,{method:"email-code",input:DQ(Y.toJSON()),req:$}),O}),F=!0}catch(O){if(O instanceof pW)throw new d({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,V.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:Q,id:K.id});return $.ctx().setCookie("access_token",D.token,M(E).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:D,isNewUser:F,method:"email-code",req:$}),{session:D,isNewUser:F}}}function ED($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var PQ="gemi_oauth_connection";class s4 extends V3{async connect($=new C){let Z=String($.params.provider??""),W=M(n3).providers[Z],Y=await q0.user(),j=V1($.search.get(B1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=UZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=c4(NQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(sZ(z,PQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:i3}),S1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:_Q($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(n3),W=await q0.user(),Y=UZ($.rawRequest),j=sZ(Y,PQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=d4({provider:NQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let B=$.search.get("error");if(B)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(Q,Z,"missing_code");try{let K=await G.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:_Q($,Z,G.config.redirectUri)}),F=await J.save(W,Z,K);await M(E).config.onConnected({user:W,provider:Z,connection:F,profile:K.profile??null,req:$})}catch(K){if(K instanceof IQ)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(Q,Z,K.providerError??K.code);throw K}return this.finish(Q,Z)}finish($,Z,J){let W=$||V1(M(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw S1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function NQ($){return`connection:${$}`}function _Q($,Z,J){if(J)return J;return`${ZZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function xQ($){return $.magicLink!==!1||Z7($.emailCode?.enabled)}function CQ($){return Object.keys($.oauthProviders??{}).length>0}function AQ($={}){let Z=[];if(xQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Z7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(CQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class SQ extends E1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([F6,"auth"])}}function EQ($={}){let Z=xQ($),J=CQ($);class W extends E1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[Z0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[Z0,"oauthCallback"])}}return class extends E1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[Z0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":SQ}}}class dW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post(Z0,"signIn"),"/sign-in-v2":this.post(Z0,"signInV2"),"/sign-up":this.post(Z0,"signUp"),"/sign-out":this.post(Z0,"signOut"),"/forgot-password":this.post(Z0,"forgotPassword"),"/reset-password":this.post(Z0,"resetPassword"),"/change-password":this.post(Z0,"changePassword"),"/verify-email":this.post(Z0,"verifyEmail"),"/me":this.get(Z0,"me").middleware(["auth"]),"/magic-link":this.post(Z0,"createMagicLinkToken"),"/sign-in-with-pin":this.post(Z0,"signInWithPin"),"/sign-in-with-pin-v2":this.post(Z0,"signInWithPinV2"),"/email-code":this.post(Z0,"requestEmailCode"),"/email-code/verify":this.post(Z0,"verifyEmailCode")}}class uW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(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 lW{}class iW extends lW{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 sN($){return $}function bQ(){return{driver:new iW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class V0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var bD=new Set([301,302,303,307,308]),RD="/api/__gemi__/services/image/";async function kQ($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=RQ($,Y);try{for(let z=0;;z++){let X=await kD(j,Z,W),Q=X.headers.get("location");if(bD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new V0(502,"The image redirects too many times");j=RQ(Q,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 wD(z,W)}}function RQ($,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 kD($,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(RD))throw new V0(403,"This image source is not allowed");if(fD($.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 b1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new V0(403,"This image source is not allowed");return b1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function fD($){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 wD($,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 sW extends C0{routes={"/resize":this.file(async()=>{let $=new C,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 fQ(400,"url query parameter is required");let X=M(wQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=ZZ();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let B;try{B=await kQ(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(F){if(F instanceof V0)return fQ(F.status,F.message);throw F}let V=await X.resize(B.bytes,{height:Y,width:W,fit:j,quality:z}),K=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(B.cacheControl)K.set("Cache-Control",B.cacheControl);return new Response(new Uint8Array(V),{headers:K})})}}function fQ($,Z){return Response.json({error:Z},{status:$})}class wQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=bQ();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 nW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(qQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function Q_($){return $}function yQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function vQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function qD($){return"run"in $}function yD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function vD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function gD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function mD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function gQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function hD($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function oW($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let B=j==="/"?"":j,V=Z==="/"?"":Z,K=hD((`${V}${B}`===""?"/":`${V}${B}`).replaceAll("//","/"));if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[K].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(mD(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(qD(z)){let X=z,Q=X.method,G=X.middlewares,B=X.run.bind(X);if(Y(j,Q,B,G,X.source),gQ(z))Y(j,"HEAD",B,G,X.source)}if(yD(z))for(let[X,Q]of Object.entries(z)){let G=Q,B=G.middlewares,V=G.run.bind(G);if(Y(j,X,V,B,G.source),X==="get"&&gQ(G))Y(j,"HEAD",V,B,G.source)}if(gD(z)){let X=new z,Q=oW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,B]of Object.entries(Q)){let V=G.replaceAll("//","/");W[V]={...W[V],...B}}}if(vD(z)){let{first:X,second:Q}=z;for(let[G,B]of Object.entries(X)){let V=B.middlewares,K=B.run.bind(B),[F,...D]=j.split("/").reverse();if(!F.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),G,K,V,B.source)}for(let[G,B]of Object.entries(Q)){let V=B.middlewares,K=B.run.bind(B);Y(j,G,K,V,B.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function o4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function aW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function rW($){let Z=o4($);return Z.length>1?Z.replace(/\/$/,""):Z}function mQ($,Z){return Z.map((J)=>({...J,path:rW(aW($,J.path))}))}function a4($){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=a4(j.routes);for(let[X,{exec:Q,middleware:G,segments:B,features:V,static:K}]of Object.entries(z)){let F=aW(J,X),D=(U)=>Y.run.call(Y,U,J);Z[o4(F)]={exec:[D,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:rW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...mQ(J,B)],...K?{static:K}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[o4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:rW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=a4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:B,features:V,static:K}]of Object.entries(j)){let F=aW(J,z);Z[o4(F)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:G,segments:mQ(J,B),...K?{static:K}:{}}}}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 tW="theme";function hQ($){return $==="light"||$==="dark"||$==="system"}function pQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
13
+ `)}function tB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(Hj($),{status:200,headers:J})}var Tj={response:tB,text:Hj,parse:Mj,fetch:rB};import{createHmac as Pj,randomBytes as eB}from"crypto";var s8="v2.";function n8($){return $.startsWith(s8)}function MZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function Nj($){let Z=eB(16).toString("hex"),J=Pj("sha256",MZ()).update(`${$}:${Z}`).digest("hex");return`${s8}${J}`}function T6($,Z){let J=Pj("sha256",MZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${s8}${J}`}import{createHash as JV,createHmac as WV,randomInt as YV,timingSafeEqual as xj}from"crypto";function _j($,Z){return Math.floor($/Z)*Z}function $V($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function o8($,Z,J,W){return Z*$V(J,W)+$}function ZV($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let B=Y*(1-(X-Z)/J);if(B<=Y)return Math.max(0,Math.ceil(B-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function Ij($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let B=o8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-B)),resetAt:Y-j+z,retryAfter:0}}let G=ZV({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class a8{}class r8 extends a8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=_j(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let B=o8(Q.current,Q.previous,X,W)+Y<=J;if(B)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return Ij({allowed:B,current:Q.current,previous:Q.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 Aj="h1.";function P6($,Z,J){let W=WV("sha256",MZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${Aj}${W}`}function HZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(Aj),X=P6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return xj(Q,Q),!1;return xj(Q,G)}function Sj($){let Z="";for(let J=0;J<$;J++)Z+=String(YV(0,10));return Z}var Ej=320;function q$($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>Ej)return null;return Z.toLowerCase()}function N6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>Ej)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var Cj=null;function bj(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(F1))return $.make(F1)}catch{}return Cj??=new F1({driver:new r8,limit:1000,window:60}),Cj}function t8($){return $.length<=64?$:`sha256:${JV("sha256").update($).digest("hex")}`}function jV($){return $==="request"||$==="verify"||$==="link"?`auth:code-${$}`:`auth:${$}`}async function y$($,Z,J,W,Y,j){let z=bj(),X=[["perIp",`ip:${t8(DZ(J))}`,W.perIp]];if(Z!==null)X.push(["perEmail",`email:${t8(Z)}`,W.perEmail]);for(let[Q,G,B]of X){if(!B)continue;let V=Y?await Y({req:J,scope:$,limit:Q}):void 0,K=jV($),F=V?`${K}:p:${t8(String(V))}:${G}`:`${K}:${G}`,[D,U]=B,O=await z.consume(F,{limit:D,window:U});if(!O.allowed)throw await j?.(Q),new Y$(O)}}async function Rj($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await bj().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as $7}from"crypto";class e8 extends C{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"}}}async function R1($,Z){if(typeof $==="function")return await $({req:Z})===!0;return Boolean($)}function Z7($){return $===!0||typeof $==="function"}function J7($={}){return{signIn:{perEmail:$.signIn?.perEmail??[10,900],perIp:$.signIn?.perIp??[50,900]},signUp:{perEmail:$.signUp?.perEmail??!1,perIp:$.signUp?.perIp??[10,3600]},forgot:{perEmail:$.forgot?.perEmail??[5,900],perIp:$.forgot?.perIp??[20,900]},reset:{perEmail:$.reset?.perEmail??!1,perIp:$.reset?.perIp??[20,900]}}}function F3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function zV($={}){let Z=[["password",$?.password],["magicLink",$?.magicLink],["verifyEmail",$?.verifyEmail],["emailCode.enabled",$?.emailCode?.enabled]];for(let[J,W]of Z)if(W!==void 0&&typeof W!=="boolean"&&typeof W!=="function")throw Error(`auth.${J} must be true, false or a function of the request, got ${JSON.stringify(W)}`)}function W7($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return F3("length",Z,4,12),F3("expiresInMinutes",J,1),F3("linkExpiresInMinutes",W,1),F3("maxAttempts",Y,1),F3("activeCodes",j,1,5),{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)`)})}}async function XV($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function kj($){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 fj($){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 mT($){return $}function wj($={}){return zV($),{basePath:"/auth",verifyEmail:!0,password:!0,passwordLimits:J7($.passwordLimits),magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:e8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:XV,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>$7(32).toString("hex"),generateEmailVerificationToken:()=>{if($.verifyEmail===!1)return"";return $7(32).toString("hex")},generateMagicLinkToken:()=>$7(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:W7($.emailCode),generateCode:()=>{return},rateLimitKey:()=>{return},onAuthenticated:()=>{}}}var QV=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),GV=new Set(["svg","math"]);function qj($){return $===32||$===9||$===10||$===12||$===13}function yj($){return $>=65&&$<=90||$>=97&&$<=122}function _6($){return $>=65&&$<=90?$+32:$}function vj(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,B=()=>{if(!J&&QV.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(GV.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},V=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",j=0;else if(K===47)$="endTagOpen";else if(yj(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(_6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(yj(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(_6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(qj(K)||K===47)$="inTag",z=K===47;else if(K===62)B();else Z+=String.fromCharCode(_6(K));return;case"inTag":if(K===62){B();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(j+=1,j===2)$="comment",j=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)j=j<2?j+1:2;else if(K===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(_6(K)===W.charCodeAt(Y))Y+=1;else Y=K===60?1:0;return}if(K===62)$="data",Z="";else if(qj(K)||K===47)$="inTag",Z="";else Y=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let F=0;F<K.length;F++){if(G())return F;V(K[F])}return K.length},write(K){for(let F=0;F<K.length;F++)V(K[F])},isSafe:G}}function r0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function KV($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${r0([$.path,$.variantKey,$.data])})</script>`}function BV($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${r0([$.id,$.locale,$.strings])})</script>`}function Y7($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(KV(D))}),W?.onUse((D)=>{j.push(BV(D))});let G=$.getReader(),B=vj(),V=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(j.length>0){let U=Y.encode(j.shift());B.write(U),V(D,U)}},F=(D,U)=>{if(j.length===0){B.write(U),V(D,U);return}let O=B.scanToInsertionPoint(U);if(O>0)V(D,U.subarray(0,O));if(B.isSafe())K(D);let L=U.subarray(O);if(L.length>0)B.write(L),V(D,L)};return new ReadableStream({async pull(D){let U;try{U=await G.read()}catch(P){throw Q(),P}let{done:O,value:L}=U;if(O){K(D),D.close(),Q();return}if(!z){if(z=!0,B.write(L),V(D,L),J.onShell?.(),B.isSafe())K(D);return}F(D,L)},cancel(D){return Q(),G.cancel(D)}})}var VV=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function I6($){if(!$)return!1;return VV.test($)}async function mj($,Z=()=>{}){let J=T.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 FV($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:gj(),isBot:I6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function hj($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function FV($,Z){if(!$.context)return{};try{let J=T.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 pj($,Z){return`${$}:${Z}`}function j7($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function cj($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function dj($,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=DV($,Z,J,W.buckets);return cj(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function UV($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function DV($,Z,J,W){let Y=pj(Z.salt??$,UV(J));if(!W)return j7(Y);let j=W.get(Y);if(j!==void 0)return j;let z=j7(Y);return W.set(Y,z),z}class uj extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class z7{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new uj(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=OV(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 OV($){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 LV{}class MV extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class X7 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class lj 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 ij{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 j${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new z7($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{T.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new lj(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=HV(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new X7(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new ij(this,hj($))}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($),Q=dj($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}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 $=T.getStore();if($?.featureContext)return $.featureContext;let Z=await mj(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=T.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=T.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 HV($){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 sj($){if($===void 0)return!0;return await M(j$).enabled($)}function nj(){try{return T.getStore()?.req??null}catch{return null}}async function TZ($,Z,J=nj()){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let W=kj($[Z]);if(!W||!await sj(W.feature))return null;if(W.enabled!==void 0&&W.enabled!==!0){if(typeof W.enabled==="function"&&!J)return null;if(!await R1(W.enabled,J))return null}let Y=W.provider;if(typeof Y.isAvailable==="function"&&!await Y.isAvailable(J))return null;return Y}async function oj($,Z=nj()){let J=[];for(let W of Object.keys($))if(await TZ($,W,Z))J.push(W);return J}function Q7($){if($&&typeof $==="object")delete $.password;return $}function TV(){return new Proxy({},{get:($,Z)=>rj(Z)})}var aj=new WeakMap;function tj($){if($&&typeof $==="object"){for(let Z of Object.values($))tj(Z);Object.freeze($)}return $}var PV={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},NV=tj({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:PV});class G7{models;constructor($=TV()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return NV}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??k1(),W=M(f1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await l0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||l0())return Y();let z=(aj.get(W)??Promise.resolve()).then(Y,Y);return aj.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return Q7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return Q7(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?Q7(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 CD}from"crypto";function y0($,Z,J,W,Y){return t0(Z,U2($,Z),J,W,Y)}function t0($,Z,J,W,Y,j){let z=U7(Z,J,W);if(Y&&Z!==z)throw RangeError(rz($,Z,J,W,j));return z}function U2($,Z){let J=$[Z];if(J===void 0)throw TypeError(dJ(Z));return J}function O0($){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 N7($){return h$({name:$},1)}function h$($,Z){return J1((J)=>({value:J,configurable:1,writable:!Z}),$)}function D2($){return J1((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 J1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function N3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function _V($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function _7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function I7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function O2($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function L2($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function M2($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function w($,...Z){return(...J)=>$(...Z,...J)}function ej($){return $[0].toUpperCase()+$.substring(1)}function _3($){return $.slice().sort()}function R6($,Z){return String(Z).padStart($,"0")}function z$($,Z){return Math.sign($-Z)}function U7($,Z,J){return Math.min(Math.max($,Z),J)}function q1($,Z){return[Math.floor($/Z),D3($,Z)]}function D3($,Z){return($%Z+Z)%Z}function G$($,Z){return[p6($,Z),x7($,Z)]}function p6($,Z){return Math.trunc($/Z)||0}function x7($,Z){return $%Z||0}function x6($){return Math.abs($%1)===0.5}function H2($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=D1[X],B=l/G,[V,K]=G$(Q,B);W+=K*G,Y+=V}let[j,z]=G$(W,l);return[Y+j,z]}function c6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=D1[Y];W[J[Y]]=p6($,j),$=x7($,j)}return W}function T2($){return $===q?N4:[]}function P2($){return $===q?f3:[]}function N2($){return $===q?["year","day"]:[]}function _2($){if($!==void 0)return W0($)}function I2($){if($!==void 0)return W1($)}function C7($){if($!==void 0)return I3($)}function W1($){return A2(I3($))}function I3($){return C2(UF($))}function A7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function x2($,Z){if(Z==null)throw RangeError(dJ($));return Z}function v1($){if(!O0($))throw TypeError(az);return $}function d6($,Z,J=$){if(typeof Z!==$)throw TypeError(b3(J,Z));return Z}function C2($,Z="number"){if(!Number.isInteger($))throw RangeError(mV(Z,$));return $||0}function A2($,Z="number"){if($<=0)throw RangeError(hV(Z,$));return $}function S7($){if(typeof $=="symbol")throw TypeError(uV);return String($)}function k6($,Z){return O0($)?String($):W0($,Z)}function u6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(dV($));return $}function S2($,Z="number"){if(typeof $=="bigint")throw TypeError(cV(Z));if($=Number($),!Number.isFinite($))throw RangeError(pV(Z,$));return $}function A0($,Z){return Math.trunc(S2($,Z))||0}function E2($,Z){return C2(S2($,Z),Z)}function $2($,Z){return A2(A0($,Z),Z)}function E7($,Z){let[J,W]=G$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function NZ($,Z,J=1){return E7($[0]+Z[0]*J,$[1]+Z[1]*J)}function _Z($,Z){return E7($[0],$[1]+Z)}function i0($,Z){return NZ(Z,$,-1)}function E0($,Z){return z$($[0],Z[0])||z$($[1],Z[1])}function b2($,Z,J){return E0($,Z)===-1||E0($,J)===1}function l6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function IZ($,Z=1){let J=l/Z,[W,Y]=G$($,J);return[W,Y*Z]}function R2($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function s0($,Z=1,J){let[W,Y]=$,[j,z]=G$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function b7($,Z,J=q1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function R7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function k7($){return y0($,"isoYear",P3,T3,1),$.isoYear===P3?y0($,"isoMonth",4,12,1):$.isoYear===T3&&y0($,"isoMonth",1,9,1),$}function X$($){return g1({...$,...Z1,isoHour:12}),$}function g1($){let Z=y0($,"isoYear",P3,T3,1),J=Z===P3?1:Z===T3?-1:0;return J&&n0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function n0($){if(!$||b2($,PF,TF))throw RangeError(M4);return $}function K$($){return H2($,5,X1)[1]}function i6($){let[Z,J]=q1($,l);return[c6(J,5,X1),Z]}function k2($){return f2($)[0]}function f2($){return b7($,$1)}function b0($){return SZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=G$(Z,g0);return[J,W*O1+($.isoMicrosecond||0)*o$+($.isoNanosecond||0)]}}function f7($,Z){let[J,W]=i6(K$($)-Z);return n0(S0({...$,isoDay:$.isoDay+W,...J}))}function f6(...$){return SZ(...$)/QX}function SZ(...$){let[Z,J]=w2(...$),W=Z.valueOf();if(!isNaN(W))return W-J*g0}function w2($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===P3?1:$===T3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function V$($,Z){let[J,W]=_Z($,Z);W<0&&(W+=l,J-=1);let[Y,j]=q1(W,O1),[z,X]=q1(j,o$);return s6(J*g0+Y,z,X)}function s6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-HF)/g0)*Math.sign($),Y=new Date($-W*g0);return AZ(I4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function q2($){return[$.isoYear,$.isoMonth,$.isoDay]}function y2(){return w1}function w7($,Z){switch(Z){case 2:return q7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function v2($){return q7($)?366:365}function q7($){return $%4==0&&($%100!=0||$%400==0)}function g2($){let[Z,J]=w2($.isoYear,$.isoMonth,$.isoDay);return D3(Z.getUTCDay()-J,7)||7}function m2({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function IV($){let Z=b0($);if(Z<_F)return m2($);let J=R7(XW(xZ),Z),{era:W,eraYear:Y}=a9(J,xZ);return[W,Y]}function n6($){return p$($),o6($,1),$}function p$($){return h2($,1),$}function Z2($){return L2(eJ,$,h2($))}function h2($,Z){let{isoYear:J}=$,W=y0($,"isoMonth",1,y2(),Z);return{isoYear:J,isoMonth:W,isoDay:y0($,"isoDay",1,w7(J,W),Z)}}function o6($,Z){return AZ(X1,[y0($,"isoHour",0,23,Z),y0($,"isoMinute",0,59,Z),y0($,"isoSecond",0,59,Z),y0($,"isoMillisecond",0,999,Z),y0($,"isoMicrosecond",0,999,Z),y0($,"isoNanosecond",0,999,Z)])}function g($){return $===void 0?0:xX(v1($))}function x3($,Z=0){$=Y1($);let J=CX($),W=fF($,Z);return[xX($),W,J]}function y7($){return CX(Y1($))}function p2($){return $=Y1($),JW($,9,6,1)}function EZ($,Z,J,W=9,Y=0,j=4){Z=Y1(Z);let z=JW(Z,W,Y),X=m7(Z),Q=q3(Z,j),G=w3(Z,W,Y,1);return z==null?z=Math.max(J,G):l2(z,G),X=h7(X,G,1),$&&(Q=((B)=>B<4?(B+2)%4:B)(Q)),[z,G,X,Q]}function a6($,Z=6,J){let W=m7($=p7($,m6)),Y=q3($,7),j=w3($,Z);return j=x2(m6,j),W=h7(W,j,void 0,J),[j,W,Y]}function v7($){return WW(Y1($))}function c2($,Z){return g7(Y1($),Z)}function g7($,Z=4){let J=u2($);return[q3($,4),...d2(w3($,Z),J)]}function d2($,Z){return $!=null?[D1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function m7($){let Z=$[O3];return Z===void 0?1:A0(Z,O3)}function h7($,Z,J,W){let Y=W?l:D1[Z+1];if(Y){let j=D1[Z];if(Y%(($=t0(O3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(b3(O3,$))}else $=t0(O3,$,1,J?1e9:1,1);return $}function u2($){let Z=$[F7];if(Z!==void 0){if(typeof Z!="number"){if(S7(Z)==="auto")return;throw RangeError(b3(F7,Z))}Z=t0(F7,Math.floor(Z),0,9,1)}return Z}function Y1($){return $===void 0?{}:v1($)}function p7($,Z){return typeof $=="string"?{[Z]:$}:v1($)}function X0($){if($!==void 0){if(O0($))return Object.assign(Object.create(null),$);throw TypeError(az)}}function r6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:xF[Z]})}function c7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=S7(j),j==="auto")return Y?W:null;let z=M7[j];if(z===void 0&&(z=LF[j]),z===void 0)throw RangeError($X($,j,M7));return t0($,z,W,J,1,k3),z}function c$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=S7(Y),z=Z[j];if(z===void 0)throw RangeError($X($,j,Z));return z}function l2($,Z){if(Z>$)throw RangeError(GF)}function L0($){return{branding:C4,epochNanoseconds:$}}function N0($,Z,J){return{branding:c1,calendar:J,timeZone:Z,epochNanoseconds:$}}function Q0($,Z=$.calendar){return{branding:r$,calendar:Z,...p0(PX,$)}}function G0($,Z=$.calendar){return{branding:a$,calendar:Z,...p0($W,$)}}function g$($,Z=$.calendar){return{branding:vZ,calendar:Z,...p0($W,$)}}function w6($,Z=$.calendar){return{branding:gZ,calendar:Z,...p0($W,$)}}function j1($){return{branding:x4,...p0(TX,$)}}function $0($){return{branding:A4,sign:F$($),...p0(aJ,$)}}function i2($){return k2($.epochNanoseconds)}function t6($){return b7($.epochNanoseconds,O1)[0]}function s2($){return R2($.epochNanoseconds,o$)}function n2($){return R2($.epochNanoseconds)}function o2($){return $.epochNanoseconds}function T0($){return typeof $=="string"?$:W0($.id)}function bZ($,Z){return $===Z||T0($)===T0(Z)}function a2($,Z,J,W,Y){let j=m$(W),[z,X]=((O,L)=>{let P=L((O=p7(O,P7))[_X]),H=kF(O);return H=x2(P7,H),[H,P]})(Y,$);if(M3(Math.max(z,j),X))return J2(W,z);if(!X)throw RangeError(H4);let[Q,G,B]=Y4(Z,J,X),V=VJ(B),K=j4(B),F=FJ(B),D=K(G,Q,W),U=F(G,Q,D,z);return M3(z,X)?J2(U,z):((O,L,P,H,I,b,S)=>{let R=F$(O),[f,N]=d7(H,tJ(P,O),P,R,I,b,S),v=u7(L,f,N);return O[h[P]]+v*R})(U,V(D),z,G,Q,V,K)}function J2($,Z){return s0(D0($),D1[Z],1)}function d7($,Z,J,W,Y,j,z){let X=h[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),B=z($,Y,Q);return[j(G),j(B)]}function u7($,Z,J){let W=s0(i0(Z,J));if(!W)throw RangeError(R3);return s0(i0(Z,$))/W}function r2($,Z){let[J,W,Y]=a6(Z,5,1);return L0($4($.epochNanoseconds,J,W,Y,1))}function t2($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=a6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((B,V,K,F)=>{let D=R0(K,V),[U,O]=B(D),L=K.epochNanoseconds,P=h0(V,U),H=h0(V,O);if(b2(L,P,H))throw RangeError(R3);return X9(u7(L,P,H),F)?H:P})(j9,G,Z,Q);else{let B=G.getOffsetNanosecondsFor(W);W=u$(G,W9(V$(W,B),z,X,Q),B,2,0,1)}return N0(W,Y,j)}function e2($,Z){return Q0(W9($,...a6(Z)),$.calendar)}function $9($,Z){let[J,W,Y]=a6(Z,5);var j;return j1((j=Y,l7($,C3(J,W),j)[0]))}function Z9($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=j9(W),z=s0(i0(h0(J,Y),h0(J,j)),P4,1);if(z<=0)throw RangeError(R3);return z}function J9($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(z9,$(J),Z);return N0(Y,J,W)}function W9($,Z,J,W){return Y9($,C3(Z,J),W)}function Y9($,Z,J){let[W,Y]=l7($,Z,J);return g1({...l$($,Y),...W})}function l7($,Z,J){return i6(B$(K$($),Z,J))}function q6($){return B$($,T4,7)}function C3($,Z){return D1[$]*Z}function j9($){let Z=z9($);return[Z,l$(Z,1)]}function z9($){return MF(6,$)}function xV($,Z,J){let W=Math.min(m$($),6);return kZ(Z4(D0($,W),Z,J),W)}function e6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let B=M3(W,X)?z4(X)&&W<6&&J>=6?AV:CV:SV,[V,K,F]=B($,Z,J,W,Y,j,z,X,Q,G);return F&&W!==7&&(V=((D,U,O,L,P,H,I,b)=>{let S=F$(D);for(let R=L+1;R<=O;R++){if(R===7&&O!==7)continue;let f=tJ(R,D);f[h[R]]+=S;let N=s0(i0(I(b(P,H,f)),U));if(N&&Math.sign(N)!==S)break;D=f}return D})(V,K,J,Math.max(6,W),z,X,Q,G)),V}function $4($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[B$(j,J,W),0]}return Z4($,C3(Z,J),W,Y)}function Z4($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=q1(B$(j,Z,J),l);return E7(Y+z,X)}function B$($,Z,J){return X9($/Z,J)*Z}function X9($,Z){return yF[Z]($)}function CV($,Z,J,W,Y,j){let z=F$($),X=D0($),Q=$4(X,W,Y,j),G=i0(X,Q),B=Math.sign(Q[0]-X[0])===z,V=kZ(Q,Math.min(J,6));return[{...$,...V},NZ(Z,G),B]}function AV($,Z,J,W,Y,j,z,X,Q,G){let B=F$($),V=s0(D0($,5)),K=C3(W,Y),F=B$(V,K,j),[D,U]=d7(z,{...$,...rJ},6,B,X,Q,G),O=F-s0(i0(D,U)),L=0;O&&Math.sign(O)!==B?Z=_Z(D,F):(L+=B,F=B$(O,K,j),Z=_Z(U,F));let P=Q4(F);return[{...$,...P,days:$.days+L},Z,Boolean(L)]}function SV($,Z,J,W,Y,j,z,X,Q,G){let B=F$($),V=h[W],K=tJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let F=p6($[V],Y)*Y;K[V]=F;let[D,U]=d7(z,K,W,Y*B,X,Q,G),O=F+u7(Z,D,U)*B*Y,L=B$(O,Y,j),P=Math.sign(L-O)===B;return K[V]=L,[K,P?U:D,P]}function i7($,Z,J,W){let[Y,j,z,X]=((G)=>{let B=g7(G=Y1(G));return[G.timeZone,...B]})(W),Q=Y!==void 0;return((G,B,V,K,F,D)=>{V=Z4(V,F,K,1);let U=B.getOffsetNanosecondsFor(V);return e7(V$(V,U),D)+(G?d$(q6(U)):"Z")})(Q,Z(Q?$(Y):t$),J.epochNanoseconds,j,z,X)}function s7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=Y1(G);let B=WW(G),V=u2(G),K=qF(G),F=q3(G,4),D=w3(G,4);return[B,wF(G),K,F,...d2(D,V)]})(J);return((G,B,V,K,F,D,U,O,L,P)=>{K=Z4(K,L,O,1);let H=G(V).getOffsetNanosecondsFor(K);return e7(V$(K,H),P)+d$(q6(H),U)+((I,b)=>b!==1?"["+(b===2?"!":"")+T0(I)+"]":"")(V,D)+$J(B,F)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function n7($,Z){let[J,W,Y,j]=((G)=>(G=Y1(G),[WW(G),...g7(G)]))(Z);return z=$.calendar,X=J,Q=j,e7(Y9($,Y,W),Q)+$J(z,X);var z,X,Q}function o7($,Z){return J=$.calendar,W=$,Y=v7(Z),y6(W)+$J(J,Y);var J,W,Y}function a7($,Z){return Q9($.calendar,G9,$,v7(Z))}function r7($,Z){return Q9($.calendar,EV,$,v7(Z))}function t7($,Z){let[J,W,Y]=c2(Z);return j=Y,K9(l7($,W,J)[0],j);var j}function J4($,Z){let[J,W,Y]=c2(Z,3);return W>1&&($={...$,...xV($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?k0(j):j,{hours:G,minutes:B}=Q,[V,K]=b7(D0(Q,3),$1,G$);M9(V);let F=ZJ(K,z),D=z>=0||!X||F;return(X<0?"-":"")+"P"+W2({Y:v$(Q.years),M:v$(Q.months),W:v$(Q.weeks),D:v$(Q.days)})+(G||B||V||D?"T"+W2({H:v$(G),M:v$(B),S:v$(V,D)+F}):"")})($,Y)}function Q9($,Z,J,W){let Y=T0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):y6(J):j?y6(J)+B9(Y,W===2):Z(J)}function W2($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function e7($,Z){return y6($)+"T"+K9($,Z)}function y6($){return G9($)+"-"+e0($.isoDay)}function G9($){let{isoYear:Z}=$;return(Z<0||Z>9999?V9(Z)+R6(6,Math.abs(Z)):R6(4,Z))+"-"+e0($.isoMonth)}function EV($){return e0($.isoMonth)+"-"+e0($.isoDay)}function K9($,Z){let J=[e0($.isoHour),e0($.isoMinute)];return Z!==-1&&J.push(e0($.isoSecond)+((W,Y,j,z)=>ZJ(W*O1+Y*o$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function d$($,Z=0){if(Z===1)return"";let[J,W]=q1(Math.abs($),P4),[Y,j]=q1(W,T4),[z,X]=q1(j,$1);return V9($)+e0(J)+":"+e0(Y)+(z||X?":"+e0(z)+ZJ(X):"")}function $J($,Z){if(Z!==1){let J=T0($);if(Z>1||Z===0&&J!==q)return B9(J,Z===2)}return""}function B9($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function ZJ($,Z){let J=R6(9,$);return J=Z===void 0?J.replace(mF,""):J.slice(0,Z),J?"."+J:""}function V9($){return $<0?"-":"+"}function v$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function bV($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=V$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function F9($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(PX,J),offset:d$(J.offsetNanoseconds),timeZone:Z.timeZone}}function u$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return f7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,B,V,K)=>{let F=S0(B);K&&(V=q6(V));for(let D of G){let U=s0(i0(D,F));if(K&&(U=q6(U)),U===V)return D}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(WF)}return z?S0(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(YF);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(_Z(Q,-l));return WJ(X.getOffsetNanosecondsFor(_Z(Q,l))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(V$(Y,z)))[J===2?0:W.length-1]}function JJ($){if(Math.abs($)>=l)throw RangeError(ZF);return $}function WJ($){if($>l)throw RangeError(JF);return $}function YJ($,Z,J){return L0(n0(NZ(Z.epochNanoseconds,((W)=>{if(H9(W))throw RangeError(XF);return D0(W,5)})($?k0(J):J))))}function jJ($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...KJ(z,X,W,J?k0(Y):Y,j)}}function zJ($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return Q0(BJ($(j),J,Z?k0(W):W,Y),j)}function XJ($,Z,J,W,Y){let{calendar:j}=J;return G0(W4($(j),J,Z?k0(W):W,Y),j)}function QJ($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=L3(z,J);Z&&(W=X4(W)),W.sign<0&&(X=z.dateAdd(X,{...P0,months:1}),X=l$(X,-1));let Q=z.dateAdd(X,W,Y);return g$(L3(z,Q),j)}function GJ($,Z,J){return j1(U9(Z,$?k0(J):J)[0])}function KJ($,Z,J,W,Y){let j=D0(W,5),z=J.epochNanoseconds;if(H9(W)){let X=R0(J,$);z=NZ(h0($,{...W4(Z,X,{...W,...rJ},Y),...p0(X1,X)}),j)}else z=NZ(z,j),g(Y);return{epochNanoseconds:n0(z)}}function BJ($,Z,J,W){let[Y,j]=U9(Z,J);return g1({...W4($,Z,{...J,...rJ,days:J.days+j},W),...Y})}function W4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);g(W);let Y=J.days+D0(J,5)[0];return Y?X$(l$(Z,Y)):Z}function L3($,Z,J=1){return l$(Z,J-$.day(Z))}function U9($,Z){let[J,W]=D0(Z,5),[Y,j]=i6(K$($)+W);return[Y,J+j]}function l$($,Z){return Z?{...$,...s6(b0($)+Z*g0)}:$}function Y4($,Z,J){let W=$(J.calendar);return z4(J)?[J,W,Z(J.timeZone)]:[{...J,...Z1},W]}function VJ($){return $?o2:S0}function j4($){return $?w(KJ,$):BJ}function FJ($){return $?w(kV,$):fV}function z4($){return $&&$.epochNanoseconds}function M3($,Z){return $<=6-(z4(Z)?1:0)}function UJ($,Z,J,W,Y,j,z){let X=$(Y1(z).relativeTo),Q=Math.max(m$(Y),m$(j));if(M3(Q,X))return $0(RZ(((U,O,L,P)=>{let H=NZ(D0(U),D0(O),P?-1:1);if(!Number.isFinite(H[0]))throw RangeError(M4);return{...P0,...kZ(H,L)}})(Y,j,Q,W)));if(!X)throw RangeError(H4);W&&(j=k0(j));let[G,B,V]=Y4(Z,J,X),K=j4(V),F=FJ(V),D=K(B,G,Y);return $0(F(B,G,K(B,D,j),Q))}function D9($,Z,J,W,Y){let j=m$(W),[z,X,Q,G,B]=((S,R,f)=>{S=p7(S,m6);let N=JW(S),v=f(S[_X]),_=m7(S),k=q3(S,7),M0=w3(S);if(N===void 0&&M0===void 0)throw RangeError(QF);return M0==null&&(M0=0),N==null&&(N=Math.max(M0,R)),l2(N,M0),_=h7(_,M0,1),[N,M0,_,k,v]})(Y,j,$),V=Math.max(j,z);if(!z4(B)&&V<=6)return $0(RZ(((S,R,f,N,v)=>{let _=$4(D0(S),f,N,v);return{...P0,...kZ(_,R)}})(W,z,X,Q,G)));if(!B)throw RangeError(H4);let[K,F,D]=Y4(Z,J,B),U=VJ(D),O=j4(D),L=FJ(D),P=O(F,K,W),H=L(F,K,P,z),I=W.sign,b=F$(H);if(I&&b&&I!==b)throw RangeError(R3);return b&&(H=e6(H,U(P),z,X,Q,G,F,K,U,O)),$0(H)}function O9($){return $.sign===-1?X4($):$}function X4($){return $0(k0($))}function k0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function L9($){return!$.sign}function F$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(zF);J=Y}}return J}function RZ($){for(let Z of OF)t0(Z,$[Z],-K2,K2,1);return M9(s0(D0($),$1)),$}function M9($){if(!Number.isSafeInteger($))throw RangeError(jF)}function D0($,Z=6){return H2($,Z,h)}function kZ($,Z=6){let[J,W]=$,Y=c6(W,Z,h);if(Y[h[Z]]+=J*(l/D1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(M4);return Y}function Q4($,Z=5){return c6($,Z,h)}function H9($){return Boolean(F$($,HX))}function m$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function RV($,Z){return[$,Z]}function Y2($){let Z=Math.floor($/E6)*E6;return[Z,Z+E6]}function T9($){let Z=U$($=k6($));if(!Z)throw RangeError(v0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(v0($));J=fZ(Z.offset)}return Z.timeZone&&MJ(Z.timeZone,1),L0(f7(n6(Z),J))}function P9($){let Z=U$(W0($));if(!Z)throw RangeError(v0($));if(Z.timeZone)return b9(Z,Z.offset?fZ(Z.offset):void 0);if(Z.m)throw RangeError(v0($));return k9(Z)}function N9($,Z){let J=U$(W0($));if(!J||!J.timeZone)throw RangeError(v0($));let{offset:W}=J,Y=W?fZ(W):void 0,[,j,z]=x3(Z);return b9(J,Y,j,z)}function fZ($){let Z=MJ($);if(Z===void 0)throw RangeError(v0($));return Z}function _9($){let Z=U$(W0($));if(!Z||Z.m)throw RangeError(v0($));return Q0(R9(Z))}function G4($){let Z=U$(W0($));if(!Z||Z.m)throw RangeError(v0($));return G0(Z.p?R9(Z):k9(Z))}function I9($,Z){let J=OJ(W0(Z));if(J)return DJ(J),g$(k7(p$(J)));let W=G4(Z);return g$(L3($(W.calendar),W))}function DJ($){if($.calendar!==q)throw RangeError(y1($.calendar))}function x9($,Z){let J=LJ(W0(Z));if(J)return DJ(J),w6(p$(J));let W=G4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,B]=j.I(z,X),[V,K]=j.N(G,B,Q);return w6(X$(j.P(V,K,Q)),Y)}function C9($){let Z,J=((W)=>{let Y=uF.exec(W);return Y?(K4(Y[10]),q9(Y)):void 0})(W0($));if(!J){if(J=U$($),!J)throw RangeError(v0($));if(!J.p)throw RangeError(v0($));if(J.m)throw RangeError(y1("Z"));DJ(J)}if((Z=OJ($))&&Z2(Z))throw RangeError(v0($));if((Z=LJ($))&&Z2(Z))throw RangeError(v0($));return j1(o6(J,1))}function A9($){let Z=((J)=>{let W=sF.exec(J);return W?((Y)=>{function j(B,V,K){let F=0,D=0;if(K&&([F,Q]=q1(Q,D1[K])),B!==void 0){if(X)throw RangeError(y1(B));D=((U)=>{let O=parseInt(U);if(!Number.isFinite(O))throw RangeError(y1(U));return O})(B),z=1,V&&(Q=HJ(V)*(D1[K]/$1),X=1)}return F+D}let z=0,X=0,Q=0,G={...AZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...c6(Q,2,h)};if(!z)throw RangeError(tz(h));return TJ(Y[1])<0&&(G=k0(G)),G})(W):void 0})(W0($));if(!Z)throw RangeError(v0($));return $0(RZ(Z))}function S9($){let Z=U$($)||OJ($)||LJ($);return Z?Z.calendar:$}function E9($){let Z=U$($);return Z&&(Z.timeZone||Z.m&&t$||Z.offset)||$}function b9($,Z,J=0,W=0){let Y=B4($.timeZone),j=S4(Y);return N0(u$(j,n6($),Z,J,W,!j.v,$.m),Y,A3($.calendar))}function R9($){return f9(g1(n6($)))}function k9($){return f9(X$(p$($)))}function f9($){return{...$,calendar:A3($.calendar)}}function U$($){let Z=dF.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:w9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...q9(J.slice(5)),...K4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function OJ($){let Z=pF.exec($);return Z?((J)=>({isoYear:w9(J),isoMonth:parseInt(J[4]),isoDay:1,...K4(J[5])}))(Z):void 0}function LJ($){let Z=cF.exec($);return Z?((J)=>({isoYear:CZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...K4(J[3])}))(Z):void 0}function MJ($,Z){let J=lF.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])*$1+HJ(W[5]||""))*TJ(W[1]))})(J,Z):void 0}function w9($){let Z=TJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(y1(-0));return Z*J}function q9($){let Z=PZ($[3]);return{...i6(HJ($[4]||""))[0],isoHour:PZ($[1]),isoMinute:PZ($[2]),isoSecond:Z===60?59:Z}}function K4($){let Z,J,W=[];if($.replace(iF,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(y1(Y))}else{if(J)throw RangeError(y1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(y1($));return{timeZone:J,calendar:W[0]||q}}function HJ($){return parseInt($.padEnd(9,"0"))}function wZ($){return new RegExp(`^${$}$`,"i")}function TJ($){return $&&$!=="+"?-1:1}function PZ($){return $===void 0?0:parseInt($)}function y9($){return B4(W0($))}function B4($){let Z=PJ($);return typeof Z=="number"?d$(Z):Z?((J)=>{if(oF.test(J))throw RangeError($F);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?ej(j).replace(/island|noronha|murdo|rivadavia|urville/,ej):j)).join("/")})($):t$}function j2($){let Z=PJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:t$}function PJ($){let Z=MJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==t$?nF($):void 0}function NJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function _J($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function v9($,Z,J,W,Y,j){let z=$(Y1(j).relativeTo),X=Math.max(m$(W),m$(Y));if(L2(h,W,Y))return 0;if(M3(X,z))return E0(D0(W),D0(Y));if(!z)throw RangeError(H4);let[Q,G,B]=Y4(Z,J,z),V=VJ(B),K=j4(B);return E0(V(K(G,Q,W)),V(K(G,Q,Y)))}function IJ($,Z){return i$($,Z)||V4($,Z)}function i$($,Z){return z$(b0($),b0(Z))}function V4($,Z){return z$(K$($),K$(Z))}function g9($,Z){return!NJ($,Z)}function m9($,Z){return!_J($,Z)&&!!F4($.timeZone,Z.timeZone)&&bZ($.calendar,Z.calendar)}function h9($,Z){return!IJ($,Z)&&bZ($.calendar,Z.calendar)}function p9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function c9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function d9($,Z){return!i$($,Z)&&bZ($.calendar,Z.calendar)}function u9($,Z){return!V4($,Z)}function F4($,Z){if($===Z)return 1;let J=T0($),W=T0(Z);if(J===W)return 1;try{return j2(J)===j2(W)}catch(Y){}}function xJ($,Z,J,W){let Y=EZ($,X0(W),3,5),j=U4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return $0($?k0(j):j)}function CJ($,Z,J,W,Y,j){let z=O4(W.calendar,Y.calendar),X=X0(j),[Q,G,B,V]=EZ(J,X,5),K=W.epochNanoseconds,F=Y.epochNanoseconds,D=E0(F,K),U;if(D)if(Q<6)U=U4(K,F,Q,G,B,V);else{let O=Z(((P,H)=>{if(!F4(P,H))throw RangeError(YX);return P})(W.timeZone,Y.timeZone)),L=$(z);U=i9(L,O,W,Y,D,Q,X),U=e6(U,F,Q,G,B,V,L,W,o2,w(KJ,O))}else U=P0;return $0(J?k0(U):U)}function AJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y),[X,Q,G,B]=EZ(Z,z,6),V=S0(J),K=S0(W),F=E0(K,V),D;if(F)if(X<=6)D=U4(V,K,X,Q,G,B);else{let U=$(j);D=s9(U,J,W,F,X,z),D=e6(D,K,X,Q,G,B,U,J,S0,BJ)}else D=P0;return $0(Z?k0(D):D)}function SJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y);return l9(Z,()=>$(j),J,W,...EZ(Z,z,6,9,6),z)}function EJ($,Z,J,W,Y){let j=O4(J.calendar,W.calendar),z=X0(Y),X=EZ(Z,z,9,9,8),Q=$(j);return l9(Z,()=>Q,L3(Q,J),L3(Q,W),...X,z)}function l9($,Z,J,W,Y,j,z,X,Q){let G=S0(J),B=S0(W),V;if(E0(B,G))if(Y===6)V=U4(G,B,Y,j,z,X);else{let K=Z();V=K.dateUntil(J,W,Y,Q),j===6&&z===1||(V=e6(V,B,Y,j,z,X,K,J,S0,W4))}else V=P0;return $0($?k0(V):V)}function bJ($,Z,J,W){let Y=X0(W),[j,z,X,Q]=EZ($,Y,5,5),G=B$(RJ(Z,J),C3(z,X),Q),B={...P0,...Q4(G,j)};return $0($?k0(B):B)}function kV($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?n9(J.epochNanoseconds,W.epochNanoseconds,Y):i9(Z,$,J,W,z,Y,j):P0}function fV($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?n9(j,z,W):s9($,Z,J,X,W,Y):P0}function i9($,Z,J,W,Y,j,z){let[X,Q,G]=((K,F,D,U)=>{function O(){return R={...l$(H,b++*-U),...P},f=h0(K,R),E0(I,f)===-U}let L=R0(F,K),P=p0(X1,L),H=R0(D,K),I=D.epochNanoseconds,b=0,S=RJ(L,H),R,f;if(Math.sign(S)===-U&&b++,O()&&(U===-1||O()))throw RangeError(R3);let N=s0(i0(f,I));return[L,R,N]})(Z,J,W,Y);var B,V;return{...j===6?(B=X,V=Q,{...P0,days:o9(B,V)}):$.dateUntil(X,Q,j,z),...Q4(G)}}function s9($,Z,J,W,Y,j){let[z,X,Q]=((G,B,V)=>{let K=B,F=RJ(G,B);return Math.sign(F)===-V&&(K=l$(B,-V),F+=l*V),[G,K,F]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...Q4(Q)}}function U4($,Z,J,W,Y,j){return{...P0,...kZ($4(i0($,Z),W,Y,j),J)}}function n9($,Z,J){return{...P0,...kZ(i0($,Z),J)}}function o9($,Z){return D4(b0($),b0(Z))}function D4($,Z){return Math.trunc((Z-$)/g0)}function RJ($,Z){return K$(Z)-K$($)}function O4($,Z){if(!bZ($,Z))throw RangeError(iJ);return $}function wV($){function Z(Y){return((j,z)=>({...a9(j,z),F:j.month,day:parseInt(j.day)}))(R7(J,Y),W)}let J=XW($),W=v6($);return{id:$,O:qV(Z),B:yV(Z)}}function qV($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function yV($){let Z=$(0).year-NF;return m0((J)=>{let W,Y=SZ(J-Z),j=[],z=[];do Y+=400*g0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*g0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=g0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:XX(z.reverse())}})}function a9($,Z){let J,W,Y=r9($);if($.era){let j=OX[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=Jz(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function r9($){return parseInt($.relatedYear||$.year)}function D7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function H3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*g0}function C6($){let Z=X2(this,$),J=X2(this,$-1),W=Z.length;if(W>J.length){let Y=Wz(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(H3.call(this,$),H3.call(this,$+1))}function z2($,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 X2($,Z){return Object.keys($.B(Z).C)}function t9($){return A3(W0($))}function A3($){if(($=$.toLowerCase())!==q&&$!==_4&&v6($)!==v6(XW($).resolvedOptions().calendar))throw RangeError(eV($));return $}function v6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function e9($){return this.R($)[0]}function $z($){return this.R($)[1]}function kJ($){let[Z]=this.h($);return D4(this.q(Z),b0($))+1}function Zz($){let Z=rF.exec($);if(!Z)throw RangeError(rV($));return[parseInt(Z[1]),Boolean(Z[2])]}function g6($,Z,J){return $+(Z||J&&$>=J?1:0)}function O7($,Z){return $-(Z&&$>=Z?1:0)}function Jz($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function L7($){return OX[Yz($)]}function Wz($){return FF[Yz($)]}function Yz($){return v6($.id||q)}function jz($,Z,J,W){let Y=D$(J,W,z1,[],VX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=s$(Y),X=$(Y.timeZone);return{epochNanoseconds:u$(Z(X),{...j,...z},Y.offset!==void 0?fZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...Z1}}function zz($,Z,J,W,Y,j){let z=D$(J,Y,z1,KX,VX),X=$(z.timeZone),[Q,G,B]=x3(j),V=J.dateFromFields(z,r6(j,Q)),K=s$(z,Q);return N0(u$(Z(X),{...V,...K},z.offset!==void 0?fZ(z.offset):void 0,G,B),X,W)}function Xz($,Z,J){let W=D$($,Z,z1,[],p1),Y=g(J);return Q0(g1({...$.dateFromFields(W,r6(J,Y)),...s$(W,Y)}))}function fJ($,Z,J,W=[]){let Y=D$($,Z,z1,W);return $.dateFromFields(Y,J)}function wJ($,Z,J,W){let Y=D$($,Z,oJ,W);return $.yearMonthFromFields(Y,J)}function qJ($,Z,J,W,Y=[]){let j=D$($,J,z1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=CZ),$.monthDayFromFields(j,W)}function Qz($,Z){let J=g(Z);return j1(s$(U1($,H7,[],1),J))}function Gz($){let Z=U1($,aJ);return $0(RZ({...P0,...Z}))}function D$($,Z,J,W=[],Y=[]){return U1(Z,[...$.fields(J),...Y].sort(),W)}function U1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(lV(X));if(X==="constructor"||X==="__proto__")throw RangeError(uJ(X));let Q=$[X];if(Q!==void 0)z=1,B2[X]&&(Q=B2[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(dJ(X));Y[X]=DX[X]}j=X}if(W&&!z)throw TypeError(tz(Z));return Y}function s$($,Z){return o6(ZU({...DX,...$}),Z)}function Kz($,Z,J,W,Y,j){let z=X0(j),{calendar:X,timeZone:Q}=J;return N0(((G,B,V,K,F)=>{let D=S3(G,V,K,z1,BX,GX),[U,O,L]=x3(F,2);return u$(B,{...G.dateFromFields(D,r6(F,U)),...s$(D,U)},fZ(D.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function Bz($,Z,J,W,Y){let j=X0(Y);return Q0(((z,X,Q,G)=>{let B=S3(z,X,Q,z1,p1),V=g(G);return g1({...z.dateFromFields(B,r6(G,V)),...s$(B,V)})})($(Z.calendar),J,W,j))}function Vz($,Z,J,W,Y){let j=X0(Y);return((z,X,Q,G)=>{let B=S3(z,X,Q,z1);return z.dateFromFields(B,G)})($(Z.calendar),J,W,j)}function Fz($,Z,J,W,Y){let j=X0(Y);return g$(((z,X,Q,G)=>{let B=S3(z,X,Q,oJ);return z.yearMonthFromFields(B,G)})($(Z.calendar),J,W,j))}function Uz($,Z,J,W,Y){let j=X0(Y);return((z,X,Q,G)=>{let B=S3(z,X,Q,z1);return z.monthDayFromFields(B,G)})($(Z.calendar),J,W,j)}function Dz($,Z,J){return j1(((W,Y,j)=>{let z=g(j);return s$({...p0(H7,W),...U1(Y,H7)},z)})($,Z,J))}function Oz($,Z){return $0((J=$,W=Z,RZ({...J,...U1(W,aJ)})));var J,W}function S3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=U1(Z,z,j),Q=U1(J,z);return X=$.mergeFields(X,Q),U1(X,z,[])}function yJ($,Z){let J=D$($,Z,UX);return $.monthDayFromFields(J)}function vJ($,Z,J){let W=D$($,Z,FX);return $.yearMonthFromFields(W,J)}function Lz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=U1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=U1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function K7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=L7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(sV);if(!j)throw RangeError(iV);let z=j[J];if(z===void 0)throw RangeError(oV(J));let X=Jz(W,z);if(Y!==void 0&&Y!==X)throw RangeError(nV);Y=X}else if(Y===void 0)throw TypeError(aV(j));return Y}function B7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,B)=>{let V=X.U(G),[K,F]=Zz(Q),D=g6(K,F,V);if(F){let U=Wz(X);if(U===void 0)throw RangeError(U3);if(U>0){if(D>U)throw RangeError(U3);if(V===void 0){if(B===1)throw RangeError(U3);D--}}else{if(D!==-U)throw RangeError(U3);if(V===void 0&&B===1)throw RangeError(U3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(JX);Y=z,W=1}else if(Y===void 0)throw TypeError(tV);return t0("month",Y,1,$.L(J),W)}function Q2($,Z,J,W,Y){return y0(Z,"day",1,$.j(W,J),Y)}function V7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Mz($){return L0(n0(l6(u6($))))}function Hz($,Z,J,W,Y=q){return N0(n0(l6(u6(J))),Z(W),$(Y))}function Tz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,B=q){return Q0(g1(n6(J1(A0,AZ(I4,[Z,J,W,Y,j,z,X,Q,G])))),$(B))}function Pz($,Z,J,W,Y=q){return G0(X$(p$(J1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Nz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return g$(k7(p$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function _z($,Z,J,W=q,Y=CZ){let j=A0(Z),z=A0(J),X=$(W);return w6(X$(p$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function Iz($=0,Z=0,J=0,W=0,Y=0,j=0){return j1(o6(J1(A0,AZ(X1,[$,Z,J,W,Y,j])),1))}function xz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return $0(RZ(J1(E2,AZ(h,[$,Z,J,W,Y,j,z,X,Q,G]))))}function gJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function Cz($){return L0($.epochNanoseconds)}function mJ($,Z){return Q0(R0(Z,$))}function hJ($,Z){return G0(R0(Z,$))}function Az($,Z,J){return vJ($(Z.calendar),J)}function Sz($,Z,J){return yJ($(Z.calendar),J)}function pJ($,Z){return j1(R0(Z,$))}function Ez($,Z,J,W){let Y=((j,z,X,Q)=>{let G=y7(Q);return h0(j(z),X,G)})($,J,Z,W);return N0(n0(Y),J,Z.calendar)}function bz($,Z,J){let W=$(Z.calendar);return g$({...Z,...vJ(W,J)})}function Rz($,Z,J){return yJ($(Z.calendar),J)}function kz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):Z1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function fz($,Z=Z1){return Q0(g1({...$,...Z}))}function wz($,Z,J){return vJ($(Z.calendar),J)}function qz($,Z,J){return yJ($(Z.calendar),J)}function yz($,Z,J,W){return((Y,j,z)=>Lz(Y,j,FX,v1(z),f3))($(Z.calendar),J,W)}function vz($,Z,J,W){return((Y,j,z)=>Lz(Y,j,UX,v1(z),N4))($(Z.calendar),J,W)}function gz($,Z,J,W,Y){let j=v1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function mz($,Z){return Q0(g1({...$,...Z}))}function hz($){return L0(n0(IZ($,$1)))}function pz($){return L0(n0(IZ($,O1)))}function cz($){return L0(n0(l6(u6($),o$)))}function dz($){return L0(n0(l6(u6($))))}function uz($,Z,J=Z1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(u$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function lz($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=oz(Z.calendar,J.calendar);return N0(u$(Y,j,j.offsetNanoseconds,2),W,z)}function iz($,Z=Z1){return Q0({...$,...Z})}function sz($,Z){return Q0({...$,...Z},oz($.calendar,Z.calendar))}function L4($,Z){return{...$,calendar:Z}}function nz($,Z){return{...$,timeZone:Z}}function oz($,Z){if($===Z)return $;let J=T0($),W=T0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(iJ)}function vV($,Z){return(J)=>J===q?$:J===_4||J===xZ?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),aF(J))}function n$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=_7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=t$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function m1($,Z=cJ){let[J,,,W]=$;return(Y,j=LU,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...gV($,Q,z)]}}function cJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(KF);J.timeZone=$}return new O$(Z,J)}function gV($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==q)&&z!==X)throw RangeError(iJ)})(T0(j.calendar),Z.calendar,Y),W(j,Z)))}function qZ($){let Z=E3();return V$(Z,$.getOffsetNanosecondsFor(Z))}function E3(){return IZ(Date.now(),O1)}function h1(){return F2||(F2=new O$().resolvedOptions().timeZone)}var mV=($,Z)=>`Non-integer ${$}: ${Z}`,hV=($,Z)=>`Non-positive ${$}: ${Z}`,pV=($,Z)=>`Non-finite ${$}: ${Z}`,cV=($)=>`Cannot convert bigint to ${$}`,dV=($)=>`Invalid bigint: ${$}`,uV="Cannot convert Symbol to string",az="Invalid object",rz=($,Z,J,W,Y)=>Y?rz($,Y[Z],Y[J],Y[W]):b3($,Z)+`; must be between ${J}-${W}`,b3=($,Z)=>`Invalid ${$}: ${Z}`,dJ=($)=>`Missing ${$}`,uJ=($)=>`Invalid field ${$}`,lV=($)=>`Duplicate field ${$}`,tz=($)=>"No valid fields: "+$.join(),ez="Invalid bag",$X=($,Z,J)=>b3($,Z)+"; must be "+Object.keys(J).join(),ZX="Cannot use valueOf",lJ="Invalid calling context",iV="Forbidden era/eraYear",sV="Mismatching era/eraYear",nV="Mismatching year/eraYear",oV=($)=>`Invalid era: ${$}`,aV=($)=>"Missing year"+($?"/era/eraYear":""),rV=($)=>`Invalid monthCode: ${$}`,JX="Mismatching month/monthCode",tV="Missing month/monthCode",G2="Cannot guess year",U3="Invalid leap month",WX="Invalid protocol",R3="Invalid protocol results",iJ="Mismatching Calendars",eV=($)=>`Invalid Calendar: ${$}`,YX="Mismatching TimeZones",$F="Forbidden ICU TimeZone",ZF="Out-of-bounds offset",JF="Out-of-bounds TimeZone gap",WF="Invalid TimeZone offset",YF="Ambiguous offset",M4="Out-of-bounds date",jF="Out-of-bounds duration",zF="Cannot mix duration signs",H4="Missing relativeTo",XF="Cannot use large units",QF="Required smallestUnit or largestUnit",GF="smallestUnit > largestUnit",v0=($)=>`Cannot parse: ${$}`,y1=($)=>`Invalid substring: ${$}`,jX=($)=>`Cannot format ${$}`,zX="Mismatching types for formatting",KF="Cannot specify TimeZone",XX=w(N3,($,Z)=>Z),yZ=w(N3,($,Z,J)=>J),e0=w(R6,2),M7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},k3=Object.keys(M7),g0=86400000,QX=1000,o$=1000,O1=1e6,$1=1e9,T4=60000000000,P4=3600000000000,l=86400000000000,D1=[1,o$,O1,$1,T4,P4,l],p1=k3.slice(0,6),H7=_3(p1),GX=["offset"],KX=["timeZone"],BX=p1.concat(GX),VX=BX.concat(KX),T7=["era","eraYear"],BF=T7.concat(["year"]),N4=["year"],sJ=["monthCode"],nJ=["month"].concat(sJ),f3=["day"],oJ=nJ.concat(N4),FX=sJ.concat(N4),z1=f3.concat(oJ),VF=f3.concat(nJ),UX=f3.concat(sJ),DX=yZ(p1,0),q="iso8601",_4="gregory",xZ="japanese",OX={[_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}},FF={chinese:13,dangi:13,hebrew:-6},W0=w(d6,"string"),LX=w(d6,"boolean"),UF=w(d6,"number"),MX=w(d6,"function"),h=k3.map(($)=>$+"s"),aJ=_3(h),DF=h.slice(0,6),HX=h.slice(6),OF=HX.slice(1),LF=XX(h),P0=yZ(h,0),rJ=yZ(DF,0),tJ=w(M2,h),X1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],eJ=["isoDay","isoMonth","isoYear"],I4=X1.concat(eJ),$W=_3(eJ),TX=_3(X1),PX=_3(I4),Z1=yZ(TX,0),MF=w(M2,I4),O$=Intl.DateTimeFormat,NX="en-GB",ZW=1e8,HF=ZW*g0,TF=[ZW,0],PF=[-ZW,0],T3=275760,P3=-271821,NF=1970,CZ=1972,w1=12,_F=SZ(1868,9,8),IF=m0(IV,WeakMap),m6="smallestUnit",P7="unit",O3="roundingIncrement",F7="fractionalSecondDigits",_X="relativeTo",IX={constrain:0,reject:1},xF=Object.keys(IX),CF={compatible:0,reject:1,earlier:2,later:3},AF={reject:0,use:1,prefer:2,ignore:3},SF={auto:0,never:1,critical:2,always:3},EF={auto:0,never:1,critical:2},bF={auto:0,never:1},RF={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},w3=w(c7,m6),JW=w(c7,"largestUnit"),kF=w(c7,P7),xX=w(c$,"overflow",IX),CX=w(c$,"disambiguation",CF),fF=w(c$,"offset",AF),WW=w(c$,"calendarName",SF),wF=w(c$,"timeZoneName",EF),qF=w(c$,"offset",bF),q3=w(c$,"roundingMode",RF),vZ="PlainYearMonth",gZ="PlainMonthDay",a$="PlainDate",r$="PlainDateTime",x4="PlainTime",c1="ZonedDateTime",C4="Instant",A4="Duration",yF=[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($)],t$="UTC",E6=5184000,vF=f6(1847),gF=f6(new Date().getUTCFullYear()+10),mF=/0+$/,R0=m0(bV,WeakMap),K2=4294967295,S4=m0(($)=>{let Z=PJ($);return typeof Z=="object"?new SX(Z):new AX(Z||0)});class AX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[f7($,this.v)]}l(){}}class SX{constructor($){this.$=((Z)=>{function J(Q){let G=U7(Q,z,X),[B,V]=Y2(G),K=Y(B),F=Y(V);return K===F?K:W(j(B,V),K,F,Q)}function W(Q,G,B,V){let K,F;for(;(V===void 0||(K=V<Q[0]?G:V>=Q[1]?B:void 0)===void 0)&&(F=Q[1]-Q[0]);){let D=Q[0]+Math.floor(F/2);Z(D)===B?Q[1]=D:Q[0]=D+1}return K}let Y=m0(Z),j=m0(RV),z=vF,X=gF;return{G(Q){let G=J(Q-86400),B=J(Q+86400),V=Q-G,K=Q-B;if(G===B)return[V];let F=J(V);return F===J(K)?[Q-F]:G>B?[V,K]:[]},V:J,l(Q,G){let B=U7(Q,z,X),[V,K]=Y2(B),F=E6*G,D=G<0?()=>K>z||(z=B,0):()=>V<X||(X=B,0);for(;D();){let U=Y(V),O=Y(K);if(U!==O){let L=j(V,K);W(L,U,O);let P=L[0];if((z$(P,Q)||1)===G)return P}V+=F,K+=F}}}})(((Z)=>(J)=>{let W=R7(Z,J*QX);return f6(r9(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(k2($))*$1}getPossibleInstantsFor($){let[Z,J]=[f6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*O1+W.isoMicrosecond*o$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>n0(_Z(IZ(Y,$1),J)))}l($,Z){let[J,W]=f2($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return IZ(Y,$1)}}var YW="([+\u2212-])",b6="(?:[.,](\\d{1,9}))?",EX=`(?:(?:${YW}(\\d{6}))|(\\d{4}))-?(\\d{2})`,jW="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+b6+")?)?",zW=YW+jW,hF=EX+"-?(\\d{2})(?:[T ]"+jW+"(Z|"+zW+")?)?",bX="\\[(!?)([^\\]]*)\\]",E4=`((?:${bX}){0,9})`,pF=wZ(EX+E4),cF=wZ("(?:--)?(\\d{2})-?(\\d{2})"+E4),dF=wZ(hF+E4),uF=wZ("T?"+jW+"(?:"+zW+")?"+E4),lF=wZ(zW),iF=new RegExp(bX,"g"),sF=wZ(`${YW}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${b6}H)?(?:(\\d+)${b6}M)?(?:(\\d+)${b6}S)?)?`),nF=m0(($)=>new O$(NX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),oF=/^(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$/,aF=m0(wV),XW=m0(($)=>new O$(NX,{calendar:$,timeZone:t$,era:"short",year:"numeric",month:"short",day:"numeric"})),rF=/^M(\d{2})(L?)$/,tF={era:k6,eraYear:A0,year:A0,month:$2,monthCode:k6,day:$2},eF=yZ(p1,A0),$U=yZ(h,E2),B2=Object.assign({},tF,eF,$U,{offset:k6}),ZU=w(_V,p1,X1),V2={dateAdd($,Z,J){let W=g(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=D0(Z,5)[0],j||z)Y=((G,B,V,K,F)=>{let[D,U,O]=G.h(B);if(V){let[L,P]=G.I(D,U);D+=V,U=g6(L,P,G.U(D)),U=t0("month",U,1,G.L(D),F)}return K&&([D,U]=G._(D,U,K)),O=t0("day",O,1,G.j(D,U),F),G.q(D,U,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=b0($)}return Y+=(7*X+Q)*g0,X$(s6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=o9({...$,...Z1},{...Z,...Z1});return J===7&&([Q,G]=G$(G,7)),{...P0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,B,V,K,F,D)=>{let U=K-G,O=F-B,L=D-V;if(U||O){let P=Math.sign(U||O),H=Q.j(K,F),I=0;if(Math.sign(L)===-P){let b=H;[K,F]=Q._(K,F,-P),U=K-G,O=F-B,H=Q.j(K,F),I=P<0?-b:H}if(L=D-Math.min(V,H)+I,U){let[b,S]=Q.I(G,B),[R,f]=Q.I(K,F);if(O=R-b||Number(f)-Number(S),Math.sign(O)===-P){let N=P<0&&-Q.L(K);U=(K-=P)-G,O=F-g6(b,S,Q.U(K))+(N||Q.L(K))}}}return[U,O,L]})(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=g(Z),W=K7(this,$),Y=B7(this,$,W,J),j=Q2(this,$,Y,W,J);return G0(X$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=g(Z),W=K7(this,$),Y=B7(this,$,W,J);return g$(k7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=g(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,B,V;if(Y!==void 0){[X,Q]=Zz(Y),V=U2($,"day");let K=this.N(X,Q,V);if(!K)throw RangeError(G2);if([G,B]=K,z!==void 0&&z!==B)throw RangeError(JX);W&&(B=t0("month",B,1,w1,1),V=t0("day",V,1,w7(j!==void 0?j:G,B),J))}else{G=j===void 0&&W?CZ:K7(this,$),B=B7(this,$,G,J),V=Q2(this,$,B,G,J);let K=this.U(G);Q=B===K,X=O7(B,K);let F=this.N(X,Q,V);if(!F)throw RangeError(G2);[G,B]=F}return w6(X$(this.P(G,B,V)),this.id||q)},fields($){return L7(this)&&$.includes("year")?[...$,...T7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return V7(J,Z,nJ),L7(this)&&(V7(J,Z,BF),this.id===xZ&&V7(J,Z,VF,T7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:kJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+e0(j)+(z?"L":""))(W,Y)},dayOfWeek:g2,daysInWeek(){return 7}},JU={dayOfYear:kJ,h:q2,q:SZ},WU=Object.assign({},JU,{weekOfYear:e9,yearOfWeek:$z,R($){function Z(F){return(7-F<W?7:0)-F}function J(F){let D=v2(K+F),U=F||1,O=Z(D3(Q+D*U,7));return B=(D+(O-G)*U)/7}let W=this.id?1:4,Y=g2($),j=this.dayOfYear($),z=D3(Y-1,7),X=j-1,Q=D3(z-X,7),G=Z(Q),B,V=Math.floor((X-G)/7)+1,K=$.isoYear;return V?V>J(0)&&(V=1,K++):(V=J(-1),K--),[V,K,B]}}),YU={dayOfYear:kJ,h:D7,q:H3,weekOfYear:e9,yearOfWeek:$z,R(){return[]}},mZ=vV(Object.assign({},V2,WU,{h:q2,ee($){return this.id===_4?m2($):this.id===xZ?IF($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[CZ,$]},K:q7,U(){},L:y2,J:($)=>$*w1,j:w7,X:v2,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:SZ,_:($,Z,J)=>($+=p6(J,w1),(Z+=x7(J,w1))<1?($--,Z+=w1):Z>w1&&($++,Z-=w1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},V2,YU,{h:D7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=C6.call(this,$);return[O7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=D7.call(this,{isoYear:CZ,isoMonth:w1,isoDay:31}),z=C6.call(this,W),X=Y===z;(z$($,O7(Y,z))||z$(Number(Z),Number(X))||z$(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,B=C6.call(this,G),V=g6($,Z,B);if(Z===(V===B)&&J<=z2.call(this,G,V))return[G,V]}},K($){let Z=A6.call(this,$);return Z>A6.call(this,$-1)&&Z>A6.call(this,$+1)},U:C6,L:S6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=S6.call(this,z+Y);return j},j:z2,X:A6,P($,Z,J){return s6(H3.call(this,$,Z,J))},q:H3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(M4);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}})),Q$="numeric",hZ=["timeZoneName"],RX={month:Q$,day:Q$},QW={year:Q$,month:Q$},GW=Object.assign({},QW,{day:Q$}),KW={hour:Q$,minute:Q$,second:Q$},BW=Object.assign({},GW,KW),jU=Object.assign({},BW,{timeZoneName:"short"}),zU=Object.keys(QW),XU=Object.keys(RX),QU=Object.keys(GW),GU=Object.keys(KW),VW=["dateStyle"],KU=zU.concat(VW),BU=XU.concat(VW),FW=QU.concat(VW,["weekday"]),y3=GU.concat(["dayPeriod","timeStyle"]),UW=FW.concat(y3),VU=UW.concat(hZ),FU=hZ.concat(y3),UU=hZ.concat(FW),DU=hZ.concat(["day","weekday"],y3),OU=hZ.concat(["year","weekday"],y3),LU={},DW=[n$(UW,BW),t6],kX=[n$(VU,jU),t6,0,($,Z)=>{let J=T0($.timeZone);if(Z&&T0(Z.timeZone)!==J)throw RangeError(YX);return J}],OW=[n$(UW,BW,hZ),b0],LW=[n$(FW,GW,FU),b0],MW=[n$(y3,KW,UU),($)=>K$($)/O1],HW=[n$(KU,QW,DU),b0,1],TW=[n$(BU,RX,OU),b0,1],F2;function H1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(lJ);yX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...B){return Q.call(this,X(this),...B)},N7(G))}function X(Q){let G=x0(Q);if(!G||G.branding!==$)throw TypeError(lJ);return G}return Object.defineProperties(j.prototype,{...D2(J1(z,J)),...h$(J1(z,W)),...h6("Temporal."+$)}),Object.defineProperties(j,{...h$(Y),...N7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return yX(G,Q),G},X]}function mX($){return $=$.concat("id").sort(),(Z)=>{if(!O2(Z,$))throw TypeError(WX);return Z}}function uZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(ez);return $}function b4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,Q=X===a$||Z.includes(X)?z:w0(j);return Y[W](Q)};return J}function _W($){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(fU),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(ZX)}function g3({calendar:$}){return typeof $=="string"?new kW($):$}function fX($,Z){if(Z=X0(Z),O0($)){let W=x0($);if(W&&W.branding===gZ)return g(Z),W;let Y=cX($);return qJ(v4(Y||q),!Y,$,Z)}let J=x9(mZ,$);return g(Z),J}function hX($,Z,J){return W=Z.call($,f0(L0(J))),JJ(I3(W));var W}function R4($,Z=iX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=w(Z[Y],$,MX($[Y]));return W}function s($,Z){return typeof $=="string"?S4($):R4($,Z)}function B0($){return s($,NW)}function L1($){if(O0($)){let Z=x0($);if(Z)switch(Z.branding){case C4:return Z;case c1:return L0(Z.epochNanoseconds)}}return T9($)}function wX($,Z,J){let W=Z.l(L1(J).epochNanoseconds,$);return W?f0(L0(W)):null}function a($){return O0($)?(x0($)||{}).timeZone||mU($):((Z)=>B4(E9(W0(Z))))($)}function L$($,Z){if(O0($)){let J=x0($)||{};switch(J.branding){case x4:return g(Z),J;case r$:return g(Z),j1(J);case c1:return g(Z),pJ(B0,J)}return Qz($,Z)}return g(Z),C9($)}function IW($){return $===void 0?void 0:L$($)}function pZ($,Z){if(Z=X0(Z),O0($)){let W=x0($);return W&&W.branding===vZ?(g(Z),W):wJ(q4(m3($)),$,Z)}let J=I9(mZ,$);return g(Z),J}function M$($,Z){if(Z=X0(Z),O0($)){let W=x0($)||{};switch(W.branding){case r$:return g(Z),W;case a$:return g(Z),Q0({...W,...Z1});case c1:return g(Z),mJ(B0,W)}return Xz(y4(m3($)),$,Z)}let J=_9($);return g(Z),J}function w0($,Z){if(Z=X0(Z),O0($)){let W=x0($)||{};switch(W.branding){case a$:return g(Z),W;case r$:return g(Z),G0(W);case c1:return g(Z),hJ(B0,W)}return fJ(y4(m3($)),$,Z)}let J=G4($);return g(Z),J}function pX($,Z,J){return W1(Z.call($,j0(G0(J,$))))}function T1($){return(Z)=>typeof Z=="string"?mZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=w(W[z],J,J[z]);return j})(Z,$)}function Y0($){if(O0($)){let Z=x0($);return Z&&Z.branding===A4?Z:Gz($)}return A9($)}function v3($){if($!==void 0){if(O0($)){let Z=x0($)||{};switch(Z.branding){case c1:case a$:return Z;case r$:return G0(Z)}let J=m3($);return{...jz(a,s,y4(J),$),calendar:J}}return P9($)}}function m3($){return cX($)||q}function cX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return O0($)?(x0($)||{}).calendar||$D($):((Z)=>A3(S9(W0(Z))))($)}function cZ($,Z){if(Z=X0(Z),O0($)){let J=x0($);if(J&&J.branding===c1)return x3(Z),J;let W=m3($);return zz(a,s,y4(W),W,$,Z)}return N9($,Z)}function qX($){return J1((Z)=>(J)=>Z(PW(J)),$)}function PW($){return R0($,B0)}function MU(){let $=O$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(O$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);fW.set(this,((z,X={})=>{let Q=new O$(z,X),G=Q.resolvedOptions(),B=G.locale,V=p0(Object.keys(X),G),K=m0(PU),F=(...D)=>{let U,O=D.map((L,P)=>{let H=x0(L),I=(H||{}).branding;if(P&&U&&U!==I)throw TypeError(zX);return U=I,H});return U?K(U)(B,V,...O):[Q,...D]};return F.u=Q,F})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&HU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||TU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function HU($){return function(...Z){let J=fW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function TU($){return function(...Z){return fW.get(this).u[$](...Z)}}function PU($){let Z=NU[$];if(!Z)throw TypeError(jX($));return m1(Z,m0(cJ))}var NU={Instant:DW,PlainDateTime:OW,PlainDate:LW,PlainTime:MW,PlainYearMonth:HW,PlainMonthDay:TW},_U=m1(DW),IU=m1(kX),xU=m1(OW),CU=m1(LW),AU=m1(MW),SU=m1(HW),EU=m1(TW),xW={era:_2,eraYear:C7,year:I3,month:W1,daysInMonth:W1,daysInYear:W1,inLeapYear:LX,monthsInYear:W1},f4={monthCode:W0},CW={day:W1},dX={dayOfWeek:W1,dayOfYear:W1,weekOfYear:I2,yearOfWeek:C7,daysInWeek:W1},uX=Object.assign({},xW,f4,CW,dX),k4=new WeakMap,x0=k4.get.bind(k4),yX=k4.set.bind(k4),bU={...b4(xW,[vZ]),...b4(dX,[]),...b4(f4,[vZ,gZ]),...b4(CW,[gZ])},AW=_W(uX),RU=_W({...xW,...f4}),kU=_W({...f4,...CW}),h3={calendarId:($)=>T0($.calendar)},fU=J1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](j0(G0(J,W))))},uX),wU=N3(($)=>(Z)=>Z[$],h.concat("sign")),SW=N3(($,Z)=>(J)=>J[X1[Z]],p1),lX={epochSeconds:i2,epochMilliseconds:t6,epochMicroseconds:s2,epochNanoseconds:n2},p3=w(_7,new Set(["branding"])),[qU,dZ,yU]=H1(gZ,w(_z,I0),{...h3,...kU},{getISOFields:p3,getCalendar:g3,with($,Z,J){return dZ(Uz(rU,$,this,uZ(Z),J))},equals:($,Z)=>d9($,fX(Z)),toPlainDate($,Z){return j0(vz(c3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=EU(Z,J,$);return W.format(Y)},toString:r7,toJSON:($)=>r7($),valueOf:P$},{from:($,Z)=>dZ(fX($,Z))}),iX={getOffsetNanosecondsFor:hX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(Q0(J,q)))].map((j)=>gU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),WJ(s0(i0(W[0],W[Y-1])))),W}},NW={getOffsetNanosecondsFor:hX},[vU,f0,gU]=H1(C4,Mz,lX,{add:($,Z)=>f0(YJ(0,$,Y0(Z))),subtract:($,Z)=>f0(YJ(1,$,Y0(Z))),until:($,Z,J)=>n(xJ(0,$,L1(Z),J)),since:($,Z,J)=>n(xJ(1,$,L1(Z),J)),round:($,Z)=>f0(r2($,Z)),equals:($,Z)=>g9($,L1(Z)),toZonedDateTime($,Z){let J=v1(Z);return K0(gJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>K0(gJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=_U(Z,J,$);return W.format(Y)},toString:($,Z)=>i7(a,B0,$,Z),toJSON:($)=>i7(a,B0,$),valueOf:P$},{from:($)=>f0(L1($)),fromEpochSeconds:($)=>f0(hz($)),fromEpochMilliseconds:($)=>f0(pz($)),fromEpochMicroseconds:($)=>f0(cz($)),fromEpochNanoseconds:($)=>f0(dz($)),compare:($,Z)=>NJ(L1($),L1(Z))}),[w4,MP]=H1("TimeZone",($)=>{let Z=y9($);return{branding:"TimeZone",id:Z,o:S4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(M$(Z)).map((J)=>f0(L0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(L1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=L1(Z).epochNanoseconds,W=R4(this,NW).getOffsetNanosecondsFor(J);return d$(W)},getPlainDateTimeFor($,Z,J=q){let W=L1(Z).epochNanoseconds,Y=R4(this,NW).getOffsetNanosecondsFor(W);return _0(Q0(V$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=M$(Z),Y=y7(J),j=R4(this);return f0(L0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>wX(1,$,Z),getPreviousTransition:({o:$},Z)=>wX(-1,$,Z),equals($,Z){return!!F4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new w4(Z):Z}}),mU=mX(Object.keys(iX)),[hU,H$]=H1(x4,Iz,SW,{getISOFields:p3,with($,Z,J){return H$(Dz(this,uZ(Z),J))},add:($,Z)=>H$(GJ(0,$,Y0(Z))),subtract:($,Z)=>H$(GJ(1,$,Y0(Z))),until:($,Z,J)=>n(bJ(0,$,L$(Z),J)),since:($,Z,J)=>n(bJ(1,$,L$(Z),J)),round:($,Z)=>H$($9($,Z)),equals:($,Z)=>u9($,L$(Z)),toZonedDateTime:($,Z)=>K0(gz(a,w0,s,$,Z)),toPlainDateTime:($,Z)=>_0(mz($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=AU(Z,J,$);return W.format(Y)},toString:t7,toJSON:($)=>t7($),valueOf:P$},{from:($,Z)=>H$(L$($,Z)),compare:($,Z)=>V4(L$($),L$(Z))}),[pU,T$,cU]=H1(vZ,w(Nz,I0),{...h3,...RU},{getISOFields:p3,getCalendar:g3,with($,Z,J){return T$(Fz(aU,$,this,uZ(Z),J))},add:($,Z,J)=>T$(QJ(vX,0,$,Y0(Z),J)),subtract:($,Z,J)=>T$(QJ(vX,1,$,Y0(Z),J)),until:($,Z,J)=>n(EJ(gX,0,$,pZ(Z),J)),since:($,Z,J)=>n(EJ(gX,1,$,pZ(Z),J)),equals:($,Z)=>c9($,pZ(Z)),toPlainDate($,Z){return j0(yz(c3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=SU(Z,J,$);return W.format(Y)},toString:a7,toJSON:($)=>a7($),valueOf:P$},{from:($,Z)=>T$(pZ($,Z)),compare:($,Z)=>i$(pZ($),pZ(Z))}),[dU,_0]=H1(r$,w(Tz,I0),{...h3,...AW,...SW},{getISOFields:p3,getCalendar:g3,with($,Z,J){return _0(Bz(c3,$,this,uZ(Z),J))},withCalendar:($,Z)=>_0(L4($,I0(Z))),withPlainDate:($,Z)=>_0(sz($,w0(Z))),withPlainTime:($,Z)=>_0(iz($,IW(Z))),add:($,Z,J)=>_0(zJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>_0(zJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(AJ(M1,0,$,M$(Z),J)),since:($,Z,J)=>n(AJ(M1,1,$,M$(Z),J)),round:($,Z)=>_0(e2($,Z)),equals:($,Z)=>h9($,M$(Z)),toZonedDateTime:($,Z,J)=>K0(Ez(s,$,a(Z),J)),toPlainDate:($)=>j0(G0($)),toPlainTime:($)=>H$(j1($)),toPlainYearMonth($){return T$(bz(q4,$,this))},toPlainMonthDay($){return dZ(Rz(v4,$,this))},toLocaleString($,Z,J){let[W,Y]=xU(Z,J,$);return W.format(Y)},toString:n7,toJSON:($)=>n7($),valueOf:P$},{from:($,Z)=>_0(M$($,Z)),compare:($,Z)=>IJ(M$($),M$(Z))}),[uU,j0,sX]=H1(a$,w(Pz,I0),{...h3,...AW},{getISOFields:p3,getCalendar:g3,with($,Z,J){return j0(Vz(c3,$,this,uZ(Z),J))},withCalendar:($,Z)=>j0(L4($,I0(Z))),add:($,Z,J)=>j0(XJ(e$,0,$,Y0(Z),J)),subtract:($,Z,J)=>j0(XJ(e$,1,$,Y0(Z),J)),until:($,Z,J)=>n(SJ(M1,0,$,w0(Z),J)),since:($,Z,J)=>n(SJ(M1,1,$,w0(Z),J)),equals:($,Z)=>p9($,w0(Z)),toZonedDateTime($,Z){let J=!O0(Z)||Z instanceof w4?{timeZone:Z}:Z;return K0(kz(a,L$,s,$,J))},toPlainDateTime:($,Z)=>_0(fz($,IW(Z))),toPlainYearMonth($){return T$(wz(q4,$,this))},toPlainMonthDay($){return dZ(qz(v4,$,this))},toLocaleString($,Z,J){let[W,Y]=CU(Z,J,$);return W.format(Y)},toString:o7,toJSON:($)=>o7($),valueOf:P$},{from:($,Z)=>j0(w0($,Z)),compare:($,Z)=>i$(w0($),w0(Z))}),EW={fields($,Z,J){return[...Z.call($,J)]}},nX=Object.assign({dateFromFields($,Z,J,W){return sX(Z.call($,Object.assign(Object.create(null),J),W))}},EW),oX=Object.assign({yearMonthFromFields($,Z,J,W){return cU(Z.call($,Object.assign(Object.create(null),J),W))}},EW),aX=Object.assign({monthDayFromFields($,Z,J,W){return yU(Z.call($,Object.assign(Object.create(null),J),W))}},EW),bW={mergeFields($,Z,J,W){return v1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},lU=Object.assign({},nX,bW),iU=Object.assign({},oX,bW),sU=Object.assign({},aX,bW),RW={dateAdd($,Z,J,W,Y){return sX(Z.call($,j0(G0(J,$)),n($0(W)),Y))}},rX=Object.assign({},RW,{dateUntil($,Z,J,W,Y,j){return eU(Z.call($,j0(G0(J,$)),j0(G0(W,$)),Object.assign(Object.create(null),j,{largestUnit:k3[Y]})))}}),nU=Object.assign({},RW,{day:pX}),oU=Object.assign({},rX,{day:pX}),q4=T1(oX),y4=T1(nX),v4=T1(aX),aU=T1(iU),c3=T1(lU),rU=T1(sU),e$=T1(RW),M1=T1(rX),vX=T1(nU),gX=T1(oU),[tU,n,eU]=H1(A4,xz,{...wU,blank:L9},{with:($,Z)=>n(Oz($,Z)),negated:($)=>n(X4($)),abs:($)=>n(O9($)),add:($,Z,J)=>n(UJ(v3,M1,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>n(UJ(v3,M1,s,1,$,Y0(Z),J)),round:($,Z)=>n(D9(v3,M1,s,$,Z)),total:($,Z)=>a2(v3,M1,s,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):J4($)},toString:J4,toJSON:($)=>J4($),valueOf:P$},{from:($)=>n(Y0($)),compare:($,Z,J)=>v9(v3,e$,s,Y0($),Y0(Z),J)}),tX={toString:($)=>$.id,toJSON:($)=>$.id,...bU,dateAdd:({id:$,o:Z},J,W,Y)=>j0(G0(Z.dateAdd(w0(J),Y0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>n($0($.dateUntil(w0(Z),w0(J),p2(W)))),dateFromFields:({id:$,o:Z},J,W)=>j0(fJ(Z,J,W,N2($))),yearMonthFromFields:({id:$,o:Z},J,W)=>T$(wJ(Z,J,W,T2($))),monthDayFromFields:({id:$,o:Z},J,W)=>dZ(qJ(Z,0,J,W,P2($))),fields({o:$},Z){let J=new Set(z1),W=[];for(let Y of Z){if(W0(Y),!J.has(Y))throw RangeError(uJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(I7(A7(Z)),I7(A7(J)))},[kW]=H1("Calendar",($)=>{let Z=t9($);return{branding:"Calendar",id:Z,o:mZ(Z)}},{id:($)=>$.id},tX,{from($){let Z=I0($);return typeof Z=="string"?new kW(Z):Z}}),$D=mX(Object.keys(tX).slice(4)),[ZD,K0]=H1(c1,w(Hz,I0,a),{...lX,...h3,...qX(AW),...qX(SW),offset:($)=>d$(PW($).offsetNanoseconds),offsetNanoseconds:($)=>PW($).offsetNanoseconds,timeZoneId:($)=>T0($.timeZone),hoursInDay:($)=>Z9(s,$)},{getISOFields:($)=>F9(B0,$),getCalendar:g3,getTimeZone:({timeZone:$})=>typeof $=="string"?new w4($):$,with($,Z,J){return K0(Kz(c3,s,$,this,uZ(Z),J))},withCalendar:($,Z)=>K0(L4($,I0(Z))),withTimeZone:($,Z)=>K0(nz($,a(Z))),withPlainDate:($,Z)=>K0(lz(s,$,w0(Z))),withPlainTime:($,Z)=>K0(uz(s,$,IW(Z))),add:($,Z,J)=>K0(jJ(e$,s,0,$,Y0(Z),J)),subtract:($,Z,J)=>K0(jJ(e$,s,1,$,Y0(Z),J)),until:($,Z,J)=>n($0(CJ(M1,s,0,$,cZ(Z),J))),since:($,Z,J)=>n($0(CJ(M1,s,1,$,cZ(Z),J))),round:($,Z)=>K0(t2(s,$,Z)),startOfDay:($)=>K0(J9(s,$)),equals:($,Z)=>m9($,cZ(Z)),toInstant:($)=>f0(Cz($)),toPlainDateTime:($)=>_0(mJ(B0,$)),toPlainDate:($)=>j0(hJ(B0,$)),toPlainTime:($)=>H$(pJ(B0,$)),toPlainYearMonth($){return T$(Az(q4,$,this))},toPlainMonthDay($){return dZ(Sz(v4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=IU(Z,J,$);return W.format(Y)},toString:($,Z)=>s7(B0,$,Z),toJSON:($)=>s7(B0,$),valueOf:P$},{from:($,Z)=>K0(cZ($,Z)),compare:($,Z)=>_J(cZ($),cZ(Z))}),JD=Object.defineProperties({},{...h6("Temporal.Now"),...h$({timeZoneId:()=>h1(),instant:()=>f0(L0(E3())),zonedDateTime:($,Z=h1())=>K0(N0(E3(),a(Z),I0($))),zonedDateTimeISO:($=h1())=>K0(N0(E3(),a($),q)),plainDateTime:($,Z=h1())=>_0(Q0(qZ(B0(a(Z))),I0($))),plainDateTimeISO:($=h1())=>_0(Q0(qZ(B0(a($))),q)),plainDate:($,Z=h1())=>j0(G0(qZ(B0(a(Z))),I0($))),plainDateISO:($=h1())=>j0(G0(qZ(B0(a($))),q)),plainTimeISO:($=h1())=>H$(j1(qZ(B0(a($)))))})}),lZ=Object.defineProperties({},{...h6("Temporal"),...h$({PlainYearMonth:pU,PlainMonthDay:qU,PlainDate:uU,PlainTime:hU,PlainDateTime:dU,ZonedDateTime:ZD,Instant:vU,Calendar:kW,TimeZone:w4,Duration:tU,Now:JD})}),WD=MU(),fW=new WeakMap,YD=Object.defineProperties(Object.create(Intl),h$({DateTimeFormat:WD}));var g4="x-gemi-socket";var IP="gemi.v1",eX="/__gemi/socket",xP=/^[A-Za-z0-9_-]{1,32}$/,CP={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function bP($){return $}function $Q(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:eX,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 jD,randomBytes as zD}from"crypto";function XD($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(jD("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var QD="__control",wW=250,GD=1e4,KD=15000;class qW{config;prefix;controlChannel;instanceId=zD(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??XD(),this.controlChannel=this.prefix+QD,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=d3((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 $})(),KD,"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 (${ZQ(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(GD,wW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(wW,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;d3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${ZQ(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??BD(Math.min(Z,wW));await d3(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 d3(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 d3(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 d3($,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 BD($){return new Promise((Z)=>setTimeout(Z,$))}function ZQ($){return $ instanceof Error?$.message:String($)}import{createHmac as VD,hkdfSync as FD,randomBytes as JQ}from"crypto";function WQ($){return VD("sha256",UD()).update($).digest("base64url").slice(0,22)}var m4=null;function UD(){let $=process.env.SECRET||void 0;if(m4&&m4.secret===$)return m4.key;let Z=$?Buffer.from(FD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):JQ(32);return m4={secret:$,key:Z},Z}function qP(){return JQ(16).toString("base64url")}var DD=/^[A-Za-z0-9_-]{8,64}$/;function yW($){return typeof $==="string"&&DD.test($)}function YQ($,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 zQ extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=P1($Q(),$),this.driver=MD(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 u3(this,h4($,Z[0]),null)}toUser($){return new u3(this,{topic:FZ($),pattern:F0},null)}toOthers($){return new XQ(this,LD($))}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){b5(Z);let Y;try{Y=YQ($.topic,Z,J,W?WQ(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=OD($);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 zQ(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 u3{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 XQ{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new u3(this.manager,h4($,Z[0]),this.except)}toUser($){return new u3(this.manager,{topic:FZ($),pattern:F0},this.except)}}function h4($,Z){if(E5($))return{topic:S8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:K3($,Z??{}),pattern:$};if($===F0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:S8($)}}function OD($){if($&&typeof $==="object"&&"user"in $)return{user:FZ($.user).slice(F0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:h4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function LD($){if($===null||$===void 0)return null;if(typeof $==="string")return yW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(g4);return yW(J)?J:null}function MD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new jQ;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new qW({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 vW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class HD{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 gW,createHmac as TD,randomBytes as QQ,timingSafeEqual as BQ}from"crypto";var i3=600,p4="gemi_oauth",PD=`__Host-${p4}`;function sZ($,Z=p4){if(Z===p4)return $?PD:p4;return $?`__Host-${Z}`:Z}function l3($){return $.toString("base64url")}function VQ($){return TD("sha256",MZ()).update(`gemi-oauth-state:${$}`).digest()}function GQ($,Z){let J=gW("sha256").update($).digest(),W=gW("sha256").update(Z).digest();return BQ(J,W)&&$.length===Z.length}function c4($,Z=Date.now(),J={}){let W=l3(QQ(32)),Y=l3(QQ(32)),j=ND(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+i3*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:_D(z)}}function ND($){return l3(gW("sha256").update($).digest())}function _D($){let Z=l3(Buffer.from(JSON.stringify($)));return`${Z}.${l3(VQ(Z))}`}function ID($){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=VQ(J);if(W.length!==Y.length||!BQ(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 N$=new Map,KQ=1e4;function xD($,Z,J){if(N$.size>=KQ){for(let[W,Y]of N$)if(Y<=J)N$.delete(W);while(N$.size>=KQ){let W=N$.keys().next().value;if(W===void 0)break;N$.delete(W)}}N$.set($,Z)}function d4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=ID($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=GQ(J.state,$.returnedState),Y=GQ(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(N$.has(J.state))return{ok:!1,reason:"invalid_state"};return xD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var mW=new WeakMap;function AD($){let Z=mW.get($);if(!Z)Z=$(CD(32).toString("hex")),mW.set($,Z),Z.catch(()=>mW.delete($));return Z}async function u4($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await AD($.hashPassword))}catch{}return!1}async function $Z($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class pW extends Error{}function hW($){return typeof $==="string"&&$!==""?$:null}function FQ($){return q$($)}var SD=256;function UQ($){return typeof $==="string"&&$!==""&&$.length<=SD?$:null}function DQ($){let{password:Z,code:J,...W}=$;return W}var i4="intended_url";function MQ($){if($.cookies.get(i4))$.ctx().setCookie(i4,"",{maxAge:-1})}function OQ($){let Z=$.cookies.get(i4);if(!Z)return null;MQ($);try{return V1(decodeURIComponent(Z),"")||null}catch{return null}}class cW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class HQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class TQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function l4(){throw new H0("Not found",{status:404})}async function d1($,Z){if(!await R1(M(E).config[$],Z))l4()}async function s3($,Z,J,W){let{config:Y}=M(E),j={signIn:"sign-in",signUp:"sign-up",forgot:"forgot",reset:"reset"}[$];await y$(j,Z,J,Y.passwordLimits?.[$]??{},Y.rateLimitKey,W)}async function LQ($,Z,J){let{config:W}=M(E);await s3("signIn",q$($),J,async(Y)=>{if(Y==="perEmail"&&typeof Z==="string")await u4(W,Z,null)})}async function nZ($){return await R1(M(E).config.verifyEmail,$)}class Z0 extends V3{async me(){let $=await q0.user();if(!$)throw new i8;return $}async verifyEmail($=new C){await d1("password",$);let Z=await $.input(),{userProvider:J}=M(E),W=hW(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 C){let Z=M(E),{userProvider:J}=Z;if(!await R1(Z.config.magicLink,$)&&!await R1(Z.config.emailCode.enabled,$))l4();let W=hW($.search.get("token")),Y=null;try{Y=q$(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,M(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){await d1("magicLink",$);let Z=M(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=q$(W),z=UQ(Y);if(await y$("verify",j,$,Z.config.emailCode.verifyLimit,Z.config.rateLimitKey),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new cW){await d1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await LQ(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 d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signIn($=new cW){await d1("password",$);let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E);await LQ(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 d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON(),{req:$}),await $Z(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signUp(){let $=M(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest;await d1("password",W);let Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:DQ(Y.toJSON()),req:W},B=FQ(j);if(await s3("signUp",B,W),!B)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(B,!1))throw new d({email:["Email address already exists"]});let K=await J.hashPassword(z),F=M(c).detectLocale(W),D;if(Q)D=await Z.findInvitation(Q,B);let U,O="";if(D)U=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:B,name:X,password:K,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:D.organizationId,userId:L.id,organizationRole:D.role}),await J.onUserCreated(L,G),L});else{if(O=await J.generateEmailVerificationToken(B),typeof J.verifyEmail==="function"&&!await nZ(W))O="";U=await Z.transaction(async()=>{let L=await Z.createUser({email:B,name:X,password:K,verificationToken:O,locale:F});return await J.onUserCreated(L,G),L})}return await J.onSignUp(U,O,W.search.toJSON(),{req:W}),U}async signOut($=new C){let Z=E$($),J=M(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(E).accessTokenCookieOptions($,new Date(0))),M(E).cookieDomain($))$.ctx().setCookie("access_token","",{...M(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)ED(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user,{req:$});return{}}async forgotPassword($=new HQ){await d1("password",$);let Z=await $.input(),J=FQ(Z.get("email"));if(await s3("forgot",J,$),!J)return{};let{userProvider:W,config:Y}=M(E),j=await W.findUserByEmailAddress(J,await nZ($));if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z,{req:$}),{}}async resetPassword($=new TQ){await d1("password",$);let{userProvider:Z,config:J}=M(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=hW(j);await s3("reset",null,$);let X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(lZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(lZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,await nZ($));if(!G)throw new d({email:["User not found"]});let B=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:B}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G,{req:$}),{}}async changePassword($=new C){await d1("password",$);let{userProvider:Z,config:J}=M(E),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(await s3("signIn",q$(W?.email),$),typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,await nZ($));if(!(typeof j==="string"&&await u4(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await TZ(J,Z,$);if(!Y){if(W)throw new H0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=UZ($.rawRequest),z=V1($.search.get(B1),"");if(z)$.ctx().setCookie(i4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else MQ($);let X=typeof Y.redirectUriFor==="function"?await Y.redirectUriFor($):void 0,{state:Q,codeChallenge:G,cookieValue:B}=c4(Z,Date.now(),X!==void 0?{redirectUri:X}:{});return $.ctx().setCookie(sZ(j),B,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:i3}),{destination:await Y.getRedirectUrl($,{state:Q,codeChallenge:G,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await TZ(Y.oauthProviders,Z,$);if(j&&!z)throw new H0("Not found",{status:404});let X=UZ($.rawRequest),Q=sZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let B=$.search.get("error");if(B)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");let V=d4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(V.payload.redirectUri!==void 0&&typeof z.redirectUriFor==="function"){let N=await z.redirectUriFor($);if(N!==void 0&&N!==V.payload.redirectUri)return console.error("Authentication error: OAuth callback refused (redirect_mismatch)"),this.oauthFailure($,"redirect_mismatch")}if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(N){if(N instanceof vW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:F,username:D,providerId:U,emailVerified:O}=K??{},L=typeof K?.email==="string"?K.email:void 0,P=L?N6(L):null,H=U?await W.findUserBySocialAccount(Z,U):null,I="signin",b=!H&&!P&&!L&&!!U&&z.createUsersWithoutEmail===!0;if(!H&&b){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{H=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:F,username:D,locale:M(c).detectLocale($),req:$}),I="signup"}catch(N){let v=await W.findUserBySocialAccount(Z,U);if(!v)throw N;H=v}}if(!H){if(!P)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":U?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let v=await this.linkOAuthAccount({provider:Z,providerId:U,email:P,rawEmail:L,name:F,username:D,locale:N,req:$,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(v==="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(v==="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(v)H=v.user,I=v.action}catch(v){let _=U?await W.findUserBySocialAccount(Z,U):null;if(!_)throw v;H=_}if(!H)return this.oauthFailure($,"account_conflict")}let S=await J.createOrUpdateSessionV2({email:H.email,id:H.id});if($.ctx().setCookie("access_token",S.token,M(E).accessTokenCookieOptions($,S.expiresAt)),I==="signup")await Y.onSignUp(H,"",$.search.toJSON(),{req:$});else await Y.onSignIn(H,$.search.toJSON(),{req:$});await $Z(J.config,{session:S,user:H,isNewUser:I==="signup",method:"oauth",req:$});let R=OQ($)??Y.redirectPath,f=Y.oauthCompleteProfilePath?V1(Y.oauthCompleteProfilePath,""):"";if(f&&!H.email){let N=new URL(f,"http://gemi.invalid");N.searchParams.set(B1,R),R=`${N.pathname}${N.search}${N.hash}`}return{session:S,redirectTo:R}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{},req:$.req}),W})}oauthFailure($,Z){let J=OQ($),W=M(E).config.oauthFailurePath;if(W){let Y=V1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(B1,J);S1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=M(E),B=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await Q.findUserByEmailAddress(W,!1),K=Y?.trim();if(!V&&K&&K!==W)V=await Q.findUserByEmailAddress(K,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let D=await Q.findSocialAccounts(V.id,Z);if(D.some((O)=>O.providerId===J))return{user:V,action:"signin"};if(D.some((O)=>O.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await Q.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(B(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let D=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(B(D.id));return await G.onUserCreated(D,{method:"oauth",input:{},req:$.req}),D}),action:"signup"}}async createMagicLinkToken($=new C){await d1("magicLink",$);let Z=await $.input(),J=q$(Z.get("email")),W=M(E),{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:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q,req:$}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(E),J=Z.config.emailCode;if(!await R1(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 d({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 C){let Z=M(E),{userProvider:J,config:W}=Z;if(!await R1(W.emailCode.enabled,$))l4();let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=N6(j),G=UQ(z);if(await y$("verify",Q,$,W.emailCode.verifyLimit,W.rateLimitKey),!Q||!G)throw new d({code:["invalid_code"]});let B=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(B.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(B.status!=="ok")throw new d({code:["invalid_code"]});let V=B.row,K=await J.findUserByEmailAddress(Q,!1),F=!1;if(K){if(!await Z.claimOneTimeCode(Q,V.id))throw new d({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let U=M(c).detectLocale($);try{K=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,V.id))throw new pW;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(O,{method:"email-code",input:DQ(Y.toJSON()),req:$}),O}),F=!0}catch(O){if(O instanceof pW)throw new d({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,V.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:Q,id:K.id});return $.ctx().setCookie("access_token",D.token,M(E).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON(),{req:$}),await $Z(Z.config,{session:D,isNewUser:F,method:"email-code",req:$}),{session:D,isNewUser:F}}}function ED($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var PQ="gemi_oauth_connection";class s4 extends V3{async connect($=new C){let Z=String($.params.provider??""),W=M(n3).providers[Z],Y=await q0.user(),j=V1($.search.get(B1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=UZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=c4(NQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(sZ(z,PQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:i3}),S1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:_Q($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(n3),W=await q0.user(),Y=UZ($.rawRequest),j=sZ(Y,PQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=d4({provider:NQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let B=$.search.get("error");if(B)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(Q,Z,"missing_code");try{let K=await G.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:_Q($,Z,G.config.redirectUri)}),F=await J.save(W,Z,K);await M(E).config.onConnected({user:W,provider:Z,connection:F,profile:K.profile??null,req:$})}catch(K){if(K instanceof IQ)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(Q,Z,K.providerError??K.code);throw K}return this.finish(Q,Z)}finish($,Z,J){let W=$||V1(M(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw S1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function NQ($){return`connection:${$}`}function _Q($,Z,J){if(J)return J;return`${ZZ()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function xQ($){return $.magicLink!==!1||Z7($.emailCode?.enabled)}function CQ($){return Object.keys($.oauthProviders??{}).length>0}function AQ($={}){let Z=[];if(xQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:Z7($.emailCode?.enabled)&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(CQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class SQ extends E1{middlewares=["cache:private"];routes={"/:provider":this.redirect([s4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([s4,"callback"]).middleware([F6,"auth"])}}function EQ($={}){let Z=xQ($),J=CQ($);class W extends E1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[Z0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[Z0,"oauthCallback"])}}return class extends E1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[Z0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":SQ}}}class dW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post(Z0,"signIn"),"/sign-in-v2":this.post(Z0,"signInV2"),"/sign-up":this.post(Z0,"signUp"),"/sign-out":this.post(Z0,"signOut"),"/forgot-password":this.post(Z0,"forgotPassword"),"/reset-password":this.post(Z0,"resetPassword"),"/change-password":this.post(Z0,"changePassword"),"/verify-email":this.post(Z0,"verifyEmail"),"/me":this.get(Z0,"me").middleware(["auth"]),"/magic-link":this.post(Z0,"createMagicLinkToken"),"/sign-in-with-pin":this.post(Z0,"signInWithPin"),"/sign-in-with-pin-v2":this.post(Z0,"signInWithPinV2"),"/email-code":this.post(Z0,"requestEmailCode"),"/email-code/verify":this.post(Z0,"verifyEmailCode")}}class uW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(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 lW{}class iW extends lW{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 sN($){return $}function bQ(){return{driver:new iW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class V0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var bD=new Set([301,302,303,307,308]),RD="/api/__gemi__/services/image/";async function kQ($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=RQ($,Y);try{for(let z=0;;z++){let X=await kD(j,Z,W),Q=X.headers.get("location");if(bD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new V0(502,"The image redirects too many times");j=RQ(Q,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 wD(z,W)}}function RQ($,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 kD($,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(RD))throw new V0(403,"This image source is not allowed");if(fD($.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 b1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new V0(403,"This image source is not allowed");return b1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function fD($){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 wD($,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 sW extends C0{routes={"/resize":this.file(async()=>{let $=new C,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 fQ(400,"url query parameter is required");let X=M(wQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=ZZ();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let B;try{B=await kQ(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(F){if(F instanceof V0)return fQ(F.status,F.message);throw F}let V=await X.resize(B.bytes,{height:Y,width:W,fit:j,quality:z}),K=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(B.cacheControl)K.set("Cache-Control",B.cacheControl);return new Response(new Uint8Array(V),{headers:K})})}}function fQ($,Z){return Response.json({error:Z},{status:$})}class wQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=bQ();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 nW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(qQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function Q_($){return $}function yQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function vQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function qD($){return"run"in $}function yD($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function vD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function gD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function mD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function gQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function hD($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function oW($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let B=j==="/"?"":j,V=Z==="/"?"":Z,K=hD((`${V}${B}`===""?"/":`${V}${B}`).replaceAll("//","/"));if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[K].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(mD(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(qD(z)){let X=z,Q=X.method,G=X.middlewares,B=X.run.bind(X);if(Y(j,Q,B,G,X.source),gQ(z))Y(j,"HEAD",B,G,X.source)}if(yD(z))for(let[X,Q]of Object.entries(z)){let G=Q,B=G.middlewares,V=G.run.bind(G);if(Y(j,X,V,B,G.source),X==="get"&&gQ(G))Y(j,"HEAD",V,B,G.source)}if(gD(z)){let X=new z,Q=oW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,B]of Object.entries(Q)){let V=G.replaceAll("//","/");W[V]={...W[V],...B}}}if(vD(z)){let{first:X,second:Q}=z;for(let[G,B]of Object.entries(X)){let V=B.middlewares,K=B.run.bind(B),[F,...D]=j.split("/").reverse();if(!F.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),G,K,V,B.source)}for(let[G,B]of Object.entries(Q)){let V=B.middlewares,K=B.run.bind(B);Y(j,G,K,V,B.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function o4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function aW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function rW($){let Z=o4($);return Z.length>1?Z.replace(/\/$/,""):Z}function mQ($,Z){return Z.map((J)=>({...J,path:rW(aW($,J.path))}))}function a4($){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=a4(j.routes);for(let[X,{exec:Q,middleware:G,segments:B,features:V,static:K}]of Object.entries(z)){let F=aW(J,X),D=(U)=>Y.run.call(Y,U,J);Z[o4(F)]={exec:[D,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:rW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...mQ(J,B)],...K?{static:K}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[o4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:rW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=a4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:B,features:V,static:K}]of Object.entries(j)){let F=aW(J,z);Z[o4(F)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:G,segments:mQ(J,B),...K?{static:K}:{}}}}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 tW="theme";function hQ($){return $==="light"||$==="dark"||$==="system"}function pQ($){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;
@@ -114,4 +114,4 @@ data: ${JSON.stringify(Z)}
114
114
  "deadline_at" BIGINT${W}
115
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 SK=191,EK=30000;class O8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class L8 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 X5{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=P1(xK(),$),this.store=ML(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(W3);return this.ownFeed??=new W3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){kK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;kK("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:zZ($.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 LL(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:RK(Z)})}cancel($,Z){return this.change($,I1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new O8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof L8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,I1,{status:"failed",error:Q instanceof L8?RK(Q):{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()+zZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new O8($);let z=null;for(;;){if(x1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await bK(z,Math.min(Q,X??1/0,EK),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 O8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=OL(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=zZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(x1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,bK(j,Math.min(z??1/0,EK))]);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 bK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function OL($,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 RK($){if(typeof $==="string")return{message:$};if($ instanceof L8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function kK($,Z){if(typeof Z!=="string"||Z===""||Z.length>SK)throw TypeError(`A run's ${$} is a string of 1 to ${SK} characters; got ${JSON.stringify(Z)}.`)}function LL($){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 ML($,Z){if($==="memory")return new J5;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(f1).connection();return new z5(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 fK extends m{static getFacadeAccessor(){return X5}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 wK extends m{static getFacadeAccessor(){return j$}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 K5{value;constructor($){this.value=$}}var HL=/^[A-Za-z_][A-Za-z0-9_$]*$/;function TL($){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"||!HL.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class M8{bound;constructor($){this.bound=$}get name(){return this.bound??k1()}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 G5(J.sql,(W)=>Q5(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=TL(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(l0()!==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 G5(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await Q5(j,()=>W(X));throw new K5(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K5)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-k6x35rn5.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=vK($,yK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=l0();if($===void 0)return;return k1()===this.name?$:void 0}connection($=this.name){return qK($),M(f1).connection($)}}var XZ=new M8;class gK extends m{static getFacadeAccessor(){return f1}static connection($){return new M8($)}static get sql(){return XZ.sql}static get dialect(){return XZ.dialect}static query($){return XZ.query($)}static execute($){return XZ.execute($)}static transaction($){return XZ.transaction($)}static readOnly($,Z){return XZ.readOnly($,Z)}static schema(){return XZ.schema()}static close(){return this.getFacadeRoot().close()}}export{K1 as ke,lK as le,a0 as me,X3 as ne,_8 as oe,BZ as pe,G3 as qe,C0 as re,X6 as se,s8 as te,n8 as ue,Nj as ve,Y$ as we,F1 as xe,k$ as ye,J0 as ze,$j as Ae,DZ as Be,_j as Ce,Ij as De,a8 as Ee,r8 as Fe,P6 as Ge,HZ as He,zV as Ie,mT as Je,wj as Ke,pj as Le,j7 as Me,cj as Ne,dj as Oe,UV as Pe,uj as Qe,z7 as Re,LV as Se,MV as Te,X7 as Ue,lj as Ve,ij as We,j$ as Xe,sj as Ye,NV as Ze,G7 as _e,w8 as $e,F6 as af,S1 as bf,k8 as cf,E1 as df,x$ as ef,G8 as ff,rG as gf,tG as hf,$L as if,i1 as jf,XA as kf,eG as lf,dY as mf,uY as nf,iY as of,JK as pf,YK as qf,jK as rf,XK as sf,GK as tf,KK as uf,qA as vf,BK as wf,B8 as xf,sY as yf,nY as zf,oY as Af,V8 as Bf,W3 as Cf,NK as Df,_K as Ef,u as Ff,K3 as Gf,g4 as Hf,IP as If,xP as Jf,CP as Kf,bP as Lf,$Q as Mf,qW as Nf,WQ as Of,qP as Pf,zQ as Qf,c0 as Rf,u3 as Sf,XQ as Tf,IK as Uf,US as Vf,Z5 as Wf,I1 as Xf,x1 as Yf,J5 as Zf,z5 as _f,DL as $f,O8 as ag,L8 as bg,X5 as cg,fK as dg,wK as eg,M8 as fg,gK as gg,vW as hg,HD as ig,lW as jg,iW as kg,sN as lg,bQ as mg,wQ as ng,Q6 as og,$$ as pg,Q_ as qg,yQ as rg,vQ as sg,OY as tg,eZ as ug,LY as vg,EI as wg,vI as xg,gI as yg,AO as zg,SY as Ag,wY as Bg,kO as Cg,bY as Dg,qO as Eg,e3 as Fg,qY as Gg,yG as Hg,Y8 as Ig,j8 as Jg,QC as Kg,GC as Lg,KC as Mg,Q1 as Ng,E as Og,q0 as Pg,G6 as Qg,y5 as Rg,zB as Sg,f5 as Tg,g5 as Ug,E8 as Vg,B6 as Wg,b8 as Xg,m5 as Yg,FB as Zg,UB as _g,l5 as $g,s5 as ah,o5 as bh,Jj as ch,Wj as dh,Yj as eh,g8 as fh,TB as gh,z0 as hh,Dj as ih,LZ as jh,Tj as kh};
116
116
 
117
- //# debugId=5AC165CC483A106E64756E2164756E21
117
+ //# debugId=CA4EDF318109CD9864756E2164756E21