@authhero/drizzle 0.50.2 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drizzle-adapter.cjs +70 -7
- package/dist/drizzle-adapter.mjs +9422 -8416
- package/package.json +3 -3
package/dist/drizzle-adapter.cjs
CHANGED
|
@@ -1,13 +1,76 @@
|
|
|
1
|
-
"use strict";var Zs=Object.defineProperty;var Ks=(n,e,t)=>e in n?Zs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var v=(n,e,t)=>Ks(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const L=Symbol.for("drizzle:entityKind");function ve(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,L))throw new Error(`Class "${e.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 t=Object.getPrototypeOf(n).constructor;if(t)for(;t;){if(L in t&&t[L]===e[L])return!0;t=Object.getPrototypeOf(t)}return!1}var $i;$i=L;class en{constructor(e,t){v(this,"name");v(this,"keyAsName");v(this,"primary");v(this,"notNull");v(this,"default");v(this,"defaultFn");v(this,"onUpdateFn");v(this,"hasDefault");v(this,"isUnique");v(this,"uniqueName");v(this,"uniqueType");v(this,"dataType");v(this,"columnType");v(this,"enumValues");v(this,"generated");v(this,"generatedIdentity");v(this,"config");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}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}v(en,$i,"Column");var ji;ji=L;class Aa{constructor(e,t,i){v(this,"config");v(this,"$default",this.$defaultFn);v(this,"$onUpdate",this.$onUpdateFn);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:i,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}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}}v(Aa,ji,"ColumnBuilder");const Ot=Symbol.for("drizzle:Name"),bi=Symbol.for("drizzle:isPgEnum");function Ws(n){return!!n&&typeof n=="function"&&bi in n&&n[bi]===!0}var Vi;Vi=L;class hi{constructor(e,t,i,o=!1,s=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:o,usedTables:s}}}v(hi,Vi,"Subquery");const Gs={startActiveSpan(n,e){return e()}},Ft=Symbol.for("drizzle:ViewBaseConfig"),In=Symbol.for("drizzle:Schema"),xi=Symbol.for("drizzle:Columns"),ki=Symbol.for("drizzle:ExtraConfigColumns"),Cn=Symbol.for("drizzle:OriginalName"),Dn=Symbol.for("drizzle:BaseName"),_n=Symbol.for("drizzle:IsAlias"),Oi=Symbol.for("drizzle:ExtraConfigBuilder"),Js=Symbol.for("drizzle:IsDrizzleTable");var Hi,Zi,Ki,Wi,Gi,Ji,Qi,Xi,Yi,eo;eo=L,Yi=Ot,Xi=Cn,Qi=In,Ji=xi,Gi=ki,Wi=Dn,Ki=_n,Zi=Js,Hi=Oi;class fe{constructor(e,t,i){v(this,Yi);v(this,Xi);v(this,Qi);v(this,Ji);v(this,Gi);v(this,Wi);v(this,Ki,!1);v(this,Zi,!0);v(this,Hi);this[Ot]=this[Cn]=e,this[In]=t,this[Dn]=i}}v(fe,eo,"Table"),v(fe,"Symbol",{Name:Ot,Schema:In,OriginalName:Cn,Columns:xi,ExtraConfigColumns:ki,BaseName:Dn,IsAlias:_n,ExtraConfigBuilder:Oi});function Ta(n){return n!=null&&typeof n.getSQL=="function"}function Qs(n){var t;const e={sql:"",params:[]};for(const i of n)e.sql+=i.sql,e.params.push(...i.params),(t=i.typings)!=null&&t.length&&(e.typings||(e.typings=[]),e.typings.push(...i.typings));return e}var to;to=L;class we{constructor(e){v(this,"value");this.value=Array.isArray(e)?e:[e]}getSQL(){return new ce([this])}}v(we,to,"StringChunk");var no;no=L;const mt=class mt{constructor(e){v(this,"decoder",Ia);v(this,"shouldInlineParams",!1);v(this,"usedTables",[]);this.queryChunks=e;for(const t of e)if(ve(t,fe)){const i=t[fe.Symbol.Schema];this.usedTables.push(i===void 0?t[fe.Symbol.Name]:i+"."+t[fe.Symbol.Name])}}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Gs.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t==null||t.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:s,escapeParam:l,prepareTyping:d,inlineParams:u,paramStartIndex:f}=i;return Qs(e.map(p=>{var m;if(ve(p,we))return{sql:p.value.join(""),params:[]};if(ve(p,un))return{sql:s(p.value),params:[]};if(p===void 0)return{sql:"",params:[]};if(Array.isArray(p)){const y=[new we("(")];for(const[b,A]of p.entries())y.push(A),b<p.length-1&&y.push(new we(", "));return y.push(new we(")")),this.buildQueryFromSourceParams(y,i)}if(ve(p,mt))return this.buildQueryFromSourceParams(p.queryChunks,{...i,inlineParams:u||p.shouldInlineParams});if(ve(p,fe)){const y=p[fe.Symbol.Schema],b=p[fe.Symbol.Name];return{sql:y===void 0||p[_n]?s(b):s(y)+"."+s(b),params:[]}}if(ve(p,en)){const y=o.getColumnCasing(p);if(t.invokeSource==="indexes")return{sql:s(y),params:[]};const b=p.table[fe.Symbol.Schema];return{sql:p.table[_n]||b===void 0?s(p.table[fe.Symbol.Name])+"."+s(y):s(b)+"."+s(p.table[fe.Symbol.Name])+"."+s(y),params:[]}}if(ve(p,gi)){const y=p[Ft].schema,b=p[Ft].name;return{sql:y===void 0||p[Ft].isAlias?s(b):s(y)+"."+s(b),params:[]}}if(ve(p,zt)){if(ve(p.value,Mt))return{sql:l(f.value++,p),params:[p],typings:["none"]};const y=p.value===null?null:p.encoder.mapToDriverValue(p.value);if(ve(y,mt))return this.buildQueryFromSourceParams([y],i);if(u)return{sql:this.mapInlineParam(y,i),params:[]};let b=["none"];return d&&(b=[d(p.encoder)]),{sql:l(f.value++,y),params:[y],typings:b}}return ve(p,Mt)?{sql:l(f.value++,p),params:[p],typings:["none"]}:ve(p,mt.Aliased)&&p.fieldAlias!==void 0?{sql:s(p.fieldAlias),params:[]}:ve(p,hi)?p._.isWith?{sql:s(p._.alias),params:[]}:this.buildQueryFromSourceParams([new we("("),p._.sql,new we(") "),new un(p._.alias)],i):Ws(p)?p.schema?{sql:s(p.schema)+"."+s(p.enumName),params:[]}:{sql:s(p.enumName),params:[]}:Ta(p)?(m=p.shouldOmitSQLParens)!=null&&m.call(p)?this.buildQueryFromSourceParams([p.getSQL()],i):this.buildQueryFromSourceParams([new we("("),p.getSQL(),new we(")")],i):u?{sql:this.mapInlineParam(p,i),params:[]}:{sql:l(f.value++,p),params:[p],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"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new mt.Aliased(this,e)}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}};v(mt,no,"SQL");let ce=mt;var io;io=L;class un{constructor(e){v(this,"brand");this.value=e}getSQL(){return new ce([this])}}v(un,io,"Name");function Xs(n){return typeof n=="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue=="function"}const Ia={mapFromDriverValue:n=>n},Ca={mapToDriverValue:n=>n};({...Ia,...Ca});var oo;oo=L;class zt{constructor(e,t=Ca){v(this,"brand");this.value=e,this.encoder=t}getSQL(){return new ce([this])}}v(zt,oo,"Param");function O(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new we(n[0]));for(const[i,o]of e.entries())t.push(o,new we(n[i+1]));return new ce(t)}(n=>{function e(){return new ce([])}n.empty=e;function t(u){return new ce(u)}n.fromList=t;function i(u){return new ce([new we(u)])}n.raw=i;function o(u,f){const p=[];for(const[m,y]of u.entries())m>0&&f!==void 0&&p.push(f),p.push(y);return new ce(p)}n.join=o;function s(u){return new un(u)}n.identifier=s;function l(u){return new Mt(u)}n.placeholder=l;function d(u,f){return new zt(u,f)}n.param=d})(O||(O={}));(n=>{var t;t=L;const i=class i{constructor(s,l){v(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=l}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};v(i,t,"SQL.Aliased");let e=i;n.Aliased=e})(ce||(ce={}));var ao;ao=L;class Mt{constructor(e){this.name=e}getSQL(){return new ce([this])}}v(Mt,ao,"Placeholder");const Ys=Symbol.for("drizzle:IsDrizzleView");var so,ro,lo;lo=L,ro=Ft,so=Ys;class gi{constructor({name:e,schema:t,selectedFields:i,query:o}){v(this,ro);v(this,so,!0);this[Ft]={name:e,originalName:e,schema:t,selectedFields:i,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new ce([this])}}v(gi,lo,"View");en.prototype.getSQL=function(){return new ce([this])};fe.prototype.getSQL=function(){return new ce([this])};hi.prototype.getSQL=function(){return new ce([this])};function tn(n,e){return{name:typeof n=="string"&&n.length>0?n:"",config:typeof n=="object"?n:e}}const Da=typeof TextDecoder>"u"?null:new TextDecoder;function ct(n,e){return Xs(e)&&!Ta(n)&&!ve(n,zt)&&!ve(n,Mt)&&!ve(n,en)&&!ve(n,fe)&&!ve(n,gi)?new zt(n,e):n}const c=(n,e)=>O`${n} = ${ct(e,n)}`,er=(n,e)=>O`${n} <> ${ct(e,n)}`;function g(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" and ")),new we(")")])}function $e(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" or ")),new we(")")])}const pn=(n,e)=>O`${n} > ${ct(e,n)}`,At=(n,e)=>O`${n} >= ${ct(e,n)}`,Ge=(n,e)=>O`${n} < ${ct(e,n)}`,yt=(n,e)=>O`${n} <= ${ct(e,n)}`;function De(n,e){return Array.isArray(e)?e.length===0?O`false`:O`${n} in ${e.map(t=>ct(t,n))}`:O`${n} in ${ct(e,n)}`}function Ce(n){return O`${n} is null`}function cn(n){return O`${n} is not null`}function xt(n,e){return O`${n} like ${e}`}function he(n){return O`${n} asc`}function se(n){return O`${n} desc`}function ge(n){return O`count(${O.raw("*")})`.mapWith(Number)}function tr(){const n=e=>{throw new Error(`Actions are not implemented in the Drizzle adapter (called ${e}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>n("create"),get:()=>n("get"),list:()=>n("list"),update:()=>n("update"),remove:()=>n("remove")}}function nr(){const n=e=>{throw new Error(`Action executions are not implemented in the Drizzle adapter (called ${e}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>n("create"),get:()=>n("get")}}function ir(){const n=e=>{throw new Error(`Action versions are not implemented in the Drizzle adapter (called ${e}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>n("create"),get:()=>n("get"),list:()=>n("list"),removeForAction:()=>n("removeForAction")}}var co;co=L;class La{constructor(e,t){v(this,"reference");v(this,"_onUpdate");v(this,"_onDelete");this.reference=()=>{const{name:i,columns:o,foreignColumns:s}=e();return{name:i,columns:o,foreignTable:s[0].table,foreignColumns:s}},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 Ra(e,this)}}v(La,co,"SQLiteForeignKeyBuilder");var _o;_o=L;class Ra{constructor(e,t){v(this,"reference");v(this,"onUpdate");v(this,"onDelete");this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){const{name:e,columns:t,foreignColumns:i}=this.reference(),o=t.map(d=>d.name),s=i.map(d=>d.name),l=[this.table[Ot],...o,i[0].table[Ot],...s];return e??`${l.join("_")}_fk`}}v(Ra,_o,"SQLiteForeignKey");function or(n,e){return`${n[Ot]}_${e.join("_")}_unique`}var uo,po;class je extends(po=Aa,uo=L,po){constructor(){super(...arguments);v(this,"foreignKeyConfigs",[])}references(t,i={}){return this.foreignKeyConfigs.push({ref:t,actions:i}),this}unique(t){return this.config.isUnique=!0,this.config.uniqueName=t,this}generatedAlwaysAs(t,i){return this.config.generated={as:t,type:"always",mode:(i==null?void 0:i.mode)??"virtual"},this}buildForeignKeys(t,i){return this.foreignKeyConfigs.map(({ref:o,actions:s})=>((l,d)=>{const u=new La(()=>{const f=l();return{columns:[t],foreignColumns:[f]}});return d.onUpdate&&u.onUpdate(d.onUpdate),d.onDelete&&u.onDelete(d.onDelete),u.build(i)})(o,s))}}v(je,uo,"SQLiteColumnBuilder");var fo,ho;class Ve extends(ho=en,fo=L,ho){constructor(e,t){t.uniqueName||(t.uniqueName=or(e,[t.name])),super(e,t),this.table=e}}v(Ve,fo,"SQLiteColumn");var go,mo;class Ua extends(mo=je,go=L,mo){constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new Fa(e,this.config)}}v(Ua,go,"SQLiteBigIntBuilder");var yo,vo;class Fa extends(vo=Ve,yo=L,vo){getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){const 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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}}v(Fa,yo,"SQLiteBigInt");var wo,So;class za extends(So=je,wo=L,So){constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new Ma(e,this.config)}}v(za,wo,"SQLiteBlobJsonBuilder");var No,Eo;class Ma extends(Eo=Ve,No=L,Eo){getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){const 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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}}v(Ma,No,"SQLiteBlobJson");var bo,xo;class Pa extends(xo=je,bo=L,xo){constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new qa(e,this.config)}}v(Pa,bo,"SQLiteBlobBufferBuilder");var ko,Oo;class qa extends(Oo=Ve,ko=L,Oo){mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}}v(qa,ko,"SQLiteBlobBuffer");function ar(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="json"?new za(t):(i==null?void 0:i.mode)==="bigint"?new Ua(t):new Pa(t)}var Ao,To;class Ba extends(To=je,Ao=L,To){constructor(e,t,i){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new $a(e,this.config)}}v(Ba,Ao,"SQLiteCustomColumnBuilder");var Io,Co;class $a extends(Co=Ve,Io=L,Co){constructor(t,i){super(t,i);v(this,"sqlName");v(this,"mapTo");v(this,"mapFrom");this.sqlName=i.customTypeParams.dataType(i.fieldConfig),this.mapTo=i.customTypeParams.toDriver,this.mapFrom=i.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(t){return typeof this.mapFrom=="function"?this.mapFrom(t):t}mapToDriverValue(t){return typeof this.mapTo=="function"?this.mapTo(t):t}}v($a,Io,"SQLiteCustomColumn");function sr(n){return(e,t)=>{const{name:i,config:o}=tn(e,t);return new Ba(i,o,n)}}var Do,Lo;class vn extends(Lo=je,Do=L,Lo){constructor(e,t,i){super(e,t,i),this.config.autoIncrement=!1}primaryKey(e){return e!=null&&e.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}}v(vn,Do,"SQLiteBaseIntegerBuilder");var Ro,Uo;class wn extends(Uo=Ve,Ro=L,Uo){constructor(){super(...arguments);v(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}v(wn,Ro,"SQLiteBaseInteger");var Fo,zo;class ja extends(zo=vn,Fo=L,zo){constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Va(e,this.config)}}v(ja,Fo,"SQLiteIntegerBuilder");var Mo,Po;class Va extends(Po=wn,Mo=L,Po){}v(Va,Mo,"SQLiteInteger");var qo,Bo;class Ha extends(Bo=vn,qo=L,Bo){constructor(e,t){super(e,"date","SQLiteTimestamp"),this.config.mode=t}defaultNow(){return this.default(O`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Za(e,this.config)}}v(Ha,qo,"SQLiteTimestampBuilder");var $o,jo;class Za extends(jo=wn,$o=L,jo){constructor(){super(...arguments);v(this,"mode",this.config.mode)}mapFromDriverValue(t){return this.config.mode==="timestamp"?new Date(t*1e3):new Date(t)}mapToDriverValue(t){const i=t.getTime();return this.config.mode==="timestamp"?Math.floor(i/1e3):i}}v(Za,$o,"SQLiteTimestamp");var Vo,Ho;class Ka extends(Ho=vn,Vo=L,Ho){constructor(e,t){super(e,"boolean","SQLiteBoolean"),this.config.mode=t}build(e){return new Wa(e,this.config)}}v(Ka,Vo,"SQLiteBooleanBuilder");var Zo,Ko;class Wa extends(Ko=wn,Zo=L,Ko){constructor(){super(...arguments);v(this,"mode",this.config.mode)}mapFromDriverValue(t){return Number(t)===1}mapToDriverValue(t){return t?1:0}}v(Wa,Zo,"SQLiteBoolean");function w(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="timestamp"||(i==null?void 0:i.mode)==="timestamp_ms"?new Ha(t,i.mode):(i==null?void 0:i.mode)==="boolean"?new Ka(t,i.mode):new ja(t)}var Wo,Go;class Ga extends(Go=je,Wo=L,Go){constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Ja(e,this.config)}}v(Ga,Wo,"SQLiteNumericBuilder");var Jo,Qo;class Ja extends(Qo=Ve,Jo=L,Qo){mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}}v(Ja,Jo,"SQLiteNumeric");var Xo,Yo;class Qa extends(Yo=je,Xo=L,Yo){constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Xa(e,this.config)}}v(Qa,Xo,"SQLiteNumericNumberBuilder");var ea,ta;class Xa extends(ta=Ve,ea=L,ta){constructor(){super(...arguments);v(this,"mapToDriverValue",String)}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}getSQLType(){return"numeric"}}v(Xa,ea,"SQLiteNumericNumber");var na,ia;class Ya extends(ia=je,na=L,ia){constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new es(e,this.config)}}v(Ya,na,"SQLiteNumericBigIntBuilder");var oa,aa;class es extends(aa=Ve,oa=L,aa){constructor(){super(...arguments);v(this,"mapFromDriverValue",BigInt);v(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}v(es,oa,"SQLiteNumericBigInt");function rr(n,e){const{name:t,config:i}=tn(n,e),o=i==null?void 0:i.mode;return o==="number"?new Qa(t):o==="bigint"?new Ya(t):new Ga(t)}var sa,ra;class ts extends(ra=je,sa=L,ra){constructor(e){super(e,"number","SQLiteReal")}build(e){return new ns(e,this.config)}}v(ts,sa,"SQLiteRealBuilder");var la,da;class ns extends(da=Ve,la=L,da){getSQLType(){return"real"}}v(ns,la,"SQLiteReal");function lr(n){return new ts(n??"")}var ca,_a;class is extends(_a=je,ca=L,_a){constructor(e,t){super(e,"string","SQLiteText"),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new os(e,this.config)}}v(is,ca,"SQLiteTextBuilder");var ua,pa;class os extends(pa=Ve,ua=L,pa){constructor(t,i){super(t,i);v(this,"enumValues",this.config.enumValues);v(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}v(os,ua,"SQLiteText");var fa,ha;class as extends(ha=je,fa=L,ha){constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new ss(e,this.config)}}v(as,fa,"SQLiteTextJsonBuilder");var ga,ma;class ss extends(ma=Ve,ga=L,ma){getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}v(ss,ga,"SQLiteTextJson");function r(n,e={}){const{name:t,config:i}=tn(n,e);return i.mode==="json"?new as(t):new is(t,i)}function dr(){return{blob:ar,customType:sr,integer:w,numeric:rr,real:lr,text:r}}const Qn=Symbol.for("drizzle:SQLiteInlineForeignKeys");var ya,va,wa,Sa,Na;class Pt extends(Na=fe,Sa=L,wa=fe.Symbol.Columns,va=Qn,ya=fe.Symbol.ExtraConfigBuilder,Na){constructor(){super(...arguments);v(this,wa);v(this,va,[]);v(this,ya)}}v(Pt,Sa,"SQLiteTable"),v(Pt,"Symbol",Object.assign({},fe.Symbol,{InlineForeignKeys:Qn}));function cr(n,e,t,i,o=n){const s=new Pt(n,i,o),l=typeof e=="function"?e(dr()):e,d=Object.fromEntries(Object.entries(l).map(([f,p])=>{const m=p;m.setName(f);const y=m.build(s);return s[Qn].push(...m.buildForeignKeys(y,s)),[f,y]})),u=Object.assign(s,d);return u[fe.Symbol.Columns]=d,u[fe.Symbol.ExtraConfigColumns]=d,t&&(u[Pt.Symbol.ExtraConfigBuilder]=t),u}const j=(n,e,t)=>cr(n,e,t);var Ea;Ea=L;class mi{constructor(e,t){this.name=e,this.unique=t}on(...e){return new rs(this.name,e,this.unique)}}v(mi,Ea,"SQLiteIndexBuilderOn");var ba;ba=L;class rs{constructor(e,t,i){v(this,"config");this.config={name:e,columns:t,unique:i,where:void 0}}where(e){return this.config.where=e,this}build(e){return new ls(this.config,e)}}v(rs,ba,"SQLiteIndexBuilder");var xa;xa=L;class ls{constructor(e,t){v(this,"config");this.config={...e,table:t}}}v(ls,xa,"SQLiteIndex");function D(n){return new mi(n,!1)}function vt(n){return new mi(n,!0)}function Te(...n){return n[0].columns?new Xn(n[0].columns,n[0].name):new Xn(n)}var ka;ka=L;class Xn{constructor(e,t){v(this,"columns");v(this,"name");this.columns=e,this.name=t}build(e){return new ds(e,this.columns,this.name)}}v(Xn,ka,"SQLitePrimaryKeyBuilder");var Oa;Oa=L;class ds{constructor(e,t,i){v(this,"columns");v(this,"name");this.table=e,this.columns=t,this.name=i}getName(){return this.name??`${this.table[Pt.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}v(ds,Oa,"SQLitePrimaryKey");const B=j("tenants",{id:r("id",{length:191}).primaryKey(),name:r("name",{length:255}),audience:r("audience",{length:255}),sender_email:r("sender_email",{length:255}),sender_name:r("sender_name",{length:255}),language:r("language",{length:255}),logo:r("logo",{length:255}),primary_color:r("primary_color",{length:255}),secondary_color:r("secondary_color",{length:255}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),support_url:r("support_url",{length:255}),idle_session_lifetime:w("idle_session_lifetime"),session_lifetime:w("session_lifetime"),session_cookie:r("session_cookie"),allowed_logout_urls:r("allowed_logout_urls"),ephemeral_session_lifetime:w("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:w("idle_ephemeral_session_lifetime"),default_redirection_uri:r("default_redirection_uri"),default_client_id:r("default_client_id",{length:255}),enabled_locales:r("enabled_locales"),default_directory:r("default_directory",{length:255}),error_page:r("error_page"),flags:r("flags"),friendly_name:r("friendly_name",{length:255}),picture_url:r("picture_url"),support_email:r("support_email",{length:255}),sandbox_version:r("sandbox_version",{length:50}),sandbox_versions_available:r("sandbox_versions_available"),legacy_sandbox_version:r("legacy_sandbox_version",{length:50}),change_password:r("change_password"),guardian_mfa_page:r("guardian_mfa_page"),device_flow:r("device_flow"),default_token_quota:r("default_token_quota"),default_audience:r("default_audience",{length:255}),default_organization:r("default_organization",{length:255}),sessions:r("sessions"),oidc_logout:r("oidc_logout"),allow_organization_name_in_authentication_api:w("allow_organization_name_in_authentication_api"),customize_mfa_in_postlogin_action:w("customize_mfa_in_postlogin_action"),acr_values_supported:r("acr_values_supported"),mtls:r("mtls"),pushed_authorization_requests_supported:w("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:w("authorization_response_iss_parameter_supported")}),H=j("users",{user_id:r("user_id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),email:r("email",{length:255}),given_name:r("given_name",{length:255}),family_name:r("family_name",{length:255}),nickname:r("nickname",{length:255}),name:r("name",{length:255}),picture:r("picture",{length:2083}),tags:r("tags",{length:255}),phone_number:r("phone_number",{length:17}),phone_verified:w("phone_verified",{mode:"boolean"}),username:r("username",{length:128}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),linked_to:r("linked_to",{length:255}),last_ip:r("last_ip",{length:255}),login_count:w("login_count").notNull(),last_login:r("last_login",{length:255}),registration_completed_at:r("registration_completed_at",{length:35}),provider:r("provider",{length:255}).notNull(),connection:r("connection",{length:255}),email_verified:w("email_verified",{mode:"boolean"}).notNull(),is_social:w("is_social",{mode:"boolean"}).notNull(),app_metadata:r("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:r("user_metadata").notNull().default("{}"),profileData:r("profileData",{length:2048}),locale:r("locale",{length:255}),middle_name:r("middle_name",{length:100}),preferred_username:r("preferred_username",{length:255}),profile:r("profile"),website:r("website"),gender:r("gender",{length:50}),birthdate:r("birthdate",{length:10}),zoneinfo:r("zoneinfo",{length:100}),address:r("address")},n=>[Te({columns:[n.user_id,n.tenant_id],name:"users_tenants"}),vt("unique_email_provider").on(n.email,n.provider,n.tenant_id),vt("unique_phone_provider").on(n.phone_number,n.provider,n.tenant_id),vt("unique_username_provider").on(n.username,n.provider,n.tenant_id),D("users_email_index").on(n.email),D("users_linked_to_index").on(n.linked_to),D("users_name_index").on(n.name),D("users_phone_tenant_provider_index").on(n.tenant_id,n.phone_number,n.provider)]),oe=j("passwords",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),password:r("password",{length:255}).notNull(),algorithm:r("algorithm",{length:16}).notNull().default("bcrypt"),is_current:w("is_current").notNull().default(1)}),ae=j("sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),expires_at_ts:w("expires_at_ts"),idle_expires_at_ts:w("idle_expires_at_ts"),authenticated_at_ts:w("authenticated_at_ts"),last_interaction_at_ts:w("last_interaction_at_ts"),used_at_ts:w("used_at_ts"),revoked_at_ts:w("revoked_at_ts"),device:r("device").notNull(),clients:r("clients").notNull(),login_session_id:r("login_session_id",{length:21})},n=>[Te({columns:[n.tenant_id,n.id],name:"sessions_pk"}),D("IDX_sessions_login_session_id").on(n.login_session_id),D("idx_sessions_user_id").on(n.tenant_id,n.user_id),D("idx_sessions_expires_at_ts").on(n.expires_at_ts)]),W=j("refresh_tokens",{id:r("id",{length:26}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),login_id:r("login_id",{length:26}).notNull(),user_id:r("user_id",{length:255}),resource_servers:r("resource_servers").notNull(),device:r("device").notNull(),rotating:w("rotating",{mode:"boolean"}).notNull(),token_lookup:r("token_lookup",{length:16}),token_hash:r("token_hash",{length:64}),family_id:r("family_id",{length:26}),rotated_to:r("rotated_to",{length:26}),rotated_at_ts:w("rotated_at_ts"),created_at_ts:w("created_at_ts").notNull(),expires_at_ts:w("expires_at_ts"),idle_expires_at_ts:w("idle_expires_at_ts"),last_exchanged_at_ts:w("last_exchanged_at_ts"),revoked_at_ts:w("revoked_at_ts")},n=>[Te({columns:[n.tenant_id,n.id],name:"refresh_tokens_pk"}),D("idx_refresh_tokens_user_id").on(n.tenant_id,n.user_id),D("idx_refresh_tokens_login_id").on(n.login_id),D("idx_refresh_tokens_expires_at_ts").on(n.expires_at_ts),D("idx_refresh_tokens_token_lookup").on(n.tenant_id,n.token_lookup),D("idx_refresh_tokens_family_id").on(n.tenant_id,n.family_id)]),Y=j("login_sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),session_id:r("session_id",{length:21}),csrf_token:r("csrf_token",{length:21}).notNull(),auth_params:r("auth_params"),authorization_url:r("authorization_url"),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),expires_at_ts:w("expires_at_ts").notNull(),ip:r("ip",{length:39}),useragent:r("useragent"),auth0Client:r("auth0Client",{length:255}),state:r("state",{length:50}).notNull().default("pending"),state_data:r("state_data"),failure_reason:r("failure_reason"),user_id:r("user_id",{length:255}),auth_connection:r("auth_connection",{length:255}),auth_strategy_strategy:r("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:r("auth_strategy_strategy_type",{length:64}),authenticated_at:r("authenticated_at",{length:35})},n=>[Te({columns:[n.tenant_id,n.id],name:"login_sessions_pk"}),D("login_sessions_id_index").on(n.id),D("login_sessions_state_idx").on(n.state),D("login_sessions_state_updated_idx").on(n.state,n.updated_at_ts),D("login_sessions_tenant_user_idx").on(n.tenant_id,n.user_id),D("idx_login_sessions_expires_at_ts").on(n.expires_at_ts)]),re=j("codes",{code_id:r("code_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}),login_id:r("login_id",{length:255}),connection_id:r("connection_id",{length:255}),code_type:r("code_type",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),code_verifier:r("code_verifier",{length:128}),code_challenge:r("code_challenge",{length:128}),code_challenge_method:r("code_challenge_method",{length:5}),redirect_uri:r("redirect_uri",{length:1024}),nonce:r("nonce",{length:1024}),state:r("state",{length:2048})},n=>[Te({columns:[n.code_id,n.code_type],name:"PK_codes_code_id_code_type"}),D("codes_expires_at_index").on(n.expires_at)]),_r=j("authentication_codes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),user_id:r("user_id",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:8192}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),ur=j("otps",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),code:r("code",{length:255}).notNull(),email:r("email",{length:255}).notNull(),user_id:r("user_id",{length:255}),send:r("send",{length:255}),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),audience:r("audience",{length:255}),ip:r("ip",{length:64})},n=>[D("otps_email_index").on(n.email),D("otps_expires_at_index").on(n.expires_at)]),pr=j("tickets",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),email:r("email",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),Z=j("clients",{client_id:r("client_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),description:r("description",{length:140}),global:w("global").notNull().default(0),client_secret:r("client_secret",{length:255}),app_type:r("app_type",{length:64}).default("regular_web"),logo_uri:r("logo_uri",{length:2083}),is_first_party:w("is_first_party").notNull().default(0),oidc_conformant:w("oidc_conformant").notNull().default(1),auth0_conformant:w("auth0_conformant").notNull().default(1),callbacks:r("callbacks").notNull(),allowed_origins:r("allowed_origins").notNull(),web_origins:r("web_origins").notNull(),client_aliases:r("client_aliases").notNull(),allowed_clients:r("allowed_clients").notNull(),allowed_logout_urls:r("allowed_logout_urls").notNull(),session_transfer:r("session_transfer").notNull(),oidc_logout:r("oidc_logout").notNull(),grant_types:r("grant_types").notNull(),jwt_configuration:r("jwt_configuration").notNull(),signing_keys:r("signing_keys").notNull(),encryption_key:r("encryption_key").notNull(),sso:w("sso").notNull().default(0),sso_disabled:w("sso_disabled").notNull().default(1),cross_origin_authentication:w("cross_origin_authentication").notNull().default(0),cross_origin_loc:r("cross_origin_loc",{length:2083}),custom_login_page_on:w("custom_login_page_on").notNull().default(0),custom_login_page:r("custom_login_page"),custom_login_page_preview:r("custom_login_page_preview"),form_template:r("form_template"),addons:r("addons").notNull(),token_endpoint_auth_method:r("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:r("client_metadata").notNull(),mobile:r("mobile").notNull(),initiate_login_uri:r("initiate_login_uri",{length:2083}),native_social_login:r("native_social_login").notNull(),refresh_token:r("refresh_token").notNull(),default_organization:r("default_organization").notNull(),organization_usage:r("organization_usage",{length:32}).default("deny"),organization_require_behavior:r("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:r("client_authentication_methods").notNull(),require_pushed_authorization_requests:w("require_pushed_authorization_requests").notNull().default(0),require_proof_of_possession:w("require_proof_of_possession").notNull().default(0),hide_sign_up_disabled_error:w("hide_sign_up_disabled_error").notNull().default(0),signed_request_object:r("signed_request_object").notNull(),compliance_level:r("compliance_level",{length:64}),par_request_expiry:w("par_request_expiry"),token_quota:r("token_quota").notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),connections:r("connections").notNull().default("[]"),owner_user_id:r("owner_user_id",{length:255}),registration_type:r("registration_type",{length:32}),registration_metadata:r("registration_metadata"),user_linking_mode:r("user_linking_mode",{length:16})},n=>[Te({columns:[n.tenant_id,n.client_id],name:"clients_tenant_id_client_id"}),D("idx_clients_owner_user_id").on(n.tenant_id,n.owner_user_id)]),X=j("client_registration_tokens",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),token_hash:r("token_hash",{length:64}).notNull(),type:r("type",{length:8}).notNull(),client_id:r("client_id",{length:191}),sub:r("sub",{length:255}),constraints:r("constraints"),single_use:w("single_use").notNull().default(0),used_at_ts:w("used_at_ts"),expires_at_ts:w("expires_at_ts"),created_at_ts:w("created_at_ts").notNull(),revoked_at_ts:w("revoked_at_ts")},n=>[vt("idx_client_registration_tokens_hash").on(n.tenant_id,n.token_hash),D("idx_client_registration_tokens_client").on(n.tenant_id,n.client_id)]),ye=j("client_grants",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),audience:r("audience",{length:191}).notNull(),scope:r("scope").default("[]"),organization_usage:r("organization_usage",{length:32}),allow_any_organization:w("allow_any_organization").default(0),is_system:w("is_system").default(0),subject_type:r("subject_type",{length:32}),authorization_details_types:r("authorization_details_types").default("[]"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"pk_client_grants"}),D("idx_client_grants_audience").on(n.audience)]),pe=j("connections",{id:r("id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),response_type:r("response_type",{length:255}),response_mode:r("response_mode",{length:255}),strategy:r("strategy",{length:64}),options:r("options",{length:8192}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),display_name:r("display_name",{length:255}),is_domain_connection:w("is_domain_connection"),show_as_button:w("show_as_button"),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096})},n=>[Te({columns:[n.tenant_id,n.id]}),D("connections_tenant_id_index").on(n.tenant_id),vt("connections_id_unique").on(n.id)]),Ie=j("custom_domains",{custom_domain_id:r("custom_domain_id",{length:256}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),primary:w("primary",{mode:"boolean"}).notNull(),status:r("status",{length:50}).notNull(),type:r("type",{length:50}).notNull(),origin_domain_name:r("origin_domain_name",{length:255}),verification:r("verification",{length:2048}),custom_client_ip_header:r("custom_client_ip_header",{length:50}),tls_policy:r("tls_policy",{length:50}),domain_metadata:r("domain_metadata",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("custom_domains_domain_unique").on(n.domain)]),fr=j("domains",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),email_service:r("email_service",{length:255}),email_api_key:r("email_api_key",{length:255}),dkim_private_key:r("dkim_private_key",{length:2048}),dkim_public_key:r("dkim_public_key",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),ee=j("organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:256}).notNull(),display_name:r("display_name",{length:256}),branding:r("branding"),metadata:r("metadata"),enabled_connections:r("enabled_connections"),token_quota:r("token_quota"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("idx_organizations_tenant_id").on(n.tenant_id)]),le=j("user_organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("user_organizations_unique").on(n.tenant_id,n.user_id,n.organization_id),D("idx_user_organizations_tenant_id").on(n.tenant_id),D("idx_user_organizations_user_id").on(n.user_id),D("idx_user_organizations_organization_id").on(n.organization_id)]),xe=j("invites",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),inviter:r("inviter").notNull(),invitee:r("invitee").notNull(),client_id:r("client_id",{length:191}).notNull(),connection_id:r("connection_id",{length:21}),invitation_url:r("invitation_url").notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),app_metadata:r("app_metadata"),user_metadata:r("user_metadata"),roles:r("roles"),ticket_id:r("ticket_id",{length:191}),ttl_sec:w("ttl_sec"),send_invitation_email:w("send_invitation_email")},n=>[D("idx_invites_tenant_id").on(n.tenant_id),D("idx_invites_organization_id").on(n.organization_id),D("idx_invites_expires_at").on(n.expires_at),D("idx_invites_tenant_created").on(n.tenant_id,n.created_at)]),_e=j("roles",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:50}).notNull(),description:r("description",{length:255}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"roles_pk"})]),Re=j("role_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),created_at:r("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.role_id,n.resource_server_identifier,n.permission_name],name:"role_permissions_pk"}),D("role_permissions_role_fk").on(n.tenant_id,n.role_id),D("role_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name)]),qe=j("user_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull().default(""),created_at:r("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.user_id,n.resource_server_identifier,n.permission_name,n.organization_id],name:"user_permissions_pk"}),D("user_permissions_user_fk").on(n.tenant_id,n.user_id),D("user_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name),D("user_permissions_organization_fk").on(n.organization_id)]),Be=j("user_roles",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),organization_id:r("organization_id",{length:191}).notNull().default(""),created_at:r("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.user_id,n.role_id,n.organization_id],name:"user_roles_pk"}),D("user_roles_user_fk").on(n.tenant_id,n.user_id),D("user_roles_role_fk").on(n.tenant_id,n.role_id),D("user_roles_organization_fk").on(n.organization_id)]),te=j("resource_servers",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),identifier:r("identifier",{length:191}).notNull(),name:r("name",{length:255}).notNull(),scopes:r("scopes",{length:4096}),signing_alg:r("signing_alg",{length:64}),signing_secret:r("signing_secret",{length:2048}),token_lifetime:w("token_lifetime"),token_lifetime_for_web:w("token_lifetime_for_web"),skip_consent_for_verifiable_first_party_clients:w("skip_consent_for_verifiable_first_party_clients"),allow_offline_access:w("allow_offline_access"),verification_key:r("verification_key",{length:4096}),options:r("options",{length:4096}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"resource_servers_pk"})]),Rt=j("branding",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),logo_url:r("logo_url",{length:512}),favicon_url:r("favicon_url",{length:512}),font_url:r("font_url",{length:512}),colors_primary:r("colors_primary",{length:8}),colors_page_background_type:r("colors_page_background_type",{length:32}),colors_page_background_start:r("colors_page_background_start",{length:8}),colors_page_background_end:r("colors_page_background_end",{length:8}),colors_page_background_angle_dev:w("colors_page_background_angle_dev"),dark_mode:r("dark_mode",{length:8})}),lt=j("universal_login_templates",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),body:r("body").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()}),Ze=j("themes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),themeId:r("themeId",{length:255}).notNull(),displayName:r("displayName",{length:255}).notNull(),colors_primary_button_label:r("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:r("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:r("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:r("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:r("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:r("colors_base_hover_color",{length:24}).notNull(),colors_body_text:r("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:r("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:r("colors_error",{length:24}).notNull(),colors_header:r("colors_header",{length:24}).notNull(),colors_icons:r("colors_icons",{length:24}).notNull(),colors_input_background:r("colors_input_background",{length:24}).notNull(),colors_input_border:r("colors_input_border",{length:24}).notNull(),colors_input_filled_text:r("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:r("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:r("colors_links_focused_components",{length:24}).notNull(),colors_success:r("colors_success",{length:24}).notNull(),colors_widget_background:r("colors_widget_background",{length:24}).notNull(),colors_widget_border:r("colors_widget_border",{length:24}).notNull(),borders_button_border_radius:w("borders_button_border_radius").notNull(),borders_button_border_weight:w("borders_button_border_weight").notNull(),borders_buttons_style:r("borders_buttons_style",{length:24}).notNull(),borders_input_border_radius:w("borders_input_border_radius").notNull(),borders_input_border_weight:w("borders_input_border_weight").notNull(),borders_inputs_style:r("borders_inputs_style",{length:24}).notNull(),borders_show_widget_shadow:w("borders_show_widget_shadow",{mode:"boolean"}).notNull(),borders_widget_border_weight:w("borders_widget_border_weight").notNull(),borders_widget_corner_radius:w("borders_widget_corner_radius").notNull(),fonts_body_text_bold:w("fonts_body_text_bold").notNull(),fonts_body_text_size:w("fonts_body_text_size").notNull(),fonts_buttons_text_bold:w("fonts_buttons_text_bold").notNull(),fonts_buttons_text_size:w("fonts_buttons_text_size").notNull(),fonts_font_url:r("fonts_font_url",{length:255}).notNull(),fonts_input_labels_bold:w("fonts_input_labels_bold").notNull(),fonts_input_labels_size:w("fonts_input_labels_size").notNull(),fonts_links_bold:w("fonts_links_bold",{mode:"boolean"}).notNull(),fonts_links_size:w("fonts_links_size").notNull(),fonts_links_style:r("fonts_links_style",{length:24}).notNull(),fonts_reference_text_size:w("fonts_reference_text_size").notNull(),fonts_subtitle_bold:w("fonts_subtitle_bold",{mode:"boolean"}).notNull(),fonts_subtitle_size:w("fonts_subtitle_size").notNull(),fonts_title_bold:w("fonts_title_bold",{mode:"boolean"}).notNull(),fonts_title_size:w("fonts_title_size").notNull(),page_background_background_color:r("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:r("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:r("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:r("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:w("widget_logo_height").notNull(),widget_logo_position:r("widget_logo_position",{length:24}).notNull(),widget_logo_url:r("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:r("widget_social_buttons_layout",{length:24}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.themeId],name:"themes_pkey"}),D("themes_tenant_id_idx").on(n.tenant_id)]),ke=j("forms",{id:r("id",{length:255}).primaryKey(),name:r("name",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),messages:r("messages",{length:255}),languages:r("languages",{length:255}),translations:r("translations",{length:4096}),nodes:r("nodes",{length:4096}),start:r("start",{length:255}),ending:r("ending",{length:255}),style:r("style",{length:1042}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("forms_tenant_id_idx").on(n.tenant_id)]),Oe=j("flows",{id:r("id",{length:24}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:150}).notNull(),actions:r("actions"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("flows_tenant_id_idx").on(n.tenant_id)]),Ut=j("prompt_settings",{tenant_id:r("tenant_id",{length:191}).primaryKey(),universal_login_experience:r("universal_login_experience",{length:16}).notNull().default("new"),identifier_first:w("identifier_first",{mode:"boolean"}).notNull().default(!0),password_first:w("password_first",{mode:"boolean"}).notNull().default(!1),webauthn_platform_first_factor:w("webauthn_platform_first_factor",{mode:"boolean"}).notNull().default(!1)}),dt=j("email_providers",{tenant_id:r("tenant_id",{length:191}).primaryKey(),name:r("name",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),default_from_address:r("default_from_address",{length:255}),credentials:r("credentials",{length:2048}).notNull().default("{}"),settings:r("settings",{length:2048}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),Ue=j("email_templates",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),template:r("template",{length:64}).notNull(),body:r("body").notNull(),from:r("from",{length:255}).notNull(),subject:r("subject",{length:255}).notNull(),syntax:r("syntax",{length:16}).notNull().default("liquid"),result_url:r("result_url",{length:2048}),url_lifetime_in_seconds:w("url_lifetime_in_seconds"),include_email_in_redirect:w("include_email_in_redirect",{mode:"boolean"}).notNull().default(!1),enabled:w("enabled",{mode:"boolean"}).notNull().default(!0),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.template]})]),me=j("hooks",{hook_id:r("hook_id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),url:r("url",{length:512}),trigger_id:r("trigger_id",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),synchronous:w("synchronous",{mode:"boolean"}).notNull().default(!1),priority:w("priority"),form_id:r("form_id",{length:128}),template_id:r("template_id",{length:64}),code_id:r("code_id",{length:21}),metadata:r("metadata")},n=>[D("hooks_tenant_id_idx").on(n.tenant_id)]),Ke=j("hook_code",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code").notNull(),secrets:r("secrets"),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[D("hook_code_tenant_id_idx").on(n.tenant_id)]),We=j("keys",{kid:r("kid",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).references(()=>B.id,{onDelete:"cascade"}),created_at:r("created_at",{length:35}).notNull(),revoked_at:r("revoked_at",{length:35}),cert:r("cert",{length:4096}),pkcs7:r("pkcs7",{length:4096}),fingerprint:r("fingerprint",{length:256}),thumbprint:r("thumbprint",{length:256}),current_since:r("current_since",{length:35}),current_until:r("current_until",{length:35}),type:r("type",{length:50}).notNull().default("jwt_signing"),connection:r("connection",{length:255}).references(()=>pe.id,{onDelete:"cascade"})}),Ne=j("custom_text",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),prompt:r("prompt",{length:64}).notNull(),language:r("language",{length:16}).notNull(),custom_text:r("custom_text").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[Te({columns:[n.tenant_id,n.prompt,n.language]})]),ue=j("authentication_methods",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),type:r("type",{length:32}).notNull(),phone_number:r("phone_number",{length:32}),totp_secret:r("totp_secret",{length:255}),credential_id:r("credential_id",{length:512}),public_key:r("public_key"),sign_count:w("sign_count"),credential_backed_up:w("credential_backed_up"),transports:r("transports",{length:512}),friendly_name:r("friendly_name",{length:255}),confirmed:w("confirmed").notNull().default(0),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[D("authentication_methods_tenant_user_idx").on(n.tenant_id,n.user_id),D("authentication_methods_credential_id_idx").on(n.credential_id)]),F=j("logs",{log_id:r("log_id",{length:21}).primaryKey(),category:r("category",{length:255}),tenant_id:r("tenant_id",{length:64}),user_id:r("user_id",{length:64}),ip:r("ip",{length:255}),type:r("type",{length:8}).notNull(),date:r("date",{length:35}).notNull(),client_id:r("client_id",{length:255}),client_name:r("client_name",{length:255}),user_agent:r("user_agent",{length:255}),description:r("description",{length:255}),details:r("details",{length:2048}),isMobile:w("isMobile"),user_name:r("user_name",{length:255}),connection:r("connection",{length:255}),connection_id:r("connection_id",{length:255}),audience:r("audience",{length:255}),scope:r("scope",{length:255}),strategy:r("strategy",{length:255}),strategy_type:r("strategy_type",{length:255}),hostname:r("hostname",{length:255}),auth0_client:r("auth0_client",{length:8192}),session_connection:r("session_connection",{length:255}),country_code:r("country_code",{length:2}),city_name:r("city_name",{length:255}),latitude:r("latitude",{length:255}),longitude:r("longitude",{length:255}),time_zone:r("time_zone",{length:255}),continent_code:r("continent_code",{length:2})},n=>[D("logs_user_id").on(n.user_id),D("logs_tenant_id").on(n.tenant_id),D("logs_date").on(n.date),D("IDX_logs_tenant_date_type_user").on(n.tenant_id,n.date,n.type,n.user_id)]),P=j("outbox_events",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),event_type:r("event_type",{length:64}).notNull(),log_type:r("log_type",{length:64}).notNull(),aggregate_type:r("aggregate_type",{length:64}).notNull(),aggregate_id:r("aggregate_id",{length:255}).notNull(),payload:r("payload").notNull(),created_at:r("created_at",{length:35}).notNull(),processed_at:r("processed_at",{length:35}),retry_count:w("retry_count").notNull().default(0),next_retry_at:r("next_retry_at",{length:35}),error:r("error"),claimed_by:r("claimed_by",{length:255}),claim_expires_at:r("claim_expires_at",{length:35}),dead_lettered_at:r("dead_lettered_at",{length:35}),final_error:r("final_error")},n=>[D("idx_outbox_events_tenant_id").on(n.tenant_id),D("idx_outbox_events_processed_at").on(n.processed_at),D("idx_outbox_events_claimed_by").on(n.claimed_by),D("idx_outbox_events_tenant_dead_lettered").on(n.tenant_id,n.dead_lettered_at)]),hr=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:_r,authenticationMethods:ue,branding:Rt,clientGrants:ye,clientRegistrationTokens:X,clients:Z,codes:re,connections:pe,customDomains:Ie,customText:Ne,domains:fr,emailProviders:dt,emailTemplates:Ue,flows:Oe,forms:ke,hookCode:Ke,hooks:me,invites:xe,keys:We,loginSessions:Y,logs:F,organizations:ee,otps:ur,outboxEvents:P,passwords:oe,promptSettings:Ut,refreshTokens:W,resourceServers:te,rolePermissions:Re,roles:_e,sessions:ae,tenants:B,themes:Ze,tickets:pr,universalLoginTemplates:lt,userOrganizations:le,userPermissions:qe,userRoles:Be,users:H},Symbol.toStringTag,{value:"Module"}));function G(n){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(t=>t!==null&&typeof t=="object"?G(t):t);const e={...n};for(const t in e){const i=e[t];i===null?delete e[t]:i!==null&&typeof i=="object"&&(Array.isArray(i)?e[t]=i.map(o=>o!==null&&typeof o=="object"?G(o):o):e[t]=G(i))}return e}function gr(n,e,t={...n}){for(const i of e)n[i]!==void 0&&(t[i]=JSON.stringify(n[i]));return t}function mr(n,e,t=n){for(const i of e)n[i]!==void 0&&(t[i]=n[i]?1:0)}function cs(n){const e={};for(const t in n)n[t]!==void 0&&n[t]!==null&&(e[t]=n[t]);return e}function z(n,e){if(n==null)return e;if(typeof n=="string")try{return JSON.parse(n)}catch{return e}return n}function Yn(n,e="",t={}){for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const o=e?`${e}_${i}`:i,s=n[i];typeof s=="object"&&s!==null&&!Array.isArray(s)?Yn(s,o,t):typeof s=="boolean"?t[o]=s?1:0:t[o]=s}return t}function _s(n,e){const t={};for(const[i,o]of Object.entries(n)){const s=e.find(l=>i.startsWith(`${l}_`));if(!s)t[i]=o;else{const l=i.slice(s.length+1);t[s]={...t[s],[l]:o}}}return t}function yr(n){return typeof n=="string"?parseInt(n,10):typeof n=="bigint"?Number(n):n}function vr(n){return n==="dark"||n==="light"||n==="auto"}function wr(n){return{async get(e){const t=await n.select().from(Rt).where(c(Rt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,colors_primary:o,colors_page_background_type:s,colors_page_background_start:l,colors_page_background_end:d,colors_page_background_angle_dev:u,font_url:f,dark_mode:p,...m}=t;return G({...m,colors:{primary:o,page_background:{type:s,start:l,end:d,angle_deg:u}},font:f?{url:f}:void 0,dark_mode:vr(p)?p:void 0})},async set(e,t){const{colors:i,font:o,dark_mode:s,...l}=t,d=i==null?void 0:i.page_background,u=d&&typeof d=="object"?d:void 0,f={...l,colors_primary:i==null?void 0:i.primary,colors_page_background_type:u==null?void 0:u.type,colors_page_background_start:u==null?void 0:u.start,colors_page_background_end:u==null?void 0:u.end,colors_page_background_angle_dev:u==null?void 0:u.angle_deg,font_url:o==null?void 0:o.url,dark_mode:s};await n.insert(Rt).values({tenant_id:e,...f}).onConflictDoUpdate({target:Rt.tenant_id,set:f})}}}var _t=class extends Error{constructor(e=500,t){super(t==null?void 0:t.message,{cause:t==null?void 0:t.cause});v(this,"res");v(this,"status");this.res=t==null?void 0:t.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};function Qe(n,e,t){const i=e.split(/ OR /i);if(i.length>1){const f=i.map(p=>{const m=p.trim().match(/^([^:]+):(.+)$/);if(m){const[,y,b]=m;if(!y||!b)return null;const A=b.replace(/^"(.*)"$/,"$1"),J=n[y.trim()];return J?c(J,A.trim()):null}return null}).filter(Boolean);return f.length===0?void 0:$e(...f)}const o=[];let s="",l=!1;for(let f=0;f<e.length;f++){const p=e[f];p==='"'?(l=!l,s+=p):p===" "&&!l?s.trim()&&(o.push(s.trim()),s=""):s+=p}s.trim()&&o.push(s.trim());const d=o.filter(f=>f!=="AND").map(f=>f.replace(/^([^:]+)=/g,"$1:")).map(f=>{let p=f.startsWith("-"),m=null,y="",b=!1,A;if(f.startsWith("-_exists_:"))m=f.substring(10),b=!0,p=!0;else if(f.startsWith("_exists_:"))m=f.substring(9),b=!0,p=!1;else if(f.includes(":")){const J=p?f.substring(1):f,Q=J.indexOf(":");m=J.substring(0,Q),y=J.substring(Q+1),b=!1,y.startsWith(">=")?(A=">=",y=y.substring(2)):y.startsWith(">")?(A=">",y=y.substring(1)):y.startsWith("<=")?(A="<=",y=y.substring(2)):y.startsWith("<")?(A="<",y=y.substring(1)):A="=",y.startsWith('"')&&y.endsWith('"')&&y.length>1&&(y=y.slice(1,-1))}else m=null,y=f,b=!1;return{key:m,value:y,isNegation:p,isExistsQuery:b,operator:A}}),u=[];for(const{key:f,value:p,isNegation:m,isExistsQuery:y,operator:b}of d)if(f){const A=n[f];if(!A){y?u.push(m?O`${O.identifier(f)} IS NULL`:O`${O.identifier(f)} IS NOT NULL`):u.push(O`${O.identifier(f)} ${O.raw(m?"!=":b??"=")} ${p}`);continue}if(y)u.push(m?Ce(A):cn(A));else if(m)switch(b){case">":u.push(yt(A,p));break;case">=":u.push(Ge(A,p));break;case"<":u.push(At(A,p));break;case"<=":u.push(pn(A,p));break;default:u.push(er(A,p))}else switch(b){case">":u.push(pn(A,p));break;case">=":u.push(At(A,p));break;case"<":u.push(Ge(A,p));break;case"<=":u.push(yt(A,p));break;default:u.push(c(A,p))}}else if(p){const J=(p.includes("|")?[...t,"user_id"]:t).map(Q=>{const ie=n[Q];return ie?Q==="user_id"?c(ie,p):xt(ie,`%${p}%`):null}).filter(Boolean);J.length>0&&u.push($e(...J))}if(u.length!==0)return u.length===1?u[0]:g(...u)}const yi=["global","is_first_party","oidc_conformant","auth0_conformant","sso","sso_disabled","cross_origin_authentication","custom_login_page_on","require_pushed_authorization_requests","require_proof_of_possession","hide_sign_up_disabled_error"],vi=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],wi=["session_transfer","oidc_logout","jwt_configuration","encryption_key","addons","client_metadata","mobile","native_social_login","refresh_token","default_organization","client_authentication_methods","signed_request_object","token_quota","registration_metadata"];function on(n){const{tenant_id:e,connections:t,...i}=n,o={...i};for(const s of yi)o[s]=!!i[s];for(const s of vi)o[s]=z(i[s],[]);for(const s of wi)o[s]=z(i[s],{});return o.connections=z(t,[]),G(o)}function Ai(n){const e={...n};mr(n,yi,e);for(const t of vi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||[]));for(const t of wi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||{}));return n.connections!==void 0&&(e.connections=JSON.stringify(n.connections||[])),cs(e)}function Sr(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),o={client_id:t.client_id,tenant_id:e,name:t.name,description:t.description,app_type:t.app_type??"regular_web",logo_uri:t.logo_uri,client_secret:t.client_secret,token_endpoint_auth_method:t.token_endpoint_auth_method??"client_secret_basic",cross_origin_loc:t.cross_origin_loc,custom_login_page:t.custom_login_page,custom_login_page_preview:t.custom_login_page_preview,form_template:t.form_template,initiate_login_uri:t.initiate_login_uri,organization_usage:t.organization_usage??"deny",organization_require_behavior:t.organization_require_behavior??"no_prompt",compliance_level:t.compliance_level,par_request_expiry:t.par_request_expiry,created_at:i,updated_at:i};for(const u of yi)o[u]=t[u]??!1;o.oidc_conformant=t.oidc_conformant??!0,o.auth0_conformant=t.auth0_conformant??!0,o.sso_disabled=t.sso_disabled??!1;for(const u of vi)o[u]=t[u]||[];for(const u of wi)o[u]=t[u]||{};o.connections=t.connections||[];const s=Ai(o);try{await n.insert(Z).values({...s,tenant_id:e})}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(d=u==null?void 0:u.message)!=null&&d.includes("duplicate key")?new _t(409,{message:"Client already exists"}):u}return on({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).get();return i?on(i):null},async getByClientId(e){const t=await n.select().from(Z).where(c(Z.client_id,e)).get();return t?{...on(t),tenant_id:t.tenant_id}:null},async update(e,t,i){const o=Ai({...i,updated_at:new Date().toISOString()});return delete o.client_id,delete o.tenant_id,await n.update(Z).set(o).where(g(c(Z.tenant_id,e),c(Z.client_id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(Z).where(c(Z.tenant_id,e)).$dynamic();if(d){const y=Qe(Z,d,["name","client_id"]);y&&(u=u.where(g(c(Z.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=Z[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(on);if(!s)return{clients:p};const[m]=await n.select({count:ge()}).from(Z).where(c(Z.tenant_id,e));return{clients:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).returning()).length>0}}}function Nr(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return G({...s,options:z(i,{}),metadata:z(o),is_system:t?!0:void 0})}function Er(n){return{async listByClient(e,t){const i=await n.select({connections:Z.connections}).from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).get();if(!i)return[];const o=z(i.connections,[])||[];if(o.length===0)return[];const l=(await n.select().from(pe).where(g(c(pe.tenant_id,e),De(pe.id,o))).all()).map(Nr);return o.map(d=>l.find(u=>u.id===d)).filter(Boolean)},async updateByClient(e,t,i){return(await n.update(Z).set({connections:JSON.stringify([...new Set(i)])}).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).returning()).length>0},async listByConnection(e,t){return(await n.select({client_id:Z.client_id,connections:Z.connections}).from(Z).where(c(Z.tenant_id,e)).all()).filter(o=>(z(o.connections,[])||[]).includes(t)).map(o=>o.client_id)},async addClientToConnection(e,t,i){var d;if(!await n.select({client_id:Z.client_id}).from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,i))).get())return!1;const s=await n.run(O`UPDATE clients SET connections = CASE
|
|
1
|
+
"use strict";var cc=Object.defineProperty;var uc=(e,t,n)=>t in e?cc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var b=(e,t,n)=>uc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const D=Symbol.for("drizzle:entityKind");function Ne(e,t){if(!e||typeof e!="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,D))throw new 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(D in n&&n[D]===t[D])return!0;n=Object.getPrototypeOf(n)}return!1}var ho;ho=D;class Kt{constructor(t,n){b(this,"name");b(this,"keyAsName");b(this,"primary");b(this,"notNull");b(this,"default");b(this,"defaultFn");b(this,"onUpdateFn");b(this,"hasDefault");b(this,"isUnique");b(this,"uniqueName");b(this,"uniqueType");b(this,"dataType");b(this,"columnType");b(this,"enumValues");b(this,"generated");b(this,"generatedIdentity");b(this,"config");this.table=t,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}mapFromDriverValue(t){return t}mapToDriverValue(t){return t}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}b(Kt,ho,"Column");var mo;mo=D;class ta{constructor(t,n,i){b(this,"config");b(this,"$default",this.$defaultFn);b(this,"$onUpdate",this.$onUpdateFn);this.config={name:t,keyAsName:t==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:i,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(t){return this.config.default=t,this.config.hasDefault=!0,this}$defaultFn(t){return this.config.defaultFn=t,this.config.hasDefault=!0,this}$onUpdateFn(t){return this.config.onUpdateFn=t,this.config.hasDefault=!0,this}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(t){this.config.name===""&&(this.config.name=t)}}b(ta,mo,"ColumnBuilder");const It=Symbol.for("drizzle:Name"),Ri=Symbol.for("drizzle:isPgEnum");function dc(e){return!!e&&typeof e=="function"&&Ri in e&&e[Ri]===!0}var yo;yo=D;class ui{constructor(t,n,i,o=!1,a=[]){this._={brand:"Subquery",sql:t,selectedFields:n,alias:i,isWith:o,usedTables:a}}}b(ui,yo,"Subquery");const _c={startActiveSpan(e,t){return t()}},Pt=Symbol.for("drizzle:ViewBaseConfig"),bn=Symbol.for("drizzle:Schema"),Li=Symbol.for("drizzle:Columns"),Pi=Symbol.for("drizzle:ExtraConfigColumns"),Sn=Symbol.for("drizzle:OriginalName"),Nn=Symbol.for("drizzle:BaseName"),ln=Symbol.for("drizzle:IsAlias"),Ui=Symbol.for("drizzle:ExtraConfigBuilder"),pc=Symbol.for("drizzle:IsDrizzleTable");var wo,vo,bo,So,No,Eo,Oo,Io,ko,Ao;Ao=D,ko=It,Io=Sn,Oo=bn,Eo=Li,No=Pi,So=Nn,bo=ln,vo=pc,wo=Ui;class ge{constructor(t,n,i){b(this,ko);b(this,Io);b(this,Oo);b(this,Eo);b(this,No);b(this,So);b(this,bo,!1);b(this,vo,!0);b(this,wo);this[It]=this[Sn]=t,this[bn]=n,this[Nn]=i}}b(ge,Ao,"Table"),b(ge,"Symbol",{Name:It,Schema:bn,OriginalName:Sn,Columns:Li,ExtraConfigColumns:Pi,BaseName:Nn,IsAlias:ln,ExtraConfigBuilder:Ui});function na(e){return e!=null&&typeof e.getSQL=="function"}function fc(e){var n;const t={sql:"",params:[]};for(const i of e)t.sql+=i.sql,t.params.push(...i.params),(n=i.typings)!=null&&n.length&&(t.typings||(t.typings=[]),t.typings.push(...i.typings));return t}var To;To=D;class Ee{constructor(t){b(this,"value");this.value=Array.isArray(t)?t:[t]}getSQL(){return new de([this])}}b(Ee,To,"StringChunk");var Co;Co=D;const _t=class _t{constructor(t){b(this,"decoder",ia);b(this,"shouldInlineParams",!1);b(this,"usedTables",[]);this.queryChunks=t;for(const n of t)if(Ne(n,ge)){const i=n[ge.Symbol.Schema];this.usedTables.push(i===void 0?n[ge.Symbol.Name]:i+"."+n[ge.Symbol.Name])}}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return _c.startActiveSpan("drizzle.buildSQL",n=>{const i=this.buildQueryFromSourceParams(this.queryChunks,t);return n==null||n.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(t,n){const i=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:o,escapeName:a,escapeParam:s,prepareTyping:c,inlineParams:u,paramStartIndex:p}=i;return fc(t.map(d=>{var h;if(Ne(d,Ee))return{sql:d.value.join(""),params:[]};if(Ne(d,cn))return{sql:a(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const m=[new Ee("(")];for(const[y,S]of d.entries())m.push(S),y<d.length-1&&m.push(new Ee(", "));return m.push(new Ee(")")),this.buildQueryFromSourceParams(m,i)}if(Ne(d,_t))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(Ne(d,ge)){const m=d[ge.Symbol.Schema],y=d[ge.Symbol.Name];return{sql:m===void 0||d[ln]?a(y):a(m)+"."+a(y),params:[]}}if(Ne(d,Kt)){const m=o.getColumnCasing(d);if(n.invokeSource==="indexes")return{sql:a(m),params:[]};const y=d.table[ge.Symbol.Schema];return{sql:d.table[ln]||y===void 0?a(d.table[ge.Symbol.Name])+"."+a(m):a(y)+"."+a(d.table[ge.Symbol.Name])+"."+a(m),params:[]}}if(Ne(d,di)){const m=d[Pt].schema,y=d[Pt].name;return{sql:m===void 0||d[Pt].isAlias?a(y):a(m)+"."+a(y),params:[]}}if(Ne(d,Ut)){if(Ne(d.value,Ft))return{sql:s(p.value++,d),params:[d],typings:["none"]};const m=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(Ne(m,_t))return this.buildQueryFromSourceParams([m],i);if(u)return{sql:this.mapInlineParam(m,i),params:[]};let y=["none"];return c&&(y=[c(d.encoder)]),{sql:s(p.value++,m),params:[m],typings:y}}return Ne(d,Ft)?{sql:s(p.value++,d),params:[d],typings:["none"]}:Ne(d,_t.Aliased)&&d.fieldAlias!==void 0?{sql:a(d.fieldAlias),params:[]}:Ne(d,ui)?d._.isWith?{sql:a(d._.alias),params:[]}:this.buildQueryFromSourceParams([new Ee("("),d._.sql,new Ee(") "),new cn(d._.alias)],i):dc(d)?d.schema?{sql:a(d.schema)+"."+a(d.enumName),params:[]}:{sql:a(d.enumName),params:[]}:na(d)?(h=d.shouldOmitSQLParens)!=null&&h.call(d)?this.buildQueryFromSourceParams([d.getSQL()],i):this.buildQueryFromSourceParams([new Ee("("),d.getSQL(),new Ee(")")],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:s(p.value++,d),params:[d],typings:["none"]}}))}mapInlineParam(t,{escapeString:n}){if(t===null)return"null";if(typeof t=="number"||typeof t=="boolean")return t.toString();if(typeof t=="string")return n(t);if(typeof t=="object"){const i=t.toString();return n(i==="[object Object]"?JSON.stringify(t):i)}throw new Error("Unexpected param value: "+t)}getSQL(){return this}as(t){return t===void 0?this:new _t.Aliased(this,t)}mapWith(t){return this.decoder=typeof t=="function"?{mapFromDriverValue:t}:t,this}inlineParams(){return this.shouldInlineParams=!0,this}if(t){return t?this:void 0}};b(_t,Co,"SQL");let de=_t;var zo;zo=D;class cn{constructor(t){b(this,"brand");this.value=t}getSQL(){return new de([this])}}b(cn,zo,"Name");function gc(e){return typeof e=="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue=="function"}const ia={mapFromDriverValue:e=>e},oa={mapToDriverValue:e=>e};({...ia,...oa});var Do;Do=D;class Ut{constructor(t,n=oa){b(this,"brand");this.value=t,this.encoder=n}getSQL(){return new de([this])}}b(Ut,Do,"Param");function k(e,...t){const n=[];(t.length>0||e.length>0&&e[0]!=="")&&n.push(new Ee(e[0]));for(const[i,o]of t.entries())n.push(o,new Ee(e[i+1]));return new de(n)}(e=>{function t(){return new de([])}e.empty=t;function n(u){return new de(u)}e.fromList=n;function i(u){return new de([new Ee(u)])}e.raw=i;function o(u,p){const d=[];for(const[h,m]of u.entries())h>0&&p!==void 0&&d.push(p),d.push(m);return new de(d)}e.join=o;function a(u){return new cn(u)}e.identifier=a;function s(u){return new Ft(u)}e.placeholder=s;function c(u,p){return new Ut(u,p)}e.param=c})(k||(k={}));(e=>{var n;n=D;const i=class i{constructor(a,s){b(this,"isSelectionField",!1);this.sql=a,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};b(i,n,"SQL.Aliased");let t=i;e.Aliased=t})(de||(de={}));var xo;xo=D;class Ft{constructor(t){this.name=t}getSQL(){return new de([this])}}b(Ft,xo,"Placeholder");const hc=Symbol.for("drizzle:IsDrizzleView");var $o,Ro,Lo;Lo=D,Ro=Pt,$o=hc;class di{constructor({name:t,schema:n,selectedFields:i,query:o}){b(this,Ro);b(this,$o,!0);this[Pt]={name:t,originalName:t,schema:n,selectedFields:i,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new de([this])}}b(di,Lo,"View");Kt.prototype.getSQL=function(){return new de([this])};ge.prototype.getSQL=function(){return new de([this])};ui.prototype.getSQL=function(){return new de([this])};function Gt(e,t){return{name:typeof e=="string"&&e.length>0?e:"",config:typeof e=="object"?e:t}}const ra=typeof TextDecoder>"u"?null:new TextDecoder;function st(e,t){return gc(t)&&!na(e)&&!Ne(e,Ut)&&!Ne(e,Ft)&&!Ne(e,Kt)&&!Ne(e,ge)&&!Ne(e,di)?new Ut(e,t):e}const _=(e,t)=>k`${e} = ${st(t,e)}`,mc=(e,t)=>k`${e} <> ${st(t,e)}`;function w(...e){const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?new de(t):new de([new Ee("("),k.join(t,new Ee(" and ")),new Ee(")")])}function Be(...e){const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?new de(t):new de([new Ee("("),k.join(t,new Ee(" or ")),new Ee(")")])}const un=(e,t)=>k`${e} > ${st(t,e)}`,Tt=(e,t)=>k`${e} >= ${st(t,e)}`,Qe=(e,t)=>k`${e} < ${st(t,e)}`,pt=(e,t)=>k`${e} <= ${st(t,e)}`;function Re(e,t){return Array.isArray(t)?t.length===0?k`false`:k`${e} in ${t.map(n=>st(n,e))}`:k`${e} in ${st(t,e)}`}function xe(e){return k`${e} is null`}function rn(e){return k`${e} is not null`}function St(e,t){return k`${e} like ${t}`}function me(e){return k`${e} asc`}function le(e){return k`${e} desc`}function ye(e){return k`count(${k.raw("*")})`.mapWith(Number)}function yc(){const e=t=>{throw new Error(`Actions are not implemented in the Drizzle adapter (called ${t}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>e("create"),get:()=>e("get"),list:()=>e("list"),update:()=>e("update"),remove:()=>e("remove")}}function wc(){const e=t=>{throw new Error(`Action executions are not implemented in the Drizzle adapter (called ${t}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>e("create"),get:()=>e("get")}}function vc(){const e=t=>{throw new Error(`Action versions are not implemented in the Drizzle adapter (called ${t}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>e("create"),get:()=>e("get"),list:()=>e("list"),removeForAction:()=>e("removeForAction")}}var Po;Po=D;class aa{constructor(t,n){b(this,"reference");b(this,"_onUpdate");b(this,"_onDelete");this.reference=()=>{const{name:i,columns:o,foreignColumns:a}=t();return{name:i,columns:o,foreignTable:a[0].table,foreignColumns:a}},n&&(this._onUpdate=n.onUpdate,this._onDelete=n.onDelete)}onUpdate(t){return this._onUpdate=t,this}onDelete(t){return this._onDelete=t,this}build(t){return new sa(t,this)}}b(aa,Po,"SQLiteForeignKeyBuilder");var Uo;Uo=D;class sa{constructor(t,n){b(this,"reference");b(this,"onUpdate");b(this,"onDelete");this.table=t,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}getName(){const{name:t,columns:n,foreignColumns:i}=this.reference(),o=n.map(c=>c.name),a=i.map(c=>c.name),s=[this.table[It],...o,i[0].table[It],...a];return t??`${s.join("_")}_fk`}}b(sa,Uo,"SQLiteForeignKey");function bc(e,t){return`${e[It]}_${t.join("_")}_unique`}var Fo,Zo;class Je extends(Zo=ta,Fo=D,Zo){constructor(){super(...arguments);b(this,"foreignKeyConfigs",[])}references(n,i={}){return this.foreignKeyConfigs.push({ref:n,actions:i}),this}unique(n){return this.config.isUnique=!0,this.config.uniqueName=n,this}generatedAlwaysAs(n,i){return this.config.generated={as:n,type:"always",mode:(i==null?void 0:i.mode)??"virtual"},this}buildForeignKeys(n,i){return this.foreignKeyConfigs.map(({ref:o,actions:a})=>((s,c)=>{const u=new aa(()=>{const p=s();return{columns:[n],foreignColumns:[p]}});return c.onUpdate&&u.onUpdate(c.onUpdate),c.onDelete&&u.onDelete(c.onDelete),u.build(i)})(o,a))}}b(Je,Fo,"SQLiteColumnBuilder");var Mo,jo;class Ke extends(jo=Kt,Mo=D,jo){constructor(t,n){n.uniqueName||(n.uniqueName=bc(t,[n.name])),super(t,n),this.table=t}}b(Ke,Mo,"SQLiteColumn");var qo,Bo;class la extends(Bo=Je,qo=D,Bo){constructor(t){super(t,"bigint","SQLiteBigInt")}build(t){return new ca(t,this.config)}}b(la,qo,"SQLiteBigIntBuilder");var Jo,Ko;class ca extends(Ko=Ke,Jo=D,Ko){getSQLType(){return"blob"}mapFromDriverValue(t){if(typeof Buffer<"u"&&Buffer.from){const n=Buffer.isBuffer(t)?t:t instanceof ArrayBuffer?Buffer.from(t):t.buffer?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t);return BigInt(n.toString("utf8"))}return BigInt(ra.decode(t))}mapToDriverValue(t){return Buffer.from(t.toString())}}b(ca,Jo,"SQLiteBigInt");var Go,Vo;class ua extends(Vo=Je,Go=D,Vo){constructor(t){super(t,"json","SQLiteBlobJson")}build(t){return new da(t,this.config)}}b(ua,Go,"SQLiteBlobJsonBuilder");var Ho,Wo;class da extends(Wo=Ke,Ho=D,Wo){getSQLType(){return"blob"}mapFromDriverValue(t){if(typeof Buffer<"u"&&Buffer.from){const n=Buffer.isBuffer(t)?t:t instanceof ArrayBuffer?Buffer.from(t):t.buffer?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t);return JSON.parse(n.toString("utf8"))}return JSON.parse(ra.decode(t))}mapToDriverValue(t){return Buffer.from(JSON.stringify(t))}}b(da,Ho,"SQLiteBlobJson");var Qo,Xo;class _a extends(Xo=Je,Qo=D,Xo){constructor(t){super(t,"buffer","SQLiteBlobBuffer")}build(t){return new pa(t,this.config)}}b(_a,Qo,"SQLiteBlobBufferBuilder");var Yo,er;class pa extends(er=Ke,Yo=D,er){mapFromDriverValue(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}getSQLType(){return"blob"}}b(pa,Yo,"SQLiteBlobBuffer");function Sc(e,t){const{name:n,config:i}=Gt(e,t);return(i==null?void 0:i.mode)==="json"?new ua(n):(i==null?void 0:i.mode)==="bigint"?new la(n):new _a(n)}var tr,nr;class fa extends(nr=Je,tr=D,nr){constructor(t,n,i){super(t,"custom","SQLiteCustomColumn"),this.config.fieldConfig=n,this.config.customTypeParams=i}build(t){return new ga(t,this.config)}}b(fa,tr,"SQLiteCustomColumnBuilder");var ir,or;class ga extends(or=Ke,ir=D,or){constructor(n,i){super(n,i);b(this,"sqlName");b(this,"mapTo");b(this,"mapFrom");this.sqlName=i.customTypeParams.dataType(i.fieldConfig),this.mapTo=i.customTypeParams.toDriver,this.mapFrom=i.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(n){return typeof this.mapFrom=="function"?this.mapFrom(n):n}mapToDriverValue(n){return typeof this.mapTo=="function"?this.mapTo(n):n}}b(ga,ir,"SQLiteCustomColumn");function Nc(e){return(t,n)=>{const{name:i,config:o}=Gt(t,n);return new fa(i,o,e)}}var rr,ar;class fn extends(ar=Je,rr=D,ar){constructor(t,n,i){super(t,n,i),this.config.autoIncrement=!1}primaryKey(t){return t!=null&&t.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}}b(fn,rr,"SQLiteBaseIntegerBuilder");var sr,lr;class gn extends(lr=Ke,sr=D,lr){constructor(){super(...arguments);b(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}b(gn,sr,"SQLiteBaseInteger");var cr,ur;class ha extends(ur=fn,cr=D,ur){constructor(t){super(t,"number","SQLiteInteger")}build(t){return new ma(t,this.config)}}b(ha,cr,"SQLiteIntegerBuilder");var dr,_r;class ma extends(_r=gn,dr=D,_r){}b(ma,dr,"SQLiteInteger");var pr,fr;class ya extends(fr=fn,pr=D,fr){constructor(t,n){super(t,"date","SQLiteTimestamp"),this.config.mode=n}defaultNow(){return this.default(k`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(t){return new wa(t,this.config)}}b(ya,pr,"SQLiteTimestampBuilder");var gr,hr;class wa extends(hr=gn,gr=D,hr){constructor(){super(...arguments);b(this,"mode",this.config.mode)}mapFromDriverValue(n){return this.config.mode==="timestamp"?new Date(n*1e3):new Date(n)}mapToDriverValue(n){const i=n.getTime();return this.config.mode==="timestamp"?Math.floor(i/1e3):i}}b(wa,gr,"SQLiteTimestamp");var mr,yr;class va extends(yr=fn,mr=D,yr){constructor(t,n){super(t,"boolean","SQLiteBoolean"),this.config.mode=n}build(t){return new ba(t,this.config)}}b(va,mr,"SQLiteBooleanBuilder");var wr,vr;class ba extends(vr=gn,wr=D,vr){constructor(){super(...arguments);b(this,"mode",this.config.mode)}mapFromDriverValue(n){return Number(n)===1}mapToDriverValue(n){return n?1:0}}b(ba,wr,"SQLiteBoolean");function N(e,t){const{name:n,config:i}=Gt(e,t);return(i==null?void 0:i.mode)==="timestamp"||(i==null?void 0:i.mode)==="timestamp_ms"?new ya(n,i.mode):(i==null?void 0:i.mode)==="boolean"?new va(n,i.mode):new ha(n)}var br,Sr;class Sa extends(Sr=Je,br=D,Sr){constructor(t){super(t,"string","SQLiteNumeric")}build(t){return new Na(t,this.config)}}b(Sa,br,"SQLiteNumericBuilder");var Nr,Er;class Na extends(Er=Ke,Nr=D,Er){mapFromDriverValue(t){return typeof t=="string"?t:String(t)}getSQLType(){return"numeric"}}b(Na,Nr,"SQLiteNumeric");var Or,Ir;class Ea extends(Ir=Je,Or=D,Ir){constructor(t){super(t,"number","SQLiteNumericNumber")}build(t){return new Oa(t,this.config)}}b(Ea,Or,"SQLiteNumericNumberBuilder");var kr,Ar;class Oa extends(Ar=Ke,kr=D,Ar){constructor(){super(...arguments);b(this,"mapToDriverValue",String)}mapFromDriverValue(n){return typeof n=="number"?n:Number(n)}getSQLType(){return"numeric"}}b(Oa,kr,"SQLiteNumericNumber");var Tr,Cr;class Ia extends(Cr=Je,Tr=D,Cr){constructor(t){super(t,"bigint","SQLiteNumericBigInt")}build(t){return new ka(t,this.config)}}b(Ia,Tr,"SQLiteNumericBigIntBuilder");var zr,Dr;class ka extends(Dr=Ke,zr=D,Dr){constructor(){super(...arguments);b(this,"mapFromDriverValue",BigInt);b(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}b(ka,zr,"SQLiteNumericBigInt");function Ec(e,t){const{name:n,config:i}=Gt(e,t),o=i==null?void 0:i.mode;return o==="number"?new Ea(n):o==="bigint"?new Ia(n):new Sa(n)}var xr,$r;class Aa extends($r=Je,xr=D,$r){constructor(t){super(t,"number","SQLiteReal")}build(t){return new Ta(t,this.config)}}b(Aa,xr,"SQLiteRealBuilder");var Rr,Lr;class Ta extends(Lr=Ke,Rr=D,Lr){getSQLType(){return"real"}}b(Ta,Rr,"SQLiteReal");function Oc(e){return new Aa(e??"")}var Pr,Ur;class Ca extends(Ur=Je,Pr=D,Ur){constructor(t,n){super(t,"string","SQLiteText"),this.config.enumValues=n.enum,this.config.length=n.length}build(t){return new za(t,this.config)}}b(Ca,Pr,"SQLiteTextBuilder");var Fr,Zr;class za extends(Zr=Ke,Fr=D,Zr){constructor(n,i){super(n,i);b(this,"enumValues",this.config.enumValues);b(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}b(za,Fr,"SQLiteText");var Mr,jr;class Da extends(jr=Je,Mr=D,jr){constructor(t){super(t,"json","SQLiteTextJson")}build(t){return new xa(t,this.config)}}b(Da,Mr,"SQLiteTextJsonBuilder");var qr,Br;class xa extends(Br=Ke,qr=D,Br){getSQLType(){return"text"}mapFromDriverValue(t){return JSON.parse(t)}mapToDriverValue(t){return JSON.stringify(t)}}b(xa,qr,"SQLiteTextJson");function l(e,t={}){const{name:n,config:i}=Gt(e,t);return i.mode==="json"?new Da(n):new Ca(n,i)}function Ic(){return{blob:Sc,customType:Nc,integer:N,numeric:Ec,real:Oc,text:l}}const qn=Symbol.for("drizzle:SQLiteInlineForeignKeys");var Jr,Kr,Gr,Vr,Hr;class Zt extends(Hr=ge,Vr=D,Gr=ge.Symbol.Columns,Kr=qn,Jr=ge.Symbol.ExtraConfigBuilder,Hr){constructor(){super(...arguments);b(this,Gr);b(this,Kr,[]);b(this,Jr)}}b(Zt,Vr,"SQLiteTable"),b(Zt,"Symbol",Object.assign({},ge.Symbol,{InlineForeignKeys:qn}));function kc(e,t,n,i,o=e){const a=new Zt(e,i,o),s=typeof t=="function"?t(Ic()):t,c=Object.fromEntries(Object.entries(s).map(([p,d])=>{const h=d;h.setName(p);const m=h.build(a);return a[qn].push(...h.buildForeignKeys(m,a)),[p,m]})),u=Object.assign(a,c);return u[ge.Symbol.Columns]=c,u[ge.Symbol.ExtraConfigColumns]=c,n&&(u[Zt.Symbol.ExtraConfigBuilder]=n),u}const Z=(e,t,n)=>kc(e,t,n);var Wr;Wr=D;class _i{constructor(t,n){this.name=t,this.unique=n}on(...t){return new $a(this.name,t,this.unique)}}b(_i,Wr,"SQLiteIndexBuilderOn");var Qr;Qr=D;class $a{constructor(t,n,i){b(this,"config");this.config={name:t,columns:n,unique:i,where:void 0}}where(t){return this.config.where=t,this}build(t){return new Ra(this.config,t)}}b($a,Qr,"SQLiteIndexBuilder");var Xr;Xr=D;class Ra{constructor(t,n){b(this,"config");this.config={...t,table:n}}}b(Ra,Xr,"SQLiteIndex");function z(e){return new _i(e,!1)}function gt(e){return new _i(e,!0)}function Ce(...e){return e[0].columns?new Bn(e[0].columns,e[0].name):new Bn(e)}var Yr;Yr=D;class Bn{constructor(t,n){b(this,"columns");b(this,"name");this.columns=t,this.name=n}build(t){return new La(t,this.columns,this.name)}}b(Bn,Yr,"SQLitePrimaryKeyBuilder");var ea;ea=D;class La{constructor(t,n,i){b(this,"columns");b(this,"name");this.table=t,this.columns=n,this.name=i}getName(){return this.name??`${this.table[Zt.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}}b(La,ea,"SQLitePrimaryKey");const F=Z("tenants",{id:l("id",{length:191}).primaryKey(),name:l("name",{length:255}),audience:l("audience",{length:255}),sender_email:l("sender_email",{length:255}),sender_name:l("sender_name",{length:255}),language:l("language",{length:255}),logo:l("logo",{length:255}),primary_color:l("primary_color",{length:255}),secondary_color:l("secondary_color",{length:255}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull(),support_url:l("support_url",{length:255}),idle_session_lifetime:N("idle_session_lifetime"),session_lifetime:N("session_lifetime"),session_cookie:l("session_cookie"),allowed_logout_urls:l("allowed_logout_urls"),ephemeral_session_lifetime:N("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:N("idle_ephemeral_session_lifetime"),default_redirection_uri:l("default_redirection_uri"),default_client_id:l("default_client_id",{length:255}),enabled_locales:l("enabled_locales"),default_directory:l("default_directory",{length:255}),error_page:l("error_page"),flags:l("flags"),friendly_name:l("friendly_name",{length:255}),picture_url:l("picture_url"),support_email:l("support_email",{length:255}),sandbox_version:l("sandbox_version",{length:50}),sandbox_versions_available:l("sandbox_versions_available"),legacy_sandbox_version:l("legacy_sandbox_version",{length:50}),change_password:l("change_password"),guardian_mfa_page:l("guardian_mfa_page"),device_flow:l("device_flow"),default_token_quota:l("default_token_quota"),default_audience:l("default_audience",{length:255}),default_organization:l("default_organization",{length:255}),sessions:l("sessions"),oidc_logout:l("oidc_logout"),allow_organization_name_in_authentication_api:N("allow_organization_name_in_authentication_api"),customize_mfa_in_postlogin_action:N("customize_mfa_in_postlogin_action"),acr_values_supported:l("acr_values_supported"),mtls:l("mtls"),pushed_authorization_requests_supported:N("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:N("authorization_response_iss_parameter_supported")}),q=Z("users",{user_id:l("user_id",{length:255}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),email:l("email",{length:255}),given_name:l("given_name",{length:255}),family_name:l("family_name",{length:255}),nickname:l("nickname",{length:255}),name:l("name",{length:255}),picture:l("picture",{length:2083}),tags:l("tags",{length:255}),phone_number:l("phone_number",{length:17}),phone_verified:N("phone_verified",{mode:"boolean"}),username:l("username",{length:128}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull(),linked_to:l("linked_to",{length:255}),last_ip:l("last_ip",{length:255}),login_count:N("login_count").notNull(),last_login:l("last_login",{length:255}),registration_completed_at:l("registration_completed_at",{length:35}),provider:l("provider",{length:255}).notNull(),connection:l("connection",{length:255}),email_verified:N("email_verified",{mode:"boolean"}).notNull(),is_social:N("is_social",{mode:"boolean"}).notNull(),app_metadata:l("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:l("user_metadata").notNull().default("{}"),profileData:l("profileData",{length:2048}),locale:l("locale",{length:255}),middle_name:l("middle_name",{length:100}),preferred_username:l("preferred_username",{length:255}),profile:l("profile"),website:l("website"),gender:l("gender",{length:50}),birthdate:l("birthdate",{length:10}),zoneinfo:l("zoneinfo",{length:100}),address:l("address")},e=>[Ce({columns:[e.user_id,e.tenant_id],name:"users_tenants"}),gt("unique_email_provider").on(e.email,e.provider,e.tenant_id),gt("unique_phone_provider").on(e.phone_number,e.provider,e.tenant_id),gt("unique_username_provider").on(e.username,e.provider,e.tenant_id),z("users_email_index").on(e.email),z("users_linked_to_index").on(e.linked_to),z("users_name_index").on(e.name),z("users_phone_tenant_provider_index").on(e.tenant_id,e.phone_number,e.provider)]),oe=Z("passwords",{id:l("id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),user_id:l("user_id",{length:255}).notNull(),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull(),password:l("password",{length:255}).notNull(),algorithm:l("algorithm",{length:16}).notNull().default("bcrypt"),is_current:N("is_current").notNull().default(1)}),se=Z("sessions",{id:l("id",{length:21}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),user_id:l("user_id",{length:255}),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull(),expires_at_ts:N("expires_at_ts"),idle_expires_at_ts:N("idle_expires_at_ts"),authenticated_at_ts:N("authenticated_at_ts"),last_interaction_at_ts:N("last_interaction_at_ts"),used_at_ts:N("used_at_ts"),revoked_at_ts:N("revoked_at_ts"),device:l("device").notNull(),clients:l("clients").notNull(),login_session_id:l("login_session_id",{length:21})},e=>[Ce({columns:[e.tenant_id,e.id],name:"sessions_pk"}),z("IDX_sessions_login_session_id").on(e.login_session_id),z("idx_sessions_user_id").on(e.tenant_id,e.user_id),z("idx_sessions_expires_at_ts").on(e.expires_at_ts)]),J=Z("refresh_tokens",{id:l("id",{length:26}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),client_id:l("client_id",{length:191}).notNull(),login_id:l("login_id",{length:26}).notNull(),user_id:l("user_id",{length:255}),resource_servers:l("resource_servers").notNull(),device:l("device").notNull(),rotating:N("rotating",{mode:"boolean"}).notNull(),token_lookup:l("token_lookup",{length:16}),token_hash:l("token_hash",{length:64}),family_id:l("family_id",{length:26}),rotated_to:l("rotated_to",{length:26}),rotated_at_ts:N("rotated_at_ts"),created_at_ts:N("created_at_ts").notNull(),expires_at_ts:N("expires_at_ts"),idle_expires_at_ts:N("idle_expires_at_ts"),last_exchanged_at_ts:N("last_exchanged_at_ts"),revoked_at_ts:N("revoked_at_ts")},e=>[Ce({columns:[e.tenant_id,e.id],name:"refresh_tokens_pk"}),z("idx_refresh_tokens_user_id").on(e.tenant_id,e.user_id),z("idx_refresh_tokens_login_id").on(e.login_id),z("idx_refresh_tokens_expires_at_ts").on(e.expires_at_ts),z("idx_refresh_tokens_token_lookup").on(e.tenant_id,e.token_lookup),z("idx_refresh_tokens_family_id").on(e.tenant_id,e.family_id)]),Q=Z("login_sessions",{id:l("id",{length:21}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),session_id:l("session_id",{length:21}),csrf_token:l("csrf_token",{length:21}).notNull(),auth_params:l("auth_params"),authorization_url:l("authorization_url"),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull(),expires_at_ts:N("expires_at_ts").notNull(),ip:l("ip",{length:39}),useragent:l("useragent"),auth0Client:l("auth0Client",{length:255}),state:l("state",{length:50}).notNull().default("pending"),state_data:l("state_data"),failure_reason:l("failure_reason"),user_id:l("user_id",{length:255}),auth_connection:l("auth_connection",{length:255}),auth_strategy_strategy:l("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:l("auth_strategy_strategy_type",{length:64}),authenticated_at:l("authenticated_at",{length:35})},e=>[Ce({columns:[e.tenant_id,e.id],name:"login_sessions_pk"}),z("login_sessions_id_index").on(e.id),z("login_sessions_state_idx").on(e.state),z("login_sessions_state_updated_idx").on(e.state,e.updated_at_ts),z("login_sessions_tenant_user_idx").on(e.tenant_id,e.user_id),z("idx_login_sessions_expires_at_ts").on(e.expires_at_ts)]),ce=Z("codes",{code_id:l("code_id",{length:191}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),user_id:l("user_id",{length:255}),login_id:l("login_id",{length:255}),connection_id:l("connection_id",{length:255}),code_type:l("code_type",{length:255}).notNull(),created_at:l("created_at",{length:35}).notNull(),expires_at:l("expires_at",{length:35}).notNull(),used_at:l("used_at",{length:35}),code_verifier:l("code_verifier",{length:128}),code_challenge:l("code_challenge",{length:128}),code_challenge_method:l("code_challenge_method",{length:5}),redirect_uri:l("redirect_uri",{length:1024}),nonce:l("nonce",{length:1024}),state:l("state",{length:2048})},e=>[Ce({columns:[e.code_id,e.code_type],name:"PK_codes_code_id_code_type"}),z("codes_expires_at_index").on(e.expires_at)]),Ac=Z("authentication_codes",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),code:l("code",{length:255}).primaryKey(),client_id:l("client_id",{length:255}).notNull(),user_id:l("user_id",{length:255}).notNull(),nonce:l("nonce",{length:255}),state:l("state",{length:8192}),scope:l("scope",{length:1024}),response_type:l("response_type",{length:256}),response_mode:l("response_mode",{length:256}),redirect_uri:l("redirect_uri",{length:1024}),created_at:l("created_at",{length:35}).notNull(),expires_at:l("expires_at",{length:35}).notNull(),used_at:l("used_at",{length:35})}),Tc=Z("otps",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),id:l("id",{length:255}).primaryKey(),client_id:l("client_id",{length:255}).notNull(),code:l("code",{length:255}).notNull(),email:l("email",{length:255}).notNull(),user_id:l("user_id",{length:255}),send:l("send",{length:255}),nonce:l("nonce",{length:255}),state:l("state",{length:1024}),scope:l("scope",{length:1024}),response_type:l("response_type",{length:256}),response_mode:l("response_mode",{length:256}),redirect_uri:l("redirect_uri",{length:1024}),created_at:l("created_at",{length:35}).notNull(),expires_at:l("expires_at",{length:35}).notNull(),used_at:l("used_at",{length:35}),audience:l("audience",{length:255}),ip:l("ip",{length:64})},e=>[z("otps_email_index").on(e.email),z("otps_expires_at_index").on(e.expires_at)]),Cc=Z("tickets",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),id:l("id",{length:255}).primaryKey(),client_id:l("client_id",{length:255}).notNull(),email:l("email",{length:255}).notNull(),nonce:l("nonce",{length:255}),state:l("state",{length:1024}),scope:l("scope",{length:1024}),response_type:l("response_type",{length:256}),response_mode:l("response_mode",{length:256}),redirect_uri:l("redirect_uri",{length:1024}),created_at:l("created_at",{length:35}).notNull(),expires_at:l("expires_at",{length:35}).notNull(),used_at:l("used_at",{length:35})}),B=Z("clients",{client_id:l("client_id",{length:191}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),name:l("name",{length:255}).notNull(),description:l("description",{length:140}),global:N("global").notNull().default(0),client_secret:l("client_secret",{length:255}),app_type:l("app_type",{length:64}).default("regular_web"),logo_uri:l("logo_uri",{length:2083}),is_first_party:N("is_first_party").notNull().default(0),oidc_conformant:N("oidc_conformant").notNull().default(1),auth0_conformant:N("auth0_conformant").notNull().default(1),callbacks:l("callbacks").notNull(),allowed_origins:l("allowed_origins").notNull(),web_origins:l("web_origins").notNull(),client_aliases:l("client_aliases").notNull(),allowed_clients:l("allowed_clients").notNull(),allowed_logout_urls:l("allowed_logout_urls").notNull(),session_transfer:l("session_transfer").notNull(),oidc_logout:l("oidc_logout").notNull(),grant_types:l("grant_types").notNull(),jwt_configuration:l("jwt_configuration").notNull(),signing_keys:l("signing_keys").notNull(),encryption_key:l("encryption_key").notNull(),sso:N("sso").notNull().default(0),sso_disabled:N("sso_disabled").notNull().default(1),cross_origin_authentication:N("cross_origin_authentication").notNull().default(0),cross_origin_loc:l("cross_origin_loc",{length:2083}),custom_login_page_on:N("custom_login_page_on").notNull().default(0),custom_login_page:l("custom_login_page"),custom_login_page_preview:l("custom_login_page_preview"),form_template:l("form_template"),addons:l("addons").notNull(),token_endpoint_auth_method:l("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:l("client_metadata").notNull(),mobile:l("mobile").notNull(),initiate_login_uri:l("initiate_login_uri",{length:2083}),native_social_login:l("native_social_login").notNull(),refresh_token:l("refresh_token").notNull(),default_organization:l("default_organization").notNull(),organization_usage:l("organization_usage",{length:32}).default("deny"),organization_require_behavior:l("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:l("client_authentication_methods").notNull(),require_pushed_authorization_requests:N("require_pushed_authorization_requests").notNull().default(0),require_proof_of_possession:N("require_proof_of_possession").notNull().default(0),hide_sign_up_disabled_error:N("hide_sign_up_disabled_error").notNull().default(0),signed_request_object:l("signed_request_object").notNull(),compliance_level:l("compliance_level",{length:64}),par_request_expiry:N("par_request_expiry"),token_quota:l("token_quota").notNull(),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull(),connections:l("connections").notNull().default("[]"),owner_user_id:l("owner_user_id",{length:255}),registration_type:l("registration_type",{length:32}),registration_metadata:l("registration_metadata"),user_linking_mode:l("user_linking_mode",{length:16})},e=>[Ce({columns:[e.tenant_id,e.client_id],name:"clients_tenant_id_client_id"}),z("idx_clients_owner_user_id").on(e.tenant_id,e.owner_user_id)]),W=Z("client_registration_tokens",{id:l("id",{length:255}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),token_hash:l("token_hash",{length:64}).notNull(),type:l("type",{length:8}).notNull(),client_id:l("client_id",{length:191}),sub:l("sub",{length:255}),constraints:l("constraints"),single_use:N("single_use").notNull().default(0),used_at_ts:N("used_at_ts"),expires_at_ts:N("expires_at_ts"),created_at_ts:N("created_at_ts").notNull(),revoked_at_ts:N("revoked_at_ts")},e=>[gt("idx_client_registration_tokens_hash").on(e.tenant_id,e.token_hash),z("idx_client_registration_tokens_client").on(e.tenant_id,e.client_id)]),Se=Z("client_grants",{id:l("id",{length:21}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),client_id:l("client_id",{length:191}).notNull(),audience:l("audience",{length:191}).notNull(),scope:l("scope").default("[]"),organization_usage:l("organization_usage",{length:32}),allow_any_organization:N("allow_any_organization").default(0),is_system:N("is_system").default(0),subject_type:l("subject_type",{length:32}),authorization_details_types:l("authorization_details_types").default("[]"),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.id],name:"pk_client_grants"}),z("idx_client_grants_audience").on(e.audience)]),fe=Z("connections",{id:l("id",{length:255}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),name:l("name",{length:255}).notNull(),response_type:l("response_type",{length:255}),response_mode:l("response_mode",{length:255}),strategy:l("strategy",{length:64}),options:l("options",{length:8192}).notNull().default("{}"),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull(),display_name:l("display_name",{length:255}),is_domain_connection:N("is_domain_connection"),show_as_button:N("show_as_button"),is_system:N("is_system").notNull().default(0),metadata:l("metadata",{length:4096})},e=>[Ce({columns:[e.tenant_id,e.id]}),z("connections_tenant_id_index").on(e.tenant_id),gt("connections_id_unique").on(e.id)]),ze=Z("custom_domains",{custom_domain_id:l("custom_domain_id",{length:256}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),domain:l("domain",{length:255}).notNull(),primary:N("primary",{mode:"boolean"}).notNull(),status:l("status",{length:50}).notNull(),type:l("type",{length:50}).notNull(),origin_domain_name:l("origin_domain_name",{length:255}),verification:l("verification",{length:2048}),custom_client_ip_header:l("custom_client_ip_header",{length:50}),tls_policy:l("tls_policy",{length:50}),domain_metadata:l("domain_metadata",{length:2048}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[gt("custom_domains_domain_unique").on(e.domain)]),zc=Z("domains",{id:l("id",{length:255}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),domain:l("domain",{length:255}).notNull(),email_service:l("email_service",{length:255}),email_api_key:l("email_api_key",{length:255}),dkim_private_key:l("dkim_private_key",{length:2048}),dkim_public_key:l("dkim_public_key",{length:2048}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()}),Y=Z("organizations",{id:l("id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull(),name:l("name",{length:256}).notNull(),display_name:l("display_name",{length:256}),branding:l("branding"),metadata:l("metadata"),enabled_connections:l("enabled_connections"),token_quota:l("token_quota"),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[z("idx_organizations_tenant_id").on(e.tenant_id)]),ue=Z("user_organizations",{id:l("id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull(),user_id:l("user_id",{length:191}).notNull(),organization_id:l("organization_id",{length:21}).notNull(),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[gt("user_organizations_unique").on(e.tenant_id,e.user_id,e.organization_id),z("idx_user_organizations_tenant_id").on(e.tenant_id),z("idx_user_organizations_user_id").on(e.user_id),z("idx_user_organizations_organization_id").on(e.organization_id)]),ke=Z("invites",{id:l("id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull(),organization_id:l("organization_id",{length:21}).notNull(),inviter:l("inviter").notNull(),invitee:l("invitee").notNull(),client_id:l("client_id",{length:191}).notNull(),connection_id:l("connection_id",{length:21}),invitation_url:l("invitation_url").notNull(),created_at:l("created_at",{length:35}).notNull(),expires_at:l("expires_at",{length:35}).notNull(),app_metadata:l("app_metadata"),user_metadata:l("user_metadata"),roles:l("roles"),ticket_id:l("ticket_id",{length:191}),ttl_sec:N("ttl_sec"),send_invitation_email:N("send_invitation_email")},e=>[z("idx_invites_tenant_id").on(e.tenant_id),z("idx_invites_organization_id").on(e.organization_id),z("idx_invites_expires_at").on(e.expires_at),z("idx_invites_tenant_created").on(e.tenant_id,e.created_at)]),_e=Z("roles",{id:l("id",{length:21}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull(),name:l("name",{length:50}).notNull(),description:l("description",{length:255}),is_system:N("is_system").notNull().default(0),metadata:l("metadata",{length:4096}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.id],name:"roles_pk"})]),Fe=Z("role_permissions",{tenant_id:l("tenant_id",{length:191}).notNull(),role_id:l("role_id",{length:21}).notNull(),resource_server_identifier:l("resource_server_identifier",{length:191}).notNull(),permission_name:l("permission_name",{length:191}).notNull(),created_at:l("created_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.role_id,e.resource_server_identifier,e.permission_name],name:"role_permissions_pk"}),z("role_permissions_role_fk").on(e.tenant_id,e.role_id),z("role_permissions_permission_fk").on(e.tenant_id,e.resource_server_identifier,e.permission_name)]),je=Z("user_permissions",{tenant_id:l("tenant_id",{length:191}).notNull(),user_id:l("user_id",{length:191}).notNull(),resource_server_identifier:l("resource_server_identifier",{length:191}).notNull(),permission_name:l("permission_name",{length:191}).notNull(),organization_id:l("organization_id",{length:21}).notNull().default(""),created_at:l("created_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.user_id,e.resource_server_identifier,e.permission_name,e.organization_id],name:"user_permissions_pk"}),z("user_permissions_user_fk").on(e.tenant_id,e.user_id),z("user_permissions_permission_fk").on(e.tenant_id,e.resource_server_identifier,e.permission_name),z("user_permissions_organization_fk").on(e.organization_id)]),qe=Z("user_roles",{tenant_id:l("tenant_id",{length:191}).notNull(),user_id:l("user_id",{length:191}).notNull(),role_id:l("role_id",{length:21}).notNull(),organization_id:l("organization_id",{length:191}).notNull().default(""),created_at:l("created_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.user_id,e.role_id,e.organization_id],name:"user_roles_pk"}),z("user_roles_user_fk").on(e.tenant_id,e.user_id),z("user_roles_role_fk").on(e.tenant_id,e.role_id),z("user_roles_organization_fk").on(e.organization_id)]),ee=Z("resource_servers",{id:l("id",{length:21}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull(),identifier:l("identifier",{length:191}).notNull(),name:l("name",{length:255}).notNull(),scopes:l("scopes",{length:4096}),signing_alg:l("signing_alg",{length:64}),signing_secret:l("signing_secret",{length:2048}),token_lifetime:N("token_lifetime"),token_lifetime_for_web:N("token_lifetime_for_web"),skip_consent_for_verifiable_first_party_clients:N("skip_consent_for_verifiable_first_party_clients"),allow_offline_access:N("allow_offline_access"),verification_key:l("verification_key",{length:4096}),options:l("options",{length:4096}),is_system:N("is_system").notNull().default(0),metadata:l("metadata",{length:4096}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.id],name:"resource_servers_pk"})]),$t=Z("branding",{tenant_id:l("tenant_id",{length:191}).primaryKey().references(()=>F.id,{onDelete:"cascade"}),logo_url:l("logo_url",{length:512}),favicon_url:l("favicon_url",{length:512}),font_url:l("font_url",{length:512}),colors_primary:l("colors_primary",{length:8}),colors_page_background_type:l("colors_page_background_type",{length:32}),colors_page_background_start:l("colors_page_background_start",{length:8}),colors_page_background_end:l("colors_page_background_end",{length:8}),colors_page_background_angle_dev:N("colors_page_background_angle_dev"),dark_mode:l("dark_mode",{length:8})}),ot=Z("universal_login_templates",{tenant_id:l("tenant_id",{length:191}).primaryKey().references(()=>F.id,{onDelete:"cascade"}),body:l("body").notNull(),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull()}),Ve=Z("themes",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),themeId:l("themeId",{length:255}).notNull(),displayName:l("displayName",{length:255}).notNull(),colors_primary_button_label:l("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:l("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:l("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:l("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:l("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:l("colors_base_hover_color",{length:24}).notNull(),colors_body_text:l("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:l("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:l("colors_error",{length:24}).notNull(),colors_header:l("colors_header",{length:24}).notNull(),colors_icons:l("colors_icons",{length:24}).notNull(),colors_input_background:l("colors_input_background",{length:24}).notNull(),colors_input_border:l("colors_input_border",{length:24}).notNull(),colors_input_filled_text:l("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:l("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:l("colors_links_focused_components",{length:24}).notNull(),colors_success:l("colors_success",{length:24}).notNull(),colors_widget_background:l("colors_widget_background",{length:24}).notNull(),colors_widget_border:l("colors_widget_border",{length:24}).notNull(),borders_button_border_radius:N("borders_button_border_radius").notNull(),borders_button_border_weight:N("borders_button_border_weight").notNull(),borders_buttons_style:l("borders_buttons_style",{length:24}).notNull(),borders_input_border_radius:N("borders_input_border_radius").notNull(),borders_input_border_weight:N("borders_input_border_weight").notNull(),borders_inputs_style:l("borders_inputs_style",{length:24}).notNull(),borders_show_widget_shadow:N("borders_show_widget_shadow",{mode:"boolean"}).notNull(),borders_widget_border_weight:N("borders_widget_border_weight").notNull(),borders_widget_corner_radius:N("borders_widget_corner_radius").notNull(),fonts_body_text_bold:N("fonts_body_text_bold").notNull(),fonts_body_text_size:N("fonts_body_text_size").notNull(),fonts_buttons_text_bold:N("fonts_buttons_text_bold").notNull(),fonts_buttons_text_size:N("fonts_buttons_text_size").notNull(),fonts_font_url:l("fonts_font_url",{length:255}).notNull(),fonts_input_labels_bold:N("fonts_input_labels_bold").notNull(),fonts_input_labels_size:N("fonts_input_labels_size").notNull(),fonts_links_bold:N("fonts_links_bold",{mode:"boolean"}).notNull(),fonts_links_size:N("fonts_links_size").notNull(),fonts_links_style:l("fonts_links_style",{length:24}).notNull(),fonts_reference_text_size:N("fonts_reference_text_size").notNull(),fonts_subtitle_bold:N("fonts_subtitle_bold",{mode:"boolean"}).notNull(),fonts_subtitle_size:N("fonts_subtitle_size").notNull(),fonts_title_bold:N("fonts_title_bold",{mode:"boolean"}).notNull(),fonts_title_size:N("fonts_title_size").notNull(),page_background_background_color:l("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:l("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:l("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:l("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:N("widget_logo_height").notNull(),widget_logo_position:l("widget_logo_position",{length:24}).notNull(),widget_logo_url:l("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:l("widget_social_buttons_layout",{length:24}).notNull(),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.themeId],name:"themes_pkey"}),z("themes_tenant_id_idx").on(e.tenant_id)]),Ae=Z("forms",{id:l("id",{length:255}).primaryKey(),name:l("name",{length:255}).notNull(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),messages:l("messages",{length:255}),languages:l("languages",{length:255}),translations:l("translations",{length:4096}),nodes:l("nodes",{length:4096}),start:l("start",{length:255}),ending:l("ending",{length:255}),style:l("style",{length:1042}),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[z("forms_tenant_id_idx").on(e.tenant_id)]),Te=Z("flows",{id:l("id",{length:24}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),name:l("name",{length:150}).notNull(),actions:l("actions"),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[z("flows_tenant_id_idx").on(e.tenant_id)]),Rt=Z("prompt_settings",{tenant_id:l("tenant_id",{length:191}).primaryKey(),universal_login_experience:l("universal_login_experience",{length:16}).notNull().default("new"),identifier_first:N("identifier_first",{mode:"boolean"}).notNull().default(!0),password_first:N("password_first",{mode:"boolean"}).notNull().default(!1),webauthn_platform_first_factor:N("webauthn_platform_first_factor",{mode:"boolean"}).notNull().default(!1)}),rt=Z("email_providers",{tenant_id:l("tenant_id",{length:191}).primaryKey(),name:l("name",{length:255}).notNull(),enabled:N("enabled",{mode:"boolean"}).notNull(),default_from_address:l("default_from_address",{length:255}),credentials:l("credentials",{length:2048}).notNull().default("{}"),settings:l("settings",{length:2048}).notNull().default("{}"),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()}),Ze=Z("email_templates",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),template:l("template",{length:64}).notNull(),body:l("body").notNull(),from:l("from",{length:255}).notNull(),subject:l("subject",{length:255}).notNull(),syntax:l("syntax",{length:16}).notNull().default("liquid"),result_url:l("result_url",{length:2048}),url_lifetime_in_seconds:N("url_lifetime_in_seconds"),include_email_in_redirect:N("include_email_in_redirect",{mode:"boolean"}).notNull().default(!1),enabled:N("enabled",{mode:"boolean"}).notNull().default(!0),created_at:l("created_at",{length:35}).notNull(),updated_at:l("updated_at",{length:35}).notNull()},e=>[Ce({columns:[e.tenant_id,e.template]})]),be=Z("hooks",{hook_id:l("hook_id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),url:l("url",{length:512}),trigger_id:l("trigger_id",{length:255}).notNull(),enabled:N("enabled",{mode:"boolean"}).notNull(),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull(),synchronous:N("synchronous",{mode:"boolean"}).notNull().default(!1),priority:N("priority"),form_id:l("form_id",{length:128}),template_id:l("template_id",{length:64}),code_id:l("code_id",{length:21}),metadata:l("metadata")},e=>[z("hooks_tenant_id_idx").on(e.tenant_id)]),He=Z("hook_code",{id:l("id",{length:21}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),code:l("code").notNull(),secrets:l("secrets"),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull()},e=>[z("hook_code_tenant_id_idx").on(e.tenant_id)]),We=Z("keys",{kid:l("kid",{length:255}).primaryKey(),tenant_id:l("tenant_id",{length:191}).references(()=>F.id,{onDelete:"cascade"}),created_at:l("created_at",{length:35}).notNull(),revoked_at:l("revoked_at",{length:35}),cert:l("cert",{length:4096}),pkcs7:l("pkcs7",{length:4096}),fingerprint:l("fingerprint",{length:256}),thumbprint:l("thumbprint",{length:256}),current_since:l("current_since",{length:35}),current_until:l("current_until",{length:35}),type:l("type",{length:50}).notNull().default("jwt_signing"),connection:l("connection",{length:255}).references(()=>fe.id,{onDelete:"cascade"})}),Oe=Z("custom_text",{tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),prompt:l("prompt",{length:64}).notNull(),language:l("language",{length:16}).notNull(),custom_text:l("custom_text").notNull(),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull()},e=>[Ce({columns:[e.tenant_id,e.prompt,e.language]})]),pe=Z("authentication_methods",{id:l("id",{length:26}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),user_id:l("user_id",{length:255}).notNull(),type:l("type",{length:32}).notNull(),phone_number:l("phone_number",{length:32}),totp_secret:l("totp_secret",{length:255}),credential_id:l("credential_id",{length:512}),public_key:l("public_key"),sign_count:N("sign_count"),credential_backed_up:N("credential_backed_up"),transports:l("transports",{length:512}),friendly_name:l("friendly_name",{length:255}),confirmed:N("confirmed").notNull().default(0),created_at_ts:N("created_at_ts").notNull(),updated_at_ts:N("updated_at_ts").notNull()},e=>[z("authentication_methods_tenant_user_idx").on(e.tenant_id,e.user_id),z("authentication_methods_credential_id_idx").on(e.credential_id)]),$=Z("logs",{log_id:l("log_id",{length:21}).primaryKey(),category:l("category",{length:255}),tenant_id:l("tenant_id",{length:64}),user_id:l("user_id",{length:64}),ip:l("ip",{length:255}),type:l("type",{length:8}).notNull(),date:l("date",{length:35}).notNull(),client_id:l("client_id",{length:255}),client_name:l("client_name",{length:255}),user_agent:l("user_agent",{length:255}),description:l("description",{length:255}),details:l("details",{length:2048}),isMobile:N("isMobile"),user_name:l("user_name",{length:255}),connection:l("connection",{length:255}),connection_id:l("connection_id",{length:255}),audience:l("audience",{length:255}),scope:l("scope",{length:255}),strategy:l("strategy",{length:255}),strategy_type:l("strategy_type",{length:255}),hostname:l("hostname",{length:255}),auth0_client:l("auth0_client",{length:8192}),session_connection:l("session_connection",{length:255}),country_code:l("country_code",{length:2}),city_name:l("city_name",{length:255}),latitude:l("latitude",{length:255}),longitude:l("longitude",{length:255}),time_zone:l("time_zone",{length:255}),continent_code:l("continent_code",{length:2})},e=>[z("logs_user_id").on(e.user_id),z("logs_tenant_id").on(e.tenant_id),z("logs_date").on(e.date),z("IDX_logs_tenant_date_type_user").on(e.tenant_id,e.date,e.type,e.user_id)]),U=Z("outbox_events",{id:l("id",{length:26}).primaryKey(),tenant_id:l("tenant_id",{length:191}).notNull().references(()=>F.id,{onDelete:"cascade"}),event_type:l("event_type",{length:64}).notNull(),log_type:l("log_type",{length:64}).notNull(),aggregate_type:l("aggregate_type",{length:64}).notNull(),aggregate_id:l("aggregate_id",{length:255}).notNull(),payload:l("payload").notNull(),created_at:l("created_at",{length:35}).notNull(),processed_at:l("processed_at",{length:35}),retry_count:N("retry_count").notNull().default(0),next_retry_at:l("next_retry_at",{length:35}),error:l("error"),claimed_by:l("claimed_by",{length:255}),claim_expires_at:l("claim_expires_at",{length:35}),dead_lettered_at:l("dead_lettered_at",{length:35}),final_error:l("final_error")},e=>[z("idx_outbox_events_tenant_id").on(e.tenant_id),z("idx_outbox_events_processed_at").on(e.processed_at),z("idx_outbox_events_claimed_by").on(e.claimed_by),z("idx_outbox_events_tenant_dead_lettered").on(e.tenant_id,e.dead_lettered_at)]),Dc=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:Ac,authenticationMethods:pe,branding:$t,clientGrants:Se,clientRegistrationTokens:W,clients:B,codes:ce,connections:fe,customDomains:ze,customText:Oe,domains:zc,emailProviders:rt,emailTemplates:Ze,flows:Te,forms:Ae,hookCode:He,hooks:be,invites:ke,keys:We,loginSessions:Q,logs:$,organizations:Y,otps:Tc,outboxEvents:U,passwords:oe,promptSettings:Rt,refreshTokens:J,resourceServers:ee,rolePermissions:Fe,roles:_e,sessions:se,tenants:F,themes:Ve,tickets:Cc,universalLoginTemplates:ot,userOrganizations:ue,userPermissions:je,userRoles:qe,users:q},Symbol.toStringTag,{value:"Module"}));function K(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>n!==null&&typeof n=="object"?K(n):n);const t={...e};for(const n in t){const i=t[n];i===null?delete t[n]:i!==null&&typeof i=="object"&&(Array.isArray(i)?t[n]=i.map(o=>o!==null&&typeof o=="object"?K(o):o):t[n]=K(i))}return t}function xc(e,t,n={...e}){for(const i of t)e[i]!==void 0&&(n[i]=JSON.stringify(e[i]));return n}function $c(e,t,n=e){for(const i of t)e[i]!==void 0&&(n[i]=e[i]?1:0)}function Pa(e){const t={};for(const n in e)e[n]!==void 0&&e[n]!==null&&(t[n]=e[n]);return t}function R(e,t){if(e==null)return t;if(typeof e=="string")try{return JSON.parse(e)}catch{return t}return e}function Jn(e,t="",n={}){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const o=t?`${t}_${i}`:i,a=e[i];typeof a=="object"&&a!==null&&!Array.isArray(a)?Jn(a,o,n):typeof a=="boolean"?n[o]=a?1:0:n[o]=a}return n}function Ua(e,t){const n={};for(const[i,o]of Object.entries(e)){const a=t.find(s=>i.startsWith(`${s}_`));if(!a)n[i]=o;else{const s=i.slice(a.length+1);n[a]={...n[a],[s]:o}}}return n}function Rc(e){return typeof e=="string"?parseInt(e,10):typeof e=="bigint"?Number(e):e}function Lc(e){return e==="dark"||e==="light"||e==="auto"}function Pc(e){return{async get(t){const n=await e.select().from($t).where(_($t.tenant_id,t)).get();if(!n)return null;const{tenant_id:i,colors_primary:o,colors_page_background_type:a,colors_page_background_start:s,colors_page_background_end:c,colors_page_background_angle_dev:u,font_url:p,dark_mode:d,...h}=n;return K({...h,colors:{primary:o,page_background:{type:a,start:s,end:c,angle_deg:u}},font:p?{url:p}:void 0,dark_mode:Lc(d)?d:void 0})},async set(t,n){const{colors:i,font:o,dark_mode:a,...s}=n,c=i==null?void 0:i.page_background,u=c&&typeof c=="object"?c:void 0,p={...s,colors_primary:i==null?void 0:i.primary,colors_page_background_type:u==null?void 0:u.type,colors_page_background_start:u==null?void 0:u.start,colors_page_background_end:u==null?void 0:u.end,colors_page_background_angle_dev:u==null?void 0:u.angle_deg,font_url:o==null?void 0:o.url,dark_mode:a};await e.insert($t).values({tenant_id:t,...p}).onConflictDoUpdate({target:$t.tenant_id,set:p})}}}var lt=class extends Error{constructor(t=500,n){super(n==null?void 0:n.message,{cause:n==null?void 0:n.cause});b(this,"res");b(this,"status");this.res=n==null?void 0:n.res,this.status=t}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};function Ye(e,t,n){const i=t.split(/ OR /i);if(i.length>1){const p=i.map(d=>{const h=d.trim().match(/^([^:]+):(.+)$/);if(h){const[,m,y]=h;if(!m||!y)return null;const S=y.replace(/^"(.*)"$/,"$1"),C=e[m.trim()];return C?_(C,S.trim()):null}return null}).filter(Boolean);return p.length===0?void 0:Be(...p)}const o=[];let a="",s=!1;for(let p=0;p<t.length;p++){const d=t[p];d==='"'?(s=!s,a+=d):d===" "&&!s?a.trim()&&(o.push(a.trim()),a=""):a+=d}a.trim()&&o.push(a.trim());const c=o.filter(p=>p!=="AND").map(p=>p.replace(/^([^:]+)=/g,"$1:")).map(p=>{let d=p.startsWith("-"),h=null,m="",y=!1,S;if(p.startsWith("-_exists_:"))h=p.substring(10),y=!0,d=!0;else if(p.startsWith("_exists_:"))h=p.substring(9),y=!0,d=!1;else if(p.includes(":")){const C=d?p.substring(1):p,L=C.indexOf(":");h=C.substring(0,L),m=C.substring(L+1),y=!1,m.startsWith(">=")?(S=">=",m=m.substring(2)):m.startsWith(">")?(S=">",m=m.substring(1)):m.startsWith("<=")?(S="<=",m=m.substring(2)):m.startsWith("<")?(S="<",m=m.substring(1)):S="=",m.startsWith('"')&&m.endsWith('"')&&m.length>1&&(m=m.slice(1,-1))}else h=null,m=p,y=!1;return{key:h,value:m,isNegation:d,isExistsQuery:y,operator:S}}),u=[];for(const{key:p,value:d,isNegation:h,isExistsQuery:m,operator:y}of c)if(p){const S=e[p];if(!S){m?u.push(h?k`${k.identifier(p)} IS NULL`:k`${k.identifier(p)} IS NOT NULL`):u.push(k`${k.identifier(p)} ${k.raw(h?"!=":y??"=")} ${d}`);continue}if(m)u.push(h?xe(S):rn(S));else if(h)switch(y){case">":u.push(pt(S,d));break;case">=":u.push(Qe(S,d));break;case"<":u.push(Tt(S,d));break;case"<=":u.push(un(S,d));break;default:u.push(mc(S,d))}else switch(y){case">":u.push(un(S,d));break;case">=":u.push(Tt(S,d));break;case"<":u.push(Qe(S,d));break;case"<=":u.push(pt(S,d));break;default:u.push(_(S,d))}}else if(d){const C=(d.includes("|")?[...n,"user_id"]:n).map(L=>{const x=e[L];return x?L==="user_id"?_(x,d):St(x,`%${d}%`):null}).filter(Boolean);C.length>0&&u.push(Be(...C))}if(u.length!==0)return u.length===1?u[0]:w(...u)}const pi=["global","is_first_party","oidc_conformant","auth0_conformant","sso","sso_disabled","cross_origin_authentication","custom_login_page_on","require_pushed_authorization_requests","require_proof_of_possession","hide_sign_up_disabled_error"],fi=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],gi=["session_transfer","oidc_logout","jwt_configuration","encryption_key","addons","client_metadata","mobile","native_social_login","refresh_token","default_organization","client_authentication_methods","signed_request_object","token_quota","registration_metadata"];function Wt(e){const{tenant_id:t,connections:n,...i}=e,o={...i};for(const a of pi)o[a]=!!i[a];for(const a of fi)o[a]=R(i[a],[]);for(const a of gi)o[a]=R(i[a],{});return o.connections=R(n,[]),K(o)}function Fi(e){const t={...e};$c(e,pi,t);for(const n of fi)e[n]!==void 0&&(t[n]=JSON.stringify(e[n]||[]));for(const n of gi)e[n]!==void 0&&(t[n]=JSON.stringify(e[n]||{}));return e.connections!==void 0&&(t.connections=JSON.stringify(e.connections||[])),Pa(t)}function Uc(e){return{async create(t,n){var s,c;const i=new Date().toISOString(),o={client_id:n.client_id,tenant_id:t,name:n.name,description:n.description,app_type:n.app_type??"regular_web",logo_uri:n.logo_uri,client_secret:n.client_secret,token_endpoint_auth_method:n.token_endpoint_auth_method??"client_secret_basic",cross_origin_loc:n.cross_origin_loc,custom_login_page:n.custom_login_page,custom_login_page_preview:n.custom_login_page_preview,form_template:n.form_template,initiate_login_uri:n.initiate_login_uri,organization_usage:n.organization_usage??"deny",organization_require_behavior:n.organization_require_behavior??"no_prompt",compliance_level:n.compliance_level,par_request_expiry:n.par_request_expiry,created_at:i,updated_at:i};for(const u of pi)o[u]=n[u]??!1;o.oidc_conformant=n.oidc_conformant??!0,o.auth0_conformant=n.auth0_conformant??!0,o.sso_disabled=n.sso_disabled??!1;for(const u of fi)o[u]=n[u]||[];for(const u of gi)o[u]=n[u]||{};o.connections=n.connections||[];const a=Fi(o);try{await e.insert(B).values({...a,tenant_id:t})}catch(u){throw(s=u==null?void 0:u.message)!=null&&s.includes("UNIQUE constraint failed")||(c=u==null?void 0:u.message)!=null&&c.includes("duplicate key")?new lt(409,{message:"Client already exists"}):u}return Wt({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(B).where(w(_(B.tenant_id,t),_(B.client_id,n))).get();return i?Wt(i):null},async getByClientId(t){const n=await e.select().from(B).where(_(B.client_id,t)).get();return n?{...Wt(n),tenant_id:n.tenant_id}:null},async update(t,n,i){const o=Fi({...i,updated_at:new Date().toISOString()});return delete o.client_id,delete o.tenant_id,await e.update(B).set(o).where(w(_(B.tenant_id,t),_(B.client_id,n))),!0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{};let u=e.select().from(B).where(_(B.tenant_id,t)).$dynamic();if(c){const m=Ye(B,c,["name","client_id"]);m&&(u=u.where(w(_(B.tenant_id,t),m)))}if(s!=null&&s.sort_by){const m=B[s.sort_by];m&&(u=u.orderBy(s.sort_order==="desc"?le(m):me(m)))}const d=(await u.offset(i*o).limit(o)).map(Wt);if(!a)return{clients:d};const[h]=await e.select({count:ye()}).from(B).where(_(B.tenant_id,t));return{clients:d,start:i*o,limit:o,length:Number((h==null?void 0:h.count)??0)}},async remove(t,n){return(await e.delete(B).where(w(_(B.tenant_id,t),_(B.client_id,n))).returning()).length>0}}}function Fc(e){const{tenant_id:t,is_system:n,options:i,metadata:o,...a}=e;return K({...a,options:R(i,{}),metadata:R(o),is_system:n?!0:void 0})}function Zc(e){return{async listByClient(t,n){const i=await e.select({connections:B.connections}).from(B).where(w(_(B.tenant_id,t),_(B.client_id,n))).get();if(!i)return[];const o=R(i.connections,[])||[];if(o.length===0)return[];const s=(await e.select().from(fe).where(w(_(fe.tenant_id,t),Re(fe.id,o))).all()).map(Fc);return o.map(c=>s.find(u=>u.id===c)).filter(Boolean)},async updateByClient(t,n,i){return(await e.update(B).set({connections:JSON.stringify([...new Set(i)])}).where(w(_(B.tenant_id,t),_(B.client_id,n))).returning()).length>0},async listByConnection(t,n){return(await e.select({client_id:B.client_id,connections:B.connections}).from(B).where(_(B.tenant_id,t)).all()).filter(o=>(R(o.connections,[])||[]).includes(n)).map(o=>o.client_id)},async addClientToConnection(t,n,i){var c;if(!await e.select({client_id:B.client_id}).from(B).where(w(_(B.tenant_id,t),_(B.client_id,i))).get())return!1;const a=await e.run(k`UPDATE clients SET connections = CASE
|
|
2
2
|
WHEN connections IS NULL OR connections = '[]' OR connections = ''
|
|
3
|
-
THEN json_array(${
|
|
4
|
-
WHEN EXISTS (SELECT 1 FROM json_each(connections) WHERE value = ${
|
|
3
|
+
THEN json_array(${n})
|
|
4
|
+
WHEN EXISTS (SELECT 1 FROM json_each(connections) WHERE value = ${n})
|
|
5
5
|
THEN connections
|
|
6
|
-
ELSE json_insert(connections, '$[#]', ${
|
|
6
|
+
ELSE json_insert(connections, '$[#]', ${n})
|
|
7
7
|
END
|
|
8
|
-
WHERE tenant_id = ${
|
|
8
|
+
WHERE tenant_id = ${t} AND client_id = ${i}`);return(a.changes??((c=a.meta)==null?void 0:c.changes)??0)>0},async removeClientFromConnection(t,n,i){var s;const o=await e.run(k`UPDATE clients SET connections = (
|
|
9
9
|
SELECT COALESCE(json_group_array(je.value), '[]')
|
|
10
10
|
FROM json_each(COALESCE(connections, '[]')) AS je
|
|
11
|
-
WHERE je.value != ${
|
|
11
|
+
WHERE je.value != ${n}
|
|
12
12
|
)
|
|
13
|
-
WHERE tenant_id = ${e} AND client_id = ${i}`);return(o.changes??((l=o.meta)==null?void 0:l.changes)??0)>0}}}let br="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",xr=n=>crypto.getRandomValues(new Uint8Array(n)),kr=(n,e,t)=>{let i=256-256%n.length;if(i===256){let s=n.length-1;return(l=e)=>{if(!l)return"";let d="";for(;;){let u=t(l),f=l;for(;f--;)if(d+=n[u[f]&s],d.length>=l)return d}}}let o=Math.ceil(1.6*256*e/i);return(s=e)=>{if(!s)return"";let l="";for(;;){let d=t(o),u=o;for(;u--;)if(d[u]<i&&(l+=n[d[u]%n.length],l.length>=s))return l}}},Or=(n,e=21)=>kr(n,e|0,xr),Le=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=br[t[n]&63];return e};function Ln(n){const{tenant_id:e,scope:t,authorization_details_types:i,allow_any_organization:o,is_system:s,...l}=n;return G({...l,scope:z(t,[]),authorization_details_types:z(i,[]),allow_any_organization:!!o,is_system:!!s})}function Ar(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),tenant_id:e,client_id:t.client_id,audience:t.audience,scope:JSON.stringify(t.scope||[]),organization_usage:t.organization_usage,allow_any_organization:t.allow_any_organization?1:0,is_system:t.is_system?1:0,subject_type:t.subject_type,authorization_details_types:JSON.stringify(t.authorization_details_types||[]),created_at:i,updated_at:i};return await n.insert(ye).values(s),Ln({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).get();return i?Ln(i):null},async update(e,t,i){const{scope:o,authorization_details_types:s,allow_any_organization:l,is_system:d,...u}=i,f={...u,updated_at:new Date().toISOString()};return o!==void 0&&(f.scope=JSON.stringify(o)),s!==void 0&&(f.authorization_details_types=JSON.stringify(s)),l!==void 0&&(f.allow_any_organization=l?1:0),d!==void 0&&(f.is_system=d?1:0),(await n.update(ye).set(f).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(ye,d,["client_id","audience"]):void 0,f=u?g(c(ye.tenant_id,e),u):c(ye.tenant_id,e);let p=n.select().from(ye).where(f).$dynamic();if(l!=null&&l.sort_by){const A=ye[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}else p=p.orderBy(he(ye.created_at));const y=(await p.offset(i*o).limit(o)).map(Ln);if(!s)return{client_grants:y};const[b]=await n.select({count:ge()}).from(ye).where(f);return{client_grants:y,start:i*o,limit:o,length:Number((b==null?void 0:b.count)??0)}},async remove(e,t){return(await n.delete(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0}}}function Tr(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(n);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(n,i[o])&&(t[i[o]]=n[i[o]]);return t}function Ir(n,e){var t;return((t=n==null?void 0:n._def)===null||t===void 0?void 0:t.typeName)===e}function Lt(n,e){const t=n.ZodType.prototype[e];n.ZodType.prototype[e]=function(...i){const o=t.apply(this,i);return o._def.openapi=this._def.openapi,o}}function Cr(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o,s){var l,d,u,f,p,m;const y=typeof o=="string"?s:o,b=y??{},{param:A}=b,J=Tr(b,["param"]),Q=Object.assign(Object.assign({},(l=this._def.openapi)===null||l===void 0?void 0:l._internal),typeof o=="string"?{refId:o}:void 0),ie=Object.assign(Object.assign(Object.assign({},(d=this._def.openapi)===null||d===void 0?void 0:d.metadata),J),!((f=(u=this._def.openapi)===null||u===void 0?void 0:u.metadata)===null||f===void 0)&&f.param||A?{param:Object.assign(Object.assign({},(m=(p=this._def.openapi)===null||p===void 0?void 0:p.metadata)===null||m===void 0?void 0:m.param),A)}:void 0),Pe=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(Q).length>0?{_internal:Q}:void 0),Object.keys(ie).length>0?{metadata:ie}:void 0)}));if(Ir(this,"ZodObject")){const Se=this.extend;Pe.extend=function(...be){var it,rt,bn,xn,kn,On,An;const Tn=Se.apply(this,be);return Tn._def.openapi={_internal:{extendedFrom:!((rt=(it=this._def.openapi)===null||it===void 0?void 0:it._internal)===null||rt===void 0)&&rt.refId?{refId:(xn=(bn=this._def.openapi)===null||bn===void 0?void 0:bn._internal)===null||xn===void 0?void 0:xn.refId,schema:this}:(On=(kn=this._def.openapi)===null||kn===void 0?void 0:kn._internal)===null||On===void 0?void 0:On.extendedFrom},metadata:(An=Tn._def.openapi)===null||An===void 0?void 0:An.metadata},Tn}}return Pe},Lt(n,"optional"),Lt(n,"nullable"),Lt(n,"default"),Lt(n,"transform"),Lt(n,"refine");const e=n.ZodObject.prototype.deepPartial;n.ZodObject.prototype.deepPartial=function(){const o=this._def.shape(),s=e.apply(this),l=s._def.shape();return Object.entries(l).forEach(([d,u])=>{var f,p;u._def.openapi=(p=(f=o[d])===null||f===void 0?void 0:f._def)===null||p===void 0?void 0:p.openapi}),s._def.openapi=void 0,s};const t=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){const s=t.apply(this,o);return s._def.openapi=void 0,s};const i=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){const s=i.apply(this,o);return s._def.openapi=void 0,s}}new Set(".\\+*[^]$()");var K;(function(n){n.assertEqual=o=>{};function e(o){}n.assertIs=e;function t(o){throw new Error}n.assertNever=t,n.arrayToEnum=o=>{const s={};for(const l of o)s[l]=l;return s},n.getValidEnumValues=o=>{const s=n.objectKeys(o).filter(d=>typeof o[o[d]]!="number"),l={};for(const d of s)l[d]=o[d];return n.objectValues(l)},n.objectValues=o=>n.objectKeys(o).map(function(s){return o[s]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&s.push(l);return s},n.find=(o,s)=>{for(const l of o)if(s(l))return l},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function i(o,s=" | "){return o.map(l=>typeof l=="string"?`'${l}'`:l).join(s)}n.joinValues=i,n.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var ei;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(ei||(ei={}));const T=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=n=>{switch(typeof n){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(n)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(n)?T.array:n===null?T.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?T.promise:typeof Map<"u"&&n instanceof Map?T.map:typeof Set<"u"&&n instanceof Set?T.set:typeof Date<"u"&&n instanceof Date?T.date:T.object;default:return T.unknown}},S=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class et extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(s){return s.message},i={_errors:[]},o=s=>{for(const l of s.issues)if(l.code==="invalid_union")l.unionErrors.map(o);else if(l.code==="invalid_return_type")o(l.returnTypeError);else if(l.code==="invalid_arguments")o(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let d=i,u=0;for(;u<l.path.length;){const f=l.path[u];u===l.path.length-1?(d[f]=d[f]||{_errors:[]},d[f]._errors.push(t(l))):d[f]=d[f]||{_errors:[]},d=d[f],u++}}};return o(this),i}static assert(e){if(!(e instanceof et))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];t[s]=t[s]||[],t[s].push(e(o))}else i.push(e(o));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}et.create=n=>new et(n);const fn=(n,e)=>{let t;switch(n.code){case S.invalid_type:n.received===T.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case S.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,K.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:t=`Unrecognized key(s) in object: ${K.joinValues(n.keys,", ")}`;break;case S.invalid_union:t="Invalid input";break;case S.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${K.joinValues(n.options)}`;break;case S.invalid_enum_value:t=`Invalid enum value. Expected ${K.joinValues(n.options)}, received '${n.received}'`;break;case S.invalid_arguments:t="Invalid function arguments";break;case S.invalid_return_type:t="Invalid function return type";break;case S.invalid_date:t="Invalid date";break;case S.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:K.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case S.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case S.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case S.custom:t="Invalid input";break;case S.invalid_intersection_types:t="Intersection results could not be merged";break;case S.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case S.not_finite:t="Number must be finite";break;default:t=e.defaultError,K.assertNever(n)}return{message:t}};let Dr=fn;function us(){return Dr}const ps=n=>{const{data:e,path:t,errorMaps:i,issueData:o}=n,s=[...t,...o.path||[]],l={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let d="";const u=i.filter(f=>!!f).slice().reverse();for(const f of u)d=f(l,{data:e,defaultError:d}).message;return{...o,path:s,message:d}};function k(n,e){const t=us(),i=ps({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===fn?void 0:fn].filter(o=>!!o)});n.common.issues.push(i)}class Ae{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const o of t){if(o.status==="aborted")return R;o.status==="dirty"&&e.dirty(),i.push(o.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const o of t){const s=await o.key,l=await o.value;i.push({key:s,value:l})}return Ae.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const o of t){const{key:s,value:l}=o;if(s.status==="aborted"||l.status==="aborted")return R;s.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof l.value<"u"||o.alwaysSet)&&(i[s.value]=l.value)}return{status:e.value,value:i}}}const R=Object.freeze({status:"aborted"}),kt=n=>({status:"dirty",value:n}),ze=n=>({status:"valid",value:n}),ti=n=>n.status==="aborted",ni=n=>n.status==="dirty",St=n=>n.status==="valid",qt=n=>typeof Promise<"u"&&n instanceof Promise;var C;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(C||(C={}));class tt{constructor(e,t,i,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ti=(n,e)=>{if(St(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new et(n.common.issues);return this._error=t,this._error}}};function q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:o}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(l,d)=>{const{message:u}=n;return l.code==="invalid_enum_value"?{message:u??d.defaultError}:typeof d.data>"u"?{message:u??i??d.defaultError}:l.code!=="invalid_type"?{message:d.defaultError}:{message:u??t??d.defaultError}},description:o}}class ${get description(){return this._def.description}_getType(e){return at(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(qt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Ti(i,o)}"~validate"(e){var i,o;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return St(s)?{value:s.value}:{issues:t.common.issues}}catch(s){(o=(i=s==null?void 0:s.message)==null?void 0:i.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>St(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)},o=this._parse({data:e,path:i.path,parent:i}),s=await(qt(o)?o:Promise.resolve(o));return Ti(i,s)}refine(e,t){const i=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const l=e(o),d=()=>s.addIssue({code:S.custom,...i(o)});return typeof Promise<"u"&&l instanceof Promise?l.then(u=>u?!0:(d(),!1)):l?!0:(d(),!1)})}refinement(e,t){return this._refinement((i,o)=>e(i)?!0:(o.addIssue(typeof t=="function"?t(i,o):t),!1))}_refinement(e){return new nt({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ye.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Je.create(this)}promise(){return Gt.create(this,this._def)}or(e){return Vt.create([this,e],this._def)}and(e){return Ht.create(this,e,this._def)}transform(e){return new nt({...q(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Jt({...q(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new Si({typeName:U.ZodBranded,type:this,...q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Qt({...q(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Nn.create(this,e)}readonly(){return Xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Lr=/^c[^\s-]{8,}$/i,Rr=/^[0-9a-z]+$/,Ur=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fr=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,zr=/^[a-z0-9_-]{21}$/i,Mr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Pr=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Br="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Rn;const $r=/^(?:(?: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])$/,jr=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Vr=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Hr=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fs="((\\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])))",Wr=new RegExp(`^${fs}$`);function hs(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Gr(n){return new RegExp(`^${hs(n)}$`)}function gs(n){let e=`${fs}T${hs(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Jr(n,e){return!!((e==="v4"||!e)&&$r.test(n)||(e==="v6"||!e)&&Vr.test(n))}function Qr(n,e){if(!Mr.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),o=JSON.parse(atob(i));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Xr(n,e){return!!((e==="v4"||!e)&&jr.test(n)||(e==="v6"||!e)&&Hr.test(n))}class Xe extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:T.string,received:s.parsedType}),R}const i=new Ae;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="length"){const l=e.data.length>s.value,d=e.data.length<s.value;(l||d)&&(o=this._getOrReturnCtx(e,o),l?k(o,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):d&&k(o,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if(s.kind==="email")qr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="emoji")Rn||(Rn=new RegExp(Br,"u")),Rn.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="uuid")Fr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="nanoid")zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid")Lr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid2")Rr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="ulid")Ur.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:S.invalid_string,message:s.message}),i.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:S.invalid_string,message:s.message}),i.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):s.kind==="datetime"?gs(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"datetime",message:s.message}),i.dirty()):s.kind==="date"?Wr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"date",message:s.message}),i.dirty()):s.kind==="time"?Gr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"time",message:s.message}),i.dirty()):s.kind==="duration"?Pr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="ip"?Jr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="jwt"?Qr(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="cidr"?Xr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="base64"?Zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="base64url"?Kr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:S.invalid_string,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(o=>e.test(o),{validation:t,code:S.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Xe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...C.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...C.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...C.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...C.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...C.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...C.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...C.errToObj(t)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new Xe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Xe.create=n=>new Xe({checks:[],typeName:U.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});function Yr(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,o=t>i?t:i,s=Number.parseInt(n.toFixed(o).replace(".","")),l=Number.parseInt(e.toFixed(o).replace(".",""));return s%l/10**o}class Nt extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==T.number){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:T.number,received:s.parsedType}),R}let i;const o=new Ae;for(const s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:S.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Yr(e.data,s.value)!==0&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,o){return new Nt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new Nt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Nt.create=n=>new Nt({checks:[],typeName:U.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class Tt extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==T.bigint)return this._getInvalidInput(e);let i;const o=new Ae;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return k(t,{code:S.invalid_type,expected:T.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,o){return new Tt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new Tt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Tt.create=n=>new Tt({checks:[],typeName:U.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});class hn extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.boolean,received:i.parsedType}),R}return ze(e.data)}}hn.create=n=>new hn({typeName:U.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class Bt extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:T.date,received:s.parsedType}),R}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_date}),R}const i=new Ae;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):K.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Bt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Bt.create=n=>new Bt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:U.ZodDate,...q(n)});class ii extends ${_parse(e){if(this._getType(e)!==T.symbol){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.symbol,received:i.parsedType}),R}return ze(e.data)}}ii.create=n=>new ii({typeName:U.ZodSymbol,...q(n)});class gn extends ${_parse(e){if(this._getType(e)!==T.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.undefined,received:i.parsedType}),R}return ze(e.data)}}gn.create=n=>new gn({typeName:U.ZodUndefined,...q(n)});class $t extends ${_parse(e){if(this._getType(e)!==T.null){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.null,received:i.parsedType}),R}return ze(e.data)}}$t.create=n=>new $t({typeName:U.ZodNull,...q(n)});class jt extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return ze(e.data)}}jt.create=n=>new jt({typeName:U.ZodAny,...q(n)});class mn extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return ze(e.data)}}mn.create=n=>new mn({typeName:U.ZodUnknown,...q(n)});class st extends ${_parse(e){const t=this._getOrReturnCtx(e);return k(t,{code:S.invalid_type,expected:T.never,received:t.parsedType}),R}}st.create=n=>new st({typeName:U.ZodNever,...q(n)});class oi extends ${_parse(e){if(this._getType(e)!==T.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.void,received:i.parsedType}),R}return ze(e.data)}}oi.create=n=>new oi({typeName:U.ZodVoid,...q(n)});class Je extends ${_parse(e){const{ctx:t,status:i}=this._processInputParams(e),o=this._def;if(t.parsedType!==T.array)return k(t,{code:S.invalid_type,expected:T.array,received:t.parsedType}),R;if(o.exactLength!==null){const l=t.data.length>o.exactLength.value,d=t.data.length<o.exactLength.value;(l||d)&&(k(t,{code:l?S.too_big:S.too_small,minimum:d?o.exactLength.value:void 0,maximum:l?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),i.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(k(t,{code:S.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),i.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(k(t,{code:S.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,d)=>o.type._parseAsync(new tt(t,l,t.path,d)))).then(l=>Ae.mergeArray(i,l));const s=[...t.data].map((l,d)=>o.type._parseSync(new tt(t,l,t.path,d)));return Ae.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new Je({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new Je({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new Je({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}Je.create=(n,e)=>new Je({type:n,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...q(e)});function bt(n){if(n instanceof de){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=Ye.create(bt(i))}return new de({...n._def,shape:()=>e})}else return n instanceof Je?new Je({...n._def,type:bt(n.element)}):n instanceof Ye?Ye.create(bt(n.unwrap())):n instanceof ft?ft.create(bt(n.unwrap())):n instanceof ut?ut.create(n.items.map(e=>bt(e))):n}class de extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=K.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==T.object){const f=this._getOrReturnCtx(e);return k(f,{code:S.invalid_type,expected:T.object,received:f.parsedType}),R}const{status:i,ctx:o}=this._processInputParams(e),{shape:s,keys:l}=this._getCached(),d=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(const f in o.data)l.includes(f)||d.push(f);const u=[];for(const f of l){const p=s[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new tt(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof st){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of d)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")d.length>0&&(k(o,{code:S.unrecognized_keys,keys:d}),i.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of d){const m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new tt(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key,y=await p.value;f.push({key:m,value:y,alwaysSet:p.alwaysSet})}return f}).then(f=>Ae.mergeObjectSync(i,f)):Ae.mergeObjectSync(i,u)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,l;const o=((l=(s=this._def).errorMap)==null?void 0:l.call(s,t,i).message)??i.defaultError;return t.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const i of K.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const i of K.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}deepPartial(){return bt(this)}partial(e){const t={};for(const i of K.objectKeys(this.shape)){const o=this.shape[i];e&&!e[i]?t[i]=o:t[i]=o.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const i of K.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let s=this.shape[i];for(;s instanceof Ye;)s=s._def.innerType;t[i]=s}return new de({...this._def,shape:()=>t})}keyof(){return ms(K.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});class Vt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function o(s){for(const d of s)if(d.result.status==="valid")return d.result;for(const d of s)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const l=s.map(d=>new et(d.ctx.common.issues));return k(t,{code:S.invalid_union,unionErrors:l}),R}if(t.common.async)return Promise.all(i.map(async s=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(o);{let s;const l=[];for(const u of i){const f={...t,common:{...t.common,issues:[]},parent:null},p=u._parseSync({data:t.data,path:t.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const d=l.map(u=>new et(u));return k(t,{code:S.invalid_union,unionErrors:d}),R}}get options(){return this._def.options}}Vt.create=(n,e)=>new Vt({options:n,typeName:U.ZodUnion,...q(e)});const ot=n=>n instanceof yn?ot(n.schema):n instanceof nt?ot(n.innerType()):n instanceof Kt?[n.value]:n instanceof pt?n.options:n instanceof Wt?K.objectValues(n.enum):n instanceof Jt?ot(n._def.innerType):n instanceof gn?[void 0]:n instanceof $t?[null]:n instanceof Ye?[void 0,...ot(n.unwrap())]:n instanceof ft?[null,...ot(n.unwrap())]:n instanceof Si||n instanceof Xt?ot(n.unwrap()):n instanceof Qt?ot(n._def.innerType):[];class Sn extends ${_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.object)return k(t,{code:S.invalid_type,expected:T.object,received:t.parsedType}),R;const i=this.discriminator,o=t.data[i],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(k(t,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const o=new Map;for(const s of t){const l=ot(s.shape[e]);if(!l.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of l){if(o.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);o.set(d,s)}}return new Sn({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...q(i)})}}function ai(n,e){const t=at(n),i=at(e);if(n===e)return{valid:!0,data:n};if(t===T.object&&i===T.object){const o=K.objectKeys(e),s=K.objectKeys(n).filter(d=>o.indexOf(d)!==-1),l={...n,...e};for(const d of s){const u=ai(n[d],e[d]);if(!u.valid)return{valid:!1};l[d]=u.data}return{valid:!0,data:l}}else if(t===T.array&&i===T.array){if(n.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<n.length;s++){const l=n[s],d=e[s],u=ai(l,d);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===T.date&&i===T.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Ht extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e),o=(s,l)=>{if(ti(s)||ti(l))return R;const d=ai(s.value,l.value);return d.valid?((ni(s)||ni(l))&&t.dirty(),{status:t.value,value:d.data}):(k(i,{code:S.invalid_intersection_types}),R)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([s,l])=>o(s,l)):o(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ht.create=(n,e,t)=>new Ht({left:n,right:e,typeName:U.ZodIntersection,...q(t)});class ut extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.array)return k(i,{code:S.invalid_type,expected:T.array,received:i.parsedType}),R;if(i.data.length<this._def.items.length)return k(i,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&i.data.length>this._def.items.length&&(k(i,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...i.data].map((l,d)=>{const u=this._def.items[d]||this._def.rest;return u?u._parse(new tt(i,l,i.path,d)):null}).filter(l=>!!l);return i.common.async?Promise.all(s).then(l=>Ae.mergeArray(t,l)):Ae.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ut({...this._def,rest:e})}}ut.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:n,typeName:U.ZodTuple,rest:null,...q(e)})};class Zt extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.object)return k(i,{code:S.invalid_type,expected:T.object,received:i.parsedType}),R;const o=[],s=this._def.keyType,l=this._def.valueType;for(const d in i.data)o.push({key:s._parse(new tt(i,d,i.path,d)),value:l._parse(new tt(i,i.data[d],i.path,d)),alwaysSet:d in i.data});return i.common.async?Ae.mergeObjectAsync(t,o):Ae.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof $?new Zt({keyType:e,valueType:t,typeName:U.ZodRecord,...q(i)}):new Zt({keyType:Xe.create(),valueType:e,typeName:U.ZodRecord,...q(t)})}}class si extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.map)return k(i,{code:S.invalid_type,expected:T.map,received:i.parsedType}),R;const o=this._def.keyType,s=this._def.valueType,l=[...i.data.entries()].map(([d,u],f)=>({key:o._parse(new tt(i,d,i.path,[f,"key"])),value:s._parse(new tt(i,u,i.path,[f,"value"]))}));if(i.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const u of l){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return R;(f.status==="dirty"||p.status==="dirty")&&t.dirty(),d.set(f.value,p.value)}return{status:t.value,value:d}})}else{const d=new Map;for(const u of l){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return R;(f.status==="dirty"||p.status==="dirty")&&t.dirty(),d.set(f.value,p.value)}return{status:t.value,value:d}}}}si.create=(n,e,t)=>new si({valueType:e,keyType:n,typeName:U.ZodMap,...q(t)});class It extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.set)return k(i,{code:S.invalid_type,expected:T.set,received:i.parsedType}),R;const o=this._def;o.minSize!==null&&i.data.size<o.minSize.value&&(k(i,{code:S.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&i.data.size>o.maxSize.value&&(k(i,{code:S.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=this._def.valueType;function l(u){const f=new Set;for(const p of u){if(p.status==="aborted")return R;p.status==="dirty"&&t.dirty(),f.add(p.value)}return{status:t.value,value:f}}const d=[...i.data.values()].map((u,f)=>s._parse(new tt(i,u,i.path,f)));return i.common.async?Promise.all(d).then(u=>l(u)):l(d)}min(e,t){return new It({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new It({...this._def,maxSize:{value:e,message:C.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}It.create=(n,e)=>new It({valueType:n,minSize:null,maxSize:null,typeName:U.ZodSet,...q(e)});class yn extends ${get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}yn.create=(n,e)=>new yn({getter:n,typeName:U.ZodLazy,...q(e)});class Kt extends ${_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return k(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:e.data}}get value(){return this._def.value}}Kt.create=(n,e)=>new Kt({value:n,typeName:U.ZodLiteral,...q(e)});function ms(n,e){return new pt({values:n,typeName:U.ZodEnum,...q(e)})}class pt extends ${_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return k(t,{expected:K.joinValues(i),received:t.parsedType,code:S.invalid_type}),R}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return k(t,{received:t.data,code:S.invalid_enum_value,options:i}),R}return ze(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return pt.create(e,{...this._def,...t})}exclude(e,t=this._def){return pt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}pt.create=ms;class Wt extends ${_parse(e){const t=K.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==T.string&&i.parsedType!==T.number){const o=K.objectValues(t);return k(i,{expected:K.joinValues(o),received:i.parsedType,code:S.invalid_type}),R}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const o=K.objectValues(t);return k(i,{received:i.data,code:S.invalid_enum_value,options:o}),R}return ze(e.data)}get enum(){return this._def.values}}Wt.create=(n,e)=>new Wt({values:n,typeName:U.ZodNativeEnum,...q(e)});class Gt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.promise&&t.common.async===!1)return k(t,{code:S.invalid_type,expected:T.promise,received:t.parsedType}),R;const i=t.parsedType===T.promise?t.data:Promise.resolve(t.data);return ze(i.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Gt.create=(n,e)=>new Gt({type:n,typeName:U.ZodPromise,...q(e)});class nt extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:l=>{k(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const l=o.transform(i.data,s);if(i.common.async)return Promise.resolve(l).then(async d=>{if(t.value==="aborted")return R;const u=await this._def.schema._parseAsync({data:d,path:i.path,parent:i});return u.status==="aborted"?R:u.status==="dirty"||t.value==="dirty"?kt(u.value):u});{if(t.value==="aborted")return R;const d=this._def.schema._parseSync({data:l,path:i.path,parent:i});return d.status==="aborted"?R:d.status==="dirty"||t.value==="dirty"?kt(d.value):d}}if(o.type==="refinement"){const l=d=>{const u=o.refinement(d,s);if(i.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(i.common.async===!1){const d=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return d.status==="aborted"?R:(d.status==="dirty"&&t.dirty(),l(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(d=>d.status==="aborted"?R:(d.status==="dirty"&&t.dirty(),l(d.value).then(()=>({status:t.value,value:d.value}))))}if(o.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!St(l))return R;const d=o.transform(l.value,s);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:d}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>St(l)?Promise.resolve(o.transform(l.value,s)).then(d=>({status:t.value,value:d})):R);K.assertNever(o)}}nt.create=(n,e,t)=>new nt({schema:n,typeName:U.ZodEffects,effect:e,...q(t)});nt.createWithPreprocess=(n,e,t)=>new nt({schema:e,effect:{type:"preprocess",transform:n},typeName:U.ZodEffects,...q(t)});class Ye extends ${_parse(e){return this._getType(e)===T.undefined?ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ye.create=(n,e)=>new Ye({innerType:n,typeName:U.ZodOptional,...q(e)});class ft extends ${_parse(e){return this._getType(e)===T.null?ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ft.create=(n,e)=>new ft({innerType:n,typeName:U.ZodNullable,...q(e)});class Jt extends ${_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===T.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Jt.create=(n,e)=>new Jt({innerType:n,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});class Qt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return qt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Qt.create=(n,e)=>new Qt({innerType:n,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});class ri extends ${_parse(e){if(this._getType(e)!==T.nan){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:T.nan,received:i.parsedType}),R}return{status:"valid",value:e.data}}}ri.create=n=>new ri({typeName:U.ZodNaN,...q(n)});class Si extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Nn extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?R:s.status==="dirty"?(t.dirty(),kt(s.value)):this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();{const o=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?R:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:i.path,parent:i})}}static create(e,t){return new Nn({in:e,out:t,typeName:U.ZodPipeline})}}class Xt extends ${_parse(e){const t=this._def.innerType._parse(e),i=o=>(St(o)&&(o.value=Object.freeze(o.value)),o);return qt(t)?t.then(o=>i(o)):i(t)}unwrap(){return this._def.innerType}}Xt.create=(n,e)=>new Xt({innerType:n,typeName:U.ZodReadonly,...q(e)});function li(n,e={},t){return jt.create()}var U;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(U||(U={}));const a=Xe.create,x=Nt.create,h=hn.create,ys=$t.create,V=jt.create,Fe=mn.create;st.create;const N=Je.create,_=de.create,Me=Vt.create,Ct=Sn.create;Ht.create;ut.create;const M=Zt.create,I=Kt.create,E=pt.create,wt=Wt.create;Gt.create;Ye.create;ft.create;const vs=nt.createWithPreprocess,el=Object.freeze(Object.defineProperty({__proto__:null,DIRTY:kt,INVALID:R,OK:ze,ParseStatus:Ae,Schema:$,ZodAny:jt,ZodArray:Je,ZodBigInt:Tt,ZodBoolean:hn,ZodBranded:Si,ZodCatch:Qt,ZodDate:Bt,ZodDefault:Jt,ZodDiscriminatedUnion:Sn,ZodEffects:nt,ZodEnum:pt,ZodError:et,get ZodFirstPartyTypeKind(){return U},ZodIntersection:Ht,ZodIssueCode:S,ZodLazy:yn,ZodLiteral:Kt,ZodMap:si,ZodNaN:ri,ZodNativeEnum:Wt,ZodNever:st,ZodNull:$t,ZodNullable:ft,ZodNumber:Nt,ZodObject:de,ZodOptional:Ye,ZodParsedType:T,ZodPipeline:Nn,ZodPromise:Gt,ZodReadonly:Xt,ZodRecord:Zt,ZodSchema:$,ZodSet:It,ZodString:Xe,ZodSymbol:ii,ZodTransformer:nt,ZodTuple:ut,ZodType:$,ZodUndefined:gn,ZodUnion:Vt,ZodUnknown:mn,ZodVoid:oi,addIssueToContext:k,any:V,array:N,boolean:h,custom:li,datetimeRegex:gs,defaultErrorMap:fn,discriminatedUnion:Ct,enum:E,getErrorMap:us,getParsedType:at,isAborted:ti,isAsync:qt,isDirty:ni,isValid:St,literal:I,makeIssue:ps,nativeEnum:wt,null:ys,number:x,object:_,get objectUtil(){return ei},preprocess:vs,record:M,string:a,union:Me,unknown:Fe,get util(){return K}},Symbol.toStringTag,{value:"Module"}));Cr(el);const He=_({created_at:a(),updated_at:a()}),ws=_({id:a(),version:a().optional()}),Ss=_({name:a(),version:a()}),Ns=_({name:a(),value:a().optional()}),Es=_({name:a().max(255),code:a().max(1e5),supported_triggers:N(ws).optional(),runtime:a().max(50).optional(),dependencies:N(Ss).optional(),secrets:N(Ns).optional(),is_system:h().optional(),inherit:h().optional()});Es.partial().extend({status:E(["draft","built"]).optional(),deployed_at:a().optional()});Es.extend({id:a(),tenant_id:a(),status:E(["draft","built"]).default("built"),deployed_at:a().optional(),secrets:N(_({name:a(),value:a().optional()})).optional(),...He.shape});const tl=a(),nl=E(["unspecified","pending","final","partial","canceled","suspended"]),il=_({id:a(),msg:a(),url:a().optional()}),ol=_({action_name:a(),error:il.nullable(),started_at:a(),ended_at:a()}),al=_({level:E(["log","info","warn","error","debug"]),message:a()}),sl=N(_({action_name:a(),lines:N(al)})),rl=_({id:a(),tenant_id:a(),trigger_id:tl,status:nl,results:N(ol),logs:sl.optional(),created_at:a(),updated_at:a()});rl.omit({tenant_id:!0,created_at:!0,updated_at:!0});const ll=_({action_id:a(),code:a().max(1e5),runtime:a().max(50).optional(),dependencies:N(Ss).optional(),secrets:N(Ns).optional(),supported_triggers:N(ws).optional(),deployed:h().default(!0)});ll.extend({id:a(),tenant_id:a(),number:x().int(),...He.shape});const dl=E(["user_action","admin_action","system","api"]),cl=_({type:E(["user","admin","system","api_key","client_credentials"]),id:a().optional(),email:a().optional(),org_id:a().optional(),org_name:a().optional(),scopes:N(a()).optional(),client_id:a().optional()}),_l=_({type:a(),id:a(),before:M(Fe()).optional(),after:M(Fe()).optional(),diff:M(_({old:Fe(),new:Fe()})).optional()}),ul=_({method:a(),path:a(),query:M(a()).optional(),body:Fe().optional(),ip:a(),user_agent:a().optional(),correlation_id:a().optional()}),pl=_({status_code:x(),body:Fe().optional()}),fl=_({country_code:a(),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),hl=_({name:a(),version:a(),env:M(a()).optional()}),gl=_({tenant_id:a(),event_type:a(),log_type:a(),description:a().optional(),category:dl,actor:cl,target:_l,request:ul,response:pl.optional(),connection:a().optional(),strategy:a().optional(),strategy_type:a().optional(),audience:a().optional(),scope:a().optional(),location:fl.optional(),auth0_client:hl.optional(),hostname:a(),is_mobile:h().optional(),timestamp:a()});gl.extend({id:a()});E(["AUTH0","EMAIL","REDIRECT"]);E(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]);E(["VERIFY_EMAIL"]);const ml=_({require_mx_record:h().optional(),block_aliases:h().optional(),block_free_emails:h().optional(),block_disposable_emails:h().optional(),blocklist:N(a()).optional(),allowlist:N(a()).optional()}),yl=_({id:a(),alias:a().max(100).optional(),type:I("AUTH0"),action:I("UPDATE_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({connection_id:a().optional(),user_id:a(),changes:M(a(),V())})}),vl=_({id:a(),alias:a().max(100).optional(),type:I("EMAIL"),action:I("VERIFY_EMAIL"),allow_failure:h().optional(),mask_output:h().optional(),params:_({email:a(),rules:ml.optional()})}),wl=E(["change-email","account","custom"]),Sl=_({id:a(),alias:a().max(100).optional(),type:I("REDIRECT"),action:I("REDIRECT_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({target:wl.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:a().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),Nl=Me([yl,vl,Sl]),El=_({name:a().min(1).max(150).openapi({description:"The name of the flow"}),actions:N(Nl).optional().default([]).openapi({description:"The list of actions to execute in sequence"})});El.extend({...He.shape,id:a().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})});_({page:a().min(0).optional().default("0").transform(n=>parseInt(n,10)).openapi({description:"The page number where 0 is the first page"}),per_page:a().min(1).optional().default("10").transform(n=>parseInt(n,10)).openapi({description:"The number of items per page"}),include_totals:a().optional().default("false").transform(n=>n==="true").openapi({description:"If the total number of items should be included in the response"}),sort:a().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:a().optional().openapi({description:"A lucene query string used to filter the results"})});_({start:x(),limit:x(),length:x(),total:x().optional()});const bl=_({email:a().optional(),email_verified:h().optional(),name:a().optional(),username:a().optional(),given_name:a().optional(),phone_number:a().optional(),phone_verified:h().optional(),family_name:a().optional()}).catchall(V()),xl=_({connection:a(),user_id:a(),provider:a(),isSocial:h(),email:a().optional(),email_verified:h().optional(),phone_number:a().optional(),phone_verified:h().optional(),username:a().optional(),access_token:a().optional(),access_token_secret:a().optional(),refresh_token:a().optional(),profileData:bl.optional()}),kl=_({formatted:a().optional(),street_address:a().optional(),locality:a().optional(),region:a().optional(),postal_code:a().optional(),country:a().optional()}).optional(),bs=_({email:a().optional().transform(n=>n&&n.toLowerCase()),username:a().refine(n=>!n.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:a().optional(),phone_verified:h().optional(),given_name:a().optional(),family_name:a().optional(),nickname:a().optional(),name:a().optional(),picture:a().optional(),locale:a().optional(),linked_to:a().optional(),profileData:a().optional(),user_id:a().optional(),app_metadata:V().default({}).optional(),user_metadata:V().default({}).optional(),middle_name:a().optional(),preferred_username:a().optional(),profile:a().optional(),website:a().optional(),gender:a().optional(),birthdate:a().optional(),zoneinfo:a().optional(),address:kl}),Ol=bs.extend({email_verified:h().default(!1),verify_email:h().optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a().optional(),provider:a().optional(),connection:a(),is_social:h().optional(),registration_completed_at:a().optional(),password:_({hash:a(),algorithm:a()}).optional()}),Al=_({...Ol.omit({password:!0}).shape,...He.shape,user_id:a(),provider:a(),is_social:h(),email:a().optional(),login_count:x().default(0),identities:N(xl).optional()});Al.omit({registration_completed_at:!0});bs.extend({login_count:x(),multifactor:N(a()).optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a()}).catchall(V());let Tl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Il=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=Tl[t[n]&63];return e};const Cl=_({client_id:a().optional().openapi({description:"ID of this client. Generated server-side if omitted (Auth0 behavior)."}),name:a().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:a().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:h().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:a().default(()=>Il()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:E(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:a().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:h().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:h().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),auth0_conformant:h().default(!0).openapi({description:"Whether this client follows Auth0-compatible behavior (true) or strict OIDC behavior (false). When true, profile/email claims are included in the ID token when scopes are requested. When false, these claims are only available from the userinfo endpoint (strict OIDC 5.4 compliance)."}),callbacks:N(a()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:N(a()).default([]).optional().openapi({description:"Comma-separated list of URLs allowed to make requests from JavaScript to Auth0 API (typically used with CORS). By default, all your callback URLs will be allowed. This field allows you to enter other origins if necessary. You can also use wildcards at the subdomain level (e.g., https://*.contoso.com). Query strings and hash information are not taken into account when validating these URLs."}),web_origins:N(a()).default([]).optional().openapi({description:"Comma-separated list of allowed origins for use with Cross-Origin Authentication, Device Flow, and web message response mode."}),client_aliases:N(a()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:N(a()).default([]).optional().openapi({description:"List of allow clients and API ids that are allowed to make delegation requests. Empty means all all your clients are allowed."}),connections:N(a()).default([]).optional().openapi({description:"List of connection IDs enabled for this client. The order determines the display order on the login page."}),allowed_logout_urls:N(a()).default([]).optional().openapi({description:"Comma-separated list of URLs that are valid to redirect to after logout from Auth0. Wildcards are allowed for subdomains."}),session_transfer:M(V()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:M(V()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:N(a()).default([]).optional().openapi({description:"List of grant types supported for this application. Can include authorization_code, implicit, refresh_token, client_credentials, password, http://auth0.com/oauth/grant-type/password-realm, http://auth0.com/oauth/grant-type/mfa-oob, http://auth0.com/oauth/grant-type/mfa-otp, http://auth0.com/oauth/grant-type/mfa-recovery-code, urn:openid:params:grant-type:ciba, and urn:ietf:params:oauth:grant-type:device_code."}),jwt_configuration:M(V()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:N(M(V())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:M(V()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:h().default(!1).openapi({description:"Applies only to SSO clients and determines whether Auth0 will handle Single Sign On (true) or whether the Identity Provider will (false)."}),sso_disabled:h().default(!1).openapi({description:"Whether Single Sign On is disabled for this client. When true, existing SSO sessions will not be reused and users must authenticate every time."}),cross_origin_authentication:h().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:a().url().optional().openapi({description:"URL of the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page."}),custom_login_page_on:h().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:a().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:M(V()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:E(["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. `none` (public client), `client_secret_post` / `client_secret_basic` (HTTP POST / Basic), `client_secret_jwt` (RFC 7523 HMAC assertion using client_secret), or `private_key_jwt` (RFC 7523 asymmetric assertion verified against the client's `jwks` / `jwks_uri`)."}),client_metadata:M(a().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),hide_sign_up_disabled_error:h().default(!1).optional().openapi({description:"Enumeration-safe variant of the connection-level `disable_signup` flag. When a signup is blocked by the password connection and this is true, the identifier screen does not reveal that an email is unknown — it advances to the OTP/password challenge as if the account existed and fails at credential check. Mitigates email enumeration at the cost of UX: users without an account see a generic credential failure instead of an explicit signup-disabled message."}),mobile:M(V()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:a().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:M(V()).default({}).optional(),refresh_token:_({rotation_type:E(["rotating","non-rotating"]).optional().openapi({description:"Whether refresh tokens for this client are rotated on every exchange (Auth0 'rotating' behavior) or kept stable (legacy non-rotating). Defaults to 'non-rotating' when unset."}),leeway:x().int().min(0).max(600).optional().openapi({description:"Seconds after a parent token's first rotation during which presenting it again still mints a fresh sibling child instead of triggering reuse-detection. Defaults to 30s when unset."}),expiration_type:E(["expiring","non-expiring"]).optional().openapi({description:"Auth0-compatible: whether refresh tokens expire."}),token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token absolute lifetime in seconds."}),infinite_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no absolute expiry."}),idle_token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token idle (sliding) lifetime in seconds."}),infinite_idle_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no idle expiry."})}).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:M(V()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:E(["deny","allow","require"]).default("deny").optional().openapi({description:"Defines how to proceed during an authentication transaction with regards an organization. Can be deny (default), allow or require."}),organization_require_behavior:E(["no_prompt","pre_login_prompt","post_login_prompt"]).default("no_prompt").optional().openapi({description:"Defines how to proceed during an authentication transaction when client.organization_usage: 'require'. Can be no_prompt (default), pre_login_prompt or post_login_prompt. post_login_prompt requires oidc_conformant: true."}),client_authentication_methods:M(V()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:h().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:h().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:M(V()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:E(["none","fapi1_adv_pkj_par","fapi1_adv_mtls_par","fapi2_sp_pkj_mtls","fapi2_sp_mtls_mtls"]).optional().openapi({description:"Defines the compliance level for this client, which may restrict it's capabilities"}),par_request_expiry:x().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:M(V()).default({}).optional(),owner_user_id:a().optional().openapi({description:"User ID of the consenting user when this client was created via IAT-gated Dynamic Client Registration. NULL for clients created via the Management API or open DCR."}),registration_type:E(["manual","open_dcr","iat_dcr"]).optional().openapi({description:"Provenance of this client. `manual` = Management API; `open_dcr` = RFC 7591 without IAT; `iat_dcr` = RFC 7591 with an Initial Access Token."}),registration_metadata:M(V()).default({}).optional().openapi({description:"Arbitrary metadata captured at Dynamic Client Registration time that isn't a first-class client field (e.g. integration_type, domain). Also stores `iat_constraints` for clients created via IAT so RFC 7592 PUT can enforce field immutability."}),user_linking_mode:E(["builtin","off"]).optional().openapi({description:"Per-client override for the built-in email-based user-linking path. `builtin` runs the legacy in-process linking at user creation/email update. `off` disables the legacy path; linking only happens if the tenant has enabled the `account-linking` template hook. When unset, the service-level `userLinkingMode` default applies."})});_({created_at:a(),updated_at:a(),...Cl.shape,client_id:a()});const Dl=_({client_id:a().min(1).openapi({description:"ID of the client."}),audience:a().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:N(a()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:E(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:h().optional().openapi({description:"If enabled, any organization can be used with this grant. If disabled (default), the grant must be explicitly assigned to the desired organizations."}),is_system:h().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:E(["client","user"]).optional().openapi({description:"The type of application access the client grant allows. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."}),authorization_details_types:N(a()).optional().openapi({description:"Types of authorization_details allowed for this client grant. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."})}),Ll=_({id:a().openapi({description:"ID of the client grant."}),...Dl.shape,created_at:a().optional(),updated_at:a().optional()});N(Ll);const xs=E(["iat","rat"]),Rl=_({id:a(),token_hash:a(),type:xs,client_id:a().optional(),sub:a().optional(),constraints:M(Fe()).optional(),single_use:h().default(!1),expires_at:a().optional()});_({created_at:a(),used_at:a().optional(),revoked_at:a().optional(),...Rl.shape});const Dt=_({x:x(),y:x()});var ks=(n=>(n.RICH_TEXT="RICH_TEXT",n.NEXT_BUTTON="NEXT_BUTTON",n.BACK_BUTTON="BACK_BUTTON",n.SUBMIT_BUTTON="SUBMIT_BUTTON",n.DIVIDER="DIVIDER",n.TEXT="TEXT",n.EMAIL="EMAIL",n.PASSWORD="PASSWORD",n.NUMBER="NUMBER",n.PHONE="PHONE",n.DATE="DATE",n.CHECKBOX="CHECKBOX",n.RADIO="RADIO",n.SELECT="SELECT",n.HIDDEN="HIDDEN",n.LEGAL="LEGAL",n))(ks||{}),Os=(n=>(n.BLOCK="BLOCK",n.FIELD="FIELD",n))(Os||{});const En=_({id:a(),category:wt(Os),type:wt(ks)}),Ul=En.extend({category:I("BLOCK"),type:I("RICH_TEXT"),config:_({content:a()}).passthrough()}),Fl=En.extend({category:I("BLOCK"),type:Me([I("NEXT_BUTTON"),I("BACK_BUTTON"),I("SUBMIT_BUTTON")]),config:_({text:a()}).passthrough()}),zl=En.extend({category:I("FIELD"),type:I("LEGAL"),required:h().optional(),sensitive:h().optional(),config:_({text:a()}).passthrough()}),Ml=En.extend({category:I("FIELD"),type:Me([I("TEXT"),I("EMAIL"),I("PASSWORD"),I("NUMBER"),I("PHONE"),I("DATE"),I("CHECKBOX"),I("RADIO"),I("SELECT"),I("HIDDEN")]),required:h().optional(),sensitive:h().optional(),config:_({label:a().optional(),placeholder:a().optional()}).passthrough()}),Pl=_({id:a(),category:a(),type:a()}).passthrough(),ql=Me([Ul,Fl,zl,Ml,Pl]),Bl=_({id:a(),type:I("STEP"),coordinates:Dt,alias:a().optional(),config:_({components:N(ql),next_node:a()}).passthrough()}),$l=_({id:a(),type:I("FLOW"),coordinates:Dt,alias:a().optional(),config:_({flow_id:a(),next_node:a()})}),jl=_({id:a(),type:I("ACTION"),coordinates:Dt,alias:a().optional(),config:_({action_type:E(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:E(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:a().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:a().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),Vl=_({id:a(),type:a(),coordinates:Dt}).passthrough(),Hl=Me([Bl,$l,jl,Vl]),Zl=_({next_node:a(),coordinates:Dt}).passthrough(),Kl=_({resume_flow:h().optional(),coordinates:Dt}).passthrough(),Wl=_({id:a(),name:a(),languages:_({primary:a()}).passthrough(),nodes:N(Hl),start:Zl,ending:Kl,created_at:a(),updated_at:a(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).passthrough()}).passthrough();Wl.omit({id:!0,created_at:!0,updated_at:!0});var As=(n=>(n.TOKEN="token",n.ID_TOKEN="id_token",n.TOKEN_ID_TOKEN="id_token token",n.CODE="code",n.CODE_ID_TOKEN="code id_token",n.CODE_TOKEN="code token",n.CODE_ID_TOKEN_TOKEN="code id_token token",n))(As||{}),Ts=(n=>(n.QUERY="query",n.FRAGMENT="fragment",n.FORM_POST="form_post",n.WEB_MESSAGE="web_message",n.SAML_POST="saml_post",n))(Ts||{}),Is=(n=>(n.S256="S256",n.Plain="plain",n))(Is||{});const Ii=Me([ys(),_({essential:h().optional(),value:Fe().optional(),values:N(Fe()).optional()})]).nullable(),Gl=_({userinfo:M(a(),Ii).optional(),id_token:M(a(),Ii).optional()}),Jl=_({client_id:a(),act_as:a().optional(),response_type:wt(As).optional(),response_mode:wt(Ts).optional(),redirect_uri:a().optional(),audience:a().optional(),organization:a().optional(),state:a().optional(),nonce:a().optional(),scope:a().optional(),prompt:a().optional(),code_challenge_method:wt(Is).optional(),code_challenge:a().optional(),username:a().optional(),ui_locales:a().optional(),max_age:x().optional(),acr_values:a().optional(),claims:Gl.optional(),vendor_id:a().optional()});_({colors:_({primary:a(),page_background:Me([a(),_({type:a().optional(),start:a().optional(),end:a().optional(),angle_deg:x().optional()})]).optional()}).optional(),logo_url:a().optional(),favicon_url:a().optional(),powered_by_logo_url:a().optional(),font:_({url:a()}).optional(),dark_mode:E(["dark","light","auto"]).optional()});const Ql=E(["password_reset","email_verification","otp","mfa_otp","authorization_code","oauth2_state","ticket"]),Xl=_({code_id:a().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:a().openapi({description:"The id of the login session that the code is connected to"}),connection_id:a().optional().openapi({description:"The connection that the code is connected to"}),code_type:Ql,code_verifier:a().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:a().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:E(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:a().optional().openapi({description:"The redirect URI associated with the code"}),otp:a().optional().openapi({description:"The one-time password value for OTP-based flows"}),nonce:a().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:a().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:a(),used_at:a().optional(),user_id:a().optional()});_({...Xl.shape,created_at:a()});const Yl=_({kid:a().optional(),team_id:a().optional(),realms:a().optional(),authentication_method:a().optional(),client_id:a().optional(),client_secret:a().optional(),app_secret:a().optional(),scope:a().optional(),authorization_endpoint:a().optional(),token_endpoint:a().optional(),userinfo_endpoint:a().optional(),jwks_uri:a().optional(),discovery_url:a().optional(),issuer:a().optional(),token_endpoint_auth_method:E(["client_secret_basic","client_secret_post"]).optional(),provider:a().optional(),from:a().optional(),twilio_sid:a().optional(),twilio_token:a().optional(),icon_url:a().optional(),domain_aliases:N(a()).optional(),callback_url:a().url().optional(),passwordPolicy:E(["none","low","fair","good","excellent"]).optional(),password_complexity_options:_({min_length:x().optional()}).optional(),password_history:_({enable:h().optional(),size:x().optional()}).optional(),password_no_personal_info:_({enable:h().optional()}).optional(),password_dictionary:_({enable:h().optional(),dictionary:N(a()).optional()}).optional(),disable_signup:h().optional(),brute_force_protection:h().optional(),import_mode:h().optional(),configuration:_({token_endpoint:a().optional(),userinfo_endpoint:a().optional(),client_id:a().optional(),client_secret:a().optional(),realm:a().optional()}).optional(),attributes:_({email:_({identifier:_({active:h().optional()}).optional(),signup:_({status:E(["required","optional","disabled"]).optional(),verification:_({active:h().optional()}).optional()}).optional(),validation:_({allowed:h().optional()}).optional(),unique:h().optional(),profile_required:h().optional(),verification_method:E(["link","code"]).optional()}).optional(),username:_({identifier:_({active:h().optional()}).optional(),signup:_({status:E(["required","optional","disabled"]).optional()}).optional(),validation:_({max_length:x().optional(),min_length:x().optional(),allowed_types:_({email:h().optional(),phone_number:h().optional()}).optional()}).optional(),profile_required:h().optional()}).optional(),phone_number:_({identifier:_({active:h().optional()}).optional(),signup:_({status:E(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:_({password:_({enabled:h().optional()}).optional(),passkey:_({enabled:h().optional()}).optional()}).optional(),passkey_options:_({challenge_ui:E(["both","autofill","button"]).optional(),local_enrollment_enabled:h().optional(),progressive_enrollment_enabled:h().optional()}).optional(),requires_username:h().optional(),validation:_({username:_({min:x().optional(),max:x().optional()}).optional()}).optional(),set_user_root_attributes:E(["on_each_login","on_first_login","never_on_login"]).optional()});function di(n){if(n!==null){if(Array.isArray(n))return n.filter(e=>e!==null).map(di);if(n&&typeof n=="object"){const e={};for(const[t,i]of Object.entries(n))i!==null&&(e[t]=di(i));return e}return n}}const ed=_({id:a().optional(),name:a(),display_name:a().optional(),strategy:a(),options:vs(n=>n===null?{}:di(n),Yl).default({}),enabled_clients:N(a()).default([]).optional(),response_type:li().optional(),response_mode:li().optional(),is_domain_connection:h().optional(),show_as_button:h().optional(),metadata:M(V()).optional(),is_system:h().optional()});_({id:a(),created_at:a().transform(n=>n===null?"":n),updated_at:a().transform(n=>n===null?"":n)}).extend(ed.shape);const td=_({domain:a(),custom_domain_id:a().optional(),type:E(["auth0_managed_certs","self_managed_certs"]),verification_method:E(["txt"]).optional(),tls_policy:E(["recommended"]).optional(),custom_client_ip_header:E(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:M(a().max(255)).optional()}),nd=Ct("name",[_({name:I("txt"),record:a(),domain:a()}),_({name:I("http"),http_body:a(),http_url:a()})]),id=_({...td.shape,custom_domain_id:a(),primary:h(),status:E(["disabled","pending","pending_verification","ready"]),origin_domain_name:a().optional(),verification:_({methods:N(nd)}).optional(),tls_policy:a().optional()});id.extend({tenant_id:a()});const Ni=_({id:a(),order:x().optional(),visible:h().optional().default(!0)}),ht=Ni.extend({category:I("BLOCK").optional()}),od=ht.extend({type:I("DIVIDER"),config:_({text:a().optional()}).optional()}),ad=ht.extend({type:I("HTML"),config:_({content:a().optional()}).optional()}),sd=ht.extend({type:I("IMAGE"),config:_({src:a().optional(),alt:a().optional(),width:x().optional(),height:x().optional()}).optional()}),rd=ht.extend({type:I("JUMP_BUTTON"),config:_({text:a().optional(),target_step:a().optional()})}),ld=ht.extend({type:I("RESEND_BUTTON"),config:_({text:a().optional(),resend_action:a().optional()})}),dd=ht.extend({type:I("NEXT_BUTTON"),config:_({text:a().optional()})}),cd=ht.extend({type:I("PREVIOUS_BUTTON"),config:_({text:a().optional()})}),_d=ht.extend({type:I("RICH_TEXT"),config:_({content:a().optional()}).optional()}),Ei=Ni.extend({category:I("WIDGET").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),required:h().optional(),sensitive:h().optional()}),ud=Ei.extend({type:I("AUTH0_VERIFIABLE_CREDENTIALS"),config:_({credential_type:a().optional()})}),pd=Ei.extend({type:I("GMAPS_ADDRESS"),config:_({api_key:a().optional()})}),fd=Ei.extend({type:I("RECAPTCHA"),config:_({site_key:a().optional()})}),Ee=Ni.extend({category:I("FIELD").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),messages:N(_({id:x().optional(),text:a(),type:E(["info","error","success","warning"])})).optional(),required:h().optional(),sensitive:h().optional()}),hd=Ee.extend({type:I("BOOLEAN"),config:_({default_value:h().optional()}).optional()}),gd=Ee.extend({type:I("CARDS"),config:_({options:N(_({value:a(),label:a(),description:a().optional(),image:a().optional()})).optional(),multi_select:h().optional()}).optional()}),md=Ee.extend({type:I("CHOICE"),config:_({options:N(_({value:a(),label:a()})).optional(),display:E(["radio","checkbox"]).optional(),multiple:h().optional(),default_value:Me([a(),N(a())]).optional()}).optional()}),yd=Ee.extend({type:I("CUSTOM"),config:_({component:a().optional(),props:M(V()).optional(),schema:M(V()).optional(),code:a().optional()})}),vd=Ee.extend({type:I("DATE"),config:_({format:a().optional(),min:a().optional(),max:a().optional(),default_value:a().optional()}).optional()}),wd=Ee.extend({type:I("DROPDOWN"),config:_({options:N(_({value:a(),label:a()})).optional(),placeholder:a().optional(),searchable:h().optional(),multiple:h().optional(),default_value:Me([a(),N(a())]).optional()}).optional()}),Sd=Ee.extend({type:I("EMAIL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Nd=Ee.extend({type:I("FILE"),config:_({accept:a().optional(),max_size:x().optional(),multiple:h().optional()}).optional()}),Ed=Ee.extend({type:I("LEGAL"),config:_({text:a(),html:h().optional()}).optional()}),bd=Ee.extend({type:I("NUMBER"),config:_({placeholder:a().optional(),min:x().optional(),max:x().optional(),step:x().optional(),default_value:a().optional()}).optional()}),xd=Ee.extend({type:I("PASSWORD"),config:_({placeholder:a().optional(),min_length:x().optional(),show_toggle:h().optional(),forgot_password_link:a().optional(),default_value:a().optional()}).optional()}),kd=Ee.extend({type:I("PAYMENT"),config:_({provider:a().optional(),currency:a().optional()}).optional()}),Od=Ee.extend({type:I("SOCIAL"),config:_({providers:N(a()).optional(),provider_details:N(_({name:a(),strategy:a().optional(),display_name:a().optional(),icon_url:a().optional(),href:a().optional()})).optional()}).optional()}),Ad=Ee.extend({type:I("TEL"),config:_({placeholder:a().optional(),default_country:a().optional(),default_value:a().optional(),allow_email:h().optional()}).optional()}),Td=Ee.extend({type:I("TEXT"),config:_({placeholder:a().optional(),multiline:h().optional(),max_length:x().optional(),default_value:a().optional()}).optional()}),Id=Ee.extend({type:I("COUNTRY"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Cd=Ee.extend({type:I("URL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Dd=Ct("type",[od,ad,sd,rd,ld,dd,cd,_d]),Ld=Ct("type",[ud,pd,fd]),Rd=Ct("type",[hd,gd,md,Id,yd,vd,wd,Sd,Nd,Ed,bd,xd,kd,Od,Ad,Td,Cd]),Cs=Me([Dd,Ld,Rd]);_({id:a(),type:I("submit"),label:a(),className:a().optional(),disabled:h().optional().default(!1),order:x().optional(),visible:h().optional().default(!0),customizations:M(a(),V()).optional()});const Yt=_({x:x(),y:x()}),Ud=_({id:a(),type:I("FLOW"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({flow_id:a().max(30),next_node:a().optional()})}),Fd=_({id:a(),type:I("ROUTER"),coordinates:Yt,alias:a().min(1).max(150),config:_({rules:N(_({id:a(),alias:a().min(1).max(150).optional(),condition:V(),next_node:a()})),fallback:a()})}),zd=_({id:a(),type:I("STEP"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({components:N(Cs),next_node:a().optional()})}),Md=Ct("type",[Ud,Fd,zd]),Pd=_({name:a().openapi({description:"The name of the form"}),messages:_({errors:M(a(),V()).optional(),custom:M(a(),V()).optional()}).optional(),languages:_({primary:a().optional(),default:a().optional()}).optional(),translations:M(a(),V()).optional(),nodes:N(Md).optional(),start:_({hidden_fields:N(_({key:a(),value:a()})).optional(),next_node:a().optional(),coordinates:Yt.optional()}).optional(),ending:_({redirection:_({delay:x().optional(),target:a().optional()}).optional(),after_submit:_({flow_id:a().optional()}).optional(),coordinates:Yt.optional(),resume_flow:h().optional()}).optional(),style:_({css:a().optional()}).optional(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"});_({...He.shape,...Pd.shape,id:a()});const qd=_({id:x().optional(),text:a(),type:E(["info","error","success","warning"])}),Bd=_({id:a().optional(),text:a(),href:a(),linkText:a().optional()});_({name:a().optional(),action:a(),method:E(["POST","GET"]),title:a().optional(),description:a().optional(),components:N(Cs),messages:N(qd).optional(),links:N(Bd).optional(),footer:a().optional()});const Ds=E(["pre-user-registration","post-user-registration","post-user-login","post-user-update","validate-registration-username","pre-user-deletion","post-user-deletion"]),Ls=E(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Rs=E(["post-user-login","post-user-registration","post-user-update","credentials-exchange"]),Us=E(["post-user-login","credentials-exchange","pre-user-registration","post-user-registration"]),Fs=E(["ensure-username","set-preferred-username","account-linking"]),gt={enabled:h().default(!1),synchronous:h().default(!1),priority:x().optional(),hook_id:a().optional(),metadata:M(Fe()).optional()},$d=_({...gt,trigger_id:Ds,url:a()}),jd=_({...gt,trigger_id:Ls,form_id:a()}),Vd=_({...gt,trigger_id:Rs,template_id:Fs}),Hd=_({...gt,trigger_id:Us,code_id:a()});Me([$d,jd,Vd,Hd]);const Zd=_({...gt,trigger_id:Ds,...He.shape,hook_id:a(),url:a()}),Kd=_({...gt,trigger_id:Ls,...He.shape,hook_id:a(),form_id:a()}),Wd=_({...gt,trigger_id:Rs,...He.shape,hook_id:a(),template_id:Fs}),Gd=_({...gt,trigger_id:Us,...He.shape,hook_id:a(),code_id:a()});Me([Zd,Kd,Wd,Gd]);const Jd=_({code:a().max(1e5),secrets:M(a()).optional()});Jd.extend({id:a(),tenant_id:a(),...He.shape});const Qd=_({name:a().optional()}),Xd=_({email:a().optional()}),Yd=_({id:a().optional(),organization_id:a().max(50),inviter:Qd,invitee:Xd,invitation_url:a().url(),client_id:a(),connection_id:a().optional(),app_metadata:M(V()).default({}).optional(),user_metadata:M(V()).default({}).optional(),ttl_sec:x().int().max(2592e3).default(604800).optional(),roles:N(a()).default([]).optional(),send_invitation_email:h().default(!0).optional()});_({id:a(),organization_id:a().max(50),created_at:a().datetime(),expires_at:a().datetime(),ticket_id:a().optional()}).extend(Yd.omit({id:!0}).shape);const ec=_({alg:E(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kid:a(),kty:E(["RSA","EC","oct"]),use:E(["sig","enc"]).optional(),n:a().optional(),e:a().optional(),crv:a().optional(),x:a().optional(),y:a().optional(),x5t:a().optional(),x5c:N(a()).optional()}).superRefine((n,e)=>{if(n.kty==="RSA")for(const t of["n","e"])n[t]||e.addIssue({code:S.custom,path:[t],message:`RSA JWK is missing required member '${t}'`});else if(n.kty==="EC")for(const t of["crv","x","y"])n[t]||e.addIssue({code:S.custom,path:[t],message:`EC JWK is missing required member '${t}'`})});_({keys:N(ec)});_({issuer:a(),authorization_endpoint:a(),token_endpoint:a(),userinfo_endpoint:a(),jwks_uri:a(),registration_endpoint:a().optional(),revocation_endpoint:a(),end_session_endpoint:a().optional(),scopes_supported:N(a()),response_types_supported:N(a()),grant_types_supported:N(a()).optional(),code_challenge_methods_supported:N(a()),response_modes_supported:N(a()),subject_types_supported:N(a()),id_token_signing_alg_values_supported:N(a()),token_endpoint_auth_methods_supported:N(a()),claims_supported:N(a()),request_uri_parameter_supported:h(),request_parameter_supported:h(),claims_parameter_supported:h().optional(),request_object_signing_alg_values_supported:N(a()).optional(),token_endpoint_auth_signing_alg_values_supported:N(a())});var zs=(n=>(n.PENDING="pending",n.AUTHENTICATED="authenticated",n.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",n.AWAITING_MFA="awaiting_mfa",n.AWAITING_HOOK="awaiting_hook",n.AWAITING_CONTINUATION="awaiting_continuation",n.COMPLETED="completed",n.FAILED="failed",n.EXPIRED="expired",n))(zs||{});const tc=wt(zs),nc=_({strategy:a(),strategy_type:a()}),ic=_({csrf_token:a(),auth0Client:a().optional(),authParams:Jl,expires_at:a(),deleted_at:a().optional(),ip:a().optional(),useragent:a().optional(),session_id:a().optional(),authorization_url:a().optional(),state:tc.optional().default("pending"),state_data:a().optional(),failure_reason:a().optional(),user_id:a().optional(),auth_connection:a().optional(),auth_strategy:nc.optional(),authenticated_at:a().optional()}).openapi({description:"This represents a login sesion"});_({...ic.shape,id:a().openapi({description:"This is is used as the state in the universal login"}),created_at:a(),updated_at:a()});const Ms={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_IMPERSONATION:"fimp",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",INFORMATION:"i",MFA_REQUIRED:"mfar",MANAGEMENT_API_READ_OPERATION:"mgmt_api_read",FAILED_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_failed",SUCCESSFUL_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_succeeded",FAILED_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_failed",SUCCESSFUL_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_succeeded",ORGANIZATION_MEMBER_ADDED:"organization_member_added",PASSKEY_CHALLENGE_FAILED:"passkey_challenge_failed",PASSKEY_CHALLENGE_STARTED:"passkey_challenge_started",PRE_LOGIN_ASSESSMENT:"pla",BREACHED_PASSWORD:"pwd_leak",BREACHED_PASSWORD_ON_RESET:"reset_pwd_leak",SUCCESS_RESOURCE_CLEANUP:"resource_cleanup",RICH_CONSENTS_ACCESS_ERROR:"rich_consents_access_error",SUCCESS_LOGIN:"s",SUCCESS_API_OPERATION:"sapi",FAILED_API_OPERATION:"fapi",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"sepotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESS_IMPERSONATION:"simp",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_HOOK:"sh",SUCCESS_PASSWORD_MIGRATION:"spm",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},oc=a().refine(n=>Object.values(Ms).includes(n),{message:"Invalid log type"});(()=>{const n={};for(const[e,t]of Object.entries(Ms))e.startsWith("SUCCESS_")||e.startsWith("SUCCESSFUL_")||e.startsWith("SUCCESSFULLY_")||e.endsWith("_SUCCEEDED")||e.endsWith("_COMPLETED")?n[t]="success":e.startsWith("FAILED_")||e.startsWith("ERROR_")||e.startsWith("BREACHED_")||e.startsWith("BLOCKED_")||e==="MFA_AUTH_FAILED"||e==="MFA_AUTH_REJECTED"||e==="MFA_RECOVERY_FAILED"||e==="MFA_ENROLLMENT_FAILED"||e==="EMAIL_VERIFICATION_FAILED"||e==="WEBAUTHN_CHALLENGE_FAILED"||e==="WEBAUTHN_ENROLLMENT_FAILED"||e==="PASSKEY_CHALLENGE_FAILED"||e==="FLOWS_EXECUTION_FAILED"||e==="FORMS_SUBMISSION_FAILED"||e==="CIBA_EXCHANGE_FAILED"||e==="CIBA_START_FAILED"||e==="ACTIONS_EXECUTION_FAILED"||e==="RICH_CONSENTS_ACCESS_ERROR"||e==="USER_CANCELED_DEVICE_CONFIRMATION"||e==="TOO_MANY_MFA_FAILURES"||e==="MFA_RECOVERY_RATE_LIMIT_EXCEED"||e==="API_LIMIT"||e==="MAX_AMOUNT_OF_AUTHENTICATORS"?n[t]="failure":e.startsWith("WARNING_")||e==="API_LIMIT_WARNING"||e==="DEPRECATION_NOTICE"||e==="PRE_LOGIN_ASSESSMENT"?n[t]="warning":e==="CODE_SENT"||e==="CODE_LINK_SENT"||e==="MFA_EMAIL_SENT"||e==="MFA_SMS_SENT"||e==="EMAIL_VERIFICATION_SENT"||e==="PUSH_NOTIFICATION_SENT"?n[t]="code_sent":e==="INFORMATION"||e==="INFORMATION_FROM_SS_SSO_OPERATION"||e==="MANAGEMENT_API_READ_OPERATION"||e==="APPI"||e==="ACLS_SUMMARY"||e==="ORGANIZATION_MEMBER_ADDED"?n[t]="info":n[t]="other";return n})();const ac=_({name:a(),version:a(),env:_({node:a().optional()}).optional()}),sc=_({country_code:a().length(2),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),rc=_({type:oc,date:a(),description:a().optional(),ip:a().optional(),user_agent:a().optional(),details:V().optional(),isMobile:h(),user_id:a().optional(),user_name:a().optional(),connection:a().optional(),connection_id:a().optional(),client_id:a().optional(),client_name:a().optional(),audience:a().optional(),scope:a().optional(),strategy:a().optional(),strategy_type:a().optional(),hostname:a().optional(),auth0_client:ac.optional(),log_id:a().optional(),location_info:sc.optional()});_({...rc.shape,log_id:a()});const lc=E(["http","eventbridge","eventgrid","splunk","datadog","sumo"]),Ps=E(["active","paused","suspended"]),dc=_({type:a(),name:a()}),cc=_({name:a(),type:lc,status:Ps.optional(),sink:M(a(),Fe()),filters:N(dc).optional(),isPriority:h().optional()});cc.extend({id:a(),status:Ps,created_at:a().optional(),updated_at:a().optional()});const _c=E(["auth0","cognito","okta","oidc"]),uc=_({domain:a(),client_id:a(),client_secret:a(),audience:a().optional(),scope:a().optional()}),pc=_({id:a().optional(),name:a(),provider:_c,connection:a(),enabled:h().default(!0),credentials:uc});_({id:a(),created_at:a(),updated_at:a()}).extend(pc.shape);const fc=_({enabled:h().optional(),shields:N(a()).optional(),admin_notification_frequency:N(a()).optional(),method:a().optional(),stage:_({"pre-user-registration":_({shields:N(a()).optional()}).optional(),"pre-change-password":_({shields:N(a()).optional()}).optional()}).optional()}),hc=_({enabled:h().optional(),shields:N(a()).optional(),allowlist:N(a()).optional(),mode:a().optional(),max_attempts:x().optional()}),gc=_({enabled:h().optional(),shields:N(a()).optional(),allowlist:N(a()).optional(),stage:_({"pre-login":_({max_attempts:x().optional(),rate:x().optional()}).optional(),"pre-user-registration":_({max_attempts:x().optional(),rate:x().optional()}).optional()}).optional()}),mc=_({breached_password_detection:fc.optional(),brute_force_protection:hc.optional(),suspicious_ip_throttling:gc.optional()}),yc=_({id:a().optional(),user_id:a(),password:a(),algorithm:E(["bcrypt","argon2id"]).default("argon2id"),is_current:h().default(!0)});yc.extend({id:a(),created_at:a(),updated_at:a()});const qs=_({initial_user_agent:a().describe("First user agent of the device from which this user logged in"),initial_ip:a().describe("First IP address associated with this session"),initial_asn:a().describe("First autonomous system number associated with this session"),last_user_agent:a().describe("Last user agent of the device from which this user logged in"),last_ip:a().describe("Last IP address from which this user logged in"),last_asn:a().describe("Last autonomous system number from which this user logged in")}),vc=_({id:a(),revoked_at:a().optional(),used_at:a().optional(),user_id:a().describe("The user ID associated with the session"),expires_at:a().optional(),login_session_id:a(),idle_expires_at:a().optional(),device:qs.describe("Metadata related to the device used in the session"),clients:N(a()).describe("List of client details for the session")});_({created_at:a(),updated_at:a(),authenticated_at:a(),last_interaction_at:a(),...vc.shape});_({kid:a().openapi({description:"The key id of the signing key"}),tenant_id:a().optional().openapi({description:"The tenant the key belongs to. Omitted means the key is shared / control-plane scoped."}),cert:a().openapi({description:"The public certificate of the signing key"}),fingerprint:a().openapi({description:"The cert fingerprint"}),thumbprint:a().openapi({description:"The cert thumbprint"}),pkcs7:a().optional().openapi({description:"The private key in pkcs7 format"}),current:h().optional().openapi({description:"True if the key is the current key"}),next:h().optional().openapi({description:"True if the key is the next key"}),previous:h().optional().openapi({description:"True if the key is the previous key"}),current_since:a().optional().openapi({description:"The date and time when the key became the current key"}),current_until:a().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:h().optional().openapi({description:"True if the key is revoked"}),revoked_at:a().optional().openapi({description:"The date and time when the key was revoked"}),connection:a().optional().openapi({description:"The connection identifier associated with the key"}),type:E(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});const wc=_({id:a().optional(),audience:a(),friendly_name:a(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sender_email:a().email(),sender_name:a(),session_lifetime:x().optional(),idle_session_lifetime:x().optional(),ephemeral_session_lifetime:x().optional(),idle_ephemeral_session_lifetime:x().optional(),session_cookie:_({mode:E(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:N(a()).optional(),default_redirection_uri:a().optional(),default_client_id:a().optional(),enabled_locales:N(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().optional()}).nullish(),flags:_({allow_changing_enable_sso:h().optional(),allow_legacy_delegation_grant_types:h().optional(),allow_legacy_ro_grant_types:h().optional(),allow_legacy_tokeninfo_endpoint:h().optional(),change_pwd_flow_v1:h().optional(),custom_domains_provisioning:h().optional(),dashboard_insights_view:h().optional(),dashboard_log_streams_next:h().optional(),disable_clickjack_protection_headers:h().optional(),disable_fields_map_fix:h().optional(),disable_impersonation:h().optional(),disable_management_api_sms_obfuscation:h().optional(),enable_adfs_waad_email_verification:h().optional(),enable_apis_section:h().optional(),enable_client_connections:h().optional(),enable_custom_domain_in_emails:h().optional(),enable_dynamic_client_registration:h().optional(),dcr_require_initial_access_token:h().optional(),dcr_allowed_grant_types:N(a()).optional(),allow_http_return_to:N(a().refine(n=>{try{const e=new URL(n);return e.protocol==="http:"&&(e.pathname===""||e.pathname==="/")&&!e.search&&!e.hash&&n===e.origin}catch{return!1}},{message:"must be a fully-qualified http origin (scheme + host + port, no path)"})).optional(),enable_idtoken_api2:h().optional(),enable_legacy_logs_search_v2:h().optional(),enable_legacy_profile:h().optional(),enable_pipeline2:h().optional(),enable_public_signup_user_exists_error:h().optional(),enable_sso:h().optional(),enforce_client_authentication_on_passwordless_start:h().optional(),genai_trial:h().optional(),improved_signup_bot_detection_in_classic:h().optional(),mfa_show_factor_list_on_enrollment:h().optional(),no_disclose_enterprise_connections:h().optional(),remove_alg_from_jwks:h().optional(),revoke_refresh_token_grant:h().optional(),trust_azure_adfs_email_verified_connection_property:h().optional(),use_scope_descriptions_for_consent:h().optional(),inherit_global_permissions_in_organizations:h().optional()}).optional(),sandbox_version:a().optional(),legacy_sandbox_version:a().optional(),sandbox_versions_available:N(a()).optional(),change_password:_({enabled:h().optional(),html:a().optional()}).optional(),guardian_mfa_page:_({enabled:h().optional(),html:a().optional()}).optional(),device_flow:_({charset:E(["base20","digits"]).optional(),mask:a().max(20).optional()}).optional(),default_token_quota:_({clients:_({client_credentials:M(V()).optional()}).optional(),organizations:_({client_credentials:M(V()).optional()}).optional()}).nullish(),default_audience:a().optional(),default_organization:a().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),oidc_logout:_({rp_logout_end_session_endpoint_discovery:h().optional()}).optional(),allow_organization_name_in_authentication_api:h().optional(),customize_mfa_in_postlogin_action:h().optional(),acr_values_supported:N(a()).optional(),mtls:_({enable_endpoint_aliases:h().optional()}).nullish(),pushed_authorization_requests_supported:h().optional(),authorization_response_iss_parameter_supported:h().optional(),attack_protection:mc.optional(),mfa:_({policy:E(["never","always"]).default("never").optional(),factors:_({sms:h().default(!1),otp:h().default(!1),email:h().default(!1),push_notification:h().default(!1),webauthn_roaming:h().default(!1),webauthn_platform:h().default(!1),recovery_code:h().default(!1),duo:h().default(!1)}).optional(),sms_provider:_({provider:E(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({created_at:a().nullable().transform(n=>n??""),updated_at:a().nullable().transform(n=>n??""),...wc.shape,id:a(),is_control_plane:h().optional()});_({access_token:a(),id_token:a().optional(),scope:a().optional(),state:a().optional(),refresh_token:a().optional(),token_type:a(),expires_in:x()});_({code:a(),state:a().optional()});const Sc=_({button_border_radius:x(),button_border_weight:x(),buttons_style:E(["pill","rounded","sharp"]),input_border_radius:x(),input_border_weight:x(),inputs_style:E(["pill","rounded","sharp"]),show_widget_shadow:h(),widget_border_weight:x(),widget_corner_radius:x()}),Nc=_({base_focus_color:a(),base_hover_color:a(),body_text:a(),captcha_widget_theme:E(["auto","dark","light"]),error:a(),header:a(),icons:a(),input_background:a(),input_border:a(),input_filled_text:a(),input_labels_placeholders:a(),links_focused_components:a(),primary_button:a(),primary_button_label:a(),secondary_button_border:a(),secondary_button_label:a(),success:a(),widget_background:a(),widget_border:a()}),Et=_({bold:h(),size:x()}),Ec=_({body_text:Et,buttons_text:Et,font_url:a(),input_labels:Et,links:Et,links_style:E(["normal","underlined"]),reference_text_size:x(),subtitle:Et,title:Et}),bc=_({background_color:a(),background_image_url:a(),page_layout:E(["center","left","right"]),logo_placement:E(["widget","chip","none"]).optional()}),xc=_({header_text_alignment:E(["center","left","right"]),logo_height:x(),logo_position:E(["center","left","none","right"]),logo_url:a(),social_buttons_layout:E(["bottom","top"])}),kc=_({borders:Sc,colors:Nc,displayName:a(),fonts:Ec,page_background:bc,widget:xc});kc.extend({themeId:a()});_({universal_login_experience:E(["new","classic"]).default("new"),identifier_first:h().default(!0),password_first:h().default(!1),webauthn_platform_first_factor:h()});_({name:a(),enabled:h().optional().default(!0),default_from_address:a().optional(),credentials:M(a(),Fe()),settings:_({}).optional()});const Oc=E(["verify_email","verify_email_by_code","reset_email","reset_email_by_code","welcome_email","blocked_account","stolen_credentials","enrollment_email","mfa_oob_code","change_password","password_reset","user_invitation"]);_({template:Oc,body:a(),from:a(),subject:a(),syntax:I("liquid").default("liquid"),resultUrl:a().optional(),urlLifetimeInSeconds:x().int().nonnegative().optional(),includeEmailInRedirect:h().default(!1),enabled:h().default(!0)});const Ac=_({id:a(),login_id:a(),user_id:a(),client_id:a(),expires_at:a().optional(),idle_expires_at:a().optional(),last_exchanged_at:a().optional(),device:qs,resource_servers:N(_({audience:a(),scopes:a()})),rotating:h(),token_lookup:a().optional(),token_hash:a().optional(),family_id:a().optional(),rotated_to:a().optional(),rotated_at:a().optional()});_({created_at:a(),revoked_at:a().optional(),...Ac.shape});_({to:a(),message:a()});_({name:a(),options:_({})});const Tc=_({value:a(),description:a().optional()}),Ic=_({token_dialect:E(["access_token","access_token_authz"]).optional(),enforce_policies:h().optional(),allow_skipping_userinfo:h().optional(),skip_userinfo:h().optional(),persist_client_authorization:h().optional(),enable_introspection_endpoint:h().optional(),mtls:_({bound_access_tokens:h().optional()}).optional()}),Cc=_({id:a().optional(),name:a(),identifier:a(),scopes:N(Tc).optional(),signing_alg:a().optional(),signing_secret:a().optional(),token_lifetime:x().default(86400),token_lifetime_for_web:x().default(7200),skip_consent_for_verifiable_first_party_clients:h().optional(),allow_offline_access:h().optional(),verificationKey:a().optional(),options:Ic.optional(),is_system:h().optional(),metadata:M(V()).optional()}),Dc=_({...Cc.shape,created_at:a().optional(),updated_at:a().optional()});N(Dc);const Lc=_({role_id:a(),resource_server_identifier:a(),permission_name:a()}),Rc=_({...Lc.shape,created_at:a()});N(Rc);const Uc=_({user_id:a(),resource_server_identifier:a(),permission_name:a(),organization_id:a().optional()}),Fc=_({...Uc.shape,tenant_id:a(),created_at:a().optional()});N(Fc);const zc=_({user_id:a(),resource_server_identifier:a(),resource_server_name:a(),permission_name:a(),description:a().nullable().optional(),created_at:a().optional(),organization_id:a().optional()});N(zc);const Mc=_({user_id:a(),role_id:a(),organization_id:a().optional()}),Pc=_({...Mc.shape,tenant_id:a(),created_at:a().optional()});N(Pc);const qc=_({id:a().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:a().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:a().max(255).optional().openapi({description:"The description of the role"}),is_system:h().optional(),metadata:M(V()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),Bc=qc.extend({id:a().openapi({description:"The unique identifier of the role"}),created_at:a().optional(),updated_at:a().optional()});N(Bc);const $c=_({logo_url:a().optional().openapi({description:"URL of the organization's logo"}),colors:_({primary:a().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:a().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),jc=_({connection_id:a().openapi({description:"ID of the connection"}),assign_membership_on_login:h().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:h().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:h().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),Vc=_({client_credentials:_({enforce:h().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:x().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:x().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),Hc=_({id:a().optional(),name:a().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:a().optional().openapi({description:"The display name of the organization"}),branding:$c,metadata:M(V()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:N(jc).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Vc});_({...Hc.shape,...He.shape,id:a(),name:a().min(1).openapi({description:"The name of the organization"})});const Zc=_({connection_id:a().openapi({description:"ID of the tenant-level connection to enable for the org."}),assign_membership_on_login:h().optional().default(!1),show_as_button:h().optional().default(!0),is_signup_enabled:h().optional().default(!0)}),Kc=_({...Zc.shape,connection:_({name:a().optional(),strategy:a().optional()}).optional(),created_at:a().optional(),updated_at:a().optional()});N(Kc);const Wc=_({user_id:a().openapi({description:"ID of the user"}),organization_id:a().openapi({description:"ID of the organization"})});_({...Wc.shape,...He.shape,id:a()});_({idle_session_lifetime:x().default(72),session_lifetime:x().default(168),session_cookie:_({mode:E(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:h().optional(),default_redirection_uri:a().optional(),enabled_locales:N(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().optional()}).optional(),flags:_({allow_legacy_delegation_grant_types:h().optional(),allow_legacy_ro_grant_types:h().optional(),allow_legacy_tokeninfo_endpoint:h().optional(),disable_clickjack_protection_headers:h().optional(),enable_apis_section:h().optional(),enable_client_connections:h().optional(),enable_custom_domain_in_emails:h().optional(),enable_dynamic_client_registration:h().optional(),enable_idtoken_api2:h().optional(),enable_legacy_logs_search_v2:h().optional(),enable_legacy_profile:h().optional(),enable_pipeline2:h().optional(),enable_public_signup_user_exists_error:h().optional(),use_scope_descriptions_for_consent:h().optional(),disable_management_api_sms_obfuscation:h().optional(),enable_adfs_waad_email_verification:h().optional(),revoke_refresh_token_grant:h().optional(),dashboard_log_streams_next:h().optional(),dashboard_insights_view:h().optional(),disable_fields_map_fix:h().optional(),mfa_show_factor_list_on_enrollment:h().optional()}).optional(),friendly_name:a().optional(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sandbox_version:a().optional(),sandbox_versions_available:N(a()).optional(),change_password:_({enabled:h(),html:a()}).optional(),guardian_mfa_page:_({enabled:h(),html:a()}).optional(),default_audience:a().optional(),default_organization:a().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),mfa:_({policy:E(["never","always"]).default("never").optional(),factors:_({sms:h().default(!1),otp:h().default(!1),email:h().default(!1),push_notification:h().default(!1),webauthn_roaming:h().default(!1),webauthn_platform:h().default(!1),recovery_code:h().default(!1),duo:h().default(!1)}).optional(),sms_provider:_({provider:E(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({date:a().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:x().openapi({description:"Number of logins on this date",example:150}),signups:x().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:x().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:a().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:a().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})});x().openapi({description:"Number of active users in the last 30 days",example:1234});E(["active-users","logins","signups","refresh-tokens","sessions"]);E(["hour","day","week","month"]);E(["time","connection","client_id","user_type","event"]);E(["password","social","passwordless","enterprise"]);const Gc=_({name:a(),type:a()}),Jc=_({elapsed:x(),rows_read:x().optional(),bytes_read:x().optional()});_({meta:N(Gc),data:N(M(a(),V())),rows:x(),rows_before_limit_at_least:x().optional(),statistics:Jc.optional()});const Qc=E(["login","login-id","login-password","signup","signup-id","signup-password","reset-password","consent","mfa","mfa-push","mfa-otp","mfa-voice","mfa-phone","mfa-webauthn","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form","login-passwordless","mfa-login-options"]),Xc=M(a(),M(a(),a())).openapi({type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}});_({prompt:Qc,language:a(),custom_text:Xc});const Yc=E(["phone","totp","email","push","webauthn-roaming","webauthn-platform","passkey"]),Bs=_({user_id:a(),type:Yc,phone_number:a().optional(),totp_secret:a().optional(),credential_id:a().optional(),public_key:a().optional(),sign_count:x().int().nonnegative().optional(),credential_backed_up:h().optional(),transports:N(a()).optional(),friendly_name:a().optional(),confirmed:h().default(!1)});function $s(n,e){n.type==="phone"&&!n.phone_number&&e.addIssue({code:S.custom,message:"phone_number is required when type is 'phone'",path:["phone_number"]}),n.type==="totp"&&!n.totp_secret&&e.addIssue({code:S.custom,message:"totp_secret is required when type is 'totp'",path:["totp_secret"]}),["webauthn-roaming","webauthn-platform","passkey"].includes(n.type)&&(n.credential_id||e.addIssue({code:S.custom,message:`credential_id is required when type is '${n.type}'`,path:["credential_id"]}),n.public_key||e.addIssue({code:S.custom,message:`public_key is required when type is '${n.type}'`,path:["public_key"]}))}Bs.superRefine($s);_({...Bs.shape,id:a(),created_at:a(),updated_at:a()}).superRefine($s);function e_(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function t_(n){if(!n)return;const e=JSON.parse(n);return e_(e)?e:void 0}function Un(n){return n==null?void 0:new Date(n).toISOString()}function an(n){if(!n)return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function Fn(n){const e=xs.parse(n.type);return{id:n.id,token_hash:n.token_hash,type:e,client_id:n.client_id??void 0,sub:n.sub??void 0,constraints:t_(n.constraints),single_use:!!n.single_use,expires_at:Un(n.expires_at_ts),used_at:Un(n.used_at_ts),revoked_at:Un(n.revoked_at_ts),created_at:new Date(n.created_at_ts).toISOString()}}function n_(n){return{async create(e,t){const i=Date.now();return await n.insert(X).values({id:t.id,tenant_id:e,token_hash:t.token_hash,type:t.type,client_id:t.client_id??null,sub:t.sub??null,constraints:t.constraints?JSON.stringify(t.constraints):null,single_use:t.single_use?1:0,expires_at_ts:an(t.expires_at),created_at_ts:i}),{id:t.id,token_hash:t.token_hash,type:t.type,client_id:t.client_id,sub:t.sub,constraints:t.constraints,single_use:t.single_use,expires_at:t.expires_at,created_at:new Date(i).toISOString()}},async get(e,t){const i=await n.select().from(X).where(g(c(X.tenant_id,e),c(X.id,t))).get();return i?Fn(i):null},async getByHash(e,t){const i=await n.select().from(X).where(g(c(X.tenant_id,e),c(X.token_hash,t))).get();return i?Fn(i):null},async listByClient(e,t){return(await n.select().from(X).where(g(c(X.tenant_id,e),c(X.client_id,t))).orderBy(se(X.created_at_ts))).map(Fn)},async markUsed(e,t,i){return(await n.update(X).set({used_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.used_at_ts))).returning()).length>0},async revoke(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.revoked_at_ts))).returning()).length>0},async revokeByClient(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.client_id,t),Ce(X.revoked_at_ts))).returning()).length},async remove(e,t){return(await n.delete(X).where(g(c(X.tenant_id,e),c(X.id,t))).returning()).length>0}}}function zn(n){const{tenant_id:e,...t}=n;return G(t)}function i_(n){return{async create(e,t){const i={...t,tenant_id:e,created_at:t.created_at||new Date().toISOString(),expires_at:t.expires_at};return await n.insert(re).values(i),zn(i)},async get(e,t,i){if(!e)throw new Error("tenant_id is required");const o=await n.select().from(re).where(g(c(re.tenant_id,e),c(re.code_id,t),c(re.code_type,i))).get();return o?zn(o):null},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(re).where(c(re.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=re[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(zn);if(!s)return{codes:f};const[p]=await n.select({count:ge()}).from(re).where(c(re.tenant_id,e));return{codes:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async used(e,t){return(await n.update(re).set({used_at:new Date().toISOString()}).where(g(c(re.tenant_id,e),c(re.code_id,t))).returning()).length>0},async consume(e,t){return(await n.update(re).set({used_at:new Date().toISOString()}).where(g(c(re.tenant_id,e),c(re.code_id,t),Ce(re.used_at))).returning()).length>0},async remove(e,t){return(await n.delete(re).where(g(c(re.tenant_id,e),c(re.code_id,t))).returning()).length>0}}}function o_(){const{customAlphabet:n}=require("nanoid");return`con_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Mn(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return G({...s,options:z(i,{}),metadata:z(o),is_system:t?!0:void 0})}function a_(n){return{async create(e,t){var s,l;const i=new Date().toISOString(),o={id:t.id||o_(),...t,tenant_id:e,options:JSON.stringify(t.options||{}),metadata:t.metadata?JSON.stringify(t.metadata):void 0,is_system:t.is_system?1:0,created_at:i,updated_at:i};try{await n.insert(pe).values(o)}catch(d){throw(s=d==null?void 0:d.message)!=null&&s.includes("UNIQUE constraint failed")||(l=d==null?void 0:d.message)!=null&&l.includes("duplicate key")?new _t(409,{message:"Connection already exists"}):d}return Mn(o)},async get(e,t){const i=await n.select().from(pe).where(g(c(pe.tenant_id,e),c(pe.id,t))).get();return i?Mn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.strategy!==void 0&&(o.strategy=i.strategy),i.options!==void 0&&(o.options=JSON.stringify(i.options)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.display_name!==void 0&&(o.display_name=i.display_name),i.response_type!==void 0&&(o.response_type=i.response_type),i.response_mode!==void 0&&(o.response_mode=i.response_mode),await n.update(pe).set(o).where(g(c(pe.tenant_id,e),c(pe.id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=c(pe.tenant_id,e);if(d){const b=Qe(pe,d,["name"]);b&&(u=g(u,b))}let f=n.select().from(pe).where(u).$dynamic();if(l!=null&&l.sort_by){const b=pe[l.sort_by];b&&(f=f.orderBy(l.sort_order==="desc"?se(b):he(b)))}const m=(await f.offset(i*o).limit(o)).map(Mn);if(!s)return{connections:m};const[y]=await n.select({count:ge()}).from(pe).where(u);return{connections:m,start:i*o,limit:o,length:Number((y==null?void 0:y.count)??0)}},async remove(e,t){return(await n.delete(pe).where(g(c(pe.tenant_id,e),c(pe.id,t))).returning()).length>0}}}function sn(n){const{tenant_id:e,domain_metadata:t,...i}=n;return G({...i,primary:!!i.primary,domain_metadata:z(t)})}function s_(n){return{async create(e,t){const i=new Date().toISOString(),s={custom_domain_id:t.custom_domain_id||Le(),tenant_id:e,domain:t.domain,primary:t.primary??!1,status:t.status||"pending",type:t.type,origin_domain_name:t.origin_domain_name,verification:t.verification,custom_client_ip_header:t.custom_client_ip_header,tls_policy:t.tls_policy,domain_metadata:t.domain_metadata?JSON.stringify(t.domain_metadata):void 0,created_at:i,updated_at:i};return await n.insert(Ie).values(s),sn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).get();return i?sn(i):null},async getByDomain(e){const t=await n.select().from(Ie).where(c(Ie.domain,e)).get();return t?{...sn(t),tenant_id:t.tenant_id}:null},async list(e){return(await n.select().from(Ie).where(c(Ie.tenant_id,e)).all()).map(sn)},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.domain!==void 0&&(o.domain=i.domain),i.primary!==void 0&&(o.primary=i.primary),i.status!==void 0&&(o.status=i.status),i.type!==void 0&&(o.type=i.type),i.origin_domain_name!==void 0&&(o.origin_domain_name=i.origin_domain_name),i.verification!==void 0&&(o.verification=i.verification),i.custom_client_ip_header!==void 0&&(o.custom_client_ip_header=i.custom_client_ip_header),i.tls_policy!==void 0&&(o.tls_policy=i.tls_policy),i.domain_metadata!==void 0&&(o.domain_metadata=JSON.stringify(i.domain_metadata)),(await n.update(Ie).set(o).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0}}}function r_(n){return{async get(e,t,i){const o=await n.select().from(Ne).where(g(c(Ne.tenant_id,e),c(Ne.prompt,t),c(Ne.language,i))).get();if(!o)return null;try{return JSON.parse(o.custom_text)}catch{return null}},async set(e,t,i,o){const s=Date.now(),l=JSON.stringify(o);await n.insert(Ne).values({tenant_id:e,prompt:t,language:i,custom_text:l,created_at_ts:s,updated_at_ts:s}).onConflictDoUpdate({target:[Ne.tenant_id,Ne.prompt,Ne.language],set:{custom_text:l,updated_at_ts:s}})},async delete(e,t,i){await n.delete(Ne).where(g(c(Ne.tenant_id,e),c(Ne.prompt,t),c(Ne.language,i)))},async list(e){return await n.select({prompt:Ne.prompt,language:Ne.language}).from(Ne).where(c(Ne.tenant_id,e)).all()}}}function l_(n){return{async create(e,t){const i=new Date().toISOString();await n.insert(dt).values({tenant_id:e,name:t.name,enabled:t.enabled,default_from_address:t.default_from_address,credentials:JSON.stringify(t.credentials||{}),settings:JSON.stringify(t.settings||{}),created_at:i,updated_at:i})},async get(e){const t=await n.select().from(dt).where(c(dt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,...o}=t;return G({...o,enabled:!!o.enabled,credentials:z(o.credentials,{}),settings:z(o.settings,{})})},async update(e,t){const i={updated_at:new Date().toISOString()};t.name!==void 0&&(i.name=t.name),t.enabled!==void 0&&(i.enabled=t.enabled),t.default_from_address!==void 0&&(i.default_from_address=t.default_from_address),t.credentials!==void 0&&(i.credentials=JSON.stringify(t.credentials)),t.settings!==void 0&&(i.settings=JSON.stringify(t.settings)),await n.update(dt).set(i).where(c(dt.tenant_id,e))},async remove(e){await n.delete(dt).where(c(dt.tenant_id,e))}}}function Ci(n){const e={template:n.template,body:n.body,from:n.from,subject:n.subject,syntax:"liquid",includeEmailInRedirect:!!n.include_email_in_redirect,enabled:!!n.enabled};return G({...e,resultUrl:n.result_url??void 0,urlLifetimeInSeconds:n.url_lifetime_in_seconds??void 0})}function d_(n){return{async get(e,t){const i=await n.select().from(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).get();return i?Ci(i):null},async list(e){return(await n.select().from(Ue).where(c(Ue.tenant_id,e)).all()).map(Ci)},async create(e,t){const i=new Date().toISOString();return await n.insert(Ue).values({tenant_id:e,template:t.template,body:t.body,from:t.from,subject:t.subject,syntax:t.syntax,result_url:t.resultUrl??null,url_lifetime_in_seconds:t.urlLifetimeInSeconds??null,include_email_in_redirect:t.includeEmailInRedirect,enabled:t.enabled,created_at:i,updated_at:i}),t},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.body!==void 0&&(o.body=i.body),i.from!==void 0&&(o.from=i.from),i.subject!==void 0&&(o.subject=i.subject),i.syntax!==void 0&&(o.syntax=i.syntax),i.resultUrl!==void 0&&(o.result_url=i.resultUrl),i.urlLifetimeInSeconds!==void 0&&(o.url_lifetime_in_seconds=i.urlLifetimeInSeconds),i.includeEmailInRedirect!==void 0&&(o.include_email_in_redirect=i.includeEmailInRedirect),i.enabled!==void 0&&(o.enabled=i.enabled);const s=await n.update(Ue).set(o).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(s.changes??0)>0},async remove(e,t){const i=await n.delete(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(i.changes??0)>0}}}function c_(n){return{async create(e,t){const i=new Date().toISOString(),o=`af_${Le()}`;return await n.insert(Oe).values({id:o,tenant_id:e,name:t.name,actions:JSON.stringify(t.actions||[]),created_at:i,updated_at:i}),{id:o,name:t.name,actions:t.actions||[],created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(Oe).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).get();if(!i)return null;const{tenant_id:o,actions:s,...l}=i;return G({...l,actions:z(s,[])})},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.actions!==void 0&&(o.actions=JSON.stringify(i.actions)),(await n.update(Oe).set(o).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).returning()).length===0?null:this.get(e,t)},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(Oe).where(c(Oe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=Oe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,actions:b,...A}=m;return G({...A,actions:z(b,[])})});if(!s)return{flows:f};const[p]=await n.select({count:ge()}).from(Oe).where(c(Oe.tenant_id,e));return{flows:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(Oe).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).returning()).length>0}}}const rn=["nodes","start","ending"];function __(n){return{async create(e,t){const i=new Date().toISOString(),o=Le(),s={id:o,tenant_id:e,name:t.name,messages:t.messages,languages:t.languages,translations:t.translations,style:t.style,created_at:i,updated_at:i};for(const l of rn)s[l]=JSON.stringify(t[l]||(l==="nodes"?[]:{}));return await n.insert(ke).values(s),{id:o,...t,created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i,l={...s};for(const d of rn)l[d]=z(s[d]);return G(l)},async update(e,t,i){const o={updated_at:new Date().toISOString()};for(const[l,d]of Object.entries(i))d!==void 0&&(rn.includes(l)?o[l]=JSON.stringify(d):o[l]=d);return(await n.update(ke).set(o).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(ke).where(c(ke.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=ke[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,...b}=m,A={...b};for(const J of rn)A[J]=z(b[J]);return G(A)});if(!s)return{forms:f};const[p]=await n.select({count:ge()}).from(ke).where(c(ke.tenant_id,e));return{forms:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0}}}function js(n){if(n!=null){if(typeof n=="number")return new Date(n).toISOString();if(typeof n=="string"){if(n==="")return;const e=parseFloat(n);return!isNaN(e)&&/^\d+(\.\d+)?$/.test(n)?new Date(e).toISOString():n}}}function ci(n,e=new Date(0).toISOString()){return js(n)??e}function ne(n){if(!n||n==="")return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function nn(n,e,t=[]){const i={};for(const o of e){const s=o.replace(/_ts$/,"");i[s]=ci(n[o])}for(const o of t){const s=o.replace(/_ts$/,"");i[s]=js(n[o])}return i}const u_=Or("0123456789abcdefghijklmnopqrstuvwxyz",17);function p_(){return`hc_${u_()}`}function Di(n){const{created_at_ts:e,updated_at_ts:t,secrets:i,...o}=n,s=nn({created_at_ts:e,updated_at_ts:t},["created_at_ts","updated_at_ts"]);return{...o,...s,secrets:i?JSON.parse(i):void 0}}function f_(n){return{async create(e,t){const i=Date.now(),s={id:p_(),tenant_id:e,code:t.code,secrets:t.secrets?JSON.stringify(t.secrets):null,created_at_ts:i,updated_at_ts:i};return await n.insert(Ke).values(s),Di({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).get();return i?Di(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.code!==void 0&&(o.code=i.code),i.secrets!==void 0&&(o.secrets=JSON.stringify(i.secrets)),(await n.update(Ke).set(o).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0}}}function h_(){const{customAlphabet:n}=require("nanoid");return`h_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function g_(n){if(!(typeof n!="string"||!n))try{const e=JSON.parse(n);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Pn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,metadata:o,...s}=n,l=nn({created_at_ts:t,updated_at_ts:i},["created_at_ts","updated_at_ts"]);return G({...s,enabled:!!s.enabled,synchronous:!!s.synchronous,metadata:g_(o),...l})}function m_(n){return{async create(e,t){const i=Date.now(),s={hook_id:t.hook_id||h_(),tenant_id:e,trigger_id:t.trigger_id,url:t.url,enabled:t.enabled??!0,synchronous:t.synchronous??!1,priority:t.priority,form_id:t.form_id,template_id:t.template_id,code_id:t.code_id,metadata:t.metadata?JSON.stringify(t.metadata):null,created_at_ts:i,updated_at_ts:i};return await n.insert(me).values(s),Pn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).get();return i?Pn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.trigger_id!==void 0&&(o.trigger_id=i.trigger_id),i.url!==void 0&&(o.url=i.url),i.enabled!==void 0&&(o.enabled=i.enabled),i.synchronous!==void 0&&(o.synchronous=i.synchronous),i.priority!==void 0&&(o.priority=i.priority),i.form_id!==void 0&&(o.form_id=i.form_id),i.template_id!==void 0&&(o.template_id=i.template_id),i.code_id!==void 0&&(o.code_id=i.code_id),i.metadata!==void 0&&(o.metadata=i.metadata===null?null:JSON.stringify(i.metadata)),(await n.update(me).set(o).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(me,d,["url","form_id","template_id","code_id"]):void 0,f=u?g(c(me.tenant_id,e),u):c(me.tenant_id,e);let p=n.select().from(me).where(f).$dynamic();const m=l!=null&&l.sort_by?me[l.sort_by]:void 0;m?p=p.orderBy((l==null?void 0:l.sort_order)==="desc"?se(m):he(m)):p=p.orderBy(se(me.priority),he(me.created_at_ts));const b=(await p.offset(i*o).limit(o)).map(Pn);if(!s)return{hooks:b};const[A]=await n.select({count:ge()}).from(me).where(f);return{hooks:b,start:i*o,limit:o,length:Number((A==null?void 0:A.count)??0)}},async remove(e,t){return(await n.delete(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0}}}function y_(){const{customAlphabet:n}=require("nanoid");return`inv_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const _i=["inviter","invitee","app_metadata","user_metadata","roles"];function qn(n){const{tenant_id:e,send_invitation_email:t,...i}=n,o={...i};for(const s of _i)o[s]=z(i[s],s==="roles"?[]:{});return o.send_invitation_email=!!t,G(o)}function v_(n){return{async create(e,t){var u,f;const i=t.id||y_(),o=t.ttl_sec||604800,s=new Date,l=new Date(s.getTime()+o*1e3).toISOString(),d={id:i,tenant_id:e,organization_id:t.organization_id,client_id:t.client_id,connection_id:t.connection_id,invitation_url:t.invitation_url,ticket_id:t.ticket_id,ttl_sec:o,send_invitation_email:t.send_invitation_email!==!1?1:0,created_at:s.toISOString(),expires_at:l};for(const p of _i)t[p]!==void 0&&(d[p]=JSON.stringify(t[p]));try{await n.insert(xe).values(d)}catch(p){throw(u=p==null?void 0:p.message)!=null&&u.includes("UNIQUE constraint failed")||(f=p==null?void 0:p.message)!=null&&f.includes("duplicate key")?new _t(409,{message:"Invite already exists"}):p}return qn({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).get();return i?qn(i):null},async update(e,t,i){const o={};for(const l of _i)i[l]!==void 0&&(o[l]=JSON.stringify(i[l]));return i.connection_id!==void 0&&(o.connection_id=i.connection_id),i.ttl_sec!==void 0&&(o.ttl_sec=i.ttl_sec,o.expires_at=new Date(Date.now()+i.ttl_sec*1e3).toISOString()),(await n.update(xe).set(o).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(xe).where(c(xe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=xe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(qn);if(!s)return{invites:f};const[p]=await n.select({count:ge()}).from(xe).where(c(xe.tenant_id,e));return{invites:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length>0}}}function w_(n){return{async create(e){await n.insert(We).values({...e,created_at:new Date().toDateString()})},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s}=e||{},l=new Date().toISOString();let d=n.select().from(We).where($e(pn(We.revoked_at,l),Ce(We.revoked_at))).$dynamic();if(s!=null&&s.sort_by){const m=We[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(m=>{const{created_at:y,...b}=m;return G(b)});if(!o)return{signingKeys:f};const[p]=await n.select({count:ge()}).from(We).where($e(pn(We.revoked_at,l),Ce(We.revoked_at)));return{signingKeys:f,start:t*i,limit:i,length:yr((p==null?void 0:p.count)??0)}},async update(e,t){return(await n.update(We).set(t).where(c(We.kid,e)).returning()).length>0}}}const ui="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Bn=ui.length;function S_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=ui.charAt(t%Bn)+i,t=Math.floor(t/Bn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=ui.charAt(o[s]%Bn);return i}function Li(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,state_data:s,auth_params:l,...d}=n,u=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o},["created_at_ts","updated_at_ts","expires_at_ts"]),f={};for(const[m,y]of Object.entries(d))y!=null&&(f[m]=y);const p=_s(f,["auth_strategy"]);return G({...p,authParams:typeof l=="string"&&l.length>0?JSON.parse(l):{},...u,state_data:z(s)})}function N_(n){return{async create(e,t){var l,d;const i=Date.now(),s={id:S_(),tenant_id:e,session_id:t.session_id,csrf_token:t.csrf_token,auth_params:JSON.stringify(t.authParams||{}),authorization_url:t.authorization_url?t.authorization_url.substring(0,1024):void 0,ip:t.ip,useragent:t.useragent,auth0Client:t.auth0Client,state:t.state||"pending",state_data:t.state_data?JSON.stringify(t.state_data):void 0,failure_reason:t.failure_reason,user_id:t.user_id,auth_connection:t.auth_connection,auth_strategy_strategy:(l=t.auth_strategy)==null?void 0:l.strategy,auth_strategy_strategy_type:(d=t.auth_strategy)==null?void 0:d.strategy_type,authenticated_at:t.authenticated_at,created_at_ts:i,updated_at_ts:i,expires_at_ts:t.expires_at?ne(t.expires_at):i+1e3*60*60*24};return await n.insert(Y).values(s),Li({...s,tenant_id:e})},async get(e,t){const i=e?g(c(Y.tenant_id,e),c(Y.id,t)):c(Y.id,t),o=await n.select().from(Y).where(i).get();return o?Li(o):null},async update(e,t,i){var s,l,d;const o={updated_at_ts:Date.now()};if(i.session_id!==void 0&&(o.session_id=i.session_id),i.state!==void 0&&(o.state=i.state),i.state_data!==void 0&&(o.state_data=JSON.stringify(i.state_data)),i.failure_reason!==void 0&&(o.failure_reason=i.failure_reason),i.user_id!==void 0&&(o.user_id=i.user_id),i.auth_connection!==void 0&&(o.auth_connection=i.auth_connection),i.auth_strategy!==void 0&&(o.auth_strategy_strategy=(s=i.auth_strategy)==null?void 0:s.strategy,o.auth_strategy_strategy_type=(l=i.auth_strategy)==null?void 0:l.strategy_type),i.authenticated_at!==void 0&&(o.authenticated_at=i.authenticated_at),i.authorization_url!==void 0&&(o.authorization_url=(d=i.authorization_url)==null?void 0:d.substring(0,1024)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.authParams!==void 0){const u=await n.select({auth_params:Y.auth_params}).from(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).get(),f=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};o.auth_params=JSON.stringify({...f,...i.authParams})}return await n.update(Y).set(o).where(g(c(Y.tenant_id,e),c(Y.id,t))),!0},async remove(e,t){return(await n.delete(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).returning()).length>0}}}function $n(n){const{tenant_id:e,isMobile:t,auth0_client:i,details:o,country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p,scope:m,...y}=n,b={...y,isMobile:!!t,auth0_client:z(i),details:z(o),scope:m?m.split(","):void 0};return s&&(b.location_info=G({country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p})),G(b)}function E_(n){return{async create(e,t){var s,l;const o={log_id:t.log_id||Le(),tenant_id:e,type:t.type,date:t.date||new Date().toISOString(),category:t.category,user_id:t.user_id,ip:t.ip,client_id:t.client_id,client_name:t.client_name,user_agent:(s=t.user_agent)==null?void 0:s.substring(0,256),description:(l=t.description)==null?void 0:l.substring(0,256),isMobile:t.isMobile?1:0,user_name:t.user_name,connection:t.connection,connection_id:t.connection_id,audience:t.audience,scope:Array.isArray(t.scope)?t.scope.join(","):t.scope,strategy:t.strategy,strategy_type:t.strategy_type,hostname:t.hostname,session_connection:t.session_connection};return t.auth0_client&&(o.auth0_client=JSON.stringify(t.auth0_client)),t.details&&(o.details=JSON.stringify(t.details).substring(0,8192)),t.location_info&&(o.country_code=t.location_info.country_code,o.city_name=t.location_info.city_name,o.latitude=t.location_info.latitude,o.longitude=t.location_info.longitude,o.time_zone=t.location_info.time_zone,o.continent_code=t.location_info.continent_code),await n.insert(F).values(o),$n({...o,tenant_id:e})},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d,from_date:u,to_date:f}=t||{},p=[c(F.tenant_id,e)];if(d){const Q=Qe(F,d,["user_id","ip","type","client_id"]);Q&&p.push(Q)}typeof u=="number"&&Number.isFinite(u)&&p.push(At(F.date,new Date(Math.floor(u)*1e3).toISOString())),typeof f=="number"&&Number.isFinite(f)&&p.push(Ge(F.date,new Date((Math.floor(f)+1)*1e3).toISOString()));const m=g(...p);let y=n.select().from(F).where(m).$dynamic();if(l!=null&&l.sort_by){const Q=F[l.sort_by];Q&&(y=y.orderBy(l.sort_order==="desc"?se(Q):he(Q)))}else y=y.orderBy(se(F.date));const A=(await y.offset(i*o).limit(o)).map($n);if(!s)return{logs:A};const[J]=await n.select({count:ge()}).from(F).where(m);return{logs:A,start:i*o,limit:o,length:Number((J==null?void 0:J.count)??0)}},async get(e,t){const i=await n.select().from(F).where(g(c(F.tenant_id,e),c(F.log_id,t))).get();return i?$n(i):null}}}const pi="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jn=pi.length;function b_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=pi.charAt(t%jn)+i,t=Math.floor(t/jn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=pi.charAt(o[s]%jn);return i}function ln(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,credential_backed_up:o,confirmed:s,transports:l,...d}=n;return G({...d,confirmed:!!s,credential_backed_up:o!=null?!!o:void 0,transports:z(l),created_at:ci(t),updated_at:ci(i)})}function x_(n){return{async create(e,t){const i=Date.now(),s={id:t.id||b_(),tenant_id:e,user_id:t.user_id,type:t.type,phone_number:t.phone_number,totp_secret:t.totp_secret,credential_id:t.credential_id,public_key:t.public_key,sign_count:t.sign_count,credential_backed_up:t.credential_backed_up!=null?t.credential_backed_up?1:0:null,transports:t.transports?JSON.stringify(t.transports):null,friendly_name:t.friendly_name,confirmed:t.confirmed?1:0,created_at_ts:i,updated_at_ts:i};return await n.insert(ue).values(s),ln({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).get();return i?ln(i):null},async getByCredentialId(e,t){const i=await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.credential_id,t))).get();return i?ln(i):null},async list(e,t){return(await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.user_id,t))).all()).map(ln)},async update(e,t,i){const o={updated_at_ts:Date.now()};i.type!==void 0&&(o.type=i.type),i.phone_number!==void 0&&(o.phone_number=i.phone_number),i.totp_secret!==void 0&&(o.totp_secret=i.totp_secret),i.credential_id!==void 0&&(o.credential_id=i.credential_id),i.public_key!==void 0&&(o.public_key=i.public_key),i.sign_count!==void 0&&(o.sign_count=i.sign_count),i.credential_backed_up!==void 0&&(o.credential_backed_up=i.credential_backed_up?1:0),i.transports!==void 0&&(o.transports=JSON.stringify(i.transports)),i.friendly_name!==void 0&&(o.friendly_name=i.friendly_name),i.confirmed!==void 0&&(o.confirmed=i.confirmed?1:0),await n.update(ue).set(o).where(g(c(ue.tenant_id,e),c(ue.id,t)));const s=await this.get(e,t);if(!s)throw new Error(`Authentication method ${t} not found after update`);return s},async remove(e,t){return(await n.delete(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).returning()).length>0}}}function k_(){const{customAlphabet:n}=require("nanoid");return`org_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Vn(n){const{tenant_id:e,branding:t,metadata:i,enabled_connections:o,token_quota:s,...l}=n;return G({...l,branding:z(t,{}),metadata:z(i,{}),enabled_connections:z(o,[]),token_quota:z(s,{})})}function O_(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),s={id:t.id||k_(),tenant_id:e,name:t.name,display_name:t.display_name,branding:JSON.stringify(t.branding||{}),metadata:JSON.stringify(t.metadata||{}),enabled_connections:JSON.stringify(t.enabled_connections||[]),token_quota:JSON.stringify(t.token_quota||{}),created_at:i,updated_at:i};try{await n.insert(ee).values(s)}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(d=u==null?void 0:u.message)!=null&&d.includes("AlreadyExists")?new _t(409,{message:"Organization already exists"}):u}return Vn({...s,tenant_id:e})},async get(e,t){let i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,t))).get();return i||(i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.name,t))).get()),i?Vn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.display_name!==void 0&&(o.display_name=i.display_name),i.branding!==void 0&&(o.branding=JSON.stringify(i.branding)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.enabled_connections!==void 0&&(o.enabled_connections=JSON.stringify(i.enabled_connections)),i.token_quota!==void 0&&(o.token_quota=JSON.stringify(i.token_quota)),(await n.update(ee).set(o).where(g(c(ee.tenant_id,e),c(ee.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(ee).where(c(ee.tenant_id,e)).$dynamic();if(d&&(u=u.where($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)))),l!=null&&l.sort_by){const b=ee[l.sort_by];b&&(u=u.orderBy(l.sort_order==="desc"?se(b):he(b)))}const p=(await u.offset(i*o).limit(o)).map(Vn);if(!s)return{organizations:p};const m=[c(ee.tenant_id,e)];d&&m.push($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)));const[y]=await n.select({count:ge()}).from(ee).where(g(...m));return{organizations:p,start:i*o,limit:o,length:Number((y==null?void 0:y.count)??0)}},async remove(e,t){return(await n.delete(ee).where(g(c(ee.tenant_id,e),c(ee.id,t))).returning()).length>0}}}function Hn(n){const{tenant_id:e,is_current:t,...i}=n;return{...i,is_current:!!t}}function A_(n){return{async create(e,t){const i=new Date().toISOString(),o=t.id||Le();t.is_current!==!1&&await n.update(oe).set({is_current:0}).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id)));const s={id:o,tenant_id:e,user_id:t.user_id,password:t.password,algorithm:t.algorithm||"bcrypt",is_current:t.is_current!==!1?1:0,created_at:i,updated_at:i};return await n.insert(oe).values(s),Hn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t),c(oe.is_current,1))).get();return i?Hn(i):null},async list(e,t,i){let o=n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t))).orderBy(se(oe.created_at)).$dynamic();return i&&(o=o.limit(i)),(await o).map(Hn)},async update(e,t){const i={updated_at:new Date().toISOString()};return t.password!==void 0&&(i.password=t.password),t.algorithm!==void 0&&(i.algorithm=t.algorithm),t.is_current!==void 0&&(i.is_current=t.is_current?1:0),t.id?await n.update(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.id,t.id))):await n.update(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id),c(oe.is_current,1))),!0}}}function T_(n){return{async get(e){const t=await n.select().from(Ut).where(c(Ut.tenant_id,e)).get();return t?{universal_login_experience:t.universal_login_experience,identifier_first:!!t.identifier_first,password_first:!!t.password_first,webauthn_platform_first_factor:!!t.webauthn_platform_first_factor}:{universal_login_experience:"new",identifier_first:!0,password_first:!1,webauthn_platform_first_factor:!1}},async set(e,t){await n.insert(Ut).values({tenant_id:e,universal_login_experience:t.universal_login_experience,identifier_first:t.identifier_first,password_first:t.password_first,webauthn_platform_first_factor:t.webauthn_platform_first_factor}).onConflictDoUpdate({target:Ut.tenant_id,set:{universal_login_experience:t.universal_login_experience,identifier_first:t.identifier_first,password_first:t.password_first,webauthn_platform_first_factor:t.webauthn_platform_first_factor}})}}}function dn(n){const{tenant_id:e,created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d,device:u,resource_servers:f,rotating:p,...m}=n,y=nn({created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts","rotated_at_ts"]);return G({...m,...y,rotating:!!p,device:z(u,{}),resource_servers:z(f,[])})}function I_(n,e){return Math.max(n??0,e??0)}function C_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),tenant_id:e,client_id:t.client_id,login_id:t.login_id,user_id:t.user_id,device:JSON.stringify(t.device||{}),resource_servers:JSON.stringify(t.resource_servers||[]),rotating:t.rotating??!1,token_lookup:t.token_lookup??null,token_hash:t.token_hash??null,family_id:t.family_id??null,rotated_to:t.rotated_to??null,rotated_at_ts:ne(t.rotated_at),created_at_ts:i,expires_at_ts:ne(t.expires_at),idle_expires_at_ts:ne(t.idle_expires_at),last_exchanged_at_ts:ne(t.last_exchanged_at)};await n.run(O`BEGIN`);try{await n.insert(W).values(o);const s=I_(o.expires_at_ts,o.idle_expires_at_ts);s>0&&o.login_id&&await n.update(Y).set({expires_at_ts:s,updated_at_ts:i}).where(g(c(Y.tenant_id,e),c(Y.id,o.login_id),Ge(Y.expires_at_ts,s))),await n.run(O`COMMIT`)}catch(s){throw await n.run(O`ROLLBACK`),s}return dn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.id,t))).get();return i?dn(i):null},async getByLookup(e,t){const i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.token_lookup,t))).get();return i?dn(i):null},async update(e,t,i,o){const s={};i.device!==void 0&&(s.device=JSON.stringify(i.device)),i.resource_servers!==void 0&&(s.resource_servers=JSON.stringify(i.resource_servers)),i.rotating!==void 0&&(s.rotating=i.rotating),i.token_lookup!==void 0&&(s.token_lookup=i.token_lookup),i.token_hash!==void 0&&(s.token_hash=i.token_hash),i.family_id!==void 0&&(s.family_id=i.family_id),i.rotated_to!==void 0&&(s.rotated_to=i.rotated_to),i.rotated_at!==void 0&&(s.rotated_at_ts=ne(i.rotated_at)),i.expires_at!==void 0&&(s.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(s.idle_expires_at_ts=ne(i.idle_expires_at)),i.last_exchanged_at!==void 0&&(s.last_exchanged_at_ts=ne(i.last_exchanged_at)),i.revoked_at!==void 0&&(s.revoked_at_ts=ne(i.revoked_at));const l=o==null?void 0:o.loginSessionBump,d=l?ne(l.expires_at):null,u=await n.update(W).set(s).where(g(c(W.tenant_id,e),c(W.id,t))).returning();return l!=null&&l.login_id&&d&&d>0&&await n.update(Y).set({expires_at_ts:d,updated_at_ts:Date.now()}).where(g(c(Y.tenant_id,e),c(Y.id,l.login_id),Ge(Y.expires_at_ts,d))).catch(()=>{}),u.length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(W).where(c(W.tenant_id,e)).$dynamic();if(d){const y=Qe(W,d,["user_id"]);y&&(u=u.where(g(c(W.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=W[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(dn);if(!s)return{refresh_tokens:p};const[m]=await n.select({count:ge()}).from(W).where(c(W.tenant_id,e));return{refresh_tokens:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(W).where(g(c(W.tenant_id,e),c(W.id,t))).returning()).length>0},async revokeByLoginSession(e,t,i){return(await n.update(W).set({revoked_at_ts:ne(i)}).where(g(c(W.tenant_id,e),c(W.login_id,t),Ce(W.revoked_at_ts))).returning()).length},async revokeFamily(e,t,i){return(await n.update(W).set({revoked_at_ts:ne(i)}).where(g(c(W.tenant_id,e),c(W.family_id,t),Ce(W.revoked_at_ts))).returning()).length}}}function D_(){const{customAlphabet:n}=require("nanoid");return`api_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const fi=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],Ri=new Set(["id","tenant_id","identifier","name","scopes","signing_alg","signing_secret","token_lifetime","token_lifetime_for_web","skip_consent_for_verifiable_first_party_clients","allow_offline_access","verification_key","options","is_system","metadata","created_at","updated_at"]);function Zn(n){const{tenant_id:e,verification_key:t,scopes:i,options:o,metadata:s,...l}=n,d={...l};d.scopes=z(i,[]),d.options=z(o,{}),d.metadata=z(s),t!==void 0&&(d.verificationKey=t);for(const u of fi)l[u]!==void 0&&l[u]!==null&&(d[u]=!!l[u]);return G(d)}function L_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||D_(),tenant_id:e,identifier:t.identifier,name:t.name,signing_alg:t.signing_alg,signing_secret:t.signing_secret,token_lifetime:t.token_lifetime,token_lifetime_for_web:t.token_lifetime_for_web,scopes:JSON.stringify(t.scopes||[]),options:JSON.stringify(t.options||{}),metadata:t.metadata?JSON.stringify(t.metadata):void 0,verification_key:t.verificationKey||t.verification_key,created_at:i,updated_at:i};for(const l of fi)t[l]!==void 0&&(s[l]=t[l]?1:0);return s.is_system===void 0&&(s.is_system=0),await n.insert(te).values(s),Zn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(te).where(g(c(te.tenant_id,e),c(te.id,t))).get();return i?Zn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.name!==void 0&&(o.name=i.name),i.identifier!==void 0&&(o.identifier=i.identifier),i.signing_alg!==void 0&&(o.signing_alg=i.signing_alg),i.signing_secret!==void 0&&(o.signing_secret=i.signing_secret),i.token_lifetime!==void 0&&(o.token_lifetime=i.token_lifetime),i.token_lifetime_for_web!==void 0&&(o.token_lifetime_for_web=i.token_lifetime_for_web),i.scopes!==void 0&&(o.scopes=JSON.stringify(i.scopes)),i.options!==void 0&&(o.options=O`json_patch(COALESCE(${te.options}, '{}'), ${JSON.stringify(i.options)})`),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.verificationKey!==void 0&&(o.verification_key=i.verificationKey);for(const l of fi)i[l]!==void 0&&(o[l]=i[l]?1:0);return(await n.update(te).set(o).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=Math.max(0,Math.floor(Number(i)||0)),f=Math.min(Math.max(1,Math.floor(Number(o)||50)),500),p=[c(te.tenant_id,e)];if(d){const J=d.match(/^([^:]+):(.+)$/);if(J){const[,Q,ie]=J,Pe=Q==null?void 0:Q.startsWith("-"),Se=Pe?Q==null?void 0:Q.substring(1):Q;if(Se&&Ri.has(Se)&&!Pe){const be=te[Se];p.push(xt(be,`%${ie}%`))}}}let m=n.select().from(te).where(g(...p)).$dynamic();if(l!=null&&l.sort_by&&Ri.has(l.sort_by)){const J=te[l.sort_by];m=m.orderBy(l.sort_order==="desc"?se(J):he(J))}const b=(await m.offset(u*f).limit(f)).map(Zn);if(!s)return{resource_servers:b};const[A]=await n.select({count:ge()}).from(te).where(g(...p));return{resource_servers:b,start:u*f,limit:f,length:Number((A==null?void 0:A.count)??0)}},async remove(e,t){return(await n.delete(te).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0}}}function R_(n){return{async assign(e,t,i){const o=new Date().toISOString();return await n.insert(Re).values(i.map(s=>({tenant_id:e,role_id:t,resource_server_identifier:s.resource_server_identifier,permission_name:s.permission_name,created_at:o}))).onConflictDoNothing(),!0},async list(e,t,i){const o=await n.select({resource_server_identifier:Re.resource_server_identifier,permission_name:Re.permission_name,created_at:Re.created_at}).from(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t))).all(),s=[...new Set(o.map(d=>d.resource_server_identifier))],l=new Map;if(s.length>0){const d=await n.select({identifier:te.identifier,name:te.name}).from(te).where(g(c(te.tenant_id,e),De(te.identifier,s))).all();for(const u of d)l.set(u.identifier,u.name)}return o.map(d=>({...d,resource_server_name:l.get(d.resource_server_identifier)||d.resource_server_identifier}))},async remove(e,t,i){const o=i.map(l=>g(c(Re.resource_server_identifier,l.resource_server_identifier),c(Re.permission_name,l.permission_name)));return(await n.delete(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t),$e(...o))).returning()).length>0}}}function U_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(qe).values({tenant_id:e,user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.includes("UNIQUE constraint")||(l=d==null?void 0:d.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw d}return!0},async list(e,t,i,o){let s=[c(qe.tenant_id,e),c(qe.user_id,t)];o&&s.push(c(qe.organization_id,o));const l=await n.select().from(qe).where(g(...s)).all();return await Promise.all(l.map(async u=>{const f=await n.select({name:te.name}).from(te).where(g(c(te.tenant_id,e),c(te.identifier,u.resource_server_identifier))).get();return{resource_server_identifier:u.resource_server_identifier,permission_name:u.permission_name,resource_server_name:(f==null?void 0:f.name)||u.resource_server_identifier,organization_id:u.organization_id===""?void 0:u.organization_id}}))},async remove(e,t,i,o){return(await n.delete(qe).where(g(c(qe.tenant_id,e),c(qe.user_id,t),c(qe.resource_server_identifier,i.resource_server_identifier),c(qe.permission_name,i.permission_name),c(qe.organization_id,o||""))).returning()).length>0}}}function Kn(n){const{tenant_id:e,is_system:t,metadata:i,...o}=n;return G({...o,is_system:t?!0:void 0,metadata:z(i)})}function F_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),tenant_id:e,name:t.name,description:t.description,is_system:t.is_system?1:0,metadata:t.metadata?JSON.stringify(t.metadata):void 0,created_at:i,updated_at:i};return await n.insert(_e).values(s),Kn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(_e).where(g(c(_e.tenant_id,e),c(_e.id,t))).get();return i?Kn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.description!==void 0&&(o.description=i.description),i.is_system!==void 0&&(o.is_system=i.is_system?1:0),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),(await n.update(_e).set(o).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(_e,d,["name"]):void 0,f=u?g(c(_e.tenant_id,e),u):c(_e.tenant_id,e);let p=n.select().from(_e).where(f).$dynamic();if(l!=null&&l.sort_by){const A=_e[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}const y=(await p.offset(i*o).limit(o)).map(Kn);if(!s)return{roles:y};const[b]=await n.select({count:ge()}).from(_e).where(f);return{roles:y,start:i*o,limit:o,length:Number((b==null?void 0:b.count)??0)}},async remove(e,t){return(await n.delete(_e).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0}}}const z_=["created_at_ts","updated_at_ts"],M_=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function Wn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f,device:p,clients:m,...y}=n,b=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f},[...z_],[...M_]);return G({...y,...b,device:z(p,{}),clients:z(m,[])})}function P_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),tenant_id:e,user_id:t.user_id,login_session_id:t.login_session_id,device:JSON.stringify(t.device||{}),clients:JSON.stringify(t.clients||[]),created_at_ts:i,updated_at_ts:i,expires_at_ts:ne(t.expires_at),idle_expires_at_ts:ne(t.idle_expires_at),authenticated_at_ts:t.authenticated_at?ne(t.authenticated_at):i,last_interaction_at_ts:t.last_interaction_at?ne(t.last_interaction_at):i,used_at_ts:ne(t.used_at),revoked_at_ts:ne(t.revoked_at)};return await n.insert(ae).values(o),Wn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).get();return i?Wn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.login_session_id!==void 0&&(o.login_session_id=i.login_session_id),i.device!==void 0&&(o.device=JSON.stringify(i.device)),i.clients!==void 0&&(o.clients=JSON.stringify(i.clients)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(o.idle_expires_at_ts=ne(i.idle_expires_at)),i.authenticated_at!==void 0&&(o.authenticated_at_ts=ne(i.authenticated_at)),i.last_interaction_at!==void 0&&(o.last_interaction_at_ts=ne(i.last_interaction_at)),i.used_at!==void 0&&(o.used_at_ts=ne(i.used_at)),i.revoked_at!==void 0&&(o.revoked_at_ts=ne(i.revoked_at)),(await n.update(ae).set(o).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(ae,d,["user_id"]):void 0,f=u?g(c(ae.tenant_id,e),u):c(ae.tenant_id,e);let p=n.select().from(ae).where(f).$dynamic();if(l!=null&&l.sort_by){const A=ae[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}const y=(await p.offset(i*o).limit(o)).map(Wn);if(!s)return{sessions:y};const[b]=await n.select({count:ge()}).from(ae).where(f);return{sessions:y,start:i*o,limit:o,length:Number((b==null?void 0:b.count)??0)}},async remove(e,t){return(await n.delete(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0}}}const Vs=["session_cookie","enabled_locales","error_page","flags","sandbox_versions_available","change_password","guardian_mfa_page","sessions","oidc_logout","device_flow","default_token_quota","allowed_logout_urls","acr_values_supported","mtls","mfa"],Hs=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function Ui(n){const e={...n};for(const t of Vs)typeof e[t]=="string"&&(e[t]=z(e[t]));for(const t of Hs)e[t]!==void 0&&e[t]!==null&&(e[t]=e[t]===1);return G(e)}function Fi(n){const e={...n};gr(n,Vs,e);for(const t of Hs)n[t]!==void 0&&(e[t]=n[t]?1:0);return cs(e)}function q_(n){return{async create(e){var o,s;const t={id:e.id||Le(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...e},i=Fi(t);try{await n.insert(B).values(i)}catch(l){throw(o=l==null?void 0:l.message)!=null&&o.includes("UNIQUE constraint failed")||(s=l==null?void 0:l.message)!=null&&s.includes("duplicate key")||(l==null?void 0:l.code)==="SQLITE_CONSTRAINT"?new _t(409,{message:`Tenant with ID '${t.id}' already exists`}):l}return t},async get(e){const t=await n.select().from(B).where(c(B.id,e)).get();return t?Ui(t):null},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s,q:l}=e||{};let d=n.select().from(B).$dynamic();if(l){const m=Qe(B,l,["friendly_name"]);m&&(d=d.where(m))}if(s!=null&&s.sort_by){const m=B[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(Ui);if(!o)return{tenants:f};const[p]=await n.select({count:ge()}).from(B);return{tenants:f,start:t*i,limit:i,length:Number((p==null?void 0:p.count)??0)}},async update(e,t){const i=Fi({...t,id:e,updated_at:new Date().toISOString()});await n.update(B).set(i).where(c(B.id,e))},async remove(e){return(await n.delete(B).where(c(B.id,e)).returning()).length>0}}}const B_=["colors","borders","fonts","page_background","widget"];function zi(n){const{tenant_id:e,...t}=n,i=_s(t,B_);return i.borders&&(i.borders.show_widget_shadow=!!i.borders.show_widget_shadow),i.fonts&&(i.fonts.links_bold=!!i.fonts.links_bold,i.fonts.subtitle_bold=!!i.fonts.subtitle_bold,i.fonts.title_bold=!!i.fonts.title_bold),G(i)}function $_(n){return{async create(e,t,i){const o=new Date().toISOString(),s=i||Le(),d={...Yn(t),tenant_id:e,themeId:s,created_at:o,updated_at:o};return await n.insert(Ze).values(d),zi({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(Ze).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))).get();return i?zi(i):null},async update(e,t,i){const o=Yn(i);return o.updated_at=new Date().toISOString(),await n.update(Ze).set(o).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))),!0},async remove(e,t){return(await n.delete(Ze).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))).returning()).length>0}}}function j_(n){return{async get(e){const t=await n.select({body:lt.body}).from(lt).where(c(lt.tenant_id,e)).get();return t?{body:t.body}:null},async set(e,t){const i=Date.now();await n.insert(lt).values({tenant_id:e,body:t.body,created_at_ts:i,updated_at_ts:i}).onConflictDoUpdate({target:lt.tenant_id,set:{body:t.body,updated_at_ts:i}})},async delete(e){await n.delete(lt).where(c(lt.tenant_id,e))}}}function Mi(n,e){const t={connection:n.connection,provider:n.provider,user_id:n.user_id,isSocial:!!n.is_social};return e?t.isPrimary=!0:t.profileData={email:n.email,email_verified:!!n.email_verified,...typeof n.profileData=="string"?z(n.profileData,{}):{}},t}function Gn(n,e=[]){const{tenant_id:t,app_metadata:i,user_metadata:o,address:s,email_verified:l,phone_verified:d,is_social:u,linked_to:f,profileData:p,...m}=n,y=Mi(n,!0),b=e.map(A=>Mi(A,!1));return G({...m,email:n.email||"",email_verified:!!l,phone_verified:d!=null?!!d:void 0,is_social:!!u,app_metadata:z(i,{}),user_metadata:z(o,{}),address:z(s),identities:[y,...b]})}function V_(n){const e=async(t,i)=>{var d,u;const o=new Date().toISOString(),s={user_id:i.user_id,tenant_id:t,email:i.email,given_name:i.given_name,family_name:i.family_name,nickname:i.nickname,name:i.name,picture:i.picture,tags:i.tags,phone_number:i.phone_number,phone_verified:i.phone_verified??!1,username:i.username,linked_to:i.linked_to,last_ip:i.last_ip,login_count:i.login_count??0,last_login:i.last_login,provider:i.provider,connection:i.connection,email_verified:i.email_verified??!1,is_social:i.is_social??!1,app_metadata:JSON.stringify(i.app_metadata||{}),user_metadata:JSON.stringify(i.user_metadata||{}),address:i.address?JSON.stringify(i.address):void 0,profileData:i.profileData?JSON.stringify(i.profileData):void 0,locale:i.locale,middle_name:i.middle_name,preferred_username:i.preferred_username,profile:i.profile,website:i.website,gender:i.gender,birthdate:i.birthdate,zoneinfo:i.zoneinfo,created_at:i.created_at||o,updated_at:i.updated_at||o},l=i.password?Le():void 0;try{if(i.password&&l){await n.run(O`BEGIN`);try{await n.insert(H).values(s),await n.insert(oe).values({id:l,tenant_id:t,user_id:i.user_id,password:i.password.hash||i.password,algorithm:i.password.algorithm||"bcrypt",is_current:1,created_at:o,updated_at:o}),await n.run(O`COMMIT`)}catch(f){throw await n.run(O`ROLLBACK`),f}}else await n.insert(H).values(s)}catch(f){throw(d=f==null?void 0:f.message)!=null&&d.includes("UNIQUE constraint")||(u=f==null?void 0:f.message)!=null&&u.includes("AlreadyExists")?new _t(409,{message:"User already exists"}):(console.error("User upsert failed:",f==null?void 0:f.code,f==null?void 0:f.message),new _t(500,{message:"Internal server error"}))}return Gn(s)};return{create:e,rawCreate:e,async get(t,i){const o=await n.select().from(H).where(g(c(H.tenant_id,t),c(H.user_id,i))).get();if(!o)return null;const s=await n.select().from(H).where(g(c(H.tenant_id,t),c(H.linked_to,i))).all();return Gn(o,s)},async update(t,i,o){const s={updated_at:new Date().toISOString()},l=["email","given_name","family_name","nickname","name","picture","tags","phone_number","username","linked_to","last_ip","login_count","last_login","provider","connection","locale","middle_name","preferred_username","profile","website","gender","birthdate","zoneinfo"];for(const u of l)o[u]!==void 0&&(s[u]=o[u]);return o.email_verified!==void 0&&(s.email_verified=o.email_verified),o.phone_verified!==void 0&&(s.phone_verified=o.phone_verified),o.is_social!==void 0&&(s.is_social=o.is_social),o.app_metadata!==void 0&&(s.app_metadata=JSON.stringify(o.app_metadata)),o.user_metadata!==void 0&&(s.user_metadata=JSON.stringify(o.user_metadata)),o.address!==void 0&&(s.address=JSON.stringify(o.address)),o.profileData!==void 0&&(s.profileData=JSON.stringify(o.profileData)),(await n.update(H).set(s).where(g(c(H.tenant_id,t),c(H.user_id,i))).returning()).length>0},async list(t,i){const{page:o=0,per_page:s=50,include_totals:l=!1,sort:d,q:u}=i||{},f=[c(H.tenant_id,t),Ce(H.linked_to)];if(u){const ie=Qe(H,u,["email","name","nickname","username"]);ie&&f.push(ie)}const p=g(...f);let m=n.select().from(H).where(p).$dynamic();if(d!=null&&d.sort_by){const ie=H[d.sort_by];ie&&(m=m.orderBy(d.sort_order==="desc"?se(ie):he(ie)))}const y=await m.offset(o*s).limit(s),b=y.map(ie=>ie.user_id);let A=[];b.length>0&&(A=await n.select().from(H).where(g(c(H.tenant_id,t),De(H.linked_to,b))));const J=y.map(ie=>{const Pe=A.filter(Se=>Se.linked_to===ie.user_id);return Gn(ie,Pe)});if(!l)return{users:J};const[Q]=await n.select({count:ge()}).from(H).where(p);return{users:J,start:o*s,limit:s,length:Number((Q==null?void 0:Q.count)??0)}},async remove(t,i){await n.run(O`BEGIN`);try{const o=await n.select({user_id:H.user_id}).from(H).where(g(c(H.tenant_id,t),c(H.linked_to,i))),s=[i,...o.map(d=>d.user_id)];await n.delete(ue).where(g(c(ue.tenant_id,t),De(ue.user_id,s))),await n.delete(oe).where(g(c(oe.tenant_id,t),De(oe.user_id,s))),await n.delete(H).where(g(c(H.tenant_id,t),c(H.linked_to,i)));const l=await n.delete(H).where(g(c(H.tenant_id,t),c(H.user_id,i))).returning();return await n.run(O`COMMIT`),l.length>0}catch(o){throw await n.run(O`ROLLBACK`),o}},async unlink(t,i,o,s){const l=`${o}|${s}`;return(await n.update(H).set({linked_to:null}).where(g(c(H.tenant_id,t),c(H.user_id,l),c(H.linked_to,i))).returning()).length>0}}}function H_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(Be).values({tenant_id:e,user_id:t,role_id:i,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.includes("UNIQUE constraint")||(l=d==null?void 0:d.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw d}return!0},async list(e,t,i,o){let s=[c(Be.tenant_id,e),c(Be.user_id,t)];o&&s.push(c(Be.organization_id,o));const l=await n.select({role_id:Be.role_id}).from(Be).where(g(...s)).all();return l.length===0?[]:(await Promise.all(l.map(async u=>{const f=await n.select().from(_e).where(g(c(_e.tenant_id,e),c(_e.id,u.role_id))).get();if(!f)return null;const{tenant_id:p,is_system:m,metadata:y,...b}=f;return G({...b,is_system:m?!0:void 0,metadata:z(y)})}))).filter(Boolean)},async remove(e,t,i,o){return(await n.delete(Be).where(g(c(Be.tenant_id,e),c(Be.user_id,t),c(Be.role_id,i),c(Be.organization_id,o||""))).returning()).length>0}}}function Z_(n){return{async create(e,t){var u,f;const i=new Date().toISOString(),s={id:t.id||Le(),tenant_id:e,user_id:t.user_id,organization_id:t.organization_id,created_at:i,updated_at:i};try{await n.insert(le).values(s)}catch(p){throw(u=p==null?void 0:p.message)!=null&&u.includes("UNIQUE constraint")||(f=p==null?void 0:p.message)!=null&&f.includes("duplicate key")?new _t(409,{message:"User organization already exists"}):p}const{tenant_id:l,...d}=s;return d},async get(e,t){const i=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i;return s},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.organization_id!==void 0&&(o.organization_id=i.organization_id),(await n.update(le).set(o).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,q:l}=t||{},d=c(le.tenant_id,e);let u=d;if(l){const y=Qe(le,l,["user_id","organization_id"]);y&&(u=g(d,y))}const p=(await n.select().from(le).where(u).offset(i*o).limit(o)).map(y=>{const{tenant_id:b,...A}=y;return A});if(!s)return{userOrganizations:p};const[m]=await n.select({count:ge()}).from(le).where(u);return{userOrganizations:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async listUserOrganizations(e,t,i){const{page:o=0,per_page:s=50,include_totals:l=!1}=i||{},d=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.user_id,t))).offset(o*s).limit(s).all(),f=(await Promise.all(d.map(async m=>{const y=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,m.organization_id))).get();if(!y)return null;const{tenant_id:b,branding:A,metadata:J,enabled_connections:Q,token_quota:ie,...Pe}=y;return G({...Pe,branding:z(A,{}),metadata:z(J,{}),enabled_connections:z(Q,[]),token_quota:z(ie,{})})}))).filter(Boolean);if(!l)return{organizations:f};const[p]=await n.select({count:ge()}).from(le).where(g(c(le.tenant_id,e),c(le.user_id,t)));return{organizations:f,start:o*s,limit:s,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(le).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0}}}const Pi=["s"],K_=["pwd_leak"];function qi(n){return/^\d{8}$/.test(n)?`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)}`:n}function W_(n){return{async getDaily(e,t){const i=new Date,o=t!=null&&t.from?qi(t.from):new Date(i.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],s=t!=null&&t.to?qi(t.to):i.toISOString().split("T")[0];return(await n.select({date:O`substr(${F.date}, 1, 10)`.as("date"),logins:O`SUM(CASE WHEN ${F.type} IN (${O.join(Pi.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:O`SUM(CASE WHEN ${F.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:O`SUM(CASE WHEN ${F.type} IN (${O.join(K_.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from(F).where(g(c(F.tenant_id,e),At(F.date,o),yt(F.date,`${s}T23:59:59.999Z`))).groupBy(O`substr(${F.date}, 1, 10)`).orderBy(O`substr(${F.date}, 1, 10)`).all()).map(d=>({date:d.date,logins:Number(d.logins)||0,signups:Number(d.signups)||0,leaked_passwords:Number(d.leaked_passwords)||0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}))},async getActiveUsers(e){const t=new Date(Date.now()-2592e6).toISOString(),[i]=await n.select({count:O`COUNT(DISTINCT ${F.user_id})`.as("count")}).from(F).where(g(c(F.tenant_id,e),At(F.date,t),O`${F.type} IN (${O.join(Pi.map(o=>O`${o}`),O`, `)})`));return Number(i==null?void 0:i.count)||0}}}const G_={"active-users":["s","seacft"],logins:["s","f","fp"],signups:["ss","fs"],"refresh-tokens":["seacft","fertft"],sessions:["slo"]},J_={"active-users":{alias:"active_users",type:"UInt64",agg:"uniq"},logins:{alias:"logins",type:"UInt64",agg:"count"},signups:{alias:"signups",type:"UInt64",agg:"count"},"refresh-tokens":{alias:"refresh_tokens",type:"UInt64",agg:"count"},sessions:{alias:"sessions",type:"UInt64",agg:"count"}};function Q_(n){switch(n){case"hour":return O`substr(${F.date}, 1, 13)`;case"month":return O`substr(${F.date}, 1, 7)`;case"day":return O`substr(${F.date}, 1, 10)`;case"week":return O`date(substr(${F.date}, 1, 10), '-' || ((cast(strftime('%w', substr(${F.date}, 1, 10)) as integer) + 6) % 7) || ' days')`;default:throw new Error(`Unsupported interval '${n}' for SQL analytics adapter`)}}function Jn(n){return`"${n.replace(/"/g,'""')}"`}function X_(n){switch(n){case"connection":return F.connection;case"client_id":return F.client_id;case"user_type":return F.strategy_type;case"event":return F.type;case"time":throw new Error("time dimension handled separately")}}function Y_(n){return{async query(e,t,i){var J,Q,ie,Pe;const o=Date.now(),s=G_[t],l=J_[t],d=[c(F.tenant_id,e),At(F.date,i.from),Ge(F.date,i.to),De(F.type,s)];(J=i.filters.connection)!=null&&J.length&&d.push(De(F.connection,i.filters.connection)),(Q=i.filters.client_id)!=null&&Q.length&&d.push(De(F.client_id,i.filters.client_id)),(ie=i.filters.user_type)!=null&&ie.length&&d.push(De(F.strategy_type,i.filters.user_type)),(Pe=i.filters.user_id)!=null&&Pe.length&&d.push(De(F.user_id,i.filters.user_id));const u={},f=[],p=[];for(const Se of i.group_by)if(Se==="time"){const be=Q_(i.interval);u.time=be,f.push(be),p.push({name:"time",type:i.interval==="hour"?"DateTime":"Date"})}else{const be=X_(Se);u[Se]=be,f.push(be),p.push({name:Se,type:"String"})}u[l.alias]=l.agg==="uniq"?O`COUNT(DISTINCT ${F.user_id})`:O`COUNT(*)`,p.push({name:l.alias,type:l.type});let m=n.select(u).from(F).where(g(...d));f.length>0&&(m=m.groupBy(...f));const y=new Set([...Object.keys(u)]);if(i.order_by){const Se=i.order_by.startsWith("-"),be=Se?i.order_by.slice(1):i.order_by;if(!y.has(be))throw new Error(`Invalid order_by column '${be}' for analytics query`);const it=Jn(be);m=m.orderBy(O.raw(`${it} ${Se?"DESC":"ASC"}`))}else i.group_by[0]==="time"?m=m.orderBy(O.raw(`${Jn("time")} ASC`)):m=m.orderBy(O.raw(`${Jn(l.alias)} DESC`));m=m.limit(i.limit).offset(i.offset);const A=(await m.all()).map(Se=>{const be={};for(const it of p){const rt=Se[it.name];be[it.name]=it.type==="UInt64"?Number(rt)||0:rt??""}return be});return{meta:p,data:A,rows:A.length,rows_before_limit_at_least:A.length,statistics:{elapsed:(Date.now()-o)/1e3}}}}}function Bi(n){return{...n,payload:z(n.payload,{})}}function eu(n){return{async create(e,t){const i=Le(),o=new Date().toISOString();return await n.insert(P).values({id:i,tenant_id:e,event_type:t.event_type,log_type:t.log_type,aggregate_type:t.aggregate_type,aggregate_id:t.aggregate_id,payload:JSON.stringify({...t,id:i}),created_at:o,processed_at:null,retry_count:0,next_retry_at:null,error:null,claimed_by:null,claim_expires_at:null}),i},async getByIds(e){return e.length===0?[]:(await n.select().from(P).where(De(P.id,e)).all()).map(Bi)},async getUnprocessed(e){const t=new Date().toISOString();return(await n.select().from(P).where(g(Ce(P.processed_at),$e(Ce(P.next_retry_at),yt(P.next_retry_at,t)),$e(Ce(P.claimed_by),yt(P.claim_expires_at,t)))).orderBy(P.created_at,P.id).limit(e).all()).map(Bi)},async claimEvents(e,t,i){if(e.length===0)return[];const o=new Date().toISOString(),s=new Date(Date.now()+i).toISOString();return await n.update(P).set({claimed_by:t,claim_expires_at:s}).where(g(De(P.id,e),Ce(P.processed_at),$e(Ce(P.claimed_by),yt(P.claim_expires_at,o)))),(await n.select({id:P.id}).from(P).where(g(De(P.id,e),c(P.claimed_by,t))).all()).map(d=>d.id)},async markProcessed(e){e.length!==0&&await n.update(P).set({processed_at:new Date().toISOString()}).where(De(P.id,e))},async markRetry(e,t,i){await n.update(P).set({error:t,next_retry_at:i,retry_count:O`${P.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(c(P.id,e))},async cleanup(e){return(await n.delete(P).where(g(O`${P.processed_at} IS NOT NULL`,yt(P.processed_at,e))).returning()).length},async deadLetter(e,t){const i=new Date().toISOString();await n.update(P).set({processed_at:i,dead_lettered_at:i,final_error:t}).where(c(P.id,e))},async listFailed(e,t={}){const{page:i=0,per_page:o=50,include_totals:s=!1}=t,d=(await n.select().from(P).where(g(c(P.tenant_id,e),cn(P.dead_lettered_at))).orderBy(se(P.dead_lettered_at),he(P.id)).offset(i*o).limit(o).all()).map(f=>({...z(f.payload,{}),id:f.id,created_at:f.created_at,processed_at:f.processed_at,retry_count:f.retry_count,next_retry_at:f.next_retry_at,error:f.error,dead_lettered_at:f.dead_lettered_at,final_error:f.final_error}));let u=d.length;if(s){const[f]=await n.select({total:ge()}).from(P).where(g(c(P.tenant_id,e),cn(P.dead_lettered_at)));u=Number((f==null?void 0:f.total)??d.length)}return{events:d,start:i*o,limit:o,length:u}},async replay(e,t){return(await n.update(P).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(g(c(P.id,e),c(P.tenant_id,t),cn(P.dead_lettered_at))).returning()).length>0}}}const tu=7*24*60*60*1e3;function nu(n){return async e=>{const t=Date.now()-tu;try{let i=[$e(Ge(W.expires_at_ts,t),Ge(W.idle_expires_at_ts,t))];e!=null&&e.tenant_id&&i.push(c(W.tenant_id,e.tenant_id)),await n.delete(W).where(g(...i)),i=[$e(Ge(ae.expires_at_ts,t),Ge(ae.idle_expires_at_ts,t))],e!=null&&e.tenant_id&&i.push(c(ae.tenant_id,e.tenant_id)),e!=null&&e.user_id&&i.push(c(ae.user_id,e.user_id)),await n.delete(ae).where(g(...i)),i=[Ge(Y.expires_at_ts,t)],e!=null&&e.tenant_id&&i.push(c(Y.tenant_id,e.tenant_id)),await n.delete(Y).where(g(...i))}catch(i){console.error("Session cleanup error:",i)}}}function iu(n,e={useTransactions:!0}){const t={actions:tr(),actionExecutions:nr(),actionVersions:ir(),branding:wr(n),clients:Sr(n),clientConnections:Er(n),clientGrants:Ar(n),clientRegistrationTokens:n_(n),codes:i_(n),connections:a_(n),customDomains:s_(n),customText:r_(n),emailProviders:l_(n),emailTemplates:d_(n),flows:c_(n),forms:__(n),hookCode:f_(n),hooks:m_(n),invites:v_(n),keys:w_(n),loginSessions:N_(n),logs:E_(n),authenticationMethods:x_(n),organizations:O_(n),passwords:A_(n),promptSettings:T_(n),refreshTokens:C_(n),resourceServers:L_(n),rolePermissions:R_(n),userPermissions:U_(n),roles:F_(n),sessions:P_(n),sessionCleanup:nu(n),tenants:q_(n),themes:$_(n),universalLoginTemplates:j_(n),users:V_(n),userRoles:H_(n),userOrganizations:Z_(n),stats:W_(n),analytics:Y_(n),outbox:eu(n),async transaction(i){if(e.useTransactions===!1)return i(t);await n.run(O`BEGIN`);try{const o=await i(t);return await n.run(O`COMMIT`),o}catch(o){throw await n.run(O`ROLLBACK`),o}}};return t}exports.default=iu;exports.sqlite=hr;
|
|
13
|
+
WHERE tenant_id = ${t} AND client_id = ${i}`);return(o.changes??((s=o.meta)==null?void 0:s.changes)??0)>0}}}let Mc="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",jc=e=>crypto.getRandomValues(new Uint8Array(e)),qc=(e,t,n)=>{let i=256-256%e.length;if(i===256){let a=e.length-1;return(s=t)=>{if(!s)return"";let c="";for(;;){let u=n(s),p=s;for(;p--;)if(c+=e[u[p]&a],c.length>=s)return c}}}let o=Math.ceil(1.6*256*t/i);return(a=t)=>{if(!a)return"";let s="";for(;;){let c=n(o),u=o;for(;u--;)if(c[u]<i&&(s+=e[c[u]%e.length],s.length>=a))return s}}},Bc=(e,t=21)=>qc(e,t|0,jc),Le=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=Mc[n[e]&63];return t};function En(e){const{tenant_id:t,scope:n,authorization_details_types:i,allow_any_organization:o,is_system:a,...s}=e;return K({...s,scope:R(n,[]),authorization_details_types:R(i,[]),allow_any_organization:!!o,is_system:!!a})}function Jc(e){return{async create(t,n){const i=new Date().toISOString(),a={id:n.id||Le(),tenant_id:t,client_id:n.client_id,audience:n.audience,scope:JSON.stringify(n.scope||[]),organization_usage:n.organization_usage,allow_any_organization:n.allow_any_organization?1:0,is_system:n.is_system?1:0,subject_type:n.subject_type,authorization_details_types:JSON.stringify(n.authorization_details_types||[]),created_at:i,updated_at:i};return await e.insert(Se).values(a),En({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(Se).where(w(_(Se.tenant_id,t),_(Se.id,n))).get();return i?En(i):null},async update(t,n,i){const{scope:o,authorization_details_types:a,allow_any_organization:s,is_system:c,...u}=i,p={...u,updated_at:new Date().toISOString()};return o!==void 0&&(p.scope=JSON.stringify(o)),a!==void 0&&(p.authorization_details_types=JSON.stringify(a)),s!==void 0&&(p.allow_any_organization=s?1:0),c!==void 0&&(p.is_system=c?1:0),(await e.update(Se).set(p).where(w(_(Se.tenant_id,t),_(Se.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{},u=c?Ye(Se,c,["client_id","audience"]):void 0,p=u?w(_(Se.tenant_id,t),u):_(Se.tenant_id,t);let d=e.select().from(Se).where(p).$dynamic();if(s!=null&&s.sort_by){const S=Se[s.sort_by];S&&(d=d.orderBy(s.sort_order==="desc"?le(S):me(S)))}else d=d.orderBy(me(Se.created_at));const m=(await d.offset(i*o).limit(o)).map(En);if(!a)return{client_grants:m};const[y]=await e.select({count:ye()}).from(Se).where(p);return{client_grants:m,start:i*o,limit:o,length:Number((y==null?void 0:y.count)??0)}},async remove(t,n){return(await e.delete(Se).where(w(_(Se.tenant_id,t),_(Se.id,n))).returning()).length>0}}}function kt(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]]);return n}const Kc={ZodAny:"any",ZodArray:"array",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDefault:"default",ZodPrefault:"prefault",ZodTransform:"transform",ZodEnum:"enum",ZodIntersection:"intersection",ZodLazy:"lazy",ZodLiteral:"literal",ZodNever:"never",ZodNull:"null",ZodNullable:"nullable",ZodNumber:"number",ZodNonOptional:"nonoptional",ZodObject:"object",ZodOptional:"optional",ZodPipe:"pipe",ZodReadonly:"readonly",ZodRecord:"record",ZodString:"string",ZodTuple:"tuple",ZodType:"type",ZodUnion:"union",ZodDiscriminatedUnion:"union",ZodUnknown:"unknown",ZodVoid:"void",ZodDate:"date",ZodTemplateLiteral:"template_literal"};function tt(e,t){return(Array.isArray(t)?t:[t]).some(i=>{var o;const a=((o=e==null?void 0:e.def)===null||o===void 0?void 0:o.type)===Kc[i];return i==="ZodDiscriminatedUnion"?a&&"discriminator"in e.def:a})}function vt(e){return e&&"def"in e}let Gc=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const i=n[0];if(this._map.set(t,i),i&&typeof i=="object"&&"id"in i){if(this._idmap.has(i.id))throw new Error(`ID ${i.id} already exists in the registry`);this._idmap.set(i.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const i={...this.get(n)??{}};return delete i.id,{...i,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Vc(){return new Gc}function On(e){return e===void 0}function Hc(e,t){const n={};return Object.entries(e).forEach(([i,o])=>{t.some(a=>a===i)||(n[i]=o)}),n}function In(e,t){const n={};return Object.entries(e).forEach(([i,o])=>{t(o,i)||(n[i]=o)}),n}const Zi=Vc();class at{static collectMetadata(t,n){const i=this.getMetadataFromRegistry(t),o=Object.assign(Object.assign({},i==null?void 0:i._internal),n==null?void 0:n._internal),a=Object.assign(Object.assign({},i==null?void 0:i.param),n==null?void 0:n.param),s=Object.assign(Object.assign(Object.assign(Object.assign({},Object.keys(o).length>0?{_internal:o}:{}),i),n),Object.keys(a).length>0?{param:a}:{});if(tt(t,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&vt(t._zod.def.innerType))return this.collectMetadata(t._zod.def.innerType,s);if(tt(t,"ZodPipe")){const c=t._zod.def.in,u=t._zod.def.out;if(tt(c,"ZodTransform")&&vt(u))return this.collectMetadata(u,s);if(vt(c))return this.collectMetadata(c,s)}return s}static getMetadata(t){return this.collectMetadata(t)}static getOpenApiMetadata(t){const n=this.collectMetadata(t),i=n??{},{_internal:o}=i;return kt(i,["_internal"])}static getInternalMetadata(t){var n;return(n=this.collectMetadata(t))===null||n===void 0?void 0:n._internal}static getParamMetadata(t){const n=this.collectMetadata(t);return Object.assign(Object.assign({},n),{param:Object.assign(Object.assign({},n!=null&&n.description?{description:n.description}:{}),n==null?void 0:n.param)})}static buildSchemaMetadata(t){return In(Hc(t,["param","_internal"]),On)}static buildParameterMetadata(t){return In(t,On)}static applySchemaMetadata(t,n){return In(Object.assign(Object.assign({},t),this.buildSchemaMetadata(n)),On)}static getRefId(t){var n;return(n=this.getInternalMetadata(t))===null||n===void 0?void 0:n.refId}static unwrapChained(t){return this.unwrapUntil(t)}static getDefaultValue(t){var n;const i=(n=this.unwrapUntil(t,"ZodDefault"))!==null&&n!==void 0?n:this.unwrapUntil(t,"ZodPrefault");return i==null?void 0:i._zod.def.defaultValue}static unwrapUntil(t,n){if(n&&tt(t,n))return t;if(tt(t,["ZodOptional","ZodNullable","ZodDefault","ZodPrefault","ZodReadonly","ZodNonOptional"])&&vt(t._zod.def.innerType))return this.unwrapUntil(t._zod.def.innerType,n);if(tt(t,"ZodPipe")){const i=t._zod.def.in,o=t._zod.def.out;if(tt(i,"ZodTransform")&&vt(o))return this.unwrapUntil(o,n);if(vt(i))return this.unwrapUntil(i,n)}return n?void 0:t}static getMetadataFromInternalRegistry(t){return Zi.get(t)}static getMetadataFromRegistry(t){const n=this.getMetadataFromInternalRegistry(t),i=t.meta();if(!n)return i;const{_internal:o}=n,a=kt(n,["_internal"]),s=i??{},{id:c,title:u}=s,p=kt(s,["id","title"]);return Object.assign(Object.assign(Object.assign({_internal:Object.assign(Object.assign({},c?{refId:c}:{}),o)},a),u?{description:u}:{}),p)}static setMetadataInRegistry(t,n){Zi.add(t,n)}}function et(e,t){const n=e[t];typeof n=="function"&&(e[t]=function(...i){const o=n.apply(this,i),a=at.getMetadataFromRegistry(this);return a&&at.setMetadataInRegistry(o,a),o})}function Wc(e){typeof e.ZodType.prototype.openapi<"u"||(e.ZodType.prototype.openapi=function(...t){const{refId:n,metadata:i,options:o}=Qc(...t),a=i??{},{param:s}=a,c=kt(a,["param"]),u=at.getMetadataFromRegistry(this),p=u??{},{_internal:d}=p,h=kt(p,["_internal"]),m=Object.assign(Object.assign(Object.assign({},d),o),n?{refId:n}:void 0),y=Object.assign(Object.assign(Object.assign({},h),c),h!=null&&h.param||s?{param:Object.assign(Object.assign({},h==null?void 0:h.param),s)}:void 0),S=new this.constructor(this._def);function C(x){at.setMetadataInRegistry(x,Object.assign(Object.assign({},Object.keys(m).length>0?{_internal:m}:void 0),y))}if(C(S),tt(S,"ZodLazy")&&C(this),tt(S,"ZodObject")){const x=at.getMetadataFromRegistry(S),G=S.extend;S.extend=function(...X){const V=G.apply(S,X),we=x??{},{_internal:j}=we,ve=kt(we,["_internal"]);return at.setMetadataInRegistry(V,{_internal:{extendedFrom:j!=null&&j.refId?{refId:j.refId,schema:S}:j==null?void 0:j.extendedFrom}}),V.openapi(ve)},et(S,"catchall")}et(S,"optional"),et(S,"nullable"),et(S,"default"),et(S,"transform"),et(S,"refine"),et(S,"length"),et(S,"min"),et(S,"max");const L=S.meta;return S.meta=function(...x){const G=L.apply(this,x);if(x[0]){const X=at.getMetadataFromInternalRegistry(this);X&&at.setMetadataInRegistry(G,Object.assign(Object.assign({},X),x[0]))}return G},S})}function Qc(e,t,n){return typeof e=="string"?{refId:e,metadata:t,options:n}:{refId:void 0,metadata:e,options:t}}new Set(".\\+*[^]$()");var Mi;function v(e,t,n){function i(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const p=s.prototype,d=Object.keys(p);for(let h=0;h<d.length;h++){const m=d[h];m in c||(c[m]=p[m].bind(c))}}const o=(n==null?void 0:n.Parent)??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function s(c){var u;const p=n!=null&&n.Parent?new a:this;i(p,c),(u=p._zod).deferred??(u.deferred=[]);for(const d of p._zod.deferred)d();return p}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>{var u,p;return n!=null&&n.Parent&&c instanceof n.Parent?!0:(p=(u=c==null?void 0:c._zod)==null?void 0:u.traits)==null?void 0:p.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}class At extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Fa extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Mi=globalThis).__zod_globalConfig??(Mi.__zod_globalConfig={});const dn=globalThis.__zod_globalConfig;function Xe(e){return e&&Object.assign(dn,e),dn}function Za(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,o])=>t.indexOf(+i)===-1).map(([i,o])=>o)}function ji(e,t="|"){return e.map(n=>qa(n)).join(t)}function Kn(e,t){return typeof t=="bigint"?t.toString():t}function hn(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function hi(e){return e==null}function mi(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Xc(e,t){const n=e/t,i=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-i)<o?0:n-i}const qi=Symbol("evaluating");function H(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==qi)return i===void 0&&(i=qi,i=n()),i},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function mt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ct(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function Bi(e){return JSON.stringify(e)}function Yc(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Ma="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Mt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const eu=hn(()=>{var e;if(dn.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ct(e){if(Mt(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Mt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ja(e){return Ct(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const tu=new Set(["string","number","symbol"]);function zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function it(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(i._zod.parent=e),i}function T(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new 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 qa(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function nu(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const iu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ou(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=ct(e._zod.def,{get shape(){const s={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(s[c]=n.shape[c])}return mt(this,"shape",s),s},checks:[]});return it(e,a)}function ru(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=ct(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete s[c]}return mt(this,"shape",s),s},checks:[]});return it(e,a)}function au(e,t){if(!Ct(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const a=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(a,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=ct(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return mt(this,"shape",a),a}});return it(e,o)}function su(e,t){if(!Ct(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ct(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return mt(this,"shape",i),i}});return it(e,n)}function lu(e,t){var i;if((i=e._zod.def.checks)!=null&&i.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=ct(e._zod.def,{get shape(){const o={...e._zod.def.shape,...t._zod.def.shape};return mt(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return it(e,n)}function cu(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=ct(t._zod.def,{get shape(){const c=t._zod.def.shape,u={...c};if(n)for(const p in n){if(!(p in c))throw new Error(`Unrecognized key: "${p}"`);n[p]&&(u[p]=e?new e({type:"optional",innerType:c[p]}):c[p])}else for(const p in c)u[p]=e?new e({type:"optional",innerType:c[p]}):c[p];return mt(this,"shape",u),u},checks:[]});return it(t,s)}function uu(e,t,n){const i=ct(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(n)for(const s in n){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(a[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)a[s]=new e({type:"nonoptional",innerType:o[s]});return mt(this,"shape",a),a}});return it(t,i)}function Nt(e,t=0){var n;if(e.aborted===!0)return!0;for(let i=t;i<e.issues.length;i++)if(((n=e.issues[i])==null?void 0:n.continue)!==!0)return!0;return!1}function du(e,t=0){var n;if(e.aborted===!0)return!0;for(let i=t;i<e.issues.length;i++)if(((n=e.issues[i])==null?void 0:n.continue)===!1)return!0;return!1}function Et(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function Qt(e){return typeof e=="string"?e:e==null?void 0:e.message}function nt(e,t,n){var u,p,d,h,m,y;const i=e.message?e.message:Qt((d=(p=(u=e.inst)==null?void 0:u._zod.def)==null?void 0:p.error)==null?void 0:d.call(p,e))??Qt((h=t==null?void 0:t.error)==null?void 0:h.call(t,e))??Qt((m=n.customError)==null?void 0:m.call(n,e))??Qt((y=n.localeError)==null?void 0:y.call(n,e))??"Invalid input",{inst:o,continue:a,input:s,...c}=e;return c.path??(c.path=[]),c.message=i,t!=null&&t.reportInput&&(c.input=s),c}function yi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _u(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function jt(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}const Ba=(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,Kn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ja=v("$ZodError",Ba),Ka=v("$ZodError",Ba,{Parent:Error});function Ga(e,t=n=>n.message){const n={},i=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):i.push(t(o));return{formErrors:i,fieldErrors:n}}function Va(e,t=n=>n.message){const n={_errors:[]},i=(o,a=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>i({issues:c},[...a,...s.path]));else if(s.code==="invalid_key")i({issues:s.issues},[...a,...s.path]);else if(s.code==="invalid_element")i({issues:s.issues},[...a,...s.path]);else{const c=[...a,...s.path];if(c.length===0)n._errors.push(t(s));else{let u=n,p=0;for(;p<c.length;){const d=c[p];p===c.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(s))):u[d]=u[d]||{_errors:[]},u=u[d],p++}}}};return i(e),n}const wi=e=>(t,n,i,o)=>{const a=i?{...i,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new At;if(s.issues.length){const c=new((o==null?void 0:o.Err)??e)(s.issues.map(u=>nt(u,a,Xe())));throw Ma(c,o==null?void 0:o.callee),c}return s.value},vi=e=>async(t,n,i,o)=>{const a=i?{...i,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){const c=new((o==null?void 0:o.Err)??e)(s.issues.map(u=>nt(u,a,Xe())));throw Ma(c,o==null?void 0:o.callee),c}return s.value},mn=e=>(t,n,i)=>{const o=i?{...i,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new At;return a.issues.length?{success:!1,error:new(e??Ja)(a.issues.map(s=>nt(s,o,Xe())))}:{success:!0,data:a.value}},pu=mn(Ka),yn=e=>async(t,n,i)=>{const o=i?{...i,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(s=>nt(s,o,Xe())))}:{success:!0,data:a.value}},fu=yn(Ka),gu=e=>(t,n,i)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return wi(e)(t,n,o)},hu=e=>(t,n,i)=>wi(e)(t,n,i),mu=e=>async(t,n,i)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return vi(e)(t,n,o)},yu=e=>async(t,n,i)=>vi(e)(t,n,i),wu=e=>(t,n,i)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return mn(e)(t,n,o)},vu=e=>(t,n,i)=>mn(e)(t,n,i),bu=e=>async(t,n,i)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return yn(e)(t,n,o)},Su=e=>async(t,n,i)=>yn(e)(t,n,i),Nu=/^[cC][0-9a-z]{6,}$/,Eu=/^[0-9a-z]+$/,Ou=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Iu=/^[0-9a-vA-V]{20}$/,ku=/^[A-Za-z0-9]{27}$/,Au=/^[a-zA-Z0-9_-]{21}$/,Tu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cu=/^([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})$/,Ji=e=>e?new 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)$/,zu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Du="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function xu(){return new RegExp(Du,"u")}const $u=/^(?:(?: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])$/,Ru=/^(([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}|:))$/,Lu=/^((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])$/,Pu=/^(([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])$/,Uu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ha=/^[A-Za-z0-9_-]*$/,Fu=/^https?$/,Zu=/^\+[1-9]\d{6,14}$/,Wa="(?:(?:\\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])))",Mu=new RegExp(`^${Wa}$`);function Qa(e){const 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 ju(e){return new RegExp(`^${Qa(e)}$`)}function qu(e){const t=Qa({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Wa}T(?:${i})$`)}const Bu=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ju=/^-?\d+$/,Xa=/^-?\d+(?:\.\d+)?$/,Ku=/^(?:true|false)$/i,Gu=/^null$/i,Vu=/^[^A-Z]*$/,Hu=/^[^a-z]*$/,Pe=v("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ya={number:"number",bigint:"bigint",object:"date"},es=v("$ZodCheckLessThan",(e,t)=>{Pe.init(e,t);const n=Ya[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ts=v("$ZodCheckGreaterThan",(e,t)=>{Pe.init(e,t);const n=Ya[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wu=v("$ZodCheckMultipleOf",(e,t)=>{Pe.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Xc(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})}}),Qu=v("$ZodCheckNumberFormat",(e,t)=>{var s;Pe.init(e,t),t.format=t.format||"float64";const n=(s=t.format)==null?void 0:s.includes("int"),i=n?"int":"number",[o,a]=iu[t.format];e._zod.onattach.push(c=>{const u=c._zod.bag;u.format=t.format,u.minimum=o,u.maximum=a,n&&(u.pattern=Ju)}),e._zod.check=c=>{const u=c.value;if(n){if(!Number.isInteger(u)){c.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?c.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):c.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}u<o&&c.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),u>a&&c.issues.push({origin:"number",input:u,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Xu=v("$ZodCheckMaxLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!hi(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const o=i.value;if(o.length<=t.maximum)return;const s=yi(o);i.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Yu=v("$ZodCheckMinLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!hi(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const o=i.value;if(o.length>=t.minimum)return;const s=yi(o);i.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ed=v("$ZodCheckLengthEquals",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!hi(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=i=>{const o=i.value,a=o.length;if(a===t.length)return;const s=yi(o),c=a>t.length;i.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),wn=v("$ZodCheckStringFormat",(e,t)=>{var n,i;Pe.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),td=v("$ZodCheckRegex",(e,t)=>{wn.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})}}),nd=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Vu),wn.init(e,t)}),id=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Hu),wn.init(e,t)}),od=v("$ZodCheckIncludes",(e,t)=>{Pe.init(e,t);const n=zt(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(i)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),rd=v("$ZodCheckStartsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`^${zt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),ad=v("$ZodCheckEndsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`.*${zt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),sd=v("$ZodCheckOverwrite",(e,t)=>{Pe.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class ld{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(`
|
|
14
|
+
`).filter(s=>s),o=Math.min(...i.map(s=>s.length-s.trimStart().length)),a=i.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of a)this.content.push(s)}compile(){const t=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(a=>` ${a}`)];return new t(...n,o.join(`
|
|
15
|
+
`))}}const cd={major:4,minor:4,patch:3},ie=v("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=cd;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const a of i)for(const s of a._zod.onattach)s(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const a=(c,u,p)=>{let d=Nt(c),h;for(const m of u){if(m._zod.def.when){if(du(c)||!m._zod.def.when(c))continue}else if(d)continue;const y=c.issues.length,S=m._zod.check(c);if(S instanceof Promise&&(p==null?void 0:p.async)===!1)throw new At;if(h||S instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await S,c.issues.length!==y&&(d||(d=Nt(c,y)))});else{if(c.issues.length===y)continue;d||(d=Nt(c,y))}}return h?h.then(()=>c):c},s=(c,u,p)=>{if(Nt(c))return c.aborted=!0,c;const d=a(u,i,p);if(d instanceof Promise){if(p.async===!1)throw new At;return d.then(h=>e._zod.parse(h,p))}return e._zod.parse(d,p)};e._zod.run=(c,u)=>{if(u.skipChecks)return e._zod.parse(c,u);if(u.direction==="backward"){const d=e._zod.parse({value:c.value,issues:[]},{...u,skipChecks:!0});return d instanceof Promise?d.then(h=>s(h,c,u)):s(d,c,u)}const p=e._zod.parse(c,u);if(p instanceof Promise){if(u.async===!1)throw new At;return p.then(d=>a(d,i,u))}return a(p,i,u)}}H(e,"~standard",()=>({validate:a=>{var s;try{const c=pu(e,a);return c.success?{value:c.data}:{issues:(s=c.error)==null?void 0:s.issues}}catch{return fu(e,a).then(u=>{var p;return u.success?{value:u.data}:{issues:(p=u.error)==null?void 0:p.issues}})}},vendor:"zod",version:1}))}),bi=v("$ZodString",(e,t)=>{var n;ie.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??Bu(e._zod.bag),e._zod.parse=(i,o)=>{if(t.coerce)try{i.value=String(i.value)}catch{}return typeof i.value=="string"||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:e}),i}}),re=v("$ZodStringFormat",(e,t)=>{wn.init(e,t),bi.init(e,t)}),ud=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cu),re.init(e,t)}),dd=v("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ji(i))}else t.pattern??(t.pattern=Ji());re.init(e,t)}),_d=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zu),re.init(e,t)}),pd=v("$ZodURL",(e,t)=>{re.init(e,t),e._zod.check=n=>{var i;try{const o=n.value.trim();if(!t.normalize&&((i=t.protocol)==null?void 0:i.source)===Fu.source&&!/^https?:\/\//i.test(o)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const a=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.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(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=a.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),fd=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=xu()),re.init(e,t)}),gd=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Au),re.init(e,t)}),hd=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Nu),re.init(e,t)}),md=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Eu),re.init(e,t)}),yd=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ou),re.init(e,t)}),wd=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Iu),re.init(e,t)}),vd=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ku),re.init(e,t)}),bd=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=qu(t)),re.init(e,t)}),Sd=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Mu),re.init(e,t)}),Nd=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ju(t)),re.init(e,t)}),Ed=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Tu),re.init(e,t)}),Od=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$u),re.init(e,t),e._zod.bag.format="ipv4"}),Id=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ru),re.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})}}}),kd=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Lu),re.init(e,t)}),Ad=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Pu),re.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[o,a]=i;if(!a)throw new Error;const s=Number(a);if(`${s}`!==a)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ns(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Td=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Uu),re.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ns(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Cd(e){if(!Ha.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ns(n)}const zd=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ha),re.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Cd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Dd=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Zu),re.init(e,t)});function xd(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const o=JSON.parse(atob(i));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const $d=v("$ZodJWT",(e,t)=>{re.init(e,t),e._zod.check=n=>{xd(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),is=v("$ZodNumber",(e,t)=>{ie.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xa,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),n}}),Rd=v("$ZodNumberFormat",(e,t)=>{Qu.init(e,t),is.init(e,t)}),Ld=v("$ZodBoolean",(e,t)=>{ie.init(e,t),e._zod.pattern=Ku,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Pd=v("$ZodNull",(e,t)=>{ie.init(e,t),e._zod.pattern=Gu,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Ud=v("$ZodAny",(e,t)=>{ie.init(e,t),e._zod.parse=n=>n}),Fd=v("$ZodUnknown",(e,t)=>{ie.init(e,t),e._zod.parse=n=>n}),Zd=v("$ZodNever",(e,t)=>{ie.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Ki(e,t,n){e.issues.length&&t.issues.push(...Et(n,e.issues)),t.value[n]=e.value}const Md=v("$ZodArray",(e,t)=>{ie.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const a=[];for(let s=0;s<o.length;s++){const c=o[s],u=t.element._zod.run({value:c,issues:[]},i);u instanceof Promise?a.push(u.then(p=>Ki(p,n,s))):Ki(u,n,s)}return a.length?Promise.all(a).then(()=>n):n}});function _n(e,t,n,i,o,a){const s=n in i;if(e.issues.length){if(o&&a&&!s)return;t.issues.push(...Et(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function os(e){var i,o,a,s;const t=Object.keys(e.shape);for(const c of t)if(!((s=(a=(o=(i=e.shape)==null?void 0:i[c])==null?void 0:o._zod)==null?void 0:a.traits)!=null&&s.has("$ZodType")))throw new Error(`Invalid element at key "${c}": expected a Zod schema`);const n=nu(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function rs(e,t,n,i,o,a){const s=[],c=o.keySet,u=o.catchall._zod,p=u.def.type,d=u.optin==="optional",h=u.optout==="optional";for(const m in t){if(m==="__proto__"||c.has(m))continue;if(p==="never"){s.push(m);continue}const y=u.run({value:t[m],issues:[]},i);y instanceof Promise?e.push(y.then(S=>_n(S,n,m,t,d,h))):_n(y,n,m,t,d,h)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const jd=v("$ZodObject",(e,t)=>{ie.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const i=hn(()=>os(t));H(e._zod,"propValues",()=>{const c=t.shape,u={};for(const p in c){const d=c[p]._zod;if(d.values){u[p]??(u[p]=new Set);for(const h of d.values)u[p].add(h)}}return u});const o=Mt,a=t.catchall;let s;e._zod.parse=(c,u)=>{s??(s=i.value);const p=c.value;if(!o(p))return c.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),c;c.value={};const d=[],h=s.shape;for(const m of s.keys){const y=h[m],S=y._zod.optin==="optional",C=y._zod.optout==="optional",L=y._zod.run({value:p[m],issues:[]},u);L instanceof Promise?d.push(L.then(x=>_n(x,c,m,p,S,C))):_n(L,c,m,p,S,C)}return a?rs(d,p,c,u,i.value,e):d.length?Promise.all(d).then(()=>c):c}}),qd=v("$ZodObjectJIT",(e,t)=>{jd.init(e,t);const n=e._zod.parse,i=hn(()=>os(t)),o=m=>{var X,V;const y=new ld(["shape","payload","ctx"]),S=i.value,C=we=>{const j=Bi(we);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};y.write("const input = payload.value;");const L=Object.create(null);let x=0;for(const we of S.keys)L[we]=`key_${x++}`;y.write("const newResult = {};");for(const we of S.keys){const j=L[we],ve=Bi(we),wt=m[we],$i=((X=wt==null?void 0:wt._zod)==null?void 0:X.optin)==="optional",lc=((V=wt==null?void 0:wt._zod)==null?void 0:V.optout)==="optional";y.write(`const ${j} = ${C(we)};`),$i&&lc?y.write(`
|
|
16
|
+
if (${j}.issues.length) {
|
|
17
|
+
if (${ve} in input) {
|
|
18
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
19
|
+
...iss,
|
|
20
|
+
path: iss.path ? [${ve}, ...iss.path] : [${ve}]
|
|
21
|
+
})));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (${j}.value === undefined) {
|
|
26
|
+
if (${ve} in input) {
|
|
27
|
+
newResult[${ve}] = undefined;
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
newResult[${ve}] = ${j}.value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
`):$i?y.write(`
|
|
34
|
+
if (${j}.issues.length) {
|
|
35
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
36
|
+
...iss,
|
|
37
|
+
path: iss.path ? [${ve}, ...iss.path] : [${ve}]
|
|
38
|
+
})));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (${j}.value === undefined) {
|
|
42
|
+
if (${ve} in input) {
|
|
43
|
+
newResult[${ve}] = undefined;
|
|
44
|
+
}
|
|
45
|
+
} else {
|
|
46
|
+
newResult[${ve}] = ${j}.value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
`):y.write(`
|
|
50
|
+
const ${j}_present = ${ve} in input;
|
|
51
|
+
if (${j}.issues.length) {
|
|
52
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
53
|
+
...iss,
|
|
54
|
+
path: iss.path ? [${ve}, ...iss.path] : [${ve}]
|
|
55
|
+
})));
|
|
56
|
+
}
|
|
57
|
+
if (!${j}_present && !${j}.issues.length) {
|
|
58
|
+
payload.issues.push({
|
|
59
|
+
code: "invalid_type",
|
|
60
|
+
expected: "nonoptional",
|
|
61
|
+
input: undefined,
|
|
62
|
+
path: [${ve}]
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (${j}_present) {
|
|
67
|
+
if (${j}.value === undefined) {
|
|
68
|
+
newResult[${ve}] = undefined;
|
|
69
|
+
} else {
|
|
70
|
+
newResult[${ve}] = ${j}.value;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
`)}y.write("payload.value = newResult;"),y.write("return payload;");const G=y.compile();return(we,j)=>G(m,we,j)};let a;const s=Mt,c=!dn.jitless,p=c&&eu.value,d=t.catchall;let h;e._zod.parse=(m,y)=>{h??(h=i.value);const S=m.value;return s(S)?c&&p&&(y==null?void 0:y.async)===!1&&y.jitless!==!0?(a||(a=o(t.shape)),m=a(m,y),d?rs([],S,m,y,h,e):m):n(m,y):(m.issues.push({expected:"object",code:"invalid_type",input:S,inst:e}),m)}});function Gi(e,t,n,i){for(const a of e)if(a.issues.length===0)return t.value=a.value,t;const o=e.filter(a=>!Nt(a));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(a=>a.issues.map(s=>nt(s,i,Xe())))}),t)}const as=v("$ZodUnion",(e,t)=>{ie.init(e,t),H(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),H(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),H(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),H(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>mi(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(i,o)=>{if(n)return n(i,o);let a=!1;const s=[];for(const c of t.options){const u=c._zod.run({value:i.value,issues:[]},o);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(c=>Gi(c,i,e,o)):Gi(s,i,e,o)}}),Bd=v("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,as.init(e,t);const n=e._zod.parse;H(e._zod,"propValues",()=>{const o={};for(const a of t.options){const s=a._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const[c,u]of Object.entries(s)){o[c]||(o[c]=new Set);for(const p of u)o[c].add(p)}}return o});const i=hn(()=>{var s;const o=t.options,a=new Map;for(const c of o){const u=(s=c._zod.propValues)==null?void 0:s[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(c)}"`);for(const p of u){if(a.has(p))throw new Error(`Duplicate discriminator value "${String(p)}"`);a.set(p,c)}}return a});e._zod.parse=(o,a)=>{const s=o.value;if(!Mt(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const c=i.value.get(s==null?void 0:s[t.discriminator]);return c?c._zod.run(o,a):t.unionFallback||a.direction==="backward"?n(o,a):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(i.value.keys()),input:s,path:[t.discriminator],inst:e}),o)}}),Jd=v("$ZodIntersection",(e,t)=>{ie.init(e,t),e._zod.parse=(n,i)=>{const o=n.value,a=t.left._zod.run({value:o,issues:[]},i),s=t.right._zod.run({value:o,issues:[]},i);return a instanceof Promise||s instanceof Promise?Promise.all([a,s]).then(([u,p])=>Vi(n,u,p)):Vi(n,a,s)}});function Gn(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ct(e)&&Ct(t)){const n=Object.keys(t),i=Object.keys(e).filter(a=>n.indexOf(a)!==-1),o={...e,...t};for(const a of i){const s=Gn(e[a],t[a]);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};o[a]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const o=e[i],a=t[i],s=Gn(o,a);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vi(e,t,n){const i=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const u of c.keys)i.has(u)||i.set(u,{}),i.get(u).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const u of c.keys)i.has(u)||i.set(u,{}),i.get(u).r=!0;else e.issues.push(c);const a=[...i].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length&&o&&e.issues.push({...o,keys:a}),Nt(e))return e;const s=Gn(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const Kd=v("$ZodRecord",(e,t)=>{ie.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!Ct(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const a=[],s=t.keyType._zod.values;if(s){n.value={};const c=new Set;for(const p of s)if(typeof p=="string"||typeof p=="number"||typeof p=="symbol"){c.add(typeof p=="number"?p.toString():p);const d=t.keyType._zod.run({value:p,issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(y=>nt(y,i,Xe())),input:p,path:[p],inst:e});continue}const h=d.value,m=t.valueType._zod.run({value:o[p],issues:[]},i);m instanceof Promise?a.push(m.then(y=>{y.issues.length&&n.issues.push(...Et(p,y.issues)),n.value[h]=y.value})):(m.issues.length&&n.issues.push(...Et(p,m.issues)),n.value[h]=m.value)}let u;for(const p in o)c.has(p)||(u=u??[],u.push(p));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let u=t.keyType._zod.run({value:c,issues:[]},i);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&Xa.test(c)&&u.issues.length){const h=t.keyType._zod.run({value:Number(c),issues:[]},i);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(u=h)}if(u.issues.length){t.mode==="loose"?n.value[c]=o[c]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(h=>nt(h,i,Xe())),input:c,path:[c],inst:e});continue}const d=t.valueType._zod.run({value:o[c],issues:[]},i);d instanceof Promise?a.push(d.then(h=>{h.issues.length&&n.issues.push(...Et(c,h.issues)),n.value[u.value]=h.value})):(d.issues.length&&n.issues.push(...Et(c,d.issues)),n.value[u.value]=d.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Gd=v("$ZodEnum",(e,t)=>{ie.init(e,t);const n=Za(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(o=>tu.has(typeof o)).map(o=>typeof o=="string"?zt(o):o.toString()).join("|")})$`),e._zod.parse=(o,a)=>{const s=o.value;return i.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),Vd=v("$ZodLiteral",(e,t)=>{if(ie.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?zt(i):i?zt(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,o)=>{const a=i.value;return n.has(a)||i.issues.push({code:"invalid_value",values:t.values,input:a,inst:e}),i}}),Hd=v("$ZodTransform",(e,t)=>{ie.init(e,t),e._zod.optin="optional",e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Fa(e.constructor.name);const o=t.transform(n.value,n);if(i.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new At;return n.value=o,n.fallback=!0,n}});function Hi(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const ss=v("$ZodOptional",(e,t)=>{ie.init(e,t),e._zod.optin="optional",e._zod.optout="optional",H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),H(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mi(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,a=t.innerType._zod.run(n,i);return a instanceof Promise?a.then(s=>Hi(s,o)):Hi(a,o)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),Wd=v("$ZodExactOptional",(e,t)=>{ss.init(e,t),H(e._zod,"values",()=>t.innerType._zod.values),H(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),Qd=v("$ZodNullable",(e,t)=>{ie.init(e,t),H(e._zod,"optin",()=>t.innerType._zod.optin),H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mi(n.source)}|null)$`):void 0}),H(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),Xd=v("$ZodDefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(a=>Wi(a,t)):Wi(o,t)}});function Wi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Yd=v("$ZodPrefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),e_=v("$ZodNonOptional",(e,t)=>{ie.init(e,t),H(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(a=>Qi(a,e)):Qi(o,e)}});function Qi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const t_=v("$ZodCatch",(e,t)=>{ie.init(e,t),e._zod.optin="optional",H(e._zod,"optout",()=>t.innerType._zod.optout),H(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(a=>(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(s=>nt(s,i,Xe()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(a=>nt(a,i,Xe()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),ls=v("$ZodPipe",(e,t)=>{ie.init(e,t),H(e._zod,"values",()=>t.in._zod.values),H(e._zod,"optin",()=>t.in._zod.optin),H(e._zod,"optout",()=>t.out._zod.optout),H(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const a=t.out._zod.run(n,i);return a instanceof Promise?a.then(s=>Xt(s,t.in,i)):Xt(a,t.in,i)}const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(a=>Xt(a,t.out,i)):Xt(o,t.out,i)}});function Xt(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const n_=v("$ZodPreprocess",(e,t)=>{ls.init(e,t)}),i_=v("$ZodReadonly",(e,t)=>{ie.init(e,t),H(e._zod,"propValues",()=>t.innerType._zod.propValues),H(e._zod,"values",()=>t.innerType._zod.values),H(e._zod,"optin",()=>{var n,i;return(i=(n=t.innerType)==null?void 0:n._zod)==null?void 0:i.optin}),H(e._zod,"optout",()=>{var n,i;return(i=(n=t.innerType)==null?void 0:n._zod)==null?void 0:i.optout}),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(Xi):Xi(o)}});function Xi(e){return e.value=Object.freeze(e.value),e}const o_=v("$ZodCustom",(e,t)=>{Pe.init(e,t),ie.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,o=t.fn(i);if(o instanceof Promise)return o.then(a=>Yi(a,n,i,e));Yi(o,n,i,e)}});function Yi(e,t,n,i){if(!e){const o={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(o.params=i._zod.def.params),t.issues.push(jt(o))}}const r_=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{const a=i[o.expected]??o.expected,s=_u(o.input),c=i[s]??s;return`Invalid input: expected ${a}, received ${c}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${qa(o.values[0])}`:`Invalid option: expected one of ${ji(o.values,"|")}`;case"too_big":{const a=o.inclusive?"<=":"<",s=t(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${a}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${a}${o.maximum.toString()}`}case"too_small":{const a=o.inclusive?">=":">",s=t(o.origin);return s?`Too small: expected ${o.origin} to have ${a}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${a}${o.minimum.toString()}`}case"invalid_format":{const a=o;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${n[a.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${ji(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function a_(){return{localeError:r_()}}var eo;class s_{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];return this._map.set(t,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const i={...this.get(n)??{}};delete i.id;const o={...i,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function cs(){return new s_}(eo=globalThis).__zod_globalRegistry??(eo.__zod_globalRegistry=cs());const Ot=globalThis.__zod_globalRegistry;function l_(e,t){return new e({type:"string",...T(t)})}function c_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...T(t)})}function to(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...T(t)})}function u_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...T(t)})}function d_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...T(t)})}function __(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...T(t)})}function p_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...T(t)})}function f_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...T(t)})}function g_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...T(t)})}function h_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...T(t)})}function m_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...T(t)})}function y_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...T(t)})}function w_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...T(t)})}function v_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...T(t)})}function b_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...T(t)})}function S_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...T(t)})}function N_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...T(t)})}function E_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...T(t)})}function O_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...T(t)})}function I_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...T(t)})}function k_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...T(t)})}function A_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...T(t)})}function T_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...T(t)})}function C_(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...T(t)})}function z_(e,t){return new e({type:"string",format:"date",check:"string_format",...T(t)})}function D_(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...T(t)})}function x_(e,t){return new e({type:"string",format:"duration",check:"string_format",...T(t)})}function $_(e,t){return new e({type:"number",checks:[],...T(t)})}function R_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...T(t)})}function L_(e,t){return new e({type:"boolean",...T(t)})}function P_(e,t){return new e({type:"null",...T(t)})}function U_(e){return new e({type:"any"})}function F_(e){return new e({type:"unknown"})}function Z_(e,t){return new e({type:"never",...T(t)})}function Vn(e,t){return new es({check:"less_than",...T(t),value:e,inclusive:!1})}function an(e,t){return new es({check:"less_than",...T(t),value:e,inclusive:!0})}function Hn(e,t){return new ts({check:"greater_than",...T(t),value:e,inclusive:!1})}function sn(e,t){return new ts({check:"greater_than",...T(t),value:e,inclusive:!0})}function Wn(e,t){return new Wu({check:"multiple_of",...T(t),value:e})}function Si(e,t){return new Xu({check:"max_length",...T(t),maximum:e})}function qt(e,t){return new Yu({check:"min_length",...T(t),minimum:e})}function Ni(e,t){return new ed({check:"length_equals",...T(t),length:e})}function us(e,t){return new td({check:"string_format",format:"regex",...T(t),pattern:e})}function ds(e){return new nd({check:"string_format",format:"lowercase",...T(e)})}function _s(e){return new id({check:"string_format",format:"uppercase",...T(e)})}function ps(e,t){return new od({check:"string_format",format:"includes",...T(t),includes:e})}function fs(e,t){return new rd({check:"string_format",format:"starts_with",...T(t),prefix:e})}function gs(e,t){return new ad({check:"string_format",format:"ends_with",...T(t),suffix:e})}function yt(e){return new sd({check:"overwrite",tx:e})}function hs(e){return yt(t=>t.normalize(e))}function ms(){return yt(e=>e.trim())}function ys(){return yt(e=>e.toLowerCase())}function ws(){return yt(e=>e.toUpperCase())}function vs(){return yt(e=>Yc(e))}function M_(e,t,n){return new e({type:"array",element:t,...T(n)})}function j_(e,t,n){const i=T(n);return i.abort??(i.abort=!0),new e({type:"custom",check:"custom",fn:t,...i})}function q_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...T(n)})}function B_(e,t){const n=J_(i=>(i.addIssue=o=>{if(typeof o=="string")i.issues.push(jt(o,i.value,n._zod.def));else{const a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=i.value),a.inst??(a.inst=n),a.continue??(a.continue=!n._zod.def.abort),i.issues.push(jt(a))}},e(i.value,i)),t);return n}function J_(e,t){const n=new Pe({check:"custom",...T(t)});return n._zod.check=e,n}function bs(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??Ot,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function he(e,t,n={path:[],schemaPath:[]}){var d,h;var i;const o=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const c=(h=(d=e._zod).toJSONSchema)==null?void 0:h.call(d);if(c)s.schema=c;else{const m={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,m);else{const S=s.schema,C=t.processors[o.type];if(!C)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);C(e,t,S,m)}const y=e._zod.parent;y&&(s.ref||(s.ref=y),he(y,t,m),t.seen.get(y).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(s.schema,u),t.io==="input"&&De(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Ss(e,t){var s,c,u,p;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const d of e.seen.entries()){const h=(s=e.metadataRegistry.get(d[0]))==null?void 0:s.id;if(h){const m=i.get(h);if(m&&m!==d[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(h,d[0])}}const o=d=>{var C;const h=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const L=(C=e.external.registry.get(d[0]))==null?void 0:C.id,x=e.external.uri??(X=>X);if(L)return{ref:x(L)};const G=d[1].defId??d[1].schema.id??`schema${e.counter++}`;return d[1].defId=G,{defId:G,ref:`${x("__shared")}#/${h}/${G}`}}if(d[1]===n)return{ref:"#"};const y=`#/${h}/`,S=d[1].schema.id??`__schema${e.counter++}`;return{defId:S,ref:y+S}},a=d=>{if(d[1].schema.$ref)return;const h=d[1],{ref:m,defId:y}=o(d);h.def={...h.schema},y&&(h.defId=y);const S=h.schema;for(const C in S)delete S[C];S.$ref=m};if(e.cycles==="throw")for(const d of e.seen.entries()){const h=d[1];if(h.cycle)throw new Error(`Cycle detected: #/${(c=h.cycle)==null?void 0:c.join("/")}/<root>
|
|
75
|
+
|
|
76
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of e.seen.entries()){const h=d[1];if(t===d[0]){a(d);continue}if(e.external){const y=(u=e.external.registry.get(d[0]))==null?void 0:u.id;if(t!==d[0]&&y){a(d);continue}}if((p=e.metadataRegistry.get(d[0]))==null?void 0:p.id){a(d);continue}if(h.cycle){a(d);continue}if(h.count>1&&e.reused==="ref"){a(d);continue}}}function Ns(e,t){var c,u,p,d;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=h=>{const m=e.seen.get(h);if(m.ref===null)return;const y=m.def??m.schema,S={...y},C=m.ref;if(m.ref=null,C){i(C);const x=e.seen.get(C),G=x.schema;if(G.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(y.allOf=y.allOf??[],y.allOf.push(G)):Object.assign(y,G),Object.assign(y,S),h._zod.parent===C)for(const V in y)V==="$ref"||V==="allOf"||V in S||delete y[V];if(G.$ref&&x.def)for(const V in y)V==="$ref"||V==="allOf"||V in x.def&&JSON.stringify(y[V])===JSON.stringify(x.def[V])&&delete y[V]}const L=h._zod.parent;if(L&&L!==C){i(L);const x=e.seen.get(L);if(x!=null&&x.schema.$ref&&(y.$ref=x.schema.$ref,x.def))for(const G in y)G==="$ref"||G==="allOf"||G in x.def&&JSON.stringify(y[G])===JSON.stringify(x.def[G])&&delete y[G]}e.override({zodSchema:h,jsonSchema:y,path:m.path??[]})};for(const h of[...e.seen.entries()].reverse())i(h[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,(c=e.external)!=null&&c.uri){const h=(u=e.external.registry.get(t))==null?void 0:u.id;if(!h)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(h)}Object.assign(o,n.def??n.schema);const a=(p=e.metadataRegistry.get(t))==null?void 0:p.id;a!==void 0&&o.id===a&&delete o.id;const s=((d=e.external)==null?void 0:d.defs)??{};for(const h of e.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const h=JSON.parse(JSON.stringify(o));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:pn(t,"input",e.processors),output:pn(t,"output",e.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function De(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return De(i.element,n);if(i.type==="set")return De(i.valueType,n);if(i.type==="lazy")return De(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return De(i.innerType,n);if(i.type==="intersection")return De(i.left,n)||De(i.right,n);if(i.type==="record"||i.type==="map")return De(i.keyType,n)||De(i.valueType,n);if(i.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:De(i.in,n)||De(i.out,n);if(i.type==="object"){for(const o in i.shape)if(De(i.shape[o],n))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(De(o,n))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(De(o,n))return!0;return!!(i.rest&&De(i.rest,n))}return!1}const K_=(e,t={})=>n=>{const i=bs({...n,processors:t});return he(e,i),Ss(i,e),Ns(i,e)},pn=(e,t,n={})=>i=>{const{libraryOptions:o,target:a}=i??{},s=bs({...o??{},target:a,io:t,processors:n});return he(e,s),Ss(s,e),Ns(s,e)},G_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},V_=(e,t,n,i)=>{const o=n;o.type="string";const{minimum:a,maximum:s,format:c,patterns:u,contentEncoding:p}=e._zod.bag;if(typeof a=="number"&&(o.minLength=a),typeof s=="number"&&(o.maxLength=s),c&&(o.format=G_[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),p&&(o.contentEncoding=p),u&&u.size>0){const d=[...u];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},H_=(e,t,n,i)=>{const o=n,{minimum:a,maximum:s,format:c,multipleOf:u,exclusiveMaximum:p,exclusiveMinimum:d}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";const h=typeof d=="number"&&d>=(a??Number.NEGATIVE_INFINITY),m=typeof p=="number"&&p<=(s??Number.POSITIVE_INFINITY),y=t.target==="draft-04"||t.target==="openapi-3.0";h?y?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof a=="number"&&(o.minimum=a),m?y?(o.maximum=p,o.exclusiveMaximum=!0):o.exclusiveMaximum=p:typeof s=="number"&&(o.maximum=s),typeof u=="number"&&(o.multipleOf=u)},W_=(e,t,n,i)=>{n.type="boolean"},Q_=(e,t,n,i)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},X_=(e,t,n,i)=>{n.not={}},Y_=(e,t,n,i)=>{},ep=(e,t,n,i)=>{},tp=(e,t,n,i)=>{const o=e._zod.def,a=Za(o.entries);a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),n.enum=a},np=(e,t,n,i)=>{const o=e._zod.def,a=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(s))}else a.push(s);if(a.length!==0)if(a.length===1){const s=a[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else a.every(s=>typeof s=="number")&&(n.type="number"),a.every(s=>typeof s=="string")&&(n.type="string"),a.every(s=>typeof s=="boolean")&&(n.type="boolean"),a.every(s=>s===null)&&(n.type="null"),n.enum=a},ip=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},op=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},rp=(e,t,n,i)=>{const o=n,a=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=he(a.element,t,{...i,path:[...i.path,"items"]})},ap=(e,t,n,i)=>{var p;const o=n,a=e._zod.def;o.type="object",o.properties={};const s=a.shape;for(const d in s)o.properties[d]=he(s[d],t,{...i,path:[...i.path,"properties",d]});const c=new Set(Object.keys(s)),u=new Set([...c].filter(d=>{const h=a.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));u.size>0&&(o.required=Array.from(u)),((p=a.catchall)==null?void 0:p._zod.def.type)==="never"?o.additionalProperties=!1:a.catchall?a.catchall&&(o.additionalProperties=he(a.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},sp=(e,t,n,i)=>{const o=e._zod.def,a=o.inclusive===!1,s=o.options.map((c,u)=>he(c,t,{...i,path:[...i.path,a?"oneOf":"anyOf",u]}));a?n.oneOf=s:n.anyOf=s},lp=(e,t,n,i)=>{const o=e._zod.def,a=he(o.left,t,{...i,path:[...i.path,"allOf",0]}),s=he(o.right,t,{...i,path:[...i.path,"allOf",1]}),c=p=>"allOf"in p&&Object.keys(p).length===1,u=[...c(a)?a.allOf:[a],...c(s)?s.allOf:[s]];n.allOf=u},cp=(e,t,n,i)=>{const o=n,a=e._zod.def;o.type="object";const s=a.keyType,c=s._zod.bag,u=c==null?void 0:c.patterns;if(a.mode==="loose"&&u&&u.size>0){const d=he(a.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const h of u)o.patternProperties[h.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=he(a.keyType,t,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=he(a.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const p=s._zod.values;if(p){const d=[...p].filter(h=>typeof h=="string"||typeof h=="number");d.length>0&&(o.required=d)}},up=(e,t,n,i)=>{const o=e._zod.def,a=he(o.innerType,t,i),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[a,{type:"null"}]},dp=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType},_p=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},pp=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},fp=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},gp=(e,t,n,i)=>{const o=e._zod.def,a=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?a?o.out:o.in:o.out;he(s,t,i);const c=t.seen.get(e);c.ref=s},hp=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType,n.readOnly=!0},Es=(e,t,n,i)=>{const o=e._zod.def;he(o.innerType,t,i);const a=t.seen.get(e);a.ref=o.innerType},Os=v("ZodISODateTime",(e,t)=>{bd.init(e,t),ae.init(e,t)});function mp(e){return C_(Os,e)}const Is=v("ZodISODate",(e,t)=>{Sd.init(e,t),ae.init(e,t)});function yp(e){return z_(Is,e)}const ks=v("ZodISOTime",(e,t)=>{Nd.init(e,t),ae.init(e,t)});function wp(e){return D_(ks,e)}const As=v("ZodISODuration",(e,t)=>{Ed.init(e,t),ae.init(e,t)});function vp(e){return x_(As,e)}const bp=(e,t)=>{Ja.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Va(e,n)},flatten:{value:n=>Ga(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Kn,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Kn,2)}},isEmpty:{get(){return e.issues.length===0}}})},Me=v("ZodError",bp,{Parent:Error}),Ts=wi(Me),Cs=vi(Me),zs=mn(Me),Ds=yn(Me),xs=gu(Me),$s=hu(Me),Rs=mu(Me),Ls=yu(Me),Ps=wu(Me),Us=vu(Me),Fs=bu(Me),Zs=Su(Me),no=new WeakMap;function Vt(e,t,n){const i=Object.getPrototypeOf(e);let o=no.get(i);if(o||(o=new Set,no.set(i,o)),!o.has(t)){o.add(t);for(const a in n){const s=n[a];Object.defineProperty(i,a,{configurable:!0,enumerable:!1,get(){const c=s.bind(this);return Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}const ne=v("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:pn(e,"input"),output:pn(e,"output")}}),e.toJSONSchema=K_(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,i)=>Ts(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>zs(e,n,i),e.parseAsync=async(n,i)=>Cs(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>Ds(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>xs(e,n,i),e.decode=(n,i)=>$s(e,n,i),e.encodeAsync=async(n,i)=>Rs(e,n,i),e.decodeAsync=async(n,i)=>Ls(e,n,i),e.safeEncode=(n,i)=>Ps(e,n,i),e.safeDecode=(n,i)=>Us(e,n,i),e.safeEncodeAsync=async(n,i)=>Fs(e,n,i),e.safeDecodeAsync=async(n,i)=>Zs(e,n,i),Vt(e,"ZodType",{check(...n){const i=this.def;return this.clone(ct(i,{checks:[...i.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return it(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(xl(n,i))},superRefine(n,i){return this.check($l(n,i))},overwrite(n){return this.check(yt(n))},optional(){return ei(this)},exactOptional(){return bl(this)},nullable(){return ti(this)},nullish(){return ei(ti(this))},nonoptional(n){return kl(this,n)},array(){return E(this)},or(n){return Ue([this,n])},and(n){return ml(this,n)},transform(n){return ni(this,ki(n))},default(n){return El(this,n)},prefault(n){return Il(this,n)},catch(n){return Tl(this,n)},pipe(n){return ni(this,n)},readonly(){return Dl(this)},describe(n){const i=this.clone();return Ot.add(i,{description:n}),i},meta(...n){if(n.length===0)return Ot.get(this);const i=this.clone();return Ot.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){var n;return(n=Ot.get(e))==null?void 0:n.description},configurable:!0}),e)),Ei=v("_ZodString",(e,t)=>{bi.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(i,o,a)=>V_(e,i,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Vt(e,"_ZodString",{regex(...i){return this.check(us(...i))},includes(...i){return this.check(ps(...i))},startsWith(...i){return this.check(fs(...i))},endsWith(...i){return this.check(gs(...i))},min(...i){return this.check(qt(...i))},max(...i){return this.check(Si(...i))},length(...i){return this.check(Ni(...i))},nonempty(...i){return this.check(qt(1,...i))},lowercase(i){return this.check(ds(i))},uppercase(i){return this.check(_s(i))},trim(){return this.check(ms())},normalize(...i){return this.check(hs(...i))},toLowerCase(){return this.check(ys())},toUpperCase(){return this.check(ws())},slugify(){return this.check(vs())}})}),Ms=v("ZodString",(e,t)=>{bi.init(e,t),Ei.init(e,t),e.email=n=>e.check(c_(js,n)),e.url=n=>e.check(f_(qs,n)),e.jwt=n=>e.check(T_(ol,n)),e.emoji=n=>e.check(g_(Bs,n)),e.guid=n=>e.check(to(Qn,n)),e.uuid=n=>e.check(u_(Lt,n)),e.uuidv4=n=>e.check(d_(Lt,n)),e.uuidv6=n=>e.check(__(Lt,n)),e.uuidv7=n=>e.check(p_(Lt,n)),e.nanoid=n=>e.check(h_(Js,n)),e.guid=n=>e.check(to(Qn,n)),e.cuid=n=>e.check(m_(Ks,n)),e.cuid2=n=>e.check(y_(Gs,n)),e.ulid=n=>e.check(w_(Vs,n)),e.base64=n=>e.check(I_(tl,n)),e.base64url=n=>e.check(k_(nl,n)),e.xid=n=>e.check(v_(Hs,n)),e.ksuid=n=>e.check(b_(Ws,n)),e.ipv4=n=>e.check(S_(Qs,n)),e.ipv6=n=>e.check(N_(Xs,n)),e.cidrv4=n=>e.check(E_(Ys,n)),e.cidrv6=n=>e.check(O_(el,n)),e.e164=n=>e.check(A_(il,n)),e.datetime=n=>e.check(mp(n)),e.date=n=>e.check(yp(n)),e.time=n=>e.check(wp(n)),e.duration=n=>e.check(vp(n))});function r(e){return l_(Ms,e)}const ae=v("ZodStringFormat",(e,t)=>{re.init(e,t),Ei.init(e,t)}),js=v("ZodEmail",(e,t)=>{_d.init(e,t),ae.init(e,t)}),Qn=v("ZodGUID",(e,t)=>{ud.init(e,t),ae.init(e,t)}),Lt=v("ZodUUID",(e,t)=>{dd.init(e,t),ae.init(e,t)}),qs=v("ZodURL",(e,t)=>{pd.init(e,t),ae.init(e,t)}),Bs=v("ZodEmoji",(e,t)=>{fd.init(e,t),ae.init(e,t)}),Js=v("ZodNanoID",(e,t)=>{gd.init(e,t),ae.init(e,t)}),Ks=v("ZodCUID",(e,t)=>{hd.init(e,t),ae.init(e,t)}),Gs=v("ZodCUID2",(e,t)=>{md.init(e,t),ae.init(e,t)}),Vs=v("ZodULID",(e,t)=>{yd.init(e,t),ae.init(e,t)}),Hs=v("ZodXID",(e,t)=>{wd.init(e,t),ae.init(e,t)}),Ws=v("ZodKSUID",(e,t)=>{vd.init(e,t),ae.init(e,t)}),Qs=v("ZodIPv4",(e,t)=>{Od.init(e,t),ae.init(e,t)}),Xs=v("ZodIPv6",(e,t)=>{Id.init(e,t),ae.init(e,t)}),Ys=v("ZodCIDRv4",(e,t)=>{kd.init(e,t),ae.init(e,t)}),el=v("ZodCIDRv6",(e,t)=>{Ad.init(e,t),ae.init(e,t)}),tl=v("ZodBase64",(e,t)=>{Td.init(e,t),ae.init(e,t)}),nl=v("ZodBase64URL",(e,t)=>{zd.init(e,t),ae.init(e,t)}),il=v("ZodE164",(e,t)=>{Dd.init(e,t),ae.init(e,t)}),ol=v("ZodJWT",(e,t)=>{$d.init(e,t),ae.init(e,t)}),Oi=v("ZodNumber",(e,t)=>{is.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(i,o,a)=>H_(e,i,o),Vt(e,"ZodNumber",{gt(i,o){return this.check(Hn(i,o))},gte(i,o){return this.check(sn(i,o))},min(i,o){return this.check(sn(i,o))},lt(i,o){return this.check(Vn(i,o))},lte(i,o){return this.check(an(i,o))},max(i,o){return this.check(an(i,o))},int(i){return this.check(Xn(i))},safe(i){return this.check(Xn(i))},positive(i){return this.check(Hn(0,i))},nonnegative(i){return this.check(sn(0,i))},negative(i){return this.check(Vn(0,i))},nonpositive(i){return this.check(an(0,i))},multipleOf(i,o){return this.check(Wn(i,o))},step(i,o){return this.check(Wn(i,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function I(e){return $_(Oi,e)}const rl=v("ZodNumberFormat",(e,t)=>{Rd.init(e,t),Oi.init(e,t)});function Xn(e){return R_(rl,e)}const al=v("ZodBoolean",(e,t)=>{Ld.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>W_(e,n,i)});function g(e){return L_(al,e)}const sl=v("ZodNull",(e,t)=>{Pd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Q_(e,n,i)});function ll(e){return P_(sl,e)}const cl=v("ZodAny",(e,t)=>{Ud.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Y_()});function M(){return U_(cl)}const ul=v("ZodUnknown",(e,t)=>{Fd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>ep()});function $e(){return F_(ul)}const dl=v("ZodNever",(e,t)=>{Zd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>X_(e,n,i)});function _l(e){return Z_(dl,e)}const pl=v("ZodArray",(e,t)=>{Md.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>rp(e,n,i,o),e.element=t.element,Vt(e,"ZodArray",{min(n,i){return this.check(qt(n,i))},nonempty(n){return this.check(qt(1,n))},max(n,i){return this.check(Si(n,i))},length(n,i){return this.check(Ni(n,i))},unwrap(){return this.element}})});function E(e,t){return M_(pl,e,t)}const fl=v("ZodObject",(e,t)=>{qd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>ap(e,n,i,o),H(e,"shape",()=>t.shape),Vt(e,"ZodObject",{keyof(){return O(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:$e()})},loose(){return this.clone({...this._zod.def,catchall:$e()})},strict(){return this.clone({...this._zod.def,catchall:_l()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return au(this,n)},safeExtend(n){return su(this,n)},merge(n){return lu(this,n)},pick(n){return ou(this,n)},omit(n){return ru(this,n)},partial(...n){return cu(Ai,this,n[0])},required(...n){return uu(Ti,this,n[0])}})});function f(e,t){const n={type:"object",shape:e??{},...T(t)};return new fl(n)}const Ii=v("ZodUnion",(e,t)=>{as.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>sp(e,n,i,o),e.options=t.options});function Ue(e,t){return new Ii({type:"union",options:e,...T(t)})}const gl=v("ZodDiscriminatedUnion",(e,t)=>{Ii.init(e,t),Bd.init(e,t)});function Dt(e,t,n){return new gl({type:"union",options:t,discriminator:e,...T(n)})}const hl=v("ZodIntersection",(e,t)=>{Jd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>lp(e,n,i,o)});function ml(e,t){return new hl({type:"intersection",left:e,right:t})}const Yn=v("ZodRecord",(e,t)=>{Kd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>cp(e,n,i,o),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,n){return!t||!t._zod?new Yn({type:"record",keyType:r(),valueType:e,...T(t)}):new Yn({type:"record",keyType:e,valueType:t,...T(n)})}const Bt=v("ZodEnum",(e,t)=>{Gd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(i,o,a)=>tp(e,i,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,o)=>{const a={};for(const s of i)if(n.has(s))a[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Bt({...t,checks:[],...T(o),entries:a})},e.exclude=(i,o)=>{const a={...t.entries};for(const s of i)if(n.has(s))delete a[s];else throw new Error(`Key ${s} not found in enum`);return new Bt({...t,checks:[],...T(o),entries:a})}});function O(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new Bt({type:"enum",entries:n,...T(t)})}function ht(e,t){return new Bt({type:"enum",entries:e,...T(t)})}const yl=v("ZodLiteral",(e,t)=>{Vd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>np(e,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function A(e,t){return new yl({type:"literal",values:Array.isArray(e)?e:[e],...T(t)})}const wl=v("ZodTransform",(e,t)=>{Hd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>op(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new Fa(e.constructor.name);n.addIssue=a=>{if(typeof a=="string")n.issues.push(jt(a,n.value,t));else{const s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(jt(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(a=>(n.value=a,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function ki(e){return new wl({type:"transform",transform:e})}const Ai=v("ZodOptional",(e,t)=>{ss.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Es(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function ei(e){return new Ai({type:"optional",innerType:e})}const vl=v("ZodExactOptional",(e,t)=>{Wd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Es(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function bl(e){return new vl({type:"optional",innerType:e})}const Sl=v("ZodNullable",(e,t)=>{Qd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>up(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function ti(e){return new Sl({type:"nullable",innerType:e})}const Nl=v("ZodDefault",(e,t)=>{Xd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>_p(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function El(e,t){return new Nl({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ja(t)}})}const Ol=v("ZodPrefault",(e,t)=>{Yd.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>pp(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function Il(e,t){return new Ol({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ja(t)}})}const Ti=v("ZodNonOptional",(e,t)=>{e_.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>dp(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function kl(e,t){return new Ti({type:"nonoptional",innerType:e,...T(t)})}const Al=v("ZodCatch",(e,t)=>{t_.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>fp(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Tl(e,t){return new Al({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Ci=v("ZodPipe",(e,t)=>{ls.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>gp(e,n,i,o),e.in=t.in,e.out=t.out});function ni(e,t){return new Ci({type:"pipe",in:e,out:t})}const Cl=v("ZodPreprocess",(e,t)=>{Ci.init(e,t),n_.init(e,t)}),zl=v("ZodReadonly",(e,t)=>{i_.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>hp(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function Dl(e){return new zl({type:"readonly",innerType:e})}const zi=v("ZodCustom",(e,t)=>{o_.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,i,o)=>ip(e,n)});function ii(e,t){return j_(zi,()=>!0,t)}function xl(e,t={}){return q_(zi,e,t)}function $l(e,t){return B_(e,t)}function Rl(e,t){return new Cl({type:"pipe",in:ki(e),out:t})}const ft={custom:"custom"};Xe(a_());const Sp=Object.freeze(Object.defineProperty({__proto__:null,ZodAny:cl,ZodArray:pl,ZodBase64:tl,ZodBase64URL:nl,ZodBoolean:al,ZodCIDRv4:Ys,ZodCIDRv6:el,ZodCUID:Ks,ZodCUID2:Gs,ZodCatch:Al,ZodCustom:zi,ZodDefault:Nl,ZodDiscriminatedUnion:gl,ZodE164:il,ZodEmail:js,ZodEmoji:Bs,ZodEnum:Bt,ZodExactOptional:vl,ZodGUID:Qn,ZodIPv4:Qs,ZodIPv6:Xs,ZodISODate:Is,ZodISODateTime:Os,ZodISODuration:As,ZodISOTime:ks,ZodIntersection:hl,ZodIssueCode:ft,ZodJWT:ol,ZodKSUID:Ws,ZodLiteral:yl,ZodNanoID:Js,ZodNever:dl,ZodNonOptional:Ti,ZodNull:sl,ZodNullable:Sl,ZodNumber:Oi,ZodNumberFormat:rl,ZodObject:fl,ZodOptional:Ai,ZodPipe:Ci,ZodPrefault:Ol,ZodPreprocess:Cl,ZodReadonly:zl,ZodRealError:Me,ZodRecord:Yn,ZodString:Ms,ZodStringFormat:ae,ZodTransform:wl,ZodType:ne,ZodULID:Vs,ZodURL:qs,ZodUUID:Lt,ZodUnion:Ii,ZodUnknown:ul,ZodXID:Hs,_ZodString:Ei,_default:El,any:M,array:E,boolean:g,catch:Tl,clone:it,config:Xe,custom:ii,decode:$s,decodeAsync:Ls,discriminatedUnion:Dt,encode:xs,encodeAsync:Rs,endsWith:gs,enum:O,exactOptional:bl,flattenError:Ga,formatError:Va,globalRegistry:Ot,gt:Hn,gte:sn,includes:ps,int:Xn,intersection:ml,length:Ni,literal:A,lowercase:ds,lt:Vn,lte:an,maxLength:Si,minLength:qt,multipleOf:Wn,nativeEnum:ht,never:_l,nonoptional:kl,normalize:hs,null:ll,nullable:ti,number:I,object:f,optional:ei,overwrite:yt,parse:Ts,parseAsync:Cs,pipe:ni,prefault:Il,preprocess:Rl,readonly:Dl,record:P,refine:xl,regex:us,registry:cs,safeDecode:Us,safeDecodeAsync:Zs,safeEncode:Ps,safeEncodeAsync:Fs,safeParse:zs,safeParseAsync:Ds,slugify:vs,startsWith:fs,string:r,superRefine:$l,toLowerCase:ys,toUpperCase:ws,transform:ki,trim:ms,union:Ue,unknown:$e,uppercase:_s},Symbol.toStringTag,{value:"Module"}));Wc(Sp);const Ge=f({created_at:r(),updated_at:r()}),Ll=f({id:r(),version:r().optional()}),Pl=f({name:r(),version:r()}),Ul=f({name:r(),value:r().optional()}),Fl=f({name:r().max(255),code:r().max(1e5),supported_triggers:E(Ll).optional(),runtime:r().max(50).optional(),dependencies:E(Pl).optional(),secrets:E(Ul).optional(),is_system:g().optional(),inherit:g().optional()});Fl.partial().extend({status:O(["draft","built"]).optional(),deployed_at:r().optional()});Fl.extend({id:r(),tenant_id:r(),status:O(["draft","built"]).default("built"),deployed_at:r().optional(),secrets:E(f({name:r(),value:r().optional()})).optional()}).extend(Ge.shape);const Np=r(),Ep=O(["unspecified","pending","final","partial","canceled","suspended"]),Op=f({id:r(),msg:r(),url:r().optional()}),Ip=f({action_name:r(),error:Op.nullable(),started_at:r(),ended_at:r()}),kp=f({level:O(["log","info","warn","error","debug"]),message:r()}),Ap=E(f({action_name:r(),lines:E(kp)})),Tp=f({id:r(),tenant_id:r(),trigger_id:Np,status:Ep,results:E(Ip),logs:Ap.optional(),created_at:r(),updated_at:r()});Tp.omit({tenant_id:!0,created_at:!0,updated_at:!0});const Cp=f({action_id:r(),code:r().max(1e5),runtime:r().max(50).optional(),dependencies:E(Pl).optional(),secrets:E(Ul).optional(),supported_triggers:E(Ll).optional(),deployed:g().default(!0)});Cp.extend({id:r(),tenant_id:r(),number:I().int()}).extend(Ge.shape);const zp=O(["user_action","admin_action","system","api"]),Dp=f({type:O(["user","admin","system","api_key","client_credentials"]),id:r().optional(),email:r().optional(),org_id:r().optional(),org_name:r().optional(),scopes:E(r()).optional(),client_id:r().optional()}),xp=f({type:r(),id:r(),before:P(r(),$e()).optional(),after:P(r(),$e()).optional(),diff:P(r(),f({old:$e(),new:$e()})).optional()}),$p=f({method:r(),path:r(),query:P(r(),r()).optional(),body:$e().optional(),ip:r(),user_agent:r().optional(),correlation_id:r().optional()}),Rp=f({status_code:I(),body:$e().optional()}),Lp=f({country_code:r(),city_name:r(),latitude:r(),longitude:r(),time_zone:r(),continent_code:r()}),Pp=f({name:r(),version:r(),env:P(r(),r()).optional()}),Up=f({tenant_id:r(),event_type:r(),log_type:r(),description:r().optional(),category:zp,actor:Dp,target:xp,request:$p,response:Rp.optional(),connection:r().optional(),strategy:r().optional(),strategy_type:r().optional(),audience:r().optional(),scope:r().optional(),location:Lp.optional(),auth0_client:Pp.optional(),hostname:r(),is_mobile:g().optional(),timestamp:r()});Up.extend({id:r()});O(["AUTH0","EMAIL","REDIRECT"]);O(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]);O(["VERIFY_EMAIL"]);const Fp=f({require_mx_record:g().optional(),block_aliases:g().optional(),block_free_emails:g().optional(),block_disposable_emails:g().optional(),blocklist:E(r()).optional(),allowlist:E(r()).optional()}),Zp=f({id:r(),alias:r().max(100).optional(),type:A("AUTH0"),action:A("UPDATE_USER"),allow_failure:g().optional(),mask_output:g().optional(),params:f({connection_id:r().optional(),user_id:r(),changes:P(r(),M())})}),Mp=f({id:r(),alias:r().max(100).optional(),type:A("EMAIL"),action:A("VERIFY_EMAIL"),allow_failure:g().optional(),mask_output:g().optional(),params:f({email:r(),rules:Fp.optional()})}),jp=O(["change-email","account","custom"]),qp=f({id:r(),alias:r().max(100).optional(),type:A("REDIRECT"),action:A("REDIRECT_USER"),allow_failure:g().optional(),mask_output:g().optional(),params:f({target:jp.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:r().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),Bp=Ue([Zp,Mp,qp]),Jp=f({name:r().min(1).max(150).openapi({description:"The name of the flow"}),actions:E(Bp).optional().default([]).openapi({description:"The list of actions to execute in sequence"})});Jp.extend(Ge.shape).extend({id:r().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})});f({page:r().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"The page number where 0 is the first page"}),per_page:r().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"The number of items per page"}),include_totals:r().optional().default("false").transform(e=>e==="true").openapi({description:"If the total number of items should be included in the response"}),sort:r().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:r().optional().openapi({description:"A lucene query string used to filter the results"})});f({start:I(),limit:I(),length:I(),total:I().optional()});const Kp=f({email:r().optional(),email_verified:g().optional(),name:r().optional(),username:r().optional(),given_name:r().optional(),phone_number:r().optional(),phone_verified:g().optional(),family_name:r().optional()}).catchall(M()),Gp=f({connection:r(),user_id:r(),provider:r(),isSocial:g(),email:r().optional(),email_verified:g().optional(),phone_number:r().optional(),phone_verified:g().optional(),username:r().optional(),access_token:r().optional(),access_token_secret:r().optional(),refresh_token:r().optional(),profileData:Kp.optional()}),Vp=f({formatted:r().optional(),street_address:r().optional(),locality:r().optional(),region:r().optional(),postal_code:r().optional(),country:r().optional()}).optional(),Zl=f({email:r().transform(e=>e.toLowerCase()).optional(),username:r().refine(e=>!e.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:r().optional(),phone_verified:g().optional(),given_name:r().optional(),family_name:r().optional(),nickname:r().optional(),name:r().optional(),picture:r().optional(),locale:r().optional(),linked_to:r().optional(),profileData:r().optional(),user_id:r().optional(),app_metadata:M().default({}).optional(),user_metadata:M().default({}).optional(),middle_name:r().optional(),preferred_username:r().optional(),profile:r().optional(),website:r().optional(),gender:r().optional(),birthdate:r().optional(),zoneinfo:r().optional(),address:Vp}),Hp=Zl.extend({email_verified:g().default(!1),verify_email:g().optional(),last_ip:r().optional(),last_login:r().optional(),user_id:r().optional(),provider:r().optional(),connection:r(),is_social:g().optional(),registration_completed_at:r().optional(),password:f({hash:r(),algorithm:r()}).optional()}),Wp=Hp.omit({password:!0}).extend(Ge.shape).extend({user_id:r(),provider:r(),is_social:g(),email:r().optional(),login_count:I().default(0),identities:E(Gp).optional()});Wp.omit({registration_completed_at:!0});Zl.extend({login_count:I(),multifactor:E(r()).optional(),last_ip:r().optional(),last_login:r().optional(),user_id:r()}).catchall(M());let Qp="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Xp=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=Qp[n[e]&63];return t};const Yp=f({client_id:r().optional().openapi({description:"ID of this client. Generated server-side if omitted (Auth0 behavior)."}),name:r().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:r().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:g().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:r().default(()=>Xp()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:O(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:r().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:g().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:g().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),auth0_conformant:g().default(!0).openapi({description:"Whether this client follows Auth0-compatible behavior (true) or strict OIDC behavior (false). When true, profile/email claims are included in the ID token when scopes are requested. When false, these claims are only available from the userinfo endpoint (strict OIDC 5.4 compliance)."}),callbacks:E(r()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:E(r()).default([]).optional().openapi({description:"Comma-separated list of URLs allowed to make requests from JavaScript to Auth0 API (typically used with CORS). By default, all your callback URLs will be allowed. This field allows you to enter other origins if necessary. You can also use wildcards at the subdomain level (e.g., https://*.contoso.com). Query strings and hash information are not taken into account when validating these URLs."}),web_origins:E(r()).default([]).optional().openapi({description:"Comma-separated list of allowed origins for use with Cross-Origin Authentication, Device Flow, and web message response mode."}),client_aliases:E(r()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:E(r()).default([]).optional().openapi({description:"List of allow clients and API ids that are allowed to make delegation requests. Empty means all all your clients are allowed."}),connections:E(r()).default([]).optional().openapi({description:"List of connection IDs enabled for this client. The order determines the display order on the login page."}),allowed_logout_urls:E(r()).default([]).optional().openapi({description:"Comma-separated list of URLs that are valid to redirect to after logout from Auth0. Wildcards are allowed for subdomains."}),session_transfer:P(r(),M()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:P(r(),M()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:E(r()).default([]).optional().openapi({description:"List of grant types supported for this application. Can include authorization_code, implicit, refresh_token, client_credentials, password, http://auth0.com/oauth/grant-type/password-realm, http://auth0.com/oauth/grant-type/mfa-oob, http://auth0.com/oauth/grant-type/mfa-otp, http://auth0.com/oauth/grant-type/mfa-recovery-code, urn:openid:params:grant-type:ciba, and urn:ietf:params:oauth:grant-type:device_code."}),jwt_configuration:P(r(),M()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:E(P(r(),M())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:P(r(),M()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:g().default(!1).openapi({description:"Applies only to SSO clients and determines whether Auth0 will handle Single Sign On (true) or whether the Identity Provider will (false)."}),sso_disabled:g().default(!1).openapi({description:"Whether Single Sign On is disabled for this client. When true, existing SSO sessions will not be reused and users must authenticate every time."}),cross_origin_authentication:g().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:r().url().optional().openapi({description:"URL of the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page."}),custom_login_page_on:g().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:r().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:r().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:r().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:P(r(),M()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:O(["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. `none` (public client), `client_secret_post` / `client_secret_basic` (HTTP POST / Basic), `client_secret_jwt` (RFC 7523 HMAC assertion using client_secret), or `private_key_jwt` (RFC 7523 asymmetric assertion verified against the client's `jwks` / `jwks_uri`)."}),client_metadata:P(r(),r().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),hide_sign_up_disabled_error:g().default(!1).optional().openapi({description:"Enumeration-safe variant of the connection-level `disable_signup` flag. When a signup is blocked by the password connection and this is true, the identifier screen does not reveal that an email is unknown — it advances to the OTP/password challenge as if the account existed and fails at credential check. Mitigates email enumeration at the cost of UX: users without an account see a generic credential failure instead of an explicit signup-disabled message."}),mobile:P(r(),M()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:r().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:P(r(),M()).default({}).optional(),refresh_token:f({rotation_type:O(["rotating","non-rotating"]).optional().openapi({description:"Whether refresh tokens for this client are rotated on every exchange (Auth0 'rotating' behavior) or kept stable (legacy non-rotating). Defaults to 'non-rotating' when unset."}),leeway:I().int().min(0).max(600).optional().openapi({description:"Seconds after a parent token's first rotation during which presenting it again still mints a fresh sibling child instead of triggering reuse-detection. Defaults to 30s when unset."}),expiration_type:O(["expiring","non-expiring"]).optional().openapi({description:"Auth0-compatible: whether refresh tokens expire."}),token_lifetime:I().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token absolute lifetime in seconds."}),infinite_token_lifetime:g().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no absolute expiry."}),idle_token_lifetime:I().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token idle (sliding) lifetime in seconds."}),infinite_idle_token_lifetime:g().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no idle expiry."})}).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:P(r(),M()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:O(["deny","allow","require"]).default("deny").optional().openapi({description:"Defines how to proceed during an authentication transaction with regards an organization. Can be deny (default), allow or require."}),organization_require_behavior:O(["no_prompt","pre_login_prompt","post_login_prompt"]).default("no_prompt").optional().openapi({description:"Defines how to proceed during an authentication transaction when client.organization_usage: 'require'. Can be no_prompt (default), pre_login_prompt or post_login_prompt. post_login_prompt requires oidc_conformant: true."}),client_authentication_methods:P(r(),M()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:g().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:g().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:P(r(),M()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:O(["none","fapi1_adv_pkj_par","fapi1_adv_mtls_par","fapi2_sp_pkj_mtls","fapi2_sp_mtls_mtls"]).optional().openapi({description:"Defines the compliance level for this client, which may restrict it's capabilities"}),par_request_expiry:I().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:P(r(),M()).default({}).optional(),owner_user_id:r().optional().openapi({description:"User ID of the consenting user when this client was created via IAT-gated Dynamic Client Registration. NULL for clients created via the Management API or open DCR."}),registration_type:O(["manual","open_dcr","iat_dcr"]).optional().openapi({description:"Provenance of this client. `manual` = Management API; `open_dcr` = RFC 7591 without IAT; `iat_dcr` = RFC 7591 with an Initial Access Token."}),registration_metadata:P(r(),M()).default({}).optional().openapi({description:"Arbitrary metadata captured at Dynamic Client Registration time that isn't a first-class client field (e.g. integration_type, domain). Also stores `iat_constraints` for clients created via IAT so RFC 7592 PUT can enforce field immutability."}),user_linking_mode:O(["builtin","off"]).optional().openapi({description:"Per-client override for the built-in email-based user-linking path. `builtin` runs the legacy in-process linking at user creation/email update. `off` disables the legacy path; linking only happens if the tenant has enabled the `account-linking` template hook. When unset, the service-level `userLinkingMode` default applies."})});f({created_at:r(),updated_at:r()}).extend(Yp.shape).extend({client_id:r()});const ef=f({client_id:r().min(1).openapi({description:"ID of the client."}),audience:r().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:E(r()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:O(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:g().optional().openapi({description:"If enabled, any organization can be used with this grant. If disabled (default), the grant must be explicitly assigned to the desired organizations."}),is_system:g().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:O(["client","user"]).optional().openapi({description:"The type of application access the client grant allows. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."}),authorization_details_types:E(r()).optional().openapi({description:"Types of authorization_details allowed for this client grant. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."})});f({id:r().openapi({description:"ID of the client grant."})}).extend(ef.shape).extend({created_at:r().optional(),updated_at:r().optional()});const Ml=O(["iat","rat"]),tf=f({id:r(),token_hash:r(),type:Ml,client_id:r().optional(),sub:r().optional(),constraints:P(r(),$e()).optional(),single_use:g().default(!1),expires_at:r().optional()});f({created_at:r(),used_at:r().optional(),revoked_at:r().optional()}).extend(tf.shape);const xt=f({x:I(),y:I()});var jl=(e=>(e.RICH_TEXT="RICH_TEXT",e.NEXT_BUTTON="NEXT_BUTTON",e.BACK_BUTTON="BACK_BUTTON",e.SUBMIT_BUTTON="SUBMIT_BUTTON",e.DIVIDER="DIVIDER",e.TEXT="TEXT",e.EMAIL="EMAIL",e.PASSWORD="PASSWORD",e.NUMBER="NUMBER",e.PHONE="PHONE",e.DATE="DATE",e.CHECKBOX="CHECKBOX",e.RADIO="RADIO",e.SELECT="SELECT",e.HIDDEN="HIDDEN",e.LEGAL="LEGAL",e))(jl||{}),ql=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(ql||{});const vn=f({id:r(),category:ht(ql),type:ht(jl)}),nf=vn.extend({category:A("BLOCK"),type:A("RICH_TEXT"),config:f({content:r()}).passthrough()}),of=vn.extend({category:A("BLOCK"),type:Ue([A("NEXT_BUTTON"),A("BACK_BUTTON"),A("SUBMIT_BUTTON")]),config:f({text:r()}).passthrough()}),rf=vn.extend({category:A("FIELD"),type:A("LEGAL"),required:g().optional(),sensitive:g().optional(),config:f({text:r()}).passthrough()}),af=vn.extend({category:A("FIELD"),type:Ue([A("TEXT"),A("EMAIL"),A("PASSWORD"),A("NUMBER"),A("PHONE"),A("DATE"),A("CHECKBOX"),A("RADIO"),A("SELECT"),A("HIDDEN")]),required:g().optional(),sensitive:g().optional(),config:f({label:r().optional(),placeholder:r().optional()}).passthrough()}),sf=f({id:r(),category:r(),type:r()}).passthrough(),lf=Ue([nf,of,rf,af,sf]),cf=f({id:r(),type:A("STEP"),coordinates:xt,alias:r().optional(),config:f({components:E(lf),next_node:r()}).passthrough()}),uf=f({id:r(),type:A("FLOW"),coordinates:xt,alias:r().optional(),config:f({flow_id:r(),next_node:r()})}),df=f({id:r(),type:A("ACTION"),coordinates:xt,alias:r().optional(),config:f({action_type:O(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:O(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:r().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:r().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),_f=f({id:r(),type:r(),coordinates:xt}).passthrough(),pf=Ue([cf,uf,df,_f]),ff=f({next_node:r(),coordinates:xt}).passthrough(),gf=f({resume_flow:g().optional(),coordinates:xt}).passthrough(),hf=f({id:r(),name:r(),languages:f({primary:r()}).passthrough(),nodes:E(pf),start:ff,ending:gf,created_at:r(),updated_at:r(),links:f({sdkSrc:r().optional(),sdk_src:r().optional()}).passthrough()}).passthrough();hf.omit({id:!0,created_at:!0,updated_at:!0});var Bl=(e=>(e.TOKEN="token",e.ID_TOKEN="id_token",e.TOKEN_ID_TOKEN="id_token token",e.CODE="code",e.CODE_ID_TOKEN="code id_token",e.CODE_TOKEN="code token",e.CODE_ID_TOKEN_TOKEN="code id_token token",e))(Bl||{}),Jl=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(Jl||{}),Kl=(e=>(e.S256="S256",e.Plain="plain",e))(Kl||{});const io=Ue([ll(),f({essential:g().optional(),value:$e().optional(),values:E($e()).optional()})]).nullable(),mf=f({userinfo:P(r(),io).optional(),id_token:P(r(),io).optional()}),yf=f({client_id:r(),act_as:r().optional(),response_type:ht(Bl).optional(),response_mode:ht(Jl).optional(),redirect_uri:r().optional(),audience:r().optional(),organization:r().optional(),state:r().optional(),nonce:r().optional(),scope:r().optional(),prompt:r().optional(),code_challenge_method:ht(Kl).optional(),code_challenge:r().optional(),username:r().optional(),ui_locales:r().optional(),max_age:I().optional(),acr_values:r().optional(),claims:mf.optional(),vendor_id:r().optional()});f({colors:f({primary:r(),page_background:Ue([r(),f({type:r().optional(),start:r().optional(),end:r().optional(),angle_deg:I().optional()})]).optional()}).optional(),logo_url:r().optional(),favicon_url:r().optional(),powered_by_logo_url:r().optional(),font:f({url:r()}).optional(),dark_mode:O(["dark","light","auto"]).optional()});const wf=O(["password_reset","email_verification","otp","mfa_otp","authorization_code","oauth2_state","ticket"]),vf=f({code_id:r().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:r().openapi({description:"The id of the login session that the code is connected to"}),connection_id:r().optional().openapi({description:"The connection that the code is connected to"}),code_type:wf,code_verifier:r().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:r().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:O(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:r().optional().openapi({description:"The redirect URI associated with the code"}),otp:r().optional().openapi({description:"The one-time password value for OTP-based flows"}),nonce:r().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:r().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:r(),used_at:r().optional(),user_id:r().optional()});vf.extend({created_at:r()});const bf=f({kid:r().optional(),team_id:r().optional(),realms:r().optional(),authentication_method:r().optional(),client_id:r().optional(),client_secret:r().optional(),app_secret:r().optional(),scope:r().optional(),authorization_endpoint:r().optional(),token_endpoint:r().optional(),userinfo_endpoint:r().optional(),jwks_uri:r().optional(),discovery_url:r().optional(),issuer:r().optional(),token_endpoint_auth_method:O(["client_secret_basic","client_secret_post"]).optional(),provider:r().optional(),from:r().optional(),twilio_sid:r().optional(),twilio_token:r().optional(),icon_url:r().optional(),domain_aliases:E(r()).optional(),callback_url:r().url().optional(),passwordPolicy:O(["none","low","fair","good","excellent"]).optional(),password_complexity_options:f({min_length:I().optional()}).optional(),password_history:f({enable:g().optional(),size:I().optional()}).optional(),password_no_personal_info:f({enable:g().optional()}).optional(),password_dictionary:f({enable:g().optional(),dictionary:E(r()).optional()}).optional(),disable_signup:g().optional(),brute_force_protection:g().optional(),import_mode:g().optional(),configuration:f({token_endpoint:r().optional(),userinfo_endpoint:r().optional(),client_id:r().optional(),client_secret:r().optional(),realm:r().optional()}).optional(),attributes:f({email:f({identifier:f({active:g().optional()}).optional(),signup:f({status:O(["required","optional","disabled"]).optional(),verification:f({active:g().optional()}).optional()}).optional(),validation:f({allowed:g().optional()}).optional(),unique:g().optional(),profile_required:g().optional(),verification_method:O(["link","code"]).optional()}).optional(),username:f({identifier:f({active:g().optional()}).optional(),signup:f({status:O(["required","optional","disabled"]).optional()}).optional(),validation:f({max_length:I().optional(),min_length:I().optional(),allowed_types:f({email:g().optional(),phone_number:g().optional()}).optional()}).optional(),profile_required:g().optional()}).optional(),phone_number:f({identifier:f({active:g().optional()}).optional(),signup:f({status:O(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:f({password:f({enabled:g().optional()}).optional(),passkey:f({enabled:g().optional()}).optional()}).optional(),passkey_options:f({challenge_ui:O(["both","autofill","button"]).optional(),local_enrollment_enabled:g().optional(),progressive_enrollment_enabled:g().optional()}).optional(),requires_username:g().optional(),validation:f({username:f({min:I().optional(),max:I().optional()}).optional()}).optional(),set_user_root_attributes:O(["on_each_login","on_first_login","never_on_login"]).optional()});function oi(e){if(e!==null){if(Array.isArray(e))return e.filter(t=>t!==null).map(oi);if(e&&typeof e=="object"){const t={};for(const[n,i]of Object.entries(e))i!==null&&(t[n]=oi(i));return t}return e}}const Sf=f({id:r().optional(),name:r(),display_name:r().optional(),strategy:r(),options:Rl(e=>e===null?{}:oi(e),bf).default({}),enabled_clients:E(r()).default([]).optional(),response_type:ii().optional(),response_mode:ii().optional(),is_domain_connection:g().optional(),show_as_button:g().optional(),metadata:P(r(),M()).optional(),is_system:g().optional()});f({id:r(),created_at:r().transform(e=>e===null?"":e),updated_at:r().transform(e=>e===null?"":e)}).extend(Sf.shape);const Nf=f({domain:r(),custom_domain_id:r().optional(),type:O(["auth0_managed_certs","self_managed_certs"]),verification_method:O(["txt"]).optional(),tls_policy:O(["recommended"]).optional(),custom_client_ip_header:O(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:P(r(),r().max(255)).optional()}),Ef=Dt("name",[f({name:A("txt"),record:r(),domain:r()}),f({name:A("http"),http_body:r(),http_url:r()})]),Of=Nf.extend({custom_domain_id:r(),primary:g(),status:O(["disabled","pending","pending_verification","ready"]),origin_domain_name:r().optional(),verification:f({methods:E(Ef)}).optional(),tls_policy:r().optional()});Of.extend({tenant_id:r()});const Di=f({id:r(),order:I().optional(),visible:g().optional().default(!0)}),ut=Di.extend({category:A("BLOCK").optional()}),If=ut.extend({type:A("DIVIDER"),config:f({text:r().optional()}).optional()}),kf=ut.extend({type:A("HTML"),config:f({content:r().optional()}).optional()}),Af=ut.extend({type:A("IMAGE"),config:f({src:r().optional(),alt:r().optional(),width:I().optional(),height:I().optional()}).optional()}),Tf=ut.extend({type:A("JUMP_BUTTON"),config:f({text:r().optional(),target_step:r().optional()})}),Cf=ut.extend({type:A("RESEND_BUTTON"),config:f({text:r().optional(),resend_action:r().optional()})}),zf=ut.extend({type:A("NEXT_BUTTON"),config:f({text:r().optional()})}),Df=ut.extend({type:A("PREVIOUS_BUTTON"),config:f({text:r().optional()})}),xf=ut.extend({type:A("RICH_TEXT"),config:f({content:r().optional()}).optional()}),xi=Di.extend({category:A("WIDGET").optional(),label:r().min(1).optional(),hint:r().min(1).max(500).optional(),required:g().optional(),sensitive:g().optional()}),$f=xi.extend({type:A("AUTH0_VERIFIABLE_CREDENTIALS"),config:f({credential_type:r().optional()})}),Rf=xi.extend({type:A("GMAPS_ADDRESS"),config:f({api_key:r().optional()})}),Lf=xi.extend({type:A("RECAPTCHA"),config:f({site_key:r().optional()})}),Ie=Di.extend({category:A("FIELD").optional(),label:r().min(1).optional(),hint:r().min(1).max(500).optional(),messages:E(f({id:I().optional(),text:r(),type:O(["info","error","success","warning"])})).optional(),required:g().optional(),sensitive:g().optional()}),Pf=Ie.extend({type:A("BOOLEAN"),config:f({default_value:g().optional()}).optional()}),Uf=Ie.extend({type:A("CARDS"),config:f({options:E(f({value:r(),label:r(),description:r().optional(),image:r().optional()})).optional(),multi_select:g().optional()}).optional()}),Ff=Ie.extend({type:A("CHOICE"),config:f({options:E(f({value:r(),label:r()})).optional(),display:O(["radio","checkbox"]).optional(),multiple:g().optional(),default_value:Ue([r(),E(r())]).optional()}).optional()}),Zf=Ie.extend({type:A("CUSTOM"),config:f({component:r().optional(),props:P(r(),M()).optional(),schema:P(r(),M()).optional(),code:r().optional()})}),Mf=Ie.extend({type:A("DATE"),config:f({format:r().optional(),min:r().optional(),max:r().optional(),default_value:r().optional()}).optional()}),jf=Ie.extend({type:A("DROPDOWN"),config:f({options:E(f({value:r(),label:r()})).optional(),placeholder:r().optional(),searchable:g().optional(),multiple:g().optional(),default_value:Ue([r(),E(r())]).optional()}).optional()}),qf=Ie.extend({type:A("EMAIL"),config:f({placeholder:r().optional(),default_value:r().optional()}).optional()}),Bf=Ie.extend({type:A("FILE"),config:f({accept:r().optional(),max_size:I().optional(),multiple:g().optional()}).optional()}),Jf=Ie.extend({type:A("LEGAL"),config:f({text:r(),html:g().optional()}).optional()}),Kf=Ie.extend({type:A("NUMBER"),config:f({placeholder:r().optional(),min:I().optional(),max:I().optional(),step:I().optional(),default_value:r().optional()}).optional()}),Gf=Ie.extend({type:A("PASSWORD"),config:f({placeholder:r().optional(),min_length:I().optional(),show_toggle:g().optional(),forgot_password_link:r().optional(),default_value:r().optional()}).optional()}),Vf=Ie.extend({type:A("PAYMENT"),config:f({provider:r().optional(),currency:r().optional()}).optional()}),Hf=Ie.extend({type:A("SOCIAL"),config:f({providers:E(r()).optional(),provider_details:E(f({name:r(),strategy:r().optional(),display_name:r().optional(),icon_url:r().optional(),href:r().optional()})).optional()}).optional()}),Wf=Ie.extend({type:A("TEL"),config:f({placeholder:r().optional(),default_country:r().optional(),default_value:r().optional(),allow_email:g().optional()}).optional()}),Qf=Ie.extend({type:A("TEXT"),config:f({placeholder:r().optional(),multiline:g().optional(),max_length:I().optional(),default_value:r().optional()}).optional()}),Xf=Ie.extend({type:A("COUNTRY"),config:f({placeholder:r().optional(),default_value:r().optional()}).optional()}),Yf=Ie.extend({type:A("URL"),config:f({placeholder:r().optional(),default_value:r().optional()}).optional()}),eg=Dt("type",[If,kf,Af,Tf,Cf,zf,Df,xf]),tg=Dt("type",[$f,Rf,Lf]),ng=Dt("type",[Pf,Uf,Ff,Xf,Zf,Mf,jf,qf,Bf,Jf,Kf,Gf,Vf,Hf,Wf,Qf,Yf]),Gl=Ue([eg,tg,ng]);f({id:r(),type:A("submit"),label:r(),className:r().optional(),disabled:g().optional().default(!1),order:I().optional(),visible:g().optional().default(!0),customizations:P(r(),M()).optional()});const Jt=f({x:I(),y:I()}),ig=f({id:r(),type:A("FLOW"),coordinates:Jt,alias:r().min(1).max(150).optional(),config:f({flow_id:r().max(30),next_node:r().optional()})}),og=f({id:r(),type:A("ROUTER"),coordinates:Jt,alias:r().min(1).max(150),config:f({rules:E(f({id:r(),alias:r().min(1).max(150).optional(),condition:M(),next_node:r()})),fallback:r()})}),rg=f({id:r(),type:A("STEP"),coordinates:Jt,alias:r().min(1).max(150).optional(),config:f({components:E(Gl),next_node:r().optional()})}),ag=Dt("type",[ig,og,rg]),sg=f({name:r().openapi({description:"The name of the form"}),messages:f({errors:P(r(),M()).optional(),custom:P(r(),M()).optional()}).optional(),languages:f({primary:r().optional(),default:r().optional()}).optional(),translations:P(r(),M()).optional(),nodes:E(ag).optional(),start:f({hidden_fields:E(f({key:r(),value:r()})).optional(),next_node:r().optional(),coordinates:Jt.optional()}).optional(),ending:f({redirection:f({delay:I().optional(),target:r().optional()}).optional(),after_submit:f({flow_id:r().optional()}).optional(),coordinates:Jt.optional(),resume_flow:g().optional()}).optional(),style:f({css:r().optional()}).optional(),links:f({sdkSrc:r().optional(),sdk_src:r().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"});Ge.extend(sg.shape).extend({id:r()});const lg=f({id:I().optional(),text:r(),type:O(["info","error","success","warning"])}),cg=f({id:r().optional(),text:r(),href:r(),linkText:r().optional()});f({name:r().optional(),action:r(),method:O(["POST","GET"]),title:r().optional(),description:r().optional(),components:E(Gl),messages:E(lg).optional(),links:E(cg).optional(),footer:r().optional()});const Vl=O(["pre-user-registration","post-user-registration","post-user-login","post-user-update","validate-registration-username","pre-user-deletion","post-user-deletion"]),Hl=O(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Wl=O(["post-user-login","post-user-registration","post-user-update","credentials-exchange"]),Ql=O(["post-user-login","credentials-exchange","pre-user-registration","post-user-registration"]),Xl=O(["ensure-username","set-preferred-username","account-linking"]),dt={enabled:g().default(!1),synchronous:g().default(!1),priority:I().optional(),hook_id:r().optional(),metadata:P(r(),$e()).optional()},ug=f({...dt,trigger_id:Vl,url:r()}),dg=f({...dt,trigger_id:Hl,form_id:r()}),_g=f({...dt,trigger_id:Wl,template_id:Xl}),pg=f({...dt,trigger_id:Ql,code_id:r()});Ue([ug,dg,_g,pg]);const fg=f({...dt,trigger_id:Vl}).extend(Ge.shape).extend({hook_id:r(),url:r()}),gg=f({...dt,trigger_id:Hl}).extend(Ge.shape).extend({hook_id:r(),form_id:r()}),hg=f({...dt,trigger_id:Wl}).extend(Ge.shape).extend({hook_id:r(),template_id:Xl}),mg=f({...dt,trigger_id:Ql}).extend(Ge.shape).extend({hook_id:r(),code_id:r()});Ue([fg,gg,hg,mg]);const yg=f({code:r().max(1e5),secrets:P(r(),r()).optional()});yg.extend({id:r(),tenant_id:r()}).extend(Ge.shape);const wg=f({name:r().optional()}),vg=f({email:r().optional()}),bg=f({id:r().optional(),organization_id:r().max(50),inviter:wg,invitee:vg,invitation_url:r().url(),client_id:r(),connection_id:r().optional(),app_metadata:P(r(),M()).default({}).optional(),user_metadata:P(r(),M()).default({}).optional(),ttl_sec:I().int().max(2592e3).default(604800).optional(),roles:E(r()).default([]).optional(),send_invitation_email:g().default(!0).optional()});f({id:r(),organization_id:r().max(50),created_at:r().datetime(),expires_at:r().datetime(),ticket_id:r().optional()}).extend(bg.omit({id:!0}).shape);const Sg=f({alg:O(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kid:r(),kty:O(["RSA","EC","oct"]),use:O(["sig","enc"]).optional(),n:r().optional(),e:r().optional(),crv:r().optional(),x:r().optional(),y:r().optional(),x5t:r().optional(),x5c:E(r()).optional()}).superRefine((e,t)=>{if(e.kty==="RSA")for(const n of["n","e"])e[n]||t.addIssue({code:ft.custom,path:[n],message:`RSA JWK is missing required member '${n}'`});else if(e.kty==="EC")for(const n of["crv","x","y"])e[n]||t.addIssue({code:ft.custom,path:[n],message:`EC JWK is missing required member '${n}'`})});f({keys:E(Sg)});f({issuer:r(),authorization_endpoint:r(),token_endpoint:r(),userinfo_endpoint:r(),jwks_uri:r(),registration_endpoint:r().optional(),revocation_endpoint:r(),end_session_endpoint:r().optional(),scopes_supported:E(r()),response_types_supported:E(r()),grant_types_supported:E(r()).optional(),code_challenge_methods_supported:E(r()),response_modes_supported:E(r()),subject_types_supported:E(r()),id_token_signing_alg_values_supported:E(r()),token_endpoint_auth_methods_supported:E(r()),claims_supported:E(r()),request_uri_parameter_supported:g(),request_parameter_supported:g(),claims_parameter_supported:g().optional(),request_object_signing_alg_values_supported:E(r()).optional(),token_endpoint_auth_signing_alg_values_supported:E(r())});var Yl=(e=>(e.PENDING="pending",e.AUTHENTICATED="authenticated",e.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",e.AWAITING_MFA="awaiting_mfa",e.AWAITING_HOOK="awaiting_hook",e.AWAITING_CONTINUATION="awaiting_continuation",e.COMPLETED="completed",e.FAILED="failed",e.EXPIRED="expired",e))(Yl||{});const Ng=ht(Yl),Eg=f({strategy:r(),strategy_type:r()}),Og=f({csrf_token:r(),auth0Client:r().optional(),authParams:yf,expires_at:r(),deleted_at:r().optional(),ip:r().optional(),useragent:r().optional(),session_id:r().optional(),authorization_url:r().optional(),state:Ng.optional().default("pending"),state_data:r().optional(),failure_reason:r().optional(),user_id:r().optional(),auth_connection:r().optional(),auth_strategy:Eg.optional(),authenticated_at:r().optional()}).openapi({description:"This represents a login sesion"});Og.extend({id:r().openapi({description:"This is is used as the state in the universal login"}),created_at:r(),updated_at:r()});const ec={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_IMPERSONATION:"fimp",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",INFORMATION:"i",MFA_REQUIRED:"mfar",MANAGEMENT_API_READ_OPERATION:"mgmt_api_read",FAILED_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_failed",SUCCESSFUL_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_succeeded",FAILED_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_failed",SUCCESSFUL_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_succeeded",ORGANIZATION_MEMBER_ADDED:"organization_member_added",PASSKEY_CHALLENGE_FAILED:"passkey_challenge_failed",PASSKEY_CHALLENGE_STARTED:"passkey_challenge_started",PRE_LOGIN_ASSESSMENT:"pla",BREACHED_PASSWORD:"pwd_leak",BREACHED_PASSWORD_ON_RESET:"reset_pwd_leak",SUCCESS_RESOURCE_CLEANUP:"resource_cleanup",RICH_CONSENTS_ACCESS_ERROR:"rich_consents_access_error",SUCCESS_LOGIN:"s",SUCCESS_API_OPERATION:"sapi",FAILED_API_OPERATION:"fapi",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"sepotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESS_IMPERSONATION:"simp",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_HOOK:"sh",SUCCESS_PASSWORD_MIGRATION:"spm",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},Ig=r().refine(e=>Object.values(ec).includes(e),{message:"Invalid log type"});(()=>{const e={};for(const[t,n]of Object.entries(ec))t.startsWith("SUCCESS_")||t.startsWith("SUCCESSFUL_")||t.startsWith("SUCCESSFULLY_")||t.endsWith("_SUCCEEDED")||t.endsWith("_COMPLETED")?e[n]="success":t.startsWith("FAILED_")||t.startsWith("ERROR_")||t.startsWith("BREACHED_")||t.startsWith("BLOCKED_")||t==="MFA_AUTH_FAILED"||t==="MFA_AUTH_REJECTED"||t==="MFA_RECOVERY_FAILED"||t==="MFA_ENROLLMENT_FAILED"||t==="EMAIL_VERIFICATION_FAILED"||t==="WEBAUTHN_CHALLENGE_FAILED"||t==="WEBAUTHN_ENROLLMENT_FAILED"||t==="PASSKEY_CHALLENGE_FAILED"||t==="FLOWS_EXECUTION_FAILED"||t==="FORMS_SUBMISSION_FAILED"||t==="CIBA_EXCHANGE_FAILED"||t==="CIBA_START_FAILED"||t==="ACTIONS_EXECUTION_FAILED"||t==="RICH_CONSENTS_ACCESS_ERROR"||t==="USER_CANCELED_DEVICE_CONFIRMATION"||t==="TOO_MANY_MFA_FAILURES"||t==="MFA_RECOVERY_RATE_LIMIT_EXCEED"||t==="API_LIMIT"||t==="MAX_AMOUNT_OF_AUTHENTICATORS"?e[n]="failure":t.startsWith("WARNING_")||t==="API_LIMIT_WARNING"||t==="DEPRECATION_NOTICE"||t==="PRE_LOGIN_ASSESSMENT"?e[n]="warning":t==="CODE_SENT"||t==="CODE_LINK_SENT"||t==="MFA_EMAIL_SENT"||t==="MFA_SMS_SENT"||t==="EMAIL_VERIFICATION_SENT"||t==="PUSH_NOTIFICATION_SENT"?e[n]="code_sent":t==="INFORMATION"||t==="INFORMATION_FROM_SS_SSO_OPERATION"||t==="MANAGEMENT_API_READ_OPERATION"||t==="APPI"||t==="ACLS_SUMMARY"||t==="ORGANIZATION_MEMBER_ADDED"?e[n]="info":e[n]="other";return e})();const kg=f({name:r(),version:r(),env:f({node:r().optional()}).optional()}),Ag=f({country_code:r().length(2),city_name:r(),latitude:r(),longitude:r(),time_zone:r(),continent_code:r()}),Tg=f({type:Ig,date:r(),description:r().optional(),ip:r().optional(),user_agent:r().optional(),details:M().optional(),isMobile:g(),user_id:r().optional(),user_name:r().optional(),connection:r().optional(),connection_id:r().optional(),client_id:r().optional(),client_name:r().optional(),audience:r().optional(),scope:r().optional(),strategy:r().optional(),strategy_type:r().optional(),hostname:r().optional(),auth0_client:kg.optional(),log_id:r().optional(),location_info:Ag.optional()});Tg.extend({log_id:r()});const Cg=O(["http","eventbridge","eventgrid","splunk","datadog","sumo"]),tc=O(["active","paused","suspended"]),zg=f({type:r(),name:r()}),Dg=f({name:r(),type:Cg,status:tc.optional(),sink:P(r(),$e()),filters:E(zg).optional(),isPriority:g().optional()});Dg.extend({id:r(),status:tc,created_at:r().optional(),updated_at:r().optional()});const xg=O(["auth0","cognito","okta","oidc"]),$g=f({domain:r(),client_id:r(),client_secret:r(),audience:r().optional(),scope:r().optional()}),Rg=f({id:r().optional(),name:r(),provider:xg,connection:r(),enabled:g().default(!0),credentials:$g});f({id:r(),created_at:r(),updated_at:r()}).extend(Rg.shape);const Lg=f({enabled:g().optional(),shields:E(r()).optional(),admin_notification_frequency:E(r()).optional(),method:r().optional(),stage:f({"pre-user-registration":f({shields:E(r()).optional()}).optional(),"pre-change-password":f({shields:E(r()).optional()}).optional()}).optional()}),Pg=f({enabled:g().optional(),shields:E(r()).optional(),allowlist:E(r()).optional(),mode:r().optional(),max_attempts:I().optional()}),Ug=f({enabled:g().optional(),shields:E(r()).optional(),allowlist:E(r()).optional(),stage:f({"pre-login":f({max_attempts:I().optional(),rate:I().optional()}).optional(),"pre-user-registration":f({max_attempts:I().optional(),rate:I().optional()}).optional()}).optional()}),Fg=f({breached_password_detection:Lg.optional(),brute_force_protection:Pg.optional(),suspicious_ip_throttling:Ug.optional()}),Zg=f({id:r().optional(),user_id:r(),password:r(),algorithm:O(["bcrypt","argon2id"]).default("argon2id"),is_current:g().default(!0)});Zg.extend({id:r(),created_at:r(),updated_at:r()});const nc=f({initial_user_agent:r().describe("First user agent of the device from which this user logged in"),initial_ip:r().describe("First IP address associated with this session"),initial_asn:r().describe("First autonomous system number associated with this session"),last_user_agent:r().describe("Last user agent of the device from which this user logged in"),last_ip:r().describe("Last IP address from which this user logged in"),last_asn:r().describe("Last autonomous system number from which this user logged in")}),Mg=f({id:r(),revoked_at:r().optional(),used_at:r().optional(),user_id:r().describe("The user ID associated with the session"),expires_at:r().optional(),login_session_id:r(),idle_expires_at:r().optional(),device:nc.describe("Metadata related to the device used in the session"),clients:E(r()).describe("List of client details for the session")});f({created_at:r(),updated_at:r(),authenticated_at:r(),last_interaction_at:r()}).extend(Mg.shape);f({kid:r().openapi({description:"The key id of the signing key"}),tenant_id:r().optional().openapi({description:"The tenant the key belongs to. Omitted means the key is shared / control-plane scoped."}),cert:r().openapi({description:"The public certificate of the signing key"}),fingerprint:r().openapi({description:"The cert fingerprint"}),thumbprint:r().openapi({description:"The cert thumbprint"}),pkcs7:r().optional().openapi({description:"The private key in pkcs7 format"}),current:g().optional().openapi({description:"True if the key is the current key"}),next:g().optional().openapi({description:"True if the key is the next key"}),previous:g().optional().openapi({description:"True if the key is the previous key"}),current_since:r().optional().openapi({description:"The date and time when the key became the current key"}),current_until:r().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:g().optional().openapi({description:"True if the key is revoked"}),revoked_at:r().optional().openapi({description:"The date and time when the key was revoked"}),connection:r().optional().openapi({description:"The connection identifier associated with the key"}),type:O(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});const jg=f({id:r().optional(),audience:r(),friendly_name:r(),picture_url:r().optional(),support_email:r().optional(),support_url:r().optional(),sender_email:r().email(),sender_name:r(),session_lifetime:I().optional(),idle_session_lifetime:I().optional(),ephemeral_session_lifetime:I().optional(),idle_ephemeral_session_lifetime:I().optional(),session_cookie:f({mode:O(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:E(r()).optional(),default_redirection_uri:r().optional(),default_client_id:r().optional(),enabled_locales:E(r()).optional(),default_directory:r().optional(),error_page:f({html:r().optional(),show_log_link:g().optional(),url:r().optional()}).nullish(),flags:f({allow_changing_enable_sso:g().optional(),allow_legacy_delegation_grant_types:g().optional(),allow_legacy_ro_grant_types:g().optional(),allow_legacy_tokeninfo_endpoint:g().optional(),change_pwd_flow_v1:g().optional(),custom_domains_provisioning:g().optional(),dashboard_insights_view:g().optional(),dashboard_log_streams_next:g().optional(),disable_clickjack_protection_headers:g().optional(),disable_fields_map_fix:g().optional(),disable_impersonation:g().optional(),disable_management_api_sms_obfuscation:g().optional(),enable_adfs_waad_email_verification:g().optional(),enable_apis_section:g().optional(),enable_client_connections:g().optional(),enable_custom_domain_in_emails:g().optional(),enable_dynamic_client_registration:g().optional(),dcr_require_initial_access_token:g().optional(),dcr_allowed_grant_types:E(r()).optional(),allow_http_return_to:E(r().refine(e=>{try{const t=new URL(e);return t.protocol==="http:"&&(t.pathname===""||t.pathname==="/")&&!t.search&&!t.hash&&e===t.origin}catch{return!1}},{message:"must be a fully-qualified http origin (scheme + host + port, no path)"})).optional(),enable_idtoken_api2:g().optional(),enable_legacy_logs_search_v2:g().optional(),enable_legacy_profile:g().optional(),enable_pipeline2:g().optional(),enable_public_signup_user_exists_error:g().optional(),enable_sso:g().optional(),enforce_client_authentication_on_passwordless_start:g().optional(),genai_trial:g().optional(),improved_signup_bot_detection_in_classic:g().optional(),mfa_show_factor_list_on_enrollment:g().optional(),no_disclose_enterprise_connections:g().optional(),remove_alg_from_jwks:g().optional(),revoke_refresh_token_grant:g().optional(),trust_azure_adfs_email_verified_connection_property:g().optional(),use_scope_descriptions_for_consent:g().optional(),inherit_global_permissions_in_organizations:g().optional()}).optional(),sandbox_version:r().optional(),legacy_sandbox_version:r().optional(),sandbox_versions_available:E(r()).optional(),change_password:f({enabled:g().optional(),html:r().optional()}).optional(),guardian_mfa_page:f({enabled:g().optional(),html:r().optional()}).optional(),device_flow:f({charset:O(["base20","digits"]).optional(),mask:r().max(20).optional()}).optional(),default_token_quota:f({clients:f({client_credentials:P(r(),M()).optional()}).optional(),organizations:f({client_credentials:P(r(),M()).optional()}).optional()}).nullish(),default_audience:r().optional(),default_organization:r().optional(),sessions:f({oidc_logout_prompt_enabled:g().optional()}).optional(),oidc_logout:f({rp_logout_end_session_endpoint_discovery:g().optional()}).optional(),allow_organization_name_in_authentication_api:g().optional(),customize_mfa_in_postlogin_action:g().optional(),acr_values_supported:E(r()).optional(),mtls:f({enable_endpoint_aliases:g().optional()}).nullish(),pushed_authorization_requests_supported:g().optional(),authorization_response_iss_parameter_supported:g().optional(),attack_protection:Fg.optional(),mfa:f({policy:O(["never","always"]).default("never").optional(),factors:f({sms:g().default(!1),otp:g().default(!1),email:g().default(!1),push_notification:g().default(!1),webauthn_roaming:g().default(!1),webauthn_platform:g().default(!1),recovery_code:g().default(!1),duo:g().default(!1)}).optional(),sms_provider:f({provider:O(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:f({sid:r().optional(),auth_token:r().optional(),from:r().optional(),messaging_service_sid:r().optional()}).optional(),phone_message:f({message:r().optional()}).optional()}).optional()});f({created_at:r().nullable().transform(e=>e??""),updated_at:r().nullable().transform(e=>e??"")}).extend(jg.shape).extend({id:r(),is_control_plane:g().optional()});f({access_token:r(),id_token:r().optional(),scope:r().optional(),state:r().optional(),refresh_token:r().optional(),token_type:r(),expires_in:I()});f({code:r(),state:r().optional()});const qg=f({button_border_radius:I(),button_border_weight:I(),buttons_style:O(["pill","rounded","sharp"]),input_border_radius:I(),input_border_weight:I(),inputs_style:O(["pill","rounded","sharp"]),show_widget_shadow:g(),widget_border_weight:I(),widget_corner_radius:I()}),Bg=f({base_focus_color:r(),base_hover_color:r(),body_text:r(),captcha_widget_theme:O(["auto","dark","light"]),error:r(),header:r(),icons:r(),input_background:r(),input_border:r(),input_filled_text:r(),input_labels_placeholders:r(),links_focused_components:r(),primary_button:r(),primary_button_label:r(),secondary_button_border:r(),secondary_button_label:r(),success:r(),widget_background:r(),widget_border:r()}),bt=f({bold:g(),size:I()}),Jg=f({body_text:bt,buttons_text:bt,font_url:r(),input_labels:bt,links:bt,links_style:O(["normal","underlined"]),reference_text_size:I(),subtitle:bt,title:bt}),Kg=f({background_color:r(),background_image_url:r(),page_layout:O(["center","left","right"]),logo_placement:O(["widget","chip","none"]).optional()}),Gg=f({header_text_alignment:O(["center","left","right"]),logo_height:I(),logo_position:O(["center","left","none","right"]),logo_url:r(),social_buttons_layout:O(["bottom","top"])}),Vg=f({borders:qg,colors:Bg,displayName:r(),fonts:Jg,page_background:Kg,widget:Gg});Vg.extend({themeId:r()});f({universal_login_experience:O(["new","classic"]).default("new"),identifier_first:g().default(!0),password_first:g().default(!1),webauthn_platform_first_factor:g()});f({name:r(),enabled:g().optional().default(!0),default_from_address:r().optional(),credentials:P(r(),$e()),settings:f({}).optional()});const Hg=O(["verify_email","verify_email_by_code","reset_email","reset_email_by_code","welcome_email","blocked_account","stolen_credentials","enrollment_email","mfa_oob_code","change_password","password_reset","user_invitation"]);f({template:Hg,body:r(),from:r(),subject:r(),syntax:A("liquid").default("liquid"),resultUrl:r().optional(),urlLifetimeInSeconds:I().int().nonnegative().optional(),includeEmailInRedirect:g().default(!1),enabled:g().default(!0)});const Wg=f({id:r(),login_id:r(),user_id:r(),client_id:r(),expires_at:r().optional(),idle_expires_at:r().optional(),last_exchanged_at:r().optional(),device:nc,resource_servers:E(f({audience:r(),scopes:r()})),rotating:g(),token_lookup:r().optional(),token_hash:r().optional(),family_id:r().optional(),rotated_to:r().optional(),rotated_at:r().optional()});Wg.extend({created_at:r(),revoked_at:r().optional()});f({to:r(),message:r()});f({name:r(),options:f({})});const Qg=f({value:r(),description:r().optional()}),Xg=f({token_dialect:O(["access_token","access_token_authz"]).optional(),enforce_policies:g().optional(),allow_skipping_userinfo:g().optional(),skip_userinfo:g().optional(),persist_client_authorization:g().optional(),enable_introspection_endpoint:g().optional(),mtls:f({bound_access_tokens:g().optional()}).optional()}),Yg=f({id:r().optional(),name:r(),identifier:r(),scopes:E(Qg).optional(),signing_alg:r().optional(),signing_secret:r().optional(),token_lifetime:I().default(86400),token_lifetime_for_web:I().default(7200),skip_consent_for_verifiable_first_party_clients:g().optional(),allow_offline_access:g().optional(),verificationKey:r().optional(),options:Xg.optional(),is_system:g().optional(),metadata:P(r(),M()).optional()});Yg.extend({created_at:r().optional(),updated_at:r().optional()});const eh=f({role_id:r(),resource_server_identifier:r(),permission_name:r()});eh.extend({created_at:r()});const th=f({user_id:r(),resource_server_identifier:r(),permission_name:r(),organization_id:r().optional()});th.extend({tenant_id:r(),created_at:r().optional()});f({user_id:r(),resource_server_identifier:r(),resource_server_name:r(),permission_name:r(),description:r().nullable().optional(),created_at:r().optional(),organization_id:r().optional()});const nh=f({user_id:r(),role_id:r(),organization_id:r().optional()});nh.extend({tenant_id:r(),created_at:r().optional()});const ih=f({id:r().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:r().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:r().max(255).optional().openapi({description:"The description of the role"}),is_system:g().optional(),metadata:P(r(),M()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})});ih.extend({id:r().openapi({description:"The unique identifier of the role"}),created_at:r().optional(),updated_at:r().optional()});const oh=f({logo_url:r().optional().openapi({description:"URL of the organization's logo"}),colors:f({primary:r().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:r().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),rh=f({connection_id:r().openapi({description:"ID of the connection"}),assign_membership_on_login:g().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:g().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:g().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),ah=f({client_credentials:f({enforce:g().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:I().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:I().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),sh=f({id:r().optional(),name:r().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:r().optional().openapi({description:"The display name of the organization"}),branding:oh,metadata:P(r(),M()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:E(rh).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:ah});sh.extend(Ge.shape).extend({id:r(),name:r().min(1).openapi({description:"The name of the organization"})});const lh=f({connection_id:r().openapi({description:"ID of the tenant-level connection to enable for the org."}),assign_membership_on_login:g().optional().default(!1),show_as_button:g().optional().default(!0),is_signup_enabled:g().optional().default(!0)});lh.extend({connection:f({name:r().optional(),strategy:r().optional()}).optional(),created_at:r().optional(),updated_at:r().optional()});const ch=f({user_id:r().openapi({description:"ID of the user"}),organization_id:r().openapi({description:"ID of the organization"})});ch.extend(Ge.shape).extend({id:r()});f({idle_session_lifetime:I().default(72),session_lifetime:I().default(168),session_cookie:f({mode:O(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:g().optional(),default_redirection_uri:r().optional(),enabled_locales:E(r()).optional(),default_directory:r().optional(),error_page:f({html:r().optional(),show_log_link:g().optional(),url:r().optional()}).optional(),flags:f({allow_legacy_delegation_grant_types:g().optional(),allow_legacy_ro_grant_types:g().optional(),allow_legacy_tokeninfo_endpoint:g().optional(),disable_clickjack_protection_headers:g().optional(),enable_apis_section:g().optional(),enable_client_connections:g().optional(),enable_custom_domain_in_emails:g().optional(),enable_dynamic_client_registration:g().optional(),enable_idtoken_api2:g().optional(),enable_legacy_logs_search_v2:g().optional(),enable_legacy_profile:g().optional(),enable_pipeline2:g().optional(),enable_public_signup_user_exists_error:g().optional(),use_scope_descriptions_for_consent:g().optional(),disable_management_api_sms_obfuscation:g().optional(),enable_adfs_waad_email_verification:g().optional(),revoke_refresh_token_grant:g().optional(),dashboard_log_streams_next:g().optional(),dashboard_insights_view:g().optional(),disable_fields_map_fix:g().optional(),mfa_show_factor_list_on_enrollment:g().optional()}).optional(),friendly_name:r().optional(),picture_url:r().optional(),support_email:r().optional(),support_url:r().optional(),sandbox_version:r().optional(),sandbox_versions_available:E(r()).optional(),change_password:f({enabled:g(),html:r()}).optional(),guardian_mfa_page:f({enabled:g(),html:r()}).optional(),default_audience:r().optional(),default_organization:r().optional(),sessions:f({oidc_logout_prompt_enabled:g().optional()}).optional(),mfa:f({policy:O(["never","always"]).default("never").optional(),factors:f({sms:g().default(!1),otp:g().default(!1),email:g().default(!1),push_notification:g().default(!1),webauthn_roaming:g().default(!1),webauthn_platform:g().default(!1),recovery_code:g().default(!1),duo:g().default(!1)}).optional(),sms_provider:f({provider:O(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:f({sid:r().optional(),auth_token:r().optional(),from:r().optional(),messaging_service_sid:r().optional()}).optional(),phone_message:f({message:r().optional()}).optional()}).optional()});f({date:r().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:I().openapi({description:"Number of logins on this date",example:150}),signups:I().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:I().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:r().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:r().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})});I().openapi({description:"Number of active users in the last 30 days",example:1234});O(["active-users","logins","signups","refresh-tokens","sessions"]);O(["hour","day","week","month"]);O(["time","connection","client_id","user_type","event"]);O(["password","social","passwordless","enterprise"]);const uh=f({name:r(),type:r()}),dh=f({elapsed:I(),rows_read:I().optional(),bytes_read:I().optional()});f({meta:E(uh),data:E(P(r(),M())),rows:I(),rows_before_limit_at_least:I().optional(),statistics:dh.optional()});const _h=O(["login","login-id","login-password","signup","signup-id","signup-password","reset-password","consent","mfa","mfa-push","mfa-otp","mfa-voice","mfa-phone","mfa-webauthn","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form","login-passwordless","mfa-login-options"]),ph=P(r(),P(r(),r())).openapi({type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}});f({prompt:_h,language:r(),custom_text:ph});const fh=O(["phone","totp","email","push","webauthn-roaming","webauthn-platform","passkey"]),ic=f({user_id:r(),type:fh,phone_number:r().optional(),totp_secret:r().optional(),credential_id:r().optional(),public_key:r().optional(),sign_count:I().int().nonnegative().optional(),credential_backed_up:g().optional(),transports:E(r()).optional(),friendly_name:r().optional(),confirmed:g().default(!1)});function oc(e,t){e.type==="phone"&&!e.phone_number&&t.addIssue({code:ft.custom,message:"phone_number is required when type is 'phone'",path:["phone_number"]}),e.type==="totp"&&!e.totp_secret&&t.addIssue({code:ft.custom,message:"totp_secret is required when type is 'totp'",path:["totp_secret"]}),["webauthn-roaming","webauthn-platform","passkey"].includes(e.type)&&(e.credential_id||t.addIssue({code:ft.custom,message:`credential_id is required when type is '${e.type}'`,path:["credential_id"]}),e.public_key||t.addIssue({code:ft.custom,message:`public_key is required when type is '${e.type}'`,path:["public_key"]}))}ic.superRefine(oc);ic.extend({id:r(),created_at:r(),updated_at:r()}).superRefine(oc);function gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hh(e){if(!e)return;const t=JSON.parse(e);return gh(t)?t:void 0}function kn(e){return e==null?void 0:new Date(e).toISOString()}function Yt(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t.getTime()}function An(e){const t=Ml.parse(e.type);return{id:e.id,token_hash:e.token_hash,type:t,client_id:e.client_id??void 0,sub:e.sub??void 0,constraints:hh(e.constraints),single_use:!!e.single_use,expires_at:kn(e.expires_at_ts),used_at:kn(e.used_at_ts),revoked_at:kn(e.revoked_at_ts),created_at:new Date(e.created_at_ts).toISOString()}}function mh(e){return{async create(t,n){const i=Date.now();return await e.insert(W).values({id:n.id,tenant_id:t,token_hash:n.token_hash,type:n.type,client_id:n.client_id??null,sub:n.sub??null,constraints:n.constraints?JSON.stringify(n.constraints):null,single_use:n.single_use?1:0,expires_at_ts:Yt(n.expires_at),created_at_ts:i}),{id:n.id,token_hash:n.token_hash,type:n.type,client_id:n.client_id,sub:n.sub,constraints:n.constraints,single_use:n.single_use,expires_at:n.expires_at,created_at:new Date(i).toISOString()}},async get(t,n){const i=await e.select().from(W).where(w(_(W.tenant_id,t),_(W.id,n))).get();return i?An(i):null},async getByHash(t,n){const i=await e.select().from(W).where(w(_(W.tenant_id,t),_(W.token_hash,n))).get();return i?An(i):null},async listByClient(t,n){return(await e.select().from(W).where(w(_(W.tenant_id,t),_(W.client_id,n))).orderBy(le(W.created_at_ts))).map(An)},async markUsed(t,n,i){return(await e.update(W).set({used_at_ts:Yt(i)}).where(w(_(W.tenant_id,t),_(W.id,n),xe(W.used_at_ts))).returning()).length>0},async revoke(t,n,i){return(await e.update(W).set({revoked_at_ts:Yt(i)}).where(w(_(W.tenant_id,t),_(W.id,n),xe(W.revoked_at_ts))).returning()).length>0},async revokeByClient(t,n,i){return(await e.update(W).set({revoked_at_ts:Yt(i)}).where(w(_(W.tenant_id,t),_(W.client_id,n),xe(W.revoked_at_ts))).returning()).length},async remove(t,n){return(await e.delete(W).where(w(_(W.tenant_id,t),_(W.id,n))).returning()).length>0}}}function Tn(e){const{tenant_id:t,...n}=e;return K(n)}function yh(e){return{async create(t,n){const i={...n,tenant_id:t,created_at:n.created_at||new Date().toISOString(),expires_at:n.expires_at};return await e.insert(ce).values(i),Tn(i)},async get(t,n,i){if(!t)throw new Error("tenant_id is required");const o=await e.select().from(ce).where(w(_(ce.tenant_id,t),_(ce.code_id,n),_(ce.code_type,i))).get();return o?Tn(o):null},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s}=n||{};let c=e.select().from(ce).where(_(ce.tenant_id,t)).$dynamic();if(s!=null&&s.sort_by){const h=ce[s.sort_by];h&&(c=c.orderBy(s.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(i*o).limit(o)).map(Tn);if(!a)return{codes:p};const[d]=await e.select({count:ye()}).from(ce).where(_(ce.tenant_id,t));return{codes:p,start:i*o,limit:o,length:Number((d==null?void 0:d.count)??0)}},async used(t,n){return(await e.update(ce).set({used_at:new Date().toISOString()}).where(w(_(ce.tenant_id,t),_(ce.code_id,n))).returning()).length>0},async consume(t,n){return(await e.update(ce).set({used_at:new Date().toISOString()}).where(w(_(ce.tenant_id,t),_(ce.code_id,n),xe(ce.used_at))).returning()).length>0},async remove(t,n){return(await e.delete(ce).where(w(_(ce.tenant_id,t),_(ce.code_id,n))).returning()).length>0}}}function wh(){const{customAlphabet:e}=require("nanoid");return`con_${e("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Cn(e){const{tenant_id:t,is_system:n,options:i,metadata:o,...a}=e;return K({...a,options:R(i,{}),metadata:R(o),is_system:n?!0:void 0})}function vh(e){return{async create(t,n){var a,s;const i=new Date().toISOString(),o={id:n.id||wh(),...n,tenant_id:t,options:JSON.stringify(n.options||{}),metadata:n.metadata?JSON.stringify(n.metadata):void 0,is_system:n.is_system?1:0,created_at:i,updated_at:i};try{await e.insert(fe).values(o)}catch(c){throw(a=c==null?void 0:c.message)!=null&&a.includes("UNIQUE constraint failed")||(s=c==null?void 0:c.message)!=null&&s.includes("duplicate key")?new lt(409,{message:"Connection already exists"}):c}return Cn(o)},async get(t,n){const i=await e.select().from(fe).where(w(_(fe.tenant_id,t),_(fe.id,n))).get();return i?Cn(i):null},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.strategy!==void 0&&(o.strategy=i.strategy),i.options!==void 0&&(o.options=JSON.stringify(i.options)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.display_name!==void 0&&(o.display_name=i.display_name),i.response_type!==void 0&&(o.response_type=i.response_type),i.response_mode!==void 0&&(o.response_mode=i.response_mode),await e.update(fe).set(o).where(w(_(fe.tenant_id,t),_(fe.id,n))),!0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{};let u=_(fe.tenant_id,t);if(c){const y=Ye(fe,c,["name"]);y&&(u=w(u,y))}let p=e.select().from(fe).where(u).$dynamic();if(s!=null&&s.sort_by){const y=fe[s.sort_by];y&&(p=p.orderBy(s.sort_order==="desc"?le(y):me(y)))}const h=(await p.offset(i*o).limit(o)).map(Cn);if(!a)return{connections:h};const[m]=await e.select({count:ye()}).from(fe).where(u);return{connections:h,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(t,n){return(await e.delete(fe).where(w(_(fe.tenant_id,t),_(fe.id,n))).returning()).length>0}}}function en(e){const{tenant_id:t,domain_metadata:n,...i}=e;return K({...i,primary:!!i.primary,domain_metadata:R(n)})}function bh(e){return{async create(t,n){const i=new Date().toISOString(),a={custom_domain_id:n.custom_domain_id||Le(),tenant_id:t,domain:n.domain,primary:n.primary??!1,status:n.status||"pending",type:n.type,origin_domain_name:n.origin_domain_name,verification:n.verification,custom_client_ip_header:n.custom_client_ip_header,tls_policy:n.tls_policy,domain_metadata:n.domain_metadata?JSON.stringify(n.domain_metadata):void 0,created_at:i,updated_at:i};return await e.insert(ze).values(a),en({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(ze).where(w(_(ze.tenant_id,t),_(ze.custom_domain_id,n))).get();return i?en(i):null},async getByDomain(t){const n=await e.select().from(ze).where(_(ze.domain,t)).get();return n?{...en(n),tenant_id:n.tenant_id}:null},async list(t){return(await e.select().from(ze).where(_(ze.tenant_id,t)).all()).map(en)},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.domain!==void 0&&(o.domain=i.domain),i.primary!==void 0&&(o.primary=i.primary),i.status!==void 0&&(o.status=i.status),i.type!==void 0&&(o.type=i.type),i.origin_domain_name!==void 0&&(o.origin_domain_name=i.origin_domain_name),i.verification!==void 0&&(o.verification=i.verification),i.custom_client_ip_header!==void 0&&(o.custom_client_ip_header=i.custom_client_ip_header),i.tls_policy!==void 0&&(o.tls_policy=i.tls_policy),i.domain_metadata!==void 0&&(o.domain_metadata=JSON.stringify(i.domain_metadata)),(await e.update(ze).set(o).where(w(_(ze.tenant_id,t),_(ze.custom_domain_id,n))).returning()).length>0},async remove(t,n){return(await e.delete(ze).where(w(_(ze.tenant_id,t),_(ze.custom_domain_id,n))).returning()).length>0}}}function Sh(e){return{async get(t,n,i){const o=await e.select().from(Oe).where(w(_(Oe.tenant_id,t),_(Oe.prompt,n),_(Oe.language,i))).get();if(!o)return null;try{return JSON.parse(o.custom_text)}catch{return null}},async set(t,n,i,o){const a=Date.now(),s=JSON.stringify(o);await e.insert(Oe).values({tenant_id:t,prompt:n,language:i,custom_text:s,created_at_ts:a,updated_at_ts:a}).onConflictDoUpdate({target:[Oe.tenant_id,Oe.prompt,Oe.language],set:{custom_text:s,updated_at_ts:a}})},async delete(t,n,i){await e.delete(Oe).where(w(_(Oe.tenant_id,t),_(Oe.prompt,n),_(Oe.language,i)))},async list(t){return await e.select({prompt:Oe.prompt,language:Oe.language}).from(Oe).where(_(Oe.tenant_id,t)).all()}}}function Nh(e){return{async create(t,n){const i=new Date().toISOString();await e.insert(rt).values({tenant_id:t,name:n.name,enabled:n.enabled,default_from_address:n.default_from_address,credentials:JSON.stringify(n.credentials||{}),settings:JSON.stringify(n.settings||{}),created_at:i,updated_at:i})},async get(t){const n=await e.select().from(rt).where(_(rt.tenant_id,t)).get();if(!n)return null;const{tenant_id:i,...o}=n;return K({...o,enabled:!!o.enabled,credentials:R(o.credentials,{}),settings:R(o.settings,{})})},async update(t,n){const i={updated_at:new Date().toISOString()};n.name!==void 0&&(i.name=n.name),n.enabled!==void 0&&(i.enabled=n.enabled),n.default_from_address!==void 0&&(i.default_from_address=n.default_from_address),n.credentials!==void 0&&(i.credentials=JSON.stringify(n.credentials)),n.settings!==void 0&&(i.settings=JSON.stringify(n.settings)),await e.update(rt).set(i).where(_(rt.tenant_id,t))},async remove(t){await e.delete(rt).where(_(rt.tenant_id,t))}}}function oo(e){const t={template:e.template,body:e.body,from:e.from,subject:e.subject,syntax:"liquid",includeEmailInRedirect:!!e.include_email_in_redirect,enabled:!!e.enabled};return K({...t,resultUrl:e.result_url??void 0,urlLifetimeInSeconds:e.url_lifetime_in_seconds??void 0})}function Eh(e){return{async get(t,n){const i=await e.select().from(Ze).where(w(_(Ze.tenant_id,t),_(Ze.template,n))).get();return i?oo(i):null},async list(t){return(await e.select().from(Ze).where(_(Ze.tenant_id,t)).all()).map(oo)},async create(t,n){const i=new Date().toISOString();return await e.insert(Ze).values({tenant_id:t,template:n.template,body:n.body,from:n.from,subject:n.subject,syntax:n.syntax,result_url:n.resultUrl??null,url_lifetime_in_seconds:n.urlLifetimeInSeconds??null,include_email_in_redirect:n.includeEmailInRedirect,enabled:n.enabled,created_at:i,updated_at:i}),n},async update(t,n,i){const o={updated_at:new Date().toISOString()};i.body!==void 0&&(o.body=i.body),i.from!==void 0&&(o.from=i.from),i.subject!==void 0&&(o.subject=i.subject),i.syntax!==void 0&&(o.syntax=i.syntax),i.resultUrl!==void 0&&(o.result_url=i.resultUrl),i.urlLifetimeInSeconds!==void 0&&(o.url_lifetime_in_seconds=i.urlLifetimeInSeconds),i.includeEmailInRedirect!==void 0&&(o.include_email_in_redirect=i.includeEmailInRedirect),i.enabled!==void 0&&(o.enabled=i.enabled);const a=await e.update(Ze).set(o).where(w(_(Ze.tenant_id,t),_(Ze.template,n))).run();return Number(a.changes??0)>0},async remove(t,n){const i=await e.delete(Ze).where(w(_(Ze.tenant_id,t),_(Ze.template,n))).run();return Number(i.changes??0)>0}}}function Oh(e){return{async create(t,n){const i=new Date().toISOString(),o=`af_${Le()}`;return await e.insert(Te).values({id:o,tenant_id:t,name:n.name,actions:JSON.stringify(n.actions||[]),created_at:i,updated_at:i}),{id:o,name:n.name,actions:n.actions||[],created_at:i,updated_at:i}},async get(t,n){const i=await e.select().from(Te).where(w(_(Te.tenant_id,t),_(Te.id,n))).get();if(!i)return null;const{tenant_id:o,actions:a,...s}=i;return K({...s,actions:R(a,[])})},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.actions!==void 0&&(o.actions=JSON.stringify(i.actions)),(await e.update(Te).set(o).where(w(_(Te.tenant_id,t),_(Te.id,n))).returning()).length===0?null:this.get(t,n)},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s}=n||{};let c=e.select().from(Te).where(_(Te.tenant_id,t)).$dynamic();if(s!=null&&s.sort_by){const h=Te[s.sort_by];h&&(c=c.orderBy(s.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(i*o).limit(o)).map(h=>{const{tenant_id:m,actions:y,...S}=h;return K({...S,actions:R(y,[])})});if(!a)return{flows:p};const[d]=await e.select({count:ye()}).from(Te).where(_(Te.tenant_id,t));return{flows:p,start:i*o,limit:o,length:Number((d==null?void 0:d.count)??0)}},async remove(t,n){return(await e.delete(Te).where(w(_(Te.tenant_id,t),_(Te.id,n))).returning()).length>0}}}const tn=["nodes","start","ending"];function Ih(e){return{async create(t,n){const i=new Date().toISOString(),o=Le(),a={id:o,tenant_id:t,name:n.name,messages:n.messages,languages:n.languages,translations:n.translations,style:n.style,created_at:i,updated_at:i};for(const s of tn)a[s]=JSON.stringify(n[s]||(s==="nodes"?[]:{}));return await e.insert(Ae).values(a),{id:o,...n,created_at:i,updated_at:i}},async get(t,n){const i=await e.select().from(Ae).where(w(_(Ae.tenant_id,t),_(Ae.id,n))).get();if(!i)return null;const{tenant_id:o,...a}=i,s={...a};for(const c of tn)s[c]=R(a[c]);return K(s)},async update(t,n,i){const o={updated_at:new Date().toISOString()};for(const[s,c]of Object.entries(i))c!==void 0&&(tn.includes(s)?o[s]=JSON.stringify(c):o[s]=c);return(await e.update(Ae).set(o).where(w(_(Ae.tenant_id,t),_(Ae.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s}=n||{};let c=e.select().from(Ae).where(_(Ae.tenant_id,t)).$dynamic();if(s!=null&&s.sort_by){const h=Ae[s.sort_by];h&&(c=c.orderBy(s.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(i*o).limit(o)).map(h=>{const{tenant_id:m,...y}=h,S={...y};for(const C of tn)S[C]=R(y[C]);return K(S)});if(!a)return{forms:p};const[d]=await e.select({count:ye()}).from(Ae).where(_(Ae.tenant_id,t));return{forms:p,start:i*o,limit:o,length:Number((d==null?void 0:d.count)??0)}},async remove(t,n){return(await e.delete(Ae).where(w(_(Ae.tenant_id,t),_(Ae.id,n))).returning()).length>0}}}function rc(e){if(e!=null){if(typeof e=="number")return new Date(e).toISOString();if(typeof e=="string"){if(e==="")return;const t=parseFloat(e);return!isNaN(t)&&/^\d+(\.\d+)?$/.test(e)?new Date(t).toISOString():e}}}function ri(e,t=new Date(0).toISOString()){return rc(e)??t}function te(e){if(!e||e==="")return null;const t=new Date(e);return isNaN(t.getTime())?null:t.getTime()}function Ht(e,t,n=[]){const i={};for(const o of t){const a=o.replace(/_ts$/,"");i[a]=ri(e[o])}for(const o of n){const a=o.replace(/_ts$/,"");i[a]=rc(e[o])}return i}const kh=Bc("0123456789abcdefghijklmnopqrstuvwxyz",17);function Ah(){return`hc_${kh()}`}function ro(e){const{created_at_ts:t,updated_at_ts:n,secrets:i,...o}=e,a=Ht({created_at_ts:t,updated_at_ts:n},["created_at_ts","updated_at_ts"]);return{...o,...a,secrets:i?JSON.parse(i):void 0}}function Th(e){return{async create(t,n){const i=Date.now(),a={id:Ah(),tenant_id:t,code:n.code,secrets:n.secrets?JSON.stringify(n.secrets):null,created_at_ts:i,updated_at_ts:i};return await e.insert(He).values(a),ro({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(He).where(w(_(He.tenant_id,t),_(He.id,n))).get();return i?ro(i):null},async update(t,n,i){const o={updated_at_ts:Date.now()};return i.code!==void 0&&(o.code=i.code),i.secrets!==void 0&&(o.secrets=JSON.stringify(i.secrets)),(await e.update(He).set(o).where(w(_(He.tenant_id,t),_(He.id,n))).returning()).length>0},async remove(t,n){return(await e.delete(He).where(w(_(He.tenant_id,t),_(He.id,n))).returning()).length>0}}}function Ch(){const{customAlphabet:e}=require("nanoid");return`h_${e("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function zh(e){if(!(typeof e!="string"||!e))try{const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function zn(e){const{tenant_id:t,created_at_ts:n,updated_at_ts:i,metadata:o,...a}=e,s=Ht({created_at_ts:n,updated_at_ts:i},["created_at_ts","updated_at_ts"]);return K({...a,enabled:!!a.enabled,synchronous:!!a.synchronous,metadata:zh(o),...s})}function Dh(e){return{async create(t,n){const i=Date.now(),a={hook_id:n.hook_id||Ch(),tenant_id:t,trigger_id:n.trigger_id,url:n.url,enabled:n.enabled??!0,synchronous:n.synchronous??!1,priority:n.priority,form_id:n.form_id,template_id:n.template_id,code_id:n.code_id,metadata:n.metadata?JSON.stringify(n.metadata):null,created_at_ts:i,updated_at_ts:i};return await e.insert(be).values(a),zn({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(be).where(w(_(be.tenant_id,t),_(be.hook_id,n))).get();return i?zn(i):null},async update(t,n,i){const o={updated_at_ts:Date.now()};return i.trigger_id!==void 0&&(o.trigger_id=i.trigger_id),i.url!==void 0&&(o.url=i.url),i.enabled!==void 0&&(o.enabled=i.enabled),i.synchronous!==void 0&&(o.synchronous=i.synchronous),i.priority!==void 0&&(o.priority=i.priority),i.form_id!==void 0&&(o.form_id=i.form_id),i.template_id!==void 0&&(o.template_id=i.template_id),i.code_id!==void 0&&(o.code_id=i.code_id),i.metadata!==void 0&&(o.metadata=i.metadata===null?null:JSON.stringify(i.metadata)),(await e.update(be).set(o).where(w(_(be.tenant_id,t),_(be.hook_id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{},u=c?Ye(be,c,["url","form_id","template_id","code_id"]):void 0,p=u?w(_(be.tenant_id,t),u):_(be.tenant_id,t);let d=e.select().from(be).where(p).$dynamic();const h=s!=null&&s.sort_by?be[s.sort_by]:void 0;h?d=d.orderBy((s==null?void 0:s.sort_order)==="desc"?le(h):me(h)):d=d.orderBy(le(be.priority),me(be.created_at_ts));const y=(await d.offset(i*o).limit(o)).map(zn);if(!a)return{hooks:y};const[S]=await e.select({count:ye()}).from(be).where(p);return{hooks:y,start:i*o,limit:o,length:Number((S==null?void 0:S.count)??0)}},async remove(t,n){return(await e.delete(be).where(w(_(be.tenant_id,t),_(be.hook_id,n))).returning()).length>0}}}function xh(){const{customAlphabet:e}=require("nanoid");return`inv_${e("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const ai=["inviter","invitee","app_metadata","user_metadata","roles"];function Dn(e){const{tenant_id:t,send_invitation_email:n,...i}=e,o={...i};for(const a of ai)o[a]=R(i[a],a==="roles"?[]:{});return o.send_invitation_email=!!n,K(o)}function $h(e){return{async create(t,n){var u,p;const i=n.id||xh(),o=n.ttl_sec||604800,a=new Date,s=new Date(a.getTime()+o*1e3).toISOString(),c={id:i,tenant_id:t,organization_id:n.organization_id,client_id:n.client_id,connection_id:n.connection_id,invitation_url:n.invitation_url,ticket_id:n.ticket_id,ttl_sec:o,send_invitation_email:n.send_invitation_email!==!1?1:0,created_at:a.toISOString(),expires_at:s};for(const d of ai)n[d]!==void 0&&(c[d]=JSON.stringify(n[d]));try{await e.insert(ke).values(c)}catch(d){throw(u=d==null?void 0:d.message)!=null&&u.includes("UNIQUE constraint failed")||(p=d==null?void 0:d.message)!=null&&p.includes("duplicate key")?new lt(409,{message:"Invite already exists"}):d}return Dn({...c,tenant_id:t})},async get(t,n){const i=await e.select().from(ke).where(w(_(ke.tenant_id,t),_(ke.id,n))).get();return i?Dn(i):null},async update(t,n,i){const o={};for(const s of ai)i[s]!==void 0&&(o[s]=JSON.stringify(i[s]));return i.connection_id!==void 0&&(o.connection_id=i.connection_id),i.ttl_sec!==void 0&&(o.ttl_sec=i.ttl_sec,o.expires_at=new Date(Date.now()+i.ttl_sec*1e3).toISOString()),(await e.update(ke).set(o).where(w(_(ke.tenant_id,t),_(ke.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s}=n||{};let c=e.select().from(ke).where(_(ke.tenant_id,t)).$dynamic();if(s!=null&&s.sort_by){const h=ke[s.sort_by];h&&(c=c.orderBy(s.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(i*o).limit(o)).map(Dn);if(!a)return{invites:p};const[d]=await e.select({count:ye()}).from(ke).where(_(ke.tenant_id,t));return{invites:p,start:i*o,limit:o,length:Number((d==null?void 0:d.count)??0)}},async remove(t,n){return(await e.delete(ke).where(w(_(ke.tenant_id,t),_(ke.id,n))).returning()).length>0}}}function Rh(e){return{async create(t){await e.insert(We).values({...t,created_at:new Date().toDateString()})},async list(t){const{page:n=0,per_page:i=50,include_totals:o=!1,sort:a}=t||{},s=new Date().toISOString();let c=e.select().from(We).where(Be(un(We.revoked_at,s),xe(We.revoked_at))).$dynamic();if(a!=null&&a.sort_by){const h=We[a.sort_by];h&&(c=c.orderBy(a.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(n*i).limit(i)).map(h=>{const{created_at:m,...y}=h;return K(y)});if(!o)return{signingKeys:p};const[d]=await e.select({count:ye()}).from(We).where(Be(un(We.revoked_at,s),xe(We.revoked_at)));return{signingKeys:p,start:n*i,limit:i,length:Rc((d==null?void 0:d.count)??0)}},async update(t,n){return(await e.update(We).set(n).where(_(We.kid,t)).returning()).length>0}}}const si="0123456789ABCDEFGHJKMNPQRSTVWXYZ",xn=si.length;function Lh(){let n=Date.now(),i="";for(let a=10;a>0;a--)i=si.charAt(n%xn)+i,n=Math.floor(n/xn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let a=0;a<16;a++)i+=si.charAt(o[a]%xn);return i}function ao(e){const{tenant_id:t,created_at_ts:n,updated_at_ts:i,expires_at_ts:o,state_data:a,auth_params:s,...c}=e,u=Ht({created_at_ts:n,updated_at_ts:i,expires_at_ts:o},["created_at_ts","updated_at_ts","expires_at_ts"]),p={};for(const[h,m]of Object.entries(c))m!=null&&(p[h]=m);const d=Ua(p,["auth_strategy"]);return K({...d,authParams:typeof s=="string"&&s.length>0?JSON.parse(s):{},...u,state_data:R(a)})}function Ph(e){return{async create(t,n){var s,c;const i=Date.now(),a={id:Lh(),tenant_id:t,session_id:n.session_id,csrf_token:n.csrf_token,auth_params:JSON.stringify(n.authParams||{}),authorization_url:n.authorization_url?n.authorization_url.substring(0,1024):void 0,ip:n.ip,useragent:n.useragent,auth0Client:n.auth0Client,state:n.state||"pending",state_data:n.state_data?JSON.stringify(n.state_data):void 0,failure_reason:n.failure_reason,user_id:n.user_id,auth_connection:n.auth_connection,auth_strategy_strategy:(s=n.auth_strategy)==null?void 0:s.strategy,auth_strategy_strategy_type:(c=n.auth_strategy)==null?void 0:c.strategy_type,authenticated_at:n.authenticated_at,created_at_ts:i,updated_at_ts:i,expires_at_ts:n.expires_at?te(n.expires_at):i+1e3*60*60*24};return await e.insert(Q).values(a),ao({...a,tenant_id:t})},async get(t,n){const i=t?w(_(Q.tenant_id,t),_(Q.id,n)):_(Q.id,n),o=await e.select().from(Q).where(i).get();return o?ao(o):null},async update(t,n,i){var a,s,c;const o={updated_at_ts:Date.now()};if(i.session_id!==void 0&&(o.session_id=i.session_id),i.state!==void 0&&(o.state=i.state),i.state_data!==void 0&&(o.state_data=JSON.stringify(i.state_data)),i.failure_reason!==void 0&&(o.failure_reason=i.failure_reason),i.user_id!==void 0&&(o.user_id=i.user_id),i.auth_connection!==void 0&&(o.auth_connection=i.auth_connection),i.auth_strategy!==void 0&&(o.auth_strategy_strategy=(a=i.auth_strategy)==null?void 0:a.strategy,o.auth_strategy_strategy_type=(s=i.auth_strategy)==null?void 0:s.strategy_type),i.authenticated_at!==void 0&&(o.authenticated_at=i.authenticated_at),i.authorization_url!==void 0&&(o.authorization_url=(c=i.authorization_url)==null?void 0:c.substring(0,1024)),i.expires_at!==void 0&&(o.expires_at_ts=te(i.expires_at)),i.authParams!==void 0){const u=await e.select({auth_params:Q.auth_params}).from(Q).where(w(_(Q.tenant_id,t),_(Q.id,n))).get(),p=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};o.auth_params=JSON.stringify({...p,...i.authParams})}return await e.update(Q).set(o).where(w(_(Q.tenant_id,t),_(Q.id,n))),!0},async remove(t,n){return(await e.delete(Q).where(w(_(Q.tenant_id,t),_(Q.id,n))).returning()).length>0}}}function $n(e){const{tenant_id:t,isMobile:n,auth0_client:i,details:o,country_code:a,city_name:s,latitude:c,longitude:u,time_zone:p,continent_code:d,scope:h,...m}=e,y={...m,isMobile:!!n,auth0_client:R(i),details:R(o),scope:h?h.split(","):void 0};return a&&(y.location_info=K({country_code:a,city_name:s,latitude:c,longitude:u,time_zone:p,continent_code:d})),K(y)}function Uh(e){return{async create(t,n){var a,s;const o={log_id:n.log_id||Le(),tenant_id:t,type:n.type,date:n.date||new Date().toISOString(),category:n.category,user_id:n.user_id,ip:n.ip,client_id:n.client_id,client_name:n.client_name,user_agent:(a=n.user_agent)==null?void 0:a.substring(0,256),description:(s=n.description)==null?void 0:s.substring(0,256),isMobile:n.isMobile?1:0,user_name:n.user_name,connection:n.connection,connection_id:n.connection_id,audience:n.audience,scope:Array.isArray(n.scope)?n.scope.join(","):n.scope,strategy:n.strategy,strategy_type:n.strategy_type,hostname:n.hostname,session_connection:n.session_connection};return n.auth0_client&&(o.auth0_client=JSON.stringify(n.auth0_client)),n.details&&(o.details=JSON.stringify(n.details).substring(0,8192)),n.location_info&&(o.country_code=n.location_info.country_code,o.city_name=n.location_info.city_name,o.latitude=n.location_info.latitude,o.longitude=n.location_info.longitude,o.time_zone=n.location_info.time_zone,o.continent_code=n.location_info.continent_code),await e.insert($).values(o),$n({...o,tenant_id:t})},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c,from_date:u,to_date:p}=n||{},d=[_($.tenant_id,t)];if(c){const L=Ye($,c,["user_id","ip","type","client_id"]);L&&d.push(L)}typeof u=="number"&&Number.isFinite(u)&&d.push(Tt($.date,new Date(Math.floor(u)*1e3).toISOString())),typeof p=="number"&&Number.isFinite(p)&&d.push(Qe($.date,new Date((Math.floor(p)+1)*1e3).toISOString()));const h=w(...d);let m=e.select().from($).where(h).$dynamic();if(s!=null&&s.sort_by){const L=$[s.sort_by];L&&(m=m.orderBy(s.sort_order==="desc"?le(L):me(L)))}else m=m.orderBy(le($.date));const S=(await m.offset(i*o).limit(o)).map($n);if(!a)return{logs:S};const[C]=await e.select({count:ye()}).from($).where(h);return{logs:S,start:i*o,limit:o,length:Number((C==null?void 0:C.count)??0)}},async get(t,n){const i=await e.select().from($).where(w(_($.tenant_id,t),_($.log_id,n))).get();return i?$n(i):null}}}const li="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Rn=li.length;function Fh(){let n=Date.now(),i="";for(let a=10;a>0;a--)i=li.charAt(n%Rn)+i,n=Math.floor(n/Rn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let a=0;a<16;a++)i+=li.charAt(o[a]%Rn);return i}function nn(e){const{tenant_id:t,created_at_ts:n,updated_at_ts:i,credential_backed_up:o,confirmed:a,transports:s,...c}=e;return K({...c,confirmed:!!a,credential_backed_up:o!=null?!!o:void 0,transports:R(s),created_at:ri(n),updated_at:ri(i)})}function Zh(e){return{async create(t,n){const i=Date.now(),a={id:n.id||Fh(),tenant_id:t,user_id:n.user_id,type:n.type,phone_number:n.phone_number,totp_secret:n.totp_secret,credential_id:n.credential_id,public_key:n.public_key,sign_count:n.sign_count,credential_backed_up:n.credential_backed_up!=null?n.credential_backed_up?1:0:null,transports:n.transports?JSON.stringify(n.transports):null,friendly_name:n.friendly_name,confirmed:n.confirmed?1:0,created_at_ts:i,updated_at_ts:i};return await e.insert(pe).values(a),nn({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(pe).where(w(_(pe.tenant_id,t),_(pe.id,n))).get();return i?nn(i):null},async getByCredentialId(t,n){const i=await e.select().from(pe).where(w(_(pe.tenant_id,t),_(pe.credential_id,n))).get();return i?nn(i):null},async list(t,n){return(await e.select().from(pe).where(w(_(pe.tenant_id,t),_(pe.user_id,n))).all()).map(nn)},async update(t,n,i){const o={updated_at_ts:Date.now()};i.type!==void 0&&(o.type=i.type),i.phone_number!==void 0&&(o.phone_number=i.phone_number),i.totp_secret!==void 0&&(o.totp_secret=i.totp_secret),i.credential_id!==void 0&&(o.credential_id=i.credential_id),i.public_key!==void 0&&(o.public_key=i.public_key),i.sign_count!==void 0&&(o.sign_count=i.sign_count),i.credential_backed_up!==void 0&&(o.credential_backed_up=i.credential_backed_up?1:0),i.transports!==void 0&&(o.transports=JSON.stringify(i.transports)),i.friendly_name!==void 0&&(o.friendly_name=i.friendly_name),i.confirmed!==void 0&&(o.confirmed=i.confirmed?1:0),await e.update(pe).set(o).where(w(_(pe.tenant_id,t),_(pe.id,n)));const a=await this.get(t,n);if(!a)throw new Error(`Authentication method ${n} not found after update`);return a},async remove(t,n){return(await e.delete(pe).where(w(_(pe.tenant_id,t),_(pe.id,n))).returning()).length>0}}}function Mh(){const{customAlphabet:e}=require("nanoid");return`org_${e("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Ln(e){const{tenant_id:t,branding:n,metadata:i,enabled_connections:o,token_quota:a,...s}=e;return K({...s,branding:R(n,{}),metadata:R(i,{}),enabled_connections:R(o,[]),token_quota:R(a,{})})}function jh(e){return{async create(t,n){var s,c;const i=new Date().toISOString(),a={id:n.id||Mh(),tenant_id:t,name:n.name,display_name:n.display_name,branding:JSON.stringify(n.branding||{}),metadata:JSON.stringify(n.metadata||{}),enabled_connections:JSON.stringify(n.enabled_connections||[]),token_quota:JSON.stringify(n.token_quota||{}),created_at:i,updated_at:i};try{await e.insert(Y).values(a)}catch(u){throw(s=u==null?void 0:u.message)!=null&&s.includes("UNIQUE constraint failed")||(c=u==null?void 0:u.message)!=null&&c.includes("AlreadyExists")?new lt(409,{message:"Organization already exists"}):u}return Ln({...a,tenant_id:t})},async get(t,n){let i=await e.select().from(Y).where(w(_(Y.tenant_id,t),_(Y.id,n))).get();return i||(i=await e.select().from(Y).where(w(_(Y.tenant_id,t),_(Y.name,n))).get()),i?Ln(i):null},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.display_name!==void 0&&(o.display_name=i.display_name),i.branding!==void 0&&(o.branding=JSON.stringify(i.branding)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.enabled_connections!==void 0&&(o.enabled_connections=JSON.stringify(i.enabled_connections)),i.token_quota!==void 0&&(o.token_quota=JSON.stringify(i.token_quota)),(await e.update(Y).set(o).where(w(_(Y.tenant_id,t),_(Y.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{};let u=e.select().from(Y).where(_(Y.tenant_id,t)).$dynamic();if(c&&(u=u.where(Be(St(Y.name,`%${c}%`),St(Y.display_name,`%${c}%`)))),s!=null&&s.sort_by){const y=Y[s.sort_by];y&&(u=u.orderBy(s.sort_order==="desc"?le(y):me(y)))}const d=(await u.offset(i*o).limit(o)).map(Ln);if(!a)return{organizations:d};const h=[_(Y.tenant_id,t)];c&&h.push(Be(St(Y.name,`%${c}%`),St(Y.display_name,`%${c}%`)));const[m]=await e.select({count:ye()}).from(Y).where(w(...h));return{organizations:d,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(t,n){return(await e.delete(Y).where(w(_(Y.tenant_id,t),_(Y.id,n))).returning()).length>0}}}function Pn(e){const{tenant_id:t,is_current:n,...i}=e;return{...i,is_current:!!n}}function qh(e){return{async create(t,n){const i=new Date().toISOString(),o=n.id||Le();n.is_current!==!1&&await e.update(oe).set({is_current:0}).where(w(_(oe.tenant_id,t),_(oe.user_id,n.user_id)));const a={id:o,tenant_id:t,user_id:n.user_id,password:n.password,algorithm:n.algorithm||"bcrypt",is_current:n.is_current!==!1?1:0,created_at:i,updated_at:i};return await e.insert(oe).values(a),Pn({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(oe).where(w(_(oe.tenant_id,t),_(oe.user_id,n),_(oe.is_current,1))).get();return i?Pn(i):null},async list(t,n,i){let o=e.select().from(oe).where(w(_(oe.tenant_id,t),_(oe.user_id,n))).orderBy(le(oe.created_at)).$dynamic();return i&&(o=o.limit(i)),(await o).map(Pn)},async update(t,n){const i={updated_at:new Date().toISOString()};return n.password!==void 0&&(i.password=n.password),n.algorithm!==void 0&&(i.algorithm=n.algorithm),n.is_current!==void 0&&(i.is_current=n.is_current?1:0),n.id?await e.update(oe).set(i).where(w(_(oe.tenant_id,t),_(oe.id,n.id))):await e.update(oe).set(i).where(w(_(oe.tenant_id,t),_(oe.user_id,n.user_id),_(oe.is_current,1))),!0}}}function Bh(e){return{async get(t){const n=await e.select().from(Rt).where(_(Rt.tenant_id,t)).get();return n?{universal_login_experience:n.universal_login_experience,identifier_first:!!n.identifier_first,password_first:!!n.password_first,webauthn_platform_first_factor:!!n.webauthn_platform_first_factor}:{universal_login_experience:"new",identifier_first:!0,password_first:!1,webauthn_platform_first_factor:!1}},async set(t,n){await e.insert(Rt).values({tenant_id:t,universal_login_experience:n.universal_login_experience,identifier_first:n.identifier_first,password_first:n.password_first,webauthn_platform_first_factor:n.webauthn_platform_first_factor}).onConflictDoUpdate({target:Rt.tenant_id,set:{universal_login_experience:n.universal_login_experience,identifier_first:n.identifier_first,password_first:n.password_first,webauthn_platform_first_factor:n.webauthn_platform_first_factor}})}}}function on(e){const{tenant_id:t,created_at_ts:n,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:a,revoked_at_ts:s,rotated_at_ts:c,device:u,resource_servers:p,rotating:d,...h}=e,m=Ht({created_at_ts:n,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:a,revoked_at_ts:s,rotated_at_ts:c},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts","rotated_at_ts"]);return K({...h,...m,rotating:!!d,device:R(u,{}),resource_servers:R(p,[])})}function Jh(e,t){return Math.max(e??0,t??0)}function Kh(e){return{async create(t,n){const i=Date.now(),o={id:n.id||Le(),tenant_id:t,client_id:n.client_id,login_id:n.login_id,user_id:n.user_id,device:JSON.stringify(n.device||{}),resource_servers:JSON.stringify(n.resource_servers||[]),rotating:n.rotating??!1,token_lookup:n.token_lookup??null,token_hash:n.token_hash??null,family_id:n.family_id??null,rotated_to:n.rotated_to??null,rotated_at_ts:te(n.rotated_at),created_at_ts:i,expires_at_ts:te(n.expires_at),idle_expires_at_ts:te(n.idle_expires_at),last_exchanged_at_ts:te(n.last_exchanged_at)};await e.run(k`BEGIN`);try{await e.insert(J).values(o);const a=Jh(o.expires_at_ts,o.idle_expires_at_ts);a>0&&o.login_id&&await e.update(Q).set({expires_at_ts:a,updated_at_ts:i}).where(w(_(Q.tenant_id,t),_(Q.id,o.login_id),Qe(Q.expires_at_ts,a))),await e.run(k`COMMIT`)}catch(a){throw await e.run(k`ROLLBACK`),a}return on({...o,tenant_id:t})},async get(t,n){const i=await e.select().from(J).where(w(_(J.tenant_id,t),_(J.id,n))).get();return i?on(i):null},async getByLookup(t,n){const i=await e.select().from(J).where(w(_(J.tenant_id,t),_(J.token_lookup,n))).get();return i?on(i):null},async update(t,n,i,o){const a={};i.device!==void 0&&(a.device=JSON.stringify(i.device)),i.resource_servers!==void 0&&(a.resource_servers=JSON.stringify(i.resource_servers)),i.rotating!==void 0&&(a.rotating=i.rotating),i.token_lookup!==void 0&&(a.token_lookup=i.token_lookup),i.token_hash!==void 0&&(a.token_hash=i.token_hash),i.family_id!==void 0&&(a.family_id=i.family_id),i.rotated_to!==void 0&&(a.rotated_to=i.rotated_to),i.rotated_at!==void 0&&(a.rotated_at_ts=te(i.rotated_at)),i.expires_at!==void 0&&(a.expires_at_ts=te(i.expires_at)),i.idle_expires_at!==void 0&&(a.idle_expires_at_ts=te(i.idle_expires_at)),i.last_exchanged_at!==void 0&&(a.last_exchanged_at_ts=te(i.last_exchanged_at)),i.revoked_at!==void 0&&(a.revoked_at_ts=te(i.revoked_at));const s=o==null?void 0:o.loginSessionBump,c=s?te(s.expires_at):null,u=await e.update(J).set(a).where(w(_(J.tenant_id,t),_(J.id,n))).returning();return s!=null&&s.login_id&&c&&c>0&&await e.update(Q).set({expires_at_ts:c,updated_at_ts:Date.now()}).where(w(_(Q.tenant_id,t),_(Q.id,s.login_id),Qe(Q.expires_at_ts,c))).catch(()=>{}),u.length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{};let u=e.select().from(J).where(_(J.tenant_id,t)).$dynamic();if(c){const m=Ye(J,c,["user_id"]);m&&(u=u.where(w(_(J.tenant_id,t),m)))}if(s!=null&&s.sort_by){const m=J[s.sort_by];m&&(u=u.orderBy(s.sort_order==="desc"?le(m):me(m)))}const d=(await u.offset(i*o).limit(o)).map(on);if(!a)return{refresh_tokens:d};const[h]=await e.select({count:ye()}).from(J).where(_(J.tenant_id,t));return{refresh_tokens:d,start:i*o,limit:o,length:Number((h==null?void 0:h.count)??0)}},async remove(t,n){return(await e.delete(J).where(w(_(J.tenant_id,t),_(J.id,n))).returning()).length>0},async revokeByLoginSession(t,n,i){return(await e.update(J).set({revoked_at_ts:te(i)}).where(w(_(J.tenant_id,t),_(J.login_id,n),xe(J.revoked_at_ts))).returning()).length},async revokeFamily(t,n,i){return(await e.update(J).set({revoked_at_ts:te(i)}).where(w(_(J.tenant_id,t),_(J.family_id,n),xe(J.revoked_at_ts))).returning()).length}}}function Gh(){const{customAlphabet:e}=require("nanoid");return`api_${e("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const ci=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],so=new Set(["id","tenant_id","identifier","name","scopes","signing_alg","signing_secret","token_lifetime","token_lifetime_for_web","skip_consent_for_verifiable_first_party_clients","allow_offline_access","verification_key","options","is_system","metadata","created_at","updated_at"]);function Un(e){const{tenant_id:t,verification_key:n,scopes:i,options:o,metadata:a,...s}=e,c={...s};c.scopes=R(i,[]),c.options=R(o,{}),c.metadata=R(a),n!==void 0&&(c.verificationKey=n);for(const u of ci)s[u]!==void 0&&s[u]!==null&&(c[u]=!!s[u]);return K(c)}function Vh(e){return{async create(t,n){const i=new Date().toISOString(),a={id:n.id||Gh(),tenant_id:t,identifier:n.identifier,name:n.name,signing_alg:n.signing_alg,signing_secret:n.signing_secret,token_lifetime:n.token_lifetime,token_lifetime_for_web:n.token_lifetime_for_web,scopes:JSON.stringify(n.scopes||[]),options:JSON.stringify(n.options||{}),metadata:n.metadata?JSON.stringify(n.metadata):void 0,verification_key:n.verificationKey||n.verification_key,created_at:i,updated_at:i};for(const s of ci)n[s]!==void 0&&(a[s]=n[s]?1:0);return a.is_system===void 0&&(a.is_system=0),await e.insert(ee).values(a),Un({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(ee).where(w(_(ee.tenant_id,t),_(ee.id,n))).get();return i?Un(i):null},async update(t,n,i){const o={updated_at:new Date().toISOString()};i.name!==void 0&&(o.name=i.name),i.identifier!==void 0&&(o.identifier=i.identifier),i.signing_alg!==void 0&&(o.signing_alg=i.signing_alg),i.signing_secret!==void 0&&(o.signing_secret=i.signing_secret),i.token_lifetime!==void 0&&(o.token_lifetime=i.token_lifetime),i.token_lifetime_for_web!==void 0&&(o.token_lifetime_for_web=i.token_lifetime_for_web),i.scopes!==void 0&&(o.scopes=JSON.stringify(i.scopes)),i.options!==void 0&&(o.options=k`json_patch(COALESCE(${ee.options}, '{}'), ${JSON.stringify(i.options)})`),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.verificationKey!==void 0&&(o.verification_key=i.verificationKey);for(const s of ci)i[s]!==void 0&&(o[s]=i[s]?1:0);return(await e.update(ee).set(o).where(w(_(ee.tenant_id,t),_(ee.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{},u=Math.max(0,Math.floor(Number(i)||0)),p=Math.min(Math.max(1,Math.floor(Number(o)||50)),500),d=[_(ee.tenant_id,t)];if(c){const C=c.match(/^([^:]+):(.+)$/);if(C){const[,L,x]=C,G=L==null?void 0:L.startsWith("-"),X=G?L==null?void 0:L.substring(1):L;if(X&&so.has(X)&&!G){const V=ee[X];d.push(St(V,`%${x}%`))}}}let h=e.select().from(ee).where(w(...d)).$dynamic();if(s!=null&&s.sort_by&&so.has(s.sort_by)){const C=ee[s.sort_by];h=h.orderBy(s.sort_order==="desc"?le(C):me(C))}const y=(await h.offset(u*p).limit(p)).map(Un);if(!a)return{resource_servers:y};const[S]=await e.select({count:ye()}).from(ee).where(w(...d));return{resource_servers:y,start:u*p,limit:p,length:Number((S==null?void 0:S.count)??0)}},async remove(t,n){return(await e.delete(ee).where(w(_(ee.tenant_id,t),_(ee.id,n))).returning()).length>0}}}function Hh(e){return{async assign(t,n,i){const o=new Date().toISOString();return await e.insert(Fe).values(i.map(a=>({tenant_id:t,role_id:n,resource_server_identifier:a.resource_server_identifier,permission_name:a.permission_name,created_at:o}))).onConflictDoNothing(),!0},async list(t,n,i){const o=await e.select({resource_server_identifier:Fe.resource_server_identifier,permission_name:Fe.permission_name,created_at:Fe.created_at}).from(Fe).where(w(_(Fe.tenant_id,t),_(Fe.role_id,n))).all(),a=[...new Set(o.map(c=>c.resource_server_identifier))],s=new Map;if(a.length>0){const c=await e.select({identifier:ee.identifier,name:ee.name}).from(ee).where(w(_(ee.tenant_id,t),Re(ee.identifier,a))).all();for(const u of c)s.set(u.identifier,u.name)}return o.map(c=>({...c,resource_server_name:s.get(c.resource_server_identifier)||c.resource_server_identifier}))},async remove(t,n,i){const o=i.map(s=>w(_(Fe.resource_server_identifier,s.resource_server_identifier),_(Fe.permission_name,s.permission_name)));return(await e.delete(Fe).where(w(_(Fe.tenant_id,t),_(Fe.role_id,n),Be(...o))).returning()).length>0}}}function Wh(e){return{async create(t,n,i,o){var a,s;try{await e.insert(je).values({tenant_id:t,user_id:n,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name,organization_id:o||"",created_at:new Date().toISOString()})}catch(c){if((a=c==null?void 0:c.message)!=null&&a.includes("UNIQUE constraint")||(s=c==null?void 0:c.message)!=null&&s.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw c}return!0},async list(t,n,i,o){let a=[_(je.tenant_id,t),_(je.user_id,n)];o&&a.push(_(je.organization_id,o));const s=await e.select().from(je).where(w(...a)).all();return await Promise.all(s.map(async u=>{const p=await e.select({name:ee.name}).from(ee).where(w(_(ee.tenant_id,t),_(ee.identifier,u.resource_server_identifier))).get();return{resource_server_identifier:u.resource_server_identifier,permission_name:u.permission_name,resource_server_name:(p==null?void 0:p.name)||u.resource_server_identifier,organization_id:u.organization_id===""?void 0:u.organization_id}}))},async remove(t,n,i,o){return(await e.delete(je).where(w(_(je.tenant_id,t),_(je.user_id,n),_(je.resource_server_identifier,i.resource_server_identifier),_(je.permission_name,i.permission_name),_(je.organization_id,o||""))).returning()).length>0}}}function Fn(e){const{tenant_id:t,is_system:n,metadata:i,...o}=e;return K({...o,is_system:n?!0:void 0,metadata:R(i)})}function Qh(e){return{async create(t,n){const i=new Date().toISOString(),a={id:n.id||Le(),tenant_id:t,name:n.name,description:n.description,is_system:n.is_system?1:0,metadata:n.metadata?JSON.stringify(n.metadata):void 0,created_at:i,updated_at:i};return await e.insert(_e).values(a),Fn({...a,tenant_id:t})},async get(t,n){const i=await e.select().from(_e).where(w(_(_e.tenant_id,t),_(_e.id,n))).get();return i?Fn(i):null},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.description!==void 0&&(o.description=i.description),i.is_system!==void 0&&(o.is_system=i.is_system?1:0),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),(await e.update(_e).set(o).where(w(_(_e.tenant_id,t),_(_e.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{},u=c?Ye(_e,c,["name"]):void 0,p=u?w(_(_e.tenant_id,t),u):_(_e.tenant_id,t);let d=e.select().from(_e).where(p).$dynamic();if(s!=null&&s.sort_by){const S=_e[s.sort_by];S&&(d=d.orderBy(s.sort_order==="desc"?le(S):me(S)))}const m=(await d.offset(i*o).limit(o)).map(Fn);if(!a)return{roles:m};const[y]=await e.select({count:ye()}).from(_e).where(p);return{roles:m,start:i*o,limit:o,length:Number((y==null?void 0:y.count)??0)}},async remove(t,n){return(await e.delete(_e).where(w(_(_e.tenant_id,t),_(_e.id,n))).returning()).length>0}}}const Xh=["created_at_ts","updated_at_ts"],Yh=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function Zn(e){const{tenant_id:t,created_at_ts:n,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:a,authenticated_at_ts:s,last_interaction_at_ts:c,used_at_ts:u,revoked_at_ts:p,device:d,clients:h,...m}=e,y=Ht({created_at_ts:n,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:a,authenticated_at_ts:s,last_interaction_at_ts:c,used_at_ts:u,revoked_at_ts:p},[...Xh],[...Yh]);return K({...m,...y,device:R(d,{}),clients:R(h,[])})}function em(e){return{async create(t,n){const i=Date.now(),o={id:n.id||Le(),tenant_id:t,user_id:n.user_id,login_session_id:n.login_session_id,device:JSON.stringify(n.device||{}),clients:JSON.stringify(n.clients||[]),created_at_ts:i,updated_at_ts:i,expires_at_ts:te(n.expires_at),idle_expires_at_ts:te(n.idle_expires_at),authenticated_at_ts:n.authenticated_at?te(n.authenticated_at):i,last_interaction_at_ts:n.last_interaction_at?te(n.last_interaction_at):i,used_at_ts:te(n.used_at),revoked_at_ts:te(n.revoked_at)};return await e.insert(se).values(o),Zn({...o,tenant_id:t})},async get(t,n){const i=await e.select().from(se).where(w(_(se.tenant_id,t),_(se.id,n))).get();return i?Zn(i):null},async update(t,n,i){const o={updated_at_ts:Date.now()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.login_session_id!==void 0&&(o.login_session_id=i.login_session_id),i.device!==void 0&&(o.device=JSON.stringify(i.device)),i.clients!==void 0&&(o.clients=JSON.stringify(i.clients)),i.expires_at!==void 0&&(o.expires_at_ts=te(i.expires_at)),i.idle_expires_at!==void 0&&(o.idle_expires_at_ts=te(i.idle_expires_at)),i.authenticated_at!==void 0&&(o.authenticated_at_ts=te(i.authenticated_at)),i.last_interaction_at!==void 0&&(o.last_interaction_at_ts=te(i.last_interaction_at)),i.used_at!==void 0&&(o.used_at_ts=te(i.used_at)),i.revoked_at!==void 0&&(o.revoked_at_ts=te(i.revoked_at)),(await e.update(se).set(o).where(w(_(se.tenant_id,t),_(se.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,sort:s,q:c}=n||{},u=c?Ye(se,c,["user_id"]):void 0,p=u?w(_(se.tenant_id,t),u):_(se.tenant_id,t);let d=e.select().from(se).where(p).$dynamic();if(s!=null&&s.sort_by){const S=se[s.sort_by];S&&(d=d.orderBy(s.sort_order==="desc"?le(S):me(S)))}const m=(await d.offset(i*o).limit(o)).map(Zn);if(!a)return{sessions:m};const[y]=await e.select({count:ye()}).from(se).where(p);return{sessions:m,start:i*o,limit:o,length:Number((y==null?void 0:y.count)??0)}},async remove(t,n){return(await e.delete(se).where(w(_(se.tenant_id,t),_(se.id,n))).returning()).length>0}}}const ac=["session_cookie","enabled_locales","error_page","flags","sandbox_versions_available","change_password","guardian_mfa_page","sessions","oidc_logout","device_flow","default_token_quota","allowed_logout_urls","acr_values_supported","mtls","mfa"],sc=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function lo(e){const t={...e};for(const n of ac)typeof t[n]=="string"&&(t[n]=R(t[n]));for(const n of sc)t[n]!==void 0&&t[n]!==null&&(t[n]=t[n]===1);return K(t)}function co(e){const t={...e};xc(e,ac,t);for(const n of sc)e[n]!==void 0&&(t[n]=e[n]?1:0);return Pa(t)}function tm(e){return{async create(t){var o,a;const n={id:t.id||Le(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...t},i=co(n);try{await e.insert(F).values(i)}catch(s){throw(o=s==null?void 0:s.message)!=null&&o.includes("UNIQUE constraint failed")||(a=s==null?void 0:s.message)!=null&&a.includes("duplicate key")||(s==null?void 0:s.code)==="SQLITE_CONSTRAINT"?new lt(409,{message:`Tenant with ID '${n.id}' already exists`}):s}return n},async get(t){const n=await e.select().from(F).where(_(F.id,t)).get();return n?lo(n):null},async list(t){const{page:n=0,per_page:i=50,include_totals:o=!1,sort:a,q:s}=t||{};let c=e.select().from(F).$dynamic();if(s){const h=Ye(F,s,["friendly_name"]);h&&(c=c.where(h))}if(a!=null&&a.sort_by){const h=F[a.sort_by];h&&(c=c.orderBy(a.sort_order==="desc"?le(h):me(h)))}const p=(await c.offset(n*i).limit(i)).map(lo);if(!o)return{tenants:p};const[d]=await e.select({count:ye()}).from(F);return{tenants:p,start:n*i,limit:i,length:Number((d==null?void 0:d.count)??0)}},async update(t,n){const i=co({...n,id:t,updated_at:new Date().toISOString()});await e.update(F).set(i).where(_(F.id,t))},async remove(t){return(await e.delete(F).where(_(F.id,t)).returning()).length>0}}}const nm=["colors","borders","fonts","page_background","widget"];function uo(e){const{tenant_id:t,...n}=e,i=Ua(n,nm);return i.borders&&(i.borders.show_widget_shadow=!!i.borders.show_widget_shadow),i.fonts&&(i.fonts.links_bold=!!i.fonts.links_bold,i.fonts.subtitle_bold=!!i.fonts.subtitle_bold,i.fonts.title_bold=!!i.fonts.title_bold),K(i)}function im(e){return{async create(t,n,i){const o=new Date().toISOString(),a=i||Le(),c={...Jn(n),tenant_id:t,themeId:a,created_at:o,updated_at:o};return await e.insert(Ve).values(c),uo({...c,tenant_id:t})},async get(t,n){const i=await e.select().from(Ve).where(w(_(Ve.tenant_id,t),_(Ve.themeId,n))).get();return i?uo(i):null},async update(t,n,i){const o=Jn(i);return o.updated_at=new Date().toISOString(),await e.update(Ve).set(o).where(w(_(Ve.tenant_id,t),_(Ve.themeId,n))),!0},async remove(t,n){return(await e.delete(Ve).where(w(_(Ve.tenant_id,t),_(Ve.themeId,n))).returning()).length>0}}}function om(e){return{async get(t){const n=await e.select({body:ot.body}).from(ot).where(_(ot.tenant_id,t)).get();return n?{body:n.body}:null},async set(t,n){const i=Date.now();await e.insert(ot).values({tenant_id:t,body:n.body,created_at_ts:i,updated_at_ts:i}).onConflictDoUpdate({target:ot.tenant_id,set:{body:n.body,updated_at_ts:i}})},async delete(t){await e.delete(ot).where(_(ot.tenant_id,t))}}}function _o(e,t){const n={connection:e.connection,provider:e.provider,user_id:e.user_id,isSocial:!!e.is_social};return t?n.isPrimary=!0:n.profileData={email:e.email,email_verified:!!e.email_verified,...typeof e.profileData=="string"?R(e.profileData,{}):{}},n}function Mn(e,t=[]){const{tenant_id:n,app_metadata:i,user_metadata:o,address:a,email_verified:s,phone_verified:c,is_social:u,linked_to:p,profileData:d,...h}=e,m=_o(e,!0),y=t.map(S=>_o(S,!1));return K({...h,email:e.email||"",email_verified:!!s,phone_verified:c!=null?!!c:void 0,is_social:!!u,app_metadata:R(i,{}),user_metadata:R(o,{}),address:R(a),identities:[m,...y]})}function rm(e){const t=async(n,i)=>{var c,u;const o=new Date().toISOString(),a={user_id:i.user_id,tenant_id:n,email:i.email,given_name:i.given_name,family_name:i.family_name,nickname:i.nickname,name:i.name,picture:i.picture,tags:i.tags,phone_number:i.phone_number,phone_verified:i.phone_verified??!1,username:i.username,linked_to:i.linked_to,last_ip:i.last_ip,login_count:i.login_count??0,last_login:i.last_login,provider:i.provider,connection:i.connection,email_verified:i.email_verified??!1,is_social:i.is_social??!1,app_metadata:JSON.stringify(i.app_metadata||{}),user_metadata:JSON.stringify(i.user_metadata||{}),address:i.address?JSON.stringify(i.address):void 0,profileData:i.profileData?JSON.stringify(i.profileData):void 0,locale:i.locale,middle_name:i.middle_name,preferred_username:i.preferred_username,profile:i.profile,website:i.website,gender:i.gender,birthdate:i.birthdate,zoneinfo:i.zoneinfo,created_at:i.created_at||o,updated_at:i.updated_at||o},s=i.password?Le():void 0;try{if(i.password&&s){await e.run(k`BEGIN`);try{await e.insert(q).values(a),await e.insert(oe).values({id:s,tenant_id:n,user_id:i.user_id,password:i.password.hash||i.password,algorithm:i.password.algorithm||"bcrypt",is_current:1,created_at:o,updated_at:o}),await e.run(k`COMMIT`)}catch(p){throw await e.run(k`ROLLBACK`),p}}else await e.insert(q).values(a)}catch(p){throw(c=p==null?void 0:p.message)!=null&&c.includes("UNIQUE constraint")||(u=p==null?void 0:p.message)!=null&&u.includes("AlreadyExists")?new lt(409,{message:"User already exists"}):(console.error("User upsert failed:",p==null?void 0:p.code,p==null?void 0:p.message),new lt(500,{message:"Internal server error"}))}return Mn(a)};return{create:t,rawCreate:t,async get(n,i){const o=await e.select().from(q).where(w(_(q.tenant_id,n),_(q.user_id,i))).get();if(!o)return null;const a=await e.select().from(q).where(w(_(q.tenant_id,n),_(q.linked_to,i))).all();return Mn(o,a)},async update(n,i,o){const a={updated_at:new Date().toISOString()},s=["email","given_name","family_name","nickname","name","picture","tags","phone_number","username","linked_to","last_ip","login_count","last_login","provider","connection","locale","middle_name","preferred_username","profile","website","gender","birthdate","zoneinfo"];for(const u of s)o[u]!==void 0&&(a[u]=o[u]);return o.email_verified!==void 0&&(a.email_verified=o.email_verified),o.phone_verified!==void 0&&(a.phone_verified=o.phone_verified),o.is_social!==void 0&&(a.is_social=o.is_social),o.app_metadata!==void 0&&(a.app_metadata=JSON.stringify(o.app_metadata)),o.user_metadata!==void 0&&(a.user_metadata=JSON.stringify(o.user_metadata)),o.address!==void 0&&(a.address=JSON.stringify(o.address)),o.profileData!==void 0&&(a.profileData=JSON.stringify(o.profileData)),(await e.update(q).set(a).where(w(_(q.tenant_id,n),_(q.user_id,i))).returning()).length>0},async list(n,i){const{page:o=0,per_page:a=50,include_totals:s=!1,sort:c,q:u}=i||{},p=[_(q.tenant_id,n),xe(q.linked_to)];if(u){const x=Ye(q,u,["email","name","nickname","username"]);x&&p.push(x)}const d=w(...p);let h=e.select().from(q).where(d).$dynamic();if(c!=null&&c.sort_by){const x=q[c.sort_by];x&&(h=h.orderBy(c.sort_order==="desc"?le(x):me(x)))}const m=await h.offset(o*a).limit(a),y=m.map(x=>x.user_id);let S=[];y.length>0&&(S=await e.select().from(q).where(w(_(q.tenant_id,n),Re(q.linked_to,y))));const C=m.map(x=>{const G=S.filter(X=>X.linked_to===x.user_id);return Mn(x,G)});if(!s)return{users:C};const[L]=await e.select({count:ye()}).from(q).where(d);return{users:C,start:o*a,limit:a,length:Number((L==null?void 0:L.count)??0)}},async remove(n,i){await e.run(k`BEGIN`);try{const o=await e.select({user_id:q.user_id}).from(q).where(w(_(q.tenant_id,n),_(q.linked_to,i))),a=[i,...o.map(c=>c.user_id)];await e.delete(pe).where(w(_(pe.tenant_id,n),Re(pe.user_id,a))),await e.delete(oe).where(w(_(oe.tenant_id,n),Re(oe.user_id,a))),await e.delete(q).where(w(_(q.tenant_id,n),_(q.linked_to,i)));const s=await e.delete(q).where(w(_(q.tenant_id,n),_(q.user_id,i))).returning();return await e.run(k`COMMIT`),s.length>0}catch(o){throw await e.run(k`ROLLBACK`),o}},async unlink(n,i,o,a){const s=`${o}|${a}`;return(await e.update(q).set({linked_to:null}).where(w(_(q.tenant_id,n),_(q.user_id,s),_(q.linked_to,i))).returning()).length>0}}}function am(e){return{async create(t,n,i,o){var a,s;try{await e.insert(qe).values({tenant_id:t,user_id:n,role_id:i,organization_id:o||"",created_at:new Date().toISOString()})}catch(c){if((a=c==null?void 0:c.message)!=null&&a.includes("UNIQUE constraint")||(s=c==null?void 0:c.message)!=null&&s.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw c}return!0},async list(t,n,i,o){let a=[_(qe.tenant_id,t),_(qe.user_id,n)];o&&a.push(_(qe.organization_id,o));const s=await e.select({role_id:qe.role_id}).from(qe).where(w(...a)).all();return s.length===0?[]:(await Promise.all(s.map(async u=>{const p=await e.select().from(_e).where(w(_(_e.tenant_id,t),_(_e.id,u.role_id))).get();if(!p)return null;const{tenant_id:d,is_system:h,metadata:m,...y}=p;return K({...y,is_system:h?!0:void 0,metadata:R(m)})}))).filter(Boolean)},async remove(t,n,i,o){return(await e.delete(qe).where(w(_(qe.tenant_id,t),_(qe.user_id,n),_(qe.role_id,i),_(qe.organization_id,o||""))).returning()).length>0}}}function sm(e){return{async create(t,n){var u,p;const i=new Date().toISOString(),a={id:n.id||Le(),tenant_id:t,user_id:n.user_id,organization_id:n.organization_id,created_at:i,updated_at:i};try{await e.insert(ue).values(a)}catch(d){throw(u=d==null?void 0:d.message)!=null&&u.includes("UNIQUE constraint")||(p=d==null?void 0:d.message)!=null&&p.includes("duplicate key")?new lt(409,{message:"User organization already exists"}):d}const{tenant_id:s,...c}=a;return c},async get(t,n){const i=await e.select().from(ue).where(w(_(ue.tenant_id,t),_(ue.id,n))).get();if(!i)return null;const{tenant_id:o,...a}=i;return a},async update(t,n,i){const o={updated_at:new Date().toISOString()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.organization_id!==void 0&&(o.organization_id=i.organization_id),(await e.update(ue).set(o).where(w(_(ue.tenant_id,t),_(ue.id,n))).returning()).length>0},async list(t,n){const{page:i=0,per_page:o=50,include_totals:a=!1,q:s}=n||{},c=_(ue.tenant_id,t);let u=c;if(s){const m=Ye(ue,s,["user_id","organization_id"]);m&&(u=w(c,m))}const d=(await e.select().from(ue).where(u).offset(i*o).limit(o)).map(m=>{const{tenant_id:y,...S}=m;return S});if(!a)return{userOrganizations:d};const[h]=await e.select({count:ye()}).from(ue).where(u);return{userOrganizations:d,start:i*o,limit:o,length:Number((h==null?void 0:h.count)??0)}},async listUserOrganizations(t,n,i){const{page:o=0,per_page:a=50,include_totals:s=!1}=i||{},c=await e.select().from(ue).where(w(_(ue.tenant_id,t),_(ue.user_id,n))).offset(o*a).limit(a).all(),p=(await Promise.all(c.map(async h=>{const m=await e.select().from(Y).where(w(_(Y.tenant_id,t),_(Y.id,h.organization_id))).get();if(!m)return null;const{tenant_id:y,branding:S,metadata:C,enabled_connections:L,token_quota:x,...G}=m;return K({...G,branding:R(S,{}),metadata:R(C,{}),enabled_connections:R(L,[]),token_quota:R(x,{})})}))).filter(Boolean);if(!s)return{organizations:p};const[d]=await e.select({count:ye()}).from(ue).where(w(_(ue.tenant_id,t),_(ue.user_id,n)));return{organizations:p,start:o*a,limit:a,length:Number((d==null?void 0:d.count)??0)}},async remove(t,n){return(await e.delete(ue).where(w(_(ue.tenant_id,t),_(ue.id,n))).returning()).length>0}}}const po=["s"],lm=["pwd_leak"];function fo(e){return/^\d{8}$/.test(e)?`${e.slice(0,4)}-${e.slice(4,6)}-${e.slice(6,8)}`:e}function cm(e){return{async getDaily(t,n){const i=new Date,o=n!=null&&n.from?fo(n.from):new Date(i.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],a=n!=null&&n.to?fo(n.to):i.toISOString().split("T")[0];return(await e.select({date:k`substr(${$.date}, 1, 10)`.as("date"),logins:k`SUM(CASE WHEN ${$.type} IN (${k.join(po.map(c=>k`${c}`),k`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:k`SUM(CASE WHEN ${$.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:k`SUM(CASE WHEN ${$.type} IN (${k.join(lm.map(c=>k`${c}`),k`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from($).where(w(_($.tenant_id,t),Tt($.date,o),pt($.date,`${a}T23:59:59.999Z`))).groupBy(k`substr(${$.date}, 1, 10)`).orderBy(k`substr(${$.date}, 1, 10)`).all()).map(c=>({date:c.date,logins:Number(c.logins)||0,signups:Number(c.signups)||0,leaked_passwords:Number(c.leaked_passwords)||0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}))},async getActiveUsers(t){const n=new Date(Date.now()-2592e6).toISOString(),[i]=await e.select({count:k`COUNT(DISTINCT ${$.user_id})`.as("count")}).from($).where(w(_($.tenant_id,t),Tt($.date,n),k`${$.type} IN (${k.join(po.map(o=>k`${o}`),k`, `)})`));return Number(i==null?void 0:i.count)||0}}}const um={"active-users":["s","seacft"],logins:["s","f","fp"],signups:["ss","fs"],"refresh-tokens":["seacft","fertft"],sessions:["slo"]},dm={"active-users":{alias:"active_users",type:"UInt64",agg:"uniq"},logins:{alias:"logins",type:"UInt64",agg:"count"},signups:{alias:"signups",type:"UInt64",agg:"count"},"refresh-tokens":{alias:"refresh_tokens",type:"UInt64",agg:"count"},sessions:{alias:"sessions",type:"UInt64",agg:"count"}};function _m(e){switch(e){case"hour":return k`substr(${$.date}, 1, 13)`;case"month":return k`substr(${$.date}, 1, 7)`;case"day":return k`substr(${$.date}, 1, 10)`;case"week":return k`date(substr(${$.date}, 1, 10), '-' || ((cast(strftime('%w', substr(${$.date}, 1, 10)) as integer) + 6) % 7) || ' days')`;default:throw new Error(`Unsupported interval '${e}' for SQL analytics adapter`)}}function jn(e){return`"${e.replace(/"/g,'""')}"`}function pm(e){switch(e){case"connection":return $.connection;case"client_id":return $.client_id;case"user_type":return $.strategy_type;case"event":return $.type;case"time":throw new Error("time dimension handled separately")}}function fm(e){return{async query(t,n,i){var C,L,x,G;const o=Date.now(),a=um[n],s=dm[n],c=[_($.tenant_id,t),Tt($.date,i.from),Qe($.date,i.to),Re($.type,a)];(C=i.filters.connection)!=null&&C.length&&c.push(Re($.connection,i.filters.connection)),(L=i.filters.client_id)!=null&&L.length&&c.push(Re($.client_id,i.filters.client_id)),(x=i.filters.user_type)!=null&&x.length&&c.push(Re($.strategy_type,i.filters.user_type)),(G=i.filters.user_id)!=null&&G.length&&c.push(Re($.user_id,i.filters.user_id));const u={},p=[],d=[];for(const X of i.group_by)if(X==="time"){const V=_m(i.interval);u.time=V,p.push(V),d.push({name:"time",type:i.interval==="hour"?"DateTime":"Date"})}else{const V=pm(X);u[X]=V,p.push(V),d.push({name:X,type:"String"})}u[s.alias]=s.agg==="uniq"?k`COUNT(DISTINCT ${$.user_id})`:k`COUNT(*)`,d.push({name:s.alias,type:s.type});let h=e.select(u).from($).where(w(...c));p.length>0&&(h=h.groupBy(...p));const m=new Set([...Object.keys(u)]);if(i.order_by){const X=i.order_by.startsWith("-"),V=X?i.order_by.slice(1):i.order_by;if(!m.has(V))throw new Error(`Invalid order_by column '${V}' for analytics query`);const we=jn(V);h=h.orderBy(k.raw(`${we} ${X?"DESC":"ASC"}`))}else i.group_by[0]==="time"?h=h.orderBy(k.raw(`${jn("time")} ASC`)):h=h.orderBy(k.raw(`${jn(s.alias)} DESC`));h=h.limit(i.limit).offset(i.offset);const S=(await h.all()).map(X=>{const V={};for(const we of d){const j=X[we.name];V[we.name]=we.type==="UInt64"?Number(j)||0:j??""}return V});return{meta:d,data:S,rows:S.length,rows_before_limit_at_least:S.length,statistics:{elapsed:(Date.now()-o)/1e3}}}}}function go(e){return{...e,payload:R(e.payload,{})}}function gm(e){return{async create(t,n){const i=Le(),o=new Date().toISOString();return await e.insert(U).values({id:i,tenant_id:t,event_type:n.event_type,log_type:n.log_type,aggregate_type:n.aggregate_type,aggregate_id:n.aggregate_id,payload:JSON.stringify({...n,id:i}),created_at:o,processed_at:null,retry_count:0,next_retry_at:null,error:null,claimed_by:null,claim_expires_at:null}),i},async getByIds(t){return t.length===0?[]:(await e.select().from(U).where(Re(U.id,t)).all()).map(go)},async getUnprocessed(t){const n=new Date().toISOString();return(await e.select().from(U).where(w(xe(U.processed_at),Be(xe(U.next_retry_at),pt(U.next_retry_at,n)),Be(xe(U.claimed_by),pt(U.claim_expires_at,n)))).orderBy(U.created_at,U.id).limit(t).all()).map(go)},async claimEvents(t,n,i){if(t.length===0)return[];const o=new Date().toISOString(),a=new Date(Date.now()+i).toISOString();return await e.update(U).set({claimed_by:n,claim_expires_at:a}).where(w(Re(U.id,t),xe(U.processed_at),Be(xe(U.claimed_by),pt(U.claim_expires_at,o)))),(await e.select({id:U.id}).from(U).where(w(Re(U.id,t),_(U.claimed_by,n))).all()).map(c=>c.id)},async markProcessed(t){t.length!==0&&await e.update(U).set({processed_at:new Date().toISOString()}).where(Re(U.id,t))},async markRetry(t,n,i){await e.update(U).set({error:n,next_retry_at:i,retry_count:k`${U.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(_(U.id,t))},async cleanup(t){return(await e.delete(U).where(w(k`${U.processed_at} IS NOT NULL`,pt(U.processed_at,t))).returning()).length},async deadLetter(t,n){const i=new Date().toISOString();await e.update(U).set({processed_at:i,dead_lettered_at:i,final_error:n}).where(_(U.id,t))},async listFailed(t,n={}){const{page:i=0,per_page:o=50,include_totals:a=!1}=n,c=(await e.select().from(U).where(w(_(U.tenant_id,t),rn(U.dead_lettered_at))).orderBy(le(U.dead_lettered_at),me(U.id)).offset(i*o).limit(o).all()).map(p=>({...R(p.payload,{}),id:p.id,created_at:p.created_at,processed_at:p.processed_at,retry_count:p.retry_count,next_retry_at:p.next_retry_at,error:p.error,dead_lettered_at:p.dead_lettered_at,final_error:p.final_error}));let u=c.length;if(a){const[p]=await e.select({total:ye()}).from(U).where(w(_(U.tenant_id,t),rn(U.dead_lettered_at)));u=Number((p==null?void 0:p.total)??c.length)}return{events:c,start:i*o,limit:o,length:u}},async replay(t,n){return(await e.update(U).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(w(_(U.id,t),_(U.tenant_id,n),rn(U.dead_lettered_at))).returning()).length>0}}}const hm=7*24*60*60*1e3;function mm(e){return async t=>{const n=Date.now()-hm;try{let i=[Be(Qe(J.expires_at_ts,n),Qe(J.idle_expires_at_ts,n))];t!=null&&t.tenant_id&&i.push(_(J.tenant_id,t.tenant_id)),await e.delete(J).where(w(...i)),i=[Be(Qe(se.expires_at_ts,n),Qe(se.idle_expires_at_ts,n))],t!=null&&t.tenant_id&&i.push(_(se.tenant_id,t.tenant_id)),t!=null&&t.user_id&&i.push(_(se.user_id,t.user_id)),await e.delete(se).where(w(...i)),i=[Qe(Q.expires_at_ts,n)],t!=null&&t.tenant_id&&i.push(_(Q.tenant_id,t.tenant_id)),await e.delete(Q).where(w(...i))}catch(i){console.error("Session cleanup error:",i)}}}function ym(e,t={useTransactions:!0}){const n={actions:yc(),actionExecutions:wc(),actionVersions:vc(),branding:Pc(e),clients:Uc(e),clientConnections:Zc(e),clientGrants:Jc(e),clientRegistrationTokens:mh(e),codes:yh(e),connections:vh(e),customDomains:bh(e),customText:Sh(e),emailProviders:Nh(e),emailTemplates:Eh(e),flows:Oh(e),forms:Ih(e),hookCode:Th(e),hooks:Dh(e),invites:$h(e),keys:Rh(e),loginSessions:Ph(e),logs:Uh(e),authenticationMethods:Zh(e),organizations:jh(e),passwords:qh(e),promptSettings:Bh(e),refreshTokens:Kh(e),resourceServers:Vh(e),rolePermissions:Hh(e),userPermissions:Wh(e),roles:Qh(e),sessions:em(e),sessionCleanup:mm(e),tenants:tm(e),themes:im(e),universalLoginTemplates:om(e),users:rm(e),userRoles:am(e),userOrganizations:sm(e),stats:cm(e),analytics:fm(e),outbox:gm(e),async transaction(i){if(t.useTransactions===!1)return i(n);await e.run(k`BEGIN`);try{const o=await i(n);return await e.run(k`COMMIT`),o}catch(o){throw await e.run(k`ROLLBACK`),o}}};return n}exports.default=ym;exports.sqlite=Dc;
|