vinojs 0.1.0 → 0.1.2
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.
- package/dist/client.mjs +1 -1
- package/dist/{compile-Lxl_tdxL.mjs → compile-glNMkyyx.mjs} +3 -47
- package/dist/compile-glNMkyyx.mjs.map +1 -0
- package/dist/{definePage-Ba4r-TFh.mjs → definePage--9Pz7rHs.mjs} +29 -7
- package/dist/definePage--9Pz7rHs.mjs.map +1 -0
- package/dist/defineServerFn-H-bz7xBX.mjs +47 -0
- package/dist/defineServerFn-H-bz7xBX.mjs.map +1 -0
- package/dist/factory-CVT0-OZw.d.mts +187 -0
- package/dist/factory-CVT0-OZw.d.mts.map +1 -0
- package/dist/factory.d.mts +2 -0
- package/dist/factory.mjs +153 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/vino.d.mts +4 -103
- package/dist/vino.d.mts.map +1 -1
- package/dist/vino.mjs +8 -3
- package/dist/vino.mjs.map +1 -1
- package/dist/vite.mjs +3 -2
- package/dist/vite.mjs.map +1 -1
- package/package.json +5 -1
- package/dist/compile-Lxl_tdxL.mjs.map +0 -1
- package/dist/definePage-Ba4r-TFh.mjs.map +0 -1
- package/examples/basic/dist/client/.assetsignore +0 -2
- package/examples/basic/dist/client/about.html +0 -1
- package/examples/basic/dist/client/admin.html +0 -1
- package/examples/basic/dist/client/assets/Counter-BvqMZKON.js +0 -1
- package/examples/basic/dist/client/assets/_slug_-CYpOSbrn.js +0 -1
- package/examples/basic/dist/client/assets/about-BZXRzUyv.js +0 -1
- package/examples/basic/dist/client/assets/admin-DRE7uh2s.js +0 -1
- package/examples/basic/dist/client/assets/client-B6nFkut5.js +0 -1
- package/examples/basic/dist/client/assets/client-pages-Bc6cNZAm.js +0 -2
- package/examples/basic/dist/client/assets/components-DX9r6vHn.js +0 -1
- package/examples/basic/dist/client/assets/components-DsWJ6F73.js +0 -2
- package/examples/basic/dist/client/assets/counter-DBpvln_F.js +0 -1
- package/examples/basic/dist/client/assets/dom-B5sHIJ1E.js +0 -1
- package/examples/basic/dist/client/assets/honoto-9UtdLp4J.js +0 -33
- package/examples/basic/dist/client/assets/honoto-client-DEh86_WZ.css +0 -1
- package/examples/basic/dist/client/assets/honoto-client.js +0 -2
- package/examples/basic/dist/client/assets/hooks-Cz6AT21d.js +0 -1
- package/examples/basic/dist/client/assets/jsx-dev-runtime-92VDsVyo.js +0 -1
- package/examples/basic/dist/client/counter.html +0 -1
- package/examples/basic/dist/client/index.html +0 -1
- package/examples/basic/dist/client/jobs.html +0 -1
- package/examples/basic/dist/ssr/.vite/manifest.json +0 -140
- package/examples/basic/dist/ssr/assets/_slug_-CY3-kffX.js +0 -46
- package/examples/basic/dist/ssr/assets/about-CTDjNhkO.js +0 -15
- package/examples/basic/dist/ssr/assets/admin-DvS-UGJx.js +0 -26
- package/examples/basic/dist/ssr/assets/constants-UoriGYcX-CUecBFMT.js +0 -6
- package/examples/basic/dist/ssr/assets/counter-DfIbc9Sp.js +0 -30
- package/examples/basic/dist/ssr/assets/honoto-CA313cVy.js +0 -2129
- package/examples/basic/dist/ssr/assets/jobs-D9hh-UO9.js +0 -42
- package/examples/basic/dist/ssr/assets/jsx-CgYLQazd.js +0 -1080
- package/examples/basic/dist/ssr/assets/jsx-dev-runtime-BlUda7H8.js +0 -742
- package/examples/basic/dist/ssr/assets/jsx-renderer-CzZcZPnS.js +0 -65
- package/examples/basic/dist/ssr/assets/layout-DYvLwr2u.js +0 -53
- package/examples/basic/dist/ssr/assets/pages-DB6jeyrt.js +0 -53
- package/examples/basic/dist/ssr/assets/rolldown-runtime-D7D4PA-g.js +0 -13
- package/examples/basic/dist/ssr/assets/ssr-hooks-CBQr0cdH.js +0 -7
- package/examples/basic/dist/ssr/index.js +0 -22
- package/examples/basic/dist/ssr/wrangler.json +0 -1
- package/examples/full/dist/client/.assetsignore +0 -2
- package/examples/full/dist/client/assets/BookmarkButton-py0xGxgl.js +0 -1
- package/examples/full/dist/client/assets/_slug_-DZUFsE9O.js +0 -1
- package/examples/full/dist/client/assets/auth-client-D2Wtuobe.js +0 -1
- package/examples/full/dist/client/assets/bun-sqlite-dialect-C7ftEUSI-CsHdUKBY.js +0 -1
- package/examples/full/dist/client/assets/client-B6nFkut5.js +0 -1
- package/examples/full/dist/client/assets/client-pages-fshKs747.js +0 -2
- package/examples/full/dist/client/assets/components-DX9r6vHn.js +0 -1
- package/examples/full/dist/client/assets/components-S_-rWrKi.js +0 -2
- package/examples/full/dist/client/assets/d1-sqlite-dialect-BZmaVTp8-FPCaMZqX.js +0 -1
- package/examples/full/dist/client/assets/default-query-compiler-CUdqIu1h.js +0 -1
- package/examples/full/dist/client/assets/dist-BoGTNvkC.js +0 -1
- package/examples/full/dist/client/assets/dom-DCd3wYW7.js +0 -1
- package/examples/full/dist/client/assets/factory-Bgf4EtLx.js +0 -8
- package/examples/full/dist/client/assets/honoto-client-BSvNAnxN.css +0 -1
- package/examples/full/dist/client/assets/honoto-client.js +0 -2
- package/examples/full/dist/client/assets/hooks-Cz6AT21d.js +0 -1
- package/examples/full/dist/client/assets/jsx-dev-runtime-92VDsVyo.js +0 -1
- package/examples/full/dist/client/assets/kysely-adapter-BHhasAnc.js +0 -1
- package/examples/full/dist/client/assets/kysely-migration-tables-DFfmKhq--U5ujlMwE.js +0 -1
- package/examples/full/dist/client/assets/node-sqlite-dialect-DJDXH5Ot.js +0 -1
- package/examples/full/dist/client/assets/pages-CUQx6Eus.js +0 -1
- package/examples/full/dist/client/assets/saved-jIi74ncJ.js +0 -1
- package/examples/full/dist/client/assets/session-B-accyM3.js +0 -611
- package/examples/full/dist/client/assets/sign-in-BelI3gSs.js +0 -1
- package/examples/full/dist/client/assets/sign-up-pR94lfdu.js +0 -1
- package/examples/full/dist/client/index.html +0 -1
- package/examples/full/dist/client/saved.html +0 -1
- package/examples/full/dist/client/sign-in.html +0 -1
- package/examples/full/dist/client/sign-up.html +0 -1
- package/examples/full/dist/ssr/.dev.vars +0 -1
- package/examples/full/dist/ssr/.vite/manifest.json +0 -219
- package/examples/full/dist/ssr/assets/BookmarkButton-KS7z5_vi.js +0 -298
- package/examples/full/dist/ssr/assets/_slug_-rRStRaAN.js +0 -89
- package/examples/full/dist/ssr/assets/auth-DSFZ4iak.js +0 -31434
- package/examples/full/dist/ssr/assets/auth-client-BFSBVoML.js +0 -894
- package/examples/full/dist/ssr/assets/bun-sqlite-dialect-C7ftEUSI-BeXpIqKl.js +0 -162
- package/examples/full/dist/ssr/assets/compiled-query-DmoyCh28.js +0 -8410
- package/examples/full/dist/ssr/assets/d1-sqlite-dialect-BZmaVTp8-CjJdvL94.js +0 -114
- package/examples/full/dist/ssr/assets/default-query-compiler-D7xOzCCJ.js +0 -1727
- package/examples/full/dist/ssr/assets/dist-LmmDoNdk.js +0 -6832
- package/examples/full/dist/ssr/assets/dist-kFDN1l4Z.js +0 -342
- package/examples/full/dist/ssr/assets/factory-AD6s9SIW.js +0 -2079
- package/examples/full/dist/ssr/assets/jsx-renderer-mMLf5XLN.js +0 -1926
- package/examples/full/dist/ssr/assets/kysely-adapter-BCLenpM8.js +0 -2
- package/examples/full/dist/ssr/assets/kysely-migration-tables-DFfmKhq--BtVr6hRe.js +0 -17
- package/examples/full/dist/ssr/assets/layout-mVA7qP4j.js +0 -44
- package/examples/full/dist/ssr/assets/node-sqlite-dialect-D-wtYAD7.js +0 -162
- package/examples/full/dist/ssr/assets/pages-Do5kR_Ia.js +0 -147
- package/examples/full/dist/ssr/assets/saved-Dr4pP6B5.js +0 -111
- package/examples/full/dist/ssr/assets/session-BvIpX7tr.js +0 -13
- package/examples/full/dist/ssr/assets/sign-in-22pzTnJE.js +0 -115
- package/examples/full/dist/ssr/assets/sign-up-CN4j8Qg1.js +0 -117
- package/examples/full/dist/ssr/assets/sqlite-adapter-DVlms5wO.js +0 -79
- package/examples/full/dist/ssr/index.js +0 -97
- package/examples/full/dist/ssr/wrangler.json +0 -1
|
@@ -1,611 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-BoGTNvkC.js","assets/factory-Bgf4EtLx.js","assets/bun-sqlite-dialect-C7ftEUSI-CsHdUKBY.js","assets/default-query-compiler-CUdqIu1h.js","assets/kysely-migration-tables-DFfmKhq--U5ujlMwE.js","assets/node-sqlite-dialect-DJDXH5Ot.js","assets/d1-sqlite-dialect-BZmaVTp8-FPCaMZqX.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{A as e,B as t,H as n,K as r,O as i,Q as a,V as o,X as s,Y as c,Z as l,q as u,x as d}from"./hooks-Cz6AT21d.js";import{t as f}from"./honoto-client.js";import{n as p,t as m}from"./components-DX9r6vHn.js";import{A as h,C as g,D as _,E as v,O as y,S as ee,T as te,_ as b,a as x,b as S,c as C,d as w,f as T,g as E,h as D,i as O,j as k,k as A,l as j,m as M,n as ne,o as N,p as re,r as ie,s as ae,t as oe,u as se,v as ce,w as le,x as ue,y as de}from"./factory-Bgf4EtLx.js";import{A as fe,C as pe,D as me,E as he,O as ge,S as _e,T as ve,_ as P,a as ye,b as be,c as xe,d as Se,f as Ce,g as we,h as Te,i as Ee,k as De,l as Oe,m as ke,n as Ae,o as je,p as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./default-query-compiler-CUdqIu1h.js";var Ve=o(null),He=0,Ue=async({children:e,fallback:r})=>{Array.isArray(e)||(e=[e]);let i=n(Ve)?.scriptNonce,a=[],o={[u]:[0,[]]},f=()=>{d.pop()};try{o[u][0]=0,d.push([[],o]),a=e.map(e=>e==null||typeof e==`boolean`?``:e.toString())}catch(n){if(n instanceof Promise){let r=t();a=[n.then(()=>r(()=>(o[u][0]=0,d.push([[],o]),Ge(e).finally(f))))]}else throw n}finally{f()}if(a.some(e=>e instanceof Promise)){let e=He++,t=await r.toString();return s(`<template id="H:${e}"></template>${t}<!--/$-->`,[...t.callbacks||[],({phase:t,buffer:n,context:r})=>{if(t!==c.BeforeStream)return Promise.all(a).then(async a=>{a=a.flat();let o=a.join(``);n&&(n[0]=n[0].replace(RegExp(`<template id="H:${e}"></template>.*?<!--/\\$-->`),o));let u=n?``:`<template data-hono-target="H:${e}">${o}</template><script${i?` nonce="${i}"`:``}>
|
|
3
|
-
((d,c,n) => {
|
|
4
|
-
c=d.currentScript.previousSibling
|
|
5
|
-
d=d.getElementById('H:${e}')
|
|
6
|
-
if(!d)return
|
|
7
|
-
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')
|
|
8
|
-
d.replaceWith(c.content)
|
|
9
|
-
})(document)
|
|
10
|
-
<\/script>`,d=a.map(e=>e.callbacks||[]).flat();return d.length?(t===c.Stream&&(u=await l(u,c.BeforeStream,!0,r)),s(u,d)):u})}])}return s(a.join(``))};Ue[r]=p,new TextEncoder;var We=0,Ge=async e=>{try{return e.flat().map(e=>e==null||typeof e==`boolean`?``:e.toString())}catch(n){if(n instanceof Promise){let r=t();return await n,r(()=>Ge(e))}throw n}},Ke=e=>{if(e==null||typeof e==`boolean`)return``;if(typeof e==`string`)return e;{let t=e.toString();return t instanceof Promise?t:s(t)}},qe=async({children:r,fallback:a,fallbackRender:o,onError:u})=>{if(!r)return s(``);Array.isArray(r)||(r=[r]);let d=n(Ve)?.scriptNonce,f,p=()=>f||=t(),m,h=()=>m||=(async()=>{let e=await a;if(typeof e==`string`)return e;{let t=await p()(()=>e?.toString());if(typeof t==`string`)return s(t,t.callbacks||e?.callbacks)}})(),g=async t=>{let n=await h();return p()(async()=>{u?.(t);let r=n===void 0?o&&e(i,{},o(t))||``:n,a=await i({children:r}).toString();return s(a,a.callbacks||r.callbacks)})},_=[];try{_=r.map(Ke)}catch(e){let t=p();_=e instanceof Promise?[e.then(()=>t(()=>Ge(r))).catch(e=>g(e))]:[await g(e)]}if(_.some(e=>e instanceof Promise)){p();let e=We++,t=RegExp(`(<template id="E:${e}"></template>.*?)(.*?)(<!--E:${e}-->)`),n=!1,r=async({error:r,buffer:i})=>{if(n)return``;n=!0;let a=await g(r),o=a.callbacks;return i?(i[0]=i[0].replace(t,a),o?.length?s(``,o):``):s(`<template data-hono-target="E:${e}">${a}</template><script>
|
|
11
|
-
((d,c,n) => {
|
|
12
|
-
c=d.currentScript.previousSibling
|
|
13
|
-
d=d.getElementById('E:${e}')
|
|
14
|
-
if(!d)return
|
|
15
|
-
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${e}')
|
|
16
|
-
d.replaceWith(c.content)
|
|
17
|
-
})(document)
|
|
18
|
-
<\/script>`,o)},i,a=Promise.all(_).catch(e=>i=e);return s(`<template id="E:${e}"></template><!--E:${e}-->`,[({phase:n,buffer:o,context:u})=>{if(n!==c.BeforeStream)return a.then(async a=>{if(i)throw i;a=a.flat();let f=a.join(``),p=o?``:`<template data-hono-target="E:${e}">${f}</template><script${d?` nonce="${d}"`:``}>
|
|
19
|
-
((d,c) => {
|
|
20
|
-
c=d.currentScript.previousSibling
|
|
21
|
-
d=d.getElementById('E:${e}')
|
|
22
|
-
if(!d)return
|
|
23
|
-
d.parentElement.insertBefore(c.content,d.nextSibling)
|
|
24
|
-
})(document)
|
|
25
|
-
<\/script>`;if(a.every(e=>!e.callbacks?.length))return o&&(o[0]=o[0].replace(t,f)),p;o&&(o[0]=o[0].replace(t,(e,t,n,r)=>`${t}${f}${r}`));let m=a.map(e=>e.callbacks||[]).flat();n===c.Stream&&(p=await l(p,c.BeforeStream,!0,u));let h=0,g=m.map(n=>(...i)=>n(...i)?.then(n=>(h++,o?(h===m.length&&(o[0]=o[0].replace(t,(e,t,n)=>n)),o[0]+=n,s(``,n.callbacks)):s(n+(h===m.length?`<script>
|
|
26
|
-
((d,c,n) => {
|
|
27
|
-
d=d.getElementById('E:${e}')
|
|
28
|
-
if(!d)return
|
|
29
|
-
n=d.nextSibling
|
|
30
|
-
while(n.nodeType!=8||n.nodeValue!='E:${e}'){n=n.nextSibling}
|
|
31
|
-
n.remove()
|
|
32
|
-
d.remove()
|
|
33
|
-
})(document)
|
|
34
|
-
<\/script>`:``),n.callbacks))).catch(e=>r({error:e,buffer:o})));return s(p,g)}).catch(e=>r({error:e,buffer:o}))}])}return i({children:_})};qe[r]=m,o(null);var F=Symbol.for(`drizzle:entityKind`);function I(e,t){if(!e||typeof e!=`object`)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??`<unknown>`}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(F in n&&n[F]===t[F])return!0;n=Object.getPrototypeOf(n)}return!1}var Je=class{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]=`Column`;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}},Ye=class{static[F]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===``&&(this.config.name=e)}},Xe=Symbol.for(`drizzle:Name`),Ze=Symbol.for(`drizzle:isPgEnum`);function Qe(e){return!!e&&typeof e==`function`&&Ze in e&&e[Ze]===!0}var $e=class{static[F]=`Subquery`;constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},et=class extends $e{static[F]=`WithSubquery`},tt={startActiveSpan(e,t){return t()}},nt=Symbol.for(`drizzle:ViewBaseConfig`),rt=Symbol.for(`drizzle:Schema`),it=Symbol.for(`drizzle:Columns`),at=Symbol.for(`drizzle:ExtraConfigColumns`),ot=Symbol.for(`drizzle:OriginalName`),st=Symbol.for(`drizzle:BaseName`),ct=Symbol.for(`drizzle:IsAlias`),lt=Symbol.for(`drizzle:ExtraConfigBuilder`),ut=Symbol.for(`drizzle:IsDrizzleTable`),L=class{static[F]=`Table`;static Symbol={Name:Xe,Schema:rt,OriginalName:ot,Columns:it,ExtraConfigColumns:at,BaseName:st,IsAlias:ct,ExtraConfigBuilder:lt};[Xe];[ot];[rt];[it];[at];[st];[ct]=!1;[ut]=!0;[lt]=void 0;constructor(e,t,n){this[Xe]=this[ot]=e,this[rt]=t,this[st]=n}};function dt(e){return e[Xe]}function ft(e){return`${e[rt]??`public`}.${e[Xe]}`}function pt(e){return e!=null&&typeof e.getSQL==`function`}function mt(e){let t={sql:``,params:[]};for(let n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||=[],t.typings.push(...n.typings));return t}var ht=class{static[F]=`StringChunk`;value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new R([this])}},R=class e{constructor(e){this.queryChunks=e;for(let t of e)if(I(t,L)){let e=t[L.Symbol.Schema];this.usedTables.push(e===void 0?t[L.Symbol.Name]:e+`.`+t[L.Symbol.Name])}}static[F]=`SQL`;decoder=vt;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tt.startActiveSpan(`drizzle.buildSQL`,t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(t,n){let r=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:i,escapeName:a,escapeParam:o,prepareTyping:s,inlineParams:c,paramStartIndex:l}=r;return mt(t.map(t=>{if(I(t,ht))return{sql:t.value.join(``),params:[]};if(I(t,gt))return{sql:a(t.value),params:[]};if(t===void 0)return{sql:``,params:[]};if(Array.isArray(t)){let e=[new ht(`(`)];for(let[n,r]of t.entries())e.push(r),n<t.length-1&&e.push(new ht(`, `));return e.push(new ht(`)`)),this.buildQueryFromSourceParams(e,r)}if(I(t,e))return this.buildQueryFromSourceParams(t.queryChunks,{...r,inlineParams:c||t.shouldInlineParams});if(I(t,L)){let e=t[L.Symbol.Schema],n=t[L.Symbol.Name];return{sql:e===void 0||t[ct]?a(n):a(e)+`.`+a(n),params:[]}}if(I(t,Je)){let e=i.getColumnCasing(t);if(n.invokeSource===`indexes`)return{sql:a(e),params:[]};let r=t.table[L.Symbol.Schema];return{sql:t.table[ct]||r===void 0?a(t.table[L.Symbol.Name])+`.`+a(e):a(r)+`.`+a(t.table[L.Symbol.Name])+`.`+a(e),params:[]}}if(I(t,wt)){let e=t[nt].schema,n=t[nt].name;return{sql:e===void 0||t[nt].isAlias?a(n):a(e)+`.`+a(n),params:[]}}if(I(t,bt)){if(I(t.value,xt))return{sql:o(l.value++,t),params:[t],typings:[`none`]};let n=t.value===null?null:t.encoder.mapToDriverValue(t.value);if(I(n,e))return this.buildQueryFromSourceParams([n],r);if(c)return{sql:this.mapInlineParam(n,r),params:[]};let i=[`none`];return s&&(i=[s(t.encoder)]),{sql:o(l.value++,n),params:[n],typings:i}}return I(t,xt)?{sql:o(l.value++,t),params:[t],typings:[`none`]}:I(t,e.Aliased)&&t.fieldAlias!==void 0?{sql:a(t.fieldAlias),params:[]}:I(t,$e)?t._.isWith?{sql:a(t._.alias),params:[]}:this.buildQueryFromSourceParams([new ht(`(`),t._.sql,new ht(`) `),new gt(t._.alias)],r):Qe(t)?t.schema?{sql:a(t.schema)+`.`+a(t.enumName),params:[]}:{sql:a(t.enumName),params:[]}:pt(t)?t.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([t.getSQL()],r):this.buildQueryFromSourceParams([new ht(`(`),t.getSQL(),new ht(`)`)],r):c?{sql:this.mapInlineParam(t,r),params:[]}:{sql:o(l.value++,t),params:[t],typings:[`none`]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(t){return t===void 0?this:new e.Aliased(this,t)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},gt=class{constructor(e){this.value=e}static[F]=`Name`;brand;getSQL(){return new R([this])}};function _t(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}var vt={mapFromDriverValue:e=>e},yt={mapToDriverValue:e=>e};({...vt,...yt});var bt=class{constructor(e,t=yt){this.value=e,this.encoder=t}static[F]=`Param`;brand;getSQL(){return new R([this])}};function z(e,...t){let n=[];(t.length>0||e.length>0&&e[0]!==``)&&n.push(new ht(e[0]));for(let[r,i]of t.entries())n.push(i,new ht(e[r+1]));return new R(n)}(e=>{function t(){return new R([])}e.empty=t;function n(e){return new R(e)}e.fromList=n;function r(e){return new R([new ht(e)])}e.raw=r;function i(e,t){let n=[];for(let[r,i]of e.entries())r>0&&t!==void 0&&n.push(t),n.push(i);return new R(n)}e.join=i;function a(e){return new gt(e)}e.identifier=a;function o(e){return new xt(e)}e.placeholder=o;function s(e,t){return new bt(e,t)}e.param=s})(z||={}),(e=>{class t{constructor(e,t){this.sql=e,this.fieldAlias=t}static[F]=`SQL.Aliased`;isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(R||={});var xt=class{constructor(e){this.name=e}static[F]=`Placeholder`;getSQL(){return new R([this])}};function St(e,t){return e.map(e=>{if(I(e,xt)){if(!(e.name in t))throw Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(I(e,bt)&&I(e.value,xt)){if(!(e.value.name in t))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}var Ct=Symbol.for(`drizzle:IsDrizzleView`),wt=class{static[F]=`View`;[nt];[Ct]=!0;constructor({name:e,schema:t,selectedFields:n,query:r}){this[nt]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new R([this])}};Je.prototype.getSQL=function(){return new R([this])},L.prototype.getSQL=function(){return new R([this])},$e.prototype.getSQL=function(){return new R([this])};var Tt=class{constructor(e){this.table=e}static[F]=`ColumnAliasProxyHandler`;get(e,t){return t===`table`?this.table:e[t]}},Et=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]=`TableAliasProxyHandler`;get(e,t){if(t===L.Symbol.IsAlias)return!0;if(t===L.Symbol.Name||this.replaceOriginalName&&t===L.Symbol.OriginalName)return this.alias;if(t===nt)return{...e[nt],name:this.alias,isAlias:!0};if(t===L.Symbol.Columns){let t=e[L.Symbol.Columns];if(!t)return t;let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new Tt(new Proxy(e,this)))}),n}let n=e[t];return I(n,Je)?new Proxy(n,new Tt(new Proxy(e,this))):n}};function Dt(e,t){return new Proxy(e,new Et(t,!1))}function Ot(e,t){return new Proxy(e,new Tt(new Proxy(e.table,new Et(t,!1))))}function kt(e,t){return new R.Aliased(At(e.sql,t),e.fieldAlias)}function At(e,t){return z.join(e.queryChunks.map(e=>I(e,Je)?Ot(e,t):I(e,R)?At(e,t):I(e,R.Aliased)?kt(e,t):e))}var jt=class extends Error{static[F]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}},Mt=class e extends Error{constructor(t,n,r){super(`Failed query: ${t}
|
|
35
|
-
params: ${n}`),this.query=t,this.params=n,this.cause=r,Error.captureStackTrace(this,e),r&&(this.cause=r)}},Nt=class extends jt{static[F]=`TransactionRollbackError`;constructor(){super({message:`Rollback`})}},Pt=class{static[F]=`ConsoleLogWriter`;write(e){console.log(e)}},Ft=class{static[F]=`DefaultLogger`;writer;constructor(e){this.writer=e?.writer??new Pt}logQuery(e,t){let n=t.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),r=n.length?` -- params: [${n.join(`, `)}]`:``;this.writer.write(`Query: ${e}${r}`)}},It=class{static[F]=`NoopLogger`;logQuery(){}},Lt=class{static[F]=`QueryPromise`;[Symbol.toStringTag]=`QueryPromise`;catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function Rt(e,t,n){let r={},i=e.reduce((e,{path:i,field:a},o)=>{let s;s=I(a,Je)?a:I(a,R)?a.decoder:a.sql.decoder;let c=e;for(let[e,l]of i.entries())if(e<i.length-1)l in c||(c[l]={}),c=c[l];else{let e=t[o],u=c[l]=e===null?null:s.mapFromDriverValue(e);if(n&&I(a,Je)&&i.length===2){let e=i[0];e in r?typeof r[e]==`string`&&r[e]!==dt(a.table)&&(r[e]=!1):r[e]=u===null&&dt(a.table)}}return e},{});if(n&&Object.keys(r).length>0)for(let[e,t]of Object.entries(r))typeof t==`string`&&!n[t]&&(i[e]=null);return i}function zt(e,t){return Object.entries(e).reduce((e,[n,r])=>{if(typeof n!=`string`)return e;let i=t?[...t,n]:[n];return I(r,Je)||I(r,R)||I(r,R.Aliased)?e.push({path:i,field:r}):I(r,L)?e.push(...zt(r[L.Symbol.Columns],i)):e.push(...zt(r,i)),e},[])}function Bt(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function Vt(e,t){let n=Object.entries(t).filter(([,e])=>e!==void 0).map(([t,n])=>I(n,R)||I(n,Je)?[t,n]:[t,new bt(n,e[L.Symbol.Columns][t])]);if(n.length===0)throw Error(`No values to set`);return Object.fromEntries(n)}function Ht(e,t){for(let n of t)for(let t of Object.getOwnPropertyNames(n.prototype))t!==`constructor`&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function Ut(e){return e[L.Symbol.Columns]}function Wt(e){return I(e,$e)?e._.alias:I(e,wt)?e[nt].name:I(e,R)?void 0:e[L.Symbol.IsAlias]?e[L.Symbol.Name]:e[L.Symbol.BaseName]}function Gt(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}var Kt=typeof TextDecoder>`u`?null:new TextDecoder,qt=Symbol.for(`drizzle:PgInlineForeignKeys`),Jt=Symbol.for(`drizzle:EnableRLS`),Yt=class extends L{static[F]=`PgTable`;static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:qt,EnableRLS:Jt});[qt]=[];[Jt]=!1;[L.Symbol.ExtraConfigBuilder]=void 0;[L.Symbol.ExtraConfigColumns]={}},Xt=class{static[F]=`PgPrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new Zt(e,this.columns,this.name)}},Zt=class{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[F]=`PgPrimaryKey`;columns;name;getName(){return this.name??`${this.table[Yt.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}};function Qt(e,t){return _t(t)&&!pt(e)&&!I(e,bt)&&!I(e,xt)&&!I(e,Je)&&!I(e,L)&&!I(e,wt)?new bt(e,t):e}var $t=(e,t)=>z`${e} = ${Qt(t,e)}`,en=(e,t)=>z`${e} <> ${Qt(t,e)}`;function tn(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new R(t):new R([new ht(`(`),z.join(t,new ht(` and `)),new ht(`)`)])}function nn(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new R(t):new R([new ht(`(`),z.join(t,new ht(` or `)),new ht(`)`)])}function rn(e){return z`not ${e}`}var an=(e,t)=>z`${e} > ${Qt(t,e)}`,on=(e,t)=>z`${e} >= ${Qt(t,e)}`,sn=(e,t)=>z`${e} < ${Qt(t,e)}`,cn=(e,t)=>z`${e} <= ${Qt(t,e)}`;function ln(e,t){return Array.isArray(t)?t.length===0?z`false`:z`${e} in ${t.map(t=>Qt(t,e))}`:z`${e} in ${Qt(t,e)}`}function un(e,t){return Array.isArray(t)?t.length===0?z`true`:z`${e} not in ${t.map(t=>Qt(t,e))}`:z`${e} not in ${Qt(t,e)}`}function dn(e){return z`${e} is null`}function fn(e){return z`${e} is not null`}function pn(e){return z`exists ${e}`}function mn(e){return z`not exists ${e}`}function hn(e,t,n){return z`${e} between ${Qt(t,e)} and ${Qt(n,e)}`}function gn(e,t,n){return z`${e} not between ${Qt(t,e)} and ${Qt(n,e)}`}function _n(e,t){return z`${e} like ${t}`}function vn(e,t){return z`${e} not like ${t}`}function yn(e,t){return z`${e} ilike ${t}`}function bn(e,t){return z`${e} not ilike ${t}`}function xn(e){return z`${e} asc`}function Sn(e){return z`${e} desc`}var Cn=class{constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[L.Symbol.Name]}static[F]=`Relation`;referencedTableName;fieldName},wn=class{constructor(e,t){this.table=e,this.config=t}static[F]=`Relations`},Tn=class e extends Cn{constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[F]=`One`;withFieldName(t){let n=new e(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=t,n}},En=class e extends Cn{constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[F]=`Many`;withFieldName(t){let n=new e(this.sourceTable,this.referencedTable,this.config);return n.fieldName=t,n}};function Dn(){return{and:tn,between:hn,eq:$t,exists:pn,gt:an,gte:on,ilike:yn,inArray:ln,isNull:dn,isNotNull:fn,like:_n,lt:sn,lte:cn,ne:en,not:rn,notBetween:gn,notExists:mn,notLike:vn,notIlike:bn,notInArray:un,or:nn,sql:z}}function On(){return{sql:z,asc:xn,desc:Sn}}function kn(e,t){Object.keys(e).length===1&&`default`in e&&!I(e.default,L)&&(e=e.default);let n={},r={},i={};for(let[a,o]of Object.entries(e))if(I(o,L)){let e=ft(o),t=r[e];n[e]=a,i[a]={tsName:a,dbName:o[L.Symbol.Name],schema:o[L.Symbol.Schema],columns:o[L.Symbol.Columns],relations:t?.relations??{},primaryKey:t?.primaryKey??[]};for(let e of Object.values(o[L.Symbol.Columns]))e.primary&&i[a].primaryKey.push(e);let s=o[L.Symbol.ExtraConfigBuilder]?.(o[L.Symbol.ExtraConfigColumns]);if(s)for(let e of Object.values(s))I(e,Xt)&&i[a].primaryKey.push(...e.columns)}else if(I(o,wn)){let e=ft(o.table),a=n[e],s=o.config(t(o.table)),c;for(let[t,n]of Object.entries(s))if(a){let e=i[a];e.relations[t]=n}else e in r||(r[e]={relations:{},primaryKey:c}),r[e].relations[t]=n}return{tables:i,tableNamesMap:n}}function An(e,t){return new wn(e,e=>Object.fromEntries(Object.entries(t(e)).map(([e,t])=>[e,t.withFieldName(e)])))}function jn(e){return function(t,n){return new Tn(e,t,n,n?.fields.reduce((e,t)=>e&&t.notNull,!0)??!1)}}function Mn(e){return function(t,n){return new En(e,t,n)}}function Nn(e,t,n){if(I(n,Tn)&&n.config)return{fields:n.config.fields,references:n.config.references};let r=t[ft(n.referencedTable)];if(!r)throw Error(`Table "${n.referencedTable[L.Symbol.Name]}" not found in schema`);let i=e[r];if(!i)throw Error(`Table "${r}" not found in schema`);let a=n.sourceTable,o=t[ft(a)];if(!o)throw Error(`Table "${a[L.Symbol.Name]}" not found in schema`);let s=[];for(let e of Object.values(i.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&s.push(e);if(s.length>1)throw n.relationName?Error(`There are multiple relations with name "${n.relationName}" in table "${r}"`):Error(`There are multiple relations between "${r}" and "${n.sourceTable[L.Symbol.Name]}". Please specify relation name`);if(s[0]&&I(s[0],Tn)&&s[0].config)return{fields:s[0].config.references,references:s[0].config.fields};throw Error(`There is not enough information to infer relation "${o}.${n.fieldName}"`)}function Pn(e){return{one:jn(e),many:Mn(e)}}function Fn(e,t,n,r,i=e=>e){let a={};for(let[o,s]of r.entries())if(s.isJson){let r=t.relations[s.tsKey],c=n[o],l=typeof c==`string`?JSON.parse(c):c;a[s.tsKey]=I(r,Tn)?l&&Fn(e,e[s.relationTableTsKey],l,s.selection,i):l.map(t=>Fn(e,e[s.relationTableTsKey],t,s.selection,i))}else{let e=i(n[o]),t=s.field,r;r=I(t,Je)?t:I(t,R)?t.decoder:t.sql.decoder,a[s.tsKey]=e===null?null:r.mapFromDriverValue(e)}return a}function In(e){return z`count(${e||z.raw(`*`)})`.mapWith(Number)}var Ln=class e{static[F]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(t,n){if(n===`_`)return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(n===nt)return{...t[nt],selectedFields:new Proxy(t[nt].selectedFields,this)};if(typeof n==`symbol`)return t[n];let r=(I(t,$e)?t._.selectedFields:I(t,wt)?t[nt].selectedFields:t)[n];if(I(r,R.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!r.isSelectionField)return r.sql;let e=r.clone();return e.isSelectionField=!0,e}if(I(r,R)){if(this.config.sqlBehavior===`sql`)return r;throw Error(`You tried to reference "${n}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return I(r,Je)?this.config.alias?new Proxy(r,new Tt(new Proxy(r.table,new Et(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!=`object`||!r?r:new Proxy(r,new e(this.config))}},Rn=class{static[F]=`SQLiteForeignKeyBuilder`;reference;_onUpdate;_onDelete;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new zn(e,this)}},zn=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]=`SQLiteForeignKey`;reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),i=n.map(e=>e.name),a=[this.table[Xe],...r,n[0].table[Xe],...i];return e??`${a.join(`_`)}_fk`}};function Bn(e,t){return`${e[Xe]}_${t.join(`_`)}_unique`}var Vn=class extends Ye{static[F]=`SQLiteColumnBuilder`;foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:`always`,mode:t?.mode??`virtual`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>((n,r)=>{let i=new Rn(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)})(n,r))}},Hn=class extends Je{constructor(e,t){t.uniqueName||=Bn(e,[t.name]),super(e,t),this.table=e}static[F]=`SQLiteColumn`},Un=class extends Vn{static[F]=`SQLiteBigIntBuilder`;constructor(e){super(e,`bigint`,`SQLiteBigInt`)}build(e){return new Wn(e,this.config)}},Wn=class extends Hn{static[F]=`SQLiteBigInt`;getSQLType(){return`blob`}mapFromDriverValue(e){if(typeof Buffer<`u`&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString(`utf8`))}return BigInt(Kt.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}},Gn=class extends Vn{static[F]=`SQLiteBlobJsonBuilder`;constructor(e){super(e,`json`,`SQLiteBlobJson`)}build(e){return new Kn(e,this.config)}},Kn=class extends Hn{static[F]=`SQLiteBlobJson`;getSQLType(){return`blob`}mapFromDriverValue(e){if(typeof Buffer<`u`&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString(`utf8`))}return JSON.parse(Kt.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}},qn=class extends Vn{static[F]=`SQLiteBlobBufferBuilder`;constructor(e){super(e,`buffer`,`SQLiteBlobBuffer`)}build(e){return new Jn(e,this.config)}},Jn=class extends Hn{static[F]=`SQLiteBlobBuffer`;mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return`blob`}};function Yn(e,t){let{name:n,config:r}=Gt(e,t);return r?.mode===`json`?new Gn(n):r?.mode===`bigint`?new Un(n):new qn(n)}var Xn=class extends Vn{static[F]=`SQLiteCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`SQLiteCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new Zn(e,this.config)}},Zn=class extends Hn{static[F]=`SQLiteCustomColumn`;sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==`function`?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==`function`?this.mapTo(e):e}};function Qn(e){return(t,n)=>{let{name:r,config:i}=Gt(t,n);return new Xn(r,i,e)}}var $n=class extends Vn{static[F]=`SQLiteBaseIntegerBuilder`;constructor(e,t,n){super(e,t,n),this.config.autoIncrement=!1}primaryKey(e){return e?.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}},er=class extends Hn{static[F]=`SQLiteBaseInteger`;autoIncrement=this.config.autoIncrement;getSQLType(){return`integer`}},tr=class extends $n{static[F]=`SQLiteIntegerBuilder`;constructor(e){super(e,`number`,`SQLiteInteger`)}build(e){return new nr(e,this.config)}},nr=class extends er{static[F]=`SQLiteInteger`},rr=class extends $n{static[F]=`SQLiteTimestampBuilder`;constructor(e,t){super(e,`date`,`SQLiteTimestamp`),this.config.mode=t}defaultNow(){return this.default(z`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new ir(e,this.config)}},ir=class extends er{static[F]=`SQLiteTimestamp`;mode=this.config.mode;mapFromDriverValue(e){return this.config.mode===`timestamp`?new Date(e*1e3):new Date(e)}mapToDriverValue(e){let t=e.getTime();return this.config.mode===`timestamp`?Math.floor(t/1e3):t}},ar=class extends $n{static[F]=`SQLiteBooleanBuilder`;constructor(e,t){super(e,`boolean`,`SQLiteBoolean`),this.config.mode=t}build(e){return new or(e,this.config)}},or=class extends er{static[F]=`SQLiteBoolean`;mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return+!!e}};function sr(e,t){let{name:n,config:r}=Gt(e,t);return r?.mode===`timestamp`||r?.mode===`timestamp_ms`?new rr(n,r.mode):r?.mode===`boolean`?new ar(n,r.mode):new tr(n)}var cr=class extends Vn{static[F]=`SQLiteNumericBuilder`;constructor(e){super(e,`string`,`SQLiteNumeric`)}build(e){return new lr(e,this.config)}},lr=class extends Hn{static[F]=`SQLiteNumeric`;mapFromDriverValue(e){return typeof e==`string`?e:String(e)}getSQLType(){return`numeric`}},ur=class extends Vn{static[F]=`SQLiteNumericNumberBuilder`;constructor(e){super(e,`number`,`SQLiteNumericNumber`)}build(e){return new dr(e,this.config)}},dr=class extends Hn{static[F]=`SQLiteNumericNumber`;mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}mapToDriverValue=String;getSQLType(){return`numeric`}},fr=class extends Vn{static[F]=`SQLiteNumericBigIntBuilder`;constructor(e){super(e,`bigint`,`SQLiteNumericBigInt`)}build(e){return new pr(e,this.config)}},pr=class extends Hn{static[F]=`SQLiteNumericBigInt`;mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return`numeric`}};function mr(e,t){let{name:n,config:r}=Gt(e,t),i=r?.mode;return i===`number`?new ur(n):i===`bigint`?new fr(n):new cr(n)}var hr=class extends Vn{static[F]=`SQLiteRealBuilder`;constructor(e){super(e,`number`,`SQLiteReal`)}build(e){return new gr(e,this.config)}},gr=class extends Hn{static[F]=`SQLiteReal`;getSQLType(){return`real`}};function _r(e){return new hr(e??``)}var vr=class extends Vn{static[F]=`SQLiteTextBuilder`;constructor(e,t){super(e,`string`,`SQLiteText`),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new yr(e,this.config)}},yr=class extends Hn{static[F]=`SQLiteText`;enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:``}`}},br=class extends Vn{static[F]=`SQLiteTextJsonBuilder`;constructor(e){super(e,`json`,`SQLiteTextJson`)}build(e){return new xr(e,this.config)}},xr=class extends Hn{static[F]=`SQLiteTextJson`;getSQLType(){return`text`}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}};function B(e,t={}){let{name:n,config:r}=Gt(e,t);return r.mode===`json`?new br(n):new vr(n,r)}function Sr(){return{blob:Yn,customType:Qn,integer:sr,numeric:mr,real:_r,text:B}}var Cr=Symbol.for(`drizzle:SQLiteInlineForeignKeys`),wr=class extends L{static[F]=`SQLiteTable`;static Symbol=Object.assign({},L.Symbol,{InlineForeignKeys:Cr});[L.Symbol.Columns];[Cr]=[];[L.Symbol.ExtraConfigBuilder]=void 0};function Tr(e,t,n,r,i=e){let a=new wr(e,r,i),o=typeof t==`function`?t(Sr()):t,s=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;n.setName(e);let r=n.build(a);return a[Cr].push(...n.buildForeignKeys(r,a)),[e,r]})),c=Object.assign(a,s);return c[L.Symbol.Columns]=s,c[L.Symbol.ExtraConfigColumns]=s,n&&(c[wr.Symbol.ExtraConfigBuilder]=n),c}var Er=(e,t,n)=>Tr(e,t,n),Dr=class{constructor(e,t){this.name=e,this.unique=t}static[F]=`SQLiteIndexBuilderOn`;on(...e){return new Or(this.name,e,this.unique)}},Or=class{static[F]=`SQLiteIndexBuilder`;config;constructor(e,t,n){this.config={name:e,columns:t,unique:n,where:void 0}}where(e){return this.config.where=e,this}build(e){return new kr(this.config,e)}},kr=class{static[F]=`SQLiteIndex`;config;constructor(e,t){this.config={...e,table:t}}};function Ar(e){return new Dr(e,!1)}function jr(e){return new Dr(e,!0)}function Mr(e){return I(e,wr)?[`${e[L.Symbol.BaseName]}`]:I(e,$e)?e._.usedTables??[]:I(e,R)?e.usedTables??[]:[]}var Nr=class extends Lt{constructor(e,t,n,r){super(),this.table=e,this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[F]=`SQLiteDelete`;config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.table[L.Symbol.Columns],new Ln({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.orderBy=n}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[wr.Symbol.Columns]){return this.config.returning=zt(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?`prepareOneTimeQuery`:`prepareQuery`](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?`all`:`run`,!0,void 0,{type:`delete`,tables:Mr(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}};function Pr(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join(`_`)}function Fr(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function Ir(e){return e}var Lr=class{static[F]=`CasingCache`;cache={};cachedTables={};convert;constructor(e){this.convert=e===`snake_case`?Pr:e===`camelCase`?Fr:Ir}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=`${e.table[L.Symbol.Schema]??`public`}.${e.table[L.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let t=`${e[L.Symbol.Schema]??`public`}.${e[L.Symbol.OriginalName]}`;if(!this.cachedTables[t]){for(let n of Object.values(e[L.Symbol.Columns])){let e=`${t}.${n.name}`;this.cache[e]=this.convert(n.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}},Rr=class extends wt{static[F]=`SQLiteViewBase`},zr=class{static[F]=`SQLiteDialect`;casing;constructor(e){this.casing=new Lr(e?.casing)}escapeName(e){return`"${e}"`}escapeParam(e){return`?`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[z`with `];for(let[n,r]of e.entries())t.push(z`${z.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(z`, `);return t.push(z` `),z.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r,limit:i,orderBy:a}){let o=this.buildWithCTE(r),s=n?z` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,c=t?z` where ${t}`:void 0,l=this.buildOrderBy(a),u=this.buildLimit(i);return z`${o}delete from ${e}${c}${s}${l}${u}`}buildUpdateSet(e,t){let n=e[L.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return z.join(r.flatMap((e,r)=>{let a=n[e],o=t[e]??z.param(a.onUpdateFn(),a),s=z`${z.identifier(this.casing.getColumnCasing(a))} = ${o}`;return r<i-1?[s,z.raw(`, `)]:[s]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,joins:a,from:o,limit:s,orderBy:c}){let l=this.buildWithCTE(i),u=this.buildUpdateSet(e,t),d=o&&z.join([z.raw(` from `),this.buildFromTable(o)]),f=this.buildJoins(a),p=r?z` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,m=n?z` where ${n}`:void 0,h=this.buildOrderBy(c),g=this.buildLimit(s);return z`${l}update ${e} set ${u}${d}${f}${m}${p}${h}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let n=e.length,r=e.flatMap(({field:e},r)=>{let i=[];if(I(e,R.Aliased)&&e.isSelectionField)i.push(z.identifier(e.fieldAlias));else if(I(e,R.Aliased)||I(e,R)){let n=I(e,R.Aliased)?e.sql:e;t?i.push(new R(n.queryChunks.map(e=>I(e,Je)?z.identifier(this.casing.getColumnCasing(e)):e))):i.push(n),I(e,R.Aliased)&&i.push(z` as ${z.identifier(e.fieldAlias)}`)}else if(I(e,Je)){let n=e.table[L.Symbol.Name];e.columnType===`SQLiteNumericBigInt`?t?i.push(z`cast(${z.identifier(this.casing.getColumnCasing(e))} as text)`):i.push(z`cast(${z.identifier(n)}.${z.identifier(this.casing.getColumnCasing(e))} as text)`):t?i.push(z.identifier(this.casing.getColumnCasing(e))):i.push(z`${z.identifier(n)}.${z.identifier(this.casing.getColumnCasing(e))}`)}return r<n-1&&i.push(z`, `),i});return z.join(r)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[n,r]of e.entries()){n===0&&t.push(z` `);let i=r.table,a=r.on?z` on ${r.on}`:void 0;if(I(i,wr)){let e=i[wr.Symbol.Name],n=i[wr.Symbol.Schema],o=i[wr.Symbol.OriginalName],s=e===o?void 0:r.alias;t.push(z`${z.raw(r.joinType)} join ${n?z`${z.identifier(n)}.`:void 0}${z.identifier(o)}${s&&z` ${z.identifier(s)}`}${a}`)}else t.push(z`${z.raw(r.joinType)} join ${i}${a}`);n<e.length-1&&t.push(z` `)}return z.join(t)}buildLimit(e){return typeof e==`object`||typeof e==`number`&&e>=0?z` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e)for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(z`, `);return t.length>0?z` order by ${z.join(t)}`:void 0}buildFromTable(e){return I(e,L)&&e[L.Symbol.IsAlias]?z`${z`${z.identifier(e[L.Symbol.Schema]??``)}.`.if(e[L.Symbol.Schema])}${z.identifier(e[L.Symbol.OriginalName])} ${z.identifier(e[L.Symbol.Name])}`:e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,distinct:d,setOperators:f}){let p=n??zt(t);for(let e of p)if(I(e.field,Je)&&dt(e.field.table)!==(I(a,$e)?a._.alias:I(a,Rr)?a[nt].name:I(a,R)?void 0:dt(a))&&!(e=>o?.some(({alias:t})=>t===(e[L.Symbol.IsAlias]?dt(e):e[L.Symbol.BaseName])))(e.field.table)){let t=dt(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let m=!o||o.length===0,h=this.buildWithCTE(e),g=d?z` distinct`:void 0,_=this.buildSelection(p,{isSingleTable:m}),v=this.buildFromTable(a),y=this.buildJoins(o),ee=r?z` where ${r}`:void 0,te=i?z` having ${i}`:void 0,b=[];if(c)for(let[e,t]of c.entries())b.push(t),e<c.length-1&&b.push(z`, `);let x=b.length>0?z` group by ${z.join(b)}`:void 0,S=this.buildOrderBy(s),C=this.buildLimit(l),w=u?z` offset ${u}`:void 0,T=z`${h}select${g} ${_} from ${v}${y}${ee}${x}${te}${S}${C}${w}`;return f.length>0?this.buildSetOperations(T,f):T}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=z`${e.getSQL()} `,c=z`${r.getSQL()}`,l;if(a&&a.length>0){let e=[];for(let t of a)if(I(t,Hn))e.push(z.identifier(t.name));else if(I(t,R)){for(let e=0;e<t.queryChunks.length;e++){let n=t.queryChunks[e];I(n,Hn)&&(t.queryChunks[e]=z.identifier(this.casing.getColumnCasing(n)))}e.push(z`${t}`)}else e.push(z`${t}`);l=z` order by ${z.join(e,z`, `)}`}let u=typeof i==`object`||typeof i==`number`&&i>=0?z` limit ${i}`:void 0,d=z.raw(`${t} ${n?`all `:``}`),f=o?z` offset ${o}`:void 0;return z`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a}){let o=[],s=e[L.Symbol.Columns],c=Object.entries(s).filter(([e,t])=>!t.shouldDisableInsert()),l=c.map(([,e])=>z.identifier(this.casing.getColumnCasing(e)));if(a){let e=t;I(e,R)?o.push(e):o.push(e.getSQL())}else{let e=t;o.push(z.raw(`values `));for(let[t,n]of e.entries()){let r=[];for(let[e,t]of c){let i=n[e];if(i===void 0||I(i,bt)&&i.value===void 0){let e;if(t.default!==null&&t.default!==void 0)e=I(t.default,R)?t.default:z.param(t.default,t);else if(t.defaultFn!==void 0){let n=t.defaultFn();e=I(n,R)?n:z.param(n,t)}else if(!t.default&&t.onUpdateFn!==void 0){let n=t.onUpdateFn();e=I(n,R)?n:z.param(n,t)}else e=z`null`;r.push(e)}else r.push(i)}o.push(r),t<e.length-1&&o.push(z`, `)}}let u=this.buildWithCTE(i),d=z.join(o),f=r?z` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,p=n?.length?z.join(n):void 0;return z`${u}insert into ${e} ${l} ${d}${p}${f}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:n,table:r,tableConfig:i,queryConfig:a,tableAlias:o,nestedQueryRelation:s,joinOn:c}){let l=[],u,d,f=[],p,m=[];if(a===!0)l=Object.entries(i.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:Ot(t,o),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let r=Object.fromEntries(Object.entries(i.columns).map(([e,t])=>[e,Ot(t,o)]));if(a.where){let e=typeof a.where==`function`?a.where(r,Dn()):a.where;p=e&&At(e,o)}let s=[],c=[];if(a.columns){let e=!1;for(let[t,n]of Object.entries(a.columns))n!==void 0&&t in i.columns&&(!e&&n===!0&&(e=!0),c.push(t));c.length>0&&(c=e?c.filter(e=>a.columns?.[e]===!0):Object.keys(i.columns).filter(e=>!c.includes(e)))}else c=Object.keys(i.columns);for(let e of c){let t=i.columns[e];s.push({tsKey:e,value:t})}let m=[];a.with&&(m=Object.entries(a.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:i.relations[e]})));let h;if(a.extras){h=typeof a.extras==`function`?a.extras(r,{sql:z}):a.extras;for(let[e,t]of Object.entries(h))s.push({tsKey:e,value:kt(t,o)})}for(let{tsKey:e,value:t}of s)l.push({dbKey:I(t,R.Aliased)?t.fieldAlias:i.columns[e].name,tsKey:e,field:I(t,Je)?Ot(t,o):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let g=typeof a.orderBy==`function`?a.orderBy(r,On()):a.orderBy??[];Array.isArray(g)||(g=[g]),f=g.map(e=>I(e,Je)?Ot(e,o):At(e,o)),u=a.limit,d=a.offset;for(let{tsKey:r,queryConfig:i,relation:a}of m){let s=Nn(t,n,a),c=n[ft(a.referencedTable)],u=`${o}_${r}`,d=tn(...s.fields.map((e,t)=>$t(Ot(s.references[t],u),Ot(e,o)))),f=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:n,table:e[c],tableConfig:t[c],queryConfig:I(a,Tn)?i===!0?{limit:1}:{...i,limit:1}:i,tableAlias:u,joinOn:d,nestedQueryRelation:a}),p=z`(${f.sql})`.as(r);l.push({dbKey:r,tsKey:r,field:p,relationTableTsKey:c,isJson:!0,selection:f.selection})}}if(l.length===0)throw new jt({message:`No fields selected for table "${i.tsName}" ("${o}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let h;if(p=tn(c,p),s){let e=z`json_array(${z.join(l.map(({field:e})=>I(e,Hn)?z.identifier(this.casing.getColumnCasing(e)):I(e,R.Aliased)?e.sql:e),z`, `)})`;I(s,En)&&(e=z`coalesce(json_group_array(${e}), json_array())`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:i.tsName,selection:l}];u!==void 0||d!==void 0||f.length>0?(h=this.buildSelectQuery({table:Dt(r,o),fields:{},fieldsFlat:[{path:[],field:z.raw(`*`)}],where:p,limit:u,offset:d,orderBy:f,setOperators:[]}),p=void 0,u=void 0,d=void 0,f=void 0):h=Dt(r,o),h=this.buildSelectQuery({table:I(h,wr)?h:new $e(h,{},o),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:I(e,Je)?Ot(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]})}else h=this.buildSelectQuery({table:Dt(r,o),fields:{},fieldsFlat:l.map(({field:e})=>({path:[],field:I(e,Je)?Ot(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]});return{tableTsKey:i.tsName,sql:h,selection:l}}},Br=class extends zr{static[F]=`SQLiteSyncDialect`;migrate(e,t,n){let r=n===void 0||typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=z`
|
|
36
|
-
CREATE TABLE IF NOT EXISTS ${z.identifier(r)} (
|
|
37
|
-
id SERIAL PRIMARY KEY,
|
|
38
|
-
hash text NOT NULL,
|
|
39
|
-
created_at numeric
|
|
40
|
-
)
|
|
41
|
-
`;t.run(i);let a=t.values(z`SELECT id, hash, created_at FROM ${z.identifier(r)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;t.run(z`BEGIN`);try{for(let n of e)if(!a||Number(a[2])<n.folderMillis){for(let e of n.sql)t.run(z.raw(e));t.run(z`INSERT INTO ${z.identifier(r)} ("hash", "created_at") VALUES(${n.hash}, ${n.folderMillis})`)}t.run(z`COMMIT`)}catch(e){throw t.run(z`ROLLBACK`),e}}},Vr=class extends zr{static[F]=`SQLiteAsyncDialect`;async migrate(e,t,n){let r=n===void 0||typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=z`
|
|
42
|
-
CREATE TABLE IF NOT EXISTS ${z.identifier(r)} (
|
|
43
|
-
id SERIAL PRIMARY KEY,
|
|
44
|
-
hash text NOT NULL,
|
|
45
|
-
created_at numeric
|
|
46
|
-
)
|
|
47
|
-
`;await t.run(i);let a=(await t.values(z`SELECT id, hash, created_at FROM ${z.identifier(r)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async t=>{for(let n of e)if(!a||Number(a[2])<n.folderMillis){for(let e of n.sql)await t.run(z.raw(e));await t.run(z`INSERT INTO ${z.identifier(r)} ("hash", "created_at") VALUES(${n.hash}, ${n.folderMillis})`)}})}},Hr=class{static[F]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},Ur=class{static[F]=`SQLiteSelectBuilder`;fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,n;return n=this.fields?this.fields:I(e,$e)?Object.fromEntries(Object.keys(e._.selectedFields).map(t=>[t,e[t]])):I(e,Rr)?e[nt].selectedFields:I(e,R)?{}:Ut(e),new Gr({table:e,fields:n,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},Wr=class extends Hr{static[F]=`SQLiteSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=Wt(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of Mr(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,n)=>{let r=this.tableName,i=Wt(t);for(let e of Mr(t))this.usedTables.add(e);if(typeof i==`string`&&this.config.joins?.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof r==`string`&&(this.config.fields={[r]:this.config.fields}),typeof i==`string`&&!I(t,R))){let e=I(t,$e)?t._.selectedFields:I(t,wt)?t[nt].selectedFields:t[L.Symbol.Columns];this.config.fields[i]=e}if(typeof n==`function`&&(n=n(new Proxy(this.config.fields,new Ln({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);crossJoin=this.createJoin(`cross`);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(qr()):n;if(!Bt(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);except=this.createSetOperator(`except`,!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ln({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ln({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ln({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ln({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Mr(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...Mr(e.table));return new Proxy(new $e(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Ln({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new Ln({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}},Gr=class extends Wr{static[F]=`SQLiteSelect`;_prepare(e=!0){if(!this.session)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let t=zt(this.config.fields),n=this.session[e?`prepareOneTimeQuery`:`prepareQuery`](this.dialect.sqlToQuery(this.getSQL()),t,`all`,!0,void 0,{type:`select`,tables:[...this.usedTables]},this.cacheConfig);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.all()}};Ht(Gr,[Lt]);function Kr(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Bt(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var qr=()=>({union:Jr,unionAll:Yr,intersect:Xr,except:Zr}),Jr=Kr(`union`,!1),Yr=Kr(`union`,!0),Xr=Kr(`intersect`,!1),Zr=Kr(`except`,!1),Qr=class{static[F]=`SQLiteQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=I(e,zr)?e:void 0,this.dialectConfig=I(e,zr)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new et(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ln({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new Ur({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(n){return new Ur({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:n,selectDistinct:r}}select(e){return new Ur({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Ur({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){return this.dialect||=new Br(this.dialectConfig),this.dialect}},$r=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[F]=`SQLiteInsertBuilder`;values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},n=this.table[L.Symbol.Columns];for(let r of Object.keys(e)){let i=e[r];t[r]=I(i,R)?i:new bt(i,n[r])}return t});return new ei(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==`function`?e(new Qr):e;if(!I(t,R)&&!Bt(this.table[it],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new ei(this.table,t,this.session,this.dialect,this.withList,!0)}},ei=class extends Lt{constructor(e,t,n,r,i,a){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a}}static[F]=`SQLiteInsert`;config;returning(e=this.config.table[wr.Symbol.Columns]){return this.config.returning=zt(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(z` on conflict do nothing`);else{let t=Array.isArray(e.target)?z`${e.target}`:z`${[e.target]}`,n=e.where?z` where ${e.where}`:z``;this.config.onConflict.push(z` on conflict ${t} do nothing${n}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);this.config.onConflict||(this.config.onConflict=[]);let t=e.where?z` where ${e.where}`:void 0,n=e.targetWhere?z` where ${e.targetWhere}`:void 0,r=e.setWhere?z` where ${e.setWhere}`:void 0,i=Array.isArray(e.target)?z`${e.target}`:z`${[e.target]}`,a=this.dialect.buildUpdateSet(this.config.table,Vt(this.config.table,e.set));return this.config.onConflict.push(z` on conflict ${i}${n} do update set ${a}${t}${r}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?`prepareOneTimeQuery`:`prepareQuery`](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?`all`:`run`,!0,void 0,{type:`insert`,tables:Mr(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}},ti=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[F]=`SQLiteUpdateBuilder`;set(e){return new ni(this.table,Vt(this.table,e),this.session,this.dialect,this.withList)}},ni=class extends Lt{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]}}static[F]=`SQLiteUpdate`;config;from(e){return this.config.from=e,this}createJoin(e){return(t,n)=>{let r=Wt(t);if(typeof r==`string`&&this.config.joins.some(e=>e.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==`function`){let e=this.config.from?I(t,wr)?t[L.Symbol.Columns]:I(t,$e)?t._.selectedFields:I(t,Rr)?t[nt].selectedFields:void 0:void 0;n=n(new Proxy(this.config.table[L.Symbol.Columns],new Ln({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new Ln({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}return this.config.joins.push({on:n,table:t,joinType:e,alias:r}),this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.table[L.Symbol.Columns],new Ln({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.orderBy=n}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[wr.Symbol.Columns]){return this.config.returning=zt(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?`prepareOneTimeQuery`:`prepareQuery`](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?`all`:`run`,!0,void 0,{type:`insert`,tables:Mr(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}},ri=class e extends R{constructor(t){super(e.buildEmbeddedCount(t.source,t.filters).queryChunks),this.params=t,this.session=t.session,this.sql=e.buildCount(t.source,t.filters)}sql;static[F]=`SQLiteCountBuilderAsync`;[Symbol.toStringTag]=`SQLiteCountBuilderAsync`;session;static buildEmbeddedCount(e,t){return z`(select count(*) from ${e}${z.raw(` where `).if(t)}${t})`}static buildCount(e,t){return z`select count(*) from ${e}${z.raw(` where `).if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},ii=class{constructor(e,t,n,r,i,a,o,s){this.mode=e,this.fullSchema=t,this.schema=n,this.tableNamesMap=r,this.table=i,this.tableConfig=a,this.dialect=o,this.session=s}static[F]=`SQLiteAsyncRelationalQueryBuilder`;findMany(e){return this.mode===`sync`?new oi(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`):new ai(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return this.mode===`sync`?new oi(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`):new ai(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},ai=class extends Lt{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[F]=`SQLiteAsyncRelationalQuery`;mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:n}=this._toSQL();return this.session[e?`prepareOneTimeQuery`:`prepareQuery`](n,void 0,this.mode===`first`?`get`:`all`,!0,(e,n)=>{let r=e.map(e=>Fn(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName});return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode===`first`?this._prepare(!1).get():this._prepare(!1).all()}async execute(){return this.executeRaw()}},oi=class extends ai{static[F]=`SQLiteSyncRelationalQuery`;sync(){return this.executeRaw()}},si=class extends Lt{constructor(e,t,n,r,i){super(),this.execute=e,this.getSQL=t,this.dialect=r,this.mapBatchResult=i,this.config={action:n}}static[F]=`SQLiteRaw`;config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},ci=class{constructor(e,t,n,r){this.resultKind=e,this.dialect=t,this.session=n,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let i=this.query;if(this._.schema)for(let[a,o]of Object.entries(this._.schema))i[a]=new ii(e,r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[a],o,t,n);this.$cache={invalidate:async e=>{}}}static[F]=`BaseSQLiteDatabase`;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new Qr(n.dialect))),new Proxy(new et(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ln({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new ri({source:e,filters:t,session:this.session})}with(...e){let t=this;function n(n){return new Ur({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new Ur({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n){return new ti(n,t.session,t.dialect,e)}function a(n){return new $r(n,t.session,t.dialect,e)}function o(n){return new Nr(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,update:i,insert:a,delete:o}}select(e){return new Ur({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Ur({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new ti(e,this.session,this.dialect)}$cache;insert(e){return new $r(e,this.session,this.dialect)}delete(e){return new Nr(e,this.session,this.dialect)}run(e){let t=typeof e==`string`?z.raw(e):e.getSQL();return this.resultKind===`async`?new si(async()=>this.session.run(t),()=>t,`run`,this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(t)}all(e){let t=typeof e==`string`?z.raw(e):e.getSQL();return this.resultKind===`async`?new si(async()=>this.session.all(t),()=>t,`all`,this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(t)}get(e){let t=typeof e==`string`?z.raw(e):e.getSQL();return this.resultKind===`async`?new si(async()=>this.session.get(t),()=>t,`get`,this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(t)}values(e){let t=typeof e==`string`?z.raw(e):e.getSQL();return this.resultKind===`async`?new si(async()=>this.session.values(t),()=>t,`values`,this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}},li=class{static[F]=`Cache`},ui=class extends li{strategy(){return`all`}static[F]=`NoopCache`;async get(e){}async put(e,t,n,r){}async onMutate(e){}};async function di(e,t){let n=`${e}-${JSON.stringify(t)}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}var fi=class extends Lt{constructor(e){super(),this.resultCb=e}static[F]=`ExecuteResultSync`;async execute(){return this.resultCb()}sync(){return this.resultCb()}},pi=class{constructor(e,t,n,r,i,a){this.mode=e,this.executeMethod=t,this.query=n,this.cache=r,this.queryMetadata=i,this.cacheConfig=a,r&&r.strategy()===`all`&&a===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}static[F]=`PreparedQuery`;joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||I(this.cache,ui)||this.queryMetadata===void 0)try{return await n()}catch(n){throw new Mt(e,t,n)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(n){throw new Mt(e,t,n)}if((this.queryMetadata.type===`insert`||this.queryMetadata.type===`update`||this.queryMetadata.type===`delete`)&&this.queryMetadata.tables.length>0)try{let[e]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return e}catch(n){throw new Mt(e,t,n)}if(!this.cacheConfig)try{return await n()}catch(n){throw new Mt(e,t,n)}if(this.queryMetadata.type===`select`){let r=await this.cache.get(this.cacheConfig.tag??await di(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let r;try{r=await n()}catch(n){throw new Mt(e,t,n)}return await this.cache.put(this.cacheConfig.tag??await di(e,t),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return r}try{return await n()}catch(n){throw new Mt(e,t,n)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error(`Not implemented`)}mapGetResult(e,t){throw Error(`Not implemented`)}execute(e){return this.mode===`async`?this[this.executeMethod](e):new fi(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case`run`:return this.mapRunResult(e,t);case`all`:return this.mapAllResult(e,t);case`get`:return this.mapGetResult(e,t)}}},mi=class{constructor(e){this.dialect=e}static[F]=`SQLiteSession`;prepareOneTimeQuery(e,t,n,r,i,a,o){return this.prepareQuery(e,t,n,r,i,a,o)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,`run`,!1).run()}catch(e){throw new jt({cause:e,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,`run`,!1).all()}extractRawAllValueFromBatchResult(e){throw Error(`Not implemented`)}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,`run`,!1).get()}extractRawGetValueFromBatchResult(e){throw Error(`Not implemented`)}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,`run`,!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error(`Not implemented`)}},hi=class extends ci{constructor(e,t,n,r,i=0){super(e,t,n,r),this.schema=r,this.nestedIndex=i}static[F]=`SQLiteTransaction`;rollback(){throw new Nt}},gi=class extends mi{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new It,this.cache=r.cache??new ui}static[F]=`SQLiteD1Session`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new yi(this.client.prepare(e.sql),e,this.logger,this.cache,a,o,t,n,r,i)}async batch(e){let t=[],n=[];for(let r of e){let e=r._prepare(),i=e.getQuery();if(t.push(e),i.params.length>0)n.push(e.stmt.bind(...i.params));else{let t=e.getQuery();n.push(this.client.prepare(t.sql).bind(...t.params))}}return(await this.client.batch(n)).map((e,n)=>t[n].mapResult(e,!0))}extractRawAllValueFromBatchResult(e){return e.results}extractRawGetValueFromBatchResult(e){return e.results[0]}extractRawValuesValueFromBatchResult(e){return vi(e.results)}async transaction(e,t){let n=new _i(`async`,this.dialect,this,this.schema);await this.run(z.raw(`begin${t?.behavior?` `+t.behavior:``}`));try{let t=await e(n);return await this.run(z`commit`),t}catch(e){throw await this.run(z`rollback`),e}}},_i=class e extends hi{static[F]=`D1Transaction`;async transaction(t){let n=`sp${this.nestedIndex}`,r=new e(`async`,this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(z.raw(`savepoint ${n}`));try{let e=await t(r);return await this.session.run(z.raw(`release savepoint ${n}`)),e}catch(e){throw await this.session.run(z.raw(`rollback to savepoint ${n}`)),e}}};function vi(e){let t=[];for(let n of e){let e=Object.keys(n).map(e=>n[e]);t.push(e)}return t}var yi=class extends pi{constructor(e,t,n,r,i,a,o,s,c,l){super(`async`,s,t,r,i,a),this.logger=n,this._isResponseInArrayMode=c,this.customResultMapper=l,this.fields=o,this.stmt=e}static[F]=`D1PreparedQuery`;customResultMapper;fields;stmt;async run(e){let t=St(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>this.stmt.bind(...t).run())}async all(e){let{fields:t,query:n,logger:r,stmt:i,customResultMapper:a}=this;if(!t&&!a){let t=St(n.params,e??{});return r.logQuery(n.sql,t),await this.queryWithCache(n.sql,t,async()=>i.bind(...t).all().then(({results:e})=>this.mapAllResult(e)))}let o=await this.values(e);return this.mapAllResult(o)}mapAllResult(e,t){return t&&(e=vi(e.results)),!this.fields&&!this.customResultMapper?e:this.customResultMapper?this.customResultMapper(e):e.map(e=>Rt(this.fields,e,this.joinsNotNullableMap))}async get(e){let{fields:t,joinsNotNullableMap:n,query:r,logger:i,stmt:a,customResultMapper:o}=this;if(!t&&!o){let t=St(r.params,e??{});return i.logQuery(r.sql,t),await this.queryWithCache(r.sql,t,async()=>a.bind(...t).all().then(({results:e})=>e[0]))}let s=await this.values(e);if(s[0])return o?o(s):Rt(t,s[0],n)}mapGetResult(e,t){return t&&(e=vi(e.results)[0]),!this.fields&&!this.customResultMapper?e:this.customResultMapper?this.customResultMapper([e]):Rt(this.fields,e,this.joinsNotNullableMap)}async values(e){let t=St(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>this.stmt.bind(...t).raw())}isResponseInArrayMode(){return this._isResponseInArrayMode}},bi=class extends ci{static[F]=`D1Database`;async batch(e){return this.session.batch(e)}};function xi(e,t={}){let n=new Vr({casing:t.casing}),r;t.logger===!0?r=new Ft:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=kn(t.schema,Pn);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new bi(`async`,n,new gi(e,n,i,{logger:r,cache:t.cache}),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}var Si=a({account:()=>Ti,accountRelations:()=>ji,articles:()=>Di,articlesRelations:()=>Mi,bookmarks:()=>Oi,bookmarksRelations:()=>Ni,session:()=>wi,sessionRelations:()=>Ai,user:()=>Ci,userRelations:()=>ki,verification:()=>Ei}),Ci=Er(`user`,{id:B(`id`).primaryKey(),name:B(`name`).notNull(),email:B(`email`).notNull().unique(),emailVerified:sr(`email_verified`,{mode:`boolean`}).default(!1).notNull(),image:B(`image`),createdAt:sr(`created_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),updatedAt:sr(`updated_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).$onUpdate(()=>new Date).notNull()}),wi=Er(`session`,{id:B(`id`).primaryKey(),expiresAt:sr(`expires_at`,{mode:`timestamp_ms`}).notNull(),token:B(`token`).notNull().unique(),createdAt:sr(`created_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),updatedAt:sr(`updated_at`,{mode:`timestamp_ms`}).$onUpdate(()=>new Date).notNull(),ipAddress:B(`ip_address`),userAgent:B(`user_agent`),userId:B(`user_id`).notNull().references(()=>Ci.id,{onDelete:`cascade`})},e=>[Ar(`session_userId_idx`).on(e.userId)]),Ti=Er(`account`,{id:B(`id`).primaryKey(),issuer:B(`issuer`).notNull(),accountId:B(`account_id`).notNull(),providerId:B(`provider_id`).notNull(),userId:B(`user_id`).notNull().references(()=>Ci.id,{onDelete:`cascade`}),accessToken:B(`access_token`),refreshToken:B(`refresh_token`),idToken:B(`id_token`),accessTokenExpiresAt:sr(`access_token_expires_at`,{mode:`timestamp_ms`}),refreshTokenExpiresAt:sr(`refresh_token_expires_at`,{mode:`timestamp_ms`}),scope:B(`scope`),password:B(`password`),createdAt:sr(`created_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),updatedAt:sr(`updated_at`,{mode:`timestamp_ms`}).$onUpdate(()=>new Date).notNull()},e=>[jr(`account_issuer_accountId_uidx`).on(e.issuer,e.accountId),Ar(`account_userId_idx`).on(e.userId)]),Ei=Er(`verification`,{id:B(`id`).primaryKey(),identifier:B(`identifier`).notNull(),value:B(`value`).notNull(),expiresAt:sr(`expires_at`,{mode:`timestamp_ms`}).notNull(),createdAt:sr(`created_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull(),updatedAt:sr(`updated_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).$onUpdate(()=>new Date).notNull()},e=>[Ar(`verification_identifier_idx`).on(e.identifier)]),Di=Er(`articles`,{id:B(`id`).primaryKey(),slug:B(`slug`).notNull().unique(),title:B(`title`).notNull(),excerpt:B(`excerpt`).notNull(),body:B(`body`).notNull(),author:B(`author`).notNull(),publishedAt:sr(`published_at`,{mode:`timestamp_ms`}).notNull()},e=>[Ar(`articles_publishedAt_idx`).on(e.publishedAt)]),Oi=Er(`bookmarks`,{id:B(`id`).primaryKey(),userId:B(`user_id`).notNull().references(()=>Ci.id,{onDelete:`cascade`}),articleId:B(`article_id`).notNull().references(()=>Di.id,{onDelete:`cascade`}),createdAt:sr(`created_at`,{mode:`timestamp_ms`}).default(z`(cast(unixepoch('subsecond') * 1000 as integer))`).notNull()},e=>[jr(`bookmarks_user_article_uidx`).on(e.userId,e.articleId),Ar(`bookmarks_userId_idx`).on(e.userId)]),ki=An(Ci,({many:e})=>({sessions:e(wi),accounts:e(Ti),bookmarks:e(Oi)})),Ai=An(wi,({one:e})=>({user:e(Ci,{fields:[wi.userId],references:[Ci.id]})})),ji=An(Ti,({one:e})=>({user:e(Ci,{fields:[Ti.userId],references:[Ci.id]})})),Mi=An(Di,({many:e})=>({bookmarks:e(Oi)})),Ni=An(Oi,({one:e})=>({user:e(Ci,{fields:[Oi.userId],references:[Ci.id]}),article:e(Di,{fields:[Oi.articleId],references:[Di.id]})}));function Pi(e){return xi(e,{schema:Si})}function Fi(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function Ii(e){let t=``;for(let n=0;n<e.length;n++)t+=Fi(e[n]);return t}function Li(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${Li(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=Ii(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`){l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);continue}for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=Fi(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:Fi(t)}c+=l}}return c}function Ri(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function zi(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=Li(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=Ri.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}function Bi(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var V=Bi({USER_NOT_FOUND:`User not found`,FAILED_TO_CREATE_USER:`Failed to create user`,FAILED_TO_CREATE_SESSION:`Failed to create session`,FAILED_TO_UPDATE_USER:`Failed to update user`,FAILED_TO_GET_SESSION:`Failed to get session`,INVALID_PASSWORD:`Invalid password`,INVALID_EMAIL:`Invalid email`,INVALID_EMAIL_OR_PASSWORD:`Invalid email or password`,INVALID_USER:`Invalid user`,SOCIAL_ACCOUNT_ALREADY_LINKED:`Social account already linked`,PROVIDER_NOT_FOUND:`Provider not found`,INVALID_TOKEN:`Invalid token`,TOKEN_EXPIRED:`Token expired`,ID_TOKEN_NOT_SUPPORTED:`id_token not supported`,FAILED_TO_GET_USER_INFO:`Failed to get user info`,USER_EMAIL_NOT_FOUND:`User email not found`,EMAIL_NOT_VERIFIED:`Email not verified`,PASSWORD_TOO_SHORT:`Password too short`,PASSWORD_TOO_LONG:`Password too long`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,EMAIL_CAN_NOT_BE_UPDATED:`Email can not be updated`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,CREDENTIAL_ACCOUNT_NOT_FOUND:`Credential account not found`,SESSION_EXPIRED:`Session expired. Re-authenticate to perform this action.`,FAILED_TO_UNLINK_LAST_ACCOUNT:`You can't unlink your last account`,ACCOUNT_NOT_FOUND:`Account not found`,USER_ALREADY_HAS_PASSWORD:`User already has a password. Provide that to delete the account.`,CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:`Cross-site navigation login blocked. This request appears to be a CSRF attack.`,VERIFICATION_EMAIL_NOT_ENABLED:`Verification email isn't enabled`,EMAIL_ALREADY_VERIFIED:`Email is already verified`,EMAIL_MISMATCH:`Email mismatch`,SESSION_NOT_FRESH:`Session is not fresh`,LINKED_ACCOUNT_ALREADY_EXISTS:`Linked account already exists`,INVALID_ORIGIN:`Invalid origin`,INVALID_CALLBACK_URL:`Invalid callbackURL`,INVALID_REDIRECT_URL:`Invalid redirectURL`,INVALID_ERROR_CALLBACK_URL:`Invalid errorCallbackURL`,INVALID_NEW_USER_CALLBACK_URL:`Invalid newUserCallbackURL`,MISSING_OR_NULL_ORIGIN:`Missing or null Origin`,CALLBACK_URL_REQUIRED:`callbackURL is required`,FAILED_TO_CREATE_VERIFICATION:`Unable to create verification`,FIELD_NOT_ALLOWED:`Field not allowed to be set`,ASYNC_VALIDATION_NOT_SUPPORTED:`Async validation is not supported`,VALIDATION_ERROR:`Validation Error`,MISSING_FIELD:`Field is required`,METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:`POST method requires deferSessionRefresh to be enabled in session config`,BODY_MUST_BE_AN_OBJECT:`Body must be an object`,PASSWORD_ALREADY_SET:`User already has a password set`}),Vi=47;function Hi(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function Ui(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Vi;)t--;return t===e.length?e:e.slice(0,t)}function Wi(e){try{return(Ui(new URL(e).pathname)||`/`)!==`/`}catch{throw new b(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Gi(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new b(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof b?t:new b(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function Ki(e,t=`/api/auth`){if(Gi(e),Wi(e))return e;let n=Ui(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function qi(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function Ji(e,t,n,r,i){if(e)return Ki(e,t);if(r!==!1){let e=v.BETTER_AUTH_URL||v.NEXT_PUBLIC_BETTER_AUTH_URL||v.PUBLIC_BETTER_AUTH_URL||v.NUXT_PUBLIC_BETTER_AUTH_URL||v.NUXT_PUBLIC_AUTH_URL||(v.BASE_URL===`/`?void 0:v.BASE_URL);if(e)return Ki(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&qi(o,`proto`)&&qi(a,`host`))try{return Ki(`${o}://${a}`,t)}catch{}if(n){let e=Yi(n.url);if(!e)throw new b(`Could not get origin from request. Please provide a valid base URL.`);return Ki(e,t)}if(typeof window<`u`&&window.location)return Ki(window.location.origin,t)}function Yi(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function Xi(e){try{return new URL(e).protocol}catch{return null}}function Zi(e){try{return new URL(e).host}catch{return null}}function Qi(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function $i(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function ea(e,t){let n=$i(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&qi(e,`host`))return e}let r=n.get(`host`);if(r&&qi(r,`host`))return r;if($i(e))try{return new URL(e.url).host}catch{return null}return null}function ta(e,t,n){if(t===`http`||t===`https`)return t;let r=$i(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&qi(e,`proto`))return e}if($i(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=ea(e,n);return i&&Hi(i)?`http`:`https`}var na=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?zi(r)(n):n.toLowerCase()===r.toLowerCase()};function ra(e,t,n,r){let i=ea(t,r);if(!i){if(e.fallback)return Ki(e.fallback,n);throw new b(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>na(i,e)))return Ki(`${ta(t,e.protocol,r)}://${i}`,n);if(e.fallback)return Ki(e.fallback,n);throw new b(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function ia(e,t,n,r,i){if(Qi(e))return n?ra(e,n,t,i):e.fallback?Ki(e.fallback,t):Ji(void 0,t,void 0,r,i);let a=$i(n)?n:void 0;return Ji(typeof e==`string`?e:void 0,t,a,r,i)}var aa=D(`a-z`,`0-9`,`A-Z`,`-_`);function oa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var sa=e=>e?`"${e}" `:``;function ca(e,t=``){if(typeof e!=`number`)throw TypeError(sa(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(sa(t)+`expected integer >= 0, got `+e);return e}function la(e,t,n=``){if(oa(e)&&(t===void 0||e.length===t))return e;t!==void 0&&ca(t,`length`);let r=oa(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=sa(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}function ua(e){if(typeof e!=`function`||typeof e.create!=`function`)throw TypeError(`expected hash wrapped by utils.createHasher`);if(ca(e.outputLen),ca(e.blockLen),e.outputLen<1||e.blockLen<1)throw Error(`hash blockLen / outputLen must be >= 1`)}var da=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)};function fa(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function pa(e,t){la(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ma(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function ha(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ga(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _a(e,t){return e<<32-t|e>>>t}function H(e,t){return e<<t|e>>>32-t>>>0}var va=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ya(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ba(e){for(let t=0;t<e.length;t++)e[t]=ya(e[t]);return e}var xa=va?e=>e:ba,Sa=async()=>{};async function Ca(e,t,n){if(ca(e,`iters`),ca(t,`tick`),typeof n!=`function`)throw TypeError(`callback must be a function`);let r=Date.now();for(let i=0;i<e;i++){n(i);let e=Date.now()-r;e>=0&&e<t||(await Sa(),r+=e)}}function wa(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function Ta(e,t=``){return typeof e==`string`?wa(e):la(e,void 0,t)}function Ea(e,t,n=`opts`){return da(e,`defaults`),t!==void 0&&da(t,n),Object.assign(e,t)}function Da(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Ea({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}var Oa=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),ka=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ua(e),la(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),ha(r)}update(e){return fa(this),this.iHash.update(e),this}digestInto(e){fa(this),pa(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Aa=(()=>{let e=((e,t,n)=>new ka(e,t).update(n).digest());return e.create=(e,t)=>new ka(e,t),e})(),ja=Uint8Array.of(0),Ma=Uint8Array.of();function Na(e,t,n,r=32,i){ua(e),ca(r,`length`),la(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Ma:la(n,void 0,`info`),!o)return i&&ha(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Aa.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){ja[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(ja).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(ja[0]=o,o>1&&c.update(u),c.update(n).update(ja).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&ha(u),ha(ja),r===s.length)return s;let f=s.slice(0,r);return ha(s),f}var Pa=(e,t,n,r,i)=>{ua(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Aa.create(e,n).update(t);return Na(e,a.digest(),r,i,a)},Fa=e=>e/2**32|0,Ia=e=>e>>>0;function La(e,t,n,r){let i=Fa(n),a=Ia(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Ra(e,t,n){return e&t^~e&n}function za(e,t,n){return e&t^e&n^t&n}var Ba=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=ga(this.buffer)}update(e){fa(this),la(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=ga(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){fa(this),pa(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),La(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:ga(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Va=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ha=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ua=new Uint32Array(64),Wa=class extends Ba{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Ua[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ua[e-15],n=Ua[e-2],r=_a(t,7)^_a(t,18)^t>>>3,i=_a(n,17)^_a(n,19)^n>>>10;Ua[e]=i+Ua[e-7]+r+Ua[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=_a(o,6)^_a(o,11)^_a(o,25),u=l+t+Ra(o,s,c)+Ha[e]+Ua[e]|0,d=(_a(n,2)^_a(n,13)^_a(n,22))+za(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ha(Ua)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ha(this.buffer)}},Ga=class extends Wa{constructor(){super(32,Va)}},Ka=Da(()=>new Ga,Oa(1)),qa=new TextEncoder,Ja=new TextDecoder,Ya=new TextDecoder(`utf-8`,{fatal:!0}),Xa=2**32;function Za(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Qa(e,t,n){if(t<0||t>=Xa)throw RangeError(`value must be >= 0 and <= ${Xa-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function $a(e){let t=Math.floor(e/Xa),n=e%Xa,r=new Uint8Array(8);return Qa(r,t,0),Qa(r,n,4),r}function eo(e){let t=new Uint8Array(4);return Qa(t,e),t}function to(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}var no=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function ro(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function io(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function ao(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw no(t.name);if(t.hash&&r.hash?.name!==t.hash)throw no(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw no(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw no(t.length,`algorithm.length`);ro(e,n)}function oo(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var so=(e,...t)=>oo(`Key must be `,e,...t),co=(e,t,...n)=>oo(`Key for the ${e} algorithm must be `,t,...n),lo=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},uo=class extends lo{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},fo=class extends lo{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},po=class extends lo{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},mo=class extends lo{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},ho=class extends lo{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},U=class extends lo{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},go=class extends lo{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},_o=class extends lo{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},vo=class extends lo{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},yo=class extends lo{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},bo=class extends lo{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},xo=class extends lo{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},So=class extends lo{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Co=class extends lo{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function wo(e){if(!To(e))throw Error(`CryptoKey instance expected`)}var To=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Eo=e=>e?.[Symbol.toStringTag]===`KeyObject`,Do=e=>To(e)||Eo(e),Oo=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function ko(e,t){let n=e.byteLength<<3;if(n!==t)throw new U(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var Ao=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function jo(e,t){if(t.length<<3!==e.ivBits)throw new U(`Invalid Initialization Vector length`)}async function Mo(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(so(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function No(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function Po(e,t,n,r,i){let[a,o,s]=await Mo(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await No(o,Za(i,r,c,$a(i.length*8)),s),iv:r}}async function Fo(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function Io(e,t,n,r,i,a){let[o,s,c]=await Mo(e,t,`decrypt`),l=await No(s,Za(a,r,n,$a(a.length*8)),c),u;try{u=await Fo(i,l)}catch{}if(!u)throw new ho;let d;try{d=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}if(!d)throw new ho;return d}async function Lo(e,t,n,r,i){let a=n instanceof Uint8Array?await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(ao(n,e.subtle,`encrypt`),n),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function Ro(e,t,n,r,i,a){let o=t instanceof Uint8Array?await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(ao(t,e.subtle,`decrypt`),t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,Za(n,i)))}catch{throw new ho}}async function zo(e,t,n,r,i){if(!To(n)&&!(n instanceof Uint8Array))throw TypeError(so(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));return r?jo(e,r):r=Ao(e),n instanceof Uint8Array&&ko(n,e.cekBits),e.cbc?Po(e,t,n,r,i):Lo(e,t,n,r,i)}async function Bo(e,t,n,r,i,a){if(!To(t)&&!(t instanceof Uint8Array))throw TypeError(so(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new U(`JWE Initialization Vector missing`);if(!i)throw new U(`JWE Authentication Tag missing`);return jo(e,r),t instanceof Uint8Array&&ko(t,e.cekBits),e.cbc?Io(e,t,n,r,i,a):Ro(e,t,n,r,i,a)}function Vo(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function Ho(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Uo=`The input to be decoded is not correctly encoded.`;function Wo(e){if(Uint8Array.fromBase64)try{return Uint8Array.fromBase64(typeof e==`string`?e:Ja.decode(e),{alphabet:`base64url`})}catch(e){throw TypeError(Uo,{cause:e})}let t=e;if(t instanceof Uint8Array&&(t=Ja.decode(t)),t.includes(`+`)||t.includes(`/`))throw TypeError(Uo);t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Ho(t)}catch{throw TypeError(Uo)}}function Go(e){let t=e;return typeof t==`string`&&(t=qa.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:`base64url`,omitPadding:!0}):Vo(t).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function Ko(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let n=t;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return t===n}function qo(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}var Jo=e=>Ko(e)&&typeof e.kty==`string`,Yo=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Xo=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Zo=e=>e.kty===`oct`&&typeof e.k==`string`,Qo=Symbol();function $o(e,t){if(e)throw TypeError(`${t} can only be called once`)}function es(e,t,n){try{return Wo(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function ts(e,t,n){try{return to(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}async function ns(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}function rs(e,t,n){let r;try{r=JSON.parse(Ya.decode(Wo(e)))}catch{throw new t(n)}if(!Ko(r))throw new t(n);return r}async function is(e,t){if(t.kty===`RSA`&&`oth`in t&&t.oth!==void 0)throw new mo(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);if(!e.kty.includes(t.kty))throw new mo(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let n=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,r=!!(t.d||t.priv),i={...t};return i.kty!==`AKP`&&delete i.alg,delete i.use,crypto.subtle.importKey(`jwk`,i,n,t.ext??!r,t.key_ops??e.usages[+!!r])}var as=e=>e[Symbol.toStringTag],os=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};function ss(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return[cs,t];if(Jo(t)){if(i?!Zo(t):!(a?Yo(t):Xo(t)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);return os(e,t,n),[ds,t]}if(!Do(t))throw TypeError(i?co(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`):co(r,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(i){if(t.type!==`secret`)throw TypeError(`${as(t)} instances for symmetric algorithms must be of type "secret"`)}else{if(t.type===`secret`)throw TypeError(`${as(t)} instances for asymmetric algorithms must not be of type "secret"`);let e=a?`private`:`public`;if((t.type===`public`||t.type===`private`)&&t.type!==e){let r=n===`sign`?`signing`:n===`verify`?`verifying`:`${n.slice(0,-1)}tion`;throw TypeError(`${as(t)} instances for asymmetric algorithm ${r} must be of type "${e}"`)}}return To(t)?[ls,t]:[us,t]}var cs=0,ls=1,us=2,ds=3,fs,ps={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function ms(e,t,n){fs||=new WeakMap;let r=fs.get(e);return n&&(r?r[t]=n:fs.set(e,{__proto__:null,[t]:n})),n??r?.[t]}var hs=async(e,t,n)=>ms(e,n.alg)??ms(e,n.alg,await is(n,{...t,alg:n.alg})),gs=(e,t)=>{let n=ms(e,t.alg);if(n)return n;let r=e.type===`public`,i=t.usages[+!r],{asymmetricKeyType:a}=e,o=ps[e.asymmetricKeyDetails?.namedCurve],s=t.resolve?.({crv:o,asymmetricKeyType:a})??t.subtle;return ms(e,t.alg,e.toCryptoKey(s,r,i))};async function _s(e,t,n){let r=ss(e,t,n);switch(r[0]){case cs:case ls:return r[1];case ds:{let t=r[1];if(t.k)return Wo(t.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}return hs(t,t,e)}case us:{let t=r[1];return t.type===`secret`?t.export():`toCryptoKey`in t&&typeof t.toCryptoKey==`function`?gs(t,e):hs(t,t.export({format:`jwk`}),e)}}}function vs(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var ys=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],bs=[[],[`deriveBits`]],xs=[[],[]];function Ss(e){return{kty:[`RSA`],subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:ys,ops:[`wrapKey`,`unwrapKey`]}}function Cs(){return{kty:[`EC`,`OKP`],subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new mo(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:bs,ops:[void 0,`deriveBits`]}}function ws(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:xs,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function Ts(){return{kty:[`oct`],secret:!0,subtle:{name:`PBKDF2`},usages:xs,ops:[`deriveBits`,`deriveBits`]}}var Es=vs({dir:{kty:[`oct`],secret:!0,subtle:{name:`AES-GCM`},usages:xs,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":Ss(1),"RSA-OAEP-256":Ss(256),"RSA-OAEP-384":Ss(384),"RSA-OAEP-512":Ss(512),"ECDH-ES":Cs(),"ECDH-ES+A128KW":Cs(),"ECDH-ES+A192KW":Cs(),"ECDH-ES+A256KW":Cs(),A128KW:ws(128),A192KW:ws(192),A256KW:ws(256),A128GCMKW:ws(128,!0),A192GCMKW:ws(192,!0),A256GCMKW:ws(256,!0),"PBES2-HS256+A128KW":Ts(),"PBES2-HS384+A192KW":Ts(),"PBES2-HS512+A256KW":Ts()}),Ds=[`encrypt`,`decrypt`];function Os(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:xs,ops:Ds,cekBits:e,ivBits:t?128:96,cbc:t}}var ks=vs({A128GCM:Os(128),A192GCM:Os(192),A256GCM:Os(256),"A128CBC-HS256":Os(256,!0),"A192CBC-HS384":Os(384,!0),"A256CBC-HS512":Os(512,!0)});function As(e,t){throw new mo(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function js(e){return(typeof e==`string`?Es[e]:void 0)??As(`alg`,`Algorithm`)}function Ms(e){return(typeof e==`string`?ks[e]:void 0)??As(`enc`,`Encryption Algorithm`)}function Ns(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);ro(e,t)}async function Ps(e,t,n){let r=js(t).subtle,i=e instanceof Uint8Array?await crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):e;return ao(i,r,n),i}async function Fs(e,t,n){let r=await Ps(t,e,`wrapKey`),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Is(e,t,n){let r=await Ps(t,e,`unwrapKey`),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Ls(e,t,n){ao(t,js(e).subtle,n),io(e,t)}function Rs(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(ao(e,js(t).subtle,`deriveBits`),e)}async function zs(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new U(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new U(`PBES2 Count Input must be a positive integer`);let i=Za(to(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Rs(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function Bs(e){return Za(eo(e.length),e)}async function Vs(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await ns(`sha256`,Za(eo(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Hs(e,t,n,r,i=new Uint8Array,a=new Uint8Array){Ns(e),Ns(t,`deriveBits`);let o=Za(Bs(to(n)),Bs(i),Bs(a),eo(r));return Vs(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function Us(e){wo(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new mo(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Ws(e){if(e===void 0)throw new U(`JWE Encrypted Key missing`)}function Gs(e){if(e!==void 0)throw new U(`Encountered unexpected JWE Encrypted Key`)}async function Ks(e,t,n,r,i,a){let o=js(e);if(e===`dir`)return Gs(r),n;switch(o.subtle.name){case`ECDH`:{if(e===`ECDH-ES`&&Gs(r),!Ko(i.epk))throw new U(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);Us(n);let a=await is(o,i.epk),s,c;if(i.apu!==void 0){if(typeof i.apu!=`string`)throw new U(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);s=es(i.apu,`apu`,U)}if(i.apv!==void 0){if(typeof i.apv!=`string`)throw new U(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);c=es(i.apv,`apv`,U)}let l=await Hs(a,n,e===`ECDH-ES`?t.alg:e,e===`ECDH-ES`?t.cekBits:parseInt(e.slice(-5,-2),10),s,c);return e===`ECDH-ES`?l:(Ws(r),Is(e.slice(-6),l,r))}case`RSA-OAEP`:return Ws(r),wo(n),Ls(e,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(Ws(r),typeof i.p2c!=`number`)throw new U(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let t=a?.maxPBES2Count||1e4;if(i.p2c>t)throw new U(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new U(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o=await zs(es(i.p2s,`p2s`,U),e,i.p2c,n);return Is(e.slice(-6),o,r)}case`AES-KW`:return Ws(r),Is(e,n,r);case`AES-GCM`:{if(Ws(r),typeof i.iv!=`string`)throw new U(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new U(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let t;t=es(i.iv,`iv`,U);let a;return a=es(i.tag,`tag`,U),Bo(Ms(e.slice(0,-2)),n,r,t,a,new Uint8Array)}}}async function qs(e,t,n,r,i={}){let a,o,s,c=js(e);if(e===`dir`)return[n,void 0,void 0];switch(c.subtle.name){case`ECDH`:{Us(n);let{apu:l,apv:u}=i,d;d=i.epk?await _s(c,i.epk,`decrypt`):(await crypto.subtle.generateKey(n.algorithm,!0,[`deriveBits`])).privateKey;let f=crypto.subtle,p=d;if(!p.extractable){if(typeof f.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);p=await f.getPublicKey(d,[])}let{x:m,y:h,crv:g,kty:_}=await f.exportKey(`jwk`,p),v=await Hs(n,d,e===`ECDH-ES`?t.alg:e,e===`ECDH-ES`?t.cekBits:parseInt(e.slice(-5,-2),10),l,u);if(o={epk:{x:m,crv:g,kty:_}},_===`EC`&&(o.epk.y=h),l&&(o.apu=Go(l)),u&&(o.apv=Go(u)),e===`ECDH-ES`){s=v;break}s=r||Oo(t),a=await Fs(e.slice(-6),v,s);break}case`RSA-OAEP`:s=r||Oo(t),wo(n),Ls(e,n,`encrypt`),a=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,n,s));break;case`PBKDF2`:{s=r||Oo(t);let{p2c:c=2048,p2s:l=crypto.getRandomValues(new Uint8Array(16))}=i,u=await zs(l,e,c,n);a=await Fs(e.slice(-6),u,s),o={p2c:c,p2s:Go(l)};break}case`AES-KW`:s=r||Oo(t),a=await Fs(e,n,s);break;case`AES-GCM`:{s=r||Oo(t);let{iv:c}=i,l=await zo(Ms(e.slice(0,-2)),s,n,c,new Uint8Array);a=l.ciphertext,o={iv:Go(l.iv),tag:Go(l.tag)};break}}return[s,a,o]}var Js={__proto__:null,b64:!0},Ys={__proto__:null};function Xs(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}function Zs(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function Qs(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new mo(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function $s(e){if(globalThis[e]===void 0)throw new mo(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function ec(e){$s(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],i=t.readable.getReader();for(;;){let{value:e,done:t}=await i.read();if(t)break;r.push(e)}return Za(...r)}async function tc(e,t){$s(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=n.readable.getReader();for(;;){let{value:e,done:n}=await o.read();if(n)break;if(i.push(e),a+=e.byteLength,t!==1/0&&a>t)throw new U(`Decompressed plaintext exceeded the configured limit`)}return Za(...i)}function nc(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;t&&(o=rs(t,U,`JWE Protected Header is invalid`));let s=t===void 0?new Uint8Array:to(t);return[o,es(n,`ciphertext`,U),r===void 0?void 0:es(r,`iv`,U),i===void 0?void 0:es(i,`tag`,U),a===void 0?s:Za(s,to(`.`),ts(a,`aad`,U))]}function rc(e){return[e&&Xs(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&Xs(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e]}async function ic(e,t,n,r){let[i,a,o]=n,[s,c,l,u,d]=t,{encrypted_key:f,header:p,unprotected:m}=e,h;if(p!==void 0||m!==void 0){if(!qo(s,p,m))throw new U(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);h={...s,...p,...m}}else h=s??{};if(Qs(U,Ys,o?.crit,s,h),h.zip!==void 0&&h.zip!==`DEF`)throw new mo(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(h.zip!==void 0&&!s?.zip)throw new U(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:g,enc:_}=h;if(typeof g!=`string`||!g)throw new U(`missing JWE Algorithm (alg) in JWE Header`);if(typeof _!=`string`||!_)throw new U(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(i&&!i.has(g)||!i&&g.startsWith(`PBES2`))throw new po(`"alg" (Algorithm) Header Parameter value not allowed`);if(a&&!a.has(_))throw new po(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let v=Ms(_),y;f!==void 0&&(y=es(f,`encrypted_key`,U));let ee=!1;typeof r==`function`&&(r=await r(s,e),ee=!0);let te=js(g),b=await _s(g===`dir`?v:te,r,`decrypt`),x;try{x=await Ks(g,v,b,y,h,o)}catch(e){if(e instanceof TypeError||e instanceof U||e instanceof mo)throw e;x=Oo(v)}let S=await Bo(v,x,c,l,u,d);if(h.zip===`DEF`){let e=o?.maxDecompressedLength??25e4;if(e===0)throw new mo(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);S=await tc(S,e).catch(e=>{throw e instanceof U?e:new U(`Failed to decompress plaintext`,{cause:e})})}return[S,s,b,ee]}async function ac(e,t,n){return ic(e,nc(e),t,n)}async function oc(e,t,n){if(e instanceof Uint8Array&&(e=Ja.decode(e)),typeof e!=`string`)throw new U(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new U(`Invalid Compact JWE`);return ac({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function sc(e,t,n){if(!qo(e,t,n))throw new U(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function cc(e){let[,t,n,r,,,,,i]=e;sc(t,n,r);let a={...t,...n,...r};if(Qs(U,Ys,i,t,a),a.zip!==void 0&&a.zip!==`DEF`)throw new mo(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(a.zip!==void 0&&!t?.zip)throw new U(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:o,enc:s}=a;if(typeof o!=`string`||!o)throw new U(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof s!=`string`||!s)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[a,o,s,Ms(s)]}async function lc(e,t,n){let[r,i,,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c;if(d&&(i===`dir`||i===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);let _=js(i),[v,y,ee]=await qs(i,a,await _s(i===`dir`?a:_,n,`encrypt`),d,p);ee&&(m?g=g?{...g,...ee}:ee:h=h?{...h,...ee}:ee,sc(h,g,l));let te,b;h?(te=Go(JSON.stringify(h)),b=to(te)):(te=``,b=new Uint8Array);let x,S;u?.byteLength?(S=Go(u),x=Za(b,to(`.`),to(S))):x=b;let C=o;r.zip===`DEF`&&(C=await ec(C).catch(e=>{throw new U(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:w,tag:T,iv:E}=await zo(a,C,v,f,x),D={ciphertext:Go(w)};return E&&(D.iv=Go(E)),T&&(D.tag=Go(T)),y&&(D.encrypted_key=Go(y)),S&&(D.aad=S),h&&(D.protected=te),l&&(D.unprotected=l),g&&(D.header=g),D}async function uc(e,t){return lc(e,cc(e),t)}var dc=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this.#e=e}setKeyManagementParameters(e){return $o(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return $o(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return $o(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return $o(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return $o(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return $o(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new U(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);return Zs(U,this.#t),uc([this.#e,this.#t,this.#r,this.#n,this.#i,this.#a,this.#o,this.#s,t?.crit,t?Qo in t:!1],e)}};async function fc(e,t,n){return t instanceof Uint8Array?crypto.subtle.importKey(`raw`,t,e.subtle,!1,[n]):(ao(t,e.subtle,n),e.minRsaBits&&io(e.alg,t),t)}async function pc(e,t,n){let r=await fc(e,t,`sign`),i=await crypto.subtle.sign(e.signing,r,n);return new Uint8Array(i)}async function mc(e,t,n,r){let i=await fc(e,t,`verify`);try{return await crypto.subtle.verify(e.signing,i,n,r)}catch{return!1}}var hc=[[`verify`],[`sign`]];function gc(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:hc}}function _c(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:hc,minRsaBits:2048}}function vc(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:hc}}function yc(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:hc}}function bc(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:hc}}var xc=vs({HS256:gc(256),HS384:gc(384),HS512:gc(512),RS256:_c(256),RS384:_c(384),RS512:_c(512),PS256:_c(256,32),PS384:_c(384,48),PS512:_c(512,64),ES256:vc(`P-256`,256),ES384:vc(`P-384`,384),ES512:vc(`P-521`,512),EdDSA:yc(),Ed25519:yc(),"ML-DSA-44":bc(44),"ML-DSA-65":bc(65),"ML-DSA-87":bc(87)});function Sc(e){let t=typeof e==`string`?xc[e]:void 0;if(!t)throw new mo(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Cc(e){return[e&&Xs(`algorithms`,e.algorithms),e?.crit]}async function wc(e,t,n){let{protected:r,header:i,payload:a}=e,o={};r&&(o=rs(r,go,`JWS Protected Header is invalid`));let s;if(i!==void 0){if(!qo(o,i))throw new go(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);s={...o,...i}}else s=o;let c=Qs(go,Js,t[1],o,s),l=!0;if(c.includes(`b64`)&&(l=o.b64,typeof l!=`boolean`))throw new go(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:u}=s;if(typeof u!=`string`||!u)throw new go(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(u))throw new po(`"alg" (Algorithm) Header Parameter value not allowed`);if(l){if(typeof a!=`string`)throw new go(`JWS Payload must be a string`)}else if(typeof a!=`string`&&!(a instanceof Uint8Array))throw new go(`JWS Payload must be a string or an Uint8Array instance`);let d=!1;typeof n==`function`&&(n=await n(o,e),d=!0);let f=Sc(u),p=Za(r===void 0?new Uint8Array:to(r),to(`.`),typeof a==`string`?l?t[2]??=ts(a,`payload`,go):qa.encode(a):a),m=es(e.signature,`signature`,go),h=await _s(f,n,`verify`);if(!await mc(f,h,m,p))throw new Co;let g;return g=l?es(a,`payload`,go):typeof a==`string`?qa.encode(a):a,[g,o,l,h,d]}async function Tc(e,t,n){if(e instanceof Uint8Array&&(e=Ja.decode(e)),typeof e!=`string`)throw new go(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new go(`Invalid Compact JWS`);return wc({payload:i,protected:r,signature:a},t,n)}var Ec=e=>Math.floor(e.getTime()/1e3),Dc={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Oc=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,kc=`check_failed`;function Ac(e){let t=Oc.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=Math.round(n*Dc[t[3][0].toLowerCase()]);return t[1]===`-`||t[4]===`ago`?-r:r}function jc(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Mc(e,t){return typeof e==`number`?jc(t,e):e instanceof Date?jc(t,Ec(e)):Ec(new Date)+Ac(e)}var Nc=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,Pc=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Fc(e,t,n=!1){let r=e[t];if(!(r===void 0&&!n)){if(typeof r!=`number`)throw new uo(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Ic(e,t){throw new uo(`unexpected "${t}" claim value`,e,t,kc)}function Lc(e,t,n={}){let r;try{r=JSON.parse(Ya.decode(t))}catch{}if(!Ko(r))throw new _o(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Nc(e.typ)!==Nc(i)))throw new uo(`unexpected "typ" JWT header value`,r,`typ`,kc);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new uo(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Ic(r,`iss`),s!==void 0&&r.sub!==s&&Ic(r,`sub`),c!==void 0&&!Pc(r.aud,typeof c==`string`?[c]:c)&&Ic(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Ac(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}jc(`clockTolerance option`,f);let{currentDate:p}=n,m=jc(`currentDate option`,Ec(p||new Date)),h=Fc(r,`iat`,l!==void 0),g=Fc(r,`nbf`);if(g!==void 0&&g>m+f)throw new uo(`"nbf" claim timestamp check failed`,r,`nbf`,kc);let _=Fc(r,`exp`);if(_!==void 0&&_<=m-f)throw new fo(`"exp" claim timestamp check failed`,r,`exp`,kc);if(l!==void 0){let e=m-h,t=typeof l==`number`?l:Ac(l);if(e-f>t)throw new fo(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,kc);if(e<0-f)throw new uo(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,kc)}return r}var Rc=class{#e;constructor(e){if(!Ko(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return qa.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){this.#e.nbf=Mc(e,`setNotBefore`)}set exp(e){this.#e.exp=Mc(e,`setExpirationTime`)}set iat(e){e===void 0?this.#e.iat=Ec(new Date):typeof e==`string`?this.#e.iat=jc(`setIssuedAt`,Ec(new Date)+Ac(e)):this.#e.iat=Mc(e,`setIssuedAt`)}};async function zc(e,t,n){let r=await Tc(e,Cc(n),t);if(!r[2])throw new _o(`JWTs MUST NOT use unencoded payload`);let i={payload:Lc(r[1],r[0],n),protectedHeader:r[1]};return typeof t==`function`?{...i,key:r[3]}:i}async function Bc(e,t,n){let r=await oc(e,rc(n),t),i=r[1],a=Lc(i,r[0],n);if(i.iss!==void 0&&i.iss!==a.iss)throw new uo(`replicated "iss" claim header parameter mismatch`,a,`iss`,`mismatch`);if(i.sub!==void 0&&i.sub!==a.sub)throw new uo(`replicated "sub" claim header parameter mismatch`,a,`sub`,`mismatch`);if(i.aud!==void 0&&JSON.stringify(i.aud)!==JSON.stringify(a.aud))throw new uo(`replicated "aud" claim header parameter mismatch`,a,`aud`,`mismatch`);let o={payload:a,protectedHeader:i};return typeof t==`function`?{...o,key:r[2]}:o}var Vc=class{#e;constructor(e){this.#e=new dc(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this.#e.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}};function Hc(e){return e?.b64===!1&&Array.isArray(e.crit)&&e.crit.includes(`b64`)}async function Uc(e,t){let{protectedHeader:n,unprotectedHeader:r}=e;if(!n&&!r)throw new go(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!qo(n,r))throw new go(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...n,...r};Zs(go,n);let a=Qs(go,Js,e.crit,n,i),o=!0;if(a.includes(`b64`)&&(o=n.b64,typeof o!=`boolean`))throw new go(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new go(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=Sc(s),l,u;if(o){let t=e.encoded??=[];t[0]??=Go(e.payload),t[1]??=to(t[0]),l=t[0],u=t[1]}else u=e.payload,l=``;let d,f;n?(d=Go(JSON.stringify(n)),f=to(d)):(d=``,f=new Uint8Array);let p=Za(f,to(`.`),u),m={signature:Go(await pc(c,await _s(c,t,`sign`),p)),payload:l};return n&&(m.protected=d),r&&(m.header=r),m}var Wc=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return $o(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return $o(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){return Uc({payload:this.#e,protectedHeader:this.#t,unprotectedHeader:this.#n,crit:t?.crit},e)}},Gc=class{#e;#t;constructor(e){this.#e=new Wc(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this.#t=e,this}async sign(e,t){if(Hc(this.#t))throw TypeError(`use the flattened module for creating JWS with b64: false`);let n=await this.#e.sign(e,t);return`${n.protected}.${n.payload}.${n.signature}`}},Kc=class{#e;#t;constructor(e={}){this.#t=new Rc(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new Gc(this.#t.data());if(n.setProtectedHeader(this.#e),Hc(this.#e))throw new _o(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}},qc=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#s=new Rc(e)}setIssuer(e){return this.#s.iss=e,this}setSubject(e){return this.#s.sub=e,this}setAudience(e){return this.#s.aud=e,this}setJti(e){return this.#s.jti=e,this}setNotBefore(e){return this.#s.nbf=e,this}setExpirationTime(e){return this.#s.exp=e,this}setIssuedAt(e){return this.#s.iat=e,this}setProtectedHeader(e){return $o(this.#r,`setProtectedHeader`),this.#r=e,this}setKeyManagementParameters(e){return $o(this.#n,`setKeyManagementParameters`),this.#n=e,this}setContentEncryptionKey(e){return $o(this.#e,`setContentEncryptionKey`),this.#e=e,this}setInitializationVector(e){return $o(this.#t,`setInitializationVector`),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(e,t){let n=new Vc(this.#s.data());return this.#r&&(this.#i||this.#a||this.#o)&&(this.#r={...this.#r,iss:this.#i?this.#s.iss:void 0,sub:this.#a?this.#s.sub:void 0,aud:this.#o?this.#s.aud:void 0}),n.setProtectedHeader(this.#r),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#n&&n.setKeyManagementParameters(this.#n),n.encrypt(e,t)}};function Jc(e=`JWK "alg" (Algorithm) Parameter`){throw new mo(`Invalid or unsupported ${e} value`)}function Yc(e,t){return(typeof e==`string`?xc[e]??Es[e]:void 0)??Jc(t)}function Xc(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function Zc(e){if(Eo(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:Go(e)};if(!To(e))throw TypeError(so(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=Xc(await crypto.subtle.exportKey(`jwk`,e));return a.kty===`AKP`&&(a.alg=r),a}function Qc(e){return Zc(e)}var $c=(e,t)=>{if(typeof e!=`string`||!e)throw new vo(`${t} missing or invalid`)};async function el(e,t){let n;if(Jo(e))n=e;else if(Do(e))n=await Qc(e);else throw TypeError(so(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$c(n.alg,`"alg" (Algorithm) Parameter`),$c(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$c(n.crv,`"crv" (Curve) Parameter`),$c(n.x,`"x" (X Coordinate) Parameter`),$c(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$c(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$c(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$c(n.e,`"e" (Exponent) Parameter`),$c(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:$c(n.k,`"k" (Key Value) Parameter`),r={k:n.k,kty:n.kty};break;default:throw new mo(`"kty" (Key Type) Parameter missing or unsupported`)}let i=to(JSON.stringify(r));return Go(await ns(t,i))}function tl(e){let t=typeof e==`string`?xc[e]:void 0;if(!t||t.secret)throw new mo(`Unsupported "alg" value for a JSON Web Key Set`);return t}function nl(e){if(!e||typeof e!=`object`)return!1;let{keys:t}=e;return Array.isArray(t)&&t.every(Ko)}var rl=class{#e;#t=new WeakMap;constructor(e){if(!nl(e))throw new yo(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=tl(n),a=this.#e.keys.filter(e=>i.kty.includes(e.kty)&&(typeof r!=`string`||r===e.kid)&&(typeof e.alg!=`string`&&e.kty!==`AKP`||n===e.alg)&&(typeof e.use!=`string`||e.use===`sig`)&&(!Array.isArray(e.key_ops)||e.key_ops.includes(`verify`))&&(!i.crv||e.crv===i.crv)),{0:o,length:s}=a;if(s===0)throw new bo;if(s!==1){let e=new xo,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await il(t,e,i)}catch{}},e}return il(this.#t,o,i)}};async function il(e,t,n){let r=e.get(t)||e.set(t,{__proto__:null}).get(t);if(r[n.alg]===void 0){let e=await is(n,{...t,alg:n.alg,ext:!0});if(e.type!==`public`)throw new yo(`JSON Web Key Set members must be public keys`);r[n.alg]=e}return r[n.alg]}function al(e){let t=new rl(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperty(n,"jwks",{value:()=>structuredClone(t.jwks())}),n}function ol(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var sl;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(sl=`jose/v6.2.9`);var cl=Symbol();async function ll(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new So:e});if(i.status!==200)throw new lo(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new lo(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var ul=Symbol();function dl(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!Ko(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Ko))}var fl=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href);let n=t??{};this.#t=typeof n.timeoutDuration==`number`?n.timeoutDuration:5e3,this.#n=typeof n.cooldownDuration==`number`?n.cooldownDuration:3e4,this.#r=typeof n.cacheMaxAge==`number`?n.cacheMaxAge:6e5,this.#o=new Headers(n.headers),sl&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,sl),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=n[cl];let r=n[ul];r!==void 0&&(this.#l=r,dl(r,this.#r)&&(this.#i=this.#l.uat,this.#c=al(this.#l.jwks)))}pendingFetch(){return!!this.#a}#u(e){return typeof this.#i==`number`&&Date.now()<this.#i+e}coolingDown(){return this.#u(this.#n)}fresh(){return this.#u(this.#r)}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof bo&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&ol()&&(this.#a=void 0),this.#a||=ll(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=al(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now()}).finally(()=>{this.#a=void 0}),await this.#a}};function pl(e,t){let n=new fl(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0},fresh:{get:()=>n.fresh(),enumerable:!0},reload:{value:()=>n.reload(),enumerable:!0},reloading:{get:()=>n.pendingFetch(),enumerable:!0},jwks:{value:()=>n.jwks(),enumerable:!0}}),r}async function ml(e,t,n){if(!Ko(e))throw TypeError(`JWK must be an object`);t??=e.alg;let r=n?.extractable??e.ext;if(e.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return Wo(e.k);case`RSA`:return is(Yc(t),{...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return is(Yc(e.alg),{...e,ext:r});case`EC`:case`OKP`:return is(Yc(t),{...e,alg:t,ext:r});default:throw new mo(`Unsupported "kty" (Key Type) Parameter value`)}}function hl(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return rs(t,TypeError,n)}function gl(e){if(typeof e!=`string`)throw new _o(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new _o(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new _o(`Invalid JWT`);if(!t)throw new _o(`JWTs must contain a payload`);let r;try{r=Wo(t)}catch{throw new _o(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Ya.decode(r))}catch{throw new _o(`Failed to parse the decoded payload as JSON`)}if(!Ko(i))throw new _o(`Invalid JWT Claims Set`);return i}async function _l(e,t,n=3600){return await new Kc(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function vl(e,t){try{return(await zc(e,new TextEncoder().encode(t))).payload}catch{return null}}var yl=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),bl=()=>Date.now()/1e3|0,xl=`dir`,Sl=`A256CBC-HS512`;function Cl(e,t){return Pa(Ka,new TextEncoder().encode(e),new TextEncoder().encode(t),yl,64)}function wl(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function Tl(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function El(e,t,n,r=3600){let i=Cl(wl(t),n),a=await el({kty:`oct`,k:Go(i)},`sha256`);return await new qc(e).setProtectedHeader({alg:xl,enc:Sl,kid:a}).setIssuedAt().setExpirationTime(bl()+r).setJti(crypto.randomUUID()).encrypt(i)}var Dl={clockTolerance:15,keyManagementAlgorithms:[xl],contentEncryptionAlgorithms:[Sl,`A256GCM`]};async function Ol(e,t,n){if(!e)return null;let r=!1;try{r=hl(e).kid!==void 0}catch{return null}try{let r=Tl(t),{payload:i}=await Bc(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=Cl(e.value,n);if(t===await el({kty:`oct`,k:Go(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,Cl(r[0].value,n)},Dl);return i}catch{if(r)return null;let i=Tl(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Bc(e,Cl(r.value,n),Dl);return a}catch{continue}return null}}function kl(e,t,n,r){ua(e);let{c:i,dkLen:a,asyncTick:o}=Ea({dkLen:32,asyncTick:10},r);if(ca(i,`c`),ca(a,`dkLen`),ca(o,`asyncTick`),i<1)throw Error(`"c" (iterations) must be >= 1`);if(a<1)throw Error(`"dkLen" must be >= 1`);if(a>(2**32-1)*e.outputLen)throw Error(`derived key too long`);let s=Ta(t,`password`),c=Ta(n,`salt`),l=new Uint8Array(a),{iHash:u,oHash:d,outputLen:f}=Aa.create(e,s);return{c:i,dkLen:a,asyncTick:o,DK:l,outputLen:f,eng:Al(u,d,c,new Uint8Array(f))}}function Al(e,t,n,r){let i=new Uint8Array(4),a=ga(i),o=e._cloneInto().update(n),s=t._cloneInto(),c=e._cloneInto,l=t._cloneInto;return{u1:(e,n)=>{a.setInt32(0,e,!1),o._cloneInto(s).update(i).digestInto(r),t._cloneInto(s).update(r).digestInto(r),n.set(r.subarray(0,n.length))},rounds:(n,i)=>{for(let a=1;a<n;a++){c.call(e,s).update(r).digestInto(r),l.call(t,s).update(r).digestInto(r);for(let e=0;e<i.length;e++)i[e]^=r[e]}},output:n=>(e.destroy(),t.destroy(),o.destroy(),s.destroy(),ha(r),n)}}function jl(e,t,n,r){let{c:i,dkLen:a,DK:o,outputLen:s,eng:c}=kl(e,t,n,r);for(let e=1,t=0;t<a;e++,t+=s){let n=o.subarray(t,t+s);c.u1(e,n),c.rounds(i,n)}return c.output(o)}function Ml(e,t,n,r,i,a){let o=e[t++]^n[r++],s=e[t++]^n[r++],c=e[t++]^n[r++],l=e[t++]^n[r++],u=e[t++]^n[r++],d=e[t++]^n[r++],f=e[t++]^n[r++],p=e[t++]^n[r++],m=e[t++]^n[r++],h=e[t++]^n[r++],g=e[t++]^n[r++],_=e[t++]^n[r++],v=e[t++]^n[r++],y=e[t++]^n[r++],ee=e[t++]^n[r++],te=e[t++]^n[r++],b=o,x=s,S=c,C=l,w=u,T=d,E=f,D=p,O=m,k=h,A=g,j=_,M=v,ne=y,N=ee,re=te;for(let e=0;e<8;e+=2)w^=H(b+M|0,7),O^=H(w+b|0,9),M^=H(O+w|0,13),b^=H(M+O|0,18),k^=H(T+x|0,7),ne^=H(k+T|0,9),x^=H(ne+k|0,13),T^=H(x+ne|0,18),N^=H(A+E|0,7),S^=H(N+A|0,9),E^=H(S+N|0,13),A^=H(E+S|0,18),C^=H(re+j|0,7),D^=H(C+re|0,9),j^=H(D+C|0,13),re^=H(j+D|0,18),x^=H(b+C|0,7),S^=H(x+b|0,9),C^=H(S+x|0,13),b^=H(C+S|0,18),E^=H(T+w|0,7),D^=H(E+T|0,9),w^=H(D+E|0,13),T^=H(w+D|0,18),j^=H(A+k|0,7),O^=H(j+A|0,9),k^=H(O+j|0,13),A^=H(k+O|0,18),M^=H(re+N|0,7),ne^=H(M+re|0,9),N^=H(ne+M|0,13),re^=H(N+ne|0,18);i[a++]=o+b|0,i[a++]=s+x|0,i[a++]=c+S|0,i[a++]=l+C|0,i[a++]=u+w|0,i[a++]=d+T|0,i[a++]=f+E|0,i[a++]=p+D|0,i[a++]=m+O|0,i[a++]=h+k|0,i[a++]=g+A|0,i[a++]=_+j|0,i[a++]=v+M|0,i[a++]=y+ne|0,i[a++]=ee+N|0,i[a++]=te+re|0}function Nl(e,t,n,r,i){let a=r+0,o=r+16*i;for(let r=0;r<16;r++)n[o+r]=e[t+(2*i-1)*16+r];for(let r=0;r<i;r++,a+=16,t+=16)Ml(n,o,e,t,n,a),r>0&&(o+=16),Ml(n,a,e,t+=16,n,o)}function Pl(e,t,n){let{N:r,r:i,p:a,dkLen:o,asyncTick:s,maxmem:c,onProgress:l}=Ea({dkLen:32,asyncTick:10,maxmem:1024**3+1024},n);if(ca(r,`N`),ca(i,`r`),ca(a,`p`),ca(o,`dkLen`),ca(s,`asyncTick`),ca(c,`maxmem`),l!==void 0&&typeof l!=`function`)throw Error(`"onProgress" must be a function`);if(i<1)throw Error(`"r" expected integer >= 1`);let u=128*i,d=u/4,f=2**32;if(r<=1||r&r-1||r>f)throw Error(`"N" expected a power of 2, and 2^1 <= N <= 2^32`);if(a<1||a>(f-1)*32/u)throw Error(`"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)`);if(o<1||o>(f-1)*32)throw Error(`"dkLen" expected integer 1..(2^32 - 1) * 32`);let p=u*(r+a+1);if(p>c)throw Error(`"maxmem" limit was hit: memUsed(128*r*(N+p+1))=`+p+`, maxmem=`+c);let m=jl(Ka,e,t,{c:1,dkLen:u*a}),h=ma(m),g=ma(new Uint8Array(u*r)),_=ma(new Uint8Array(u)),v=()=>{};if(l){let e=2*r*a,t=Math.max(Math.floor(e/1e4),1),n=0;v=()=>{if(n++,l&&(!(n%t)||n===e))try{l(n/e)}catch(e){throw ha(m,g,_),e}}}return{N:r,r:i,p:a,dkLen:o,blockSize32:d,V:g,B32:h,B:m,tmp:_,blockMixCb:v,asyncTick:s}}function Fl(e,t,n,r,i){let a=jl(Ka,e,n,{c:1,dkLen:t});return ha(n,r,i),a}async function Il(e,t,n){let{N:r,r:i,p:a,dkLen:o,blockSize32:s,V:c,B32:l,B:u,tmp:d,blockMixCb:f,asyncTick:p}=Pl(e,t,n);xa(l);for(let e=0;e<a;e++){let t=s*e;for(let e=0;e<s;e++)c[e]=l[t+e];let n=0;await Ca(r-1,p,()=>{Nl(c,n,c,n+=s,i),f()}),Nl(c,(r-1)*s,l,t,i),f(),await Ca(r,p,()=>{let e=(l[t+s-16]&r-1)>>>0;for(let n=0;n<s;n++)d[n]=l[t+n]^c[e*s+n];Nl(d,0,l,t,i),f()})}return xa(l),Fl(e,o,u,c,d)}var Ll=`0123456789abcdef`,Rl={encode:e=>{if(typeof e==`string`&&(e=new TextEncoder().encode(e)),e.byteLength===0)return``;let t=new Uint8Array(e),n=``;for(let e of t)n+=e.toString(16).padStart(2,`0`);return n},decode:e=>{if(!e)return``;if(typeof e==`string`){if(e.length%2!=0||!RegExp(`^[${Ll}]+$`).test(e))throw Error(`Invalid hexadecimal string`);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return new TextDecoder().decode(t)}return new TextDecoder().decode(e)}},zl={N:16384,r:16,p:1,dkLen:64};async function Bl(e,t){return Il(e.normalize(`NFKC`),t,{N:zl.N,r:zl.r,p:zl.p,dkLen:zl.dkLen,maxmem:128*zl.N*zl.r*2})}async function Vl(e){let t=Rl.encode(crypto.getRandomValues(new Uint8Array(16))),n=await Bl(e,t);return`${t}:${Rl.encode(n)}`}async function Hl(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);let i=await Bl(t,n);return Rl.encode(i)===r}var Ul=Vl,Wl=async({hash:e,password:t})=>Hl(e,t);function Gl(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function Kl(e){return e?`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`}function ql(e,t,n){let r=``,i=0,a=0;for(let n of e)for(i=i<<8|n,a+=8;a>=6;)a-=6,r+=t[i>>a&63];if(a>0&&(r+=t[i<<6-a&63]),n){let e=(4-r.length%4)%4;r+=`=`.repeat(e)}return r}function Jl(e,t){let n=new Map;for(let e=0;e<t.length;e++)n.set(t[e],e);let r=[],i=0,a=0;for(let t of e){if(t===`=`)break;let e=n.get(t);if(e===void 0)throw Error(`Invalid Base64 character: ${t}`);i=i<<6|e,a+=6,a>=8&&(a-=8,r.push(i>>a&255))}return Uint8Array.from(r)}var Yl={encode(e,t={}){let n=Kl(!1);return ql(typeof e==`string`?new TextEncoder().encode(e):new Uint8Array(e),n,t.padding??!0)},decode(e){typeof e!=`string`&&(e=new TextDecoder().decode(e));let t=Kl(e.includes(`-`)||e.includes(`_`));return Jl(e,t)}},Xl={encode(e,t={}){let n=Kl(!0);return ql(typeof e==`string`?new TextEncoder().encode(e):new Uint8Array(e),n,t.padding??!0)},decode(e){return Jl(e,Kl(e.includes(`-`)||e.includes(`_`)))}};function Zl(e,t){return{digest:async n=>{let r=new TextEncoder,i=typeof n==`string`?r.encode(n):n,a=await Gl().digest(e,i);return t===`hex`?Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?Xl.encode(a,{padding:t!==`base64urlnopad`}):Yl.encode(a):a}}}function Ql(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var $l=e=>e?`"${e}" `:``;function eu(e,t=``){if(typeof e!=`boolean`)throw TypeError($l(t)+`expected boolean, got type=`+typeof e);return e}function tu(e,t=``){if(typeof e!=`number`)throw TypeError($l(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError($l(t)+`expected integer >= 0, got `+e);return e}function nu(e,t,n=``){if(Ql(e)&&(t===void 0||e.length===t))return e;t!==void 0&&tu(t,`length`);let r=Ql(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=$l(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var ru=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function iu(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function au(e,t){nu(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ou(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function su(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function cu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var lu=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function uu(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function du(e){for(let t=0;t<e.length;t++)e[t]=uu(e[t]);return e}var fu=lu?e=>e:du,pu=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,mu=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function hu(e){if(nu(e),pu)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=mu[e[n]];return t}function gu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function _u(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(pu)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=gu(e.charCodeAt(i)),a=gu(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function vu(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function yu(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function bu(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];nu(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function xu(e,t){return ru(e,`defaults`),ru(t,`opts`),Object.assign(e,t)}function Su(e,t){if(e=nu(e),t=nu(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function Cu(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var wu=(e,t)=>{function n(n,...r){if(nu(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];nu(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Ql(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&nu(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);nu(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,nu(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(nu(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function Tu(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(nu(t,e,`output`),n&&!Du(t))throw Error(`invalid output, must be aligned`);return t}function Eu(e,t,n){tu(e),tu(t),eu(n);let r=new Uint8Array(16),i=cu(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function Du(e){return e.byteOffset%4==0}function Ou(e){return Uint8Array.from(nu(e))}function ku(e=32){tu(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function Au(e,t=ku){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;tu(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=bu(e,t);return yu(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){nu(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){nu(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}var ju=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),Mu=fu(ou(ju(`expand 16-byte k`))),Nu=fu(ou(ju(`expand 32-byte k`)));function Pu(e,t){return e<<t|e>>>32-t}var Fu=64,Iu=16,Lu=2**32-1,Ru=Uint32Array.of();function zu(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Fu),u=ou(l),d=lu&&Du(i)&&Du(a),f=d?ou(i):Ru,p=d?ou(a):Ru;if(!lu){for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),fu(u),o>=Lu)throw Error(`arx: counter overflow`);let f=Math.min(Fu,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}return}for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Lu)throw Error(`arx: counter overflow`);let h=Math.min(Fu,c-m);if(d&&h===Fu){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Iu;t++)n=e+t,p[n]=f[n]^u[t];m+=Fu;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function Bu(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=xu({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return tu(i),tu(o),eu(a),eu(n),(t,s,c,l,u=0)=>{nu(t,void 0,`key`),nu(s,void 0,`nonce`),nu(c,void 0,`data`);let d=c.length;if(l=Tu(d,l,!1),tu(u),u<0||u>=Lu)throw Error(`arx: counter overflow`);let f=[],p=t.length,m,h;if(p===32)f.push(m=Ou(t)),h=Nu;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=Mu,f.push(m);else throw nu(t,32,`arx key`),Error(`invalid key size`);(!lu||!Du(s))&&f.push(s=Ou(s));let g=ou(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(lu)r(h,g,ou(e),g);else{let t=fu(Uint32Array.from(h));r(t,g,ou(e),g),su(t),fu(g)}s=s.subarray(16)}else lu||fu(g);let _=16-i;if(_!==s.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let v=fu(ou(s));try{return zu(e,h,g,v,c,l,u,o),l}finally{su(...f)}}}function Vu(e,t){return e[t++]&255|(e[t++]&255)<<8}var Hu=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ou(nu(e,32,`key`));let t=Vu(e,0),n=Vu(e,2),r=Vu(e,4),i=Vu(e,6),a=Vu(e,8),o=Vu(e,10),s=Vu(e,12),c=Vu(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Vu(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=Vu(e,t+0),_=Vu(e,t+2),v=Vu(e,t+4),y=Vu(e,t+6),ee=Vu(e,t+8),te=Vu(e,t+10),b=Vu(e,t+12),x=Vu(e,t+14),S=i[0]+(g&8191),C=i[1]+((g>>>13|_<<3)&8191),w=i[2]+((_>>>10|v<<6)&8191),T=i[3]+((v>>>7|y<<9)&8191),E=i[4]+((y>>>4|ee<<12)&8191),D=i[5]+(ee>>>1&8191),O=i[6]+((ee>>>14|te<<2)&8191),k=i[7]+((te>>>11|b<<5)&8191),A=i[8]+((b>>>8|x<<8)&8191),j=i[9]+(x>>>5|r),M=0,ne=M+S*o+5*h*C+5*m*w+5*p*T+5*f*E;M=ne>>>13,ne&=8191,ne+=5*d*D+5*u*O+5*l*k+5*c*A+5*s*j,M+=ne>>>13,ne&=8191;let N=M+S*s+C*o+5*h*w+5*m*T+5*p*E;M=N>>>13,N&=8191,N+=5*f*D+5*d*O+5*u*k+5*l*A+5*c*j,M+=N>>>13,N&=8191;let re=M+S*c+C*s+w*o+5*h*T+5*m*E;M=re>>>13,re&=8191,re+=5*p*D+5*f*O+5*d*k+5*u*A+5*l*j,M+=re>>>13,re&=8191;let ie=M+S*l+C*c+w*s+T*o+5*h*E;M=ie>>>13,ie&=8191,ie+=5*m*D+5*p*O+5*f*k+5*d*A+5*u*j,M+=ie>>>13,ie&=8191;let ae=M+S*u+C*l+w*c+T*s+E*o;M=ae>>>13,ae&=8191,ae+=5*h*D+5*m*O+5*p*k+5*f*A+5*d*j,M+=ae>>>13,ae&=8191;let oe=M+S*d+C*u+w*l+T*c+E*s;M=oe>>>13,oe&=8191,oe+=D*o+5*h*O+5*m*k+5*p*A+5*f*j,M+=oe>>>13,oe&=8191;let se=M+S*f+C*d+w*u+T*l+E*c;M=se>>>13,se&=8191,se+=D*s+O*o+5*h*k+5*m*A+5*p*j,M+=se>>>13,se&=8191;let ce=M+S*p+C*f+w*d+T*u+E*l;M=ce>>>13,ce&=8191,ce+=D*c+O*s+k*o+5*h*A+5*m*j,M+=ce>>>13,ce&=8191;let le=M+S*m+C*p+w*f+T*d+E*u;M=le>>>13,le&=8191,le+=D*l+O*c+k*s+A*o+5*h*j,M+=le>>>13,le&=8191;let ue=M+S*h+C*m+w*p+T*f+E*d;M=ue>>>13,ue&=8191,ue+=D*u+O*l+k*c+A*s+j*o,M+=ue>>>13,ue&=8191,M=(M<<2)+M|0,M=M+ne|0,ne=M&8191,M>>>=13,N+=M,i[0]=ne,i[1]=N,i[2]=re,i[3]=ie,i[4]=ae,i[5]=oe,i[6]=se,i[7]=ce,i[8]=le,i[9]=ue}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;su(n)}update(e){iu(this),nu(e),e=Ou(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,su(this.h,this.r,this.buffer,this.pad)}digestInto(e){iu(this),au(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},Uu=Cu(32,e=>new Hu(e));function Wu(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],ee=n[1],te=n[2],b=o,x=s,S=c,C=l,w=u,T=d,E=f,D=p,O=m,k=h,A=g,j=_,M=v,ne=y,N=ee,re=te;for(let e=0;e<a;e+=2)b=b+w|0,M=Pu(M^b,16),O=O+M|0,w=Pu(w^O,12),b=b+w|0,M=Pu(M^b,8),O=O+M|0,w=Pu(w^O,7),x=x+T|0,ne=Pu(ne^x,16),k=k+ne|0,T=Pu(T^k,12),x=x+T|0,ne=Pu(ne^x,8),k=k+ne|0,T=Pu(T^k,7),S=S+E|0,N=Pu(N^S,16),A=A+N|0,E=Pu(E^A,12),S=S+E|0,N=Pu(N^S,8),A=A+N|0,E=Pu(E^A,7),C=C+D|0,re=Pu(re^C,16),j=j+re|0,D=Pu(D^j,12),C=C+D|0,re=Pu(re^C,8),j=j+re|0,D=Pu(D^j,7),b=b+T|0,re=Pu(re^b,16),A=A+re|0,T=Pu(T^A,12),b=b+T|0,re=Pu(re^b,8),A=A+re|0,T=Pu(T^A,7),x=x+E|0,M=Pu(M^x,16),j=j+M|0,E=Pu(E^j,12),x=x+E|0,M=Pu(M^x,8),j=j+M|0,E=Pu(E^j,7),S=S+D|0,ne=Pu(ne^S,16),O=O+ne|0,D=Pu(D^O,12),S=S+D|0,ne=Pu(ne^S,8),O=O+ne|0,D=Pu(D^O,7),C=C+w|0,N=Pu(N^C,16),k=k+N|0,w=Pu(w^k,12),C=C+w|0,N=Pu(N^C,8),k=k+N|0,w=Pu(w^k,7);let ie=0;r[ie++]=o+b|0,r[ie++]=s+x|0,r[ie++]=c+S|0,r[ie++]=l+C|0,r[ie++]=u+w|0,r[ie++]=d+T|0,r[ie++]=f+E|0,r[ie++]=p+D|0,r[ie++]=m+O|0,r[ie++]=h+k|0,r[ie++]=g+A|0,r[ie++]=_+j|0,r[ie++]=v+M|0,r[ie++]=y+ne|0,r[ie++]=ee+N|0,r[ie++]=te+re|0}function Gu(e,t,n,r){let i=lu?e:fu(e.slice(0,4)),a=lu?t:fu(t.slice(0,8)),o=lu?n:fu(n.slice(0,4)),s=new Uint32Array(16);Wu(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,fu(r),lu||su(i,a,o),su(s)}var Ku=Bu(Wu,{counterRight:!1,counterLength:8,extendNonceFn:Gu,allowShortKeys:!1}),qu=new Uint8Array(16),Ju=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(qu.subarray(n))},Yu=new Uint8Array(32);function Xu(e,t,n,r,i){i!==void 0&&nu(i,void 0,`AAD`);let a=e(t,n,Yu),o=Eu(r.length,i?i.length:0,!0),s=Uu.create(a);i&&Ju(s,i),Ju(s,r),s.update(o);let c=s.digest();return su(a,o),c}var Zu=wu({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=Tu(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Xu(e,t,n,s,r);return a.set(c,o),su(c),a},decrypt(i,a){a=Tu(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Xu(e,t,n,o,r);if(!Su(s,c))throw su(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),su(c),a}}))(Ku)),Qu=`$ba$`;function $u(e){if(!e.startsWith(Qu))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function ed(e,t){return`${Qu}${e}$${t}`}async function td(e,t){let n=await Zl(`SHA-256`).digest(e),r=vu(t);return hu(Au(Zu)(new Uint8Array(n)).encrypt(r))}async function nd(e,t){let n=await Zl(`SHA-256`).digest(e),r=_u(t),i=Au(Zu)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var rd=async({key:e,data:t})=>{if(typeof e==`string`)return td(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await td(n,t);return ed(e.currentVersion,r)},id=async({key:e,data:t})=>{if(typeof e==`string`)return nd(e,t);let n=$u(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return nd(t,n.ciphertext)}if(e.legacySecret)return nd(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)};function ad(e){return!!e.database||!!e.secondaryStorage}function od(e){return!!e.database}function sd(e){return od(e)}var cd;function W(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var ld=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ud=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(cd=globalThis).__zod_globalConfig??(cd.__zod_globalConfig={});var dd=globalThis.__zod_globalConfig;function fd(e){return e&&Object.assign(dd,e),dd}function pd(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function md(e,t){return typeof t==`bigint`?t.toString():t}function hd(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function gd(e){return e==null}function _d(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function vd(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var yd=Symbol(`evaluating`);function bd(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==yd)return r===void 0&&(r=yd,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function xd(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Sd(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Cd(e){return JSON.stringify(e)}function wd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Td=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ed(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Dd=hd(()=>{if(dd.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Od(e){if(Ed(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ed(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function kd(e){return Od(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Ad=new Set([`string`,`number`,`symbol`]);function jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Md(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function G(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Nd(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var Pd={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fd(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Md(e,Sd(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return xd(this,`shape`,e),e},checks:[]}))}function Id(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Md(e,Sd(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return xd(this,`shape`,r),r},checks:[]}))}function Ld(e,t){if(!Od(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Md(e,Sd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return xd(this,`shape`,n),n}}))}function Rd(e,t){if(!Od(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Md(e,Sd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return xd(this,`shape`,n),n}}))}function zd(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Md(e,Sd(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return xd(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Bd(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Md(t,Sd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return xd(this,`shape`,i),i},checks:[]}))}function Vd(e,t,n){return Md(t,Sd(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return xd(this,`shape`,i),i}}))}function Hd(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ud(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Wd(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Gd(e){return typeof e==`string`?e:e?.message}function Kd(e,t,n){let r=e.message?e.message:Gd(e.inst?._zod.def?.error?.(e))??Gd(t?.error?.(e))??Gd(n.customError?.(e))??Gd(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function qd(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Jd(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var Yd=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,md,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Xd=W(`$ZodError`,Yd),Zd=W(`$ZodError`,Yd,{Parent:Error});function Qd(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function $d(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}var ef=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new ld;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Kd(e,a,fd())));throw Td(t,i?.callee),t}return o.value},tf=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>Kd(e,a,fd())));throw Td(t,i?.callee),t}return o.value},nf=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ld;return a.issues.length?{success:!1,error:new(e??Xd)(a.issues.map(e=>Kd(e,i,fd())))}:{success:!0,data:a.value}},rf=nf(Zd),af=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Kd(e,i,fd())))}:{success:!0,data:a.value}},of=af(Zd),sf=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ef(e)(t,n,i)},cf=e=>(t,n,r)=>ef(e)(t,n,r),lf=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return tf(e)(t,n,i)},uf=e=>async(t,n,r)=>tf(e)(t,n,r),df=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return nf(e)(t,n,i)},ff=e=>(t,n,r)=>nf(e)(t,n,r),pf=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return af(e)(t,n,i)},mf=e=>async(t,n,r)=>af(e)(t,n,r),hf=/^[cC][0-9a-z]{6,}$/,gf=/^[0-9a-z]+$/,_f=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vf=/^[0-9a-vA-V]{20}$/,yf=/^[A-Za-z0-9]{27}$/,bf=/^[a-zA-Z0-9_-]{21}$/,xf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sf=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Cf=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Tf=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function Ef(){return new RegExp(Tf,`u`)}var Df=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Of=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,kf=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Af=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mf=/^[A-Za-z0-9_-]*$/,Nf=/^https?$/,Pf=/^\+[1-9]\d{6,14}$/,Ff=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,If=RegExp(`^${Ff}$`);function Lf(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rf(e){return RegExp(`^${Lf(e)}$`)}function zf(e){let t=Lf({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Ff}T(?:${r})$`)}var Bf=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Vf=/^-?\d+$/,Hf=/^-?\d+(?:\.\d+)?$/,Uf=/^(?:true|false)$/i,Wf=/^[^A-Z]*$/,Gf=/^[^a-z]*$/,Kf=W(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qf={number:`number`,bigint:`bigint`,object:`date`},Jf=W(`$ZodCheckLessThan`,(e,t)=>{Kf.init(e,t);let n=qf[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yf=W(`$ZodCheckGreaterThan`,(e,t)=>{Kf.init(e,t);let n=qf[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xf=W(`$ZodCheckMultipleOf`,(e,t)=>{Kf.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):vd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Zf=W(`$ZodCheckNumberFormat`,(e,t)=>{Kf.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Pd[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Vf)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Qf=W(`$ZodCheckMaxLength`,(e,t)=>{var n;Kf.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=qd(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$f=W(`$ZodCheckMinLength`,(e,t)=>{var n;Kf.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=qd(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ep=W(`$ZodCheckLengthEquals`,(e,t)=>{var n;Kf.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!gd(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=qd(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),tp=W(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Kf.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),np=W(`$ZodCheckRegex`,(e,t)=>{tp.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),rp=W(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Wf,tp.init(e,t)}),ip=W(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Gf,tp.init(e,t)}),ap=W(`$ZodCheckIncludes`,(e,t)=>{Kf.init(e,t);let n=jd(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),op=W(`$ZodCheckStartsWith`,(e,t)=>{Kf.init(e,t);let n=RegExp(`^${jd(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),sp=W(`$ZodCheckEndsWith`,(e,t)=>{Kf.init(e,t);let n=RegExp(`.*${jd(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),cp=W(`$ZodCheckOverwrite`,(e,t)=>{Kf.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),lp=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
48
|
-
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
49
|
-
`))}},up={major:4,minor:4,patch:3},dp=W(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=up;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=Hd(e),i;for(let a of t){if(a._zod.def.when){if(Ud(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new ld;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=Hd(e,t))});else{if(e.issues.length===t)continue;r||=Hd(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(Hd(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new ld;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new ld;return o.then(e=>t(e,r,a))}return t(o,r,a)}}bd(e,`~standard`,()=>({validate:t=>{try{let n=rf(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return of(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),fp=W(`$ZodString`,(e,t)=>{dp.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Bf(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),pp=W(`$ZodStringFormat`,(e,t)=>{tp.init(e,t),fp.init(e,t)}),mp=W(`$ZodGUID`,(e,t)=>{t.pattern??=Sf,pp.init(e,t)}),hp=W(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Cf(e)}else t.pattern??=Cf();pp.init(e,t)}),gp=W(`$ZodEmail`,(e,t)=>{t.pattern??=wf,pp.init(e,t)}),_p=W(`$ZodURL`,(e,t)=>{pp.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Nf.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),vp=W(`$ZodEmoji`,(e,t)=>{t.pattern??=Ef(),pp.init(e,t)}),yp=W(`$ZodNanoID`,(e,t)=>{t.pattern??=bf,pp.init(e,t)}),bp=W(`$ZodCUID`,(e,t)=>{t.pattern??=hf,pp.init(e,t)}),xp=W(`$ZodCUID2`,(e,t)=>{t.pattern??=gf,pp.init(e,t)}),Sp=W(`$ZodULID`,(e,t)=>{t.pattern??=_f,pp.init(e,t)}),Cp=W(`$ZodXID`,(e,t)=>{t.pattern??=vf,pp.init(e,t)}),wp=W(`$ZodKSUID`,(e,t)=>{t.pattern??=yf,pp.init(e,t)}),Tp=W(`$ZodISODateTime`,(e,t)=>{t.pattern??=zf(t),pp.init(e,t)}),Ep=W(`$ZodISODate`,(e,t)=>{t.pattern??=If,pp.init(e,t)}),Dp=W(`$ZodISOTime`,(e,t)=>{t.pattern??=Rf(t),pp.init(e,t)}),Op=W(`$ZodISODuration`,(e,t)=>{t.pattern??=xf,pp.init(e,t)}),kp=W(`$ZodIPv4`,(e,t)=>{t.pattern??=Df,pp.init(e,t),e._zod.bag.format=`ipv4`}),Ap=W(`$ZodIPv6`,(e,t)=>{t.pattern??=Of,pp.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),jp=W(`$ZodCIDRv4`,(e,t)=>{t.pattern??=kf,pp.init(e,t)}),Mp=W(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Af,pp.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Np(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Pp=W(`$ZodBase64`,(e,t)=>{t.pattern??=jf,pp.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Np(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Fp(e){if(!Mf.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Np(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Ip=W(`$ZodBase64URL`,(e,t)=>{t.pattern??=Mf,pp.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Fp(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Lp=W(`$ZodE164`,(e,t)=>{t.pattern??=Pf,pp.init(e,t)});function Rp(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var zp=W(`$ZodJWT`,(e,t)=>{pp.init(e,t),e._zod.check=n=>{Rp(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Bp=W(`$ZodNumber`,(e,t)=>{dp.init(e,t),e._zod.pattern=e._zod.bag.pattern??Hf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Vp=W(`$ZodNumberFormat`,(e,t)=>{Zf.init(e,t),Bp.init(e,t)}),Hp=W(`$ZodBoolean`,(e,t)=>{dp.init(e,t),e._zod.pattern=Uf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Up=W(`$ZodAny`,(e,t)=>{dp.init(e,t),e._zod.parse=e=>e}),Wp=W(`$ZodUnknown`,(e,t)=>{dp.init(e,t),e._zod.parse=e=>e}),Gp=W(`$ZodNever`,(e,t)=>{dp.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),Kp=W(`$ZodDate`,(e,t)=>{dp.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let i=n.value,a=i instanceof Date;return a&&!Number.isNaN(i.getTime())||n.issues.push({expected:`date`,code:`invalid_type`,input:i,...a?{received:`Invalid Date`}:{},inst:e}),n}});function qp(e,t,n){e.issues.length&&t.issues.push(...Wd(n,e.issues)),t.value[n]=e.value}var Jp=W(`$ZodArray`,(e,t)=>{dp.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>qp(t,n,e))):qp(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function Yp(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...Wd(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function Xp(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Nd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Zp(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Yp(e,n,i,t,u,d))):Yp(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var Qp=W(`$ZodObject`,(e,t)=>{if(dp.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=hd(()=>Xp(t));bd(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Ed,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>Yp(n,t,e,s,r,i))):Yp(a,t,e,s,r,i)}return i?Zp(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),$p=W(`$ZodObjectJIT`,(e,t)=>{Qp.init(e,t);let n=e._zod.parse,r=hd(()=>Xp(t)),i=e=>{let t=new lp([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Cd(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Cd(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
50
|
-
if (${n}.issues.length) {
|
|
51
|
-
if (${o} in input) {
|
|
52
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
53
|
-
...iss,
|
|
54
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
55
|
-
})));
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (${n}.value === undefined) {
|
|
60
|
-
if (${o} in input) {
|
|
61
|
-
newResult[${o}] = undefined;
|
|
62
|
-
}
|
|
63
|
-
} else {
|
|
64
|
-
newResult[${o}] = ${n}.value;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
`):c?t.write(`
|
|
68
|
-
if (${n}.issues.length) {
|
|
69
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
70
|
-
...iss,
|
|
71
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
72
|
-
})));
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
if (${n}.value === undefined) {
|
|
76
|
-
if (${o} in input) {
|
|
77
|
-
newResult[${o}] = undefined;
|
|
78
|
-
}
|
|
79
|
-
} else {
|
|
80
|
-
newResult[${o}] = ${n}.value;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
`):t.write(`
|
|
84
|
-
const ${n}_present = ${o} in input;
|
|
85
|
-
if (${n}.issues.length) {
|
|
86
|
-
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
87
|
-
...iss,
|
|
88
|
-
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
89
|
-
})));
|
|
90
|
-
}
|
|
91
|
-
if (!${n}_present && !${n}.issues.length) {
|
|
92
|
-
payload.issues.push({
|
|
93
|
-
code: "invalid_type",
|
|
94
|
-
expected: "nonoptional",
|
|
95
|
-
input: undefined,
|
|
96
|
-
path: [${o}]
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
if (${n}_present) {
|
|
101
|
-
if (${n}.value === undefined) {
|
|
102
|
-
newResult[${o}] = undefined;
|
|
103
|
-
} else {
|
|
104
|
-
newResult[${o}] = ${n}.value;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Ed,s=!dd.jitless,c=s&&Dd.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Zp([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function em(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Hd(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Kd(e,r,fd())))}),t)}var tm=W(`$ZodUnion`,(e,t)=>{dp.init(e,t),bd(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),bd(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),bd(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),bd(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>_d(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>em(t,r,e,i)):em(o,r,e,i)}}),nm=W(`$ZodIntersection`,(e,t)=>{dp.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>im(e,t,n)):im(e,i,a)}});function rm(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Od(e)&&Od(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=rm(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=rm(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function im(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Hd(e))return e;let o=rm(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var am=W(`$ZodRecord`,(e,t)=>{dp.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Od(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Kd(e,r,fd())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Wd(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Wd(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Hf.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Kd(e,r,fd())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Wd(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Wd(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),om=W(`$ZodEnum`,(e,t)=>{dp.init(e,t);let n=pd(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ad.has(typeof e)).map(e=>typeof e==`string`?jd(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),sm=W(`$ZodLiteral`,(e,t)=>{if(dp.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?jd(e):e?jd(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),cm=W(`$ZodTransform`,(e,t)=>{dp.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ud(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new ld;return n.value=i,n.fallback=!0,n}});function lm(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var um=W(`$ZodOptional`,(e,t)=>{dp.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,bd(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),bd(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${_d(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>lm(e,r)):lm(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),dm=W(`$ZodExactOptional`,(e,t)=>{um.init(e,t),bd(e._zod,`values`,()=>t.innerType._zod.values),bd(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),fm=W(`$ZodNullable`,(e,t)=>{dp.init(e,t),bd(e._zod,`optin`,()=>t.innerType._zod.optin),bd(e._zod,`optout`,()=>t.innerType._zod.optout),bd(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${_d(e.source)}|null)$`):void 0}),bd(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),pm=W(`$ZodDefault`,(e,t)=>{dp.init(e,t),e._zod.optin=`optional`,bd(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>mm(e,t)):mm(r,t)}});function mm(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var hm=W(`$ZodPrefault`,(e,t)=>{dp.init(e,t),e._zod.optin=`optional`,bd(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),gm=W(`$ZodNonOptional`,(e,t)=>{dp.init(e,t),bd(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>_m(t,e)):_m(i,e)}});function _m(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var vm=W(`$ZodCatch`,(e,t)=>{dp.init(e,t),e._zod.optin=`optional`,bd(e._zod,`optout`,()=>t.innerType._zod.optout),bd(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Kd(e,n,fd()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Kd(e,n,fd()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),ym=W(`$ZodPipe`,(e,t)=>{dp.init(e,t),bd(e._zod,`values`,()=>t.in._zod.values),bd(e._zod,`optin`,()=>t.in._zod.optin),bd(e._zod,`optout`,()=>t.out._zod.optout),bd(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>bm(e,t.in,n)):bm(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>bm(e,t.out,n)):bm(r,t.out,n)}});function bm(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var xm=W(`$ZodReadonly`,(e,t)=>{dp.init(e,t),bd(e._zod,`propValues`,()=>t.innerType._zod.propValues),bd(e._zod,`values`,()=>t.innerType._zod.values),bd(e._zod,`optin`,()=>t.innerType?._zod?.optin),bd(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Sm):Sm(r)}});function Sm(e){return e.value=Object.freeze(e.value),e}var Cm=W(`$ZodCustom`,(e,t)=>{Kf.init(e,t),dp.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>wm(t,n,r,e));wm(i,n,r,e)}});function wm(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Jd(e))}}var Tm,Em=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Dm(){return new Em}(Tm=globalThis).__zod_globalRegistry??(Tm.__zod_globalRegistry=Dm());var Om=globalThis.__zod_globalRegistry;function km(e,t){return new e({type:`string`,...G(t)})}function Am(e,t){return new e({type:`string`,coerce:!0,...G(t)})}function jm(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...G(t)})}function Mm(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...G(t)})}function Nm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...G(t)})}function Pm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...G(t)})}function Fm(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...G(t)})}function Im(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...G(t)})}function Lm(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...G(t)})}function Rm(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...G(t)})}function zm(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...G(t)})}function Bm(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...G(t)})}function Vm(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...G(t)})}function Hm(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...G(t)})}function Um(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...G(t)})}function Wm(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...G(t)})}function Gm(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...G(t)})}function Km(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...G(t)})}function qm(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...G(t)})}function Jm(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...G(t)})}function Ym(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...G(t)})}function Xm(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...G(t)})}function Zm(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...G(t)})}function Qm(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...G(t)})}function $m(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...G(t)})}function eh(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...G(t)})}function th(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...G(t)})}function nh(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...G(t)})}function rh(e,t){return new e({type:`number`,checks:[],...G(t)})}function ih(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...G(t)})}function ah(e,t){return new e({type:`boolean`,...G(t)})}function oh(e,t){return new e({type:`boolean`,coerce:!0,...G(t)})}function sh(e){return new e({type:`any`})}function ch(e){return new e({type:`unknown`})}function lh(e,t){return new e({type:`never`,...G(t)})}function uh(e,t){return new e({type:`date`,...G(t)})}function dh(e,t){return new Jf({check:`less_than`,...G(t),value:e,inclusive:!1})}function fh(e,t){return new Jf({check:`less_than`,...G(t),value:e,inclusive:!0})}function ph(e,t){return new Yf({check:`greater_than`,...G(t),value:e,inclusive:!1})}function mh(e,t){return new Yf({check:`greater_than`,...G(t),value:e,inclusive:!0})}function hh(e,t){return new Xf({check:`multiple_of`,...G(t),value:e})}function gh(e,t){return new Qf({check:`max_length`,...G(t),maximum:e})}function _h(e,t){return new $f({check:`min_length`,...G(t),minimum:e})}function vh(e,t){return new ep({check:`length_equals`,...G(t),length:e})}function yh(e,t){return new np({check:`string_format`,format:`regex`,...G(t),pattern:e})}function bh(e){return new rp({check:`string_format`,format:`lowercase`,...G(e)})}function xh(e){return new ip({check:`string_format`,format:`uppercase`,...G(e)})}function Sh(e,t){return new ap({check:`string_format`,format:`includes`,...G(t),includes:e})}function Ch(e,t){return new op({check:`string_format`,format:`starts_with`,...G(t),prefix:e})}function wh(e,t){return new sp({check:`string_format`,format:`ends_with`,...G(t),suffix:e})}function Th(e){return new cp({check:`overwrite`,tx:e})}function Eh(e){return Th(t=>t.normalize(e))}function Dh(){return Th(e=>e.trim())}function Oh(){return Th(e=>e.toLowerCase())}function kh(){return Th(e=>e.toUpperCase())}function Ah(){return Th(e=>wd(e))}function jh(e,t,n){return new e({type:`array`,element:t,...G(n)})}function Mh(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...G(n)})}function Nh(e,t){let n=Ph(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Jd(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Jd(r))}},e(t.value,t)),t);return n}function Ph(e,t){let n=new Kf({check:`custom`,...G(t)});return n._zod.check=e,n}function Fh(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Om,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function Ih(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Ih(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&zh(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Lh(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
109
|
-
|
|
110
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Rh(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Vh(t,`input`,e.processors),output:Vh(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function zh(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return zh(r.element,n);if(r.type===`set`)return zh(r.valueType,n);if(r.type===`lazy`)return zh(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return zh(r.innerType,n);if(r.type===`intersection`)return zh(r.left,n)||zh(r.right,n);if(r.type===`record`||r.type===`map`)return zh(r.keyType,n)||zh(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:zh(r.in,n)||zh(r.out,n);if(r.type===`object`){for(let e in r.shape)if(zh(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(zh(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(zh(e,n))return!0;return!!(r.rest&&zh(r.rest,n))}return!1}var Bh=(e,t={})=>n=>{let r=Fh({...n,processors:t});return Ih(e,r),Lh(r,e),Rh(r,e)},Vh=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Fh({...i??{},target:a,io:t,processors:n});return Ih(e,o),Lh(o,e),Rh(o,e)},Hh={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Uh=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Hh[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Wh=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Gh=(e,t,n,r)=>{n.type=`boolean`},Kh=(e,t,n,r)=>{n.not={}},qh=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},Jh=(e,t,n,r)=>{let i=e._zod.def,a=pd(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Yh=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Xh=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Zh=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Qh=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Ih(a.element,t,{...r,path:[...r.path,`items`]})},$h=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Ih(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Ih(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},eg=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Ih(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},tg=(e,t,n,r)=>{let i=e._zod.def,a=Ih(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Ih(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ng=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Ih(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Ih(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Ih(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},rg=(e,t,n,r)=>{let i=e._zod.def,a=Ih(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ig=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ag=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},og=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},sg=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},cg=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Ih(o,t,r);let s=t.seen.get(e);s.ref=o},lg=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ug=(e,t,n,r)=>{let i=e._zod.def;Ih(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},dg=W(`ZodISODateTime`,(e,t)=>{Tp.init(e,t),Lg.init(e,t)});function fg(e){return $m(dg,e)}var pg=W(`ZodISODate`,(e,t)=>{Ep.init(e,t),Lg.init(e,t)});function mg(e){return eh(pg,e)}var hg=W(`ZodISOTime`,(e,t)=>{Dp.init(e,t),Lg.init(e,t)});function gg(e){return th(hg,e)}var _g=W(`ZodISODuration`,(e,t)=>{Op.init(e,t),Lg.init(e,t)});function vg(e){return nh(_g,e)}var yg=W(`ZodError`,(e,t)=>{Xd.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>$d(e,t)},flatten:{value:t=>Qd(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,md,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,md,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),bg=ef(yg),xg=tf(yg),Sg=nf(yg),Cg=af(yg),wg=sf(yg),Tg=cf(yg),Eg=lf(yg),Dg=uf(yg),Og=df(yg),kg=ff(yg),Ag=pf(yg),jg=mf(yg),Mg=new WeakMap;function Ng(e,t,n){let r=Object.getPrototypeOf(e),i=Mg.get(r);if(i||(i=new Set,Mg.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Pg=W(`ZodType`,(e,t)=>(dp.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Vh(e,`input`),output:Vh(e,`output`)}}),e.toJSONSchema=Bh(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>bg(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Sg(e,t,n),e.parseAsync=async(t,n)=>xg(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Cg(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>wg(e,t,n),e.decode=(t,n)=>Tg(e,t,n),e.encodeAsync=async(t,n)=>Eg(e,t,n),e.decodeAsync=async(t,n)=>Dg(e,t,n),e.safeEncode=(t,n)=>Og(e,t,n),e.safeDecode=(t,n)=>kg(e,t,n),e.safeEncodeAsync=async(t,n)=>Ag(e,t,n),e.safeDecodeAsync=async(t,n)=>jg(e,t,n),Ng(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Sd(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Md(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rv(e,t))},superRefine(e,t){return this.check(iv(e,t))},overwrite(e){return this.check(Th(e))},optional(){return z_(this)},exactOptional(){return V_(this)},nullable(){return U_(this)},nullish(){return z_(U_(this))},nonoptional(e){return Y_(this,e)},array(){return x_(this)},or(e){return D_([this,e])},and(e){return k_(this,e)},transform(e){return $_(this,L_(e))},default(e){return G_(this,e)},prefault(e){return q_(this,e)},catch(e){return Z_(this,e)},pipe(e){return $_(this,e)},readonly(){return tv(this)},describe(e){let t=this.clone();return Om.add(t,{description:e}),t},meta(...e){if(e.length===0)return Om.get(this);let t=this.clone();return Om.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Om.get(e)?.description},configurable:!0}),e)),Fg=W(`_ZodString`,(e,t)=>{fp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uh(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ng(e,`_ZodString`,{regex(...e){return this.check(yh(...e))},includes(...e){return this.check(Sh(...e))},startsWith(...e){return this.check(Ch(...e))},endsWith(...e){return this.check(wh(...e))},min(...e){return this.check(_h(...e))},max(...e){return this.check(gh(...e))},length(...e){return this.check(vh(...e))},nonempty(...e){return this.check(_h(1,...e))},lowercase(e){return this.check(bh(e))},uppercase(e){return this.check(xh(e))},trim(){return this.check(Dh())},normalize(...e){return this.check(Eh(...e))},toLowerCase(){return this.check(Oh())},toUpperCase(){return this.check(kh())},slugify(){return this.check(Ah())}})}),Ig=W(`ZodString`,(e,t)=>{fp.init(e,t),Fg.init(e,t),e.email=t=>e.check(jm(Rg,t)),e.url=t=>e.check(Lm(Hg,t)),e.jwt=t=>e.check(Qm(a_,t)),e.emoji=t=>e.check(Rm(Ug,t)),e.guid=t=>e.check(Mm(Bg,t)),e.uuid=t=>e.check(Nm(Vg,t)),e.uuidv4=t=>e.check(Pm(Vg,t)),e.uuidv6=t=>e.check(Fm(Vg,t)),e.uuidv7=t=>e.check(Im(Vg,t)),e.nanoid=t=>e.check(zm(Wg,t)),e.guid=t=>e.check(Mm(Bg,t)),e.cuid=t=>e.check(Bm(Gg,t)),e.cuid2=t=>e.check(Vm(Kg,t)),e.ulid=t=>e.check(Hm(qg,t)),e.base64=t=>e.check(Ym(n_,t)),e.base64url=t=>e.check(Xm(r_,t)),e.xid=t=>e.check(Um(Jg,t)),e.ksuid=t=>e.check(Wm(Yg,t)),e.ipv4=t=>e.check(Gm(Xg,t)),e.ipv6=t=>e.check(Km(Qg,t)),e.cidrv4=t=>e.check(qm(e_,t)),e.cidrv6=t=>e.check(Jm(t_,t)),e.e164=t=>e.check(Zm(i_,t)),e.datetime=t=>e.check(fg(t)),e.date=t=>e.check(mg(t)),e.time=t=>e.check(gg(t)),e.duration=t=>e.check(vg(t))});function K(e){return km(Ig,e)}var Lg=W(`ZodStringFormat`,(e,t)=>{pp.init(e,t),Fg.init(e,t)}),Rg=W(`ZodEmail`,(e,t)=>{gp.init(e,t),Lg.init(e,t)});function zg(e){return jm(Rg,e)}var Bg=W(`ZodGUID`,(e,t)=>{mp.init(e,t),Lg.init(e,t)}),Vg=W(`ZodUUID`,(e,t)=>{hp.init(e,t),Lg.init(e,t)}),Hg=W(`ZodURL`,(e,t)=>{_p.init(e,t),Lg.init(e,t)}),Ug=W(`ZodEmoji`,(e,t)=>{vp.init(e,t),Lg.init(e,t)}),Wg=W(`ZodNanoID`,(e,t)=>{yp.init(e,t),Lg.init(e,t)}),Gg=W(`ZodCUID`,(e,t)=>{bp.init(e,t),Lg.init(e,t)}),Kg=W(`ZodCUID2`,(e,t)=>{xp.init(e,t),Lg.init(e,t)}),qg=W(`ZodULID`,(e,t)=>{Sp.init(e,t),Lg.init(e,t)}),Jg=W(`ZodXID`,(e,t)=>{Cp.init(e,t),Lg.init(e,t)}),Yg=W(`ZodKSUID`,(e,t)=>{wp.init(e,t),Lg.init(e,t)}),Xg=W(`ZodIPv4`,(e,t)=>{kp.init(e,t),Lg.init(e,t)});function Zg(e){return Gm(Xg,e)}var Qg=W(`ZodIPv6`,(e,t)=>{Ap.init(e,t),Lg.init(e,t)});function $g(e){return Km(Qg,e)}var e_=W(`ZodCIDRv4`,(e,t)=>{jp.init(e,t),Lg.init(e,t)}),t_=W(`ZodCIDRv6`,(e,t)=>{Mp.init(e,t),Lg.init(e,t)}),n_=W(`ZodBase64`,(e,t)=>{Pp.init(e,t),Lg.init(e,t)}),r_=W(`ZodBase64URL`,(e,t)=>{Ip.init(e,t),Lg.init(e,t)}),i_=W(`ZodE164`,(e,t)=>{Lp.init(e,t),Lg.init(e,t)}),a_=W(`ZodJWT`,(e,t)=>{zp.init(e,t),Lg.init(e,t)}),o_=W(`ZodNumber`,(e,t)=>{Bp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wh(e,t,n,r),Ng(e,`ZodNumber`,{gt(e,t){return this.check(ph(e,t))},gte(e,t){return this.check(mh(e,t))},min(e,t){return this.check(mh(e,t))},lt(e,t){return this.check(dh(e,t))},lte(e,t){return this.check(fh(e,t))},max(e,t){return this.check(fh(e,t))},int(e){return this.check(l_(e))},safe(e){return this.check(l_(e))},positive(e){return this.check(ph(0,e))},nonnegative(e){return this.check(mh(0,e))},negative(e){return this.check(dh(0,e))},nonpositive(e){return this.check(fh(0,e))},multipleOf(e,t){return this.check(hh(e,t))},step(e,t){return this.check(hh(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function s_(e){return rh(o_,e)}var c_=W(`ZodNumberFormat`,(e,t)=>{Vp.init(e,t),o_.init(e,t)});function l_(e){return ih(c_,e)}var u_=W(`ZodBoolean`,(e,t)=>{Hp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gh(e,t,n,r)});function d_(e){return ah(u_,e)}var f_=W(`ZodAny`,(e,t)=>{Up.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function p_(){return sh(f_)}var m_=W(`ZodUnknown`,(e,t)=>{Wp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function h_(){return ch(m_)}var g_=W(`ZodNever`,(e,t)=>{Gp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kh(e,t,n,r)});function __(e){return lh(g_,e)}var v_=W(`ZodDate`,(e,t)=>{Kp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qh(e,t,n,r),e.min=(t,n)=>e.check(mh(t,n)),e.max=(t,n)=>e.check(fh(t,n));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function y_(e){return uh(v_,e)}var b_=W(`ZodArray`,(e,t)=>{Jp.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qh(e,t,n,r),e.element=t.element,Ng(e,`ZodArray`,{min(e,t){return this.check(_h(e,t))},nonempty(e){return this.check(_h(1,e))},max(e,t){return this.check(gh(e,t))},length(e,t){return this.check(vh(e,t))},unwrap(){return this.element}})});function x_(e,t){return jh(b_,e,t)}var S_=W(`ZodObject`,(e,t)=>{$p.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$h(e,t,n,r),bd(e,`shape`,()=>t.shape),Ng(e,`ZodObject`,{keyof(){return N_(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:h_()})},loose(){return this.clone({...this._zod.def,catchall:h_()})},strict(){return this.clone({...this._zod.def,catchall:__()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Ld(this,e)},safeExtend(e){return Rd(this,e)},merge(e){return zd(this,e)},pick(e){return Fd(this,e)},omit(e){return Id(this,e)},partial(...e){return Bd(R_,this,e[0])},required(...e){return Vd(J_,this,e[0])}})});function C_(e,t){return new S_({type:`object`,shape:e??{},...G(t)})}function w_(e,t){return new S_({type:`object`,shape:e,catchall:__(),...G(t)})}function T_(e,t){return new S_({type:`object`,shape:e,catchall:h_(),...G(t)})}var E_=W(`ZodUnion`,(e,t)=>{tm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eg(e,t,n,r),e.options=t.options});function D_(e,t){return new E_({type:`union`,options:e,...G(t)})}var O_=W(`ZodIntersection`,(e,t)=>{nm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tg(e,t,n,r)});function k_(e,t){return new O_({type:`intersection`,left:e,right:t})}var A_=W(`ZodRecord`,(e,t)=>{am.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ng(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function j_(e,t,n){return!t||!t._zod?new A_({type:`record`,keyType:K(),valueType:e,...G(t)}):new A_({type:`record`,keyType:e,valueType:t,...G(n)})}var M_=W(`ZodEnum`,(e,t)=>{om.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jh(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new M_({...t,checks:[],...G(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new M_({...t,checks:[],...G(r),entries:i})}});function N_(e,t){return new M_({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...G(t)})}var P_=W(`ZodLiteral`,(e,t)=>{sm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yh(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function F_(e,t){return new P_({type:`literal`,values:Array.isArray(e)?e:[e],...G(t)})}var I_=W(`ZodTransform`,(e,t)=>{cm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zh(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ud(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Jd(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Jd(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function L_(e){return new I_({type:`transform`,transform:e})}var R_=W(`ZodOptional`,(e,t)=>{um.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function z_(e){return new R_({type:`optional`,innerType:e})}var B_=W(`ZodExactOptional`,(e,t)=>{dm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ug(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V_(e){return new B_({type:`optional`,innerType:e})}var H_=W(`ZodNullable`,(e,t)=>{fm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function U_(e){return new H_({type:`nullable`,innerType:e})}var W_=W(`ZodDefault`,(e,t)=>{pm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ag(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function G_(e,t){return new W_({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():kd(t)}})}var K_=W(`ZodPrefault`,(e,t)=>{hm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>og(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function q_(e,t){return new K_({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():kd(t)}})}var J_=W(`ZodNonOptional`,(e,t)=>{gm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ig(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Y_(e,t){return new J_({type:`nonoptional`,innerType:e,...G(t)})}var X_=W(`ZodCatch`,(e,t)=>{vm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Z_(e,t){return new X_({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Q_=W(`ZodPipe`,(e,t)=>{ym.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cg(e,t,n,r),e.in=t.in,e.out=t.out});function $_(e,t){return new Q_({type:`pipe`,in:e,out:t})}var ev=W(`ZodReadonly`,(e,t)=>{xm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lg(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tv(e){return new ev({type:`readonly`,innerType:e})}var nv=W(`ZodCustom`,(e,t)=>{Cm.init(e,t),Pg.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xh(e,t,n,r)});function rv(e,t={}){return Mh(nv,e,t)}function iv(e,t){return Nh(e,t)}function av(e){return Am(Ig,e)}function ov(e){return oh(u_,e)}var sv=C_({id:K(),createdAt:y_().default(()=>new Date),updatedAt:y_().default(()=>new Date)});sv.extend({providerId:K(),issuer:K(),accountId:K(),userId:av(),accessToken:K().nullish(),refreshToken:K().nullish(),idToken:K().nullish(),accessTokenExpiresAt:y_().nullish(),refreshTokenExpiresAt:y_().nullish(),scope:K().nullish(),password:K().nullish()});function cv(e){return encodeURIComponent(e)}function lv(e){return`local:${cv(e)}`}function uv(e){return`local:oauth:${cv(e)}`}var dv=sv.extend({userId:av(),expiresAt:y_(),token:K(),ipAddress:K().nullish(),userAgent:K().nullish()}),fv=sv.extend({email:K().transform(e=>e.toLowerCase()),emailVerified:d_().default(!1),name:K(),image:K().nullish()});function pv(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}var mv=new WeakMap;function hv(e,t,n){let r=`${t}:${n}`;mv.has(e)||mv.set(e,new Map);let i=mv.get(e);if(i.has(r))return i.get(r);let a=n===`output`?se(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function gv(e,t){return pv(t,hv(e,`user`,`output`))}function _v(e,t){let n=hv(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function vv(e,t){return pv(t,hv(e,`session`,`output`))}function yv(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=pv(t,hv(e,`account`,`output`));return c}function bv(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r){if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw E.from(`BAD_REQUEST`,{...V.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw E.from(`INTERNAL_SERVER_ERROR`,V.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw E.from(`BAD_REQUEST`,{...V.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t];continue}if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue;continue}if(r[t].required&&n===`create`)throw E.from(`BAD_REQUEST`,{...V.MISSING_FIELD,message:`${t} is required`})}return i}function xv(e,t={},n){return bv(t,{fields:hv(e,`user`,`input`),action:n})}function Sv(e,t={},n){let r=hv(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return bv(i,{fields:r,action:n})}function Cv(e,t,n){return bv(t,{fields:hv(e,`session`,`input`),action:n})}function wv(e){let t=hv(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}var Tv=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Ev(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Dv=1e3,Ov=Dv*60,kv=Ov*60,Av=kv*24,jv=Av*7,Mv=Av*30,Nv=Av*365.25,Pv=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function Fv(e){let t=Pv.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*Nv;break;case`months`:case`month`:case`mo`:i=n*Mv;break;case`weeks`:case`week`:case`w`:i=n*jv;break;case`days`:case`day`:case`d`:i=n*Av;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*kv;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*Ov;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*Dv;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function Iv(e){return Math.round(Fv(e)/1e3)}var Lv=T_({session:dv.loose(),user:fv.loose(),updatedAt:s_(),version:K().optional()}),Rv=C_({session:j_(K(),h_()),expiresAt:s_(),signature:K()});function zv(e){let t=Lv.safeParse(j(e));return t.success?t.data:null}function Bv(e){let t=Rv.safeParse(e);return t.success?t.data:null}function Vv(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}var Hv=`__Secure-`;function Uv(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}var Wv=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Gv=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function Kv(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function qv(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function Jv(e){let t=new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=qv(n.slice(0,e)),i=Kv(qv(n.slice(e+1)));Wv.test(r)&&Gv.test(i)&&t.set(r,Vv(i))}return t}function Yv(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}var Xv={name:`HMAC`,hash:`SHA-256`},Zv=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Yv().importKey(`raw`,t,Xv,!1,[`sign`,`verify`])},Qv=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await Yv().verify(Xv,n,i,new TextEncoder().encode(t))}catch{return!1}},$v=async(e,t)=>{let n=await Zv(t),r=await Yv().sign(Xv.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},ey=async(e,t)=>{let n=await $v(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},ty=/^application\/([a-z0-9.+-]*\+)?json/i;async function ny(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new ce(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new ce(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(ty.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new ce(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function ry(e){return e instanceof ce||e?.name===`APIError`}function iy(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function ay(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function oy(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var sy=(e,t)=>{let n=e;if(t){if(t===`secure`)n=`__Secure-`+e;else if(t===`host`)n=`__Host-`+e;else return}return n};function cy(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,iy(n))}n=i+1}return t}var ly=(e,t,n={})=>{let r;if(r=n?.prefix===`secure`?`${`__Secure-${e}`}=${t}`:n?.prefix===`host`?`${`__Host-${e}`}=${t}`:`${e}=${t}`,e.startsWith(`__Secure-`)&&!n.secure&&(n.secure=!0),e.startsWith(`__Host-`)&&(n.secure||=!0,n.path!==`/`&&(n.path=`/`),n.domain&&=void 0),n&&typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&n.prefix!==`host`&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(n.secure||=!0,r+=`; Partitioned`),r},uy=(e,t,n)=>(t=encodeURIComponent(t),ly(e,t,n)),dy=async(e,t,n,r)=>(t=await ey(t,n),ly(e,t,r));async function fy(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:py(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:py(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function py(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var my=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await fy(t,e);if(o)throw new S(o.message,o.issues);let s=`headers`in e?e.headers instanceof Headers?e.headers:new Headers(e.headers):`request`in e&&oy(e.request)?e.request.headers:null,c=s?.get(`cookie`),l=c?cy(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=sy(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=sy(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await Qv(s,o,await Zv(t))?o:!1},setCookie:(e,t,n)=>{let i=uy(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await dy(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new ce(`FOUND`,void 0,r)),error:(e,t,n)=>new ce(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function hy(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function gy(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function _y(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var vy=new Set(`host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function yy(e){for(let t of vy)e.delete(t)}function by(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function xy(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);yy(n),by(e.headers,n)}return e}if(_y(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(by(i,r?.headers),by(i,e.headers),t?.headers){let e=new Headers(t.headers);yy(e),by(i,e)}return i.set(`Content-Type`,`application/json`),new Response(JSON.stringify(n),{...r,headers:i,status:e.status??t?.status??r?.status,statusText:t?.statusText??r?.statusText})}if(ry(e))return xy(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return yy(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):hy(e)&&(n=gy(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function Sy(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new de(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new de(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await ay(my(t,{options:i,path:r}));if(o)throw o instanceof S?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new ce(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(ry(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?xy(s,{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function Cy(e,t){return[...e??[],...t??[]]}Sy.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return Sy(n,{...r,use:Cy(r.use,e?.use)},i)}let[n,r]=t;return Sy({...n,use:Cy(n.use,e?.use)},r)}return t};function wy(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await my(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw ry(e)&&Object.defineProperty(e,ue,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}wy.create=e=>{function t(t,n){if(typeof t==`function`)return wy({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return wy({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var Ty={};function Ey(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function Dy(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof S_&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof S_&&t.push({name:e,in:`query`,schema:{type:Ey(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function Oy(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof S_||e.body instanceof R_)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof S_&&(n[e]={type:Ey(t),description:t.description},t instanceof R_||r.push(e))}),{required:e.body instanceof R_?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function ky(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function Ay(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(!(!t.path||n.metadata?.SERVER_ONLY)&&(n.method===`GET`&&(Ty[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Dy(n),responses:ky(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=Oy(n);Ty[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Dy(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:ky(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:Ty}}var jy=(e,t)=>`<!doctype html>
|
|
111
|
-
<html>
|
|
112
|
-
<head>
|
|
113
|
-
<title>Scalar API Reference</title>
|
|
114
|
-
<meta charset="utf-8" />
|
|
115
|
-
<meta
|
|
116
|
-
name="viewport"
|
|
117
|
-
content="width=device-width, initial-scale=1" />
|
|
118
|
-
</head>
|
|
119
|
-
<body>
|
|
120
|
-
<script
|
|
121
|
-
id="api-reference"
|
|
122
|
-
type="application/json">
|
|
123
|
-
${JSON.stringify(e)}
|
|
124
|
-
<\/script>
|
|
125
|
-
<script>
|
|
126
|
-
var configuration = {
|
|
127
|
-
favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
|
|
128
|
-
theme: ${t?.theme||`saturn`},
|
|
129
|
-
metaData: {
|
|
130
|
-
title: ${t?.title||`Open API Reference`},
|
|
131
|
-
description: ${t?.description||`Better Call Open API`},
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
document.getElementById('api-reference').dataset.configuration =
|
|
135
|
-
JSON.stringify(configuration)
|
|
136
|
-
<\/script>
|
|
137
|
-
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
|
|
138
|
-
</body>
|
|
139
|
-
</html>`,My=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function Ny(){return{root:{key:``},static:new My}}function Py(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function Fy(e){if(!e.includes(`{`))return;let t=Py(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}var Iy=`__rou3_unnamed_`,Ly=`__rou3_esc_`;function Ry(e){return`${Iy}${e}`}function zy(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:Ly+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function By(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function Vy(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92){n++;continue}if(r===40){t++;continue}if(r===41&&t>0){t--;continue}if(r===42&&t===0)return!0}return!1}function Hy(e,t,n=Ry){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);if(o===92){a+=e[t],t+1<e.length&&(a+=e[++t]);continue}if(o===40){r++,a+=e[t];continue}if(o===41&&r>0){r--,a+=e[t];continue}if(o===42&&r===0){a+=`(?<${n(i++)}>[^/]*)`;continue}a+=e[t]}return[a,i]}function Uy(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function Wy(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||Vy(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function Gy(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function Ky(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function qy(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function Jy(e){let t=qy(e);for(;t[t.length-1]===``;)t.pop();return t}function Yy(e,t){let n=new My;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[By(t)]=e.groups[t]}}return n}function Xy(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=Fy(n);if(i){for(let n of i)Xy(e,t,n,r);return}n=Uy(n);let a=Jy(n),o=Gy(a);if(o){for(let n of o)Xy(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=Wy(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=Zy(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new My),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new My;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function Zy(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=``+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=Hy(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${zy(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${Ry(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function Qy(e,t=``,n,r){r?.normalize&&(n=Ky(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=qy(n),o=$y(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?Yy(a,o.paramsMap):void 0}}function $y(e,t,n,r){if(r===n.length){if(e.methods){let r=eb(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&eb(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&eb(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=$y(a,t,n,r+1);if(e)return e}}if(e.param){let i=$y(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return eb(e.wildcard.methods,t,n,!0,!1)}function eb(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function tb(e,t=``,n,r){r?.normalize&&(n=Ky(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=qy(n),a=nb(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?Yy(i,e.paramsMap):void 0}))}function nb(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)rb(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}rb(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(nb(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}rb(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&nb(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&rb(i,n,e.key===`*`)}return i}function rb(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}var ib=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=Sy(n.path,{method:`GET`},async t=>{let r=await Ay(e);return new Response(jy(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=Ny(),r=Ny();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)Xy(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)Xy(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=Qy(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await ny(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=tb(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return xy(r)}catch(e){if(ry(e))return xy(e);throw e}if(t?.throwError)throw n;return ry(n)?xy(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=oy(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}},ab=4050,ob=100;function sb(e,t){return ab-uy(e,``,{...t}).length}function cb(e,t){let n={},r=Jv(t.headers?.get(`cookie`)||``);for(let[t,i]of r)t.startsWith(e)&&(n[t]=i);return n}function lb(e,t,n,r){let i=sb(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>ob)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${ab} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function ub(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}var db=e=>(t,n,r)=>{let i=cb(t,r),a=r.context.logger,o=()=>{let e=ub(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=lb(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},fb=db(`Session`),pb=db(`Account`);function mb(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of Jv(i))if(e.startsWith(t+`.`)){let t=e.split(`.`).at(-1),i=parseInt(t||`0`,10);isNaN(i)||r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function hb(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await El(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=pb(n.name,r,e);a.setCookies(a.chunk(i,r))}async function gb(e){let t=mb(e,e.context.authCookies.accountData.name);if(t){let n=j(await Ol(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}var _b=z_(C_({disableCookieCache:ov().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:ov().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()})),vb=new Map,yb={decode:(e,t=`utf-8`)=>(vb.has(t)||vb.set(t,new TextDecoder(t)),vb.get(t).decode(e)),encode:new TextEncoder().encode},bb=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>Gl().importKey(`raw`,typeof t==`string`?new TextEncoder().encode(t):t,{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await Gl().sign(`HMAC`,e,typeof r==`string`?new TextEncoder().encode(r):r);return t===`hex`?Rl.encode(i):t===`base64`||t===`base64url`||t===`base64urlnopad`?Xl.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=Rl.decode(i)),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await Yl.decode(i)),Gl().verify(`HMAC`,e,typeof i==`string`?new TextEncoder().encode(i):i,typeof r==`string`?new TextEncoder().encode(r):r))};return n};function xb(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):h):e.advanced?.useSecureCookies)?Hv:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!Qi(e.baseURL))throw new b(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function Sb(e){let t=xb(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||Iv(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function Cb(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=pv(t.session,e.context.options.session?.additionalFields),i=gv(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=Ev(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=Tv(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await El(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;d=t?await t.sign(e,s,c.maxAge||300):await _l(s,e.context.secret,c.maxAge||300)}else d=Xl.encode(JSON.stringify({session:s,expiresAt:l,signature:await bb(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=fb(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!Db(e,e.context.authCookies.accountData.name)){let n=await gb(e);if(n){if(!sd(e.context.options)||n.userId===t.user.id)await hb(e,n);else{Ob(e,e.context.authCookies.accountData);let t=pb(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function wb(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await Ol(t,e.context.secretConfig,`better-auth-session`),r=zv(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await vl(t,e.context.secret),i=zv(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=Bv(j(yb.decode(Xl.decode(t))));if(!r||!await bb(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=zv(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function Tb(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await Cb(e,t,n),e.context.setNewSession(t)}function Eb(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():Uv(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function Db(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():Uv(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function Ob(e,t){Eb(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function kb(e,t){if(Ob(e,e.context.authCookies.sessionToken),Ob(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){Ob(e,e.context.authCookies.accountData);let t=pb(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&Ob(e,e.context.createAuthCookie(`oauth_state`));let n=fb(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||Ob(e,e.context.authCookies.dontRememberToken)}var Ab=T_({callbackURL:K(),codeVerifier:K(),errorURL:K().optional(),newUserURL:K().optional(),expiresAt:s_(),oauthState:K().optional(),link:C_({email:K(),userId:av()}).optional(),requestSignUp:d_().optional(),idTokenNonce:K().optional(),serverContext:j_(K(),h_()).optional()});new Set(Object.keys(Ab.shape));var jb=class extends b{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function Mb(e,t,n){let r=aa(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await rd({key:e.context.secretConfig,data:JSON.stringify(i)}),o=e.context.createAuthCookie(n?.cookieName??`oauth_state`,{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:r,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(n?.cookieName??`state`,{maxAge:300});await e.setSignedCookie(i.name,r,e.context.secret,i.attributes);let a=new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:r}),identifier:r,expiresAt:a}))throw new jb(`Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database`,{code:`state_generation_error`});return{state:r,codeVerifier:t.codeVerifier}}async function Nb(e,t,n){if(!t)throw new jb(`State not found in OAuth callback`,{code:`state_not_found`});let r=e.context.oauthConfig.storeStateStrategy,i;if(r===`cookie`){let r=e.context.createAuthCookie(n?.cookieName??`oauth_state`),a=e.getCookie(r.name);if(!a)throw new jb(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await id({key:e.context.secretConfig,data:a});i=Ab.parse(JSON.parse(t))}catch(e){throw new jb(`State invalid: Failed to decrypt or parse auth state`,{code:`state_invalid`,details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new jb(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});Ob(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw new jb(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=Ab.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new jb(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});let a=e.context.createAuthCookie(n?.cookieName??`state`),o=await e.getSignedCookie(a.name,e.context.secret);if(!(n?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new jb(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});Ob(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(t)}if(i.expiresAt<Date.now())throw new jb(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}var Pb={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`},Fb=`https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`;function Ib(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=t.includes(`?`)?`&`:`?`;throw e.redirect(`${t}${a}${i.toString()}`)}function Lb(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See ${Fb}`}var Rb=Symbol.for(`better-auth:global`),zb=null,Bb={},Vb=`1.7.1`;function Hb(){return globalThis[Rb]||(globalThis[Rb]={version:Vb,epoch:1,context:Bb},zb=globalThis[Rb]),zb=globalThis[Rb],zb.version!==Vb&&(zb.version=Vb,zb.epoch++),globalThis[Rb]}function Ub(){return Hb().version}var Wb=class{#e=void 0;run(e,t){let n=this.#e;this.#e=e;let r=t();return r instanceof Promise?r.finally(()=>{this.#e=n}):(this.#e=n,r)}getStore(){return this.#e}},Gb=Promise.resolve().then(()=>`AsyncLocalStorage`in globalThis?globalThis.AsyncLocalStorage:Wb);async function Kb(){let e=await Gb;if(e===null)throw Error(`getAsyncLocalStorage is only available in server code`);return e}var qb=async()=>{let e=Hb(),t=e.context.endpointContextAsyncStorage;if(t)return t;let n=await Kb();return e.context.endpointContextAsyncStorage??=new n,e.context.endpointContextAsyncStorage};async function Jb(){let e=(await qb()).getStore();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function Yb(e,t){return(await qb()).run(e,t)}var Xb=async()=>{let e=Hb(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await Kb();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function Zb(){return(await Xb()).getStore()!==void 0}async function Qb(){let e=(await Xb()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function $b(e,t){return(await Xb()).run(e,t)}function ex(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await Qb();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await Qb()).set(t,e)}}}var tx=async()=>{let e=Hb(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await Kb();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},nx=async e=>tx().then(t=>t.getStore()?.adapter||e).catch(()=>e),rx=async(e,t)=>{let n=!1;return tx().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},ix=async(e,t,n)=>{let r=!1;return tx().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=[],o,s,c=!1;try{o=await e.transaction(async e=>i.run({adapter:e,pendingHooks:a,isTransactionActive:!0},t))}catch(e){c=!0,s=e}if(c)throw s;for(let e of a)try{await e()}catch(e){if(!n?.onAfterCommitHookError)throw e;try{await n.onAfterCommitHookError(e)}catch{}}return o}).catch(e=>{if(!r)return t();throw e})},ax=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await tx()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)},{get:ox,set:sx}=ex(()=>null),{get:cx,set:lx}=ex(()=>null);function ux(e){return e.requiresIdTokenNonce?aa(32):void 0}async function dx(e,t){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw E.from(`BAD_REQUEST`,V.CALLBACK_URL_REQUIRED);let r=t?.codeVerifier??aa(128),i=await cx(),a=i&&Object.keys(i).length?i:void 0,o={...t?.additionalData?t.additionalData:{},callbackURL:n,codeVerifier:r,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:a,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await sx(o);try{return Mb(e,o)}catch(t){throw e.context.logger.error(`Failed to create verification`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`Unable to create verification`,cause:t})}}async function fx(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await Nb(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof jb&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL??n),Ib(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await sx(r),r}var px={scope:`server`};function mx(e){return e instanceof ce||e instanceof E||e?.name===`APIError`}var hx={"Cache-Control":`no-store`,Pragma:`no-cache`};function gx(e,t){!mx(t)||!e||Object.defineProperty(t,ue,{enumerable:!1,configurable:!0,value:e,writable:!1})}var _x=wy(async()=>({})),vx=wy.create({use:[_x,wy(async()=>({}))]}),yx=Sy.create({use:[_x]});function bx(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(hx))t.setHeader(e,n);try{return await Yb(t,()=>e(t))}catch(e){throw gx(t.responseHeaders,e),e}}}function q(...e){if(e.length===3){let[t,n,r]=e;return yx(t,n,bx(r,n))}let[t,n]=e;return yx(t,bx(n,t))}function xx(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}q.serverOnly=(e,t)=>q(xx(e),t);var Sx=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},Cx=e=>{let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=Sx(r.replace(/[?#].*$/,``));return{scheme:n,authority:i.toLowerCase(),path:a}},wx=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths?e.startsWith(`/`)&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(e):!1;if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return zi(t)(Yi(e)||e);let n=Zi(e);return n?zi(t)(n):!1}let r=Xi(e);if(r===`http:`||r===`https:`||!r)return t===Yi(e);let i=Cx(e),a=Cx(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function Tx(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}var Ex=[`javascript:`,`data:`,`vbscript:`];function Dx(e){let t;try{t=new URL(e)}catch{return!0}return!Ex.includes(t.protocol)}function Ox(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function kx(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function Ax(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=Tx(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}var jx=Ox(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),Mx=vx(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await Px(e),Ax(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw E.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,V.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,V.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,V.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,V.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,V.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),Nx=e=>vx(async t=>{if(!t.request||Ax(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,V.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,V.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,V.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,V.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,V.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function Px(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`)||n.get(`referer`)||``,i=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(kx(e)){e.context.options.advanced?.disableOriginCheck===!0&&jx();return}if(Ax(e)||!(t||i))return;if(!r||r===`null`)throw E.from(`FORBIDDEN`,V.MISSING_OR_NULL_ORIGIN);let a=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!a.some(e=>wx(r,e)))throw e.context.logger.error(`Invalid origin: ${r}`),e.context.logger.info(`If it's a valid URL, please add ${r} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${a}`),E.from(`FORBIDDEN`,V.INVALID_ORIGIN)}var Fx=vx(async e=>{e.request&&await Ix(e)});async function Ix(e){let t=e.request;if(!t||e.context.skipCSRFCheck||kx(e))return;let n=t.headers;if(n.has(`cookie`))return await Px(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),E.from(`FORBIDDEN`,V.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await Px(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await Px(e,!0)}function Lx(e){return Zg().safeParse(e).success||$g().safeParse(e).success}function Rx(e){return $g().safeParse(e).success}function zx(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(Zg().safeParse(e).success)return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&Zg().safeParse(e).success)return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=Bx(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function Bx(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function Vx(e,t){let n=Bx(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function Hx(e,t={}){if(Zg().safeParse(e).success||!Rx(e))return e.toLowerCase();let n=zx(e);return n?n.toLowerCase():Vx(e,t.ipv6Subnet??64)}function Ux(e){if(Zg().safeParse(e).success)return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!Rx(e))return null;let t=zx(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=Bx(e),r=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}var Wx=/^\d+$/;function Gx(e){let t=e.lastIndexOf(`/`),n=Ux(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!Wx.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function Kx(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function qx(e){return e.filter(e=>Gx(e)===null)}function Jx(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(Gx).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?Ux(i):null;if(!i||!a)return null;if(!r.some(e=>Kx(a,e)))return Hx(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!Lx(i)?null:Hx(i,{ipv6Subnet:t.ipv6Subnet})}var Yx=`127.0.0.1`,Xx=[`x-forwarded-for`];function Zx(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||Xx;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=Jx(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return k()||A()?Yx:null}function Qx(e,t){return`${e}|${t}`}var $x=new Map,eS=1e5;function tS(){let e=Date.now();for(let[t,n]of $x)e>=n.expiresAt&&$x.delete(t);if($x.size<=eS)return;let t=$x.size-eS,n=0;for(let e of $x.keys())if($x.delete(e),++n>=t)break}function nS(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:iS(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function rS(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"X-Retry-After":e.toString()}})}function iS(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function aS(e){let t=`rateLimit`,n=e.adapter,r=Math.max(...oS(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return typeof r?.lastRequest==`bigint`&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:iS(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function oS(e){let t=[e.rateLimit.window,...fS().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function sS(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new b(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){tS();let r=Date.now(),i=$x.get(e),a=nS(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&$x.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return aS(e)}var cS=!1,lS=`no-trusted-ip`;async function uS(e,t){let n=new URL(t.baseURL).pathname,r=Tx(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=Zx(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!cS&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),cS=!0);let s=Qx(o??lS,r),c=fS().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?zi(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function dS(e,t){if(!t.rateLimit.enabled)return;let n=await uS(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=sS(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return rS(l??i)}function fS(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}var{get:pS,set:mS}=ex(()=>!1),hS=()=>q(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:_b,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw E.from(`METHOD_NOT_ALLOWED`,V.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return null;let i=mb(e,e.context.authCookies.sessionData.name),a=i?await wb(e,i):null;i&&!a&&Ob(e,e.context.authCookies.sessionData);let o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(a?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let t=a.session,n=t.session.token!==r;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=a.expiresAt<e||!Number.isFinite(r)||r<e}if(n)Ob(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=vv(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=gv(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=a.expiresAt-Date.now(),i=n.updateAge*1e3,s=await pS();if(r<i&&!s){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await Cb(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=o?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=vv(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),s=gv(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:s},e.json({session:a,user:s})}let c=vv(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=gv(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:c,user:l},e.json({session:c,user:l})}}let s=await e.context.internalAdapter.findSession(r);if(e.context.session=s,!s||s.session.expiresAt<new Date)return kb(e),s&&(!t||n)&&await e.context.internalAdapter.deleteSession(s.session.token),e.json(null);if(o||e.query?.disableRefresh){let t=vv(e.context.options,s.session),n=gv(e.context.options,s.user);return e.json({session:t,user:n})}let c=e.context.sessionConfig.expiresIn,l=e.context.sessionConfig.updateAge,u=s.session.expiresAt.valueOf()-c*1e3+l*1e3<=Date.now(),d=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,f=await pS(),p=u&&!d&&!f;if(t&&!n){await Cb(e,s,!!o);let t=vv(e.context.options,s.session),n=gv(e.context.options,s.user);return e.json({session:t,user:n,needsRefresh:p})}if(p){let t=await e.context.internalAdapter.updateSession(s.session.token,{expiresAt:Tv(e.context.sessionConfig.expiresIn,`sec`),updatedAt:new Date});if(!t)throw kb(e),E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await Tb(e,{session:t,user:s.user},!1,{maxAge:n});let r=vv(e.context.options,t),i=gv(e.context.options,s.user);return e.json({session:r,user:i})}await Cb(e,s,!!o);let m=vv(e.context.options,s.session),h=gv(e.context.options,s.user);return e.json({session:m,user:h})}catch(t){throw mx(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),E.from(`INTERNAL_SERVER_ERROR`,V.FAILED_TO_GET_SESSION))}}),gS=e=>ad(e.context.options),_S=async(e,t)=>{if(e.context.session)return e.context.session;let n=await hS()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},vS=async e=>gS(e)?(e.context.session=null,_S(e,{disableCookieCache:!0})):_S(e),yS=vx(async e=>{let t=await _S(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),bS=vx(async e=>{let t=await vS(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});vx(async e=>{let t=await _S(e);if(!t?.session&&(e.request||e.headers))throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});var xS=vx(async e=>{let t=await _S(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`FORBIDDEN`,V.SESSION_NOT_FRESH)}return{session:t}}),SS=()=>q(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[xS],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>vv(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),CS=q(`/revoke-session`,{method:`POST`,body:C_({token:K().meta({description:`The token to revoke`})}),use:[bS],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),wS=q(`/revoke-sessions`,{method:`POST`,use:[bS],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),TS=q(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[bS],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function ES(e){if(!e?.method)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function DS(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;ES(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new E(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new E(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}var OS=async e=>{let t=await Zl(`SHA-256`).digest(new TextEncoder().encode(e));return Xl.encode(new Uint8Array(t),{padding:!1})};async function kS(e,t){return!t||t===`plain`?e:t===`hashed`?OS(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function AS(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}var jS=`better_auth.operation_id`,MS=`better_auth.hook.type`,NS=`better_auth.context`;function PS(e,t){let n=t.hooks;async function r(t,r,i){let a=await Jb().catch(()=>null),o=t;for(let{source:e,hooks:t}of n){let n=t[r]?.create?.before;if(n){let t=await x(`db create.before ${r}`,{[MS]:`create.before`,[N]:r,[NS]:e},()=>n(o,a));if(t===!1)return null;typeof t==`object`&&`data`in t&&(o={...o,...t.data})}}let s=null;(!i||i.executeMainFn)&&(s=await(await nx(e)).create({model:r,data:o,forceAllowId:!0})),i?.fn&&(s=await i.fn(s??o));for(let{source:e,hooks:t}of n){let n=t[r]?.create?.after;n&&await ax(async()=>{await x(`db create.after ${r}`,{[MS]:`create.after`,[N]:r,[NS]:e},()=>n(s,a))})}return s}async function i(t,r,i,a){let o=await Jb().catch(()=>null),s=t;for(let{source:e,hooks:r}of n){let n=r[i]?.update?.before;if(n){let r=await x(`db update.before ${i}`,{[MS]:`update.before`,[N]:i,[NS]:e},()=>n(t,o));if(r===!1)return null;typeof r==`object`&&`data`in r&&(s={...s,...r.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await(await nx(e)).update({model:i,update:s,where:r}):c;for(let{source:e,hooks:t}of n){let n=t[i]?.update?.after;n&&await ax(async()=>{await x(`db update.after ${i}`,{[MS]:`update.after`,[N]:i,[NS]:e},()=>n(l,o))})}return l}async function a(t,r,i,a){let o=await Jb().catch(()=>null),s=t;for(let{source:e,hooks:r}of n){let n=r[i]?.update?.before;if(n){let r=await x(`db updateMany.before ${i}`,{[MS]:`updateMany.before`,[N]:i,[NS]:e},()=>n(t,o));if(r===!1)return null;typeof r==`object`&&`data`in r&&(s={...s,...r.data})}}let c=a?await a.fn(s):null,l=!a||a.executeMainFn?await(await nx(e)).updateMany({model:i,update:s,where:r}):c;for(let{source:e,hooks:t}of n){let n=t[i]?.update?.after;n&&await ax(async()=>{await x(`db updateMany.after ${i}`,{[MS]:`updateMany.after`,[N]:i,[NS]:e},()=>n(l,o))})}return l}async function o(t,r,i){let a=await Jb().catch(()=>null),o=null;try{o=(await(await nx(e)).findMany({model:r,where:t,limit:1}))[0]||null}catch{}if(o)for(let{source:e,hooks:t}of n){let n=t[r]?.delete?.before;if(n&&await x(`db delete.before ${r}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":r,"better_auth.context":e},()=>n(o,a))===!1)return null}let s=i?await i.fn(t):null,c=(!i||i.executeMainFn)&&o?await(await nx(e)).delete({model:r,where:t}):s;if(o)for(let{source:e,hooks:t}of n){let n=t[r]?.delete?.after;n&&await ax(async()=>{await x(`db delete.after ${r}`,{[MS]:`delete.after`,[N]:r,[NS]:e},()=>n(o,a))})}return c}async function s(t,r,i){let a=await Jb().catch(()=>null),o=[];try{o=await(await nx(e)).findMany({model:r,where:t})}catch{}for(let e of o)for(let{source:t,hooks:i}of n){let n=i[r]?.delete?.before;if(n&&await x(`db delete.before ${r}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":r,"better_auth.context":t},()=>n(e,a))===!1)return null}let s=i?await i.fn(t):null,c=!i||i.executeMainFn?await(await nx(e)).deleteMany({model:r,where:t}):s;for(let e of o)for(let{source:t,hooks:i}of n){let n=i[r]?.delete?.after;n&&await ax(async()=>{await x(`db delete.after ${r}`,{[MS]:`delete.after`,[N]:r,[NS]:t},()=>n(e,a))})}return c}async function c(t,r,i,a){let o=await Jb().catch(()=>null),s=n.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),c=a??null;if(s.length){if(!c)try{c=(await(await nx(e)).findMany({model:t,where:r,limit:1}))[0]||null}catch{}if(c){for(let{source:e,fn:n}of s)if(await x(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>n(c,o))===!1)return null}}let l=await i();if(!l)return null;for(let{source:e,hooks:r}of n){let n=r[t]?.delete?.after;n&&await ax(async()=>{await x(`db delete.after ${t}`,{[MS]:`delete.after`,[N]:t,[NS]:e},()=>n(l,o))})}return l}return{createWithHooks:r,updateWithHooks:i,updateManyWithHooks:a,deleteWithHooks:o,deleteManyWithHooks:s,consumeOneWithHooks:c}}function FS(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}var IS=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=new Map,o=r.session?.expiresIn||604800,{createWithHooks:s,updateWithHooks:c,updateManyWithHooks:l,deleteWithHooks:u,deleteManyWithHooks:d,consumeOneWithHooks:f}=PS(e,t),p=t=>{let n=[...t,{field:`expiresAt`,value:new Date,operator:`gt`}];return d(n,`session`,{fn:async()=>{await(await nx(e)).updateMany({model:`session`,where:n,update:{expiresAt:new Date}})},executeMainFn:!1})};async function m(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=(j(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=j(r);if(!a)return;let o=FS(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function h(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&j(t)||[]}async function g(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await h(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;if(c){await i.set(r,JSON.stringify(s),FS(c,o));return}await i.delete(r)}async function _(e,t){if(!i)return;let r=t??await h(e);await ax(()=>g(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function v(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>ix(e,async()=>{let e=await s({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new E(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await s({...n,userId:e.id,createdAt:new Date,updatedAt:new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};ES(e);let r;try{r=await Jb()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new E(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await DS(r,{user:i,source:e})}return await s(i,`user`,void 0)},createAccount:async e=>await s({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=j(e)||[],a=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(vv(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await nx(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await nx(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await nx(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await h(e);(!i||r.session?.storeSessionInDatabase)&&await d([{field:`userId`,value:e}],`session`,void 0),await d([{field:`userId`,value:e}],`account`,void 0),await u([{field:`id`,value:e}],`user`,void 0)!==null&&await _(e,t)},createSession:async(a,c,l,u,d)=>{let f=await(async()=>{let e=await Jb().catch(()=>null);return e?.headers||e?.request?.headers})(),p=r.session?.storeSessionInDatabase,m=p===!0&&r.session?.preserveSessionInDatabase!==!0,{id:h,...g}=l||{},_;if(i&&!p){let e=t.generateId({model:`session`});_=e===!1?O():e}let v=wv(r),y={..._?{id:_}:{},ipAddress:f&&Zx(f,r)||``,userAgent:f?.get(`user-agent`)||``,...g,expiresAt:Tv(c?86400:o,`sec`),userId:a,token:O(32),createdAt:new Date,updatedAt:new Date,...v,...u?g:{}},ee=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=j(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==y.token));let s=[...r,{token:y.token,expiresAt:y.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=FS(s.at(-1)?.expiresAt??y.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await nx(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=FS(y.expiresAt,o);return u>0&&await i.set(y.token,JSON.stringify({session:t,user:l}),u),t},te=await s(y,`session`,i?{fn:async e=>d?.deferSecondaryStorageWrites?e:ee(e),executeMainFn:p}:void 0);return i&&d?.deferSecondaryStorageWrites&&te&&await ax(async()=>{await ee(te)},m?{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}:void 0),te},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=j(e);return n?{session:vv(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:gv(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await nx(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:vv(t.options,s),user:gv(t.options,o)}:null},findSessions:async(t,n)=>{if(i){let e=[];for(let r of t){let t=await i.get(r);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=new Date)continue;let a={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};e.push(a)}catch{continue}}return e}let r=await(await nx(e)).findMany({model:`session`,where:[{field:`token`,value:t,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]],join:{user:!0}});return!r.length||r.some(e=>!e.user)?[]:r.map(e=>{let{user:t,...n}=e;return{session:n,user:t}})},updateSession:async(e,n)=>await c(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=j(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=vv(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=FS(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&j(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),FS(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=j(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=j(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),FS(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await p([{field:`token`,value:e}]);return}}await u([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await d([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await u([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await h(e);if(i){if(!r.session?.storeSessionInDatabase){await _(e,n);return}if(t.options.session?.preserveSessionInDatabase){await p([{field:`userId`,value:e}])!==null&&await _(e,n);return}}await d([{field:`userId`,value:e}],`session`,void 0)!==null&&await _(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await p([{field:`token`,value:e,operator:`in`}]);return}}await d([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({issuer:t,accountId:n})=>{let r=await(await nx(e)).findOne({model:`account`,where:[{field:`issuer`,value:t},{field:`accountId`,value:n}],join:{user:!0}});if(!r)return null;let{user:i,...a}=r;return i?{kind:`owned`,user:i,account:a}:{kind:`orphaned`,account:a}},findUserByEmail:async(t,n)=>{let r=await(await nx(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await nx(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await s({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await c({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await ax(()=>m(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await c({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await ax(()=>m(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await l({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`issuer`,value:lv(`credential`)},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await nx(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await nx(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`issuer`,value:lv(`credential`)},{field:`accountId`,value:t}]}),findAccountByKey:async({issuer:t,accountId:n})=>await(await nx(e)).findOne({model:`account`,where:[{field:`issuer`,value:t},{field:`accountId`,value:n}]}),findAccountByUserId:async t=>await(await nx(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await c(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=AS(e.identifier,r.verification?.storeIdentifier),n=await kS(e.identifier,t);return await s({createdAt:new Date,updatedAt:new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=FS(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=AS(t,r.verification?.storeIdentifier),a=await kS(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=j(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=j(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await nx(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await d([{field:`expiresAt`,value:new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await kS(e,AS(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await u([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=AS(t,r.verification?.storeIdentifier),a=await kS(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?j(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>v(`verification:${t}`,()=>ix(e,async()=>{let n=await nx(e),r=[{field:`identifier`,value:t}],i=(await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:1}))[0]??null;return i?f(`verification`,[{field:`id`,value:i.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:i.id}]});return e?(await n.deleteMany({model:`verification`,where:r}),e):null},i):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt<new Date?null:c},reserveVerificationValue:async t=>{let n=Xl.encode(new Uint8Array(await Zl(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),{padding:!1}),a=AS(t.identifier,r.verification?.storeIdentifier),o=await kS(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new b(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=FS(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await kS(e,AS(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=j(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=FS(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await c(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:m}};function LS(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function RS(e,t,n=`.`,r){if(!LS(t))return RS(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:LS(a)&&LS(i[t])?RS(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function zS(e){return(...t)=>t.reduce((t,n)=>RS(t,n,``,e),{})}var BS=zS(),VS=new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function HS(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function US(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function WS(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function GS(e){return e.replace(/\.+$/,``)}function KS(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function qS(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function JS(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function YS(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=qS(e);return JS(t,qS(`127.0.0.0`),8)?`loopback`:JS(t,qS(`10.0.0.0`),8)||JS(t,qS(`172.16.0.0`),12)||JS(t,qS(`192.168.0.0`),16)?`private`:JS(t,qS(`169.254.0.0`),16)?`linkLocal`:JS(t,qS(`100.64.0.0`),10)?`sharedAddressSpace`:JS(t,qS(`192.0.2.0`),24)||JS(t,qS(`198.51.100.0`),24)||JS(t,qS(`203.0.113.0`),24)?`documentation`:JS(t,qS(`198.18.0.0`),15)?`benchmarking`:JS(t,qS(`224.0.0.0`),4)?`multicast`:JS(t,qS(`0.0.0.0`),8)||JS(t,qS(`192.0.0.0`),24)||JS(t,qS(`192.88.99.0`),24)||JS(t,qS(`240.0.0.0`),4)?`reserved`:`public`}function XS(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function ZS(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=XS(e,1);return t&&YS(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=XS(e,6);return t&&YS(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=XS(e,6,{xor:!0});return t&&YS(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function QS(e){let t=GS(WS(HS(US(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!Lx(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:VS.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(KS(t))return{kind:YS(t),literal:`ipv4`,canonical:t};let n=Hx(t,{ipv6Subnet:128});return KS(n)?{kind:YS(n),literal:`ipv4`,canonical:n}:{kind:ZS(n),literal:`ipv6`,canonical:n}}function $S(e){let t=QS(e).kind;return t===`loopback`||t===`localhost`}async function eC(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=Ev(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=BS(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=IS(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function tC(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function nC(e,t){let n=[];if(Qi(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||$S(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=Ji(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=v.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function rC(e){if($i(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(!(!t.has(`host`)&&!t.has(`x-forwarded-host`)))return t}function iC(e){return e.advanced?.trustedProxyHeaders??!1}async function aC(e,t,n){let r=e.options.baseURL,i=ia(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new b(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:Yi(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?$i(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await nC(o,c),a.trustedProviders=await sC(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=Sb(a.options),a.createAuthCookie=xb(a.options)),a}async function oC(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function sC(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function cC(e){return e}async function lC(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new b(`OAUTH_ACCOUNT_SUBJECT_INVALID`);let s=e.accountIssuer,c=s===void 0?uv(e.id):typeof s==`function`?await s(r):s;if(typeof c!=`string`||c.trim().length===0||c===`undefined`||c===`null`)throw new b(`OAUTH_ACCOUNT_ISSUER_INVALID`);return{issuer:c,accountId:o}}async function uC(e,t,n){try{return await lC(e,t,n)}catch{throw E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_USER_INFO)}}function dC(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function fC(e,t){return e&&(t.options.account?.encryptOAuthTokens&&dC(e)?id({key:t.secretConfig,data:e}):e)}function pC(e,t){return t.options.account?.encryptOAuthTokens&&e?rd({key:t.secretConfig,data:e}):e}function mC(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function hC(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function gC(e,t,n,r=3600,i){return await _l({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function _C(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,V.VERIFICATION_EMAIL_NOT_ENABLED);let n=await gC(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}var vC=q(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:C_({email:zg().meta({description:`The email to send the verification email to`}),callbackURL:K().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,V.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await _S(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await gC(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await _C(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw E.from(`BAD_REQUEST`,V.EMAIL_MISMATCH);if(n?.user.emailVerified)throw E.from(`BAD_REQUEST`,V.EMAIL_ALREADY_VERIFIED);return await _C(e,n.user),e.json({status:!0})}),yC=q(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:C_({token:K().meta({description:`The token to verify the email`}),callbackURL:K().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[Nx(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){throw e.query.callbackURL?e.query.callbackURL.includes(`?`)?e.redirect(`${e.query.callbackURL}&error=${t.code}`):e.redirect(`${e.query.callbackURL}?error=${t.code}`):E.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await zc(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof fo?t(V.TOKEN_EXPIRED):t(V.INVALID_TOKEN)}let i=C_({email:zg(),updateTo:K().optional(),requestType:K().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(V.USER_NOT_FOUND);if(i.updateTo){let n=await _S(e);if(n&&n.user.email!==i.email)return t(V.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await gC(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},hC(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,V.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await Tb(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:gv(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,V.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await gC(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},hC(e.request))),await Tb(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:gv(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await _S(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,V.FAILED_TO_CREATE_SESSION);await Tb(e,{session:t,user:{...a.user,emailVerified:!0}})}else await Tb(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});async function bC(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({issuer:r.issuer,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
|
|
140
|
-
Error: `,t),Ib(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)});if(u?.kind===`orphaned`)return e.context.logger.error(`OAuth account references a missing user. Repair the account before retrying authentication.`),{error:`unable to link account`,data:null,isRegister:!1};let d=await(async()=>{if(u?.kind===`owned`){if(t.selectedUser&&u.user.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`account_ownership_conflict`,message:`Account is already linked to another user`});if(c&&u.account.providerId!==r.providerId)throw new E(`CONFLICT`,{code:`account_provider_conflict`,message:`Account is already linked through another provider`});return{user:u.user,linkedAccount:u.account,accounts:[u.account]}}if(t.selectedUser){let n=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!n)throw new E(`NOT_FOUND`,{code:`user_not_found`,message:`User not found`});return{user:n,linkedAccount:null,accounts:[]}}let i=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return i?{user:i.user,linkedAccount:null,accounts:i.accounts}:null})().catch(t=>{if(mx(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
|
|
141
|
-
Error: `,t),Ib(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,p=!f;if(d){let i=d.linkedAccount??d.accounts.find(e=>e.issuer===r.issuer&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await DS(e,{user:{...o,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`sign-in`}});let u=e.context.options.account?.updateAccountOnSignIn===!1?{}:Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await pC(r.accessToken,e.context),refreshToken:await pC(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>t!==void 0));if(e.context.options.account?.storeAccountCookie){let n={...i,...u};t.deferNonDatabaseWrites?l=n:await hb(e,n)}if(Object.keys(u).length>0){let n=await e.context.internalAdapter.updateAccount(i.id,u);if(!n)return{error:`unable to update account`,data:null};if(c&&(n.issuer!==r.issuer||n.accountId!==r.accountId||n.providerId!==r.providerId||n.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});t.deferNonDatabaseWrites&&l&&(l=n)}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!d.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return A()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:`account not linked`,data:null};try{let{id:i,...a}=n;await DS(e,{user:{...a,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`link-account`}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,issuer:r.issuer,accountId:r.accountId,userId:d.user.id,accessToken:await pC(r.accessToken,e.context),refreshToken:await pC(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:`unable to link account`,data:null};if(c&&(o.issuer!==r.issuer||o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=o:await hb(e,o))}catch(t){if(mx(t))throw t;return e.context.logger.error(`Unable to link account`,t),{error:`unable to link account`,data:null}}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0}),t.selectedUser||(f=await SC(e,d.user.id,n)??f)}if(t.selectedUser?t.selectedUser.profile===`update`:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...c}=n,l=Sv(e.context.options,c,`update`),u=await e.context.internalAdapter.updateUser(d.user.id,{name:o,image:s,...l,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===d.user.email&&d.user.emailVerified||n.emailVerified});if(u??e.context.logger.warn(`Could not update user info during OAuth sign in; preserving existing user for session.`),t.selectedUser&&u&&u.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`user_hook_selection_conflict`,message:`User hook changed the selected user`});f=u??f}}else{if(a)return{error:`signup disabled`,data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:u,image:d,...p}=n,m=Sv(e.context.options,p,`create`),h={accessToken:await pC(r.accessToken,e.context),refreshToken:await pC(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,issuer:r.issuer,accountId:r.accountId},{createdUser:g,createdAccount:_}=await ix(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:u,image:d,...m,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...h,userId:t.id})}});if(c&&(_.issuer!==r.issuer||_.accountId!==r.accountId||_.providerId!==r.providerId||_.userId!==g.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});f=g,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=_:await hb(e,_))}catch(t){if(mx(t))throw t;return e.context.logger.error(`Unable to create OAuth user`,t),{error:`unable to create user`,data:null,isRegister:!1}}}if(!f)return{error:`unable to create user`,data:null,isRegister:!1};let m=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(p&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??m)&&await xC(e,f,i,t.deferNonDatabaseWrites),m&&!f.emailVerified)return!p&&e.context.options.emailVerification?.sendOnSignIn&&await xC(e,f,i,t.deferNonDatabaseWrites),{error:Pb.EMAIL_NOT_VERIFIED,data:null,isRegister:p};let h=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!h)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&h.userId!==(t.selectedUser?.userId??f.id))throw new E(`CONFLICT`,{code:`session_hook_user_conflict`,message:`Session hook changed the selected user`});return{data:{session:h,user:f},error:null,isRegister:p,accountCookie:l}}async function xC(e,t,n,r){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let a=async()=>{try{let r=await gC(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(n||`/`)}`;await e.context.runInBackgroundOrAwait(i({user:t,url:a,token:r},e.request))}catch(t){e.context.logger.error(`Failed to send OAuth verification email`,t)}};r?await ax(a):await a()}async function SC(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=Sv(e.context.options,s,`update`);return await e.context.internalAdapter.updateUser(t,{name:a,image:o,...c})}catch(t){e.context.logger.warn(`Could not update user info on account link`,t);return}}function CC(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function wC(e){let t=e=>new Date(new Date().getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:CC(e.scope),idToken:e.id_token,raw:e}}function TC(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[...new Set([...n,...r])].join(`,`)}function EC(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function DC(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Xl.encode(new Uint8Array(n),{padding:!1})}var OC=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],kC=new Set(OC);async function J({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let ee=EC(t.clientId);if(!ee)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,ee),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await DC(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))kC.has(e)||y.searchParams.set(e,t);return y}var AC=j_(K(),K()).refine(e=>!Object.keys(e).some(e=>kC.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${OC.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional();function jC(e){return new URLSearchParams({v:e}).toString().slice(2)}function MC(e,t){let n=`${jC(e)}:${jC(t)}`;return`Basic ${Yl.encode(n)}`}var NC=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`;async function PC({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:NC}}var FC=Object.defineProperty,IC=Object.defineProperties,LC=Object.getOwnPropertyDescriptors,RC=Object.getOwnPropertySymbols,zC=Object.prototype.hasOwnProperty,BC=Object.prototype.propertyIsEnumerable,VC=(e,t,n)=>t in e?FC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,HC=(e,t)=>{for(var n in t||={})zC.call(t,n)&&VC(e,n,t[n]);if(RC)for(var n of RC(t))BC.call(t,n)&&VC(e,n,t[n]);return e},UC=(e,t)=>IC(e,LC(t)),WC=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},GC=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},KC=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},qC=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function JC(e){if(typeof e==`number`)return new KC({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new KC(e);case`exponential`:return new qC(e);default:throw Error(`Invalid retry strategy`)}}var YC=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},XC=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function ZC(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return XC.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function QC(e){try{return JSON.parse(e),!0}catch{return!1}}function $C(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function ew(e){try{return JSON.parse(e)}catch{return e}}function tw(e){return typeof e==`function`}function nw(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&tw(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&tw(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function rw(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function iw(e){let t=new Headers(rw(e?.headers,await YC(e)));if(!t.has(`content-type`)){let n=aw(e?.body);n&&t.set(`content-type`,n)}return t}function aw(e){return $C(e)?`application/json`:null}function ow(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function sw(e,t){let{body:n}=e;return n?!$C(n)||typeof n==`string`?n:ow(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function cw(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return fw.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function lw(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var uw=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function dw(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new uw(n.issues);return n.value}var fw=[`get`,`post`,`put`,`patch`,`delete`],pw=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await dw(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=UC(HC({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=UC(HC({},r),{body:i.input?await dw(i.input,n?.body):n?.body,params:i.params?await dw(i.params,n?.params):n?.params,query:i.query?await dw(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),mw=e=>{async function t(t,n){let r=UC(HC(HC({},e),n),{headers:rw(e?.headers,n?.headers),plugins:[...e?.plugins||[],pw(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Y(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Y(t,r)}return t},hw=e=>e===`.`||e===`..`;function gw(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(hw(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function _w(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];fw.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}let l=new Map;if(r){if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t))}o=o.split(`/`).map(e=>gw(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var Y=async(e,t)=>{let{hooks:n,url:r,options:i}=await GC(e,t),a=nw(i),o=new AbortController,s=i.signal??o.signal,c=_w(r,i),l=await iw(i),u=sw(i,l),d=cw(r,i),f=UC(HC({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=lw(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(UC(HC({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=ZC(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??ew)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await dw(f.output,r.data));for(let e of n.onSuccess)e&&await e(UC(HC({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??ew,_=await m.text(),v=QC(_),y=v?await g(_):null,ee={response:m,responseText:_,request:f,error:UC(HC({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(UC(HC({},ee),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=JC(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Y(e,UC(HC({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new WC(m.status,m.statusText,v?y:_);return{data:null,error:UC(HC({},y),{status:m.status,statusText:m.statusText})}},vw=new Set([301,302,303,307,308]);function yw(e){return e.type===`opaqueredirect`||vw.has(e.status)}function bw(e){return new b(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}var xw={redirect:`manual`};async function Sw(e,t){let n=!1,r=t?.onError,i=await Y(e,{...t,...xw,async onError(e){yw(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?bw(e):t});if(n)throw bw(e);return i}function Cw(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function ww(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function Tw(e,t){t&&e.set(`client_id`,t)}function Ew(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function Dw(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function Ow({body:e,options:t,clientId:n,requireClientSecret:r}){r&&Ew(`client_secret_post`,t),t.clientSecret&&(Dw(`client_secret_post`,n),Tw(e,n),e.set(`client_secret`,t.clientSecret))}function kw({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);Ew(`client_secret_basic`,t),Dw(`client_secret_basic`,n),e.authorization=MC(n,t.clientSecret)}function Aw(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function jw({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){Aw(e);let s=EC(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);ww(`private_key_jwt`,n,e),Tw(e,s);return}let c=a??Cw(n,o);if(c.method===`private_key_jwt`){if(ww(c.method,n,e),Dw(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await PC({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});Tw(e,s);for(let[n,r]of Object.entries(t))e.set(n,r);return}if(c.method===`none`){if(ww(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);Dw(c.method,s),Tw(e,s);return}if(c.method===`client_secret_basic`){kw({headers:t,options:n,clientId:s,body:e});return}Ow({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}var Mw=new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function Nw({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=Fw({refreshToken:e,options:t,extraParams:a,resource:o});return await jw({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function Pw(e,t){if(t)for(let[n,r]of Object.entries(t))Mw.has(n)||e.set(n,r)}function Fw({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&Pw(i,n),{body:i,headers:a}}async function Iw({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await Nw({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await Sw(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:CC(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date(new Date().getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date(new Date().getTime()+l.refresh_token_expires_in*1e3)),d}async function Lw({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=Rw({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await jw({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function Rw({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function zw({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await Lw({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await Sw(i,{method:`POST`,body:d,headers:f});if(m)throw m;return wC(p)}async function Bw(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Vw(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await Bw(t):!1}function Hw(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function Uw(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;if(!a)return!1;if(`verify`in a)return await a.verify(t,n,r);if(t.split(`.`).length!==3)return a.allowOpaqueToken===!0;let{alg:o}=hl(t),{payload:s}=await zc(t,a.jwks,{issuer:a.issuer,audience:a.audience,algorithms:a.algorithms??(o?[o]:void 0),maxTokenAge:a.maxTokenAge});return!(n&&!await Vw(s.nonce,n,a.nonceComparison)||a.verifyClaims&&!a.verifyClaims(s))}catch{return!1}}var Ww=e=>{let t=`https://appleid.apple.com/auth/token`;return{id:`apple`,name:`Apple`,accountSubject:({profile:e})=>e.sub,accountIssuer:`https://appleid.apple.com`,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i,codeVerifier:a}){if(!EC(e.clientId)||!e.clientSecret)throw g.error(`Client ID and client secret are required for Apple. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`name`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await J({id:`apple`,options:e,authorizationEndpoint:`https://appleid.apple.com/auth/authorize`,scopes:o,state:t,redirectURI:r,codeVerifier:a,responseMode:`form_post`,responseType:`code id_token`,additionalParams:i})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>Gw(e.kid),issuer:`https://appleid.apple.com`,audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:`1h`,nonceComparison:`exact-or-sha256`},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gl(t.idToken);if(!n)return null;let r;r=t.user?.name?`${t.user.name.firstName||``} ${t.user.name.lastName||``}`.trim():n.name||``;let i=typeof n.email_verified==`boolean`?n.email_verified:n.email_verified===`true`,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},Gw=async e=>{let{data:t}=await Y(`https://appleid.apple.com/auth/keys`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await ml(n,n.alg)},Kw=e=>{let t=`https://auth.atlassian.com/oauth/token`;return{id:`atlassian`,name:`Atlassian`,accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw g.error(`Client Id and Secret are required for Atlassian`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new b(`codeVerifier is required for Atlassian`);let o=e.disableDefaultScope?[]:[`read:jira-user`,`offline_access`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`atlassian`,options:e,authorizationEndpoint:`https://auth.atlassian.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:{...a??{},audience:`api.atlassian.com`},prompt:e.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:n}=await Y(`https://api.atlassian.com/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}catch(e){return g.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},qw=e=>{if(!e.domain||!e.region||!e.userPoolId)throw g.error(`Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options.`),new b(`DOMAIN_AND_REGION_REQUIRED`);let t=e.domain.replace(/^https?:\/\//,``),n=`https://${t}/oauth2/authorize`,r=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:`cognito`,name:`Cognito`,accountSubject:({profile:e})=>e.sub,accountIssuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!EC(e.clientId))throw g.error(`ClientId is required for Amazon Cognito. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(e.requireClientSecret&&!e.clientSecret)throw g.error(`Client Secret is required when requireClientSecret is true. Make sure to provide it in the options.`),new b(`CLIENT_SECRET_REQUIRED`);let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];e.scope&&s.push(...e.scope),r&&s.push(...r);let c=await J({id:`cognito`,options:{...e},authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...o??{}}}),l=c.searchParams.get(`scope`);if(l){c.searchParams.delete(`scope`);let e=encodeURIComponent(l),t=c.toString(),n=t.includes(`?`)?`&`:`?`;return new URL(`${t}${n}scope=${e}`)}return c},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>zw({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>Jw(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=gl(t.idToken);if(!n)return null;let r=n.name||n.given_name||n.username||``,i={...n,name:r},a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:i}}catch(e){g.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await Y(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n){let t=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.given_name||n.username||``,email:n.email,image:n.picture,emailVerified:n.email_verified,...t},data:n}}}catch(e){g.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},Jw=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await Y(r);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await ml(n,n.alg)}catch(e){throw g.error(`Failed to fetch Cognito public key:`,e),e}},Yw=e=>{let t=`https://discord.com/api/oauth2/token`;return{id:`discord`,name:`Discord`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identify`,`email`];n&&a.push(...n),e.scope&&a.push(...e.scope);let o=a.includes(`bot`);return J({id:`discord`,options:e,authorizationEndpoint:`https://discord.com/api/oauth2/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`none`,additionalParams:{...o&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...i??{}}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://discord.com/api/users/@me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator===`0`?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let e=n.avatar.startsWith(`a_`)?`gif`:`png`;n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${e}`}let i=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||``,email:n.email,emailVerified:n.verified,image:n.image_url,...i},data:n}},options:e}},Xw=e=>{let t=`https://api.dropboxapi.com/oauth2/token`;return{id:`dropbox`,name:`Dropbox`,accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`account_info.read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await J({id:`dropbox`,options:e,authorizationEndpoint:`https://www.dropbox.com/oauth2/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>await zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.dropboxapi.com/2/users/get_current_account`,{method:`POST`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}};async function Zw(e,t){let n=EC(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await Y(`https://graph.facebook.com/debug_token`,{query:{input_token:e,access_token:`${n}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return o!==!0||!s||!r.includes(s)||!c?null:c}var Qw=e=>({id:`facebook`,name:`Facebook`,accountSubject:({profile:e})=>`sub`in e?e.sub:e.id,accountIssuer:`https://www.facebook.com`,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a}){if(!EC(e.clientId)||!e.clientSecret)throw g.error(`Client ID and client secret are required for Facebook. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`public_profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await J({id:`facebook`,options:e,authorizationEndpoint:`https://www.facebook.com/v24.0/dialog/oauth`,scopes:o,state:t,redirectURI:r,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...a??{}}})},validateAuthorizationCode:async({code:t,redirectURI:n})=>zw({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:pl(new URL(`https://limited.facebook.com/.well-known/oauth/openid/jwks/`)),issuer:`https://www.facebook.com`,audience:e.clientId,algorithms:[`RS256`],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&t.idToken.split(`.`).length===3){let n=gl(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}let n=t.accessToken;if(!n)return null;let r=await Zw(n,e);if(!r)return null;let{data:i,error:a}=await Y(`https://graph.facebook.com/me?fields=`+[`id`,`name`,`email`,`picture`,...e?.fields||[]].join(`,`),{auth:{type:`Bearer`,token:n}});if(a||i.id!==r)return null;let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),$w=e=>{let t=`https://api.figma.com/v1/oauth/token`;return{id:`figma`,name:`Figma`,accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw g.error(`Client Id and Client Secret are required for Figma. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new b(`codeVerifier is required for Figma`);let o=e.disableDefaultScope?[]:[`current_user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await J({id:`figma`,options:e,authorizationEndpoint:`https://www.figma.com/oauth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await Y(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return g.error(`Failed to fetch user from Figma`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...r},data:n}}catch(e){return g.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},eT=e=>{let t=`https://github.com/login/oauth/access_token`;return{id:`github`,name:`GitHub`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`read:user`,`user:email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),J({id:`github`,options:e,authorizationEndpoint:`https://github.com/login/oauth/authorize`,scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:r,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>{let{body:a,headers:o}=await Lw({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await Y(t,{method:`POST`,body:a,headers:o});return c?(g.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(g.error(`GitHub OAuth token exchange failed:`,s),null):wC(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await Y(`https://api.github.com/user/emails`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});!n.email&&i&&(n.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===n.email)?.verified??!1,o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||``,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},tT=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),nT=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:tT(`${t}/oauth/authorize`),tokenEndpoint:tT(`${t}/oauth/token`),userinfoEndpoint:tT(`${t}/api/v4/user`)}},rT=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=nT(e.issuer),i=`gitlab`;return{id:i,name:`Gitlab`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:n,scopes:r,codeVerifier:a,loginHint:o,redirectURI:s,additionalParams:c})=>{let l=e.disableDefaultScope?[]:[`read_user`];return e.scope&&l.push(...e.scope),r&&l.push(...r),await J({id:i,options:e,authorizationEndpoint:t,scopes:l,state:n,redirectURI:s,codeVerifier:a,loginHint:o,additionalParams:c})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>zw({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:i}=await Y(r,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||n.state!==`active`||n.locked)return null;let a=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.username??``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...a},data:n}},options:e}},iT=`1h`,aT=`RS256`,oT=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,sT=e=>({id:`google`,name:`Google`,accountSubject:({profile:e})=>e.sub,accountIssuer:`https://accounts.google.com`,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,display:o,additionalParams:s}){if(!EC(e.clientId)||!e.clientSecret)throw g.error(`Client Id and Client Secret is required for Google. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new b(`codeVerifier is required for Google`);let c=e.disableDefaultScope?[]:[`email`,`profile`,`openid`];return e.scope&&c.push(...e.scope),n&&c.push(...n),await J({id:`google`,options:e,authorizationEndpoint:`https://accounts.google.com/o/oauth2/v2/auth`,scopes:c,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:`true`},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>zw({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>cT(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,maxTokenAge:iT,verifyClaims:e.hd?t=>oT(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gl(t.idToken);if(!oT(e.hd,n.hd))return g.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??`<missing>`}" does not satisfy the configured "hd" option "${e.hd}".`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...r},data:n}},options:e}),cT=async e=>{let[t]=await lT(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},lT=async e=>{let{data:t}=await Y(`https://www.googleapis.com/oauth2/v3/certs`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=e?t.keys.filter(t=>t.kid===e):t.keys;if(!n.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(n.map(e=>ml(e,aT)))},uT=e=>{let t=`https://huggingface.co/oauth/token`;return{id:`huggingface`,name:`Hugging Face`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`huggingface`,options:e,authorizationEndpoint:`https://huggingface.co/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://huggingface.co/oauth/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},dT=e=>{let t=`https://kauth.kakao.com/oauth/token`;return{id:`kakao`,name:`Kakao`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`account_email`,`profile_image`,`profile_nickname`];return e.scope&&a.push(...e.scope),n&&a.push(...n),J({id:`kakao`,options:e,authorizationEndpoint:`https://kauth.kakao.com/oauth/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://kapi.kakao.com/v2/user/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n),a=n.kakao_account||{},o=a.profile||{};return{user:{name:o.nickname||a.name||``,email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:n}},options:e}},fT=e=>({id:`kick`,name:`Kick`,accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,codeVerifier:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`kick`,redirectURI:r,options:e,authorizationEndpoint:`https://id.kick.com/oauth/authorize`,scopes:o,codeVerifier:i,state:t,additionalParams:a})},async validateAuthorizationCode({code:t,redirectURI:n,codeVerifier:r}){return zw({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:`https://id.kick.com/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.kick.com/public/v1/users`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=n.data[0],a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),pT=e=>{let t=`https://api.line.me/oauth2/v2.1/token`;return{id:`line`,name:`LINE`,accountSubject:({profile:e})=>e.sub,accountIssuer:`https://access.line.me`,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),await J({id:`line`,options:e,authorizationEndpoint:`https://access.line.me/oauth2/v2.1/authorize`,scopes:s,state:t,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,n)=>{let r=new URLSearchParams;r.set(`id_token`,t),r.set(`client_id`,e.clientId),n&&r.set(`nonce`,n);let{data:i,error:a}=await Y(`https://api.line.me/oauth2/v2.1/verify`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:r});return!(a||!i||i.aud!==e.clientId||i.nonce&&i.nonce!==n)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=null;if(t.idToken)try{n=gl(t.idToken)}catch{}if(!n){let{data:e}=await Y(`https://api.line.me/oauth2/v2.1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});n=e||null}if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}},options:e}},mT=e=>{let t=`https://api.linear.app/oauth/token`;return{id:`linear`,name:`Linear`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`linear`,options:e,authorizationEndpoint:`https://linear.app/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.linear.app/graphql`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
|
|
142
|
-
query {
|
|
143
|
-
viewer {
|
|
144
|
-
id
|
|
145
|
-
name
|
|
146
|
-
email
|
|
147
|
-
avatarUrl
|
|
148
|
-
active
|
|
149
|
-
createdAt
|
|
150
|
-
updatedAt
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
`})});if(r||!n?.data?.viewer)return null;let i=n.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{name:n.data.viewer.name,email:n.data.viewer.email,image:n.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},hT=e=>{let t=`https://www.linkedin.com/oauth/v2/accessToken`;return{id:`linkedin`,name:`Linkedin`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`profile`,`email`,`openid`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await J({id:`linkedin`,options:e,authorizationEndpoint:`https://www.linkedin.com/oauth/v2/authorization`,scopes:o,state:t,loginHint:i,redirectURI:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>await zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.linkedin.com/v2/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,emailVerified:n.email_verified??!1,image:n.picture,...i},data:n}},options:e}},gT=`9188040d-6c67-4c5b-b112-36a304b66dad`,_T=e=>{let t=e.tenantId||`common`,n=e.authority||`https://login.microsoftonline.com`;for(;n.endsWith(`/`);)n=n.slice(0,-1);let r=`${n}/${t}/oauth2/v2.0/authorize`,i=`${n}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new b(`Microsoft Entra ID clientAssertion cannot be combined with clientSecret`);let a=e.clientAssertion?{method:`private_key_jwt`,getClientAssertion:e.clientAssertion}:void 0;return{id:`microsoft`,name:`Microsoft EntraID`,accountSubject:({profile:e})=>e.oid,accountIssuer:({profile:e})=>e.iss,createAuthorizationURL(t){if(!EC(e.clientId))throw g.error(`Client Id is required for Microsoft Entra ID. Make sure to provide it in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),J({id:`microsoft`,options:e,authorizationEndpoint:r,state:t.state,codeVerifier:t.codeVerifier,scopes:n,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode({code:t,codeVerifier:n,redirectURI:r}){return zw({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:i,tokenEndpointAuth:a})},idToken:{jwks:e=>vT(e.kid,t,n),audience:e.clientId,maxTokenAge:`1h`,issuer:t!==`common`&&t!==`organizations`&&t!==`consumers`?`${n}/${t}/v2.0`:void 0,verifyClaims:e=>{let r=e.tid;return!(typeof r!=`string`||e.iss!==`${n}/${r}/v2.0`||t===`organizations`&&r===gT||t===`consumers`&&r!==gT)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gl(t.idToken);if(typeof n.oid!=`string`||n.oid.trim().length===0)return g.error(`Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier.`),null;let r=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await Y(`https://graph.microsoft.com/v1.0/me/photos/${r}x${r}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer();n.picture=`data:image/jpeg;base64, ${Yl.encode(t)}`}catch(e){g.error(e&&typeof e==`object`&&`name`in e?e.name:``,e)}}});let i=await e.mapProfileToUser?.(n),a=n.email_verified===void 0?!!(n.email&&(n.verified_primary_email?.includes(n.email)||n.verified_secondary_email?.includes(n.email))):n.email_verified;return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:a,...i},data:n}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),Iw({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:n.join(` `)},tokenEndpoint:i,tokenEndpointAuth:a})},options:e}},vT=async(e,t,n)=>{let{data:r}=await Y(`${n}/${t}/discovery/v2.0/keys`);if(!r?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let i=r.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await ml(i,i.alg)},yT=e=>{let t=`https://nid.naver.com/oauth2.0/token`;return{id:`naver`,name:`Naver`,accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`profile`,`email`];return e.scope&&a.push(...e.scope),n&&a.push(...n),J({id:`naver`,options:e,authorizationEndpoint:`https://nid.naver.com/oauth2.0/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://openapi.naver.com/v1/nid/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n||n.resultcode!==`00`)return null;let i=await e.mapProfileToUser?.(n),a=n.response||{};return{user:{name:a.name||a.nickname||``,email:a.email,image:a.profile_image,emailVerified:!1,...i},data:n}},options:e}},bT=e=>{let t=`https://api.notion.com/v1/oauth/token`;return{id:`notion`,name:`Notion`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=(e.disableDefaultScope,[]);return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`notion`,options:e,authorizationEndpoint:`https://api.notion.com/v1/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:{...a??{},owner:`user`}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.notion.com/v1/users/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":`2022-06-28`}});if(r||!n)return null;let i=n.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{name:i.name||``,email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},xT=e=>{let t=e.issuer||`https://idp.paybin.io`,n=`${t}/oauth2/authorize`,r=`${t}/oauth2/token`;return{id:`paybin`,name:`Paybin`,accountSubject:({profile:e})=>e.sub,accountIssuer:t,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw g.error(`Client Id and Client Secret is required for Paybin. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new b(`codeVerifier is required for Paybin`);let c=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&c.push(...e.scope),r&&c.push(...r),await J({id:`paybin`,options:e,authorizationEndpoint:n,scopes:c,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>zw({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gl(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified||!1,...r},data:n}},options:e}},ST=e=>{let t=(e.environment||`sandbox`)===`sandbox`,n=t?`https://www.sandbox.paypal.com/signin/authorize`:`https://www.paypal.com/signin/authorize`,r=t?`https://api-m.sandbox.paypal.com/v1/oauth2/token`:`https://api-m.paypal.com/v1/oauth2/token`,i=t?`https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo`:`https://api-m.paypal.com/v1/identity/oauth2/userinfo`;return{id:`paypal`,name:`PayPal`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw g.error(`Client Id and Client Secret is required for PayPal. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);return await J({id:`paypal`,options:e,authorizationEndpoint:n,scopes:[],state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:t,redirectURI:n})=>{let i=Yl.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await Y(r,{method:`POST`,headers:{Authorization:`Basic ${i}`,Accept:`application/json`,"Accept-Language":`en_US`,"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`authorization_code`,code:t,redirect_uri:n}).toString()});if(!e.data)throw new b(`FAILED_TO_GET_ACCESS_TOKEN`);let a=e.data;return{accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?new Date(Date.now()+a.expires_in*1e3):void 0,idToken:a.id_token}}catch(e){throw g.error(`PayPal token exchange failed:`,e),new b(`FAILED_TO_GET_ACCESS_TOKEN`)}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let n=Yl.encode(`${e.clientId}:${e.clientSecret}`);try{let e=await Y(r,{method:`POST`,headers:{Authorization:`Basic ${n}`,Accept:`application/json`,"Accept-Language":`en_US`,"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`refresh_token`,refresh_token:t}).toString()});if(!e.data)throw new b(`FAILED_TO_REFRESH_ACCESS_TOKEN`);let i=e.data;return{accessToken:i.access_token,refreshToken:i.refresh_token,accessTokenExpiresAt:i.expires_in?new Date(Date.now()+i.expires_in*1e3):void 0}}catch(e){throw g.error(`PayPal token refresh failed:`,e),new b(`FAILED_TO_REFRESH_ACCESS_TOKEN`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return g.error(`Access token is required to fetch PayPal user info`),null;try{let n=await Y(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:`application/json`}});if(!n.data)return g.error(`Failed to fetch user info from PayPal`),null;let r=n.data;if(t.idToken){let e;try{e=gl(t.idToken).sub}catch(e){return g.error(`Failed to decode PayPal ID token:`,e),null}let n=r.sub??r.user_id;if(!e||n!==e)return g.error(`PayPal user info subject does not match ID token subject`),null}let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:r}}catch(e){return g.error(`Failed to fetch user info from PayPal:`,e),null}},options:e}},CT=e=>{let t=`https://api.polar.sh/v1/oauth2/token`;return{id:`polar`,name:`Polar`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`polar`,options:e,authorizationEndpoint:`https://polar.sh/oauth2/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.polar.sh/v1/oauth2/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.public_name||n.username||``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},wT=`https://backboard.railway.com/oauth/auth`,TT=`https://backboard.railway.com/oauth/token`,ET=`https://backboard.railway.com/oauth/me`,DT={apple:Ww,atlassian:Kw,cognito:qw,discord:Yw,facebook:Qw,figma:$w,github:eT,microsoft:_T,google:sT,huggingface:uT,slack:e=>{let t=`https://slack.com/api/openid.connect.token`;return{id:`slack`,name:`Slack`,accountSubject:({profile:e})=>e[`https://slack.com/user_id`],createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return n&&a.push(...n),e.scope&&a.push(...e.scope),J({id:`slack`,options:e,authorizationEndpoint:`https://slack.com/openid/connect/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://slack.com/api/openid.connect.userInfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,emailVerified:n.email_verified,image:n.picture||n[`https://slack.com/user_image_512`],...i},data:n}},options:e}},spotify:e=>{let t=`https://accounts.spotify.com/api/token`;return{id:`spotify`,name:`Spotify`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user-read-email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`spotify`,options:e,authorizationEndpoint:`https://accounts.spotify.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.spotify.com/v1/me`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.display_name,email:n.email,image:n.images[0]?.url,emailVerified:!1,...i},data:n}},options:e}},twitch:e=>{let t=`https://id.twitch.tv/oauth2/token`;return{id:`twitch`,name:`Twitch`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user:read:email`,`openid`];return e.scope&&a.push(...e.scope),n&&a.push(...n),J({id:`twitch`,redirectURI:r,options:e,authorizationEndpoint:`https://id.twitch.tv/oauth2/authorize`,scopes:a,state:t,claims:e.claims||[`email`,`email_verified`,`preferred_username`,`picture`],additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.idToken;if(!n)return g.error(`No idToken found in token`),null;let r=gl(n),i=await e.mapProfileToUser?.(r);return{user:{name:r.preferred_username,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}},twitter:e=>{let t=`https://api.x.com/2/oauth2/token`;return{id:`twitter`,name:`Twitter`,accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let n=e.disableDefaultScope?[]:[`users.read`,`tweet.read`,`offline.access`,`users.email`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),J({id:`twitter`,options:e,authorizationEndpoint:`https://x.com/i/oauth2/authorize`,scopes:n,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>zw({code:n,codeVerifier:r,authentication:`basic`,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:`basic`,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.x.com/2/users/me?user.fields=profile_image_url`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i,error:a}=await Y(`https://api.x.com/2/users/me?user.fields=confirmed_email`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(n.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(n);return{user:{name:n.data.name,email:n.data.email||n.data.username||null,image:n.data.profile_image_url,emailVerified:o,...s},data:n}},options:e}},dropbox:Xw,kick:fT,linear:mT,linkedin:hT,gitlab:rT,tiktok:e=>{let t=`https://open.tiktokapis.com/v2/oauth/token/`;return{id:`tiktok`,name:`TikTok`,accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user.info.profile`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://www.tiktok.com/v2/auth/authorize`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`client_key`,e.clientKey),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),i)for(let[e,t]of Object.entries(i))kC.has(e)||e!==`client_key`&&o.searchParams.set(e,t);return o},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:e.redirectURI||r,options:{clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`post`,extraParams:{client_key:e.clientKey}}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://open.tiktokapis.com/v2/user/info/?fields=${[`open_id`,`avatar_large_url`,`display_name`,`username`].join(`,`)}`,{headers:{authorization:`Bearer ${t.accessToken}`}});return r?null:{user:{email:n.data.user.email||n.data.user.username,name:n.data.user.display_name||n.data.user.username||``,image:n.data.user.avatar_large_url,emailVerified:!1},data:n}},options:e}},reddit:e=>({id:`reddit`,name:`Reddit`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identity`];return e.scope&&a.push(...e.scope),n&&a.push(...n),J({id:`reddit`,options:e,authorizationEndpoint:`https://www.reddit.com/api/v1/authorize`,scopes:a,state:t,redirectURI:r,duration:e.duration,additionalParams:i})},validateAuthorizationCode:async({code:t,redirectURI:n})=>{let r=new URLSearchParams({grant_type:`authorization_code`,code:t,redirect_uri:e.redirectURI||n}),{data:i,error:a}=await Y(`https://www.reddit.com/api/v1/access_token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`,accept:`text/plain`,"user-agent":`better-auth`,Authorization:`Basic ${Yl.encode(`${e.clientId}:${e.clientSecret}`)}`},body:r.toString()});if(a)throw a;return wC(i)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:`basic`,tokenEndpoint:`https://www.reddit.com/api/v1/access_token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://oauth.reddit.com/api/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});if(r)return null;let i=await e.mapProfileToUser?.(n),a=i?.email||`${n.id}@reddit.invalid`;return{user:{name:n.name,image:n.icon_img?.split(`?`)[0],...i,email:a,emailVerified:i?.emailVerified??!1},data:n}},options:e}),roblox:e=>{let t=`https://apis.roblox.com/oauth/v1/token`;return{id:`roblox`,name:`Roblox`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`];return e.scope&&a.push(...e.scope),n&&a.push(...n),J({id:`roblox`,options:e,authorizationEndpoint:`https://apis.roblox.com/oauth/v1/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`select_account consent`,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>zw({code:n,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t,authentication:`post`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://apis.roblox.com/oauth/v1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.nickname||n.preferred_username||``,image:n.picture,email:n.preferred_username||null,emailVerified:!1,...i},data:{...n}}},options:e}},salesforce:e=>{let t=(e.environment??`production`)===`sandbox`,n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?`https://test.salesforce.com/services/oauth2/authorize`:`https://login.salesforce.com/services/oauth2/authorize`,r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?`https://test.salesforce.com/services/oauth2/token`:`https://login.salesforce.com/services/oauth2/token`,i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?`https://test.salesforce.com/services/oauth2/userinfo`:`https://login.salesforce.com/services/oauth2/userinfo`;return{id:`salesforce`,name:`Salesforce`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw g.error(`Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options.`),new b(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new b(`codeVerifier is required for Salesforce`);let s=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&s.push(...e.scope),r&&s.push(...r),J({id:`salesforce`,options:e,authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:e.redirectURI||a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>zw({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await Y(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return g.error(`Failed to fetch user info from Salesforce`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.photos?.picture||n.photos?.thumbnail,emailVerified:n.email_verified??!1,...r},data:n}}catch(e){return g.error(`Failed to fetch user info from Salesforce:`,e),null}},options:e}},vk:e=>{let t=`https://id.vk.com/oauth2/auth`;return{id:`vk`,name:`VK`,accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`email`,`phone`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`vk`,options:e,authorizationEndpoint:`https://id.vk.com/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i,deviceId:a})=>zw({code:n,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>Iw({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let{data:n,error:r}=await Y(`https://id.vk.com/oauth2/user_info`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString()});if(r)return null;let i=await e.mapProfileToUser?.(n);return!n.user.email&&!i?.email?null:{user:{first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...i},data:n}},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:`zoom`,name:`Zoom`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:n,codeVerifier:r,additionalParams:i})=>J({id:`zoom`,options:t,authorizationEndpoint:`https://zoom.us/oauth/authorize`,state:e,redirectURI:n,codeVerifier:t.pkce?r:void 0,additionalParams:i}),validateAuthorizationCode:async({code:e,redirectURI:n,codeVerifier:r})=>zw({code:e,redirectURI:t.redirectURI||n,codeVerifier:r,options:t,tokenEndpoint:`https://zoom.us/oauth/token`,authentication:`post`}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>Iw({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:`https://zoom.us/oauth/token`}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:n,error:r}=await Y(`https://api.zoom.us/v2/users/me`,{headers:{authorization:`Bearer ${e.accessToken}`}});if(r)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.display_name,image:n.pic_url,email:n.email,emailVerified:!!n.verified,...i},data:{...n}}}}},notion:bT,kakao:dT,naver:yT,line:pT,paybin:xT,paypal:ST,polar:CT,railway:e=>({id:`railway`,name:`Railway`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),J({id:`railway`,options:e,authorizationEndpoint:wT,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>zw({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:TT,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>Iw({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:TT,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(ET,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:e}),vercel:e=>({id:`vercel`,name:`Vercel`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!r)throw new b(`codeVerifier is required for Vercel`);let o;return(e.scope!==void 0||n!==void 0)&&(o=[],e.scope&&o.push(...e.scope),n&&o.push(...n)),J({id:`vercel`,options:e,authorizationEndpoint:`https://vercel.com/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>zw({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://api.vercel.com/login/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await Y(`https://api.vercel.com/login/oauth/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}),wechat:e=>({id:`wechat`,name:`WeChat`,accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`snsapi_login`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://open.weixin.qq.com/connect/qrconnect`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`appid`,e.clientId),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),o.searchParams.set(`lang`,e.lang||`cn`),i)for(let[e,t]of Object.entries(i))kC.has(e)||e!==`appid`&&o.searchParams.set(e,t);return o.hash=`wechat_redirect`,o},validateAuthorizationCode:async({code:t})=>{let{data:n,error:r}=await Y(`https://api.weixin.qq.com/sns/oauth2/access_token?`+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:`authorization_code`}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`),openid:n.openid,unionid:n.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:n,error:r}=await Y(`https://api.weixin.qq.com/sns/oauth2/refresh_token?`+new URLSearchParams({appid:e.clientId,grant_type:`refresh_token`,refresh_token:t}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.openid;if(!n)return null;let{data:r,error:i}=await Y(`https://api.weixin.qq.com/sns/userinfo?`+new URLSearchParams({access_token:t.accessToken||``,openid:n,lang:`zh_CN`}).toString(),{method:`GET`});if(i||!r||r.errcode)return null;let a=await e.mapProfileToUser?.(r);return{user:{name:r.nickname,email:r.email||`${r.unionid||r.openid||n}@wechat.invalid`,image:r.headimgurl,emailVerified:!1,...a},data:r}},options:e})},OT=N_(Object.keys(DT)).or(K());function kT(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}var AT=q(`/list-accounts`,{method:`GET`,use:[yS],metadata:{openapi:{operationId:`listUserAccounts`,description:`List all accounts linked to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},createdAt:{type:`string`,format:`date-time`},updatedAt:{type:`string`,format:`date-time`},issuer:{type:`string`},accountId:{type:`string`},userId:{type:`string`},scopes:{type:`array`,items:{type:`string`}}},required:[`id`,`providerId`,`createdAt`,`updatedAt`,`issuer`,`accountId`,`userId`,`scopes`]}}}}}}}}},async e=>{let t=e.context.session,n=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(n.map(t=>{let{scope:n,...r}=yv(e.context.options,t);return{...r,scopes:kT(n)}}))}),jT=q(`/link-social`,{method:`POST`,requireHeaders:!0,body:C_({callbackURL:K().meta({description:`The URL to redirect to after the user has signed in`}).optional(),provider:OT,idToken:C_({token:K(),nonce:K().optional(),accessToken:K().optional(),refreshToken:K().optional()}).optional(),requestSignUp:d_().optional(),scopes:x_(K()).meta({description:`Additional scopes to request from the provider`}).optional(),errorCallbackURL:K().meta({description:`The URL to redirect to if there is an error during the link process`}).optional(),disableRedirect:d_().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),loginHint:K().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:AC,additionalData:j_(K(),p_()).optional()}),use:[yS],metadata:{openapi:{description:`Link a social account to the user`,operationId:`linkSocialAccount`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{url:{type:`string`,description:`The authorization URL to redirect the user to`},redirect:{type:`boolean`,description:`Indicates if the user should be redirected to the authorization URL`},status:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=e.context.session,n=await oC(e.context.socialProviders,{value:e.body.provider});if(!n)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,V.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!Hw(n))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,V.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await Uw(n,r,i,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.INVALID_TOKEN);let a=await n.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(Lb(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.USER_EMAIL_NOT_FOUND);let o=await uC(n,{idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},a.data),s=await e.context.internalAdapter.findAccountByKey(o);if(s?.userId===t.user.id){let i=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await pC(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await pC(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>t!==void 0));return await e.context.internalAdapter.updateAccount(s.id,i),await SC(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}if(s)throw E.from(`CONFLICT`,V.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(n.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - linking not allowed`,code:`LINKING_NOT_ALLOWED`});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - different emails not allowed`,code:`LINKING_DIFFERENT_EMAILS_NOT_ALLOWED`});try{await e.context.internalAdapter.createAccount({userId:t.user.id,providerId:n.id,...o,accessToken:await pC(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await pC(e.body.idToken.refreshToken,e.context)})}catch{throw E.from(`EXPECTATION_FAILED`,{message:`Account not linked - unable to create account`,code:`LINKING_FAILED`})}return await SC(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}let r=ux(n),i=await dx(e,{link:{userId:t.user.id,email:t.user.email},additionalData:e.body.additionalData,idTokenNonce:r}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:r,redirectURI:`${e.context.baseURL}${mC(n)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),MT=q(`/unlink-account`,{method:`POST`,body:C_({accountId:K().meta({description:`The Better Auth account ID to unlink`})}),use:[xS],metadata:{openapi:{description:`Unlink an account`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let{accountId:t}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(n.length===1&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw E.from(`BAD_REQUEST`,V.FAILED_TO_UNLINK_LAST_ACCOUNT);let r=n.find(e=>e.id===t);if(!r)throw E.from(`BAD_REQUEST`,V.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(r.id),e.json({status:!0})});async function NT(e,t){let n=await _S(e,{disableCookieCache:gS(e)});if(!n&&(e.request||e.headers))throw e.error(`UNAUTHORIZED`);let r=n?.user?.id||t;if(!r)throw E.from(`BAD_REQUEST`,{message:`Either userId or session is required`,code:`USER_ID_OR_SESSION_REQUIRED`});return r}var PT=D_([w_({accountId:K().meta({description:`The Better Auth account ID`}),userId:K().meta({description:`The user ID associated with the account`}).optional()}),w_({useAccountCookie:F_(!0).meta({description:`Select the current OAuth account from its signed cookie`}),userId:K().meta({description:`The user ID associated with the account`}).optional()})]);function FT(e,t,{resolvedUserId:n,selection:r}){return(!sd(e.context.options)||t.userId===n)&&(`accountId`in r?t.id===r.accountId:!0)}async function IT(e,{resolvedUserId:t,selection:n}){if(`accountId`in n){let r=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===n.accountId);if(r)return{account:r,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let r=await gb(e);if(r&&FT(e,r,{resolvedUserId:t,selection:n}))return{account:r,accountCookie:r}}throw E.from(`BAD_REQUEST`,V.ACCOUNT_NOT_FOUND)}async function LT(e,{resolvedUserId:t,selection:n,account:r}){let i=r??(await IT(e,{resolvedUserId:t,selection:n})).account;if(!FT(e,i,{resolvedUserId:t,selection:n}))throw E.from(`BAD_REQUEST`,V.ACCOUNT_NOT_FOUND);let a=await oC(e.context.socialProviders,{value:i.providerId});if(!a)throw E.from(`BAD_REQUEST`,{message:`Provider ${i.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});try{let t=null,n=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(i.refreshToken&&n&&a.refreshAccessToken){let n=await fC(i.refreshToken,e.context);t=await a.refreshAccessToken(n,e);let r={accessToken:await pC(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await pC(t.refreshToken,e.context):i.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:t?.idToken||i.idToken},o=null;i.id&&(o=await e.context.internalAdapter.updateAccount(i.id,r)),e.context.options.account?.storeAccountCookie&&await hb(e,{...i,...o??r})}let r=(()=>{if(t?.accessTokenExpiresAt)return typeof t.accessTokenExpiresAt==`string`?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt;if(i.accessTokenExpiresAt)return typeof i.accessTokenExpiresAt==`string`?new Date(i.accessTokenExpiresAt):i.accessTokenExpiresAt})();return{accessToken:t?.accessToken??await fC(i.accessToken??``,e.context),accessTokenExpiresAt:r,scopes:kT(i.scope),idToken:t?.idToken??i.idToken??void 0}}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to get a valid access token`,code:`FAILED_TO_GET_ACCESS_TOKEN`})}}var RT=q(`/get-access-token`,{method:`POST`,body:PT,metadata:{openapi:{description:`Get a valid access token, doing a refresh if needed`,responses:{200:{description:`A Valid access token`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,n=await LT(e,{resolvedUserId:await NT(e,t),selection:e.body});return e.json(n)}),zT=q(`/refresh-token`,{method:`POST`,body:PT,metadata:{openapi:{description:`Refresh the access token using a refresh token`,responses:{200:{description:`Access token refreshed successfully`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},refreshToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`},refreshTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,{account:n,accountCookie:r}=await IT(e,{resolvedUserId:await NT(e,t),selection:e.body}),i=await oC(e.context.socialProviders,{value:n.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});if(!i.refreshAccessToken)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} does not support token refreshing.`,code:`TOKEN_REFRESH_NOT_SUPPORTED`});let a=n.refreshToken??void 0;if(!a)throw E.from(`BAD_REQUEST`,{message:`Refresh token not found`,code:`REFRESH_TOKEN_NOT_FOUND`});try{let t=await fC(a,e.context),o=await i.refreshAccessToken(t,e),s=o.refreshToken?await pC(o.refreshToken,e.context):a,c=o.refreshTokenExpiresAt??n.refreshTokenExpiresAt,l={accessToken:await pC(o.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,idToken:o.idToken||n.idToken},u=null;n.id&&(u=await e.context.internalAdapter.updateAccount(n.id,l)),r?.id===n.id&&e.context.options.account?.storeAccountCookie&&await hb(e,{...r,...u??l});let d=u?.scope??n.scope;return e.json({accessToken:o.accessToken,refreshToken:o.refreshToken??t,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,scope:d,idToken:o.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to refresh access token`,code:`FAILED_TO_REFRESH_ACCESS_TOKEN`})}}),BT=q(`/account-info`,{method:`GET`,metadata:{openapi:{description:`Get the account info provided by the provider`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,properties:{name:{type:`string`},email:{type:`string`,nullable:!0},image:{type:`string`},emailVerified:{type:`boolean`}},required:[`emailVerified`]},account:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},issuer:{type:`string`},accountId:{type:`string`}},required:[`id`,`providerId`,`issuer`,`accountId`],additionalProperties:!1},data:{type:`object`,properties:{},additionalProperties:!0}},required:[`user`,`data`,`account`],additionalProperties:!1}}}}}}},query:PT},async e=>{let{userId:t}=e.query,n=await NT(e,t),{account:r}=await IT(e,{resolvedUserId:n,selection:e.query}),i=await oC(e.context.socialProviders,{value:r.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Account is not associated with a configured social provider.`,code:`PROVIDER_NOT_CONFIGURED`});let a=await LT(e,{resolvedUserId:n,selection:e.query,account:r});if(!a.accessToken)throw E.from(`BAD_REQUEST`,{message:`Access token not found`,code:`ACCESS_TOKEN_NOT_FOUND`});let o=await i.getUserInfo({...a,accessToken:a.accessToken});if(!o)throw E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_USER_INFO);return e.json({...o,account:{id:r.id,providerId:r.providerId,issuer:r.issuer,accountId:r.accountId}})}),VT=C_({code:K().optional(),error:K().optional(),device_id:K().optional(),error_description:K().optional(),state:K().optional(),user:K().optional(),iss:K().optional()}),HT=q(`/callback/:id`,{method:[`GET`,`POST`],operationId:`handleOAuthCallback`,body:VT.optional(),query:VT.optional(),metadata:{...px,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`]}},async e=>{let t,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if(e.method===`POST`){let t=e.body?VT.parse(e.body):{},n=e.query?VT.parse(e.query):{},r=VT.parse({...t,...n}),i=new URLSearchParams;for(let[e,t]of Object.entries(r))t!=null&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if(e.method===`GET`)t=VT.parse(e.query);else if(e.method===`POST`)t=VT.parse(e.body);else throw Error(`Unsupported method`)}catch(t){throw e.context.logger.error(`INVALID_CALLBACK_REQUEST`,t),e.redirect(`${n}?error=invalid_callback_request`)}let{code:r,error:i,state:a,error_description:o,device_id:s,user:c,iss:l}=t;if(a===void 0&&r){let t=await oC(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let n=ux(t),{state:r,codeVerifier:i}=await dx(e,{idTokenNonce:n}),a=await t.createAuthorizationURL({state:r,codeVerifier:i,idTokenNonce:n,redirectURI:`${e.context.baseURL}${mC(t)}`});throw e.redirect(a.toString())}}if(!a){e.context.logger.error(`State not found`,i);let t=`${n}${n.includes(`?`)?`&`:`?`}error=state_not_found`;throw e.redirect(t)}let{codeVerifier:u,callbackURL:d,link:f,errorURL:p,newUserURL:m,requestSignUp:h,idTokenNonce:g}=await fx(e);function _(t,r){let i=p??n,a=new URLSearchParams({error:t});r&&a.set(`error_description`,r);let o=`${i}${i.includes(`?`)?`&`:`?`}${a.toString()}`;throw e.redirect(o)}if(i&&_(i,o),!r)throw e.context.logger.warn(`Code not found`),_(Pb.NO_CODE);let v=await oC(e.context.socialProviders,{value:e.params.id});if(!v)throw e.context.logger.warn(`OAuth provider not found`,{providerId:e.params.id}),_(Pb.PROVIDER_NOT_FOUND);if(l&&v.issuer&&l!==v.issuer)throw e.context.logger.error(`OAuth issuer mismatch`,{expected:v.issuer,received:l}),_(Pb.ISSUER_MISMATCH);if(v.requiresIdTokenNonce&&!g)throw e.context.logger.error(`OAuth id_token nonce binding required but no expected nonce was found in state`,{providerId:v.id}),_(Pb.NONCE_BINDING_MISSING);let y;try{y=await v.validateAuthorizationCode({code:r,codeVerifier:u,deviceId:s,redirectURI:`${e.context.baseURL}${mC(v)}`})}catch(t){throw e.context.logger.error(``,t),_(Pb.INVALID_CODE)}if(!y)throw _(Pb.INVALID_CODE);let ee=c?j(c):null,te=await v.getUserInfo({...y,...g?{expectedIdTokenNonce:g}:{},user:ee??void 0});if(!te?.user)return e.context.logger.error(`Unable to get user info`),_(Pb.UNABLE_TO_GET_USER_INFO);let b=te.user,x=cC(te.data),S;try{S=await lC(v,y,te.data)}catch(t){return e.context.logger.error(`Unable to derive provider account identity`,{providerId:v.id,error:t}),_(Pb.UNABLE_TO_GET_USER_INFO)}let{accountId:C}=S;if(!d)throw e.context.logger.error(`No callback URL found`),_(Pb.NO_CALLBACK_URL);if(f){try{await DS(e,{user:{...b,id:f.userId,email:b.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:v.id,profile:x}}})}catch(e){throw mx(e)&&e.body?.code?_(e.body.code,e.body.message):e}if(!e.context.trustedProviders.includes(v.id)&&!b.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),_(Pb.UNABLE_TO_LINK_ACCOUNT);if(b.email?.toLowerCase()!==f.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return _(Pb.EMAIL_DOES_NOT_MATCH);let t=await e.context.internalAdapter.findAccountByKey(S);if(t){if(t.userId.toString()!==f.userId.toString())return _(Pb.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=TC(t.scope,y.scopes),r=Object.fromEntries(Object.entries({providerId:v.id,accessToken:await pC(y.accessToken,e.context),refreshToken:await pC(y.refreshToken,e.context),idToken:y.idToken,accessTokenExpiresAt:y.accessTokenExpiresAt,refreshTokenExpiresAt:y.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(t.id,r)}else if(!await e.context.internalAdapter.createAccount({userId:f.userId,providerId:v.id,...S,...y,accessToken:await pC(y.accessToken,e.context),refreshToken:await pC(y.refreshToken,e.context),scope:y.scopes?.join(`,`)}))return _(Pb.UNABLE_TO_LINK_ACCOUNT);await SC(e,f.userId,b);let n;try{n=d.toString()}catch{n=d}throw e.redirect(n)}if(!b.email)return e.context.logger.error(Lb(v.id)),_(Pb.EMAIL_NOT_FOUND);let w={providerId:v.id,...S,...y,scope:y.scopes?.join(`,`)},T;try{T=await bC(e,{userInfo:{...b,id:C,email:b.email,name:b.name||``},account:w,callbackURL:d,disableSignUp:v.disableImplicitSignUp&&!h||v.options?.disableSignUp,overrideUserInfo:v.options?.overrideUserInfoOnSignIn,source:{method:`oauth`,oauth:{providerId:v.id,profile:x}}})}catch(e){throw mx(e)&&e.body?.code&&_(e.body.code,e.body.message),e}if(T.error)return e.context.logger.error(T.error.split(` `).join(`_`)),_(T.error.split(` `).join(`_`));let{session:E,user:D}=T.data;await Tb(e,{session:E,user:D});let O;try{O=(T.isRegister&&m||d).toString()}catch{O=T.isRegister&&m||d}throw e.redirect(O)});function UT(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,`&`)}var WT=(e,t=`Unknown`,n=null)=>{let r=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
|
|
154
|
-
<html lang="en">
|
|
155
|
-
<head>
|
|
156
|
-
<meta charset="UTF-8" />
|
|
157
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
158
|
-
<title>Error</title>
|
|
159
|
-
<style>
|
|
160
|
-
* {
|
|
161
|
-
box-sizing: border-box;
|
|
162
|
-
}
|
|
163
|
-
body {
|
|
164
|
-
font-family: ${r?.font?.defaultFamily||`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`};
|
|
165
|
-
background: ${r?.colors?.background||`var(--background)`};
|
|
166
|
-
color: var(--foreground);
|
|
167
|
-
margin: 0;
|
|
168
|
-
}
|
|
169
|
-
:root,
|
|
170
|
-
:host {
|
|
171
|
-
--spacing: 0.25rem;
|
|
172
|
-
--container-md: 28rem;
|
|
173
|
-
--text-sm: ${r?.size?.textSm||`0.875rem`};
|
|
174
|
-
--text-sm--line-height: calc(1.25 / 0.875);
|
|
175
|
-
--text-2xl: ${r?.size?.text2xl||`1.5rem`};
|
|
176
|
-
--text-2xl--line-height: calc(2 / 1.5);
|
|
177
|
-
--text-4xl: ${r?.size?.text4xl||`2.25rem`};
|
|
178
|
-
--text-4xl--line-height: calc(2.5 / 2.25);
|
|
179
|
-
--text-6xl: ${r?.size?.text6xl||`3rem`};
|
|
180
|
-
--text-6xl--line-height: 1;
|
|
181
|
-
--font-weight-medium: 500;
|
|
182
|
-
--font-weight-semibold: 600;
|
|
183
|
-
--font-weight-bold: 700;
|
|
184
|
-
--default-transition-duration: 150ms;
|
|
185
|
-
--default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
|
186
|
-
--radius: ${r?.size?.radiusSm||`0.625rem`};
|
|
187
|
-
--default-mono-font-family: ${r?.font?.monoFamily||`var(--font-geist-mono)`};
|
|
188
|
-
--primary: ${r?.colors?.primary||`black`};
|
|
189
|
-
--primary-foreground: ${r?.colors?.primaryForeground||`white`};
|
|
190
|
-
--background: ${r?.colors?.background||`white`};
|
|
191
|
-
--foreground: ${r?.colors?.foreground||`oklch(0.271 0 0)`};
|
|
192
|
-
--border: ${r?.colors?.border||`oklch(0.89 0 0)`};
|
|
193
|
-
--destructive: ${r?.colors?.destructive||`oklch(0.55 0.15 25.723)`};
|
|
194
|
-
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.545 0 0)`};
|
|
195
|
-
--corner-border: ${r?.colors?.cornerBorder||`#404040`};
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
button, .btn {
|
|
199
|
-
cursor: pointer;
|
|
200
|
-
background: none;
|
|
201
|
-
border: none;
|
|
202
|
-
color: inherit;
|
|
203
|
-
font: inherit;
|
|
204
|
-
transition: all var(--default-transition-duration)
|
|
205
|
-
var(--default-transition-timing-function);
|
|
206
|
-
}
|
|
207
|
-
button:hover, .btn:hover {
|
|
208
|
-
opacity: 0.8;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
@media (prefers-color-scheme: dark) {
|
|
212
|
-
:root,
|
|
213
|
-
:host {
|
|
214
|
-
--primary: ${r?.colors?.primary||`white`};
|
|
215
|
-
--primary-foreground: ${r?.colors?.primaryForeground||`black`};
|
|
216
|
-
--background: ${r?.colors?.background||`oklch(0.15 0 0)`};
|
|
217
|
-
--foreground: ${r?.colors?.foreground||`oklch(0.98 0 0)`};
|
|
218
|
-
--border: ${r?.colors?.border||`oklch(0.27 0 0)`};
|
|
219
|
-
--destructive: ${r?.colors?.destructive||`oklch(0.65 0.15 25.723)`};
|
|
220
|
-
--muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.65 0 0)`};
|
|
221
|
-
--corner-border: ${r?.colors?.cornerBorder||`#a0a0a0`};
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
@media (max-width: 640px) {
|
|
225
|
-
:root, :host {
|
|
226
|
-
--text-6xl: 2.5rem;
|
|
227
|
-
--text-2xl: 1.25rem;
|
|
228
|
-
--text-sm: 0.8125rem;
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
@media (max-width: 480px) {
|
|
232
|
-
:root, :host {
|
|
233
|
-
--text-6xl: 2rem;
|
|
234
|
-
--text-2xl: 1.125rem;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
</style>
|
|
238
|
-
</head>
|
|
239
|
-
<body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
|
|
240
|
-
<div
|
|
241
|
-
style="
|
|
242
|
-
display: flex;
|
|
243
|
-
flex-direction: column;
|
|
244
|
-
align-items: center;
|
|
245
|
-
justify-content: center;
|
|
246
|
-
gap: 1.5rem;
|
|
247
|
-
position: relative;
|
|
248
|
-
width: 100%;
|
|
249
|
-
min-height: 100vh;
|
|
250
|
-
padding: 1rem;
|
|
251
|
-
"
|
|
252
|
-
>
|
|
253
|
-
${r?.disableBackgroundGrid?``:`
|
|
254
|
-
<div
|
|
255
|
-
style="
|
|
256
|
-
position: absolute;
|
|
257
|
-
inset: 0;
|
|
258
|
-
background-image: linear-gradient(to right, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px),
|
|
259
|
-
linear-gradient(to bottom, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px);
|
|
260
|
-
background-size: 40px 40px;
|
|
261
|
-
opacity: 0.6;
|
|
262
|
-
pointer-events: none;
|
|
263
|
-
width: 100vw;
|
|
264
|
-
height: 100vh;
|
|
265
|
-
"
|
|
266
|
-
></div>
|
|
267
|
-
<div
|
|
268
|
-
style="
|
|
269
|
-
position: absolute;
|
|
270
|
-
inset: 0;
|
|
271
|
-
display: flex;
|
|
272
|
-
align-items: center;
|
|
273
|
-
justify-content: center;
|
|
274
|
-
background: ${r?.colors?.background||`var(--background)`};
|
|
275
|
-
mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
276
|
-
-webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
|
|
277
|
-
pointer-events: none;
|
|
278
|
-
"
|
|
279
|
-
></div>
|
|
280
|
-
`}
|
|
281
|
-
|
|
282
|
-
<div
|
|
283
|
-
style="
|
|
284
|
-
position: relative;
|
|
285
|
-
z-index: 10;
|
|
286
|
-
border: 2px solid var(--border);
|
|
287
|
-
background: ${r?.colors?.cardBackground||`var(--background)`};
|
|
288
|
-
padding: 1.5rem;
|
|
289
|
-
max-width: 42rem;
|
|
290
|
-
width: 100%;
|
|
291
|
-
"
|
|
292
|
-
>
|
|
293
|
-
${r?.disableCornerDecorations?``:`
|
|
294
|
-
<!-- Corner decorations -->
|
|
295
|
-
<div
|
|
296
|
-
style="
|
|
297
|
-
position: absolute;
|
|
298
|
-
top: -2px;
|
|
299
|
-
left: -2px;
|
|
300
|
-
width: 2rem;
|
|
301
|
-
height: 2rem;
|
|
302
|
-
border-top: 4px solid var(--corner-border);
|
|
303
|
-
border-left: 4px solid var(--corner-border);
|
|
304
|
-
"
|
|
305
|
-
></div>
|
|
306
|
-
<div
|
|
307
|
-
style="
|
|
308
|
-
position: absolute;
|
|
309
|
-
top: -2px;
|
|
310
|
-
right: -2px;
|
|
311
|
-
width: 2rem;
|
|
312
|
-
height: 2rem;
|
|
313
|
-
border-top: 4px solid var(--corner-border);
|
|
314
|
-
border-right: 4px solid var(--corner-border);
|
|
315
|
-
"
|
|
316
|
-
></div>
|
|
317
|
-
|
|
318
|
-
<div
|
|
319
|
-
style="
|
|
320
|
-
position: absolute;
|
|
321
|
-
bottom: -2px;
|
|
322
|
-
left: -2px;
|
|
323
|
-
width: 2rem;
|
|
324
|
-
height: 2rem;
|
|
325
|
-
border-bottom: 4px solid var(--corner-border);
|
|
326
|
-
border-left: 4px solid var(--corner-border);
|
|
327
|
-
"
|
|
328
|
-
></div>
|
|
329
|
-
<div
|
|
330
|
-
style="
|
|
331
|
-
position: absolute;
|
|
332
|
-
bottom: -2px;
|
|
333
|
-
right: -2px;
|
|
334
|
-
width: 2rem;
|
|
335
|
-
height: 2rem;
|
|
336
|
-
border-bottom: 4px solid var(--corner-border);
|
|
337
|
-
border-right: 4px solid var(--corner-border);
|
|
338
|
-
"
|
|
339
|
-
></div>`}
|
|
340
|
-
|
|
341
|
-
<div style="text-align: center; margin-bottom: 1.5rem;">
|
|
342
|
-
<div style="margin-bottom: 1.5rem;">
|
|
343
|
-
<div
|
|
344
|
-
style="
|
|
345
|
-
display: inline-block;
|
|
346
|
-
border: 2px solid ${r?.disableTitleBorder?`transparent`:r?.colors?.titleBorder||`var(--destructive)`};
|
|
347
|
-
padding: 0.375rem 1rem;
|
|
348
|
-
"
|
|
349
|
-
>
|
|
350
|
-
<h1
|
|
351
|
-
style="
|
|
352
|
-
font-size: var(--text-6xl);
|
|
353
|
-
font-weight: var(--font-weight-semibold);
|
|
354
|
-
color: ${r?.colors?.titleColor||`var(--foreground)`};
|
|
355
|
-
letter-spacing: -0.02em;
|
|
356
|
-
margin: 0;
|
|
357
|
-
"
|
|
358
|
-
>
|
|
359
|
-
ERROR
|
|
360
|
-
</h1>
|
|
361
|
-
</div>
|
|
362
|
-
<div
|
|
363
|
-
style="
|
|
364
|
-
height: 2px;
|
|
365
|
-
background-color: var(--border);
|
|
366
|
-
width: calc(100% + 3rem);
|
|
367
|
-
margin-left: -1.5rem;
|
|
368
|
-
margin-top: 1.5rem;
|
|
369
|
-
"
|
|
370
|
-
></div>
|
|
371
|
-
</div>
|
|
372
|
-
|
|
373
|
-
<h2
|
|
374
|
-
style="
|
|
375
|
-
font-size: var(--text-2xl);
|
|
376
|
-
font-weight: var(--font-weight-semibold);
|
|
377
|
-
color: var(--foreground);
|
|
378
|
-
margin: 0 0 1rem;
|
|
379
|
-
"
|
|
380
|
-
>
|
|
381
|
-
Something went wrong
|
|
382
|
-
</h2>
|
|
383
|
-
|
|
384
|
-
<div
|
|
385
|
-
style="
|
|
386
|
-
display: inline-flex;
|
|
387
|
-
align-items: center;
|
|
388
|
-
gap: 0.5rem;
|
|
389
|
-
border: 2px solid var(--border);
|
|
390
|
-
background-color: var(--muted);
|
|
391
|
-
padding: 0.375rem 0.75rem;
|
|
392
|
-
margin: 0 0 1rem;
|
|
393
|
-
flex-wrap: wrap;
|
|
394
|
-
justify-content: center;
|
|
395
|
-
"
|
|
396
|
-
>
|
|
397
|
-
<span
|
|
398
|
-
style="
|
|
399
|
-
font-size: 0.75rem;
|
|
400
|
-
color: var(--muted-foreground);
|
|
401
|
-
font-weight: var(--font-weight-semibold);
|
|
402
|
-
"
|
|
403
|
-
>
|
|
404
|
-
CODE:
|
|
405
|
-
</span>
|
|
406
|
-
<span
|
|
407
|
-
style="
|
|
408
|
-
font-size: var(--text-sm);
|
|
409
|
-
font-family: var(--default-mono-font-family, monospace);
|
|
410
|
-
color: var(--foreground);
|
|
411
|
-
word-break: break-all;
|
|
412
|
-
"
|
|
413
|
-
>
|
|
414
|
-
${UT(t)}
|
|
415
|
-
</span>
|
|
416
|
-
</div>
|
|
417
|
-
|
|
418
|
-
<p
|
|
419
|
-
style="
|
|
420
|
-
color: var(--muted-foreground);
|
|
421
|
-
max-width: 28rem;
|
|
422
|
-
margin: 0 auto;
|
|
423
|
-
font-size: var(--text-sm);
|
|
424
|
-
line-height: 1.5;
|
|
425
|
-
text-wrap: pretty;
|
|
426
|
-
"
|
|
427
|
-
>
|
|
428
|
-
${n||`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`}
|
|
429
|
-
</p>
|
|
430
|
-
</div>
|
|
431
|
-
|
|
432
|
-
<div
|
|
433
|
-
style="
|
|
434
|
-
display: flex;
|
|
435
|
-
gap: 0.75rem;
|
|
436
|
-
margin-top: 1.5rem;
|
|
437
|
-
justify-content: center;
|
|
438
|
-
flex-wrap: wrap;
|
|
439
|
-
"
|
|
440
|
-
>
|
|
441
|
-
<a
|
|
442
|
-
href="/"
|
|
443
|
-
style="
|
|
444
|
-
text-decoration: none;
|
|
445
|
-
"
|
|
446
|
-
>
|
|
447
|
-
<div
|
|
448
|
-
style="
|
|
449
|
-
border: 2px solid var(--border);
|
|
450
|
-
background: var(--primary);
|
|
451
|
-
color: var(--primary-foreground);
|
|
452
|
-
padding: 0.5rem 1rem;
|
|
453
|
-
border-radius: 0;
|
|
454
|
-
white-space: nowrap;
|
|
455
|
-
"
|
|
456
|
-
class="btn"
|
|
457
|
-
>
|
|
458
|
-
Go Home
|
|
459
|
-
</div>
|
|
460
|
-
</a>
|
|
461
|
-
<a
|
|
462
|
-
href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
|
|
463
|
-
target="_blank"
|
|
464
|
-
rel="noopener noreferrer"
|
|
465
|
-
style="
|
|
466
|
-
text-decoration: none;
|
|
467
|
-
"
|
|
468
|
-
>
|
|
469
|
-
<div
|
|
470
|
-
style="
|
|
471
|
-
border: 2px solid var(--border);
|
|
472
|
-
background: transparent;
|
|
473
|
-
color: var(--foreground);
|
|
474
|
-
padding: 0.5rem 1rem;
|
|
475
|
-
border-radius: 0;
|
|
476
|
-
white-space: nowrap;
|
|
477
|
-
"
|
|
478
|
-
class="btn"
|
|
479
|
-
>
|
|
480
|
-
Ask AI
|
|
481
|
-
</div>
|
|
482
|
-
</a>
|
|
483
|
-
</div>
|
|
484
|
-
</div>
|
|
485
|
-
</div>
|
|
486
|
-
</body>
|
|
487
|
-
</html>`},GT=q(`/error`,{method:`GET`,metadata:{...px,openapi:{description:`Displays an error page`,responses:{200:{description:`Success`,content:{"text/html":{schema:{type:`string`,description:`The HTML content of the error page`}}}}}}}},async e=>{let t=new URL(e.request?.url||``),n=t.searchParams.get(`error`)||`UNKNOWN`,r=t.searchParams.get(`error_description`)||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||``)?n:`UNKNOWN`,a=r?UT(r):null,o=new URLSearchParams;o.set(`error`,i),r&&o.set(`error_description`,r);let s=e.context.options,c=s.onAPIError?.errorURL;return c?new Response(null,{status:302,headers:{Location:`${c}${c.includes(`?`)?`&`:`?`}${o.toString()}`}}):h&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(WT(e.context.options,i,a),{headers:{"Content-Type":`text/html`}})}),KT=q(`/ok`,{method:`GET`,metadata:{...px,openapi:{description:`Check if the API is working`,responses:{200:{description:`API is working`,content:{"application/json":{schema:{type:`object`,properties:{ok:{type:`boolean`,description:`Indicates if the API is working`}},required:[`ok`]}}}}}}}},async e=>e.json({ok:!0}));async function qT(e,t){let n=await e.context.internalAdapter.findCredentialAccount(t.userId),r=n?.password;return!n||!r?!1:await e.context.password.verify({hash:r,password:t.password})}async function JT(e,t){let n=await t.context.internalAdapter.findCredentialAccount(e),r=n?.password,i=t.body.password;if(!n||!r||!i)throw i&&await t.context.password.hash(i),E.from(`BAD_REQUEST`,V.INVALID_PASSWORD);if(!await t.context.password.verify({hash:r,password:i}))throw E.from(`BAD_REQUEST`,V.INVALID_PASSWORD);return!0}function YT(e,t,n){let r=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}function XT(e,t,n){let r=new URL(t,e.baseURL);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}var ZT=q(`/request-password-reset`,{method:`POST`,body:C_({email:zg().meta({description:`The email address of the user to send a password reset email to`}),redirectTo:K().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:`requestPasswordReset`,description:`Send a password reset email to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`},message:{type:`string`}}}}}}}}},use:[Nx(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error(`Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!`),E.from(`BAD_REQUEST`,{message:`Reset password isn't enabled`,code:`RESET_PASSWORD_DISABLED`});let{email:t,redirectTo:n}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return O(24),await e.context.internalAdapter.findVerificationValue(`dummy-verification-token`),e.context.logger.warn(`Reset Password: User not found`),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`});let i=Tv(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,`sec`),a=O(24);await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=n?encodeURIComponent(n):``,s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:r.user,url:s,token:a},e.request)),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`})}),QT=q(`/reset-password/:token`,{method:`GET`,operationId:`resetPasswordCallback`,query:C_({callbackURL:K().meta({description:`The URL to redirect the user to reset their password`})}),use:[Nx(e=>e.query.callbackURL)],metadata:{openapi:{operationId:`resetPasswordCallback`,description:`Redirects the user to the callback URL with the token`,parameters:[{name:`token`,in:`path`,required:!0,description:`The token to reset the password`,schema:{type:`string`}},{name:`callbackURL`,in:`query`,required:!0,description:`The URL to redirect the user to reset their password`,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:n}=e.query;if(!t||!n)throw e.redirect(YT(e.context,n,{error:`INVALID_TOKEN`}));let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt<new Date?e.redirect(YT(e.context,n,{error:`INVALID_TOKEN`})):e.redirect(XT(e.context,n,{token:t}))}),$T=q(`/reset-password`,{method:`POST`,operationId:`resetPassword`,query:C_({token:K().optional()}).optional(),body:C_({newPassword:K().meta({description:`The new password to set`}),token:K().meta({description:`The token to reset the password`}).optional()}),metadata:{openapi:{operationId:`resetPassword`,description:`Reset the password for a user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw E.from(`BAD_REQUEST`,V.INVALID_TOKEN);let{newPassword:n}=e.body,r=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(n.length<r)throw E.from(`BAD_REQUEST`,V.PASSWORD_TOO_SHORT);if(n.length>i)throw E.from(`BAD_REQUEST`,V.PASSWORD_TOO_LONG);let a=`reset-password:${t}`,o=await e.context.internalAdapter.consumeVerificationValue(a);if(!o)throw E.from(`BAD_REQUEST`,V.INVALID_TOKEN);let s=o.value,c=await e.context.internalAdapter.findUserById(s);if(!c)throw E.from(`BAD_REQUEST`,V.USER_NOT_FOUND);let l=await e.context.password.hash(n);return await e.context.internalAdapter.findCredentialAccount(s)?await e.context.internalAdapter.updatePassword(s,l):await e.context.internalAdapter.createAccount({userId:s,providerId:`credential`,issuer:lv(`credential`),accountId:c.id,password:l}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:c},e.request),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(s),e.json({status:!0})}),eE=q(`/verify-password`,{method:`POST`,body:C_({password:K().meta({description:`The password to verify`})}),metadata:{scope:`server`,openapi:{operationId:`verifyPassword`,description:`Verify the current user's password`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}},use:[bS]},async e=>{let{password:t}=e.body,n=e.context.session;if(!await qT(e,{password:t,userId:n.user.id}))throw E.from(`BAD_REQUEST`,V.INVALID_PASSWORD);return e.json({status:!0})}),tE=C_({callbackURL:K().meta({description:`Callback URL to redirect to after the user has signed in`}).optional(),newUserCallbackURL:K().optional(),errorCallbackURL:K().meta({description:`Callback URL to redirect to if an error happens`}).optional(),provider:OT,disableRedirect:d_().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),idToken:z_(C_({token:K().meta({description:`ID token from the provider`}),nonce:K().meta({description:`Nonce used to generate the token`}).optional(),accessToken:K().meta({description:`Access token from the provider`}).optional(),refreshToken:K().meta({description:`Refresh token from the provider`}).optional(),expiresAt:s_().meta({description:`Expiry date of the token`}).optional(),user:C_({name:C_({firstName:K().optional(),lastName:K().optional()}).optional(),email:K().optional()}).meta({description:`The user object from the provider. Only available for some providers like Apple.`}).optional()})),scopes:x_(K()).meta({description:`Array of scopes to request from the provider. This will override the default scopes passed.`}).optional(),requestSignUp:d_().meta({description:`Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider`}).optional(),loginHint:K().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:AC,additionalData:j_(K(),p_()).optional().meta({description:`Additional data to be passed through the OAuth flow`})}),nE=()=>q(`/sign-in/social`,{method:`POST`,operationId:`socialSignIn`,body:tE,metadata:{$Infer:{body:{},returned:{}},openapi:{description:`Sign in with a social provider`,operationId:`socialSignIn`,responses:{200:{description:`Success - Returns session details (idToken branch) or an authorize URL (redirect branch)`,content:{"application/json":{schema:{type:`object`,description:`Returns session details when idToken is provided, or an authorize URL otherwise`,properties:{token:{type:`string`},user:{type:`object`,$ref:`#/components/schemas/User`},url:{type:`string`},redirect:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=await oC(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,V.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!Hw(t))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,V.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:r}=e.body.idToken;if(!await Uw(t,n,r,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.INVALID_TOKEN);let i={idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},a=await t.getUserInfo(i);if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(Lb(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,V.USER_EMAIL_NOT_FOUND);let o=await uC(t,i,a.data),s=cC(a.data),c=await bC(e,{userInfo:{...a.user,email:a.user.email,id:o.accountId,name:a.user.name||``,image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,...o,accessToken:e.body.idToken.accessToken,idToken:n},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.disableSignUp,source:{method:`oauth`,oauth:{providerId:t.id,profile:s}}});if(c.error)throw c.error===Pb.EMAIL_NOT_VERIFIED?E.from(`FORBIDDEN`,V.EMAIL_NOT_VERIFIED):E.from(`UNAUTHORIZED`,{message:c.error,code:`OAUTH_LINK_ERROR`});return await Tb(e,c.data),e.json({redirect:!1,token:c.data.session.token,url:void 0,user:gv(e.context.options,c.data.user)})}let n=ux(t),{codeVerifier:r,state:i}=await dx(e,{additionalData:e.body.additionalData,idTokenNonce:n}),a=await t.createAuthorizationURL({state:i,codeVerifier:r,idTokenNonce:n,redirectURI:`${e.context.baseURL}${mC(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),rE=()=>q(`/sign-in/email`,{method:`POST`,operationId:`signInEmail`,use:[Fx],cloneRequest:!0,body:C_({email:K().meta({description:`Email of the user`}),password:K().meta({description:`Password of the user`}),callbackURL:K().meta({description:`Callback URL to use as a redirect for email verification`}).optional(),rememberMe:d_().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signInEmail`,description:`Sign in with email and password`,responses:{200:{description:`Success - Returns either session details or redirect URL`,content:{"application/json":{schema:{type:`object`,description:`Session response when idToken is provided`,properties:{redirect:{type:`boolean`,enum:[!1]},token:{type:`string`,description:`Session token`},url:{type:`string`,nullable:!0},user:{type:`object`,$ref:`#/components/schemas/User`}},required:[`redirect`,`token`,`user`]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),E.from(`BAD_REQUEST`,{code:`EMAIL_PASSWORD_DISABLED`,message:`Email and password is not enabled`});let{email:t,password:n}=e.body;if(!zg().safeParse(t).success)throw E.from(`BAD_REQUEST`,V.INVALID_EMAIL);let r=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),i=lv(`credential`),a=r?.accounts.find(e=>e.providerId===`credential`&&e.issuer===i&&e.accountId===r.user.id);if(!r||!a)throw await e.context.password.hash(n),e.context.logger.warn(`User not found`),E.from(`UNAUTHORIZED`,V.INVALID_EMAIL_OR_PASSWORD);let o=r.user,s=a.password;if(!s)throw await e.context.password.hash(n),e.context.logger.warn(`Password not found`),E.from(`UNAUTHORIZED`,V.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:s,password:n}))throw e.context.logger.warn(`Invalid password`),E.from(`UNAUTHORIZED`,V.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!o.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw E.from(`FORBIDDEN`,V.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await gC(e.context.secret,o.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:o,url:r,token:t},hC(e.request)))}throw E.from(`FORBIDDEN`,V.EMAIL_NOT_VERIFIED)}let c=await e.context.internalAdapter.createSession(o.id,e.body.rememberMe===!1);if(!c)throw e.context.logger.error(`Failed to create session`),E.from(`UNAUTHORIZED`,V.FAILED_TO_CREATE_SESSION);return await Tb(e,{session:c,user:o},e.body.rememberMe===!1),e.body.callbackURL&&e.setHeader(`Location`,e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:c.token,url:e.body.callbackURL,user:gv(e.context.options,o)})}),iE=C_({callbackURL:K().meta({description:`The URL to redirect to after provider logout`}).optional(),disableRedirect:d_().meta({description:`Return the provider logout URL without redirecting`}).optional(),state:K().meta({description:`State to pass to the provider logout endpoint`}).optional()}).optional(),aE=e=>({success:!0,url:e?.url,redirect:e?.redirect}),oE=q(`/sign-out`,{method:`POST`,body:iE,operationId:`signOut`,requireHeaders:!0,metadata:{openapi:{operationId:`signOut`,description:`Sign out the current user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`},url:{type:`string`,description:`Provider logout URL when RP-initiated logout is available`},redirect:{type:`boolean`,description:`Whether the client should redirect to the provider logout URL`}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),n=null;if(t)try{n=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error(`Failed to read session from database`,t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error(`Failed to delete session from database`,t)}kb(e);let r=await(async()=>{try{if(!n)return null;let t=await e.context.internalAdapter.findAccounts(n.user.id),r=new Map(e.context.socialProviders.map(e=>[e.id,e])),i=t.filter(e=>!!r.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(i.length===0)return null;let a=new Set,o=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of i){if(a.has(t.providerId))continue;a.add(t.providerId);let n=r.get(t.providerId);try{let r=await n?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:o,state:e.body?.state});if(r)return r.toString()}catch(n){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,n)}}return null}catch(t){return e.context.logger.error(`Failed to create provider logout URL`,t),null}})();if(r){let t=!e.body?.disableRedirect;return t&&e.setHeader(`Location`,r),e.json(aE({url:r,redirect:t}))}return e.json(aE())}),sE=C_({name:K(),email:zg(),password:K().nonempty(),image:K().optional(),callbackURL:K().optional(),rememberMe:d_().optional()}).and(j_(K(),p_())),cE=()=>q(`/sign-up/email`,{method:`POST`,operationId:`signUpWithEmailAndPassword`,use:[Fx],body:sE,cloneRequest:!0,metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signUpWithEmailAndPassword`,description:`Sign up a user using email and password`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},email:{type:`string`,description:`The email of the user`},password:{type:`string`,description:`The password of the user`},image:{type:`string`,description:`The profile image URL of the user`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`},rememberMe:{type:`boolean`,description:"If this is false, the session will not be remembered. Default is `true`."}},required:[`name`,`email`,`password`]}}}},responses:{200:{description:`Successfully created user`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`Authentication token for the session`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}},422:{description:`Unprocessable Entity. User already exists or failed to create user.`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}}}}}}},async e=>ix(e.context.adapter,async()=>{if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw E.from(`BAD_REQUEST`,{message:`Email and password sign up is not enabled`,code:`EMAIL_PASSWORD_SIGN_UP_DISABLED`});let t=e.body,{name:n,email:r,password:i,image:a,callbackURL:o,rememberMe:s,...c}=t;if(!zg().safeParse(r).success)throw E.from(`BAD_REQUEST`,V.INVALID_EMAIL);if(!i||typeof i!=`string`)throw E.from(`BAD_REQUEST`,V.INVALID_PASSWORD);let l=e.context.password.config.minPasswordLength;if(i.length<l)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_SHORT);let u=e.context.password.config.maxPasswordLength;if(i.length>u)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_LONG);let d=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,f=e.context.options.emailAndPassword.autoSignIn===!1||d,p=xv(e.context.options,c,`create`),m=r.toLowerCase(),h=()=>{let t=new Date,r=e.context.generateId({model:`user`})||O(),i={name:n,email:m,emailVerified:!1,image:a??null,createdAt:t,updatedAt:t},o=e.context.options.emailAndPassword?.customSyntheticUser,s;if(o){let t=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of t)e in p&&(n[e]=p[e]);let a=o({coreFields:i,additionalFields:n,id:r});s=_v(e.context.options,a)}else s=_v(e.context.options,{...i,...p,id:r});return e.json({token:null,user:gv(e.context.options,s)})},g=await e.context.internalAdapter.findUserByEmail(m);if(g?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${r}`),d)return await e.context.password.hash(i),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:g.user},hC(e.request))),h();throw E.from(`UNPROCESSABLE_ENTITY`,V.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let _=await e.context.password.hash(i),v;try{if(v=await e.context.internalAdapter.createUser({email:m,name:n,image:a,...p,emailVerified:!1},{method:`email-password`}),!v)throw E.from(`BAD_REQUEST`,V.FAILED_TO_CREATE_USER)}catch(t){if(mx(t)){if(t.statusCode===403&&d)return h();throw t}throw A()&&e.context.logger.error(`Failed to create user`,t),e.context.logger?.error(`Failed to create user`,t),E.from(`UNPROCESSABLE_ENTITY`,V.FAILED_TO_CREATE_USER)}if(!v)throw E.from(`UNPROCESSABLE_ENTITY`,V.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:v.id,providerId:`credential`,issuer:lv(`credential`),accountId:v.id,password:_}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await gC(e.context.secret,v.email,void 0,e.context.options.emailVerification?.expiresIn),r=t.callbackURL?encodeURIComponent(t.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:v,url:i,token:n},hC(e.request)))}if(f)return e.json({token:null,user:gv(e.context.options,v)});let y=await e.context.internalAdapter.createSession(v.id,s===!1);if(!y)throw E.from(`BAD_REQUEST`,V.FAILED_TO_CREATE_SESSION);return await Tb(e,{session:y,user:v},s===!1),e.json({token:y.token,user:gv(e.context.options,v)})})),lE=j_(K().meta({description:`Field name must be a string`}),p_()),uE=()=>q(`/update-session`,{method:`POST`,operationId:`updateSession`,body:lE,use:[yS],metadata:{$Infer:{body:{}},openapi:{operationId:`updateSession`,description:`Update the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{session:{type:`object`,$ref:`#/components/schemas/Session`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,V.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,r=Cv(e.context.options,t,`update`);if(Object.keys(r).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let i=await e.context.internalAdapter.updateSession(n.session.token,{...r,updatedAt:new Date});if(!i&&gS(e))throw kb(e),E.from(`UNAUTHORIZED`,V.FAILED_TO_GET_SESSION);let a=i??{...n.session,...r,updatedAt:new Date};return await Tb(e,{session:a,user:n.user}),e.json({session:vv(e.context.options,a)})}),dE=j_(K().meta({description:`Field name must be a string`}),p_()),fE=()=>q(`/update-user`,{method:`POST`,operationId:`updateUser`,body:dE,use:[yS],metadata:{$Infer:{body:{}},openapi:{operationId:`updateUser`,description:`Update the current user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},image:{type:`string`,description:`The image of the user`,nullable:!0}}}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,V.BODY_MUST_BE_AN_OBJECT);if(t.email)throw E.from(`BAD_REQUEST`,V.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:r,...i}=t,a=e.context.session,o=xv(e.context.options,i,`update`);if(r===void 0&&n===void 0&&Object.keys(o).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:n,image:r,...o})??{...a.user,...n!==void 0&&{name:n},...r!==void 0&&{image:r},...o};return await Tb(e,{session:a.session,user:s}),e.json({status:!0})}),pE=q(`/change-password`,{method:`POST`,operationId:`changePassword`,body:C_({newPassword:K().meta({description:`The new password to set`}),currentPassword:K().meta({description:`The current password is required`}),revokeOtherSessions:d_().meta({description:`Must be a boolean value`}).optional()}),use:[bS],metadata:{openapi:{operationId:`changePassword`,description:`Change the password of the user`,responses:{200:{description:`Password successfully changed`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`New session token if other sessions were revoked`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}}}}}},async e=>{let{newPassword:t,currentPassword:n,revokeOtherSessions:r}=e.body,i=e.context.session,a=e.context.password.config.minPasswordLength;if(t.length<a)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_SHORT);let o=e.context.password.config.maxPasswordLength;if(t.length>o)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_LONG);let s=await e.context.internalAdapter.findCredentialAccount(i.user.id);if(!s||!s.password)throw E.from(`BAD_REQUEST`,V.CREDENTIAL_ACCOUNT_NOT_FOUND);let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:s.password,password:n}))throw E.from(`BAD_REQUEST`,V.INVALID_PASSWORD);await e.context.internalAdapter.updateAccount(s.id,{password:c});let l=null;if(r){await e.context.internalAdapter.deleteUserSessions(i.user.id);let t=await e.context.internalAdapter.createSession(i.user.id);if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,V.FAILED_TO_GET_SESSION);await Tb(e,{session:t,user:i.user}),l=t.token}return e.json({token:l,user:gv(e.context.options,i.user)})}),mE=q.serverOnly({method:`POST`,body:C_({newPassword:K().meta({description:`The new password to set is required`})}),use:[bS]},async e=>{let{newPassword:t}=e.body,n=e.context.session,r=e.context.password.config.minPasswordLength;if(t.length<r)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_SHORT);let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,V.PASSWORD_TOO_LONG);let a=await e.context.internalAdapter.findCredentialAccount(n.user.id),o=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:n.user.id,providerId:`credential`,issuer:lv(`credential`),accountId:n.user.id,password:o}),e.json({status:!0});if(!a.password)return await e.context.internalAdapter.updateAccount(a.id,{password:o}),e.json({status:!0});throw E.from(`BAD_REQUEST`,V.PASSWORD_ALREADY_SET)}),hE=q(`/delete-user`,{method:`POST`,use:[bS],body:C_({callbackURL:K().meta({description:`The callback URL to redirect to after the user is deleted`}).optional(),password:K().meta({description:`The password of the user is required to delete the user`}).optional(),token:K().meta({description:`The token to delete the user is required`}).optional()}),metadata:{openapi:{operationId:`deleteUser`,description:`Delete the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{callbackURL:{type:`string`,description:`The callback URL to redirect to after the user is deleted`},password:{type:`string`,description:`The user's password. Required if session is not fresh`},token:{type:`string`,description:`The deletion verification token`}}}}}},responses:{200:{description:`User deletion processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the operation was successful`},message:{type:`string`,enum:[`User deleted`,`Verification email sent`],description:`Status message of the deletion process`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.fromStatus(`NOT_FOUND`);let t=e.context.session;if(e.body.password){let n=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!n||!n.password)throw E.from(`BAD_REQUEST`,V.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw E.from(`BAD_REQUEST`,V.INVALID_PASSWORD)}if(e.body.token)return await gE({...e,query:{token:e.body.token}}),e.json({success:!0,message:`User deleted`});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=aa(32,`0-9`,`a-z`);await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1e3)});let r=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:r,token:n},e.request)),e.json({success:!0,message:`Verification email sent`})}if(!e.body.password&&e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`BAD_REQUEST`,V.SESSION_EXPIRED)}let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),kb(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:`User deleted`})}),gE=q(`/delete-user/callback`,{method:`GET`,query:C_({token:K().meta({description:`The token to verify the deletion request`}),callbackURL:K().meta({description:`The URL to redirect to after deletion`}).optional()}),use:[Nx(e=>e.query.callbackURL)],metadata:{openapi:{description:`Callback to complete user deletion with verification token`,responses:{200:{description:`User successfully deleted`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the deletion was successful`},message:{type:`string`,enum:[`User deleted`],description:`Confirmation message`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.from(`NOT_FOUND`,{message:`Not found`,code:`NOT_FOUND`});let t=await _S(e,{disableCookieCache:gS(e)});if(!t)throw E.from(`NOT_FOUND`,V.FAILED_TO_GET_USER_INFO);let n=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!n||n.value!==t.user.id)throw E.from(`NOT_FOUND`,V.INVALID_TOKEN);let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),kb(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||`/`);return e.json({success:!0,message:`User deleted`})}),_E=q(`/change-email`,{method:`POST`,body:C_({newEmail:zg().meta({description:`The new email address to set must be a valid email address`}),callbackURL:K().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[bS],metadata:{openapi:{operationId:`changeEmail`,responses:{200:{description:`Email change request processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the request was successful`},message:{type:`string`,enum:[`Email updated`,`Verification email sent`],description:`Status message of the email change process`,nullable:!0}},required:[`status`]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error(`Change email is disabled.`),E.from(`BAD_REQUEST`,V.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn(`Email is the same`),E.fromStatus(`BAD_REQUEST`,{message:`Email is the same`});let n=e.context.session.user.emailVerified!==!0&&e.context.options.user.changeEmail.updateEmailWithoutVerification,r=e.context.options.emailVerification?.sendVerificationEmail,i=r&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});if(await e.context.internalAdapter.findUserByEmail(t))return await gC(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info(`Change email attempt for existing email`),e.json({status:!0});if(n){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await Tb(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),r){let n=await gC(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:i,token:n},e.request))}return e.json({status:!0})}if(i){let n=await gC(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-confirmation`}),r=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:r,token:n},e.request)),e.json({status:!0})}if(!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});let a=await gC(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),vE=zS((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),yE=new WeakMap;function bE(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function xE(e,t){t&&t.forEach((t,n)=>{e.responseHeaders?n.toLowerCase()===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t):e.responseHeaders=new Headers({[n]:t})})}function SE(e){let t=e[ue],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function CE(e,t,n,r){let i={};for(let a of t){let t=!1;try{t=a.matcher(e)}catch(t){let n=yE.get(a.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let o=yE.get(a.handler)??`unknown`,s=n.path??`/:virtual`,c=await x(`hook before ${s} ${o}`,{[MS]:`before`,[C]:s,[NS]:o,[jS]:r},()=>a.handler({...e,returnHeaders:!0})).catch(t=>{throw mx(t)&&le(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});xE(e.context,c?.headers);let l=c?.response;if(l&&typeof l==`object`){if(`context`in l&&typeof l.context==`object`){let{headers:e,...t}=l.context;e instanceof Headers&&(i.headers?e.forEach((e,t)=>{i.headers?.set(t,e)}):i.headers=e),i=vE(t,i);continue}return l}}return{context:i}}async function wE(e,t,n,r){for(let i of t){if(!i.matcher(e))continue;let t=yE.get(i.handler)??`unknown`,a=n.path??`/:virtual`,o=await x(`hook after ${a} ${t}`,{[MS]:`after`,[C]:a,[NS]:t,[jS]:r},()=>i.handler(e)).catch(t=>{if(mx(t))return le(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:SE(t)};throw t});xE(e.context,o.headers),o.response!==void 0&&(e.context.returned=o.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function TE(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(yE.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(yE.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(yE.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(yE.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function EE(e,t){let n=t.operationId??bE(e),r=e.path??`/:virtual`,i=e.options?.method,a=Array.isArray(i)?i[0]:i,o=t.method??t.request?.method??a??`?`,s=t.asResponse??$i(t.request),c={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return x(`${o} ${r}`,{[C]:r,[jS]:n},async()=>Yb(c,async()=>{let{beforeHooks:i,afterHooks:a}=TE(c.context),o=await CE(c,i,e,n);if(`context`in o&&o.context&&typeof o.context==`object`){let{headers:e,...t}=o.context;if(e){c.headers||(c.headers=new Headers);let t=c.headers;e.forEach((e,n)=>{t.set(n,e)})}c=vE(t,c)}else if(o){let e=c.context.responseHeaders;return s?xy(o,{headers:e}):t.returnHeaders?{headers:e,response:o}:o}c.asResponse=!1,c.returnHeaders=!0,c.returnStatus=!0;let l=await Yb(c,()=>x(`handler ${r}`,{[C]:r,[jS]:n},()=>e(c))).catch(e=>{if(mx(e))return{response:e,status:e.statusCode,headers:SE(e)};throw e});if(l instanceof Response)return l;c.context.returned=l.response,c.context.responseHeaders=l.headers??void 0;let u=await wE(c,a,e,n);if(u.response!==void 0&&(l.response=u.response),l.headers=u.headers??l.headers,mx(l.response)&&le(c.context.logger.level,`debug`)&&(l.response.stack=l.response.errorStack),mx(l.response)&&!s)throw l.headers&&Object.defineProperty(l.response,ue,{enumerable:!1,configurable:!0,writable:!1,value:l.headers}),l.response;return s?xy(l.response,{headers:l.headers??void 0,status:l.status}):t.returnHeaders?t.returnStatus?{headers:l.headers,response:l.response,status:l.status}:{headers:l.headers,response:l.response}:t.returnStatus?{response:l.response,status:l.status}:l.response}))}async function DE(e,t){if(e.baseURL)return e;let n=rC(t),r=e.options.baseURL,i=Qi(r)&&!!r.fallback;if(n===void 0&&!i)throw new E(`INTERNAL_SERVER_ERROR`,{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await aC(e,n,iC(e.options))}catch(e){throw e instanceof b?new E(`INTERNAL_SERVER_ERROR`,{message:e.message}):e}}function OE(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=async e=>{let n=bE(i,r),a=async()=>{let r=await t,a=Qi(r.options.baseURL)?await DE(r,e):r;return EE(i,{...e,context:a,operationId:n,asResponse:e?.asResponse??$i(e?.request)})};return await Zb()?a():$b(new WeakMap,a)},n[r].path=i.path,n[r].options=i.options;return n}function kE(e,t){let n=new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,r]of Object.entries(e.endpoints))if(r&&`path`in r&&typeof r.path==`string`){let i=r.path,a=[];r.options&&`method`in r.options&&(Array.isArray(r.options.method)?a=r.options.method:typeof r.options.method==`string`&&(a=[r.options.method])),a.length===0&&(a=[`*`]),n.has(i)||n.set(i,[]),n.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let r=[];for(let[e,t]of n.entries())if(t.length>1){let n=new Map,i=!1;for(let e of t)for(let r of e.methods)n.has(r)||n.set(r,[]),n.get(r).push(e.pluginId),n.get(r).length>1&&(i=!0),(r===`*`&&t.length>1||r!==`*`&&n.has(`*`))&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,r]of n.entries())(r.length>1||e===`*`&&t.length>1||e!==`*`&&n.has(`*`))&&a.push(e);r.push({path:e,plugins:i,conflictingMethods:a})}}if(r.length>0){let e=r.map(e=>` - "${e.path}" [${e.conflictingMethods.join(`, `)}] used by plugins: ${e.plugins.join(`, `)}`).join(`
|
|
488
|
-
`);t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
|
|
489
|
-
${e}
|
|
490
|
-
|
|
491
|
-
To resolve this, you can:
|
|
492
|
-
1. Use only one of the conflicting plugins
|
|
493
|
-
2. Configure the plugins to use different paths (if supported)
|
|
494
|
-
3. Ensure plugins use different HTTP methods for the same path
|
|
495
|
-
`)}}function AE(e,t){let n=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},r=t.plugins?.map(t=>t.middlewares?.map(n=>{let r=(async r=>{let i=await e;return x(`middleware ${n.path} ${t.id}`,{"better_auth.hook.type":`middleware`,"http.route":n.path,"better_auth.context":`plugin:${t.id}`},()=>n.middleware({...r,context:{...i,...r.context}}))});return r.options=n.middleware.options,{path:n.path,middleware:r}})).filter(e=>e!==void 0).flat()||[];return{api:OE({signInSocial:nE(),callbackOAuth:HT,getSession:hS(),signOut:oE,signUpEmail:cE(),signInEmail:rE(),resetPassword:$T,verifyPassword:eE,verifyEmail:yC,sendVerificationEmail:vC,changeEmail:_E,changePassword:pE,setPassword:mE,updateSession:uE(),updateUser:fE(),deleteUser:hE,requestPasswordReset:ZT,requestPasswordResetCallback:QT,listSessions:SS(),revokeSession:CS,revokeSessions:wS,revokeOtherSessions:TS,linkSocialAccount:jT,listUserAccounts:AT,deleteUserCallback:gE,unlinkAccount:MT,refreshToken:zT,getAccessToken:RT,accountInfo:BT,...n,ok:KT,error:GT},e),middlewares:r}}var jE=(e,t)=>{let{api:n,middlewares:r}=AE(e,t),i=new URL(e.baseURL).pathname;return ib(n,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:`/**`,middleware:Mx},...r],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let n=e.options.disabledPaths||[],r=Tx(t.url,i);if(n.includes(r))return new Response(`Not Found`,{status:404});let a=t,o=await dS(a,e);if(o)return o;for(let t of e.options.plugins||[])if(t.onRequest){let n=await x(`onRequest ${t.id}`,{[MS]:`onRequest`,[NS]:`plugin:${t.id}`},()=>t.onRequest(a,e));if(n&&`response`in n)return n.response;n&&`request`in n&&(a=n.request)}return a},async onResponse(t,n){for(let n of e.options.plugins||[])if(n.onResponse){let r=await x(`onResponse ${n.id}`,{[MS]:`onResponse`,[NS]:`plugin:${n.id}`,[ae]:t.status},()=>n.onResponse(t,e));if(r)return r.response}return t},onError(n){if(mx(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?g:void 0;if(t.logger?.disabled!==!0){if(n&&typeof n==`object`&&`message`in n&&typeof n.message==`string`&&(n.message.includes(`no column`)||n.message.includes(`column`)||n.message.includes(`relation`)||n.message.includes(`table`)||n.message.includes(`does not exist`))){e.logger?.error(n.message);return}mx(n)?(n.status===`INTERNAL_SERVER_ERROR`&&e.logger.error(n.status,n),i?.error(n.message)):e.logger?.error(n&&typeof n==`object`&&`name`in n?n.name:``,n)}}})};async function ME(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=se(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await f(async()=>{let{memoryAdapter:e}=await import(`./dist-BoGTNvkC.js`);return{memoryAdapter:e}},__vite__mapDeps([0,1]));n=i(r)(e)}return n.transaction||(g.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function NE(e){return ME(e,async e=>{let{createKyselyAdapter:t}=await f(async()=>{let{createKyselyAdapter:e}=await import(`./kysely-adapter-BHhasAnc.js`);return{createKyselyAdapter:e}},[]),{kysely:n,databaseType:r,transaction:i}=await t(e);if(!n)throw new b(`Failed to initialize database adapter`);let{kyselyAdapter:a}=await f(async()=>{let{kyselyAdapter:e}=await import(`./kysely-adapter-BHhasAnc.js`);return{kyselyAdapter:e}},[]);return a(n,{type:r||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:i})(e)})}function PE(e){let{indexesByTable:t,tables:n}=w(e),r={};for(let e in n){let t=n[e],i=t.fields,a={};if(Object.entries(i).forEach(([e,t])=>{if(a[t.fieldName||e]=t,t.references){let r=n[t.references.model];r&&(a[t.fieldName||e].references={...t.references,model:r.modelName,field:t.references.field})}}),r[t.modelName]){r[t.modelName].fields={...r[t.modelName].fields,...a},t.disableMigrations&&(r[t.modelName].disableMigrations=!0);continue}r[t.modelName]={fields:a,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,n]of t)r[e]&&(r[e].indexes=n);return r}var FE=P({is(e){return e.kind===`AlterTableNode`},create(e){return P({kind:`AlterTableNode`,table:e})},cloneWithTableProps(e,t){return P({...e,...t})},cloneWithColumnAlteration(e,t){return P({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}}),IE=P({is(e){return e.kind===`CreateIndexNode`},create(e){return P({kind:`CreateIndexNode`,name:Te.create(e)})},cloneWith(e,t){return P({...e,...t})},cloneWithColumns(e,t){return P({...e,columns:[...e.columns||[],...t]})}}),LE=P({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return P({kind:`CreateSchemaNode`,schema:Te.create(e),...t})},cloneWith(e,t){return P({...e,...t})}}),RE=P({is(e){return e.kind===`DropIndexNode`},create(e,t){return P({kind:`DropIndexNode`,name:Ce.create(e),...t})},cloneWith(e,t){return P({...e,...t})}}),zE=P({is(e){return e.kind===`DropSchemaNode`},create(e,t){return P({kind:`DropSchemaNode`,schema:Te.create(e),...t})},cloneWith(e,t){return P({...e,...t})}}),BE=P({is(e){return e.kind===`DropTableNode`},create(e,t){return P({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return P({...e,...t})}}),VE=P({is(e){return e.kind===`AliasNode`},create(e,t){return P({kind:`AliasNode`,node:e,alias:t})}}),HE=P({is(e){return e.kind===`TableNode`},create(e){return P({kind:`TableNode`,table:Ce.create(e)})},createWithSchema(e,t){return P({kind:`TableNode`,table:Ce.createWithSchema(e,t)})}});function UE(e){return he(e)&&pe(e.toOperationNode)}function WE(e){return he(e)&&`expressionType`in e&&UE(e)}function GE(e){return he(e)&&`expression`in e&&ge(e.alias)&&UE(e)}var KE=P({is(e){return e.kind===`SelectModifierNode`},create(e,t){return P({kind:`SelectModifierNode`,modifier:e,of:t})},createWithExpression(e){return P({kind:`SelectModifierNode`,rawModifier:e})}}),qE=P({is(e){return e.kind===`AndNode`},create(e,t){return P({kind:`AndNode`,left:e,right:t})}}),JE=P({is(e){return e.kind===`OrNode`},create(e,t){return P({kind:`OrNode`,left:e,right:t})}}),YE=P({is(e){return e.kind===`OnNode`},create(e){return P({kind:`OnNode`,on:e})},cloneWithOperation(e,t,n){return P({...e,on:t===`And`?qE.create(e.on,n):JE.create(e.on,n)})}}),XE=P({is(e){return e.kind===`JoinNode`},create(e,t){return P({kind:`JoinNode`,joinType:e,table:t,on:void 0})},createWithOn(e,t,n){return P({kind:`JoinNode`,joinType:e,table:t,on:YE.create(n)})},cloneWithOn(e,t){return P({...e,on:e.on?YE.cloneWithOperation(e.on,`And`,t):YE.create(t)})}}),ZE=P({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return P({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),QE=P({is(e){return e.kind===`ColumnNode`},create(e){return P({kind:`ColumnNode`,column:Te.create(e)})}}),$E=P({is(e){return e.kind===`SelectAllNode`},create(){return P({kind:`SelectAllNode`})}}),eD=P({is(e){return e.kind===`ReferenceNode`},create(e,t){return P({kind:`ReferenceNode`,table:t,column:e})},createSelectAll(e){return P({kind:`ReferenceNode`,table:e,column:$E.create()})}}),tD=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return gD(this.#e)}};function nD(e){return he(e)&&UE(e)&&ge(e.dynamicReference)}var rD=P({is(e){return e.kind===`OrderByItemNode`},create(e,t){return P({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return P({...e,...t})}}),iD=P({is(e){return e.kind===`CollateNode`},create(e){return P({kind:`CollateNode`,collation:Te.create(e)})}}),aD=class e{#e;constructor(e){this.#e=P(e)}desc(){return new e({node:rD.cloneWith(this.#e.node,{direction:Pe.createWithSql(`desc`)})})}asc(){return new e({node:rD.cloneWith(this.#e.node,{direction:Pe.createWithSql(`asc`)})})}nullsLast(){return new e({node:rD.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new e({node:rD.cloneWith(this.#e.node,{nulls:`first`})})}collate(t){return new e({node:rD.cloneWith(this.#e.node,{collation:iD.create(t)})})}toOperationNode(){return this.#e.node}},oD=new Set;function sD(e){oD.has(e)||(oD.add(e),console.log(e))}function cD(e){return e===`asc`||e===`desc`}function lD(e){if(e.length===2)return[uD(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(sD(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>uD(e))):[uD(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function uD(e,t){let n=dD(e);if(rD.is(n)){if(t)throw Error(`Cannot specify direction twice!`);return n}return fD(n,t)}function dD(e){if(TA(e))return CA(e);if(nD(e))return e.toOperationNode();let[t,n]=e.split(` `);return n?(sD("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),fD(bD(t),n)):bD(e)}function fD(e,t){if(typeof t==`string`){if(!cD(t))throw Error(`Invalid order by direction: ${t}`);return rD.create(e,Pe.createWithSql(t))}if(WE(t))return sD("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),rD.create(e,t.toOperationNode());let n=rD.create(e);return t?t(new aD({node:n})).toOperationNode():n}var pD=P({is(e){return e.kind===`JSONReferenceNode`},create(e,t){return P({kind:`JSONReferenceNode`,reference:e,traversal:t})},cloneWithTraversal(e,t){return P({...e,traversal:t})}}),mD=P({is(e){return e.kind===`JSONOperatorChainNode`},create(e){return P({kind:`JSONOperatorChainNode`,operator:e,values:P([])})},cloneWithValue(e,t){return P({...e,values:P([...e.values,t])})}}),hD=P({is(e){return e.kind===`JSONPathNode`},create(e){return P({kind:`JSONPathNode`,inOperator:e,pathLegs:P([])})},cloneWithLeg(e,t){return P({...e,pathLegs:P([...e.pathLegs,t])})}});function gD(e){return ge(e)?bD(e):e.toOperationNode()}function _D(e){return me(e)?e.map(e=>vD(e)):[vD(e)]}function vD(e){return TA(e)?CA(e):gD(e)}function yD(e,t){if(Ie(t))return pD.create(bD(e),mD.create(xe.create(t)));if(t===`->$`||t===`->>$`)return pD.create(bD(e),hD.create(xe.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function bD(e){if(!e.includes(`.`))return eD.create(QE.create(e));let t=e.split(`.`).map(ED);if(t.length===3)return wD(t);if(t.length===2)return TD(t);throw Error(`invalid column reference ${e}`)}function xD(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(ED);return VE.create(bD(n),Te.create(r))}return bD(e)}function SD(e){return QE.create(e)}function CD(e){if(e.includes(` `)){let[t,n]=e.split(` `).map(ED);if(!cD(n))throw Error(`invalid order direction "${n}" next to "${t}"`);return lD([t,n])[0]}return SD(e)}function wD(e){let[t,n,r]=e;return eD.create(QE.create(r),HE.createWithSchema(t,n))}function TD(e){let[t,n]=e;return eD.create(QE.create(n),HE.create(t))}function ED(e){return e.trim()}var DD=P({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return P({kind:`PrimitiveValueListNode`,values:P([...e])})}}),OD=P({is(e){return e.kind===`ValueListNode`},create(e){return P({kind:`ValueListNode`,values:P(e)})}}),kD=P({is(e){return e.kind===`ValueNode`},create(e){return P({kind:`ValueNode`,value:e})},createImmediate(e){return P({kind:`ValueNode`,value:e,immediate:!0})}});function AD(e){return me(e)?PD(e):jD(e)}function jD(e){return TA(e)?CA(e):kD.create(e)}function MD(e){return ve(e)||be(e)||Re(e)}function ND(e){if(!MD(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return kD.createImmediate(e)}function PD(e){return e.some(TA)?OD.create(e.map(e=>jD(e))):DD.create(e)}function FD(e){if(e.length===3)return ID(e[0],e[1],e[2]);if(e.length===1)return jD(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function ID(e,t,n){return BD(t)&&VD(n)?ZE.create(vD(e),HD(t),kD.createImmediate(n)):ZE.create(vD(e),HD(t),AD(n))}function LD(e,t,n){return ZE.create(vD(e),HD(t),vD(n))}function RD(e,t){return zD(Object.entries(e).filter(([,e])=>!De(e)).map(([e,t])=>ID(e,VD(t)?`is`:`=`,t)),t)}function zD(e,t,n=!0){let r=t===`and`?qE.create:JE.create;if(e.length===0)return ZE.create(kD.createImmediate(1),xe.create(`=`),kD.createImmediate(+(t===`and`)));let i=UD(e[0]);for(let t=1;t<e.length;++t)i=r(i,UD(e[t]));return e.length>1&&n?je.create(i):i}function BD(e){return e===`is`||e===`is not`}function VD(e){return Re(e)||be(e)}function HD(e){if(Oe(e))return xe.create(e);if(UE(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function UD(e){return UE(e)?e.toOperationNode():e}var WD=P({is(e){return e.kind===`OrderByNode`},create(e){return P({kind:`OrderByNode`,items:P([...e])})},cloneWithItems(e,t){return P({...e,items:P([...e.items,...t])})}}),GD=P({is(e){return e.kind===`PartitionByNode`},create(e){return P({kind:`PartitionByNode`,items:P(e)})},cloneWithItems(e,t){return P({...e,items:P([...e.items,...t])})}}),KD=P({is(e){return e.kind===`OverNode`},create(){return P({kind:`OverNode`})},cloneWithOrderByItems(e,t){return P({...e,orderBy:e.orderBy?WD.cloneWithItems(e.orderBy,t):WD.create(t)})},cloneWithPartitionByItems(e,t){return P({...e,partitionBy:e.partitionBy?GD.cloneWithItems(e.partitionBy,t):GD.create(t)})}}),qD=P({is(e){return e.kind===`FromNode`},create(e){return P({kind:`FromNode`,froms:P(e)})},cloneWithFroms(e,t){return P({...e,froms:P([...e.froms,...t])})}}),JD=P({is(e){return e.kind===`GroupByNode`},create(e){return P({kind:`GroupByNode`,items:P(e)})},cloneWithItems(e,t){return P({...e,items:P([...e.items,...t])})}}),YD=P({is(e){return e.kind===`HavingNode`},create(e){return P({kind:`HavingNode`,having:e})},cloneWithOperation(e,t,n){return P({...e,having:t===`And`?qE.create(e.having,n):JE.create(e.having,n)})}}),XD=P({is(e){return e.kind===`ListNode`},create(e){return P({kind:`ListNode`,items:P(e)})}}),ZD=P({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return P({kind:`UpdateQueryNode`,table:e.length===1?e[0]:XD.create(e),...t&&{with:t}})},createWithoutTable(){return P({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return P({...e,from:e.from?qD.cloneWithFroms(e.from,t):qD.create(t)})},cloneWithUpdates(e,t){return P({...e,updates:e.updates?P([...e.updates,...t]):t})},cloneWithLimit(e,t){return P({...e,limit:t})}}),QD=P({is(e){return e.kind===`UsingNode`},create(e){return P({kind:`UsingNode`,tables:P(e)})},cloneWithTables(e,t){return P({...e,tables:P([...e.tables,...t])})}}),$D=P({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return P({kind:`DeleteQueryNode`,from:qD.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>X.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>X.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return P({...e,limit:t})},cloneWithoutLimit(e){return P({...e,limit:void 0})},cloneWithUsing(e,t){return P({...e,using:e.using===void 0?QD.create(t):QD.cloneWithTables(e.using,t)})}}),eO=P({is(e){return e.kind===`WhereNode`},create(e){return P({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return P({...e,where:t===`And`?qE.create(e.where,n):JE.create(e.where,n)})}}),tO=P({is(e){return e.kind===`ReturningNode`},create(e){return P({kind:`ReturningNode`,selections:P(e)})},cloneWithSelections(e,t){return P({...e,selections:e.selections?P([...e.selections,...t]):P(t)})}}),nO=P({is(e){return e.kind===`ExplainNode`},create(e,t){return P({kind:`ExplainNode`,format:e,options:t})}}),rO=P({is(e){return e.kind===`MergeQueryNode`},create(e,t){return P({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return P({...e,using:t})},cloneWithWhen(e,t){return P({...e,whens:e.whens?P([...e.whens,t]):P([t])})},cloneWithThen(e,t){return P({...e,whens:e.whens?P([...e.whens.slice(0,-1),Ee.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),iO=P({is(e){return e.kind===`OutputNode`},create(e){return P({kind:`OutputNode`,selections:P(e)})},cloneWithSelections(e,t){return P({...e,selections:e.selections?P([...e.selections,...t]):P(t)})}}),X=P({is(e){return aO.is(e)||ye.is(e)||ZD.is(e)||$D.is(e)||rO.is(e)},cloneWithEndModifier(e,t){return P({...e,endModifiers:e.endModifiers?P([...e.endModifiers,t]):P([t])})},cloneWithWhere(e,t){return P({...e,where:e.where?eO.cloneWithOperation(e.where,`And`,t):eO.create(t)})},cloneWithJoin(e,t){return P({...e,joins:e.joins?P([...e.joins,t]):P([t])})},cloneWithReturning(e,t){return P({...e,returning:e.returning?tO.cloneWithSelections(e.returning,t):tO.create(t)})},cloneWithoutReturning(e){return P({...e,returning:void 0})},cloneWithoutWhere(e){return P({...e,where:void 0})},cloneWithExplain(e,t,n){return P({...e,explain:nO.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return P({...e,top:t})},cloneWithOutput(e,t){return P({...e,output:e.output?iO.cloneWithSelections(e.output,t):iO.create(t)})},cloneWithOrderByItems(e,t){return P({...e,orderBy:e.orderBy?WD.cloneWithItems(e.orderBy,t):WD.create(t)})},cloneWithoutOrderBy(e){return P({...e,orderBy:void 0})}}),aO=P({is(e){return e.kind===`SelectQueryNode`},create(e){return P({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return P({kind:`SelectQueryNode`,from:qD.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return P({...e,selections:e.selections?P([...e.selections,...t]):P(t)})},cloneWithDistinctOn(e,t){return P({...e,distinctOn:e.distinctOn?P([...e.distinctOn,...t]):P(t)})},cloneWithFrontModifier(e,t){return P({...e,frontModifiers:e.frontModifiers?P([...e.frontModifiers,t]):P([t])})},cloneWithOrderByItems:(e,t)=>X.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return P({...e,groupBy:e.groupBy?JD.cloneWithItems(e.groupBy,t):JD.create(t)})},cloneWithLimit(e,t){return P({...e,limit:t})},cloneWithOffset(e,t){return P({...e,offset:t})},cloneWithFetch(e,t){return P({...e,fetch:t})},cloneWithHaving(e,t){return P({...e,having:e.having?YD.cloneWithOperation(e.having,`And`,t):YD.create(t)})},cloneWithSetOperations(e,t){return P({...e,setOperations:e.setOperations?P([...e.setOperations,...t]):P([...t])})},cloneWithoutSelections(e){return P({...e,selections:[]})},cloneWithoutLimit(e){return P({...e,limit:void 0})},cloneWithoutOffset(e){return P({...e,offset:void 0})},cloneWithoutOrderBy:e=>X.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return P({...e,groupBy:void 0})}}),oO=class e{#e;constructor(e){this.#e=P(e)}on(...t){return new e({...this.#e,joinNode:XE.cloneWithOn(this.#e.joinNode,FD(t))})}onRef(t,n,r){return new e({...this.#e,joinNode:XE.cloneWithOn(this.#e.joinNode,LD(t,n,r))})}onTrue(){return new e({...this.#e,joinNode:XE.cloneWithOn(this.#e.joinNode,Pe.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}},sO=P({is(e){return e.kind===`PartitionByItemNode`},create(e){return P({kind:`PartitionByItemNode`,partitionBy:e})}});function cO(e){return _D(e).map(sO.create)}var lO=class e{#e;constructor(e){this.#e=P(e)}orderBy(...t){return new e({overNode:KD.cloneWithOrderByItems(this.#e.overNode,lD(t))})}clearOrderBy(){return new e({overNode:X.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(t){return new e({overNode:KD.cloneWithPartitionByItems(this.#e.overNode,cO(t))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}},uO=P({is(e){return e.kind===`SelectionNode`},create(e){return P({kind:`SelectionNode`,selection:e})},createSelectAll(){return P({kind:`SelectionNode`,selection:$E.create()})},createSelectAllFromTable(e){return P({kind:`SelectionNode`,selection:eD.createSelectAll(e)})}});function dO(e){return pe(e)?dO(e(SA())):me(e)?e.map(e=>fO(e)):[fO(e)]}function fO(e){return ge(e)?uO.create(xD(e)):nD(e)?uO.create(e.toOperationNode()):uO.create(wA(e))}function pO(e){return e?Array.isArray(e)?e.map(mO):[mO(e)]:[uO.createSelectAll()]}function mO(e){if(ge(e))return uO.createSelectAllFromTable(MA(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}var hO=P({is(e){return e.kind===`ValuesNode`},create(e){return P({kind:`ValuesNode`,values:P(e)})}}),gO=P({is(e){return e.kind===`DefaultInsertValueNode`},create(){return P({kind:`DefaultInsertValueNode`})}});function _O(e){let t=pe(e)?e(SA()):e;return vO(me(t)?t:P([t]))}function vO(e){let t=yO(e);return[P([...t.keys()].map(QE.create)),hO.create(e.map(e=>bO(e,t)))]}function yO(e){let t=new Map;for(let n of e){let e=Object.keys(n);for(let r of e)!t.has(r)&&n[r]!==void 0&&t.set(r,t.size)}return t}function bO(e,t){let n=Object.keys(e),r=Array.from({length:t.size}),i=!1,a=n.length;for(let o of n){let n=t.get(o);if(De(n)){a--;continue}let s=e[o];(De(s)||TA(s))&&(i=!0),r[n]=s}if(a<t.size||i){let e=gO.create();return OD.create(r.map(t=>De(t)?e:jD(t)))}return DD.create(r)}var xO=P({is(e){return e.kind===`ColumnUpdateNode`},create(e,t){return P({kind:`ColumnUpdateNode`,column:e,value:t})}});function SO(...e){return e.length===2?[xO.create(vD(e[0]),jD(e[1]))]:CO(e[0])}function CO(e){let t=pe(e)?e(SA()):e;return Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>xO.create(QE.create(e),jD(t)))}var wO=P({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return P({kind:`OnDuplicateKeyNode`,updates:e})}}),TO=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},EO=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function DO(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}var OO=P({is(e){return e.kind===`OnConflictNode`},create(){return P({kind:`OnConflictNode`})},cloneWith(e,t){return P({...e,...t})},cloneWithIndexWhere(e,t){return P({...e,indexWhere:e.indexWhere?eO.cloneWithOperation(e.indexWhere,`And`,t):eO.create(t)})},cloneWithIndexOrWhere(e,t){return P({...e,indexWhere:e.indexWhere?eO.cloneWithOperation(e.indexWhere,`Or`,t):eO.create(t)})},cloneWithUpdateWhere(e,t){return P({...e,updateWhere:e.updateWhere?eO.cloneWithOperation(e.updateWhere,`And`,t):eO.create(t)})},cloneWithUpdateOrWhere(e,t){return P({...e,updateWhere:e.updateWhere?eO.cloneWithOperation(e.updateWhere,`Or`,t):eO.create(t)})},cloneWithoutIndexWhere(e){return P({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return P({...e,updateWhere:void 0})}}),kO=class e{#e;constructor(e){this.#e=P(e)}column(t){let n=QE.create(t);return new e({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?P([...this.#e.onConflictNode.columns,n]):P([n])})})}columns(t){let n=t.map(QE.create);return new e({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?P([...this.#e.onConflictNode.columns,...n]):P(n)})})}constraint(t){return new e({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{constraint:Te.create(t)})})}expression(t){return new e({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{indexExpression:t.toOperationNode()})})}where(...t){return new e({...this.#e,onConflictNode:OO.cloneWithIndexWhere(this.#e.onConflictNode,FD(t))})}whereRef(t,n,r){return new e({...this.#e,onConflictNode:OO.cloneWithIndexWhere(this.#e.onConflictNode,LD(t,n,r))})}clearWhere(){return new e({...this.#e,onConflictNode:OO.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new AO({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new jO({...this.#e,onConflictNode:OO.cloneWith(this.#e.onConflictNode,{updates:CO(e)})})}$call(e){return e(this)}},AO=class{#e;constructor(e){this.#e=P(e)}toOperationNode(){return this.#e.onConflictNode}},jO=class e{#e;constructor(e){this.#e=P(e)}where(...t){return new e({...this.#e,onConflictNode:OO.cloneWithUpdateWhere(this.#e.onConflictNode,FD(t))})}whereRef(t,n,r){return new e({...this.#e,onConflictNode:OO.cloneWithUpdateWhere(this.#e.onConflictNode,LD(t,n,r))})}clearWhere(){return new e({...this.#e,onConflictNode:OO.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}},MO=P({is(e){return e.kind===`TopNode`},create(e,t){return P({kind:`TopNode`,expression:e,modifiers:t})}});function NO(e,t){if(!ve(e)&&!Be(e))throw Error(`Invalid top expression: ${e}`);if(!De(t)&&!PO(t))throw Error(`Invalid top modifiers: ${t}`);return MO.create(e,t)}function PO(e){return e===`percent`||e===`with ties`||e===`percent with ties`}var FO=P({is(e){return e.kind===`OrActionNode`},create(e){return P({kind:`OrActionNode`,action:e})}}),IO=class e{#e;constructor(e){this.#e=P(e)}values(t){let[n,r]=_O(t);return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{columns:n,values:r})})}columns(t){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{columns:P(t.map(QE.create))})})}expression(t){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{values:CA(t)})})}defaultValues(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(t){return new e({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,t.toOperationNode())})}ignore(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`ignore`)})})}orIgnore(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`ignore`)})})}orAbort(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`abort`)})})}orFail(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`fail`)})})}orReplace(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`replace`)})})}orRollback(){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{orAction:FO.create(`rollback`)})})}top(t,n){return new e({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(t,n))})}onConflict(t){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{onConflict:t(new kO({onConflictNode:OO.create()})).toOperationNode()})})}onDuplicateKeyUpdate(t){return new e({...this.#e,queryNode:ye.cloneWith(this.#e.queryNode,{onDuplicateKey:wO.create(CO(t))})})}returning(t){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,dO(t))})}returningAll(){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,pO())})}output(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,dO(t))})}outputAll(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,pO(t))})}clearReturning(){return new e({...this.#e,queryNode:X.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(t,n){return t?n(this):new e({...this.#e})}$castTo(){return new e(this.#e)}$narrowType(){return new e(this.#e)}$assertType(){return new e(this.#e)}withPlugin(t){return new e({...this.#e,executor:this.#e.executor.withPlugin(t)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new TO(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??EO;throw DO(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(t,n){return await new e({...this.#e,queryNode:X.cloneWithExplain(this.#e.queryNode,t,n)}).execute()}},LO=class{numDeletedRows;constructor(e){this.numDeletedRows=e}},RO=P({is(e){return e.kind===`LimitNode`},create(e){return P({kind:`LimitNode`,limit:e})}}),zO,BO=class{#e;constructor(e){this.#e=P(e)}where(...e){return new zO({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,FD(e))})}whereRef(e,t,n){return new zO({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,LD(e,t,n))})}clearWhere(){return new zO({...this.#e,queryNode:X.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new zO({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(e,t))})}using(e){return new zO({...this.#e,queryNode:$D.cloneWithUsing(this.#e.queryNode,kA(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new zO({...this.#e,queryNode:X.cloneWithJoin(this.#e.queryNode,Nk(e,t))})}returning(e){return new zO({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,dO(e))})}returningAll(e){return new zO({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,pO(e))})}output(e){return new zO({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,dO(e))})}outputAll(e){return new zO({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,pO(e))})}clearReturning(){return new zO({...this.#e,queryNode:X.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new zO({...this.#e,queryNode:$D.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new zO({...this.#e,queryNode:X.cloneWithOrderByItems(this.#e.queryNode,lD(e))})}clearOrderBy(){return new zO({...this.#e,queryNode:X.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new zO({...this.#e,queryNode:$D.cloneWithLimit(this.#e.queryNode,RO.create(jD(e)))})}modifyEnd(e){return new zO({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new zO({...this.#e})}$castTo(){return new zO(this.#e)}$narrowType(){return new zO(this.#e)}$assertType(){return new zO(this.#e)}withPlugin(e){return new zO({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new LO(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??EO;throw DO(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new zO({...this.#e,queryNode:X.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};zO=BO;var VO=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},HO,UO=class{#e;constructor(e){this.#e=P(e)}where(...e){return new HO({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,FD(e))})}whereRef(e,t,n){return new HO({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,LD(e,t,n))})}clearWhere(){return new HO({...this.#e,queryNode:X.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new HO({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(e,t))})}from(e){return new HO({...this.#e,queryNode:ZD.cloneWithFromItems(this.#e.queryNode,kA(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new HO({...this.#e,queryNode:X.cloneWithJoin(this.#e.queryNode,Nk(e,t))})}orderBy(...e){return new HO({...this.#e,queryNode:X.cloneWithOrderByItems(this.#e.queryNode,lD(e))})}clearOrderBy(){return new HO({...this.#e,queryNode:X.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new HO({...this.#e,queryNode:ZD.cloneWithLimit(this.#e.queryNode,RO.create(jD(e)))})}set(...e){return new HO({...this.#e,queryNode:ZD.cloneWithUpdates(this.#e.queryNode,SO(...e))})}returning(e){return new HO({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,dO(e))})}returningAll(e){return new HO({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,pO(e))})}output(e){return new HO({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,dO(e))})}outputAll(e){return new HO({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,pO(e))})}modifyEnd(e){return new HO({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new HO({...this.#e,queryNode:X.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new HO({...this.#e})}$castTo(){return new HO(this.#e)}$narrowType(){return new HO(this.#e)}$assertType(){return new HO(this.#e)}withPlugin(e){return new HO({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new VO(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??EO;throw DO(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new HO({...this.#e,queryNode:X.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};HO=UO;var WO=P({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return P({kind:`CommonTableExpressionNameNode`,table:HE.create(e),columns:t?P(t.map(QE.create)):void 0})}}),GO=P({is(e){return e.kind===`CommonTableExpressionNode`},create(e,t){return P({kind:`CommonTableExpressionNode`,name:e,expression:t})},cloneWith(e,t){return P({...e,...t})}}),KO=class e{#e;constructor(e){this.#e=P(e)}materialized(){return new e({...this.#e,node:GO.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new e({...this.#e,node:GO.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}};function qO(e,t){let n=UE(t)?t.toOperationNode():t(Ak()).toOperationNode();return pe(e)?e(JO(n)).toOperationNode():GO.create(YO(e),n)}function JO(e){return t=>new KO({node:GO.create(YO(t),e)})}function YO(e){if(e.includes(`(`)){let t=e.split(/[\(\)]/),n=t[0],r=t[1].split(`,`).map(e=>e.trim());return WO.create(n,r)}return WO.create(e)}var XO=P({is(e){return e.kind===`WithNode`},create(e,t){return P({kind:`WithNode`,expressions:P([e]),...t})},cloneWithExpression(e,t){return P({...e,expressions:P([...e.expressions,t])})}}),ZO=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function QO(e){let t=``;for(let n=0;n<e;++n)t+=$O();return t}function $O(){return ZO[~~(Math.random()*ZO.length)]}function Z(){return new ek}var ek=class{#e;get queryId(){return this.#e===void 0&&(this.#e=QO(8)),this.#e}},tk=class{nodeStack=[];#e=P({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(e,t){if(!e)return e;this.nodeStack.push(e);let n=this.transformNodeImpl(e,t);return this.nodeStack.pop(),P(n)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){return e&&P(e.map(e=>this.transformNode(e,t)))}transformSelectQuery(e,t){return{kind:`SelectQueryNode`,from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)}}transformSelection(e,t){return{kind:`SelectionNode`,selection:this.transformNode(e.selection,t)}}transformColumn(e,t){return{kind:`ColumnNode`,column:this.transformNode(e.column,t)}}transformAlias(e,t){return{kind:`AliasNode`,node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)}}transformTable(e,t){return{kind:`TableNode`,table:this.transformNode(e.table,t)}}transformFrom(e,t){return{kind:`FromNode`,froms:this.transformNodeList(e.froms,t)}}transformReference(e,t){return{kind:`ReferenceNode`,column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)}}transformAnd(e,t){return{kind:`AndNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformOr(e,t){return{kind:`OrNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformValueList(e,t){return{kind:`ValueListNode`,values:this.transformNodeList(e.values,t)}}transformParens(e,t){return{kind:`ParensNode`,node:this.transformNode(e.node,t)}}transformJoin(e,t){return{kind:`JoinNode`,joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)}}transformRaw(e,t){return{kind:`RawNode`,sqlFragments:P([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)}}transformWhere(e,t){return{kind:`WhereNode`,where:this.transformNode(e.where,t)}}transformInsertQuery(e,t){return{kind:`InsertQueryNode`,into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformValues(e,t){return{kind:`ValuesNode`,values:this.transformNodeList(e.values,t)}}transformDeleteQuery(e,t){return{kind:`DeleteQueryNode`,from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformReturning(e,t){return{kind:`ReturningNode`,selections:this.transformNodeList(e.selections,t)}}transformCreateTable(e,t){return{kind:`CreateTableNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),indexes:this.transformNodeList(e.indexes,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)}}transformColumnDefinition(e,t){return{kind:`ColumnDefinitionNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,t){return{kind:`AddColumnNode`,column:this.transformNode(e.column,t)}}transformDropTable(e,t){return{kind:`DropTableNode`,table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade,temporary:e.temporary}}transformOrderBy(e,t){return{kind:`OrderByNode`,items:this.transformNodeList(e.items,t)}}transformOrderByItem(e,t){return{kind:`OrderByItemNode`,orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls}}transformGroupBy(e,t){return{kind:`GroupByNode`,items:this.transformNodeList(e.items,t)}}transformGroupByItem(e,t){return{kind:`GroupByItemNode`,groupBy:this.transformNode(e.groupBy,t)}}transformUpdateQuery(e,t){return{kind:`UpdateQueryNode`,table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)}}transformColumnUpdate(e,t){return{kind:`ColumnUpdateNode`,column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)}}transformLimit(e,t){return{kind:`LimitNode`,limit:this.transformNode(e.limit,t)}}transformOffset(e,t){return{kind:`OffsetNode`,offset:this.transformNode(e.offset,t)}}transformOnConflict(e,t){return{kind:`OnConflictNode`,columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing}}transformOnDuplicateKey(e,t){return{kind:`OnDuplicateKeyNode`,updates:this.transformNodeList(e.updates,t)}}transformCreateIndex(e,t){return{kind:`CreateIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,t){return{kind:`ListNode`,items:this.transformNodeList(e.items,t)}}transformDropIndex(e,t){return{kind:`DropIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,t){return{kind:`PrimaryKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,t){return{kind:`UniqueConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,t){return{kind:`ForeignKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,t){return{kind:`SetOperationNode`,operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all}}transformReferences(e,t){return{kind:`ReferencesNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,t){return{kind:`CheckConstraintNode`,expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)}}transformWith(e,t){return{kind:`WithNode`,expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive}}transformCommonTableExpression(e,t){return{kind:`CommonTableExpressionNode`,name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)}}transformCommonTableExpressionName(e,t){return{kind:`CommonTableExpressionNameNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)}}transformHaving(e,t){return{kind:`HavingNode`,having:this.transformNode(e.having,t)}}transformCreateSchema(e,t){return{kind:`CreateSchemaNode`,schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists}}transformDropSchema(e,t){return{kind:`DropSchemaNode`,schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,t){return{kind:`AlterTableNode`,table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)}}transformDropColumn(e,t){return{kind:`DropColumnNode`,column:this.transformNode(e.column,t),ifExists:e.ifExists}}transformRenameColumn(e,t){return{kind:`RenameColumnNode`,column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)}}transformAlterColumn(e,t){return{kind:`AlterColumnNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,t){return{kind:`ModifyColumnNode`,column:this.transformNode(e.column,t)}}transformAddConstraint(e,t){return{kind:`AddConstraintNode`,constraint:this.transformNode(e.constraint,t)}}transformDropConstraint(e,t){return{kind:`DropConstraintNode`,constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,t){return{kind:`RenameConstraintNode`,oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)}}transformCreateView(e,t){return{kind:`CreateViewNode`,name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)}}transformRefreshMaterializedView(e,t){return{kind:`RefreshMaterializedViewNode`,name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,t){return{kind:`DropViewNode`,name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,t){return{kind:`GeneratedNode`,byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)}}transformDefaultValue(e,t){return{kind:`DefaultValueNode`,defaultValue:this.transformNode(e.defaultValue,t)}}transformOn(e,t){return{kind:`OnNode`,on:this.transformNode(e.on,t)}}transformSelectModifier(e,t){return{kind:`SelectModifierNode`,modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)}}transformCreateType(e,t){return{kind:`CreateTypeNode`,name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)}}transformDropType(e,t){return{kind:`DropTypeNode`,name:this.transformNode(e.name,t),additionalNames:this.transformNodeList(e.additionalNames,t),cascade:e.cascade,ifExists:e.ifExists}}transformExplain(e,t){return{kind:`ExplainNode`,format:e.format,options:this.transformNode(e.options,t)}}transformSchemableIdentifier(e,t){return{kind:`SchemableIdentifierNode`,schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)}}transformAggregateFunction(e,t){return{kind:`AggregateFunctionNode`,func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)}}transformOver(e,t){return{kind:`OverNode`,orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)}}transformPartitionBy(e,t){return{kind:`PartitionByNode`,items:this.transformNodeList(e.items,t)}}transformPartitionByItem(e,t){return{kind:`PartitionByItemNode`,partitionBy:this.transformNode(e.partitionBy,t)}}transformBinaryOperation(e,t){return{kind:`BinaryOperationNode`,leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)}}transformUnaryOperation(e,t){return{kind:`UnaryOperationNode`,operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)}}transformUsing(e,t){return{kind:`UsingNode`,tables:this.transformNodeList(e.tables,t)}}transformFunction(e,t){return{kind:`FunctionNode`,func:e.func,arguments:this.transformNodeList(e.arguments,t)}}transformCase(e,t){return{kind:`CaseNode`,value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement}}transformWhen(e,t){return{kind:`WhenNode`,condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)}}transformJSONReference(e,t){return{kind:`JSONReferenceNode`,reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)}}transformJSONPath(e,t){return{kind:`JSONPathNode`,inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)}}transformJSONPathLeg(e,t){return{kind:`JSONPathLegNode`,type:e.type,value:e.value}}transformJSONOperatorChain(e,t){return{kind:`JSONOperatorChainNode`,operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)}}transformTuple(e,t){return{kind:`TupleNode`,values:this.transformNodeList(e.values,t)}}transformMergeQuery(e,t){return{kind:`MergeQueryNode`,into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)}}transformMatched(e,t){return{kind:`MatchedNode`,not:e.not,bySource:e.bySource}}transformAddIndex(e,t){return{kind:`AddIndexNode`,name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists}}transformCast(e,t){return{kind:`CastNode`,expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)}}transformFetch(e,t){return{kind:`FetchNode`,rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier}}transformTop(e,t){return{kind:`TopNode`,expression:e.expression,modifiers:e.modifiers}}transformOutput(e,t){return{kind:`OutputNode`,selections:this.transformNodeList(e.selections,t)}}transformAlterType(e,t){return{kind:`AlterTypeNode`,name:this.transformNode(e.name,t),addValue:this.transformNode(e.addValue,t),renameTo:this.transformNode(e.renameTo,t),renameValue:this.transformNode(e.renameValue,t),setSchema:this.transformNode(e.setSchema,t)}}transformAddValue(e,t){return{kind:`AddValueNode`,value:this.transformNode(e.value,t),ifNotExists:e.ifNotExists,isBefore:e.isBefore,neighborValue:this.transformNode(e.neighborValue,t)}}transformRenameValue(e,t){return{kind:`RenameValueNode`,oldValue:this.transformNode(e.oldValue,t),newValue:this.transformNode(e.newValue,t)}}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}};function nk(e){return he(e)&&ge(e.kind)}var rk={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function ik(e){return nk(e)&&rk[e.kind]===!0}var ak=P({json_agg:!0,to_json:!0}),ok=class extends tk{#e;#t=new Set;#n=new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,t){if(!ik(e))return super.transformNodeImpl(e,t);let n=this.#a(e);for(let e of n)this.#n.add(e);let r=this.#i(e);for(let e of r)this.#t.add(e);let i=super.transformNodeImpl(e,t);for(let e of r)this.#t.delete(e);for(let e of n)this.#n.delete(e);return i}transformSchemableIdentifier(e,t){let n=super.transformSchemableIdentifier(e,t);return n.schema||!this.#t.has(e.identifier.name)?n:{...n,schema:Te.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:HE.createWithSchema(this.#e,n.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#r(e,t,`aggregated`)}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#r(e,t,`arguments`)}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map(e=>HE.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return ak[e.func]?e[n].map(e=>!HE.is(e)||e.table.schema?this.transformNode(e,t):{...e,table:this.transformIdentifier(e.table.identifier,t)}):this.transformNodeList(e[n],t)}#i(e){let t=new Set;if(`name`in e&&e.name&&Ce.is(e.name)&&this.#s(e.name,t),`from`in e&&e.from)for(let n of e.from.froms)this.#o(n,t);if(`into`in e&&e.into&&this.#o(e.into,t),`table`in e&&e.table&&this.#o(e.table,t),`joins`in e&&e.joins)for(let n of e.joins)this.#o(n.table,t);return`using`in e&&e.using&&(XE.is(e.using)?this.#o(e.using.table,t):this.#o(e.using,t)),t}#a(e){let t=new Set;return`with`in e&&e.with&&this.#c(e.with,t),t}#o(e,t){if(HE.is(e))return this.#s(e.table,t);if(VE.is(e)&&HE.is(e.node))return this.#s(e.node.table,t);if(XD.is(e)){for(let n of e.items)this.#o(n,t);return}if(QD.is(e)){for(let n of e.tables)this.#o(n,t);return}}#s(e,t){let n=e.identifier.name;!this.#t.has(n)&&!this.#n.has(n)&&t.add(n)}#c(e,t){for(let n of e.expressions){let e=n.name.table.table.identifier.name;this.#n.has(e)||t.add(e)}}},sk=class{#e;constructor(e){this.#e=new ok(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}},ck=P({is(e){return e.kind===`MatchedNode`},create(e,t=!1){return P({kind:`MatchedNode`,not:e,bySource:t})}});function lk(e,t,n){return Ee.create(zD([ck.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&n?LD(t[0],t[1],t[2]):FD(t)]:[]],`and`,!1))}function uk(e){return ge(e)?Pe.create([e],[]):UE(e)?e.toOperationNode():e}var dk=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function fk(e,t){let n=new dk,r=new dk;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),P({connection:await n.promise,release:r.resolve})}function pk(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),mk(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),mk(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function mk(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function hk(e,t,n){e?.aborted&&(n?.(),gk(e.reason,t))}function gk(e,t){throw bk(e,t),e}var _k={};async function vk(e,t,n,r){if(!t)return e;hk(t,`before ${n}`,r);let{promise:i,resolve:a}=new dk,o=()=>a(_k);t.addEventListener(`abort`,o);try{hk(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==_k)return a;r?.(),gk(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,o),a(_k)}}function yk(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${Le(t)}`)}function bk(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}var xk=P([]),Sk=class{#e;constructor(e=xk){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}hk(r,`before query execution`),t=P({signal:r});let{connection:i,release:a}=await fk(this,t),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new dk,l=()=>c(_k);r.addEventListener(`abort`,l,{once:!0});try{hk(r,`before query execution`,a);let c=pk(n,i,a);if(c&&i.collectSessionInfo){hk(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===_k&&(e.catch(yk(`collectSessionInfo`)).finally(a),gk(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===_k?(Promise.allSettled([l.catch(yk(`query`)),c?.(o).catch(yk(`inflightQueryAbortHandler`))]).finally(a),gk(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===_k&&(d.catch(yk(`plugins.transformResult`)),gk(r.reason,`during result transformation`)),f}finally{c(_k),r.removeEventListener(`abort`,l)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await fk(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=P({signal:r}),hk(r,`before connection acquisition`);let{connection:i,release:a}=await fk(this,n),{promise:o,resolve:s}=new dk,c=()=>s(_k);r.addEventListener(`abort`,c,{once:!0});let l,u;hk(r,`before query streaming`,a);let{queryId:d}=e;try{for(l=i.streamQuery(e,t,n);;){hk(r,`during query streaming`);let e=l.next(),t=await Promise.race([o,e]);if(t===_k&&(u=e.catch(yk(`iterator.next`)),gk(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,d,n),a=await Promise.race([o,i]);a===_k&&(u=i.catch(yk(`plugins.transformResult`)),gk(r.reason,`during result transformation`)),yield a}}finally{s(_k),r.removeEventListener(`abort`,c);let e=(l?.return?.()||Promise.resolve()).finally(()=>u).finally(a);u||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(P({queryId:t,result:e,signal:r}));return e}},Ck=new class e extends Sk{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(t){return new e([...this.plugins,t])}withPlugins(t){return new e([...this.plugins,...t])}withPluginAtFront(t){return new e([t,...this.plugins])}withoutPlugins(){return new e([])}},wk=class{numChangedRows;constructor(e){this.numChangedRows=e}},Tk=class e{#e;constructor(e){this.#e=P(e)}modifyEnd(t){return new e({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,t.toOperationNode())})}top(t,n){return new e({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(t,n))})}using(...e){return new Ek({...this.#e,queryNode:rO.cloneWithUsing(this.#e.queryNode,Nk(`Using`,e))})}returning(t){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,dO(t))})}returningAll(t){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,pO(t))})}output(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,dO(t))})}outputAll(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,pO(t))})}},Ek=class e{#e;constructor(e){this.#e=P(e)}modifyEnd(t){return new e({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,t.toOperationNode())})}top(t,n){return new e({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(t,n))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,n){return this.#t([e,t,n],!0)}#t(e,t){return new Dk({...this.#e,queryNode:rO.cloneWithWhen(this.#e.queryNode,lk({isMatched:!0},e,t))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,t,n){return this.#n([e,t,n],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,n){return this.#n([e,t,n],!0,!0)}returning(t){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,dO(t))})}returningAll(t){return new e({...this.#e,queryNode:X.cloneWithReturning(this.#e.queryNode,pO(t))})}output(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,dO(t))})}outputAll(t){return new e({...this.#e,queryNode:X.cloneWithOutput(this.#e.queryNode,pO(t))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:rO.cloneWithWhen(this.#e.queryNode,lk({isMatched:!1,bySource:n},e,t))};return new(n?Dk:Ok)(r)}$call(e){return e(this)}$if(t,n){return t?n(this):new e({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new wk(n.numAffectedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??EO;throw DO(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}},Dk=class{#e;constructor(e){this.#e=P(e)}thenDelete(){return new Ek({...this.#e,queryNode:rO.cloneWithThen(this.#e.queryNode,uk(`delete`))})}thenDoNothing(){return new Ek({...this.#e,queryNode:rO.cloneWithThen(this.#e.queryNode,uk(`do nothing`))})}thenUpdate(e){return new Ek({...this.#e,queryNode:rO.cloneWithThen(this.#e.queryNode,uk(e(new UO({queryId:this.#e.queryId,executor:Ck,queryNode:ZD.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},Ok=class{#e;constructor(e){this.#e=P(e)}thenDoNothing(){return new Ek({...this.#e,queryNode:rO.cloneWithThen(this.#e.queryNode,uk(`do nothing`))})}thenInsertValues(e){let[t,n]=_O(e);return new Ek({...this.#e,queryNode:rO.cloneWithThen(this.#e.queryNode,uk(ye.cloneWith(ye.createWithoutInto(),{columns:t,values:n})))})}},kk=class e{#e;constructor(e){this.#e=P(e)}selectFrom(e){return Yk({queryId:Z(),executor:this.#e.executor,queryNode:aO.createFrom(kA(e),this.#e.withNode)})}selectNoFrom(e){return Yk({queryId:Z(),executor:this.#e.executor,queryNode:aO.cloneWithSelections(aO.create(this.#e.withNode),dO(e))})}insertInto(e){return new IO({queryId:Z(),executor:this.#e.executor,queryNode:ye.create(MA(e),this.#e.withNode)})}replaceInto(e){return new IO({queryId:Z(),executor:this.#e.executor,queryNode:ye.create(MA(e),this.#e.withNode,!0)})}deleteFrom(e){return new BO({queryId:Z(),executor:this.#e.executor,queryNode:$D.create(kA(e),this.#e.withNode)})}updateTable(e){return new UO({queryId:Z(),executor:this.#e.executor,queryNode:ZD.create(kA(e),this.#e.withNode)})}mergeInto(e){return new Tk({queryId:Z(),executor:this.#e.executor,queryNode:rO.create(jA(e),this.#e.withNode)})}with(t,n){let r=qO(t,n);return new e({...this.#e,withNode:this.#e.withNode?XO.cloneWithExpression(this.#e.withNode,r):XO.create(r)})}withRecursive(t,n){let r=qO(t,n);return new e({...this.#e,withNode:this.#e.withNode?XO.cloneWithExpression(this.#e.withNode,r):XO.create(r,{recursive:!0})})}withPlugin(t){return new e({...this.#e,executor:this.#e.executor.withPlugin(t)})}withoutPlugins(){return new e({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(t){return new e({...this.#e,executor:this.#e.executor.withPluginAtFront(new sk(t))})}};function Ak(){return new kk({executor:Ck})}function jk(e,t){return new oO({joinNode:XE.create(e,AA(t))})}function Mk(){return new lO({overNode:KD.create()})}function Nk(e,t){if(t.length===3)return Fk(e,t[0],t[1],t[2]);if(t.length===2)return Pk(e,t[0],t[1]);if(t.length===1)return Ik(e,t[0]);throw Error(`not implemented`)}function Pk(e,t,n){return n(jk(e,t)).toOperationNode()}function Fk(e,t,n,r){return XE.createWithOn(e,AA(t),LD(n,`=`,r))}function Ik(e,t){return XE.create(e,AA(t))}var Lk=P({is(e){return e.kind===`OffsetNode`},create(e){return P({kind:`OffsetNode`,offset:e})}}),Rk=P({is(e){return e.kind===`GroupByItemNode`},create(e){return P({kind:`GroupByItemNode`,groupBy:e})}});function zk(e){return e=pe(e)?e(SA()):e,_D(e).map(Rk.create)}function Bk(e,t,n){return pe(t)&&(t=t(xA())),me(t)||(t=[t]),t.map(t=>Ne.create(e,CA(t),n))}var Vk=class e{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Hk(this,e)}or(...e){return new Uk(JE.create(this.#e,FD(e)))}and(...e){return new Wk(qE.create(this.#e,FD(e)))}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},Hk=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return VE.create(this.#e.toOperationNode(),UE(this.#t)?this.#t.toOperationNode():Te.create(this.#t))}},Uk=class e{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Hk(this,e)}or(...t){return new e(JE.create(this.#e,FD(t)))}$castTo(){return new e(this.#e)}toOperationNode(){return je.create(this.#e)}},Wk=class e{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new Hk(this,e)}and(...t){return new e(qE.create(this.#e,FD(t)))}$castTo(){return new e(this.#e)}toOperationNode(){return je.create(this.#e)}},Gk=P({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:kD.create(e),modifier:t}}});function Kk(e,t){if(!ve(e)&&!Be(e))throw Error(`Invalid fetch row count: ${e}`);if(!qk(t))throw Error(`Invalid fetch modifier: ${t}`);return Gk.create(e,t)}function qk(e){return e===`only`||e===`with ties`}var Q,Jk=class{#e;constructor(e){this.#e=P(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new Q({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,FD(e))})}whereRef(e,t,n){return new Q({...this.#e,queryNode:X.cloneWithWhere(this.#e.queryNode,LD(e,t,n))})}having(...e){return new Q({...this.#e,queryNode:aO.cloneWithHaving(this.#e.queryNode,FD(e))})}havingRef(e,t,n){return new Q({...this.#e,queryNode:aO.cloneWithHaving(this.#e.queryNode,LD(e,t,n))})}select(e){return new Q({...this.#e,queryNode:aO.cloneWithSelections(this.#e.queryNode,dO(e))})}distinctOn(e){return new Q({...this.#e,queryNode:aO.cloneWithDistinctOn(this.#e.queryNode,_D(e))})}modifyFront(e){return new Q({...this.#e,queryNode:aO.cloneWithFrontModifier(this.#e.queryNode,KE.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.createWithExpression(e.toOperationNode()))})}distinct(){return new Q({...this.#e,queryNode:aO.cloneWithFrontModifier(this.#e.queryNode,KE.create(`Distinct`))})}forUpdate(e){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`ForUpdate`,e?we(e).map(MA):void 0))})}forShare(e){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`ForShare`,e?we(e).map(MA):void 0))})}forKeyShare(e){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`ForKeyShare`,e?we(e).map(MA):void 0))})}forNoKeyUpdate(e){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`ForNoKeyUpdate`,e?we(e).map(MA):void 0))})}skipLocked(){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`SkipLocked`))})}noWait(){return new Q({...this.#e,queryNode:X.cloneWithEndModifier(this.#e.queryNode,KE.create(`NoWait`))})}selectAll(e){return new Q({...this.#e,queryNode:aO.cloneWithSelections(this.#e.queryNode,pO(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new Q({...this.#e,queryNode:X.cloneWithJoin(this.#e.queryNode,Nk(e,t))})}orderBy(...e){return new Q({...this.#e,queryNode:X.cloneWithOrderByItems(this.#e.queryNode,lD(e))})}groupBy(e){return new Q({...this.#e,queryNode:aO.cloneWithGroupByItems(this.#e.queryNode,zk(e))})}limit(e){return new Q({...this.#e,queryNode:aO.cloneWithLimit(this.#e.queryNode,RO.create(jD(e)))})}offset(e){return new Q({...this.#e,queryNode:aO.cloneWithOffset(this.#e.queryNode,Lk.create(jD(e)))})}fetch(e,t=`only`){return new Q({...this.#e,queryNode:aO.cloneWithFetch(this.#e.queryNode,Kk(e,t))})}top(e,t){return new Q({...this.#e,queryNode:X.cloneWithTop(this.#e.queryNode,NO(e,t))})}union(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`union`,e,!1))})}unionAll(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`union`,e,!0))})}intersect(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`intersect`,e,!1))})}intersectAll(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`intersect`,e,!0))})}except(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`except`,e,!1))})}exceptAll(e){return new Q({...this.#e,queryNode:aO.cloneWithSetOperations(this.#e.queryNode,Bk(`except`,e,!0))})}as(e){return new Xk(this,e)}clearSelect(){return new Q({...this.#e,queryNode:aO.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new Q({...this.#e,queryNode:X.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new Q({...this.#e,queryNode:aO.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new Q({...this.#e,queryNode:aO.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new Q({...this.#e,queryNode:X.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new Q({...this.#e,queryNode:aO.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new Q({...this.#e})}$castTo(){return new Q(this.#e)}$narrowType(){return new Q(this.#e)}$assertType(){return new Q(this.#e)}$asTuple(){return new Vk(this.toOperationNode())}$asScalar(){return new Vk(this.toOperationNode())}withPlugin(e){return new Q({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??EO;throw DO(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new Q({...this.#e,queryNode:X.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};Q=Jk;function Yk(e){return new Jk(e)}var Xk=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return VE.create(this.#e.toOperationNode(),Te.create(this.#t))}},Zk=P({is(e){return e.kind===`AggregateFunctionNode`},create(e,t=[]){return P({kind:`AggregateFunctionNode`,func:e,aggregated:t})},cloneWithDistinct(e){return P({...e,distinct:!0})},cloneWithOrderBy(e,t,n=!1){let r=n?`withinGroup`:`orderBy`;return P({...e,[r]:e[r]?WD.cloneWithItems(e[r],t):WD.create(t)})},cloneWithFilter(e,t){return P({...e,filter:e.filter?eO.cloneWithOperation(e.filter,`And`,t):eO.create(t)})},cloneWithOrFilter(e,t){return P({...e,filter:e.filter?eO.cloneWithOperation(e.filter,`Or`,t):eO.create(t)})},cloneWithOver(e,t){return P({...e,over:t})}}),Qk=P({is(e){return e.kind===`FunctionNode`},create(e,t){return P({kind:`FunctionNode`,func:e,arguments:t})}}),$k=class e{#e;constructor(e){this.#e=P(e)}get expressionType(){}as(e){return new eA(this,e)}distinct(){return new e({...this.#e,aggregateFunctionNode:Zk.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...t){return new e({...this.#e,aggregateFunctionNode:X.cloneWithOrderByItems(this.#e.aggregateFunctionNode,lD(t))})}clearOrderBy(){return new e({...this.#e,aggregateFunctionNode:X.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...t){return new e({...this.#e,aggregateFunctionNode:Zk.cloneWithOrderBy(this.#e.aggregateFunctionNode,lD(t),!0)})}filterWhere(...t){return new e({...this.#e,aggregateFunctionNode:Zk.cloneWithFilter(this.#e.aggregateFunctionNode,FD(t))})}filterWhereRef(t,n,r){return new e({...this.#e,aggregateFunctionNode:Zk.cloneWithFilter(this.#e.aggregateFunctionNode,LD(t,n,r))})}over(t){let n=Mk();return new e({...this.#e,aggregateFunctionNode:Zk.cloneWithOver(this.#e.aggregateFunctionNode,(t?t(n):n).toOperationNode())})}$call(e){return e(this)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},eA=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return VE.create(this.#e.toOperationNode(),Te.create(this.#t))}};function tA(){let e=(e,t)=>new Vk(Qk.create(e,_D(t??[]))),t=(e,t)=>new $k({aggregateFunctionNode:Zk.create(e,t?_D(t):void 0)});return Object.assign(e,{agg:t,avg(e){return t(`avg`,[e])},coalesce(...t){return e(`coalesce`,t)},count(e){return t(`count`,[e])},countAll(e){return new $k({aggregateFunctionNode:Zk.create(`count`,pO(e))})},max(e){return t(`max`,[e])},min(e){return t(`min`,[e])},sum(e){return t(`sum`,[e])},any(t){return e(`any`,[t])},jsonAgg(e){return new $k({aggregateFunctionNode:Zk.create(`json_agg`,[ge(e)?MA(e):e.toOperationNode()])})},toJson(e){return new Vk(Qk.create(`to_json`,[ge(e)?MA(e):e.toOperationNode()]))}})}var nA=P({is(e){return e.kind===`UnaryOperationNode`},create(e,t){return P({kind:`UnaryOperationNode`,operator:e,operand:t})}});function rA(e,t){if(Se(e))return nA.create(xe.create(e),vD(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}var iA=P({is(e){return e.kind===`CaseNode`},create(e){return P({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return P({...e,when:P(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return P({...e,when:e.when?P([...e.when.slice(0,-1),Ee.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return P({...e,...t})}}),aA=class{#e;constructor(e){this.#e=P(e)}when(...e){return new oA({...this.#e,node:iA.cloneWithWhen(this.#e.node,Ee.create(FD(e)))})}whenRef(e,t,n){return new oA({...this.#e,node:iA.cloneWithWhen(this.#e.node,Ee.create(LD(e,t,n)))})}},oA=class{#e;constructor(e){this.#e=P(e)}then(e){return new sA({...this.#e,node:iA.cloneWithThen(this.#e.node,MD(e)?ND(e):jD(e))})}thenRef(e){return new sA({...this.#e,node:iA.cloneWithThen(this.#e.node,vD(e))})}},sA=class{#e;constructor(e){this.#e=P(e)}when(...e){return new oA({...this.#e,node:iA.cloneWithWhen(this.#e.node,Ee.create(FD(e)))})}whenRef(e,t,n){return new oA({...this.#e,node:iA.cloneWithWhen(this.#e.node,Ee.create(LD(e,t,n)))})}else(e){return new cA({...this.#e,node:iA.cloneWith(this.#e.node,{else:MD(e)?ND(e):jD(e)})})}elseRef(e){return new cA({...this.#e,node:iA.cloneWith(this.#e.node,{else:vD(e)})})}end(){return new Vk(iA.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Vk(iA.cloneWith(this.#e.node,{isStatement:!0}))}},cA=class{#e;constructor(e){this.#e=P(e)}end(){return new Vk(iA.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Vk(iA.cloneWith(this.#e.node,{isStatement:!0}))}},lA=P({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return P({kind:`JSONPathLegNode`,type:e,value:t})}}),uA=/^#-\d+$/,dA=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!uA.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t(`ArrayLocation`,e)}key(e){return this.#t(`Member`,e)}#t(e,t){return pD.is(this.#e)?new fA(pD.cloneWithTraversal(this.#e,hD.is(this.#e.traversal)?hD.cloneWithLeg(this.#e.traversal,lA.create(e,t)):mD.cloneWithValue(this.#e.traversal,kD.createImmediate(t)))):new fA(hD.cloneWithLeg(this.#e,lA.create(e,t)))}},fA=class e extends dA{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new pA(this,e)}$castTo(){return new e(this.#e)}$notNull(){return new e(this.#e)}toOperationNode(){return this.#e}},pA=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return VE.create(this.#e.toOperationNode(),UE(this.#t)?this.#t.toOperationNode():Te.create(this.#t))}},mA=P({is(e){return e.kind===`TupleNode`},create(e){return P({kind:`TupleNode`,values:P(e)})}}),hA=P({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),gA=P([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),_A=P({is(e){return e.kind===`DataTypeNode`},create(e){return P({kind:`DataTypeNode`,dataType:e})}});function vA(e){return hA[e]||gA.some(t=>t.test(e))}function yA(e){if(UE(e))return e.toOperationNode();if(vA(e))return _A.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}var bA=P({is(e){return e.kind===`CastNode`},create(e,t){return P({kind:`CastNode`,expression:e,dataType:t})}});function xA(e=Ck){function t(e,t,n){return new Vk(ID(e,t,n))}function n(e,t){return new Vk(rA(e,t))}let r=Object.assign(t,{fn:void 0,eb:void 0,selectFrom(t){return Yk({queryId:Z(),executor:e,queryNode:aO.createFrom(kA(t))})},case(e){return new aA({node:iA.create(De(e)?void 0:vD(e))})},ref(e,t){return De(t)?new Vk(bD(e)):new dA(yD(e,t))},jsonPath(){return new dA(hD.create())},table(e){return new Vk(MA(e))},val(e){return new Vk(jD(e))},refTuple(...e){return new Vk(mA.create(e.map(vD)))},tuple(...e){return new Vk(mA.create(e.map(jD)))},lit(e){return new Vk(ND(e))},unary:n,not(e){return n(`not`,e)},exists(e){return n(`exists`,e)},neg(e){return n(`-`,e)},between(e,t,n){return new Vk(ZE.create(vD(e),xe.create(`between`),qE.create(jD(t),jD(n))))},betweenSymmetric(e,t,n){return new Vk(ZE.create(vD(e),xe.create(`between symmetric`),qE.create(jD(t),jD(n))))},and(e){return me(e)?new Vk(zD(e,`and`)):new Vk(RD(e,`and`))},or(e){return me(e)?new Vk(zD(e,`or`)):new Vk(RD(e,`or`))},parens(...e){let t=FD(e);return je.is(t)?new Vk(t):new Vk(je.create(t))},cast(e,t){return new Vk(bA.create(vD(e),yA(t)))}});return r.fn=tA(),r.eb=r,r}function SA(e){return xA()}function CA(e){if(UE(e))return e.toOperationNode();if(pe(e))return e(SA()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function wA(e){if(UE(e))return e.toOperationNode();if(pe(e))return e(SA()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function TA(e){return WE(e)||GE(e)||pe(e)}var EA=class{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new DA(this.#e,e)}},DA=class{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return VE.create(MA(this.#e),Te.create(this.#t))}};function OA(e){return he(e)&&UE(e)&&ge(e.table)&&ge(e.alias)}function kA(e){return me(e)?e.map(e=>AA(e)):[AA(e)]}function AA(e){return ge(e)?jA(e):OA(e)?e.toOperationNode():wA(e)}function jA(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(NA);return VE.create(MA(n),Te.create(r))}return MA(e)}function MA(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(NA);return HE.createWithSchema(t,n)}return HE.create(e)}function NA(e){return e.trim()}var PA=P({is(e){return e.kind===`AddColumnNode`},create(e){return P({kind:`AddColumnNode`,column:e})}}),FA=P({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return P({kind:`ColumnDefinitionNode`,column:QE.create(e),dataType:t})},cloneWithFrontModifier(e,t){return P({...e,frontModifiers:e.frontModifiers?P([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return P({...e,endModifiers:e.endModifiers?P([...e.endModifiers,t]):[t]})},cloneWith(e,t){return P({...e,...t})}}),IA=P({is(e){return e.kind===`DropColumnNode`},create(e){return P({kind:`DropColumnNode`,column:QE.create(e)})},cloneWith(e,t){return P({...e,...t})}}),LA=P({is(e){return e.kind===`RenameColumnNode`},create(e,t){return P({kind:`RenameColumnNode`,column:QE.create(e),renameTo:QE.create(t)})}}),RA=P({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return P({kind:`CheckConstraintNode`,expression:e,name:t?Te.create(t):void 0})}}),zA=P({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(zA);var BA=P({is(e){return e.kind===`ReferencesNode`},create(e,t){return P({kind:`ReferencesNode`,table:e,columns:P([...t])})},cloneWithOnDelete(e,t){return P({...e,onDelete:t})},cloneWithOnUpdate(e,t){return P({...e,onUpdate:t})}});function VA(e){return ge(e)&&zA[e]}function HA(e){return UE(e)?e.toOperationNode():kD.createImmediate(e)}var UA=P({is(e){return e.kind===`GeneratedNode`},create(e){return P({kind:`GeneratedNode`,...e})},createWithExpression(e){return P({kind:`GeneratedNode`,always:!0,expression:e})},cloneWith(e,t){return P({...e,...t})}}),WA=P({is(e){return e.kind===`DefaultValueNode`},create(e){return P({kind:`DefaultValueNode`,defaultValue:e})}});function GA(e){if(VA(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}var KA=class e{#e;constructor(e){this.#e=e}autoIncrement(){return new e(FA.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new e(FA.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new e(FA.cloneWith(this.#e,{primaryKey:!0}))}references(t){let n=bD(t);if(!n.table||$E.is(n.column))throw Error(`invalid call references('${t}'). The reference must have format table.column or schema.table.column`);return new e(FA.cloneWith(this.#e,{references:BA.create(n.table,[n.column])}))}onDelete(t){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new e(FA.cloneWith(this.#e,{references:BA.cloneWithOnDelete(this.#e.references,GA(t))}))}onUpdate(t){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new e(FA.cloneWith(this.#e,{references:BA.cloneWithOnUpdate(this.#e.references,GA(t))}))}unique(){return new e(FA.cloneWith(this.#e,{unique:!0}))}notNull(){return new e(FA.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new e(FA.cloneWith(this.#e,{unsigned:!0}))}defaultTo(t){return new e(FA.cloneWith(this.#e,{defaultTo:WA.create(HA(t))}))}check(t){return new e(FA.cloneWith(this.#e,{check:RA.create(t.toOperationNode())}))}generatedAlwaysAs(t){return new e(FA.cloneWith(this.#e,{generated:UA.createWithExpression(t.toOperationNode())}))}generatedAlwaysAsIdentity(){return new e(FA.cloneWith(this.#e,{generated:UA.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new e(FA.cloneWith(this.#e,{generated:UA.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new e(FA.cloneWith(this.#e,{generated:UA.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(t){return new e(FA.cloneWithFrontModifier(this.#e,t.toOperationNode()))}nullsNotDistinct(){return new e(FA.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new e(FA.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(t){return new e(FA.cloneWithEndModifier(this.#e,t.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}},qA=P({is(e){return e.kind===`ModifyColumnNode`},create(e){return P({kind:`ModifyColumnNode`,column:e})}}),JA=P({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return P({kind:`ForeignKeyConstraintNode`,columns:e,references:BA.create(t,n),name:r?Te.create(r):void 0})},cloneWith(e,t){return P({...e,...t})}}),YA=class e{#e;constructor(e){this.#e=e}onDelete(t){return new e(JA.cloneWith(this.#e,{onDelete:GA(t)}))}onUpdate(t){return new e(JA.cloneWith(this.#e,{onUpdate:GA(t)}))}deferrable(){return new e(JA.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new e(JA.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new e(JA.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new e(JA.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},XA=P({is(e){return e.kind===`AddConstraintNode`},create(e){return P({kind:`AddConstraintNode`,constraint:e})}}),ZA=P({is(e){return e.kind===`UniqueConstraintNode`},create(e,t,n){return ge(e.at(0))&&(sD("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(QE.create)),P({kind:`UniqueConstraintNode`,columns:P(e),name:t?Te.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return P({...e,...t})}}),QA=P({is(e){return e.kind===`DropConstraintNode`},create(e){return P({kind:`DropConstraintNode`,constraintName:Te.create(e)})},cloneWith(e,t){return P({...e,...t})}}),$A=P({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return P({kind:`AlterColumnNode`,column:QE.create(e),[t]:n})}}),ej=class{#e;constructor(e){this.#e=e}setDataType(e){return new tj($A.create(this.#e,`dataType`,yA(e)))}setDefault(e){return new tj($A.create(this.#e,`setDefault`,HA(e)))}dropDefault(){return new tj($A.create(this.#e,`dropDefault`,!0))}setNotNull(){return new tj($A.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new tj($A.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},tj=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}},nj=class{#e;constructor(e){this.#e=P(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},rj=class e{#e;constructor(e){this.#e=P(e)}onDelete(t){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(t)})}onUpdate(t){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(t)})}deferrable(){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new e({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(FE.cloneWithTableProps(this.#e.node,{addConstraint:XA.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ij=class e{#e;constructor(e){this.#e=P(e)}ifExists(){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{dropConstraint:QA.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{dropConstraint:QA.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{dropConstraint:QA.cloneWith(this.#e.node.dropConstraint,{modifier:`restrict`})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},aj=P({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return P({kind:`PrimaryKeyConstraintNode`,columns:P(e.map(QE.create)),name:t?Te.create(t):void 0})},cloneWith(e,t){return P({...e,...t})}}),oj=P({is(e){return e.kind===`AddIndexNode`},create(e){return P({kind:`AddIndexNode`,name:Te.create(e)})},cloneWith(e,t){return P({...e,...t})},cloneWithColumns(e,t){return P({...e,columns:[...e.columns||[],...t]})}}),sj=class e{#e;constructor(e){this.#e=P(e)}unique(){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(t){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.cloneWithColumns(this.#e.node.addIndex,[ge(t)?CD(t):t.toOperationNode()])})})}columns(t){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.cloneWithColumns(this.#e.node.addIndex,t.map(e=>ge(e)?CD(e):e.toOperationNode()))})})}expression(t){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.cloneWithColumns(this.#e.node.addIndex,[t.toOperationNode()])})})}using(t){return new e({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.cloneWith(this.#e.node.addIndex,{using:Pe.createWithSql(t)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},cj=class e{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new e(ZA.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new e(ZA.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new e(ZA.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new e(ZA.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new e(ZA.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},lj=class e{#e;constructor(e){this.#e=e}deferrable(){return new e(aj.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new e(aj.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new e(aj.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new e(aj.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},uj=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}},dj=P({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return P({kind:`RenameConstraintNode`,oldName:Te.create(e),newName:Te.create(t)})}}),fj=class e{#e;constructor(e){this.#e=P({...e})}ifExists(){return new e({...this.#e,node:IA.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}},pj=class{#e;constructor(e){this.#e=P(e)}renameTo(e){return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{renameTo:MA(e)})})}setSchema(e){return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{setSchema:Te.create(e)})})}alterColumn(e,t){let n=t(new ej(e));return new mj({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=fe){let n=t(new fj({node:IA.create(e)}));return new mj({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new mj({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,LA.create(e,t))})}addColumn(e,t,n=fe){let r=n(new KA(FA.create(e,yA(t))));return new mj({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,PA.create(r.toOperationNode()))})}modifyColumn(e,t,n=fe){let r=n(new KA(FA.create(e,yA(t))));return new mj({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,qA.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=fe){let r=n(new cj(ZA.create(t.map(e=>ge(e)?QE.create(e):CA(e)),e)));return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addConstraint:XA.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=fe){let r=n(new uj(RA.create(t.toOperationNode(),e)));return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addConstraint:XA.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=fe){let a=i(new YA(JA.create(t.map(QE.create),MA(n),r.map(QE.create),e)));return new rj({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=fe){let r=n(new lj(aj.create(t,e)));return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addConstraint:XA.create(r.toOperationNode())})})}dropConstraint(e){return new ij({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{dropConstraint:QA.create(e)})})}renameConstraint(e,t){return new ij({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{renameConstraint:dj.create(e,t)})})}addIndex(e){return new sj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{addIndex:oj.create(e)})})}dropIndex(e){return new nj({...this.#e,node:FE.cloneWithTableProps(this.#e.node,{dropIndex:RE.create(e)})})}$call(e){return e(this)}},mj=class e{#e;constructor(e){this.#e=P(e)}alterColumn(t,n){let r=n(new ej(t));return new e({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(t,n=fe){let r=n(new fj({node:IA.create(t)}));return new e({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}renameColumn(t,n){return new e({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,LA.create(t,n))})}addColumn(t,n,r=fe){let i=r(new KA(FA.create(t,yA(n))));return new e({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,PA.create(i.toOperationNode()))})}modifyColumn(t,n,r=fe){let i=r(new KA(FA.create(t,yA(n))));return new e({...this.#e,node:FE.cloneWithColumnAlteration(this.#e.node,qA.create(i.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},hj=class extends tk{transformPrimitiveValueList(e){return OD.create(e.values.map(kD.createImmediate))}transformValue(e){return kD.createImmediate(e.value)}},gj=class e{#e;constructor(e){this.#e=P(e)}ifNotExists(){return new e({...this.#e,node:IE.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new e({...this.#e,node:IE.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new e({...this.#e,node:IE.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(t){return new e({...this.#e,node:IE.cloneWith(this.#e.node,{table:MA(t)})})}column(t){return new e({...this.#e,node:IE.cloneWithColumns(this.#e.node,[ge(t)?CD(t):t.toOperationNode()])})}columns(t){return new e({...this.#e,node:IE.cloneWithColumns(this.#e.node,t.map(e=>ge(e)?CD(e):e.toOperationNode()))})}expression(t){return new e({...this.#e,node:IE.cloneWithColumns(this.#e.node,[t.toOperationNode()])})}using(t){return new e({...this.#e,node:IE.cloneWith(this.#e.node,{using:Pe.createWithSql(t)})})}where(...t){let n=new hj;return new e({...this.#e,node:X.cloneWithWhere(this.#e.node,n.transformNode(FD(t),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},_j=class e{#e;constructor(e){this.#e=P(e)}ifNotExists(){return new e({...this.#e,node:LE.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function vj(e){if(ke.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var yj=class e{#e;constructor(e){this.#e=e}using(t){return new e(oj.cloneWith(this.#e,{using:Pe.createWithSql(t)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},bj=class e{#e;constructor(e){this.#e=P(e)}temporary(){return new e({...this.#e,node:Me.cloneWith(this.#e.node,{temporary:!0})})}onCommit(t){return new e({...this.#e,node:Me.cloneWith(this.#e.node,{onCommit:vj(t)})})}ifNotExists(){return new e({...this.#e,node:Me.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(t,n,r=fe){let i=r(new KA(FA.create(t,yA(n))));return new e({...this.#e,node:Me.cloneWithColumn(this.#e.node,i.toOperationNode())})}addPrimaryKeyConstraint(t,n,r=fe){let i=r(new lj(aj.create(n,t)));return new e({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addUniqueConstraint(t,n,r=fe){let i=r(new cj(ZA.create(n.map(e=>ge(e)?QE.create(e):CA(e)),t)));return new e({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addIndex(t,n,r=fe){let i=r(new yj(oj.cloneWithColumns(oj.create(t),n.map(e=>ge(e)?QE.create(e):CA(e)))));return new e({...this.#e,node:Me.cloneWithIndex(this.#e.node,i.toOperationNode())})}addCheckConstraint(t,n,r=fe){let i=r(new uj(RA.create(n.toOperationNode(),t)));return new e({...this.#e,node:Me.cloneWithConstraint(this.#e.node,i.toOperationNode())})}addForeignKeyConstraint(t,n,r,i,a=fe){let o=a(new YA(JA.create(n.map(QE.create),MA(r),i.map(QE.create),t)));return new e({...this.#e,node:Me.cloneWithConstraint(this.#e.node,o.toOperationNode())})}modifyFront(t){return new e({...this.#e,node:Me.cloneWithFrontModifier(this.#e.node,t.toOperationNode())})}modifyEnd(t){return new e({...this.#e,node:Me.cloneWithEndModifier(this.#e.node,t.toOperationNode())})}as(t){return new e({...this.#e,node:Me.cloneWith(this.#e.node,{selectQuery:CA(t)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},xj=class e{#e;constructor(e){this.#e=P(e)}on(t){return new e({...this.#e,node:RE.cloneWith(this.#e.node,{table:MA(t)})})}ifExists(){return new e({...this.#e,node:RE.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new e({...this.#e,node:RE.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Sj=class e{#e;constructor(e){this.#e=P(e)}ifExists(){return new e({...this.#e,node:zE.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new e({...this.#e,node:zE.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Cj=class e{#e;constructor(e){this.#e=P(e)}temporary(){return new e({...this.#e,node:BE.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new e({...this.#e,node:BE.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new e({...this.#e,node:BE.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},wj=class{#e=new hj;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}},Tj=class e{#e;constructor(e){this.#e=P(e)}temporary(){return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{orReplace:!0})})}columns(t){return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{columns:t.map(SD)})})}as(t){let n=t.withPlugin(new wj).toOperationNode();return new e({...this.#e,node:Ae.cloneWith(this.#e.node,{as:n})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Ej=P({is(e){return e.kind===`DropViewNode`},create(e){return P({kind:`DropViewNode`,name:Ce.create(e)})},cloneWith(e,t){return P({...e,...t})}}),Dj=class e{#e;constructor(e){this.#e=P(e)}materialized(){return new e({...this.#e,node:Ej.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new e({...this.#e,node:Ej.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new e({...this.#e,node:Ej.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Oj=P({is(e){return e.kind===`CreateTypeNode`},create(e){return P({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return P({...e,enum:OD.create(t.map(kD.createImmediate))})}}),kj=class e{#e;constructor(e){this.#e=P(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(t){return new e({...this.#e,node:Oj.cloneWithEnum(this.#e.node,t)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Aj=P({is(e){return e.kind===`DropTypeNode`},create(e){return Array.isArray(e)||(e=[e]),P({kind:`DropTypeNode`,name:e[0],additionalNames:e.slice(1)})},cloneWith(e,t){return P({...e,...t})}}),jj=class e{#e;constructor(e){this.#e=P(e)}ifExists(){return new e({...this.#e,node:Aj.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new e({...this.#e,node:Aj.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function Mj(e){if(e.includes(`.`)){let t=e.split(`.`).map(Pj);if(t.length===2)return Ce.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return Ce.create(e)}function Nj(e){return Array.isArray(e)||(e=[e]),e.map(Mj)}function Pj(e){return e.trim()}var Fj=P({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return P({kind:`RefreshMaterializedViewNode`,name:Ce.create(e)})},cloneWith(e,t){return P({...e,...t})}}),Ij=class e{#e;constructor(e){this.#e=P(e)}concurrently(){return new e({...this.#e,node:Fj.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new e({...this.#e,node:Fj.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new e({...this.#e,node:Fj.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Lj=P({is(e){return e.kind===`AlterTypeNode`},create(e){return P({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return P({...e,...t})}}),Rj=P({is(e){return e.kind===`AddValueNode`},create(e){return P({kind:`AddValueNode`,value:e})},cloneWith(e,t){return P({...e,...t})}}),zj=class{#e;constructor(e){this.#e=P(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){return await this.#e.executor.executeQuery(this.compile(),e)}},Bj,Vj=class extends zj{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Bj({...this.#e,node:Lj.cloneWith(this.#e.node,{addValue:Rj.cloneWith(this.#e.node.addValue,{ifNotExists:!0})})})}before(e){return this.#t(e,!0)}after(e){return this.#t(e,!1)}#t(e,t){return new Bj({...this.#e,node:Lj.cloneWith(this.#e.node,{addValue:Rj.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:kD.createImmediate(e)})})})}};Bj=Vj;var Hj=P({is(e){return e.kind===`RenameValueNode`},create(e,t){return P({kind:`RenameValueNode`,oldValue:e,newValue:t})}}),Uj=class{#e;constructor(e){this.#e=P(e)}addValue(e){return new Vj({...this.#e,node:Lj.cloneWith(this.#e.node,{addValue:Rj.create(kD.createImmediate(e))})})}renameTo(e){return new zj({...this.#e,node:Lj.cloneWith(this.#e.node,{renameTo:Te.create(e)})})}renameValue(e,t){return new zj({...this.#e,node:Lj.cloneWith(this.#e.node,{renameValue:Hj.create(kD.createImmediate(e),kD.createImmediate(t))})})}setSchema(e){return new zj({...this.#e,node:Lj.cloneWith(this.#e.node,{setSchema:Te.create(e)})})}},Wj=class e{#e;constructor(e){this.#e=e}createTable(e){return new bj({queryId:Z(),executor:this.#e,node:Me.create(MA(e))})}dropTable(e){return new Cj({queryId:Z(),executor:this.#e,node:BE.create(MA(e))})}createIndex(e){return new gj({queryId:Z(),executor:this.#e,node:IE.create(e)})}dropIndex(e){return new xj({queryId:Z(),executor:this.#e,node:RE.create(e)})}createSchema(e){return new _j({queryId:Z(),executor:this.#e,node:LE.create(e)})}dropSchema(e){return new Sj({queryId:Z(),executor:this.#e,node:zE.create(e)})}alterTable(e){return new pj({queryId:Z(),executor:this.#e,node:FE.create(MA(e))})}createView(e){return new Tj({queryId:Z(),executor:this.#e,node:Ae.create(e)})}refreshMaterializedView(e){return new Ij({queryId:Z(),executor:this.#e,node:Fj.create(e)})}dropView(e){return new Dj({queryId:Z(),executor:this.#e,node:Ej.create(e)})}createType(e){return new kj({queryId:Z(),executor:this.#e,node:Oj.create(Mj(e))})}alterType(e){return new Uj({executor:this.#e,node:Lj.create(Mj(e)),queryId:Z()})}dropType(e){return new jj({queryId:Z(),executor:this.#e,node:Aj.create(Nj(e))})}withPlugin(t){return new e(this.#e.withPlugin(t))}withoutPlugins(){return new e(this.#e.withoutPlugins())}withSchema(t){return new e(this.#e.withPluginAtFront(new sk(t)))}},Gj=class{ref(e){return new tD(e)}table(e){return new EA(e)}},Kj=class{#e;constructor(e){this.#e=e}async provideConnection(e,t){let n=await this.#e.acquireConnection(t);try{return await e(n)}finally{await this.#e.releaseConnection(n,t)}}},qj=class e extends Sk{#e;#t;#n;constructor(e,t,n,r=[]){super(r),this.#e=e,this.#t=t,this.#n=n}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#n.provideConnection(e,t)}withPlugins(t){return new e(this.#e,this.#t,this.#n,[...this.plugins,...t])}withPlugin(t){return new e(this.#e,this.#t,this.#n,[...this.plugins,t])}withPluginAtFront(t){return new e(this.#e,this.#t,this.#n,[t,...this.plugins])}withConnectionProvider(t){return new e(this.#e,this.#t,t,[...this.plugins])}withoutPlugins(){return new e(this.#e,this.#t,this.#n,[])}};function Jj(){return typeof performance<`u`&&pe(performance.now)?performance.now():Date.now()}var Yj=class{#e;#t;async obtainLock(){for(;this.#e;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}releaseLock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},Xj=class{#e;#t;#n;#r;#i;#a=new WeakSet;#o;constructor(e,t,n){this.#e=e,this.#r=!1,this.#t=n,t.supportsMultipleConnections===!1&&(this.#o=new Yj)}async init(e){if(this.#i)throw Error(`driver has already been destroyed`);this.#n??=this.#e.init(e).then(()=>{this.#r=!0}).catch(e=>{throw this.#n=void 0,e}),await vk(this.#n,e?.signal,`init`)}async acquireConnection(e){if(this.#i)throw Error(`driver has already been destroyed`);if(this.#r||await this.init(e),this.#o){let t=this.#o.obtainLock();await vk(t,e?.signal,`acquireConnection:mutex`,()=>t.then(()=>this.#o?.releaseLock()))}let t=this.#e.acquireConnection(e),n=await vk(t,e?.signal,`acquireConnection:acquire`,()=>t?.then(e=>this.releaseConnection(e).catch(yk(`driver.releaseConnection`))).catch(yk(`driver.acquireConnection`)));return this.#a.has(n)||(this.#s()&&this.#c(n),this.#a.add(n)),n}async releaseConnection(e,t){await this.#e.releaseConnection(e,t),this.#o?.releaseLock()}async beginTransaction(e,t){return await this.#e.beginTransaction(e,t)}async commitTransaction(e){return await this.#e.commitTransaction(e)}async rollbackTransaction(e){return await this.#e.rollbackTransaction(e)}async savepoint(e,t,n){if(this.#e.savepoint)return await this.#e.savepoint(e,t,n);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(e,t,n){if(this.#e.rollbackToSavepoint)return await this.#e.rollbackToSavepoint(e,t,n);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(e,t,n){if(this.#e.releaseSavepoint)return await this.#e.releaseSavepoint(e,t,n);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(e){this.#n&&(await vk(this.#n,e?.signal,`destroy:initPromise`),this.#i??=this.#e.destroy(e).catch(e=>{throw this.#i=void 0,e}),await vk(this.#i,e?.signal,`destroy`))}#s(){return this.#t.isLevelEnabled(`query`)||this.#t.isLevelEnabled(`error`)}#c(e){let t=e.executeQuery,n=e.streamQuery,r=this;e.executeQuery=async(n,i)=>{let a,o=Jj();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,o),e}finally{a||await r.#u(n,o)}},e.streamQuery=async function*(t,i,a){let o,s=Jj();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw o=e,await r.#l(e,t,s),e}finally{o||await r.#u(t,s,!0)}}}async#l(e,t,n){await this.#t.error(()=>({level:`error`,error:e,query:t,queryDurationMillis:this.#d(n)}))}async#u(e,t,n=!1){await this.#t.query(()=>({level:`query`,isStream:n,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return Jj()-e}},Zj=()=>{},Qj=class{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(Zj);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}},$j=[`read only`,`read write`],eM=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function tM(e){if(e.accessMode&&!$j.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!eM.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}P([`query`,`error`]);var nM=class{#e;#t;constructor(e){pe(e)?(this.#t=e,this.#e=P({query:!0,error:!0})):(this.#t=rM,this.#e=P({query:e.includes(`query`),error:e.includes(`error`)}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}};function rM(e){if(e.level===`query`){let t=`kysely:query:${e.isStream?`stream:`:``}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else e.level===`error`&&(e.error instanceof Error?console.error(`kysely:error: ${e.error.stack??e.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`))}function iM(e){return he(e)&&pe(e.compile)}Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);var aM=class e extends kk{#e;constructor(e){let t,n;if(sM(e))t={executor:e.executor},n={...e};else{let r=e.dialect,i=r.createDriver(),a=r.createQueryCompiler(),o=r.createAdapter(),s=new Xj(i,o,new nM(e.log??[])),c=new qj(a,o,new Kj(s),e.plugins??[]);t={executor:c},n={config:e,executor:c,dialect:r,driver:s}}super(t),this.#e=P(n)}get schema(){return new Wj(this.#e.executor)}get dynamic(){return new Gj}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new aA({node:iA.create(De(e)?void 0:CA(e))})}get fn(){return tA()}transaction(){return new lM({...this.#e})}startTransaction(){return new uM({...this.#e})}connection(){return new cM({...this.#e})}withPlugin(t){return new e({...this.#e,executor:this.#e.executor.withPlugin(t)})}withoutPlugins(){return new e({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(t){return new e({...this.#e,executor:this.#e.executor.withPluginAtFront(new sk(t))})}$extendTables(){return new e({...this.#e})}$omitTables(){return new e({...this.#e})}$pickTables(){return new e({...this.#e})}withTables(){return this.$extendTables()}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}async executeQuery(e,t){let n=iM(e)?e.compile():e;return await this.#e.executor.executeQuery(n,t)}async[Symbol.asyncDispose](){await this.destroy()}},oM=class e extends aM{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw Error(`calling the transaction method for a Transaction is not supported`)}startTransaction(){throw Error(`calling the controlled transaction method for a Transaction is not supported`)}connection(){throw Error(`calling the connection method for a Transaction is not supported`)}destroy(){throw Error(`calling the destroy method for a Transaction is not supported`)}withPlugin(t){return new e({...this.#e,executor:this.#e.executor.withPlugin(t)})}withoutPlugins(){return new e({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(t){return new e({...this.#e,executor:this.#e.executor.withPluginAtFront(new sk(t))})}withTables(){return new e({...this.#e})}$extendTables(){return new e({...this.#e})}$omitTables(){return new e({...this.#e})}$pickTables(){return new e({...this.#e})}};function sM(e){return he(e)&&he(e.config)&&he(e.driver)&&he(e.executor)&&he(e.dialect)}var cM=class{#e;constructor(e){this.#e=P(e)}async execute(e,t){return this.#e.executor.provideConnection(async t=>{let n=this.#e.executor.withConnectionProvider(new Qj(t));return await e(new aM({...this.#e,executor:n}))},P({signal:t?.signal}))}},lM=class e{#e;constructor(e){this.#e=P(e)}setAccessMode(t){return new e({...this.#e,accessMode:t})}setIsolationLevel(t){return new e({...this.#e,isolationLevel:t})}async execute(e){let{isolationLevel:t,accessMode:n,...r}=this.#e,i={isolationLevel:t,accessMode:n};return tM(i),this.#e.executor.provideConnection(async t=>{let n={isCommitted:!1,isRolledBack:!1},a=new mM(this.#e.executor.withConnectionProvider(new Qj(t)),n),o=new oM({...r,executor:a}),s=!1;try{await this.#e.driver.beginTransaction(t,i),s=!0;let r=await e(o);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw s&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},uM=class e{#e;constructor(e){this.#e=P(e)}setAccessMode(t){return new e({...this.#e,accessMode:t})}setIsolationLevel(t){return new e({...this.#e,isolationLevel:t})}async execute(){let{isolationLevel:e,accessMode:t,...n}=this.#e,r={isolationLevel:e,accessMode:t};tM(r);let i=await fk(this.#e.executor);return await this.#e.driver.beginTransaction(i.connection,r),new dM({...n,connection:i,executor:this.#e.executor.withConnectionProvider(new Qj(i.connection))})}},dM=class e extends oM{#e;#t;#n;constructor(e){let t={isCommitted:!1,isRolledBack:!1};e={...e,executor:new mM(e.executor,t)};let{connection:n,...r}=e;super(r),this.#e=P(e),this.#n=t;let i=Z();this.#t=t=>e.executor.compileQuery(t,i)}get isCommitted(){return this.#n.isCommitted}get isRolledBack(){return this.#n.isRolledBack}commit(){return pM(this.#n),new fM(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#n.isCommitted=!0,this.#e.connection.release()})}rollback(){return pM(this.#n),new fM(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#n.isRolledBack=!0,this.#e.connection.release()})}savepoint(t){return pM(this.#n),new fM(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,t,this.#t),new e({...this.#e})))}rollbackToSavepoint(t){return pM(this.#n),new fM(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,t,this.#t),new e({...this.#e})))}releaseSavepoint(t){return pM(this.#n),new fM(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,t,this.#t),new e({...this.#e})))}withPlugin(t){return new e({...this.#e,executor:this.#e.executor.withPlugin(t)})}withoutPlugins(){return new e({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(t){return new e({...this.#e,executor:this.#e.executor.withPluginAtFront(new sk(t))})}withTables(){return new e({...this.#e})}$extendTables(){return new e({...this.#e})}$omitTables(){return new e({...this.#e})}$pickTables(){return new e({...this.#e})}},fM=class{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}};function pM(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var mM=class e{#e;#t;constructor(t,n){this.#e=t instanceof e?t.#e:t,this.#t=n}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#e.provideConnection(e,t)}executeQuery(e,t){return pM(this.#t),this.#e.executeQuery(e,t)}stream(e,t,n){return pM(this.#t),this.#e.stream(e,t,n)}withConnectionProvider(t){return new e(this.#e.withConnectionProvider(t),this.#t)}withPlugin(t){return new e(this.#e.withPlugin(t),this.#t)}withPlugins(t){return new e(this.#e.withPlugins(t),this.#t)}withPluginAtFront(t){return new e(this.#e.withPluginAtFront(t),this.#t)}withoutPlugins(){return new e(this.#e.withoutPlugins(),this.#t)}},hM=class e{#e;constructor(e){this.#e=P(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new _M(this,e)}$castTo(){return new e({...this.#e})}$notNull(){return new e(this.#e)}withPlugin(t){return new e({...this.#e,plugins:this.#e.plugins===void 0?P([t]):P([...this.#e.plugins,t])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e,t){let n=this.#t(e);return n.executeQuery(this.#r(n),t)}#t(e){let t=e===void 0?Ck:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function gM(e){return new hM(e)}var _M=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return VE.create(this.#e.toOperationNode(),UE(this.#t)?this.#t.toOperationNode():Te.create(this.#t))}},$=Object.assign((e,...t)=>gM({queryId:Z(),rawNode:Pe.create(e,t?.map(vM)??[])}),{ref(e){return gM({queryId:Z(),rawNode:Pe.createWithChild(bD(e))})},val(e){return gM({queryId:Z(),rawNode:Pe.createWithChild(jD(e))})},table(e){return gM({queryId:Z(),rawNode:Pe.createWithChild(MA(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,gM({queryId:Z(),rawNode:Pe.create(t,e.map(Te.create))})},lit(e){return gM({queryId:Z(),rawNode:Pe.createWithChild(kD.createImmediate(e))})},raw(e){return gM({queryId:Z(),rawNode:Pe.createWithSql(e)})},join(e,t=$`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=vM(e[t]),t!==e.length-1&&(n[2*t+1]=r);return gM({queryId:Z(),rawNode:Pe.createWithChildren(n)})}});function vM(e){return UE(e)?e.toOperationNode():jD(e)}var yM=P({raw(e,t=[]){return P({sql:e,query:Pe.createWithSql(e),parameters:P(t),queryId:Z()})}}),bM=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function xM(e,t){return Pe.createWithChildren([Pe.createWithSql(`${e} `),Te.create(t)])}var SM=class{#e;#t;#n;constructor(e){this.#e=P({...e})}async init(e){this.#t=pe(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new CM(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(yM.raw(`begin`))}async commitTransaction(e){await e.executeQuery(yM.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(yM.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(xM(`savepoint`,t),Z()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(xM(`rollback to`,t),Z()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(xM(`release`,t),Z()))}async releaseConnection(){}async destroy(){this.#t?.close()}},CM=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!aO.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}},wM=/"/g,TM=/[\\'"]/g,EM=class extends Fe{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(wM,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(TM,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}},DM=`kysely_migration`,OM=`kysely_migration_lock`;P({__noMigrations__:!0});var kM=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,DM).where(`name`,`!=`,OM)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,$`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},AM=class extends bM{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},jM=class{#e;constructor(e){this.#e=P({...e})}createDriver(){return new SM(this.#e)}createQueryCompiler(){return new EM}createAdapter(){return new AM}createIntrospector(e){return new kM(e)}};function MM(e,t){if(NM(e)&&t.stack){let n=t.stack.split(`
|
|
496
|
-
`).slice(1).join(`
|
|
497
|
-
`);return e.stack+=`\n${n}`,e}return e}function NM(e){return he(e)&&ge(e.stack)}var PM=Symbol(),FM=class{#e;#t=new WeakMap;#n;constructor(e){this.#e=P({...e})}async init(e){this.#n=pe(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#r(),n=this.#t.get(t);return n||(n=new LM(t,this.#e.controlConnection),this.#t.set(t,n),this.#e?.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e?.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let n=[];t.isolationLevel&&n.push(`isolation level ${t.isolationLevel}`),t.accessMode&&n.push(t.accessMode);let r=`set transaction ${n.join(`, `)}`;await e.executeQuery(yM.raw(r))}await e.executeQuery(yM.raw(`begin`))}async commitTransaction(e){await e.executeQuery(yM.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(yM.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(xM(`savepoint`,t),Z()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(xM(`rollback to`,t),Z()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(xM(`release savepoint`,t),Z()))}async releaseConnection(e){e[PM]()}async destroy(){return new Promise((e,t)=>{this.#n.end(n=>{n?t(n):e()})})}async#r(){return new Promise((e,t)=>{this.#n.getConnection(async(n,r)=>{n?t(n):e(r)})})}};function IM(e){return he(e)&&`insertId`in e&&`affectedRows`in e}var LM=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){await this.#a(`kill query ${this.#n}`,e)}async collectSessionInfo(){if(this.#n)return;let{threadId:e}=this.#e;if(e!=null)this.#n=e;else{let[{cid:e}]=await this.#i(yM.raw(`select connection_id() as cid`));this.#n=Number(e)}}async executeQuery(e){try{this.#r=e.queryId;let t=await this.#i(e);if(!IM(t))return{rows:Array.isArray(t)?t:[]};let{insertId:n,affectedRows:r,changedRows:i}=t;return{insertId:n!=null&&n.toString()!==`0`?BigInt(n):void 0,numAffectedRows:r==null?void 0:BigInt(r),numChangedRows:i==null?void 0:BigInt(i),rows:[]}}catch(e){throw MM(e,Error())}finally{this.#r=void 0}}async killSession(e){try{this.#e.destroy()}catch{}await this.#a(`kill connection ${this.#n}`,e)}async*streamQuery(e,t){this.#r=e.queryId;let n=this.#e.query(e.sql,e.parameters).stream({objectMode:!0});try{for await(let e of n)yield{rows:[e]}}catch(e){if(he(e)&&`code`in e&&e.code===`ERR_STREAM_PREMATURE_CLOSE`)return;throw e}finally{this.#r=void 0}}[PM](){this.#e.release()}#i(e){return new Promise((t,n)=>{this.#e.query(e.sql,e.parameters,(e,r)=>{e?n(e):t(r)})})}async#a(e,t){if(!this.#r)return;let{config:n}=this.#e,r=this.#r;if(!this.#t||!n)return await t(async t=>{r.queryId===this.#r?.queryId&&await t.executeQuery(yM.raw(e,[]))});let{clientFlags:i,maxPacketSize:a,...o}=n,s=this.#t(o);try{await new Promise((t,n)=>{s.connect(i=>{if(i)return n(i);if(r.queryId!==this.#r?.queryId)return t();s.query(e,[],e=>{if(e)return n(e);t()})})})}finally{s.destroy()}}},RM=/[\\']/g,zM=/`/g,BM=/[\\'"]/g,VM=class extends Fe{getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getExplainOptionAssignment(){return`=`}getExplainOptionsDelimiter(){return` `}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return zM.source}getRightIdentifierWrapper(){return zM.source}sanitizeIdentifier(e){return e.replace(zM,"``")}sanitizeStringLiteral(e){return e.replace(RM,e=>e===`\\`?`\\\\`:`''`)}sanitizeJSONPathMemberValue(e){return e.replace(BM,e=>e===`\\`?`\\\\\\\\`:e===`'`?`''`:`\\\\"`)}visitCreateIndex(e){this.append(`create `),e.unique&&this.append(`unique `),this.append(`index `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),e.using&&(this.append(` using `),this.visitNode(e.using)),e.table&&(this.append(` on `),this.visitNode(e.table)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.where&&(this.append(` `),this.visitNode(e.where))}},HM=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`information_schema.schemata`).select(`schema_name`).$castTo().execute()).map(e=>({name:e.SCHEMA_NAME}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`information_schema.columns as columns`).innerJoin(`information_schema.tables as tables`,e=>e.onRef(`columns.TABLE_CATALOG`,`=`,`tables.TABLE_CATALOG`).onRef(`columns.TABLE_SCHEMA`,`=`,`tables.TABLE_SCHEMA`).onRef(`columns.TABLE_NAME`,`=`,`tables.TABLE_NAME`)).select([`columns.COLUMN_NAME`,`columns.COLUMN_DEFAULT`,`columns.TABLE_NAME`,`columns.TABLE_SCHEMA`,`tables.TABLE_TYPE`,`tables.ENGINE`,`columns.IS_NULLABLE`,`columns.DATA_TYPE`,`columns.EXTRA`,`columns.COLUMN_COMMENT`]).where(`columns.TABLE_SCHEMA`,`=`,$`database()`).orderBy(`columns.TABLE_NAME`).orderBy(`columns.ORDINAL_POSITION`).$castTo();e.withInternalKyselyTables||(t=t.where(`columns.TABLE_NAME`,`!=`,DM).where(`columns.TABLE_NAME`,`!=`,OM));let n=await t.execute();return this.#t(n)}#t(e){return e.reduce((e,t)=>{let n=e.find(e=>e.name===t.TABLE_NAME);return n||(n=P({name:t.TABLE_NAME,isView:t.TABLE_TYPE===`VIEW`,isForeign:t.ENGINE===`FEDERATED`,schema:t.TABLE_SCHEMA,columns:[]}),e.push(n)),n.columns.push(P({name:t.COLUMN_NAME,dataType:t.DATA_TYPE,isNullable:t.IS_NULLABLE===`YES`,isAutoIncrementing:t.EXTRA.toLowerCase().includes(`auto_increment`),hasDefaultValue:t.COLUMN_DEFAULT!==null,comment:t.COLUMN_COMMENT===``?void 0:t.COLUMN_COMMENT})),e},[])}},UM=`ea586330-2c93-47c8-908d-981d9d270f9d`,WM=3600,GM=class extends bM{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(e,t){await $`select get_lock(${$.lit(UM)}, ${$.lit(WM)})`.execute(e)}async releaseMigrationLock(e,t){await $`select release_lock(${$.lit(UM)})`.execute(e)}},KM=class{#e;constructor(e){this.#e=e}createDriver(){return new FM(this.#e)}createQueryCompiler(){return new VM}createAdapter(){return new GM}createIntrospector(e){return new HM(e)}},qM=Symbol(),JM=class{#e;#t=new WeakMap;#n;constructor(e){this.#e=P({...e})}async init(e){this.#n=pe(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect(),n=this.#t.get(t);return n||(n=new YM(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(yM.raw(n))}async commitTransaction(e){await e.executeQuery(yM.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(yM.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(xM(`savepoint`,t),Z()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(xM(`rollback to`,t),Z()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(xM(`release`,t),Z()))}async releaseConnection(e){e[qM]()}async destroy(){if(this.#n){let e=this.#n;this.#n=void 0,await e.end()}}},YM=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){return await this.#i(`select pg_cancel_backend(${this.#r})`,e)}async collectSessionInfo(){if(this.#r)return;let{processID:e}=this.#e;if(e)this.#r=e;else{let{rows:[{pid:e}]}=await this.#e.query(`select pg_backend_pid() as pid`,[]);this.#r=Number(e)}}async executeQuery(e){try{this.#n=e.queryId;let{command:t,rowCount:n,rows:r}=await this.#e.query(e.sql,e.parameters);return{numAffectedRows:t===`INSERT`||t===`UPDATE`||t===`DELETE`||t===`MERGE`?BigInt(n):void 0,rows:r??[]}}catch(e){throw MM(e,Error())}finally{this.#n=void 0}}async killSession(e){return await this.#i(`select pg_terminate_backend(${this.#r})`,e)}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#n=e.queryId;let n=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{for(;;){let e=await n.read(t);if(e.length===0)break;yield{rows:e}}}finally{await n.close(),this.#n=void 0}}[qM](){this.#e.release()}async#i(e,t){if(!this.#n)return;let{controlClient:n,poolOptions:r}=this.#t,i=this.#n;if(!n)return await t(async t=>{i.queryId===this.#n?.queryId&&await t.executeQuery(yM.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},XM=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,$`col_description(a.attrelid, a.attnum)`.as(`column_description`),$`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where($`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,DM).where(`c.relname`,`!=`,OM));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.schema);e||(e=new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=P({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(P({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}},ZM=/"/g,QM=class extends Fe{sanitizeIdentifier(e){return e.replace(ZM,`""`)}},$M=BigInt(`3853314791062309107`),eN=36e5,tN=class extends bM{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await $`
|
|
498
|
-
with set_timeout as (
|
|
499
|
-
select set_config('lock_timeout', '${$.lit(eN)}', true) as config_val
|
|
500
|
-
)
|
|
501
|
-
select pg_advisory_lock(${$.lit($M)})
|
|
502
|
-
from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await $`select pg_advisory_unlock(${$.lit($M)})`.execute(e)}},nN=class{#e;constructor(e){this.#e=e}createDriver(){return new JM(this.#e)}createQueryCompiler(){return new QM}createAdapter(){return new tN}createIntrospector(e){return new XM(e)}},rN=`dbo`,iN=class extends bM{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(e,t){await $`exec sp_getapplock @DbPrincipal = ${$.lit(rN)}, @Resource = ${$.lit(DM)}, @LockMode = ${$.lit(`Exclusive`)}, @LockOwner = ${$.lit(`Session`)}`.execute(e)}async releaseMigrationLock(e,t){await $`exec sp_releaseapplock @DbPrincipal = ${$.lit(rN)}, @Resource = ${$.lit(DM)}, @LockOwner = ${$.lit(`Session`)}`.execute(e)}},aN=Symbol(),oN=Symbol(),sN=Symbol(),cN=class{#e;#t;constructor(e){this.#e=P({...e});let{tarn:t,tedious:n,validateConnections:r}=this.#e;this.#t=new t.Pool({...t.options,create:async()=>await new lN(await n.connectionFactory(),n).connect(),destroy:async e=>{await e[oN]()},validate:r===!1?void 0:e=>e[sN]()})}async init(){}async acquireConnection(){return await this.#t.acquire().promise}async beginTransaction(e,t){await e.beginTransaction(t)}async commitTransaction(e){await e.commitTransaction()}async rollbackTransaction(e){await e.rollbackTransaction()}async savepoint(e,t){await e.savepoint(t)}async rollbackToSavepoint(e,t){await e.rollbackTransaction(t)}async releaseConnection(e){this.#e.resetConnectionsOnRelease&&await e[aN](),this.#t.release(e)}async destroy(){await this.#t.destroy()}},lN=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=!1,this.#n=t}async beginTransaction(e){let{isolationLevel:t}=e;await new Promise((e,n)=>this.#e.beginTransaction(t=>{t?n(t):e(void 0)},t?QO(8):void 0,t?this.#i(t):void 0))}async cancelQuery(){if(this.#r)return new Promise(e=>{this.#r?.request.once(`requestCompleted`,e),this.#e.cancel()||(this.#r?.request.off(`requestCompleted`,e),e())})}async commitTransaction(){await new Promise((e,t)=>this.#e.commitTransaction(n=>{n?t(n):e(void 0)}))}async connect(){let{promise:e,reject:t,resolve:n}=new dk;this.#e.connect(e=>{if(e)return t(e);n()}),this.#e.on(`error`,e=>{e instanceof Error&&`code`in e&&e.code===`ESOCKET`&&(this.#t=!0),console.error(e),t(e)});function r(){t(Error(`The connection ended without ever completing the connection`))}return this.#e.once(`end`,r),await e,this.#e.off(`end`,r),this}async executeQuery(e){try{let t=new dk;this.#r=new uN({compiledQuery:e,tedious:this.#n,onDone:t}),this.#e.execSql(this.#r.request);let{rowCount:n,rows:r}=await t.promise;return{numAffectedRows:n===void 0?void 0:BigInt(n),rows:r}}catch(e){throw MM(e,Error())}finally{this.#r=void 0}}async rollbackTransaction(e){await new Promise((t,n)=>this.#e.rollbackTransaction(e=>{e?n(e):t(void 0)},e))}async savepoint(e){await new Promise((t,n)=>this.#e.saveTransaction(e=>{e?n(e):t(void 0)},e))}async*streamQuery(e,t){this.#r=new uN({compiledQuery:e,streamChunkSize:t,tedious:this.#n}),this.#e.execSql(this.#r.request);try{for(;;){let e=await this.#r.readChunk();if(e.length===0||(yield{rows:e},e.length<t))break}}finally{await this.cancelQuery(),this.#r=void 0}}#i(e){let{ISOLATION_LEVEL:t}=this.#n,n={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[e];if(n===void 0)throw Error(`Unknown isolation level: ${e}`);return n}[oN](){return`closed`in this.#e&&this.#e.closed?Promise.resolve():new Promise(e=>{this.#e.once(`end`,e),this.#e.close()})}async[aN](){await new Promise((e,t)=>{this.#e.reset(n=>{if(n)return t(n);e()})})}async[sN](){if(this.#t||this.#a())return!1;try{let e=new dk,t=new uN({compiledQuery:yM.raw(`select 1`),onDone:e,tedious:this.#n});return this.#e.execSql(t.request),await e.promise,!0}catch{return!1}}#a(){return`closed`in this.#e&&!!this.#e.closed}},uN=class{#e;#t;#n;#r;#i;#a;constructor(e){let{compiledQuery:t,onDone:n,streamChunkSize:r,tedious:i}=e;if(this.#t=[],this.#n=r,this.#r={},this.#i=i,n){let e=`onDone`;this.#r[e]=(t,r)=>{if(t!==`chunkReady`){if(delete this.#r[e],t===`error`)return n.reject(r);n.resolve({rowCount:this.#a,rows:this.#t})}}}this.#e=new this.#i.Request(t.sql,(e,t)=>{if(e)return Object.values(this.#r).forEach(t=>t(`error`,e instanceof AggregateError?e.errors:e));this.#a=t}),this.#o(t.parameters),this.#s()}get request(){return this.#e}readChunk(){let e=this.readChunk.name;return new Promise((t,n)=>{this.#r[e]=(r,i)=>{if(delete this.#r[e],r===`error`)return n(i);t(this.#t.splice(0,this.#n))},this.#e.resume()})}#o(e){for(let t=0;t<e.length;t++){let n=e[t];this.#e.addParameter(String(t+1),this.#c(n),n)}}#s(){let e=this.#n?()=>{this.#n<=this.#t.length&&(this.#e.pause(),Object.values(this.#r).forEach(e=>e(`chunkReady`)))}:()=>{},t=t=>{let n={};for(let e of t)n[e.metadata.colName]=e.value;this.#t.push(n),e()};this.#e.on(`row`,t),this.#e.once(`requestCompleted`,()=>{Object.values(this.#r).forEach(e=>e(`completed`)),this.#e.off(`row`,t)})}#c(e){return Re(e)||De(e)||ge(e)?this.#i.TYPES.NVarChar:Be(e)||ve(e)&&e%1==0?e<-2147483648||e>2147483647?this.#i.TYPES.BigInt:this.#i.TYPES.Int:ve(e)?this.#i.TYPES.Float:be(e)?this.#i.TYPES.Bit:_e(e)?this.#i.TYPES.DateTime:ze(e)?this.#i.TYPES.VarBinary:this.#i.TYPES.NVarChar}},dN=class{#e;constructor(e){this.#e=e}async getSchemas(){return await this.#e.selectFrom(`sys.schemas`).select(`name`).execute()}async getTables(e={withInternalKyselyTables:!1}){let t=await this.#e.selectFrom(`sys.tables as tables`).leftJoin(`sys.schemas as table_schemas`,`table_schemas.schema_id`,`tables.schema_id`).innerJoin(`sys.columns as columns`,`columns.object_id`,`tables.object_id`).innerJoin(`sys.types as types`,`types.user_type_id`,`columns.user_type_id`).leftJoin(`sys.schemas as type_schemas`,`type_schemas.schema_id`,`types.schema_id`).leftJoin(`sys.extended_properties as comments`,e=>e.onRef(`comments.major_id`,`=`,`tables.object_id`).onRef(`comments.minor_id`,`=`,`columns.column_id`).on(`comments.name`,`=`,`MS_Description`)).$if(!e.withInternalKyselyTables,e=>e.where(`tables.name`,`!=`,DM).where(`tables.name`,`!=`,OM)).select([`tables.name as table_name`,e=>e.ref(`tables.type`).$castTo().as(`table_type`),`table_schemas.name as table_schema_name`,`columns.default_object_id as column_default_object_id`,`columns.generated_always_type_desc as column_generated_always_type`,`columns.is_computed as column_is_computed`,`columns.is_identity as column_is_identity`,`columns.is_nullable as column_is_nullable`,`columns.is_rowguidcol as column_is_rowguidcol`,`columns.name as column_name`,`types.is_nullable as type_is_nullable`,`types.name as type_name`,`type_schemas.name as type_schema_name`,`comments.value as column_comment`]).unionAll(this.#e.selectFrom(`sys.views as views`).leftJoin(`sys.schemas as view_schemas`,`view_schemas.schema_id`,`views.schema_id`).innerJoin(`sys.columns as columns`,`columns.object_id`,`views.object_id`).innerJoin(`sys.types as types`,`types.user_type_id`,`columns.user_type_id`).leftJoin(`sys.schemas as type_schemas`,`type_schemas.schema_id`,`types.schema_id`).leftJoin(`sys.extended_properties as comments`,e=>e.onRef(`comments.major_id`,`=`,`views.object_id`).onRef(`comments.minor_id`,`=`,`columns.column_id`).on(`comments.name`,`=`,`MS_Description`)).select([`views.name as table_name`,`views.type as table_type`,`view_schemas.name as table_schema_name`,`columns.default_object_id as column_default_object_id`,`columns.generated_always_type_desc as column_generated_always_type`,`columns.is_computed as column_is_computed`,`columns.is_identity as column_is_identity`,`columns.is_nullable as column_is_nullable`,`columns.is_rowguidcol as column_is_rowguidcol`,`columns.name as column_name`,`types.is_nullable as type_is_nullable`,`types.name as type_name`,`type_schemas.name as type_schema_name`,`comments.value as column_comment`])).orderBy(`table_schema_name`).orderBy(`table_name`).orderBy(`column_name`).execute(),n={};for(let e of t){let t=`${e.table_schema_name}.${e.table_name}`;(n[t]=n[t]||P({columns:[],isForeign:!1,isView:e.table_type===`V `,name:e.table_name,schema:e.table_schema_name??void 0})).columns.push(P({dataType:e.type_name,dataTypeSchema:e.type_schema_name??void 0,hasDefaultValue:e.column_default_object_id>0||e.column_generated_always_type!==`NOT_APPLICABLE`||e.column_is_identity||e.column_is_computed||e.column_is_rowguidcol,isAutoIncrementing:e.column_is_identity,isNullable:e.column_is_nullable&&e.type_is_nullable,name:e.column_name,comment:e.column_comment??void 0}))}return Object.values(n)}},fN=/^[a-z0-9_]$/i,pN=class extends Fe{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(e){super.visitOffset(e),this.append(` rows`)}compileColumnAlterations(e){let t={};for(let n of e)t[n.kind]||(t[n.kind]=[]),t[n.kind].push(n);let n=!0;t.AddColumnNode&&(this.append(`add `),this.compileList(t.AddColumnNode),n=!1),t.AlterColumnNode&&(n||this.append(`, `),this.compileList(t.AlterColumnNode)),t.DropColumnNode&&(n||this.append(`, `),this.append(`drop `),this.compileList(t.DropColumnNode),n=!1),t.ModifyColumnNode&&(n||this.append(`, `),this.compileList(t.ModifyColumnNode)),t.RenameColumnNode&&(n||this.append(`, `),this.compileList(t.RenameColumnNode))}visitAddColumn(e){this.visitNode(e.column)}visitDropColumn(e){this.append(`column `),e.ifExists&&this.append(`if exists `),this.visitNode(e.column)}visitMergeQuery(e){super.visitMergeQuery(e),this.append(`;`)}visitCollate(e){this.append(`collate `);let{name:t}=e.collation;for(let e of t)if(!fN.test(e))throw Error(`Invalid collation: ${t}`);this.append(t)}announcesNewColumnDataType(){return!1}},mN=class{#e;constructor(e){this.#e=e}createDriver(){return new cN(this.#e)}createQueryCompiler(){return new pN}createAdapter(){return new iN}createIntrospector(e){return new dN(e)}};function hN(e){return e.charAt(0).toUpperCase()+e.slice(1)}var gN=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,_N=/['\u2019]/g;function vN(e){return e.replace(_N,``).match(gN)??[]}function yN(e){return vN(e).map(e=>e.toLowerCase()).join(`-`)}function bN(e){if(!e)return null;if(`dialect`in e)return bN(e.dialect);if(`createDriver`in e){if(e instanceof jM)return`sqlite`;if(e instanceof KM)return`mysql`;if(e instanceof nN)return`postgres`;if(e instanceof mN)return`mssql`}return`aggregate`in e?`sqlite`:`getConnection`in e?`mysql`:`connect`in e?`postgres`:`fileControl`in e||`open`in e&&`close`in e&&`prepare`in e||`batch`in e&&`exec`in e&&`prepare`in e?`sqlite`:null}var xN=async e=>{let t=e.database;if(!t)return{kysely:null,databaseType:null,transaction:void 0};if(`db`in t)return{kysely:t.db,databaseType:t.type,transaction:t.transaction};if(`dialect`in t)return{kysely:new aM({dialect:t.dialect}),databaseType:t.type,transaction:t.transaction};let n,r,i=bN(t);if(`createDriver`in t&&(n=t),`aggregate`in t&&!(`createSession`in t)&&(n=new jM({database:t}),r=!0),`getConnection`in t&&(n=new KM(t),r=!0),`connect`in t&&(n=new nN({pool:t}),r=!0),`fileControl`in t){let{BunSqliteDialect:e}=await f(async()=>{let{BunSqliteDialect:e}=await import(`./bun-sqlite-dialect-C7ftEUSI-CsHdUKBY.js`);return{BunSqliteDialect:e}},__vite__mapDeps([2,3,4]));n=new e({database:t}),r=!0}if(`createSession`in t){let e;try{({DatabaseSync:e}=await f(()=>import(`node:sqlite`),[]))}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code!==`ERR_UNKNOWN_BUILTIN_MODULE`)throw e}if(e&&t instanceof e){let{NodeSqliteDialect:e}=await f(async()=>{let{NodeSqliteDialect:e}=await import(`./node-sqlite-dialect-DJDXH5Ot.js`);return{NodeSqliteDialect:e}},__vite__mapDeps([5,3,4]));n=new e({database:t}),r=!0}}if(`batch`in t&&`exec`in t&&`prepare`in t){let{D1SqliteDialect:e}=await f(async()=>{let{D1SqliteDialect:e}=await import(`./d1-sqlite-dialect-BZmaVTp8-FPCaMZqX.js`);return{D1SqliteDialect:e}},__vite__mapDeps([6,4]));n=new e({database:t}),r=!1}return{kysely:n?new aM({dialect:n}):null,databaseType:i,transaction:r}};function SN(e,t,n){return n===`postgres`?$`${$.ref(e)} ILIKE ${t}`:$`LOWER(${$.ref(e)}) LIKE LOWER(${t})`}function CN(e,t){return{lhs:$`LOWER(${$.ref(e)})`,values:t.map(e=>e.toLowerCase())}}function wN(e,t){return{lhs:$`LOWER(${$.ref(e)})`,values:t.map(e=>e.toLowerCase())}}function TN(e,t){return{lhs:$`LOWER(${$.ref(e)})`,value:t.toLowerCase()}}function EN(e,t){return{lhs:$`LOWER(${$.ref(e)})`,value:t.toLowerCase()}}var DN=(e,t)=>{let n=null,r=!1,i=(e,n=!1)=>({getFieldName:i,schema:a,getDefaultFieldName:o,getDefaultModelName:s,getFieldAttributes:c,getModelName:l,options:u})=>{t?.type===`mysql`&&u.advanced?.database?.generateId===!1&&!r&&(r=!0,g.warn(`[Kysely Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth's default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.`));let d=e=>{let t=[],n=[];if(e)for(let[r,i]of Object.entries(e)){let e=a[s(r)]?.fields,[i,o]=r.includes(`.`)?r.split(`.`):[void 0,r];if(e){e.id={type:`string`};for(let[i,a]of Object.entries(e))t.push($`${$.ref(`join_${o}`)}.${$.ref(a.fieldName||i)} as ${$.ref(`_joined_${o}_${a.fieldName||i}`)}`),n.push({joinModel:r,joinModelRef:o,fieldName:a.fieldName||i})}}return{allSelectsStr:n,allSelects:t}},f=async(r,o,c,l)=>{if(t?.type===`mysql`){if(l.length>0){let t=await o.executeTakeFirst();if(!t||Number(t.numUpdatedRows??0)===0)return null;let n=l.find(e=>e.field===`id`&&(e.operator===void 0||e.operator===`eq`)&&e.connector!==`OR`&&e.value!==void 0&&e.value!==null),a,s;if(r.id!==void 0&&r.id!==null)a=`id`,s=r.id;else if(n)a=`id`,s=n.value;else if(l[0]?.field)a=l[0].field,s=r[a]===void 0?l[0].value:r[a];else return null;return await e.selectFrom(c).selectAll().where(i({model:c,field:a}),s===null?`is`:`=`,s).limit(1).executeTakeFirst()}await o.execute();let t=async e=>{if(r.id)return await e.selectFrom(c).selectAll().where(i({model:c,field:`id`}),`=`,r.id).limit(1).executeTakeFirst();if(u.advanced?.database?.generateId===`serial`){let t=(await $`SELECT LAST_INSERT_ID() as id`.execute(e)).rows[0]?.id;if(t)return await e.selectFrom(c).selectAll().where(i({model:c,field:`id`}),`=`,t).limit(1).executeTakeFirst()}let t=a[s(c)]?.fields;if(t)for(let[n,a]of Object.entries(t)){if(!a.unique)continue;let t=i({model:c,field:n}),o=r[t];if(o==null)continue;let s=await e.selectFrom(c).selectAll().where(t,`=`,o).limit(1).executeTakeFirst();if(s)return s}let n=e.selectFrom(c).selectAll(),o=!1;for(let[e,t]of Object.entries(r))t!==void 0&&(n=n.where(e,t===null?`is`:`=`,t),o=!0);if(o){let e=await n.limit(2).execute();if(e.length===1)return e[0]}return g.warn(`[Kysely Adapter] Unable to safely identify the inserted "${c}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return n?t(e):e.transaction().execute(t)}return t?.type===`mssql`?await o.outputAll(`inserted`).executeTakeFirst():await o.returningAll().executeTakeFirst()};function p(e,n){if(!n)return{and:null,or:null};let r={and:[],or:[]};return n.forEach(n=>{let{field:a,value:o,operator:s=`eq`,connector:c=`AND`,mode:l=`sensitive`}=n,u=o,d=i({model:e,field:a}),f=l===`insensitive`&&(typeof u==`string`||Array.isArray(u)&&u.every(e=>typeof e==`string`)),p=n=>{let r=`${e}.${d}`;if(s.toLowerCase()===`in`){if(f){let{lhs:e,values:t}=CN(r,Array.isArray(u)?u:[u]);return n(e,`in`,t)}return n(r,`in`,Array.isArray(u)?u:[u])}if(s.toLowerCase()===`not_in`){if(f){let{lhs:e,values:t}=wN(r,Array.isArray(u)?u:[u]);return n(e,`not in`,t)}return n(r,`not in`,Array.isArray(u)?u:[u])}if(s===`contains`)return f&&typeof u==`string`?SN(r,`%${u}%`,t?.type):n(r,`like`,`%${u}%`);if(s===`starts_with`)return f&&typeof u==`string`?SN(r,`${u}%`,t?.type):n(r,`like`,`${u}%`);if(s===`ends_with`)return f&&typeof u==`string`?SN(r,`%${u}`,t?.type):n(r,`like`,`%${u}`);if(s===`eq`){if(u===null)return n(r,`is`,null);if(f&&typeof u==`string`){let{lhs:e,value:t}=TN(r,u);return n(e,`=`,t)}return n(r,`=`,u)}if(s===`ne`){if(u===null)return n(r,`is not`,null);if(f&&typeof u==`string`){let{lhs:e,value:t}=EN(r,u);return n(e,`<>`,t)}return n(r,`<>`,u)}return s===`gt`?n(r,`>`,u):s===`gte`?n(r,`>=`,u):s===`lt`?n(r,`<`,u):s===`lte`?n(r,`<=`,u):n(r,s,u)};c===`OR`?r.or.push(p):r.and.push(p)}),{and:r.and.length?r.and:null,or:r.or.length?r.or:null}}function m(e,t,n){if(!t||!e.length)return e;let r=new Map;for(let a of e){let e={},o={};for(let[e]of Object.entries(t))o[l(e)]={};for(let[t,r]of Object.entries(a)){let a=String(t),s=!1;for(let{joinModel:e,fieldName:t,joinModelRef:c}of n)if(a===`_joined_${c}_${t}`||a===`_Joined${hN(c)}${hN(t)}`){o[l(e)][i({model:e,field:t})]=r,s=!0;break}s||(e[t]=r)}let s=e.id;if(!s)continue;if(!r.has(s)){let n={...e};for(let[e,r]of Object.entries(t))n[l(e)]=r.relation===`one-to-one`?null:[];r.set(s,n)}let c=r.get(s);for(let[e,n]of Object.entries(t)){let t=n.relation===`one-to-one`,r=n.limit??100,a=o[l(e)],s=a&&Object.keys(a).length>0&&Object.values(a).some(e=>e!=null);if(t)c[l(e)]=s?a:null;else{let t=l(e);if(Array.isArray(c[t])&&s){if(c[t].length>=r)continue;let n=i({model:e,field:`id`}),o=a[n];o?!c[t].some(e=>e[n]===o)&&c[t].length<r&&c[t].push(a):c[t].length<r&&c[t].push(a)}}}}let a=Array.from(r.values());for(let e of a)for(let[n,r]of Object.entries(t))if(r.relation!==`one-to-one`){let t=l(n);if(Array.isArray(e[t])){let n=r.limit??100;e[t].length>n&&(e[t]=e[t].slice(0,n))}}return a}return{async create({data:t,model:n}){return await f(t,e.insertInto(n).values(t),n,[])},async findOne({model:t,where:n,select:r,join:a}){let{and:o,or:s}=p(t,n),c=e.selectFrom(e=>{let n=e.selectFrom(t);return o&&(n=n.where(e=>e.and(o.map(t=>t(e))))),s&&(n=n.where(e=>e.or(s.map(t=>t(e))))),n=r?.length&&r.length>0?n.select(r.map(e=>i({model:t,field:e}))):n.selectAll(),n.as(`primary`)}).selectAll(`primary`);if(a)for(let[e,t]of Object.entries(a)){let[n,r]=e.includes(`.`)?e.split(`.`):[void 0,e];c=c.leftJoin(`${e} as join_${r}`,e=>e.onRef(`join_${r}.${t.on.to}`,`=`,`primary.${t.on.from}`))}let{allSelectsStr:l,allSelects:u}=d(a);c=c.select(u);let f=await c.execute();if(!f||!Array.isArray(f)||f.length===0)return null;let h=f[0];return a?m(f,a,l)[0]:h},async findMany({model:n,where:r,limit:a,select:o,offset:s,sortBy:c,join:l}){let{and:u,or:f}=p(n,r),h=e.selectFrom(e=>{let r=e.selectFrom(n);return t?.type===`mssql`?s===void 0?a!==void 0&&(r=r.top(a)):(c||(r=r.orderBy(i({model:n,field:`id`}))),r=r.offset(s).fetch(a||100)):(a!==void 0&&(r=r.limit(a)),s!==void 0&&(r=r.offset(s))),c?.field&&(r=r.orderBy(`${i({model:n,field:c.field})}`,c.direction)),u&&(r=r.where(e=>e.and(u.map(t=>t(e))))),f&&(r=r.where(e=>e.or(f.map(t=>t(e))))),r=o?.length&&o.length>0?r.select(o.map(e=>i({model:n,field:e}))):r.selectAll(),r.as(`primary`)}).selectAll(`primary`);if(l)for(let[e,t]of Object.entries(l)){let[n,r]=e.includes(`.`)?e.split(`.`):[void 0,e];h=h.leftJoin(`${e} as join_${r}`,e=>e.onRef(`join_${r}.${t.on.to}`,`=`,`primary.${t.on.from}`))}let{allSelectsStr:g,allSelects:_}=d(l);h=h.select(_),c?.field&&(h=h.orderBy(`${i({model:n,field:c.field})}`,c.direction));let v=await h.execute();return v?l?m(v,l,g):v:[]},async update({model:t,where:n,update:r}){if(n.length===0)return null;let{and:i,or:a}=p(t,n),o=e.updateTable(t).set(r);return i&&(o=o.where(e=>e.and(i.map(t=>t(e))))),a&&(o=o.where(e=>e.or(a.map(t=>t(e))))),await f(r,o,t,n)},async updateMany({model:t,where:n,update:r}){let{and:i,or:a}=p(t,n),o=e.updateTable(t).set(r);i&&(o=o.where(e=>e.and(i.map(t=>t(e))))),a&&(o=o.where(e=>e.or(a.map(t=>t(e)))));let s=(await o.executeTakeFirst()).numUpdatedRows;return s>2**53-1?2**53-1:Number(s)},async count({model:t,where:n}){let{and:r,or:i}=p(t,n),a=e.selectFrom(t).select(e.fn.count(`id`).as(`count`));r&&(a=a.where(e=>e.and(r.map(t=>t(e))))),i&&(a=a.where(e=>e.or(i.map(t=>t(e)))));let o=await a.execute();return typeof o[0].count==`number`?o[0].count:typeof o[0].count==`bigint`?Number(o[0].count):parseInt(o[0].count)},async delete({model:t,where:n}){let{and:r,or:i}=p(t,n),a=e.deleteFrom(t);r&&(a=a.where(e=>e.and(r.map(t=>t(e))))),i&&(a=a.where(e=>e.or(i.map(t=>t(e))))),await a.execute()},async deleteMany({model:t,where:n}){let{and:r,or:i}=p(t,n),a=e.deleteFrom(t);r&&(a=a.where(e=>e.and(r.map(t=>t(e))))),i&&(a=a.where(e=>e.or(i.map(t=>t(e)))));let o=(await a.executeTakeFirst()).numDeletedRows;return o>2**53-1?2**53-1:Number(o)},async consumeOne({model:r,where:a}){let{and:o,or:s}=p(r,a),c=e=>(o&&(e=e.where(e=>e.and(o.map(t=>t(e))))),s&&(e=e.where(e=>e.or(s.map(t=>t(e))))),e),l=i({model:r,field:`id`}),u=async(e,n)=>{let i=n[l]??n.id;if(i==null)return null;let a=e.deleteFrom(r).where(`${r}.${l}`,`=`,i);if(t?.type===`mysql`){let e=await a.executeTakeFirst();return Number(e.numDeletedRows)>0?n:null}return t?.type===`mssql`?await a.outputAll(`deleted`).executeTakeFirst()??null:await a.returningAll().executeTakeFirst()??null},d=async e=>t?.type===`mssql`?await e.outputAll(`deleted`).executeTakeFirst()??null:await e.returningAll().executeTakeFirst()??null;if(t?.type===`mysql`){let t=async e=>{let t=await c(e.selectFrom(r).selectAll().forUpdate()).limit(1).executeTakeFirst();return t?u(e,t):null};return n?t(e):e.transaction().execute(t)}let f=c(e.selectFrom(r).select(`${r}.${l}`)),m=t?.type===`mssql`?f.top(1):f.limit(1);return d(e.deleteFrom(r).where(`${r}.${l}`,`in`,m))},async incrementOne({model:r,where:a,increment:o,set:s}){let{and:c,or:l}=p(r,a),u=e=>(c&&(e=e.where(e=>e.and(c.map(t=>t(e))))),l&&(e=e.where(e=>e.or(l.map(t=>t(e))))),e),d={...s??{}};for(let[e,t]of Object.entries(o))d[e]=$`${$.ref(e)} + ${t}`;let f=i({model:r,field:`id`});if(t?.type===`mysql`){let t=async e=>{let t=await u(e.selectFrom(r).select(`${r}.${f}`).forUpdate()).limit(1).executeTakeFirst();if(!t)return null;let n=t[f]??t.id;if(n==null)return null;let i=await u(e.updateTable(r).set(d)).where(`${r}.${f}`,`=`,n).executeTakeFirst();return Number(i.numUpdatedRows)===0?null:await e.selectFrom(r).selectAll().where(`${r}.${f}`,`=`,n).limit(1).executeTakeFirst()??null};return n?t(e):e.transaction().execute(t)}let m=u(e.selectFrom(r).select(`${r}.${f}`)),h=t?.type===`mssql`?m.top(1):m.limit(1),g=u(e.updateTable(r).set(d)).where(`${r}.${f}`,`in`,h);return t?.type===`mssql`?await g.outputAll(`inserted`).executeTakeFirst()??null:await g.returningAll().executeTakeFirst()??null},options:t}},a=null;a={config:{adapterId:`kysely`,adapterName:`Kysely Adapter`,usePlural:t?.usePlural,debugLogs:t?.debugLogs,supportsBooleans:!(t?.type===`sqlite`||t?.type===`mssql`||t?.type===`mysql`||!t?.type),supportsDates:!(t?.type===`sqlite`||t?.type===`mssql`||!t?.type),supportsJSON:t?.type===`postgres`,supportsArrays:!1,supportsUUIDs:t?.type===`postgres`,transaction:t?.transaction?t=>e.transaction().execute(e=>t(oe({config:{...a.config,transaction:!1},adapter:i(e,!0)})(n))):!1},adapter:i(e)};let o=oe(a);return e=>(n=e,o(e))},ON={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function kN(e,t){return`${M(e)}\u0000${M(t)}`}function AN(e,t){return`${e}\u0000${t}`}function jN(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,n)=>e===t.columns[n])}function MN(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}async function NN(e,t,n){let r;r=t===`sqlite`?(await $`
|
|
503
|
-
SELECT
|
|
504
|
-
tables.name AS "tableName",
|
|
505
|
-
index_list.name AS "indexName",
|
|
506
|
-
index_info.name AS "columnName",
|
|
507
|
-
index_list."unique" AS "isUnique",
|
|
508
|
-
index_list.partial AS "isPartial",
|
|
509
|
-
index_info.seqno AS "columnPosition"
|
|
510
|
-
FROM sqlite_master AS tables
|
|
511
|
-
INNER JOIN pragma_index_list(tables.name) AS index_list
|
|
512
|
-
INNER JOIN pragma_index_info(index_list.name) AS index_info
|
|
513
|
-
WHERE tables.type = 'table'
|
|
514
|
-
`.execute(e)).rows:t===`postgres`?(await $`
|
|
515
|
-
SELECT
|
|
516
|
-
table_class.relname AS "tableName",
|
|
517
|
-
index_class.relname AS "indexName",
|
|
518
|
-
index_attribute.attname AS "columnName",
|
|
519
|
-
index_data.indisunique AS "isUnique",
|
|
520
|
-
index_data.indisvalid AS "isValid",
|
|
521
|
-
(index_data.indpred IS NOT NULL) AS "isPartial",
|
|
522
|
-
index_column.ordinality AS "columnPosition"
|
|
523
|
-
FROM pg_class AS table_class
|
|
524
|
-
INNER JOIN pg_namespace AS table_namespace
|
|
525
|
-
ON table_namespace.oid = table_class.relnamespace
|
|
526
|
-
INNER JOIN pg_index AS index_data
|
|
527
|
-
ON index_data.indrelid = table_class.oid
|
|
528
|
-
INNER JOIN pg_class AS index_class
|
|
529
|
-
ON index_class.oid = index_data.indexrelid
|
|
530
|
-
INNER JOIN LATERAL unnest(index_data.indkey)
|
|
531
|
-
WITH ORDINALITY AS index_column(attribute_number, ordinality)
|
|
532
|
-
ON TRUE
|
|
533
|
-
LEFT JOIN pg_attribute AS index_attribute
|
|
534
|
-
ON index_attribute.attrelid = table_class.oid
|
|
535
|
-
AND index_attribute.attnum = index_column.attribute_number
|
|
536
|
-
WHERE table_namespace.nspname = ${n}
|
|
537
|
-
AND table_class.relkind = 'r'
|
|
538
|
-
AND index_column.ordinality <= index_data.indnkeyatts
|
|
539
|
-
`.execute(e)).rows:t===`mysql`?(await $`
|
|
540
|
-
SELECT
|
|
541
|
-
table_name AS tableName,
|
|
542
|
-
index_name AS indexName,
|
|
543
|
-
column_name AS columnName,
|
|
544
|
-
non_unique AS nonUnique,
|
|
545
|
-
seq_in_index AS columnPosition,
|
|
546
|
-
sub_part AS prefixLength
|
|
547
|
-
FROM information_schema.statistics
|
|
548
|
-
WHERE table_schema = DATABASE()
|
|
549
|
-
`.execute(e)).rows:(await $`
|
|
550
|
-
SELECT
|
|
551
|
-
tables.name AS "tableName",
|
|
552
|
-
indexes.name AS "indexName",
|
|
553
|
-
columns.name AS "columnName",
|
|
554
|
-
indexes.is_unique AS "isUnique",
|
|
555
|
-
indexes.is_disabled AS "isDisabled",
|
|
556
|
-
indexes.is_hypothetical AS "isHypothetical",
|
|
557
|
-
indexes.has_filter AS "isPartial",
|
|
558
|
-
index_columns.key_ordinal AS "columnPosition"
|
|
559
|
-
FROM sys.indexes AS indexes
|
|
560
|
-
INNER JOIN sys.tables AS tables
|
|
561
|
-
ON indexes.object_id = tables.object_id
|
|
562
|
-
INNER JOIN sys.schemas AS table_schemas
|
|
563
|
-
ON table_schemas.schema_id = tables.schema_id
|
|
564
|
-
INNER JOIN sys.index_columns AS index_columns
|
|
565
|
-
ON index_columns.object_id = indexes.object_id
|
|
566
|
-
AND index_columns.index_id = indexes.index_id
|
|
567
|
-
INNER JOIN sys.columns AS columns
|
|
568
|
-
ON columns.object_id = index_columns.object_id
|
|
569
|
-
AND columns.column_id = index_columns.column_id
|
|
570
|
-
WHERE table_schemas.name = ${n}
|
|
571
|
-
AND indexes.name IS NOT NULL
|
|
572
|
-
AND index_columns.key_ordinal > 0
|
|
573
|
-
`.execute(e)).rows;let i=new Map;for(let e of r){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,n=e.indexName??e.index_name??e.INDEX_NAME??e.name,r=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!n)continue;let a=kN(t,n),o=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=o===void 0?MN(e.isUnique??e.is_unique):!MN(o),c=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),l=i.get(a)??{columns:[],name:n,table:t,unique:s,validFullColumns:!0};r?l.columns.push({name:r,position:c}):l.validFullColumns=!1,(MN(e.isPartial)||MN(e.isDisabled)||MN(e.isHypothetical)||e.isValid!==void 0&&!MN(e.isValid)||e.prefixLength!==void 0&&e.prefixLength!==null)&&(l.validFullColumns=!1),i.set(a,l)}return new Map([...i].map(([e,t])=>[e,{columns:t.columns.sort((e,t)=>e.position-t.position).map(e=>e.name),name:t.name,table:t.table,unique:t.unique,validFullColumns:t.validFullColumns}]))}async function PN(e,t,n){if(t!==`mysql`&&t!==`mssql`)return new Map;let r;return r=t===`mysql`?(await $`
|
|
574
|
-
SELECT
|
|
575
|
-
table_name AS tableName,
|
|
576
|
-
column_name AS columnName,
|
|
577
|
-
data_type AS dataType,
|
|
578
|
-
character_maximum_length AS characterMaximumLength
|
|
579
|
-
FROM information_schema.columns
|
|
580
|
-
WHERE table_schema = DATABASE()
|
|
581
|
-
`.execute(e)).rows:(await $`
|
|
582
|
-
SELECT
|
|
583
|
-
tables.name AS "tableName",
|
|
584
|
-
columns.name AS "columnName",
|
|
585
|
-
types.name AS "dataType",
|
|
586
|
-
columns.max_length AS "maxLength"
|
|
587
|
-
FROM sys.columns AS columns
|
|
588
|
-
INNER JOIN sys.tables AS tables
|
|
589
|
-
ON tables.object_id = columns.object_id
|
|
590
|
-
INNER JOIN sys.schemas AS table_schemas
|
|
591
|
-
ON table_schemas.schema_id = tables.schema_id
|
|
592
|
-
INNER JOIN sys.types AS types
|
|
593
|
-
ON types.user_type_id = columns.user_type_id
|
|
594
|
-
WHERE table_schemas.name = ${n}
|
|
595
|
-
`.execute(e)).rows,new Map(r.flatMap(e=>{let n=e.tableName??e.TABLE_NAME,r=e.columnName??e.COLUMN_NAME,i=(e.dataType??e.DATA_TYPE)?.toLowerCase();if(!n||!r||!i)return[];if(t===`mysql`){let t=e.characterMaximumLength??e.CHARACTER_MAXIMUM_LENGTH,i=t==null?null:Number(t)*4;return[[AN(n,r),{maxIndexBytes:i}]]}let a=Number(e.maxLength??-1);return[[AN(n,r),{maxIndexBytes:a<0?null:a}]]}))}function FN({columnBounds:e,dbType:t,existingColumns:n,fields:r,indexes:i,index:a,table:o}){let s=t===`mysql`?3072:1700,c=0;for(let s of a.columns){let l=r[s];if(l){if(l.type===`string`||Array.isArray(l.type)){if(!n.has(s)){let e=re({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let l=e.get(AN(o,s));if(!l?.maxIndexBytes)throw new b(`Cannot create database index "${a.name}" on existing table "${o}" because column "${s}" is not bounded for ${t===`mysql`?`MySQL`:`SQL Server`}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);c+=l.maxIndexBytes}else c+=16}}if(c>s)throw new b(`Cannot create database index "${a.name}" on existing table "${o}" because its columns can exceed ${t===`mysql`?`MySQL`:`SQL Server`}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}var IN=`https://better-auth.com/docs/guides/1-7-upgrade-guide#account-identity-is-scoped-by-issuer`,LN=class extends b{};function RN(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function zN(e){return!(e.unique&&e.required===!1)&&(e.type===`string`||e.type===`number`||e.type===`boolean`)&&e.defaultValue!==void 0&&e.defaultValue!==null&&typeof e.defaultValue!=`function`}async function BN(e,t,n){let r=e.selectFrom(n).select($`1`.as(`present`));return(await(t===`mssql`?r.top(1):r.limit(1)).execute()).length>0}function VN(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=ON[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function HN(e){try{let t=await $`SHOW search_path`.execute(e),n=t.rows[0]?.search_path??t.rows[0]?.searchPath;if(n)return n.split(`,`).map(e=>e.trim()).map(e=>e.replace(/^["']|["']$/g,``)).filter(e=>!e.startsWith(`$`)&&!e.startsWith(`\\$`))[0]||`public`}catch{}return`public`}async function UN(e){try{return(await $`
|
|
596
|
-
SELECT SCHEMA_NAME() AS "schemaName"
|
|
597
|
-
`.execute(e)).rows[0]?.schemaName||`dbo`}catch{return`dbo`}}async function WN(e,{throwOnUnsafe:t=!0}={}){let n=PE(e),r=se(e),i=r.account&&{table:r.account.modelName,column:r.account.fields.issuer?.fieldName||`issuer`},a=(e,t)=>e===i?.table&&t===i.column,o=ee(e.logger),s=[],c=e=>{if(t)throw new LN(e);s.push(e)},{kysely:l,databaseType:u}=await xN(e);u||=(o.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),l||(o.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let d=u===`mssql`?await UN(l):`public`;if(u===`postgres`){d=await HN(l),o.debug(`PostgreSQL migration: Using schema '${d}' (from search_path)`);try{let e=await $`
|
|
598
|
-
SELECT schema_name
|
|
599
|
-
FROM information_schema.schemata
|
|
600
|
-
WHERE schema_name = ${d}
|
|
601
|
-
`.execute(l);(e.rows[0]?.schema_name??e.rows[0]?.schemaName)||o.warn(`Schema '${d}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`)}catch(e){o.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}}else u===`mssql`&&o.debug(`SQL Server migration: Using schema '${d}' (from the current user's default schema)`);let f=await l.introspection.getTables(),p=await NN(l,u,d),m=await PN(l,u,d),h=f;if(u===`postgres`)try{let e=await $`
|
|
602
|
-
SELECT table_name
|
|
603
|
-
FROM information_schema.tables
|
|
604
|
-
WHERE table_schema = ${d}
|
|
605
|
-
AND table_type = 'BASE TABLE'
|
|
606
|
-
`.execute(l),t=new Set(e.rows.map(e=>e.table_name??e.tableName));h=f.filter(e=>e.schema===d&&t.has(e.name)),o.debug(`Found ${h.length} table(s) in schema '${d}': ${h.map(e=>e.name).join(`, `)||`(none)`}`)}catch(e){o.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${e instanceof Error?e.message:String(e)}`)}else u===`mssql`&&(h=f.filter(e=>e.schema===d));let g=[],_=[],v=[],y=new Map;for(let[e,t]of Object.entries(n)){if(t.disableMigrations)continue;let n=h.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=kN(e,i),o=p.get(a);if(o){if(!jN(o,r))throw new b(`Database index "${i}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if(u===`sqlite`||u===`postgres`){let t=[...p.values()].find(t=>M(t.name)===M(i)&&M(t.table)!==M(e));if(t)throw new b(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=y.get(a);if(s){if(!jN({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new b(`Database index name "${i}" identifies more than one index on table "${e}".`);continue}n&&(u===`mysql`||u===`mssql`)&&FN({columnBounds:m,dbType:u,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),y.set(a,r),v.push({table:e,index:r,name:i})}if(!n){let n=g.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=g.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?g.push(r):g[n].fields={...g[n].fields,...t.fields}:g.splice(i,0,r);continue}let r={};for(let[i,a]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===i);if(!t){r[i]=a;continue}a.required!==!1&&t.isNullable&&o.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!VN(t.dataType,a.type,u)&&o.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${a.type} but got ${t.dataType}.`)}Object.keys(r).length>0&&_.push({table:e,fields:r,order:t.order||1/0})}let te=[],x=e.advanced?.database?.generateId===`uuid`,S=e.advanced?.database?.generateId===`serial`;function C(e,t,n){let r=e.type,i=u||`sqlite`,a={string:{sqlite:`text`,postgres:`text`,mysql:n?`varchar(${n})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:n?`varchar(${n})`:e.unique||e.sortable?`varchar(255)`:e.references?`varchar(36)`:`varchar(8000)`},boolean:{sqlite:`integer`,postgres:`boolean`,mysql:`boolean`,mssql:`smallint`},number:{sqlite:e.bigint?`bigint`:`integer`,postgres:e.bigint?`bigint`:`integer`,mysql:e.bigint?`bigint`:`integer`,mssql:e.bigint?`bigint`:`integer`},date:{sqlite:`date`,postgres:`timestamptz`,mysql:`timestamp(3)`,mssql:$`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:S?$`integer GENERATED BY DEFAULT AS IDENTITY`:x?`uuid`:`text`,mysql:S?`integer`:`varchar(36)`,mssql:S?`integer`:`varchar(36)`,sqlite:S?`integer`:`text`},foreignKeyId:{postgres:S?`integer`:x?`uuid`:`text`,mysql:S?`integer`:`varchar(36)`,mssql:S?`integer`:`varchar(36)`,sqlite:S?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(t===`id`||e.references?.field===`id`)return t===`id`?a.id[i]:a.foreignKeyId[i];if(Array.isArray(r))return`text`;if(!(r in a))throw Error(`Unsupported field type '${String(r)}' for field '${t}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return a[r][i]}let w=ne({schema:r,usePlural:!1}),E=ie({schema:r,usePlural:!1});function D(e,t){try{return`${w(e)}.${E({model:e,field:t})}`}catch{return`${e}.${t}`}}let O=[],k=(e,t)=>{if(u!==`mysql`&&u!==`mssql`)return;let r=n[e];if(r)return re({columnName:t,dialect:u,fields:r.fields,indexes:r.indexes??[]})};if(_.length){let e=new Map;for(let t of _)for(let[n,r]of Object.entries(t.fields)){let i=RN(r,u),s=zN(r);if(r.required!==!1&&!i&&!s){let i=e.get(t.table);if(i===void 0&&(i=await BN(l,u,t.table),e.set(t.table,i)),i){let e=r.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``,i=a(t.table,n)?` See ${IN}`:``;c(`Cannot add required column "${n}" to populated table "${t.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.${i}`)}}let d=C(r,n,k(t.table,n)),f=l.schema.alterTable(t.table);if(r.index||r.unique){let e=T(t.table,n,r.unique??!1),i=l.schema.createIndex(e).on(t.table).columns([n]);r.unique&&(i=i.unique(),r.required===!1&&u===`mssql`&&(i=i.where(n,`is not`,null)),r.required!==!1&&r.defaultValue!==void 0&&r.defaultValue!==null&&typeof r.defaultValue!=`function`&&o.warn(`Adding unique column "${n}" to existing table "${t.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),O.push(i)}let p=f.addColumn(n,d,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(D(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),i?e=u===`mysql`?e.defaultTo($`CURRENT_TIMESTAMP(3)`):e.defaultTo($`CURRENT_TIMESTAMP`):s&&(e=e.defaultTo(typeof r.defaultValue==`boolean`&&(u===`sqlite`||u===`mssql`)?+!!r.defaultValue:r.defaultValue)),e));te.push(p)}}if(g.length)for(let e of g){let t=C({type:S?`number`:`string`},`id`),n=l.schema.createTable(e.table).addColumn(`id`,t,e=>S?u===`postgres`||u===`sqlite`?e.primaryKey().notNull():u===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():x&&u===`postgres`?e.primaryKey().defaultTo($`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[t,r]of Object.entries(e.fields)){let i=C(r,t,k(e.table,t));if(n=n.addColumn(t,i,e=>(e=r.required===!1?e:e.notNull(),r.references&&(e=e.references(D(r.references.model,r.references.field)).onDelete(r.references.onDelete||`cascade`)),r.unique&&(e=e.unique()),r.type===`date`&&typeof r.defaultValue==`function`&&(u===`postgres`||u===`mysql`||u===`mssql`)&&(e=u===`mysql`?e.defaultTo($`CURRENT_TIMESTAMP(3)`):e.defaultTo($`CURRENT_TIMESTAMP`)),e)),r.index&&!r.unique){let n=l.schema.createIndex(T(e.table,t,!1)).on(e.table).columns([t]);O.push(n)}}te.push(n)}for(let{table:e,index:t,name:n}of v){let r=l.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),O.push(r)}for(let e of O)te.push(e);async function A(){for(let e of te)await e.execute()}async function j(){return te.map(e=>e.compile().sql).join(`;
|
|
607
|
-
|
|
608
|
-
`)+`;`}return{toBeCreated:g,toBeAdded:_,toBeAddedIndexes:v,unsafeChanges:s,runMigrations:A,compileMigrations:j}}var GN=`better-auth-secret-12345678901234567890`;function KN(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function qN(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new b(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let n=parseInt(e.slice(0,t),10);if(!Number.isInteger(n)||n<0)throw new b(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let r=e.slice(t+1).trim();if(!r)throw new b(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function JN(e,t){if(e.length===0)throw new b("`secrets` array must contain at least one entry.");let n=new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new b(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new b(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new b(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);n.add(e)}let r=e[0];r.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${r.version}) should be at least 32 characters long for adequate security.`),KN(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function YN(e,t){let n=new Map;for(let t of e)n.set(parseInt(String(t.version),10),t.value);return{keys:n,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&t!==`better-auth-secret-12345678901234567890`?t:void 0}}async function XN(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let n=e.socialProviders?.[t];if(!n)return{};let r=typeof n==`function`?await n():n;return{id:t,mapProfileToUser:!!r.mapProfileToUser,disableDefaultScope:!!r.disableDefaultScope,disableIdTokenSignIn:!!r.disableIdTokenSignIn,disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,getUserInfo:!!r.getUserInfo,overrideUserInfoOnSignIn:!!r.overrideUserInfoOnSignIn,prompt:r.prompt,verifyIdToken:!!r.verifyIdToken,scope:r.scope,refreshAccessToken:!!r.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}async function ZN(e){}async function QN(){}var $N={pg:`postgresql`,mysql:`mysql`,mariadb:`mariadb`,sqlite3:`sqlite`,"better-sqlite3":`sqlite`,"@prisma/client":`prisma`,mongoose:`mongodb`,mongodb:`mongodb`,"drizzle-orm":`drizzle`};async function eP(){for(let[e,t]of Object.entries($N)){let n=await ZN(e);if(n)return{name:t,version:n}}}var tP={next:`next`,nuxt:`nuxt`,"react-router":`react-router`,astro:`astro`,"@sveltejs/kit":`sveltekit`,"solid-start":`solid-start`,"tanstack-start":`tanstack-start`,hono:`hono`,express:`express`,elysia:`elysia`,expo:`expo`};async function nP(){for(let[e,t]of Object.entries(tP)){let n=await ZN(e);if(n)return{name:t,version:n}}}function rP(){let e=v.npm_config_user_agent;if(!e)return;let t=e.split(` `)[0],n=t.lastIndexOf(`/`),r=t.substring(0,n);return{name:r===`npminstall`?`cnpm`:r,version:t.substring(n+1)}}function iP(){let e=(...e)=>e.some(e=>!!v[e]);return e(`CF_PAGES`,`CF_PAGES_URL`,`CF_ACCOUNT_ID`)||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`?`cloudflare`:e(`VERCEL`,`VERCEL_URL`,`VERCEL_ENV`)?`vercel`:e(`NETLIFY`,`NETLIFY_URL`)?`netlify`:e(`RENDER`,`RENDER_URL`,`RENDER_INTERNAL_HOSTNAME`,`RENDER_SERVICE_ID`)?`render`:e(`AWS_LAMBDA_FUNCTION_NAME`,`AWS_EXECUTION_ENV`,`LAMBDA_TASK_ROOT`)?`aws`:e(`GOOGLE_CLOUD_FUNCTION_NAME`,`GOOGLE_CLOUD_PROJECT`,`GCP_PROJECT`,`K_SERVICE`)?`gcp`:e(`AZURE_FUNCTION_NAME`,`FUNCTIONS_WORKER_RUNTIME`,`WEBSITE_INSTANCE_ID`,`WEBSITE_SITE_NAME`)?`azure`:e(`DENO_DEPLOYMENT_ID`,`DENO_REGION`)?`deno-deploy`:e(`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`)?`fly-io`:e(`RAILWAY_STATIC_URL`,`RAILWAY_ENVIRONMENT_NAME`)?`railway`:e(`DYNO`,`HEROKU_APP_NAME`)?`heroku`:e(`DO_DEPLOYMENT_ID`,`DO_APP_NAME`,`DIGITALOCEAN`)?`digitalocean`:e(`KOYEB`,`KOYEB_DEPLOYMENT_ID`,`KOYEB_APP_NAME`)?`koyeb`:null}async function aP(){return{deploymentVendor:iP(),systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}function oP(){return v.CI!==`false`&&(`BUILD_ID`in v||`BUILD_NUMBER`in v||`CI`in v||`CI_APP_ID`in v||`CI_BUILD_ID`in v||`CI_BUILD_NUMBER`in v||`CI_NAME`in v||`CONTINUOUS_INTEGRATION`in v||`RUN_ID`in v)}function sP(){return typeof Deno<`u`?{name:`deno`,version:Deno?.version?.deno??null}:typeof Bun<`u`?{name:`bun`,version:Bun?.version??null}:typeof process<`u`&&process?.versions?.node?{name:`node`,version:process.versions.node??null}:{name:`edge`,version:null}}function cP(){return y(`NODE_ENV`)===`production`?`production`:oP()?`ci`:k()?`test`:`development`}async function lP(e){let t=await Zl(`SHA-256`).digest(e);return Yl.encode(t)}var uP=e=>D(`a-z`,`A-Z`,`0-9`)(e||32),dP=null;async function fP(e){if(dP)return dP;let t=await QN();return t?(dP=await lP(e?e+t:t),dP):e?(dP=await lP(e),dP):(dP=uP(32),dP)}var pP=async function(){};async function mP(e,t){let n=e.telemetry?.debug||_(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=te.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:pP};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(g.error):r&&(n?g.info(`telemetry event`,JSON.stringify(e,null,2)):await Y(r,{method:`POST`,body:e}).catch(g.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(_(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!k())})(),o;return a&&(o=await fP(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await XN(e,t),runtime:sP(),database:await eP(),framework:await nP(),environment:cP(),systemInfo:await aP(),packageManager:rP()},anonymousId:o})),{publish:async t=>{a&&(o||=await fP(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function hP(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function gP(e,t){let n=e===GN;if(!k()){if(n&&h)throw new b("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!e)throw new b("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");e.length<32&&t.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),hP(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function _P(e,t,n){let r=ad(t);r||(t=BS(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=BS(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=tC(t),o=ee(t.logger),s=Qi(t.baseURL);if(Qi(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new b(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:Ji(typeof t.baseURL==`string`?t.baseURL:void 0,t.basePath);!c&&!s&&o.warn(`[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly.`),e.id===`memory`&&t.advanced?.database?.generateId===!1&&o.error(`[better-auth] Misconfiguration detected.
|
|
609
|
-
You are using the memory DB with generateId: false.
|
|
610
|
-
This will cause no id to be generated for any model.
|
|
611
|
-
Most of the features of Better Auth will not work correctly.`);let l=t.secrets??qN(v.BETTER_AUTH_SECRETS),u=t.secret||v.BETTER_AUTH_SECRET||v.AUTH_SECRET||``,d,f;l?(JN(l,o),d=l[0].value,f=YN(l,u)):(d=u||`better-auth-secret-12345678901234567890`,gP(d,o),f=d),t={...t,secret:d,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},kE(t,o);let p=t.advanced?.ipAddress?.trustedProxies;if(p&&p.length>0){let e=qx(p);e.length>0&&o.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(`, `)}. Each entry must be an IP address or CIDR range.`)}let m=Sb(t),g=se(t),_=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let n=typeof t==`function`?await t():t;if(n==null||n.enabled===!1)return null;n.clientId||o.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=DT[e](n);return r.disableImplicitSignUp=n.disableImplicitSignUp,r}))).filter(e=>e!==null),y=({model:e,size:n})=>{if(typeof t.advanced?.generateId==`function`)return t.advanced.generateId({model:e,size:n});let r=t?.advanced?.database?.generateId;return typeof r==`function`?r({model:e,size:n}):r===`uuid`?crypto.randomUUID():r===`serial`||r===!1?!1:O(n)},{publish:te}=await mP(t,{adapter:e.id,database:typeof t.database==`function`?`adapter`:n(t.database)}),x=new Set(t.plugins.map(e=>e.id)),S=e=>t.plugins.find(t=>t.id===e)??null,C=e=>x.has(e),w=await nC(t),T=await sC(t),E={appName:t.appName||`Better Auth`,baseURL:c||``,version:Ub(),socialProviders:_,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:g,trustedOrigins:w,trustedProviders:T,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>wx(e,n,t))},sessionConfig:{updateAge:t.session?.updateAge===void 0?86400:t.session.updateAge,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(()=>{let e=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300;return r&&e?(o.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):e===!1||e===void 0?!1:e===!0?{enabled:!0,updateAge:Math.floor(n*.2)}:{enabled:!0,updateAge:e.updateAge===void 0?Math.floor(n*.2):e.updateAge}})()},secret:d,secretConfig:f,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??h,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?`secondary-storage`:`memory`)},authCookies:m,logger:o,generateId:y,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||Ul,verify:t.emailAndPassword?.password?.verify||Wl,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:JT},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:IS(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:y}),createAuthCookie:xb(t),async runMigrations(){throw new b(`runMigrations will be set by the specific init implementation`)},publishTelemetry:te,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!k():t.advanced.disableOriginCheck,runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{o.error(`Failed to run background task:`,e)})):await e}catch(e){o.error(`Failed to run background task:`,e)}},getPlugin:S,hasPlugin:C},D=eC(E);return Ev(D)&&await D,E}var vP=async e=>{let t=await _P(await NE(e),e,e=>bN(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new b(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await WN(e);await t()},t},yP=(e,t)=>{let n=t(e),{api:r}=AE(n,e),i=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),a=async t=>{let r=await n,i=r.options.basePath||`/api/auth`,a;if(Qi(e.baseURL))a=await aC(r,t,iC(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=Ji(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new b(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:Yi(n)||void 0},e=a.options}a.trustedOrigins=await nC(e,t),a.trustedProviders=await sC(e,t)}let{handler:o}=jE(a,e);return rx(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...V}}},bP=e=>yP(e,vP);function xP(e,t,n){return n===`pg`?yn(e,t):z`LOWER(${e}) LIKE LOWER(${t})`}function SP(e,t){return t.length===0?z`false`:z`LOWER(${e}) IN (${z.join(t.map(e=>z`LOWER(${e})`),z`, `)})`}function CP(e,t){return t.length===0?z`true`:z`LOWER(${e}) NOT IN (${z.join(t.map(e=>z`LOWER(${e})`),z`, `)})`}function wP(e,t){return z`LOWER(${e}) = LOWER(${t})`}function TP(e,t){return z`LOWER(${e}) <> LOWER(${t})`}function EP(e,t,n){let r=0;if(e&&typeof e==`object`&&`rowCount`in e?r=e.rowCount:e&&typeof e==`object`&&typeof e.count==`number`?r=e.count:Array.isArray(e)?r=e.length>0&&OP(e[0])?DP(e[0]):e.length:OP(e)&&(r=DP(e)),typeof r!=`number`||!Number.isFinite(r))throw g.error(`[Drizzle Adapter] The result of the ${t} operation is not a finite number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.`,{result:e,...n}),new b(`Drizzle adapter ${t} returned an invalid affected row count`);return r}function DP(e){if(!e||typeof e!=`object`)return;let t=e;if(`affectedRows`in t)return t.affectedRows;if(`rowsAffected`in t)return t.rowsAffected;if(`changes`in t)return t.changes;if(`meta`in t){let e=t.meta;if(e&&typeof e==`object`&&`changes`in e)return e.changes}}function OP(e){return DP(e)!==void 0}var kP=(e,t)=>{let n=null,r=!1,i=(e,n=!1)=>({getFieldName:i,getDefaultFieldName:a,getDefaultModelName:o,options:s,schema:c})=>{t.provider===`mysql`&&s.advanced?.database?.generateId===!1&&!r&&(r=!0,g.warn(`[Drizzle Adapter] MySQL does not support INSERT...RETURNING. With generateId set to false, the adapter uses best-effort fallback strategies (unique columns, full-field match) to retrieve inserted rows. For reliable behavior, use Better Auth's default ID generation, a custom generateId function, or generateId: "serial" for auto-increment.`));function l(n){let r=t.schema||e._.fullSchema;if(!r)throw new b(`Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.`);let i=r[n];if(!i)throw new b(`[# Drizzle Adapter]: The model "${n}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return i}let u=async(r,a,u,f)=>{if(t.provider!==`mysql`)return(await a.returning())[0];await a.execute();let p=l(r),m=a.config?.values;if(f?.length){let t=d(f.map(e=>u[e.field]===void 0?e:{...e,value:u[e.field]}),r);return(await e.select().from(p).where(...t))[0]}let h=async e=>{let t=m?.[0]?.id?.value;if(t)return(await e.select().from(p).where($t(p.id,t)).limit(1).execute())[0]??null;if(u.id)return(await e.select().from(p).where($t(p.id,u.id)).limit(1).execute())[0]??null;if(s.advanced?.database?.generateId===`serial`&&p.id){let t=(await e.select({id:z`LAST_INSERT_ID()`}).from(p).limit(1).execute())[0]?.id;if(t)return(await e.select().from(p).where($t(p.id,t)).limit(1).execute())[0]??null}let n=c[o(r)]?.fields;if(n)for(let[t,a]of Object.entries(n)){if(!a.unique)continue;let n=i({model:r,field:t}),o=u[n];if(o==null||!p[n])continue;let s=await e.select().from(p).where($t(p[n],o)).limit(1).execute();if(s[0])return s[0]}let a=[];for(let[e,t]of Object.entries(u))t===void 0||!p[e]||a.push(t===null?dn(p[e]):$t(p[e],t));if(a.length>0){let t=tn(...a);if(t){let n=await e.select().from(p).where(t).limit(2).execute();if(n.length===1)return n[0]}}return g.warn(`[Drizzle Adapter] Unable to safely identify the inserted "${r}" row on MySQL. Enable Better Auth ID generation or use generateId: "serial" for reliable behavior.`),null};return n?h(e):e.transaction(h)};function d(e,n){let r=l(n);if(!e)return[];if(e.length===1){let a=e[0];if(!a)return[];let o=i({model:n,field:a.field});if(!r[o])throw new b(`The field "${a.field}" does not exist in the schema for the model "${n}". Please update your schema.`);let s=(a.mode??`sensitive`)===`insensitive`&&(typeof a.value==`string`||Array.isArray(a.value)&&a.value.every(e=>typeof e==`string`));if(a.operator===`in`){if(!Array.isArray(a.value))throw new b(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return s?[SP(r[o],a.value)]:[ln(r[o],a.value)]}if(a.operator===`not_in`){if(!Array.isArray(a.value))throw new b(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return s?[CP(r[o],a.value)]:[un(r[o],a.value)]}return a.operator===`contains`?s&&typeof a.value==`string`?[xP(r[o],`%${a.value}%`,t.provider)]:[_n(r[o],`%${a.value}%`)]:a.operator===`starts_with`?s&&typeof a.value==`string`?[xP(r[o],`${a.value}%`,t.provider)]:[_n(r[o],`${a.value}%`)]:a.operator===`ends_with`?s&&typeof a.value==`string`?[xP(r[o],`%${a.value}`,t.provider)]:[_n(r[o],`%${a.value}`)]:a.operator===`lt`?[sn(r[o],a.value)]:a.operator===`lte`?[cn(r[o],a.value)]:a.operator===`ne`?a.value===null?[fn(r[o])]:s&&typeof a.value==`string`?[TP(r[o],a.value)]:[en(r[o],a.value)]:a.operator===`gt`?[an(r[o],a.value)]:a.operator===`gte`?[on(r[o],a.value)]:a.value===null?[dn(r[o])]:s&&typeof a.value==`string`?[wP(r[o],a.value)]:[$t(r[o],a.value)]}let a=e.filter(e=>e.connector===`AND`||!e.connector),o=e.filter(e=>e.connector===`OR`),s=tn(...a.map(e=>{let a=i({model:n,field:e.field}),o=(e.mode??`sensitive`)===`insensitive`&&(typeof e.value==`string`||Array.isArray(e.value)&&e.value.every(e=>typeof e==`string`));if(e.operator===`in`){if(!Array.isArray(e.value))throw new b(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return o?SP(r[a],e.value):ln(r[a],e.value)}if(e.operator===`not_in`){if(!Array.isArray(e.value))throw new b(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return o?CP(r[a],e.value):un(r[a],e.value)}return e.operator===`contains`?o&&typeof e.value==`string`?xP(r[a],`%${e.value}%`,t.provider):_n(r[a],`%${e.value}%`):e.operator===`starts_with`?o&&typeof e.value==`string`?xP(r[a],`${e.value}%`,t.provider):_n(r[a],`${e.value}%`):e.operator===`ends_with`?o&&typeof e.value==`string`?xP(r[a],`%${e.value}`,t.provider):_n(r[a],`%${e.value}`):e.operator===`lt`?sn(r[a],e.value):e.operator===`lte`?cn(r[a],e.value):e.operator===`gt`?an(r[a],e.value):e.operator===`gte`?on(r[a],e.value):e.operator===`ne`?e.value===null?fn(r[a]):o&&typeof e.value==`string`?TP(r[a],e.value):en(r[a],e.value):e.value===null?dn(r[a]):o&&typeof e.value==`string`?wP(r[a],e.value):$t(r[a],e.value)})),c=nn(...o.map(e=>{let a=i({model:n,field:e.field});if(!r[a])throw new b(`The field "${e.field}" does not exist in the schema for the model "${n}". Please update your schema.`);let o=(e.mode??`sensitive`)===`insensitive`&&(typeof e.value==`string`||Array.isArray(e.value)&&e.value.every(e=>typeof e==`string`));if(e.operator===`in`){if(!Array.isArray(e.value))throw new b(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return o?SP(r[a],e.value):ln(r[a],e.value)}if(e.operator===`not_in`){if(!Array.isArray(e.value))throw new b(`The value for the field "${e.field}" must be an array when using the "not_in" operator.`);return o?CP(r[a],e.value):un(r[a],e.value)}return e.operator===`contains`?o&&typeof e.value==`string`?xP(r[a],`%${e.value}%`,t.provider):_n(r[a],`%${e.value}%`):e.operator===`starts_with`?o&&typeof e.value==`string`?xP(r[a],`${e.value}%`,t.provider):_n(r[a],`${e.value}%`):e.operator===`ends_with`?o&&typeof e.value==`string`?xP(r[a],`%${e.value}`,t.provider):_n(r[a],`%${e.value}`):e.operator===`lt`?sn(r[a],e.value):e.operator===`lte`?cn(r[a],e.value):e.operator===`gt`?an(r[a],e.value):e.operator===`gte`?on(r[a],e.value):e.operator===`ne`?e.value===null?fn(r[a]):o&&typeof e.value==`string`?TP(r[a],e.value):en(r[a],e.value):e.value===null?dn(r[a]):o&&typeof e.value==`string`?wP(r[a],e.value):$t(r[a],e.value)}));return a.length&&o.length?[tn(s,c)]:a.length?[s]:o.length?[c]:[]}function f(e,t,n){if(!e)throw new b(`Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.`);for(let r in n){let n;try{n=i({model:t,field:r})}catch{n=r}if(!e[n])throw new b(`The field "${r}" does not exist in the "${t}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}}function p(n){if(!e.query)return null;if(e.query[n])return n;if(t.usePlural){let t=`${n}s`;if(e.query[t])return t}if(t.schema){let r=t.schema[n];if(r){let t=e._.fullSchema;if(t){for(let n of Object.keys(e.query))if(t[n]===r)return n}}}return null}return{async create({model:t,data:n}){let r=l(t);return f(r,t,n),await u(t,e.insert(r).values(n),n)},async findOne({model:n,where:r,select:a,join:o}){let c=l(n),u=d(r,n);if(o){let r=p(n);if(!e.query||!r)g.error(`[# Drizzle Adapter]: The model "${n}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),g.info(`Falling back to regular query`);else{let c,l=[];c={};let d=Object.entries(o);for(let[e,n]of d){let r=n.limit??s.advanced?.database?.defaultFindManyLimit??100,i=n.relation===`one-to-one`,a=i||t.usePlural?``:`s`;c[`${e}${a}`]=i?!0:{limit:r},i||l.push(`${e}${a}`)}let f=await e.query[r].findFirst({where:u[0],columns:a?.length&&a.length>0?a.reduce((e,t)=>(e[i({model:n,field:t})]=!0,e),{}):void 0,with:c});if(f)for(let e of l){let n=t.usePlural?e:e.slice(0,-1);f[n]=f[e],e!==n&&delete f[e]}return f}}let f=await e.select(a?.length&&a.length>0?a.reduce((e,t)=>{let r=i({model:n,field:t});return{...e,[r]:c[r]}},{}):void 0).from(c).where(...u);return f.length?f[0]:null},async findMany({model:n,where:r,sortBy:a,limit:o,select:c,offset:u,join:f}){let m=l(n),h=r?d(r,n):[],_=a?.direction===`desc`?Sn:xn;if(f){let r=p(n);if(!e.query||!r)g.error(`[# Drizzle Adapter]: The model "${n}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),g.info(`Falling back to regular query`);else{let l,d=[];l={};let p=Object.entries(f);for(let[e,n]of p){let r=n.relation===`one-to-one`,i=n.limit??s.advanced?.database?.defaultFindManyLimit??100,a=r||t.usePlural?``:`s`;l[`${e}${a}`]=r?!0:{limit:i},r||d.push(`${e}${a}`)}let g;a?.field&&(g=[_(m[i({model:n,field:a?.field})])]);let v=await e.query[r].findMany({where:h[0],with:l,columns:c?.length&&c.length>0?c.reduce((e,t)=>(e[i({model:n,field:t})]=!0,e),{}):void 0,limit:o??100,offset:u??0,orderBy:g});if(v)for(let e of v)for(let n of d){let r=t.usePlural?n:n.slice(0,-1);r!==n&&(e[r]=e[n],delete e[n])}return v}}let v=e.select(c?.length&&c.length>0?c.reduce((e,t)=>{let r=i({model:n,field:t});return{...e,[r]:m[r]}},{}):void 0).from(m),y=o,ee=u;return y!==void 0&&(v=v.limit(y)),ee!==void 0&&(v=v.offset(ee)),a?.field&&(v=v.orderBy(_(m[i({model:n,field:a?.field})]))),await v.where(...h)},async count({model:t,where:n}){let r=l(t),i=n?d(n,t):[];return(await e.select({count:In()}).from(r).where(...i))[0].count},async update({model:t,where:n,update:r}){let i=l(t),a=d(n,t);return await u(t,e.update(i).set(r).where(...a),r,n)},async updateMany({model:t,where:n,update:r}){let i=l(t),a=d(n,t);return EP(await e.update(i).set(r).where(...a),`updateMany`,{model:t,where:n})},async delete({model:t,where:n}){let r=l(t),i=d(n,t);return await e.delete(r).where(...i)},async deleteMany({model:t,where:n}){let r=l(t),i=d(n,t);return EP(await e.delete(r).where(...i),`deleteMany`,{model:t,where:n})},async consumeOne({model:r,where:a}){let o=l(r),s=d(a,r),c=i({model:r,field:`id`}),u=o[c];if(t.provider===`mysql`){let t=async e=>{let t=(await e.select().from(o).where(...s).for(`update`).limit(1))[0];if(!t)return null;let n=t[c]??t.id;return n==null||!u?null:EP(await e.delete(o).where($t(u,n)).execute(),`consumeOne`,{model:r,where:a})>0?t:null};return n?t(e):e.transaction(t)}if(!u)return null;let f=e.select({id:u}).from(o).where(...s).limit(1);return(await e.delete(o).where(ln(u,f)).returning())[0]??null},async incrementOne({model:r,where:a,increment:o,set:s}){let c=l(r),u=d(a,r),f=i({model:r,field:`id`}),p=c[f],m={};for(let[e,t]of Object.entries(o)){let n=i({model:r,field:e}),a=c[n];if(!a)throw new b(`The field "${e}" does not exist in the schema for the model "${r}". Please update your schema.`);m[n]=z`${a} + ${z.param(t)}`}if(s)for(let[e,t]of Object.entries(s)){let n=i({model:r,field:e});if(!c[n])throw new b(`The field "${e}" does not exist in the schema for the model "${r}". Please update your schema.`);m[n]=t}if(t.provider===`mysql`){let t=async e=>{let t=(await e.select().from(c).where(...u).for(`update`).limit(1))[0];if(!t)return null;let n=t[f]??t.id;return n==null||!p?null:(await e.update(c).set(m).where($t(p,n)).execute(),(await e.select().from(c).where($t(p,n)).limit(1).execute())[0]??null)};return n?t(e):e.transaction(t)}if(!p)return null;let h=e.select({id:p}).from(c).where(...u).limit(1);return(await e.update(c).set(m).where(ln(p,h)).returning())[0]??null},options:t}},a=null;a={config:{adapterId:`drizzle`,adapterName:`Drizzle Adapter`,usePlural:t.usePlural??!1,debugLogs:t.debugLogs??!1,supportsUUIDs:t.provider===`pg`,supportsJSON:t.provider===`pg`,supportsArrays:t.provider===`pg`,customTransformOutput:({data:e,fieldAttributes:t})=>t.type===`date`?e==null?e:new Date(e):e,transaction:t.transaction??!1?t=>e.transaction(e=>t(oe({config:{...a.config,transaction:!1},adapter:i(e,!0)})(n))):!1},adapter:i(e)};let o=oe(a);return e=>(n=e,o(e))};function AP(e){let t=new Set([e]);try{let n=new URL(e);(n.hostname===`localhost`||n.hostname===`127.0.0.1`)&&(t.add(`${n.protocol}//localhost:${n.port||`80`}`),t.add(`${n.protocol}//127.0.0.1:${n.port||`80`}`))}catch{}return[...t]}function jP(e){let t=Pi(e.DB);return bP({baseURL:e.BETTER_AUTH_URL,secret:e.BETTER_AUTH_SECRET,trustedOrigins:AP(e.BETTER_AUTH_URL),database:kP(t,{provider:`sqlite`,schema:Si}),emailAndPassword:{enabled:!0}})}async function MP(e){let t=await jP(e.env).api.getSession({headers:e.req.raw.headers});return t?.user?{id:t.user.id,name:t.user.name,email:t.user.email}:null}export{Oi as _,hN as a,$t as b,EM as c,mw as d,BS as f,Di as g,Pi as h,DN as i,yM as l,Ji as m,xN as n,yN as o,Dx as p,bN as r,AM as s,MP as t,$ as u,Sn as v,ln as x,tn as y};
|