@tempoxyz/id 0.0.0-pr-415.sha-8d37051 → 0.0.0-pr-416.sha-e4bee27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/admin/app/server/index.js +1 -1
  2. package/dist/admin/app/server/index.js.map +1 -1
  3. package/dist/app/db/auth.d.ts.map +1 -1
  4. package/dist/app/db/auth.js +0 -1
  5. package/dist/app/db/auth.js.map +1 -1
  6. package/dist/app/server/assets/Grant-TXwmc9xo.js.map +1 -1
  7. package/dist/app/server/index.js +26 -26
  8. package/dist/app/server/index.js.map +1 -1
  9. package/dist/client/Actions.d.ts +0 -4
  10. package/dist/client/Actions.d.ts.map +1 -1
  11. package/dist/client/Actions.js +2 -19
  12. package/dist/client/Actions.js.map +1 -1
  13. package/dist/client/BackendSession.d.ts +118 -0
  14. package/dist/client/BackendSession.d.ts.map +1 -0
  15. package/dist/client/BackendSession.js +195 -0
  16. package/dist/client/BackendSession.js.map +1 -0
  17. package/dist/client/Storage.d.ts +6 -2
  18. package/dist/client/Storage.d.ts.map +1 -1
  19. package/dist/client/Storage.js.map +1 -1
  20. package/dist/client.d.ts +1 -0
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +1 -0
  23. package/dist/client.js.map +1 -1
  24. package/dist/internal/Apps.d.ts +0 -8
  25. package/dist/internal/Apps.d.ts.map +1 -1
  26. package/dist/internal/Apps.js +0 -11
  27. package/dist/internal/Apps.js.map +1 -1
  28. package/dist/internal/Auth.d.ts +0 -1
  29. package/dist/internal/Auth.d.ts.map +1 -1
  30. package/dist/internal/Auth.js +2 -5
  31. package/dist/internal/Auth.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/admin/app/dist/server/index.js +1 -1
  34. package/src/admin/app/dist/server/index.js.map +1 -1
  35. package/src/app/crons/cleanup.ts +2 -9
  36. package/src/app/db/auth.ts +0 -3
  37. package/src/app/db/migrations/meta/_journal.json +0 -7
  38. package/src/client/Actions.ts +7 -26
  39. package/src/client/BackendSession.ts +332 -0
  40. package/src/client/Storage.ts +6 -2
  41. package/src/client.ts +1 -0
  42. package/src/internal/Apps.ts +0 -12
  43. package/src/internal/Auth.ts +2 -5
  44. package/src/app/db/migrations/0032_refresh_token_replay.sql +0 -1
  45. package/src/app/db/migrations/meta/0032_snapshot.json +0 -2963
@@ -17,7 +17,7 @@ params: ${n}`),this.query=t,this.params=n,this.cause=r,Error.captureStackTrace(t
17
17
  hash text NOT NULL,
18
18
  created_at bigint
19
19
  )
20
- `;await t.execute(z`CREATE SCHEMA IF NOT EXISTS ${z.identifier(i)}`),await t.execute(a);let o=(await t.all(z`select id, hash, created_at from ${z.identifier(i)}.${z.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(z.raw(e));await t.execute(z`insert into ${z.identifier(i)}.${z.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e.replace(/"/g,`""`)}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[z`with `];for(let[n,r]of e.entries())t.push(z`${z.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(z`, `);return t.push(z` `),z.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?z` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,o=t?z` where ${t}`:void 0;return z`${i}delete from ${e}${o}${a}`}buildUpdateSet(e,t){let n=e[L.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return z.join(r.flatMap((e,r)=>{let a=n[e],o=a.onUpdateFn?.(),s=t[e]??(F(o,R)?o:z.param(o,a)),c=z`${z.identifier(this.casing.getColumnCasing(a))} = ${s}`;return r<i-1?[c,z.raw(`, `)]:[c]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[lc.Symbol.Name],l=e[lc.Symbol.Schema],u=e[lc.Symbol.OriginalName],d=c===u?void 0:c,f=z`${l?z`${z.identifier(l)}.`:void 0}${z.identifier(u)}${d&&z` ${z.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&z.join([z.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?z` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0,_=n?z` where ${n}`:void 0;return z`${s}update ${f} set ${p}${m}${h}${_}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let n=e.length,r=e.flatMap(({field:e},r)=>{let i=[];if(F(e,R.Aliased)&&e.isSelectionField)i.push(z.identifier(e.fieldAlias));else if(F(e,R.Aliased)||F(e,R)){let n=F(e,R.Aliased)?e.sql:e;t?i.push(new R(n.queryChunks.map(e=>F(e,I)?z.identifier(this.casing.getColumnCasing(e)):e))):i.push(n),F(e,R.Aliased)&&i.push(z` as ${z.identifier(e.fieldAlias)}`)}else if(F(e,Pi))t?i.push(z.identifier(this.casing.getColumnCasing(e))):i.push(e);else if(F(e,ca)){let t=Object.entries(e._.selectedFields);if(t.length===1){let n=t[0][1],r=F(n,R)?n.decoder:F(n,Pi)?{mapFromDriverValue:e=>n.mapFromDriverValue(e)}:n.sql.decoder;r&&(e._.sql.decoder=r)}i.push(e)}return r<n-1&&i.push(z`, `),i});return z.join(r)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[n,r]of e.entries()){n===0&&t.push(z` `);let i=r.table,a=r.lateral?z` lateral`:void 0,o=r.on?z` on ${r.on}`:void 0;if(F(i,lc)){let e=i[lc.Symbol.Name],n=i[lc.Symbol.Schema],s=i[lc.Symbol.OriginalName],c=e===s?void 0:r.alias;t.push(z`${z.raw(r.joinType)} join${a} ${n?z`${z.identifier(n)}.`:void 0}${z.identifier(s)}${c&&z` ${z.identifier(c)}`}${o}`)}else if(F(i,Na)){let e=i[da].name,n=i[da].schema,s=i[da].originalName,c=e===s?void 0:r.alias;t.push(z`${z.raw(r.joinType)} join${a} ${n?z`${z.identifier(n)}.`:void 0}${z.identifier(s)}${c&&z` ${z.identifier(c)}`}${o}`)}else t.push(z`${z.raw(r.joinType)} join${a} ${i}${o}`);n<e.length-1&&t.push(z` `)}return z.join(t)}buildFromTable(e){if(F(e,L)&&e[L.Symbol.IsAlias]){let t=z`${z.identifier(e[L.Symbol.OriginalName])}`;return e[L.Symbol.Schema]&&(t=z`${z.identifier(e[L.Symbol.Schema])}.${t}`),z`${t} ${z.identifier(e[L.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,lockingClause:d,distinct:f,setOperators:p}){let m=n??Ha(t);for(let e of m)if(F(e.field,Pi)&&ba(e.field.table)!==(F(a,ca)?a._.alias:F(a,ml)?a[da].name:F(a,R)?void 0:ba(a))&&!(e=>o?.some(({alias:t})=>t===(e[L.Symbol.IsAlias]?ba(e):e[L.Symbol.BaseName])))(e.field.table)){let t=ba(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let h=!o||o.length===0,g=this.buildWithCTE(e),_;f&&(_=f===!0?z` distinct`:z` distinct on (${z.join(f.on,z`, `)})`);let v=this.buildSelection(m,{isSingleTable:h}),y=this.buildFromTable(a),b=this.buildJoins(o),x=r?z` where ${r}`:void 0,ee=i?z` having ${i}`:void 0,te;s&&s.length>0&&(te=z` order by ${z.join(s,z`, `)}`);let S;c&&c.length>0&&(S=z` group by ${z.join(c,z`, `)}`);let C=typeof l==`object`||typeof l==`number`&&l>=0?z` limit ${l}`:void 0,w=u?z` offset ${u}`:void 0,ne=z.empty();if(d){let e=z` for ${z.raw(d.strength)}`;d.config.of&&e.append(z` of ${z.join(Array.isArray(d.config.of)?d.config.of:[d.config.of],z`, `)}`),d.config.noWait?e.append(z` nowait`):d.config.skipLocked&&e.append(z` skip locked`),ne.append(e)}let T=z`${g}select${_} ${v} from ${y}${b}${x}${S}${ee}${te}${C}${w}${ne}`;return p.length>0?this.buildSetOperations(T,p):T}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=z`(${e.getSQL()}) `,c=z`(${r.getSQL()})`,l;if(a&&a.length>0){let e=[];for(let t of a)if(F(t,I))e.push(z.identifier(t.name));else if(F(t,R)){for(let e=0;e<t.queryChunks.length;e++){let n=t.queryChunks[e];F(n,I)&&(t.queryChunks[e]=z.identifier(n.name))}e.push(z`${t}`)}else e.push(z`${t}`);l=z` order by ${z.join(e,z`, `)} `}let u=typeof i==`object`||typeof i==`number`&&i>=0?z` limit ${i}`:void 0,d=z.raw(`${t} ${n?`all `:``}`),f=o?z` offset ${o}`:void 0;return z`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,overridingSystemValue_:o}){let s=[],c=e[L.Symbol.Columns],l=Object.entries(c).filter(([e,t])=>!t.shouldDisableInsert()),u=l.map(([,e])=>z.identifier(this.casing.getColumnCasing(e)));if(a){let e=t;F(e,R)?s.push(e):s.push(e.getSQL())}else{let e=t;s.push(z.raw(`values `));for(let[t,n]of e.entries()){let r=[];for(let[e,t]of l){let i=n[e];if(i===void 0||F(i,ka)&&i.value===void 0){if(t.defaultFn!==void 0){let e=t.defaultFn(),n=F(e,R)?e:z.param(e,t);r.push(n)}else if(!t.default&&t.onUpdateFn!==void 0){let e=t.onUpdateFn(),n=F(e,R)?e:z.param(e,t);r.push(n)}else r.push(z`default`)}else r.push(i)}s.push(r),t<e.length-1&&s.push(z`, `)}}let d=this.buildWithCTE(i),f=z.join(s),p=r?z` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,m=n?z` on conflict ${n}`:void 0,h=o===!0?z`overriding system value `:void 0;return z`${d}insert into ${e} ${u} ${h}${f}${m}${p}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){let r=t?z` concurrently`:void 0,i=n?z` with no data`:void 0;return z`refresh materialized view${r} ${e}${i}`}prepareTyping(e){return F(e,Ho)||F(e,zo)?`json`:F(e,ns)?`decimal`:F(e,Is)?`time`:F(e,zs)||F(e,Vs)?`timestamp`:F(e,So)||F(e,wo)?`date`:F(e,Us)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:r,tableConfig:i,queryConfig:a,tableAlias:o,nestedQueryRelation:s,joinOn:c}){let l=[],u,d,f=[],p,m=[];if(a===!0)l=Object.entries(i.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:La(t,o),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let r=Object.fromEntries(Object.entries(i.columns).map(([e,t])=>[e,La(t,o)]));if(a.where){let e=typeof a.where==`function`?a.where(r,rl()):a.where;p=e&&za(e,o)}let s=[],c=[];if(a.columns){let e=!1;for(let[t,n]of Object.entries(a.columns))n!==void 0&&t in i.columns&&(!e&&n===!0&&(e=!0),c.push(t));c.length>0&&(c=e?c.filter(e=>a.columns?.[e]===!0):Object.keys(i.columns).filter(e=>!c.includes(e)))}else c=Object.keys(i.columns);for(let e of c){let t=i.columns[e];s.push({tsKey:e,value:t})}let h=[];a.with&&(h=Object.entries(a.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:i.relations[e]})));let g;if(a.extras){g=typeof a.extras==`function`?a.extras(r,{sql:z}):a.extras;for(let[e,t]of Object.entries(g))s.push({tsKey:e,value:Ra(t,o)})}for(let{tsKey:e,value:t}of s)l.push({dbKey:F(t,R.Aliased)?t.fieldAlias:i.columns[e].name,tsKey:e,field:F(t,Pi)?La(t,o):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let _=typeof a.orderBy==`function`?a.orderBy(r,il()):a.orderBy??[];Array.isArray(_)||(_=[_]),f=_.map(e=>F(e,Pi)?La(e,o):za(e,o)),u=a.limit,d=a.offset;for(let{tsKey:r,queryConfig:i,relation:a}of h){let s=ll(t,n,a),c=n[xa(a.referencedTable)],u=`${o}_${r}`,d=U(...s.fields.map((e,t)=>H(La(s.references[t],u),La(e,o)))),f=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:e[c],tableConfig:t[c],queryConfig:F(a,tl)?i===!0?{limit:1}:{...i,limit:1}:i,tableAlias:u,joinOn:d,nestedQueryRelation:a}),p=z`${z.identifier(u)}.${z.identifier(`data`)}`.as(r);m.push({on:z`true`,table:new ca(f.sql,{},u),alias:u,joinType:`left`,lateral:!0}),l.push({dbKey:r,tsKey:r,field:p,relationTableTsKey:c,isJson:!0,selection:f.selection})}}if(l.length===0)throw new Oc({message:`No fields selected for table "${i.tsName}" ("${o}")`});let h;if(p=U(c,p),s){let e=z`json_build_array(${z.join(l.map(({field:e,tsKey:t,isJson:n})=>n?z`${z.identifier(`${o}_${t}`)}.${z.identifier(`data`)}`:F(e,R.Aliased)?e.sql:e),z`, `)})`;F(s,nl)&&(e=z`coalesce(json_agg(${e}${f.length>0?z` order by ${z.join(f,z`, `)}`:void 0}), '[]'::json)`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:i.tsName,selection:l}];u!==void 0||d!==void 0||f.length>0?(h=this.buildSelectQuery({table:Ia(r,o),fields:{},fieldsFlat:[{path:[],field:z.raw(`*`)}],where:p,limit:u,offset:d,orderBy:f,setOperators:[]}),p=void 0,u=void 0,d=void 0,f=[]):h=Ia(r,o),h=this.buildSelectQuery({table:F(h,lc)?h:new ca(h,{},o),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:F(e,Pi)?La(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]})}else h=this.buildSelectQuery({table:Ia(r,o),fields:{},fieldsFlat:l.map(({field:e})=>({path:[],field:F(e,Pi)?La(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]});return{tableTsKey:i.tsName,sql:h,selection:l}}},gl=class{static[P]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},_l=class{static[P]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,n=e,r;return r=this.fields?this.fields:F(n,ca)?Object.fromEntries(Object.keys(n._.selectedFields).map(e=>[e,n[e]])):F(n,ml)?n[da].selectedFields:F(n,R)?{}:Ka(n),new yl({table:n,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},vl=class extends gl{static[P]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=qa(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of Bl(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(n,r)=>{let i=this.tableName,a=qa(n);for(let e of Bl(n))this.usedTables.add(e);if(typeof a==`string`&&this.config.joins?.some(e=>e.alias===a))throw Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==`string`&&(this.config.fields={[i]:this.config.fields}),typeof a==`string`&&!F(n,R))){let e=F(n,ca)?n._.selectedFields:F(n,Na)?n[da].selectedFields:n[L.Symbol.Columns];this.config.fields[a]=e}if(typeof r==`function`&&(r=r(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:r,table:n,joinType:e,alias:a,lateral:t}),typeof a==`string`)switch(e){case`left`:this.joinsNotNullableMap[a]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[a]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!1}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(xl()):n;if(!Ua(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Bl(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...Bl(e.table));return new Proxy(new ca(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new Ba({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},yl=class extends vl{static[P]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return ua.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=Ha(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};Ga(yl,[Ni]);function bl(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Ua(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var xl=()=>({union:Sl,unionAll:Cl,intersect:wl,intersectAll:Tl,except:El,exceptAll:Dl}),Sl=bl(`union`,!1),Cl=bl(`union`,!0),wl=bl(`intersect`,!1),Tl=bl(`intersect`,!0),El=bl(`except`,!1),Dl=bl(`except`,!0),Ol=class{static[P]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=F(e,hl)?e:void 0,this.dialectConfig=F(e,hl)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new la(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new _l({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new _l({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new _l({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new _l({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new _l({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new _l({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new hl(this.dialectConfig),this.dialect}},kl=class{constructor(e,t){this.name=e,this.schema=t}static[P]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},Al=class extends kl{static[P]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new Ol));let t=new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Fl({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},jl=class extends kl{static[P]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Ka(dc(e,t))}existing(){return new Proxy(new Fl({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Fl({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Ml=class{constructor(e,t){this.name=e,this.schema=t}static[P]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},Nl=class extends Ml{static[P]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new Ol));let t=new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Ll({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Pl=class extends Ml{static[P]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Ka(dc(e,t))}existing(){return new Proxy(new Ll({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Ll({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Fl=class extends ml{static[P]=`PgView`;[Cc];constructor({pgConfig:e,config:t}){super(t),e&&(this[Cc]={with:e.with})}},Il=Symbol.for(`drizzle:PgMaterializedViewConfig`),Ll=class extends ml{static[P]=`PgMaterializedView`;[Il];constructor({pgConfig:e,config:t}){super(t),this[Il]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function Rl(e,t,n){return t?new jl(e,t,n):new Al(e,n)}function zl(e,t,n){return t?new Pl(e,t,n):new Nl(e,n)}function Bl(e){return F(e,lc)?[e[fa]?`${e[fa]}.${e[L.Symbol.BaseName]}`:e[L.Symbol.BaseName]]:F(e,ca)?e._.usedTables??[]:F(e,R)?e.usedTables??[]:[]}var Vl=class extends Ni{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[P]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[L.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Ha(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:Bl(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Hl=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[P]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},n=this.table[L.Symbol.Columns];for(let r of Object.keys(e)){let i=e[r];t[r]=F(i,R)?i:new ka(i,n[r])}return t});return new Ul(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e==`function`?e(new Ol):e;if(!F(t,R)&&!Ua(this.table[pa],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new Ul(this.table,t,this.session,this.dialect,this.withList,!0)}},Ul=class extends Ni{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[P]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[L.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Ha(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=z`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?z` where ${e.where}`:void 0;this.config.onConflict=z`(${z.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?z` where ${e.where}`:void 0,n=e.targetWhere?z` where ${e.targetWhere}`:void 0,r=e.setWhere?z` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,Wa(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=z`(${z.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:Bl(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Wl=class extends Ni{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[P]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},Gl=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[P]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new Kl(this.table,Wa(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},Kl=class extends Ni{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=qa(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[P]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=qa(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return F(e,lc)?e[L.Symbol.Columns]:F(e,ca)?e._.selectedFields:e[da].selectedFields}createJoin(e){return(t,n)=>{let r=qa(t);if(typeof r==`string`&&this.config.joins.some(e=>e.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==`function`){let e=this.config.from&&!F(this.config.from,R)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[L.Symbol.Columns],new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:n,table:t,joinType:e,alias:r}),typeof r==`string`)switch(e){case`left`:this.joinsNotNullableMap[r]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!0;break;case`inner`:this.joinsNotNullableMap[r]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[L.Symbol.Columns]),this.config.from)){let t=qa(this.config.from);if(typeof t==`string`&&this.config.from&&!F(this.config.from,R)){let n=this.getTableLikeFields(this.config.from);e[t]=n}for(let t of this.config.joins){let n=qa(t.table);if(typeof n==`string`&&!F(t.table,R)){let r=this.getTableLikeFields(t.table);e[n]=r}}}return this.config.returningFields=e,this.config.returning=Ha(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:Bl(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},ql=class e extends R{constructor(t){super(e.buildEmbeddedCount(t.source,t.filters).queryChunks),this.params=t,this.mapWith(Number),this.session=t.session,this.sql=e.buildCount(t.source,t.filters)}sql;token;static[P]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return z`(select count(*) from ${e}${z.raw(` where `).if(t)}${t})`}static buildCount(e,t){return z`select count(*) as count from ${e}${z.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},Jl=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[P]=`PgRelationalQueryBuilder`;findMany(e){return new Yl(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new Yl(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},Yl=class extends Ni{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[P]=`PgRelationalQuery`;_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>dl(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Xl=class extends Ni{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[P]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},Zl=class{constructor(e,t,n){if(this.dialect=e,this.session=t,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[r,i]of Object.entries(this._.schema))this.query[r]=new Jl(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[r],i,e,t);this.$cache={invalidate:async e=>{}}}static[P]=`PgDatabase`;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new Ol(n.dialect))),new Proxy(new la(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new ql({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new _l({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new _l({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new _l({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new Gl(n,t.session,t.dialect,e)}function o(n){return new Hl(n,t.session,t.dialect,e)}function s(n){return new Vl(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new _l({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new _l({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new _l({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Gl(e,this.session,this.dialect)}insert(e){return new Hl(e,this.session,this.dialect)}delete(e){return new Vl(e,this.session,this.dialect)}refreshMaterializedView(e){return new Wl(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?z.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new Xl(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}},Ql=class{static[P]=`Cache`},$l=class extends Ql{strategy(){return`all`}static[P]=`NoopCache`;async get(e){}async put(e,t,n,r){}async onMutate(e){}};async function eu(e,t){let n=`${e}-${JSON.stringify(t)}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}var tu=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[P]=`PgSequence`};function nu(e,t,n){return new tu(e,t,n)}var ru=class{constructor(e){this.schemaName=e}static[P]=`PgSchema`;table=(e,t,n)=>uc(e,t,n,this.schemaName);view=(e,t)=>Rl(e,t,this.schemaName);materializedView=(e,t)=>zl(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?oa(e,[...t],this.schemaName):sa(e,t,this.schemaName)}sequence=(e,t)=>nu(e,t,this.schemaName);getSQL(){return new R([z.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function iu(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new ru(e)}var au=class{constructor(e,t,n,r){this.query=e,this.cache=t,this.queryMetadata=n,this.cacheConfig=r,t&&t.strategy()===`all`&&r===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[P]=`PgPreparedQuery`;joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||F(this.cache,$l)||this.queryMetadata===void 0||this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(n){throw new kc(e,t,n)}if((this.queryMetadata.type===`insert`||this.queryMetadata.type===`update`||this.queryMetadata.type===`delete`)&&this.queryMetadata.tables.length>0)try{let[e]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return e}catch(n){throw new kc(e,t,n)}if(!this.cacheConfig)try{return await n()}catch(n){throw new kc(e,t,n)}if(this.queryMetadata.type===`select`){let r=await this.cache.get(this.cacheConfig.tag??await eu(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let r;try{r=await n()}catch(n){throw new kc(e,t,n)}return await this.cache.put(this.cacheConfig.tag??await eu(e,t),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return r}try{return await n()}catch(n){throw new kc(e,t,n)}}},ou=class{constructor(e){this.dialect=e}static[P]=`PgSession`;execute(e,t){return ua.startActiveSpan(`drizzle.operation`,()=>ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let n=await this.execute(e,t);return Number(n[0].count)}},su=class extends Zl{constructor(e,t,n,r=0){super(e,t,n),this.schema=n,this.nestedIndex=r}static[P]=`PgTransaction`;rollback(){throw new Ac}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable==`boolean`&&t.push(e.deferrable?`deferrable`:`not deferrable`),z.raw(t.join(` `))}setTransaction(e){return this.session.execute(z`set transaction ${this.getTransactionConfigSQL(e)}`)}},{Pool:cu,types:lu}=ki,uu=class extends au{constructor(e,t,n,r,i,a,o,s,c,l,u){super({sql:t,params:n},i,a,o),this.client=e,this.queryString=t,this.params=n,this.logger=r,this.fields=s,this._isResponseInArrayMode=l,this.customResultMapper=u,this.rawQueryConfig={name:c,text:t,types:{getTypeParser:(e,t)=>e===lu.builtins.TIMESTAMPTZ||e===lu.builtins.TIMESTAMP||e===lu.builtins.DATE||e===lu.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:lu.getTypeParser(e,t)}},this.queryConfig={name:c,text:t,rowMode:`array`,types:{getTypeParser:(e,t)=>e===lu.builtins.TIMESTAMPTZ||e===lu.builtins.TIMESTAMP||e===lu.builtins.DATE||e===lu.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:lu.getTypeParser(e,t)}}}static[P]=`NodePgPreparedQuery`;rawQueryConfig;queryConfig;async execute(e={}){return ua.startActiveSpan(`drizzle.execute`,async()=>{let t=ja(this.params,e);this.logger.logQuery(this.rawQueryConfig.text,t);let{fields:n,rawQueryConfig:r,client:i,queryConfig:a,joinsNotNullableMap:o,customResultMapper:s}=this;if(!n&&!s)return ua.startActiveSpan(`drizzle.driver.execute`,async e=>(e?.setAttributes({"drizzle.query.name":r.name,"drizzle.query.text":r.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(r.text,t,async()=>await i.query(r,t))));let c=await ua.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":a.name,"drizzle.query.text":a.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(a.text,t,async()=>await i.query(a,t))));return ua.startActiveSpan(`drizzle.mapResponse`,()=>s?s(c.rows):c.rows.map(e=>Va(n,e,o)))})}all(e={}){return ua.startActiveSpan(`drizzle.execute`,()=>{let t=ja(this.params,e);return this.logger.logQuery(this.rawQueryConfig.text,t),ua.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":this.rawQueryConfig.name,"drizzle.query.text":this.rawQueryConfig.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(this.rawQueryConfig.text,t,async()=>this.client.query(this.rawQueryConfig,t)).then(e=>e.rows)))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},du=class e extends ou{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new Mi,this.cache=r.cache??new $l}static[P]=`NodePgSession`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new uu(this.client,e.sql,e.params,this.logger,this.cache,a,o,t,n,r,i)}async transaction(t,n){let r=this.client instanceof cu||Object.getPrototypeOf(this.client).constructor.name.includes(`Pool`),i=r?new e(await this.client.connect(),this.dialect,this.schema,this.options):this,a=new fu(this.dialect,i,this.schema);await a.execute(z`begin${n?z` ${a.getTransactionConfigSQL(n)}`:void 0}`);try{let e=await t(a);return await a.execute(z`commit`),e}catch(e){throw await a.execute(z`rollback`),e}finally{r&&i.client.release()}}async count(e){let t=await this.execute(e);return Number(t.rows[0].count)}},fu=class e extends su{static[P]=`NodePgTransaction`;async transaction(t){let n=`sp${this.nestedIndex+1}`,r=new e(this.dialect,this.session,this.schema,this.nestedIndex+1);await r.execute(z.raw(`savepoint ${n}`));try{let e=await t(r);return await r.execute(z.raw(`release savepoint ${n}`)),e}catch(e){throw await r.execute(z.raw(`rollback to savepoint ${n}`)),e}}},pu=class{constructor(e,t,n={}){this.client=e,this.dialect=t,this.options=n}static[P]=`NodePgDriver`;createSession(e){return new du(this.client,this.dialect,e,{logger:this.options.logger,cache:this.options.cache})}},mu=class extends Zl{static[P]=`NodePgDatabase`};function hu(e,t={}){let n=new hl({casing:t.casing}),r;t.logger===!0?r=new ji:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=al(t.schema,ul);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new mu(n,new pu(e,n,{logger:r,cache:t.cache}).createSession(i),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}function gu(...e){if(typeof e[0]==`string`)return hu(new ki.Pool({connectionString:e[0]}),e[1]);if(Ya(e[0])){let{connection:t,client:n,...r}=e[0];return hu(n||(typeof t==`string`?new ki.Pool({connectionString:t}):new ki.Pool(t)),r)}return hu(e[0],e[1])}(e=>{function t(e){return hu({},e)}e.mock=t})(gu||={});var _u={crossOriginEmbedderPolicy:[`Cross-Origin-Embedder-Policy`,`require-corp`],crossOriginResourcePolicy:[`Cross-Origin-Resource-Policy`,`same-origin`],crossOriginOpenerPolicy:[`Cross-Origin-Opener-Policy`,`same-origin`],originAgentCluster:[`Origin-Agent-Cluster`,`?1`],referrerPolicy:[`Referrer-Policy`,`no-referrer`],strictTransportSecurity:[`Strict-Transport-Security`,`max-age=15552000; includeSubDomains`],xContentTypeOptions:[`X-Content-Type-Options`,`nosniff`],xDnsPrefetchControl:[`X-DNS-Prefetch-Control`,`off`],xDownloadOptions:[`X-Download-Options`,`noopen`],xFrameOptions:[`X-Frame-Options`,`SAMEORIGIN`],xPermittedCrossDomainPolicies:[`X-Permitted-Cross-Domain-Policies`,`none`],xXssProtection:[`X-XSS-Protection`,`0`]},vu={crossOriginEmbedderPolicy:!1,crossOriginResourcePolicy:!0,crossOriginOpenerPolicy:!0,originAgentCluster:!0,referrerPolicy:!0,strictTransportSecurity:!0,xContentTypeOptions:!0,xDnsPrefetchControl:!0,xDownloadOptions:!0,xFrameOptions:!0,xPermittedCrossDomainPolicies:!0,xXssProtection:!0,removePoweredBy:!0,permissionsPolicy:{}},yu=e=>{let t={...vu,...e},n=bu(t),r=[];if(t.contentSecurityPolicy){let[e,i]=xu(t.contentSecurityPolicy,`Content-Security-Policy`);e&&r.push(e),n.push([`Content-Security-Policy`,i])}if(t.contentSecurityPolicyReportOnly){let[e,i]=xu(t.contentSecurityPolicyReportOnly,`Content-Security-Policy-Report-Only`);e&&r.push(e),n.push([`Content-Security-Policy-Report-Only`,i])}return t.permissionsPolicy&&Object.keys(t.permissionsPolicy).length>0&&n.push([`Permissions-Policy`,Su(t.permissionsPolicy)]),t.reportingEndpoints&&n.push([`Reporting-Endpoints`,wu(t.reportingEndpoints)]),t.reportTo&&n.push([`Report-To`,Tu(t.reportTo)]),async function(e,i){let a=r.length===0?n:r.reduce((t,n)=>n(e,t),n);await i(),Eu(e,a),t?.removePoweredBy&&e.res.headers.delete(`X-Powered-By`)}};function bu(e){return Object.entries(_u).filter(([t])=>e[t]).map(([t,n])=>{let r=e[t];return typeof r==`string`?[n[0],r]:n})}function xu(e,t){let n=[],r=[];for(let[t,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];e.forEach((e,i)=>{if(typeof e==`function`){let a=i*2+2+r.length;n.push((n,r)=>{r[a]=e(n,t)})}}),r.push(t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(e,t)=>t?`-`+e.toLowerCase():e.toLowerCase()),...e.flatMap(e=>[` `,e]),`; `)}return r.pop(),n.length===0?[void 0,r.join(``)]:[(e,r)=>r.map(r=>{if(r[0]===t){let t=r[1].slice();return n.forEach(n=>{n(e,t)}),[r[0],t.join(``)]}return r}),r]}function Su(e){return Object.entries(e).map(([e,t])=>{let n=Cu(e);return typeof t==`boolean`?`${n}=${t?`*`:`()`}`:Array.isArray(t)?t.length===0?`${n}=()`:t.length===1&&t[0]===`*`?`${n}=*`:t.length===1&&t[0]===`none`?`${n}=()`:`${n}=(${t.map(e=>[`self`,`src`].includes(e)?e:`"${e}"`).join(` `)})`:``}).filter(Boolean).join(`, `)}function Cu(e){return e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).toLowerCase()}function wu(e=[]){return e.map(e=>`${e.name}="${e.url}"`).join(`, `)}function Tu(e=[]){return e.map(e=>JSON.stringify(e)).join(`, `)}function Eu(e,t){t.forEach(([t,n])=>{e.res.headers.set(t,n)})}var Du=/^[a-z_][a-z0-9_]{0,62}$/,Ou=(()=>{let e=globalThis.process?.env?.DATABASE_SCHEMA;if(e&&e!==`public`){if(!Du.test(e))throw Error(`Invalid DATABASE_SCHEMA: ${JSON.stringify(e)}. Set it to a lowercase Postgres schema name, such as pr_141, or leave it unset.`);return e}})(),ku=Ou?iu(Ou).table:dc,Au=ku(`account`,{accessToken:B(`access_token`),accessTokenExpiresAt:V(`access_token_expires_at`),accountId:B(`account_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),idToken:B(`id_token`),password:B(`password`),providerId:B(`provider_id`).notNull(),refreshToken:B(`refresh_token`),refreshTokenExpiresAt:V(`refresh_token_expires_at`),scope:B(`scope`),updatedAt:V(`updated_at`).$onUpdate(()=>new Date).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`account_userId_idx`).on(e.userId)]),ju=ol(Au,({one:e})=>({user:e(q,{fields:[Au.userId],references:[q.id]})})),Mu=ku(`device_code`,{acr:B(`acr`),amr:B(`amr`).array(),authTime:V(`auth_time`),clientId:B(`client_id`),deviceCode:B(`device_code`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),lastPolledAt:V(`last_polled_at`),oauthClientId:B(`oauth_client_id`),pollingInterval:Po(`polling_interval`),referenceId:B(`reference_id`),resources:B(`resources`).array(),scope:B(`scope`),status:B(`status`).notNull(),userCode:B(`user_code`).notNull(),userId:B(`user_id`)},e=>[yc(`deviceCode_deviceCode_uidx`).on(e.deviceCode),vc(`deviceCode_expiresAt_idx`).on(e.expiresAt),yc(`deviceCode_userCode_uidx`).on(e.userCode)]),Nu=ku(`jwks`,{alg:B(`alg`),createdAt:V(`created_at`).notNull(),crv:B(`crv`),expiresAt:V(`expires_at`),id:B(`id`).primaryKey(),privateKey:B(`private_key`).notNull(),publicKey:B(`public_key`).notNull()}),Pu=ku(`oauth_access_token`,{authorizationCodeId:B(`authorization_code_id`),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),confirmation:Uo(`confirmation`),createdAt:V(`created_at`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),refreshId:B(`refresh_id`).references(()=>G.id,{onDelete:`cascade`}),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),revoked:V(`revoked`),scopes:B(`scopes`).array().notNull(),sessionId:B(`session_id`).references(()=>K.id,{onDelete:`set null`}),token:B(`token`).notNull().unique(),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthAccessToken_authorizationCodeId_idx`).on(e.authorizationCodeId),vc(`oauthAccessToken_clientId_idx`).on(e.clientId),vc(`oauthAccessToken_expiresAt_idx`).on(e.expiresAt),vc(`oauthAccessToken_refreshId_idx`).on(e.refreshId),vc(`oauthAccessToken_sessionId_idx`).on(e.sessionId),vc(`oauthAccessToken_userId_idx`).on(e.userId)]),Fu=ol(Pu,({one:e})=>({oauthClient:e(W,{fields:[Pu.clientId],references:[W.clientId]}),oauthRefreshToken:e(G,{fields:[Pu.refreshId],references:[G.id]}),session:e(K,{fields:[Pu.sessionId],references:[K.id]}),user:e(q,{fields:[Pu.userId],references:[q.id]})})),W=ku(`oauth_client`,{accessAudience:B(`access_audience`),applicationType:B(`application_type`),attestation:Uo(`attestation`),backchannelLogoutSessionRequired:lo(`backchannel_logout_session_required`),backchannelLogoutUri:B(`backchannel_logout_uri`),clientCredentialsScopes:B(`client_credentials_scopes`).array().default([]),clientDiscoveryId:B(`client_discovery_id`),clientId:B(`client_id`).notNull().unique(),clientSecret:B(`client_secret`),contacts:B(`contacts`).array(),createdAt:V(`created_at`),disabled:lo(`disabled`).default(!1),dpopBoundAccessTokens:lo(`dpop_bound_access_tokens`).default(!1),employee:lo(`employee`).default(!1),enableEndSession:lo(`enable_end_session`),frontchannelLogoutSessionRequired:lo(`frontchannel_logout_session_required`),frontchannelLogoutUri:B(`frontchannel_logout_uri`),grantTypes:B(`grant_types`).array(),icon:B(`icon`),id:B(`id`).primaryKey(),jwks:B(`jwks`),jwksUri:B(`jwks_uri`),metadata:Uo(`metadata`),name:B(`name`),policy:B(`policy`),postLogoutRedirectUris:B(`post_logout_redirect_uris`).array(),redirectUris:B(`redirect_uris`).array().notNull(),referenceId:B(`reference_id`),refreshTokenLifetime:Po(`refresh_token_lifetime`).default(2592e3),requirePKCE:lo(`require_pkce`),requirePushedAuthorizationRequests:lo(`require_pushed_authorization_requests`).default(!1),responseTypes:B(`response_types`).array(),scopes:B(`scopes`).array(),sectorIdentifier:B(`sector_identifier`),skipConsent:lo(`skip_consent`),softwareId:B(`software_id`),softwareStatement:B(`software_statement`),softwareVersion:B(`software_version`),subjectType:B(`subject_type`),tokenEndpointAuthMethod:B(`token_endpoint_auth_method`),tos:B(`tos`),updatedAt:V(`updated_at`),uri:B(`uri`),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthClient_userId_idx`).on(e.userId)]),Iu=ku(`oauth_client_assertion`,{expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey()},e=>[vc(`oauthClientAssertion_expiresAt_idx`).on(e.expiresAt)]),Lu=ol(W,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthClientResources:e(Ru),oauthConsents:e(Bu),oauthRefreshTokens:e(G),user:t(q,{fields:[W.userId],references:[q.id]})})),Ru=ku(`oauth_client_resource`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),createdAt:V(`created_at`),id:B(`id`).primaryKey(),metadata:Uo(`metadata`),resourceId:B(`resource_id`).notNull().references(()=>Uu.identifier,{onDelete:`cascade`})},e=>[vc(`oauthClientResource_clientId_idx`).on(e.clientId),yc(`oauthClientResource_clientId_resourceId_uidx`).on(e.clientId,e.resourceId),vc(`oauthClientResource_resourceId_idx`).on(e.resourceId)]),zu=ol(Ru,({one:e})=>({oauthClient:e(W,{fields:[Ru.clientId],references:[W.clientId]}),oauthResource:e(Uu,{fields:[Ru.resourceId],references:[Uu.identifier]})})),Bu=ku(`oauth_consent`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),createdAt:V(`created_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),scopes:B(`scopes`).array().notNull(),updatedAt:V(`updated_at`).notNull(),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthConsent_clientId_idx`).on(e.clientId),vc(`oauthConsent_userId_idx`).on(e.userId)]),Vu=ol(Bu,({one:e})=>({oauthClient:e(W,{fields:[Bu.clientId],references:[W.clientId]}),user:e(q,{fields:[Bu.userId],references:[q.id]})})),G=ku(`oauth_refresh_token`,{acr:B(`acr`),amr:B(`amr`).array(),authorizationCodeId:B(`authorization_code_id`),authTime:V(`auth_time`),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),confirmation:Uo(`confirmation`),createdAt:V(`created_at`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),revoked:V(`revoked`),rotatedAt:V(`rotated_at`),rotationReplayExpiresAt:V(`rotation_replay_expires_at`),rotationReplayResponse:B(`rotation_replay_response`),scopes:B(`scopes`).array().notNull(),sessionId:B(`session_id`).references(()=>K.id,{onDelete:`set null`}),token:B(`token`).notNull().unique(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthRefreshToken_authorizationCodeId_idx`).on(e.authorizationCodeId),vc(`oauthRefreshToken_clientId_idx`).on(e.clientId),vc(`oauthRefreshToken_expiresAt_idx`).on(e.expiresAt),vc(`oauthRefreshToken_rotationReplayExpiresAt_idx`).on(e.rotationReplayExpiresAt),vc(`oauthRefreshToken_sessionId_idx`).on(e.sessionId),vc(`oauthRefreshToken_userId_idx`).on(e.userId)]),Hu=ol(G,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthClient:t(W,{fields:[G.clientId],references:[W.clientId]}),session:t(K,{fields:[G.sessionId],references:[K.id]}),user:t(q,{fields:[G.userId],references:[q.id]})})),Uu=ku(`oauth_resource`,{accessTokenTtl:Po(`access_token_ttl`),allowedScopes:B(`allowed_scopes`).array(),createdAt:V(`created_at`),customClaims:Uo(`custom_claims`),disabled:lo(`disabled`).default(!1),dpopBoundAccessTokensRequired:lo(`dpop_bound_access_tokens_required`).default(!1),id:B(`id`).primaryKey(),identifier:B(`identifier`).notNull().unique(),metadata:Uo(`metadata`),name:B(`name`).notNull(),policyVersion:Po(`policy_version`).default(1),refreshTokenTtl:Po(`refresh_token_ttl`),signingAlgorithm:B(`signing_algorithm`),signingKeyId:B(`signing_key_id`),updatedAt:V(`updated_at`)}),Wu=ol(Uu,({many:e})=>({oauthClientResources:e(Ru)})),K=ku(`session`,{createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),ipAddress:B(`ip_address`),token:B(`token`).notNull().unique(),updatedAt:V(`updated_at`).$onUpdate(()=>new Date).notNull(),userAgent:B(`user_agent`),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`session_expiresAt_idx`).on(e.expiresAt),vc(`session_userId_idx`).on(e.userId)]),Gu=ol(K,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthRefreshTokens:e(G),user:t(q,{fields:[K.userId],references:[q.id]})})),q=ku(`user`,{createdAt:V(`created_at`).defaultNow().notNull(),email:B(`email`).notNull().unique(),emailVerified:lo(`email_verified`).default(!1).notNull(),id:B(`id`).primaryKey(),image:B(`image`),name:B(`name`).notNull(),updatedAt:V(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull()}),Ku=ol(q,({many:e})=>({accounts:e(Au),oauthAccessTokens:e(Pu),oauthClients:e(W),oauthConsents:e(Bu),oauthRefreshTokens:e(G),sessions:e(K)})),qu=ku(`verification`,{createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),identifier:B(`identifier`).notNull(),updatedAt:V(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull(),value:B(`value`).notNull()},e=>[vc(`verification_expiresAt_idx`).on(e.expiresAt),vc(`verification_identifier_idx`).on(e.identifier)]),Ju=r({accessKeys:()=>Yu,account:()=>Au,accountConfigs:()=>Xu,accountRelations:()=>ju,appRealms:()=>Zu,auditEvents:()=>Qu,deviceCode:()=>Mu,deviceRequests:()=>$u,firstAccounts:()=>ed,jwks:()=>Nu,keys:()=>td,oauthAccessToken:()=>Pu,oauthAccessTokenRelations:()=>Fu,oauthClient:()=>W,oauthClientAssertion:()=>Iu,oauthClientRelations:()=>Lu,oauthClientResource:()=>Ru,oauthClientResourceRelations:()=>zu,oauthConsent:()=>Bu,oauthConsentRelations:()=>Vu,oauthRefreshToken:()=>G,oauthRefreshTokenRelations:()=>Hu,oauthResource:()=>Uu,oauthResourceRelations:()=>Wu,pendingKeys:()=>nd,realmPasskeys:()=>rd,realmPrivy:()=>id,realmSecp256k1:()=>ad,realms:()=>J,revokedSigningKeys:()=>od,secp256k1Owners:()=>sd,securityEvents:()=>cd,session:()=>K,sessionRelations:()=>Gu,user:()=>q,userRelations:()=>Ku,verification:()=>qu}),Yu=ku(`access_keys`,{account:B(`account`).notNull(),address:B(`address`).notNull(),chainId:Po(`chain_id`).notNull(),clientId:B(`client_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),keyType:B(`key_type`).notNull(),limits:Uo(`limits`),realmId:B(`realm_id`),revokedAt:V(`revoked_at`),scopes:Uo(`scopes`),transaction:B(`transaction`),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`access_keys_expires_at_idx`).on(e.expiresAt),vc(`access_keys_user_id_idx`).on(e.userId,e.expiresAt),bc({columns:[e.chainId,e.account,e.address]})]),Xu=ku(`account_configs`,{address:B(`address`).notNull(),chainId:Po(`chain_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),key:B(`key`).notNull(),owners:Uo(`owners`).notNull(),salt:B(`salt`).notNull(),threshold:Po(`threshold`).notNull(),updatedAt:V(`updated_at`).defaultNow().notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`}),version:B(`version`).notNull()},e=>[bc({columns:[e.chainId,e.address]}),vc(`account_configs_user_id_idx`).on(e.userId)]),Zu=ku(`app_realms`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),position:Po(`position`).notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id)},e=>[mc(`app_realms_position_check`,z`${e.position} >= 0`),bc({columns:[e.clientId,e.position]}),Bi(`app_realms_client_id_realm_id_unique`).on(e.clientId,e.realmId)]),Qu=ku(`audit_events`,{action:B(`action`).notNull(),actor:B(`actor`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),details:Uo(`details`).$type().notNull(),id:B(`id`).primaryKey(),requestId:B(`request_id`),targetId:B(`target_id`).notNull(),targetType:B(`target_type`).notNull()},e=>[vc(`audit_events_created_at_idx`).on(e.createdAt,e.id),vc(`audit_events_target_idx`).on(e.targetType,e.targetId)]),$u=ku(`device_requests`,{account:B(`account`),challenge:B(`challenge`),city:B(`city`),country:B(`country`),createdAt:V(`created_at`).defaultNow().notNull(),device:B(`device`),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),ip:B(`ip`),key:Uo(`key`),keyAuthorization:Uo(`key_authorization`),location:B(`location`)},e=>[vc(`device_requests_expires_at_idx`).on(e.expiresAt)]),ed=ku(`first_accounts`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id,{onDelete:`cascade`}),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[bc({columns:[e.userId,e.realmId]})]),td=ku(`keys`,{address:B(`address`).unique(),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),publicKey:B(`public_key`).notNull(),rpId:B(`rp_id`).notNull(),source:B(`source`).notNull(),type:B(`type`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[mc(`keys_source_check`,z`${e.source} in ('registered', 'tempo-id', 'tempo-wallet', 'wallet')`),mc(`keys_type_check`,z`${e.type} = 'passkey'`),vc(`keys_user_id_idx`).on(e.userId)]),nd=ku(`pending_keys`,{account:B(`account`).notNull(),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),codeChallenge:B(`code_challenge`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),keyAuthorization:Uo(`key_authorization`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`pending_keys_expires_at_idx`).on(e.expiresAt),bc({columns:[e.clientId,e.codeChallenge]})]),rd=ku(`realm_passkeys`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`}),rpId:B(`rp_id`).notNull().unique()}),id=ku(`realm_privy`,{appId:B(`app_id`).notNull().unique(),appSecret:B(`app_secret`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`})}),ad=ku(`realm_secp256k1`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`})}),J=ku(`realms`,{createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),name:B(`name`).notNull()},e=>[mc(`realms_id_check`,z`${e.id} ~ '^[a-z0-9]+(-[a-z0-9]+)*$'`)]),od=ku(`revoked_signing_keys`,{alg:B(`alg`),id:B(`id`).primaryKey(),publicKey:B(`public_key`).notNull(),revokedAt:V(`revoked_at`).notNull(),signsUntil:V(`signs_until`).notNull()}),sd=ku(`secp256k1_owners`,{address:B(`address`).notNull().unique(),createdAt:V(`created_at`).defaultNow().notNull(),privateKey:B(`private_key`).notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id,{onDelete:`cascade`}),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[bc({columns:[e.userId,e.realmId]})]),cd=ku(`security_events`,{clientId:B(`client_id`),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),type:B(`type`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`security_events_created_at_idx`).on(e.createdAt),vc(`security_events_user_idx`).on(e.userId,e.createdAt,e.id)]),ld=`Payload Too Large`,ud=e=>{let t=e.onError||(()=>{throw new hn(413,{res:new Response(ld,{status:413})})}),n=e.maxSize;return async function(e,r){if(!e.req.raw.body)return r();let i=e.req.raw.headers.has(`transfer-encoding`);if(e.req.raw.headers.has(`content-length`)&&!i)return parseInt(e.req.raw.headers.get(`content-length`)||`0`,10)>n?t(e):r();let a=0,o=[],s=e.req.raw.body.getReader();for(;;){let{done:r,value:i}=await s.read();if(r)break;if(a+=i.length,a>n)return t(e);o.push(i)}let c={body:new ReadableStream({start(e){for(let t of o)e.enqueue(t);e.close()}}),duplex:`half`};return e.req.raw=new Request(e.req.raw,c),r()}},dd=`https://github.com/tempoxyz/id/blob/main/docs/errors.md`,fd={already_decided:{description:`The user code was already approved or denied.`,error:`invalid_request`,status:409},app_exists:{description:`Another OAuth app already has the client ID.`,error:`invalid_request`,status:409},authorization_expired:{description:`The app's authorization request that sign-in or the approval page continues is forged or expired.`,error:`invalid_request`,status:400},backend_sign_in_not_permitted:{description:`The app may not sign users in from its backend: it is not an enabled first-party app with a client secret and backend sign-in.`,error:`unauthorized_client`,status:403},body_too_large:{description:`The request body exceeds 64 KiB.`,error:`invalid_request`,status:413},challenge_not_permitted:{description:"A request carries a challenge, and its app lacks the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},config_conflict:{description:`The chain's configuration of the account differs from the one that Tempo ID stores.`,error:`invalid_request`,status:409},configurable_accounts_disabled:{description:`The deployment has no configurable accounts, or the request names another chain.`,error:`invalid_request`,status:400},cross_site_request:{description:`A form or body-less write came from another site.`,error:`access_denied`,status:403},duplicate_limit:{description:`Two limits name the same token.`,error:`invalid_authorization_details`,status:400},duplicate_scope:{description:`Two scopes name the same call on one target, or one allows any function on a target that another names a function on.`,error:`invalid_authorization_details`,status:400},employee_required:{description:`The request carries no verified Tempo employee identity, or the identity is inactive.`,error:`access_denied`,status:401},empty_limits:{description:"`limits` is an empty list.",error:`invalid_authorization_details`,status:400},empty_scopes:{description:"`scopes` is an empty list.",error:`invalid_authorization_details`,status:400},expiry_exceeds_maximum:{description:`A headless key lasts longer than a year.`,error:`invalid_authorization_details`,status:403},expiry_passed:{description:`The key expiry has passed.`,error:`invalid_authorization_details`,status:400},foreign_account:{description:`The request names a Tempo Account that is not the user's in the app's realms.`,error:`access_denied`,status:403},invalid_app:{description:`A value of an OAuth app, such as its name or a redirect URI, is not valid, or does not fit the app's type.`,error:`invalid_request`,status:400},invalid_chain:{description:`The key chain ID is 0.`,error:`invalid_authorization_details`,status:400},invalid_client:{description:`The client authentication failed: the app is unknown or disabled, or the client secret is missing or wrong.`,error:`invalid_client`,status:401},invalid_client_attestation:{description:`A native app's client attestation, its proof, or the platform attestation behind it is missing or does not verify.`,error:`invalid_client`,status:401},invalid_code:{description:`The emailed code is wrong or expired.`,error:`invalid_grant`,status:401},invalid_dpop_proof:{description:`The DPoP proof of a code redemption is missing, invalid, replayed, or from another key than the tokens.`,error:`invalid_dpop_proof`,status:400},invalid_expiry:{description:`The key expiry is 0, which never expires.`,error:`invalid_authorization_details`,status:400},invalid_field:{description:`A field is missing or malformed.`,error:`invalid_request`,status:400},invalid_id_token_hint:{description:`The ID token hint is not an ID token that Tempo ID signed for the app.`,error:`invalid_request`,status:400},invalid_origin:{description:`A headless request came from an origin its redirect URI does not allow.`,error:`unauthorized_client`,status:403},invalid_period:{description:"A limit's `period` is not a whole number of seconds.",error:`invalid_authorization_details`,status:400},invalid_public_key:{description:`The key public key is not a valid point.`,error:`invalid_authorization_details`,status:400},invalid_realm:{description:`A value of a realm, such as its ID, name, passkey relying party, or Privy app, or a list of an app's realms, is not valid.`,error:`invalid_request`,status:400},invalid_recipients:{description:"A scope's `recipients` names the zero address or a duplicate, or is on a call other than `transfer`, `transferWithMemo`, or `approve` on a TIP-20 token.",error:`invalid_authorization_details`,status:400},limit_exceeds_maximum:{description:`A headless key limit exceeds the token’s ceiling.`,error:`invalid_authorization_details`,status:403},logout_not_permitted:{description:`The app that the ID token hint names may not end the session at the end-session endpoint.`,error:`unauthorized_client`,status:403},malformed_body:{description:`The request body is not valid JSON.`,error:`invalid_request`,status:400},missing_key:{description:`The key authorization names no key.`,error:`invalid_authorization_details`,status:400},missing_permissions:{description:"A third-party app's key request leaves out `expiry`, `limits`, or `scopes`.",error:`invalid_authorization_details`,status:400},missing_recipients:{description:"An `approve` scope names no spenders.",error:`invalid_authorization_details`,status:400},passkey_link_expired:{description:`The email step's link to a wallet.tempo passkey expired, or the browser holds no link for it.`,error:`invalid_request`,status:400},passkey_not_permitted:{description:`A passkey sign-in names an app, or reaches a realm, that holds no passkeys for Tempo ID.`,error:`unauthorized_client`,status:403},passkey_register_not_permitted:{description:"A passkey registration comes from an app's page, and no app at the page's origin holds the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},not_configurable:{description:`The account is not configurable on the chain, so no owner can join it, or no passkey owns it, so it cannot upgrade.`,error:`invalid_request`,status:400},origin_required:{description:"A request without `Origin` names an app by `client_id` alone, which proves no app.",error:`access_denied`,status:403},owner_exists:{description:`The account already holds the owner that the request adds, or is already configurable.`,error:`invalid_request`,status:409},owner_unavailable:{description:`The user's cloud wallet cannot join the account, since its own account holds a balance or live access keys, another account names it, or no realm creates one.`,error:`invalid_request`,status:409},passkey_limit:{description:`The user holds the most passkeys that Tempo ID registers for one user.`,error:`access_denied`,status:403},post_logout_redirect_not_permitted:{description:`The post-logout redirect URI is not one of the post-logout redirect URIs the app registered.`,error:`invalid_request`,status:400},privy_app_taken:{description:`Another realm holds the Privy app.`,error:`invalid_request`,status:409},public_app:{description:`The OAuth app redeems codes with PKCE alone, so it has no client secret to rotate.`,error:`invalid_request`,status:400},pushed_authorization_required:{description:`The OAuth app requires a pushed authorization request (RFC 9126) for a key, and the request carries its parameters in the URL.`,error:`invalid_request`,status:400},rate_limited:{description:`Tempo ID, or a service it depends on, is rate limiting the request.`,error:`temporarily_unavailable`,status:429},realm_exists:{description:`A realm with the ID exists.`,error:`invalid_request`,status:409},realm_in_use:{description:`An OAuth app names the realm, so it cannot be removed.`,error:`invalid_request`,status:409},reauthentication_required:{description:`The request needs a session that signed in within the last 10 minutes, such as for a passkey registration, an owner change, or a key above the headless ceiling.`,error:`login_required`,status:401},rejected:{description:`The issuer refused the authorization request.`,error:`invalid_request`,status:400},relying_party_taken:{description:`Another realm holds the passkey relying party.`,error:`invalid_request`,status:409},scope_without_limit:{description:`A scope calls a listed token that no limit names.`,error:`invalid_authorization_details`,status:400},session_changed:{description:`The signed-in session differs from the one that the approval page showed.`,error:`invalid_request`,status:409},session_required:{description:`The request needs a signed-in session.`,error:`login_required`,status:401},sign_not_permitted:{description:"A request to sign as the user's cloud wallet comes from a page that is not a first-party app with the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},sign_out_link_expired:{description:`A security email's link to sign out every session is unknown, spent, or expired.`,error:`invalid_request`,status:400},sign_up_not_permitted:{description:`The verified address has no account, and its domain is not one where the deployment creates accounts.`,error:`access_denied`,status:403},signing_key_in_use:{description:`A revocation names a signing key that signs tokens now or after the publication delay, without a rotation.`,error:`invalid_request`,status:409},too_many_signing_keys:{description:`The deployment holds the most signing keys that a rotation keeps, live or in their grace period.`,error:`invalid_request`,status:409},unexpected:{description:`An unexpected failure.`,error:`server_error`,status:500},unknown_app:{description:`No registered OAuth app has the client ID.`,error:`invalid_request`,status:404},unknown_code:{description:`The user code is wrong or expired.`,error:`invalid_request`,status:404},unknown_endpoint:{description:`No API endpoint matches this method and path.`,error:`invalid_request`,status:404},unknown_key:{description:`The signed-in user holds no live access key with the address on the account and chain.`,error:`invalid_request`,status:404},unknown_realm:{description:`No realm has the ID.`,error:`invalid_request`,status:404},unknown_session:{description:`The user has no session with the ID.`,error:`invalid_request`,status:404},unknown_signing_key:{description:`No signing key that is not revoked has the ID.`,error:`invalid_request`,status:404},unknown_user:{description:`No user has the ID.`,error:`invalid_request`,status:404},unsupported_call:{description:`A selector does not parse, a scope allows any function on a TIP-20 token, or a headless scope names an unrecognized call.`,error:`invalid_authorization_details`,status:400},unsupported_token:{description:`A limit names a token that is not supported on the chain.`,error:`invalid_authorization_details`,status:400},upgrade_required:{description:`A key authorization names a wallet.tempo passkey's account on a chain whose accounts are configurable, before its upgrade.`,error:`interaction_required`,status:403},upstream_unavailable:{description:`A service Tempo ID depends on failed or did not respond.`,error:`temporarily_unavailable`,status:503},webauthn_rejected:{description:`A passkey ceremony failed: its challenge is unknown, spent, or expired, or its response does not verify.`,error:`access_denied`,status:401},webauthn_required:{description:`A request without a page names a Tempo Account whose passkey signs only on a Tempo ID page.`,error:`interaction_required`,status:403}},pd=class extends hn{name=`ErrorResponse.ResponseError`;response;constructor(e){let t=fd[e.reason].status;super(t,{res:Response.json(e,{status:t})}),this.response=e}};function md(e){return class extends pd{static reason=e;constructor(t){super(Sd({...t,reason:e}))}}}var hd=class extends md(`cross_site_request`){name=`ErrorResponse.CrossSiteRequestError`;constructor(){super({error_description:`Cross-site request refused. Send JSON from an allowed origin.`})}},gd=class extends md(`malformed_body`){name=`ErrorResponse.MalformedBodyError`;constructor(){super({error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."})}},_d=class extends md(`rate_limited`){name=`ErrorResponse.RateLimitedError`;retryAfter;constructor(e={}){let{retryAfter:t}=e;super({error_description:`Rate limited by an upstream service. Try again ${t?`in ${Ed({seconds:t})}`:`later`}.`,...t?{meta:{retryAfter:t}}:{}}),this.retryAfter=t}},vd=class extends md(`unexpected`){name=`ErrorResponse.UnexpectedError`;constructor(){super({error_description:`Unexpected error. Try again.`})}},yd=class extends md(`unknown_endpoint`){name=`ErrorResponse.UnknownEndpointError`;constructor(){super({error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`})}},bd=class extends md(`upstream_unavailable`){name=`ErrorResponse.UpstreamUnavailableError`;constructor(){super({error_description:`An upstream service is unavailable. Retry later.`})}},xd;(function(e){let t=e.base=v({error:y().meta({description:"The OAuth error code (RFC 6749, OIDC Core, RFC 8628, RFC 9396), which `reason` determines."}),error_description:y().meta({description:`What went wrong and how to fix it, for people. Its wording may change.`}),error_uri:se().meta({description:"The errors page, at the refusal’s `reason`."}),field:y().optional().meta({description:`Extension: the request field at fault, as a dotted path.`}),meta:C(y(),ce([S(),y()])).readonly().optional().meta({description:`Extension: the values the refusal compared. Base units are decimal strings.`}),reason:y().meta({description:`Extension: a stable name for the refusal, to branch on.`}),request_id:y().optional().meta({description:"Extension: the request ID, which `X-Request-Id` also carries. The Worker adds it to every error response."})}),n={already_decided:{error_description:`Code already approved or denied.`,field:`code`},app_exists:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T already exists. Update it, or choose another client ID.`,field:`clientId`},authorization_expired:{error_description:`Expired authorization request: the request from the app is no longer valid. Return to the app, and start again.`,field:`oauth_query`},backend_sign_in_not_permitted:{error_description:"Backend sign-in not permitted: the app does not hold backend sign-in. Grant it with `tempo-id admin apps clientId patch <client-id> --backend-sign-in true`.",field:`client_id`},body_too_large:{error_description:`Invalid request body: exceeds the 65536-byte maximum. Send a body of 65536 bytes or fewer.`},challenge_not_permitted:{error_description:"Challenge not permitted: the app lacks the `tempo-id:sign` scope. Remove `challenge`, or grant the app the scope.",field:`challenge`},config_conflict:{error_description:`Configuration conflict: the chain's configuration of 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c differs from the stored one. Reload the account, and try again.`,field:`account`},configurable_accounts_disabled:{error_description:"Configurable accounts are not available on the chain `testnet`. Select the chain `t14`.",field:`chain`},cross_site_request:{error_description:`Cross-site request refused. Send JSON from an allowed origin.`},duplicate_limit:{error_description:`Duplicate limit for 0x20c0000000000000000000000000000000000001. Limit each token once.`,field:`key_authorization.limits.1.token`},duplicate_scope:{error_description:`Duplicate scope for 0xa9059cbb on OUSD. Name each call on a target once.`,field:`key_authorization.scopes.1.selector`},employee_required:{error_description:`Employee identity required: the Cf-Access-Jwt-Assertion header holds no verified employee identity for this app. Forward the access assertion of a request that the app's access policy admitted.`,field:`Cf-Access-Jwt-Assertion`},empty_limits:{error_description:"Empty `limits`. Name at least one token, or omit `limits`.",field:`key_authorization.limits`},empty_scopes:{error_description:"Empty `scopes`. Name at least one call, or omit `scopes`.",field:`key_authorization.scopes`},expiry_exceeds_maximum:{error_description:"Invalid `expiry`: Sat, 01 Jan 2028 00:00:00 GMT exceeds the one-year maximum. Use an earlier expiry, or authorize through a redirect or device grant.",field:`key_authorization.expiry`},expiry_passed:{error_description:"Invalid `expiry`: Wed, 01 Jan 2025 00:00:00 GMT has passed. Use a future Unix time.",field:`key_authorization.expiry`},foreign_account:{error_description:`Access denied to Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Name one of the user's accounts in the app's realms.`,field:`account`},invalid_app:{error_description:`Invalid redirect URI: http://app.example/callback uses http. Use an https URI.`},invalid_chain:{error_description:"Invalid `chainId`: 0. Use a Tempo chain ID, such as 4217.",field:`key_authorization.chainId`},invalid_client:{error_description:`Client authentication failed. Send the client ID and secret, or a client assertion, of an enabled app.`,field:`client_secret`},invalid_client_attestation:{error_description:"Invalid client attestation: the proof is too old, or issued in the future. Attest the app again at `POST /v1/attestation`, and send a new proof.",field:`OAuth-Client-Attestation-PoP`},invalid_code:{error_description:`Invalid or expired code. Request a new one.`,field:`code`},invalid_dpop_proof:{error_description:`Invalid DPoP proof: DPoP proof jti has already been used. Send a new proof for POST /oauth2/token from the key of the app.`,field:`dpop`},invalid_expiry:{error_description:"Invalid `expiry`: 0 never expires. Use a future Unix time.",field:`key_authorization.expiry`},invalid_field:{error_description:"Invalid request. `email`: Invalid email address.",field:`email`},invalid_id_token_hint:{error_description:`Invalid id_token_hint: it is not an ID token that this issuer signed for the app. Send the ID token that the app received at sign-in.`,field:`id_token_hint`},invalid_origin:{error_description:"Invalid `Origin`: https://other.example.com. Requests for this redirect URI must come from https://app.example.com.",field:`Origin`},invalid_period:{error_description:"Invalid `period` on the OUSD limit: 1.5. Use a whole number of seconds, or 0 for a one-time limit.",field:`key_authorization.limits.0.period`},invalid_public_key:{error_description:"Invalid `publicKey`. Provide an uncompressed public key, or `address`.",field:`key_authorization.publicKey`},invalid_realm:{error_description:`Invalid id: Use lowercase kebab case, such as tempo-cash.`},invalid_recipients:{error_description:`Invalid recipient 0x0000000000000000000000000000000000000000 for 0x095ea7b3 on OUSD. Name each recipient once, and never the zero address.`,field:`key_authorization.scopes.0.recipients.0`},limit_exceeds_maximum:{error_description:`Invalid OUSD limit: 5000 exceeds the 1000 maximum. Lower the limit, or authorize through a redirect or device grant.`,field:`key_authorization.limits.0.limit`},logout_not_permitted:{error_description:`Logout not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T may not end the session. Register the app for logout, then retry.`},malformed_body:{error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."},missing_key:{error_description:"Missing `address` or `publicKey`. Provide the access key.",field:`key_authorization.address`},missing_permissions:{error_description:"Missing `limits` and `scopes`. Name the expiry, limits, and scopes of the key. Without `limits` and `scopes`, a key spends any amount or makes any call.",field:`key_authorization.limits`},missing_recipients:{error_description:"Missing `recipients` for `approve` on OUSD. Name the allowed spenders.",field:`key_authorization.scopes.0.recipients`},passkey_link_expired:{error_description:`Expired passkey sign-in: the link from the passkey step is no longer valid. Enter the code again to sign in with email only, or sign in with the passkey again.`,field:`link`},passkey_not_permitted:{error_description:`Passkey not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T holds no passkeys. Sign in with an emailed code.`},passkey_register_not_permitted:{error_description:"Passkey registration not permitted: no app at https://app.example.com holds the `tempo-id:sign` scope. Register the passkey on Tempo ID, or grant the app the scope."},not_configurable:{error_description:`Not configurable: 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account yet. Upgrade it with its passkey, then add the owner.`,field:`account`},origin_required:{error_description:`Origin required: the request names the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T without an Origin header. Send it from a page at a redirect URI of the app, or leave out client_id.`,field:`client_id`},owner_exists:{error_description:`Owner exists: a cloud wallet already owns 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Use the account as it is.`,field:`wallet`},owner_unavailable:{error_description:"Owner unavailable: the cloud wallet 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c holds a balance on its own account, so it cannot join 0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f. Move the balance to another account, or upgrade without `add_owner`.",field:`add_owner`},passkey_limit:{error_description:`Passkey limit reached: the user holds 10 registered passkeys, the most that Tempo ID registers. Sign in with one of them.`},post_logout_redirect_not_permitted:{error_description:`Invalid post_logout_redirect_uri: https://app.example/elsewhere is not registered for the app. Use one of its post-logout redirect URIs, or leave it out.`,field:`post_logout_redirect_uri`},privy_app_taken:{error_description:`Privy app cm0000000000000000000000 belongs to another realm. Give each realm its own Privy app.`,field:`appId`},public_app:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T has no client secret. Rotate the secret of an app with a backend.`,field:`clientId`},pushed_authorization_required:{error_description:"Pushed authorization request required: the app sends `key_authorization` only through `/oauth2/par`. Push the request, and send its `request_uri` to `/oauth2/authorize`.",field:`key_authorization`},rate_limited:{error_description:`Too many requests. Try again in 30 seconds.`},realm_exists:{error_description:`Realm tempo-cash exists. Choose another ID.`,field:`id`},realm_in_use:{error_description:`Realm tempo-cash is in use. Remove it from the realms of each app first.`,field:`id`},reauthentication_required:{error_description:`Sign in again: this action needs a sign-in within the last 10 minutes. Confirm the sign-in with a passkey or an emailed code, then retry.`},rejected:{error_description:"Authorization request rejected. Check `client_id`, `redirect_uri`, and `scope` against the app's registration."},relying_party_taken:{error_description:`Relying party example.com belongs to another realm. Give each realm its own relying party.`,field:`rpId`},scope_without_limit:{error_description:`Scope on 0x20c0000000000000000000000000000000000002 has no limit. Add a limit for it, or remove the scope.`,field:`key_authorization.scopes.0.address`},session_changed:{error_description:`Changed session: the signed-in account differs from the one that this page showed. Reload the page, and check the account before the decision.`,field:`session_id`},session_required:{error_description:`Sign in first.`},sign_not_permitted:{error_description:"Signing not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T at https://app.example.com does not hold the `tempo-id:sign` scope. Grant the app the scope, or sign with the account's passkey.",field:`client_id`},sign_out_link_expired:{error_description:`Expired link: the link to sign out every session is spent or older than 7 days. Sign in, and review the passkeys and apps of the account.`,field:`token`},sign_up_not_permitted:{error_description:`Sign-up not permitted: new accounts need an address at example.com. Sign in with an existing account, or with an address at example.com.`,field:`email`},signing_key_in_use:{error_description:`Invalid revocation of signing key 0b5c2f0e-4f7a-4a8e-9a43-3f1d7b8c6e21: the key signs tokens now or after the 5-minute publication delay. Set rotate to true to replace the key in the same operation.`,field:`rotate`},too_many_signing_keys:{error_description:`Too many signing keys: 100 are live or in their grace period. Rotate again after the grace period of the oldest key ends.`},unexpected:{error_description:`Unexpected error. Try again.`},unknown_app:{error_description:`Unknown app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T. Name a registered OAuth app.`,field:`clientId`},unknown_code:{error_description:`Invalid or expired code. Check the code in the terminal.`,field:`code`},unknown_endpoint:{error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`},unknown_key:{error_description:`Unknown access key 0x81C0f22bD173C115d18eeeA0F6a38E935ecF52fB: no live key with this address acts for the account on the chain. Reload the keys, and name a listed one.`,field:`address`},unknown_realm:{error_description:`Unknown realm tempo-cash. Add it first.`,field:`id`},unknown_session:{error_description:`Unknown session 9fQe2hXc7mLk. Name a live session from GET /users/user_01JZ8Q6W3N1R5B4V7C2X9K0M3T.`,field:`sessionId`},unknown_signing_key:{error_description:`Unknown signing key 0b5c2f0e-4f7a-4a8e-9a43-3f1d7b8c6e21: no live, retired, or expired key has the ID. List the keys, and name a key that is not revoked.`,field:`kid`},unknown_user:{error_description:`Unknown user user_01JZ8Q6W3N1R5B4V7C2X9K0M3T. Name a user that exists.`,field:`id`},unsupported_call:{error_description:"Unsupported call on OUSD: any function, which includes `approve` without spenders. Name each function in `selector`, such as `transfer`.",field:`key_authorization.scopes.0.selector`},unsupported_token:{error_description:`Unsupported token on chain 4217: 0x20c00000000000000000000000000000000000ff. Use a supported token, such as OUSD.`,field:`key_authorization.limits.0.token`},upgrade_required:{error_description:`Upgrade required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account on this chain yet. Upgrade it on the account page, then authorize again.`,field:`key_authorization.account`},upstream_unavailable:{error_description:`An upstream service is unavailable. Retry later.`},webauthn_rejected:{error_description:`Passkey rejected. Request new options, then try again with the same passkey or another one.`},webauthn_required:{error_description:`Passkey required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c signs key authorizations only with its passkey, on a Tempo ID page. Authorize through a redirect, popup, or device grant, or name another account.`,field:`key_authorization.account`}},r=new Map(Object.entries(fd).map(([e,r])=>{let i=n[e],a=t.extend({error:ve(r.error).meta(t.shape.error.meta()),error_description:t.shape.error_description.meta({...t.shape.error_description.meta(),examples:[i.error_description]}),error_uri:t.shape.error_uri.meta({...t.shape.error_uri.meta(),examples:[`${dd}#${e}`]}),reason:ve(e).meta(t.shape.reason.meta()),request_id:t.shape.request_id.meta({...t.shape.request_id.meta(),examples:[`8f1c2a3b4d5e6f70-SJC`]})});return[e,(i.field?a.extend({field:t.shape.field.meta({...t.shape.field.meta(),examples:[i.field]})}):a.omit({field:!0})).meta({description:`\`${r.error}\` (${r.status}): ${r.description}`,id:`ErrorResponse.${e}`})]}));function i(e){return r.get(e)}e.of=i})(xd||={});function Sd(e){let{error_description:t,field:n,meta:r,reason:i}=e;return{error:fd[i].error,error_description:t,error_uri:`${dd}#${i}`,...n?{field:n}:{},...r?{meta:r}:{},reason:i}}function Cd(e){if(e instanceof hn)return;let t=`status`in e?e.status:void 0;if(t===429)return new _d({retryAfter:(()=>{if(e instanceof Response){let t=Number(e.headers.get(`retry-after`));return Number.isInteger(t)&&t>0?t:void 0}return`retryAfter`in e&&typeof e.retryAfter==`number`?e.retryAfter:void 0})()});let n=`status`in e&&t===void 0;if(typeof t==`number`&&(t===408||t>=500)||n||e instanceof Error&&e.name===`TimeoutError`)return new bd}(function(e){e.errors=[_d,bd]})(Cd||={});function wd(e,t){if(e instanceof pd)return Td(t,e);if(e instanceof hn&&e.status===400)return Td(t,new gd);if(e instanceof hn&&e.status===403)return Td(t,new hd);let n=Cd(e);return n?(gr(t,{error:e,message:`An upstream service refused a request.`}),Td(t,n)):(pr(t,{error:e,message:`The API failed a request.`}),Td(t,new vd))}function Td(e,t){let{response:n}=t;return t instanceof _d&&t.retryAfter&&e.header(`retry-after`,String(t.retryAfter)),e.json(n,fd[n.reason].status)}function Ed(e){let{seconds:t}=e,[n,r]=t<60?[t,`second`]:t<3600?[Math.ceil(t/60),`minute`]:[Math.ceil(t/3600),`hour`];return new Intl.NumberFormat(`en`,{style:`unit`,unit:r,unitDisplay:`long`}).format(n)}var Dd=class extends md(`body_too_large`){name=`BodyLimit.BodyTooLargeError`;constructor(e={}){let{maximum:t=Od}=e;super({error_description:`Invalid request body: exceeds the ${t}-byte maximum. Send a body of ${t} bytes or fewer.`,meta:{maximum:t}})}},Od=65536,kd=ud({maxSize:Od,onError:e=>Td(e,new Dd)}),Ad=e=>e.__COMPOSED_HANDLER?Ad(e[Ln]):e,jd=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;return n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t),h(r,e)[e]}return r?h(r):{}},Md=(e,t,n)=>{let r;return r=n?.prefix===`secure`?d(`__Secure-`+e,t,{path:`/`,...n,secure:!0}):n?.prefix===`host`?d(`__Host-`+e,t,{...n,path:`/`,secure:!0,domain:void 0}):d(e,t,{path:`/`,...n}),r},Nd=(e,t,n,r)=>{let i=Md(t,n,r);e.header(`Set-Cookie`,i,{append:!0})},Pd=(e,t,n)=>{let r=jd(e,t,n?.prefix);return Nd(e,t,``,{...n,maxAge:0}),r},Fd=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,Id=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/i,Ld=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,Rd=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Fd.test(a))break;try{i=await n.req.json()}catch{throw new hn(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(Id.test(a)||Ld.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{e=await _n(await n.req.arrayBuffer(),a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new hn(400,{message:t})}let t=Object.create(null);e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):Object.hasOwn(t,n)?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=jd(n)}let o=await t(i,n);return o instanceof Response?o:(n.req.addValidatedData(e,o),await r())},zd={header:[`cookie`]};function Bd(e,t,n){if(!(n in zd))return e;let r=zd[n]||[];return t===`arktype`?Vd(e,r):t===`valibot`?Hd(e,r):e}function Vd(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`data`in e&&typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)){let n={...e.data};for(let e of t)delete n[e];let r=Object.create(Object.getPrototypeOf(e));return Object.assign(r,e,{data:n}),r}return e})}function Hd(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`path`in e&&Array.isArray(e.path)){for(let n of e.path)if(typeof n==`object`&&`input`in n&&typeof n.input==`object`&&n.input!==null&&!Array.isArray(n.input))for(let e of t)delete n.input[e]}return e})}var Ud=(e,t,n)=>Rd(e,async(r,i)=>{let a=await t[`~standard`].validate(r);if(n){let t=await n(a.issues?{data:r,error:a.issues,success:!1,target:e}:{data:r,success:!0,target:e},i);if(t){if(t instanceof Response)return t;if(typeof t==`object`&&`response`in t)return t.response}}if(a.issues){let n=Bd(a.issues,t[`~standard`].vendor,e);return i.json({data:r,error:n,success:!1},400)}return a.value}),Wd=Symbol(`openapi`),Gd=`__HonoOpenAPIValidator__`,Kd=[`GET`,`PUT`,`POST`,`DELETE`,`OPTIONS`,`HEAD`,`PATCH`,`TRACE`],qd=e=>{let t=e;if(t.startsWith(`:`)){let e=t.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);e?t=`{${e[1]}}`:(t=t.slice(1,t.length),t.endsWith(`?`)&&(t=t.slice(0,-1)),t=`{${t}}`)}return t},Jd=e=>e.split(`/`).map(qd).join(`/`),Yd=e=>e.split(/[\W_]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),Xd=e=>{let t=e.method.toLowerCase();if(e.path===`/`)return`${t}Index`;for(let n of e.path.split(`/`)){let e=qd(n);e.charCodeAt(0)===123?t+=`By${Yd(e.slice(1,-1))}`:t+=Yd(e)}return t},Zd=e=>`$ref`in e?e.$ref:`${e.in} ${e.name}`;function Qd(...e){let t=e.flatMap(e=>e??[]).reduce((e,t)=>(e.set(Zd(t),t),e),new Map);return Array.from(t.values())}var $d=new Map;function ef(e,t){let n=[];for(let[r,i]of t){if(!i)continue;let t=r.endsWith(`/*`)?r.slice(0,-2):r;(e===t||e.startsWith(`${t}/`))&&n.push(i)}return n}function tf(e,t){return!e||!t||`$ref`in e||`$ref`in t?t:{...e,...t,content:{...e.content,...t.content}}}function nf(e,...t){return t.reduce((t,n)=>{if(!n||!t)return t;for(let[r,i]of Object.entries(n))if(i!=null){if(r in t&&(typeof i==`object`||typeof i==`function`&&r===`operationId`)){if(Array.isArray(i)){let e=[...t[r]??[],...i];t[r]=r===`tags`?Array.from(new Set(e)):r===`parameters`?Qd(e):e}else typeof i==`function`?t[r]=i(e):r===`parameters`?t[r]=Qd(t[r],i):r===`requestBody`?t.requestBody=tf(t.requestBody,i):t[r]={...t[r],...i}}else t[r]=i}return t},{operationId:Xd(e)})}function rf({route:e,specs:t,paths:n},r=$d){let i=Jd(e.path),a=e.method.toLowerCase();if(a===`all`){if(!t)return;if(r.has(i)){let n=r.get(i)??{};r.set(i,nf(e,n,t))}else r.set(i,t)}else{let o=ef(i,r);i in n||(n[i]={}),n[i]&&(n[i][a]=nf(e,...o,n[i]?.[a],t))}}function af(e,t){let{exclude:n,excludeStaticFile:r}=t.options,i={},a=Array.isArray(n)?n:[n];for(let[n,o]of Object.entries(e)){if(o==null||a.some(e=>typeof e==`string`?n===e:e.test(n))||n.includes(`*`)&&!n.includes(`{`))continue;if(r){let e=n.includes(`{`),t=(n.split(`/`).pop()||``).includes(`.`);if(!e&&t)continue}for(let e of Object.keys(o)){let r=o[e];if(r==null)continue;let i=r[Gd]===!0;if(delete r[Gd],n.includes(`{`)){r.parameters=r.parameters?[...r.parameters]:[];let e=n.split(`/`).filter(e=>e.startsWith(`{`)&&!r.parameters.find(t=>t.in===`path`&&t.name===e.slice(1,e.length-1)));for(let n of e){let e=n.slice(1,n.length-1);r.parameters.findIndex(n=>{if(`$ref`in n){let r=n.$ref.split(`/`).pop();if(r){let n=t.components.parameters?.[r];if(n&&!(`$ref`in n))return n.in===`path`&&n.name===e}return!1}return n.in===`path`&&n.name===e})===-1&&r.parameters.push({schema:{type:`string`},in:`path`,name:e,required:!0})}}if(r.responses||={200:{}},i&&t.options.defaultValidationErrorResponse!==!1&&!r.responses[400]){let e=t.options.defaultValidationErrorResponse;typeof e==`object`?r.responses[400]=structuredClone(e):t.validationErrorResponse&&(r.responses[400]=structuredClone(t.validationErrorResponse))}}let e={};for(let t of Object.keys(o))o[t]!=null&&(e[t]=o[t]);Object.keys(e).length>0&&(i[n]=e)}return i}var of={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:[`OPTIONS`],excludeTags:[],defaultValidationErrorResponse:!0},sf={description:`Validation Error`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,enum:[!1]},error:{type:`array`,items:{}},data:{}},required:[`success`,`error`,`data`]}}}};async function cf(e,t=of,n){let r={components:{},options:{...of,...t},validationErrorResponse:sf},i=r.options.documentation??{},a={...i,components:i.components&&{...i.components}},o=await lf(e,r);for(let e in o)for(let t in o[e])uf({valueOrFunc:o[e][t]?.hide,method:t,path:e,c:n})&&(o[e][t]=void 0);let s=a.components?.responses?await hf(a.components.responses):void 0;s&&a.components&&(a.components.responses=s.responses);let c=_f(a.components,s?.components,r.components);return{openapi:`3.1.0`,...a,tags:a.tags?.filter(e=>!r.options.excludeTags?.includes(e?.name)),info:{title:`Hono Documentation`,description:`Development documentation`,version:`0.0.0`,...a.info},paths:{...af(o,r),...a.paths},components:c}}async function lf(e,t){let n={},r=new Map;for(let i of e.routes){let e=Ad(i.handler)[Wd];if(!e){t.options.includeEmptyPaths&&rf({route:i,paths:n},r);continue}let a=i.method;if(a!==`ALL`&&(t.options.excludeMethods?.includes(a)||!Kd.includes(a)))continue;let{schema:o,components:s={}}=await df(e,t.options.defaultOptions?.[a]&&{...t.options.defaultOptions[a]},t.components.parameters);t.components=_f(t.components,s),rf({route:i,specs:o,paths:n},r)}return n}function uf(e){let{valueOrFunc:t,c:n,method:r,path:i}=e;if(t!=null){if(typeof t==`boolean`)return t;if(typeof t==`function`)return t({c:n,method:r,path:i})}return!1}async function df(e,t,n){if(`spec`in e){let n={...t,...e.spec,responses:{...t?.responses,...e.spec.responses}},r={};if(n.responses){let e=await hf(n.responses);n.responses=e.responses,r=e.components}if(n.requestBody&&`content`in n.requestBody){let e=await mf(n.requestBody.content);n.requestBody={...n.requestBody,content:e.content},r=_f(r,e.components)}return{schema:n,components:r}}let r=await e.toOpenAPISchema();gf(r);let i={...t,[Gd]:!0};if(e.target===`form`||e.target===`json`){let t=e.options?.media??(e.target===`json`?`application/json`:`multipart/form-data`);!i.requestBody||!(`content`in i.requestBody)||!i.requestBody.content?i.requestBody={required:!0,content:{[t]:{schema:r.schema}}}:i.requestBody.content[t]={schema:r.schema}}else{let t=[];if(`$ref`in r.schema){let i=r.schema.$ref.split(`/`).pop();if(i&&r.components?.schemas?.[i]){let a=r.components.schemas[i],o=ff(e.target,a,r.components.schemas),s=o.length===1?o[0]:void 0,c=n?.[i];s&&(!c||`in`in c&&c.in===s.in&&c.name===s.name)?(r.components.parameters??={},r.components.parameters[i]=s,t.push({$ref:`#/components/parameters/${i}`}),delete r.components.schemas[i]):t=o}}else t=ff(e.target,r.schema,r.components?.schemas);i.parameters=t}return{schema:i,components:r.components}}function ff(e,t,n){let r=[];for(let[i,a]of pf(t,n)){let t={in:e===`param`?`path`:e,name:i,schema:a.schema};a.required&&(t.required=!0),t.schema&&`description`in t.schema&&t.schema.description&&(t.description=t.schema.description,t.schema={...t.schema,description:void 0}),r.push(t)}return r}function pf(e,t){let n=new Map,r=new Set,i=e=>{for(let[t,r]of Object.entries(e.properties??{})){let i=n.get(t);n.set(t,{schema:i?{allOf:[i.schema,r]}:r,required:!!e.required?.includes(t)||i?.required})}for(let n of e.allOf??[])if(`$ref`in n){if(!n.$ref.startsWith(`#/components/schemas/`))continue;let e=n.$ref.slice(21).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`),a=t?.[e];a&&!r.has(e)&&(r.add(e),i(a),r.delete(e))}else i(n)};return i(e),n}async function mf(e){let t={},n={};for(let[r,i]of Object.entries(e))if(i){if(i.schema&&`toOpenAPISchema`in i.schema){let e=await i.schema.toOpenAPISchema();gf(e),n[r]={...i,schema:e.schema},e.components&&(t=_f(t,e.components))}else n[r]=i}return{content:n,components:t}}async function hf(e){let t={},n={};for(let[r,i]of Object.entries(e)){if(!i||!(`content`in i)||!i.content){n[r]=i;continue}let e=await mf(i.content);n[r]={...i,content:e.content},t=_f(t,e.components)}return{responses:n,components:t}}function gf(e){let t=e.schema.$defs;t&&typeof t==`object`&&(e.components??={},e.components.schemas={...t,...e.components.schemas},delete e.schema.$defs)}function _f(...e){return e.reduce((e,t,n)=>(t==null||n===0||((e.schemas&&Object.keys(e.schemas).length>0||t.schemas&&Object.keys(t.schemas).length>0)&&(e.schemas={...e.schemas,...t.schemas}),(e.parameters&&Object.keys(e.parameters).length>0||t.parameters&&Object.keys(t.parameters).length>0)&&(e.parameters={...e.parameters,...t.parameters})),e),e[0]??{})}var vf=e=>e.base,yf=e=>{e.zodSchema._zod.def.type===`date`&&(e.jsonSchema.type=`string`,e.jsonSchema.format=`date-time`)};function bf(e,t){let n=e[`~standard`].vendor;return{vendor:n,validate:e[`~standard`].validate,toJSONSchema:n=>ye(e,{...t,...n}),toOpenAPISchema:r=>be(e,{...t,...r,...n===`arktype`?xf(t,r):void 0,...n===`zod`?Sf(e,t,r):void 0})}}function xf(e,t){let n=e?.options,r=t?.options;if(!(e?.fallback||n?.fallback||t?.fallback||r?.fallback))return{options:{fallback:vf,...n,...r}}}function Sf(e,t,n){if(!(`_zod`in e))return;let r=t?.options,i=n?.options;if(!(t?.override||r?.override||n?.override||i?.override))return{options:{unrepresentable:`any`,override:yf,...r,...i}}}function Cf(e,t,n,r){let i=Ud(e,t,n);return Object.defineProperty(i,"name",{value:`validator`,configurable:!0}),Object.assign(i,{[Wd]:{target:e,...bf(t,r),options:r}})}function wf(e){let t=async(e,t)=>{await t()};return Object.defineProperty(t,"name",{value:`describeRoute`,configurable:!0}),Object.assign(t,{[Wd]:{spec:e}})}var Tf=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(dt(e),Me(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Be(r)}update(e){return Le(this),this.iHash.update(e),this}digestInto(e){Le(this),Ve(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ef=(()=>{let e=((e,t,n)=>new Tf(e,t).update(n).digest());return e.create=(e,t)=>new Tf(e,t),e})(),Df=Uint8Array.of(0),Of=Uint8Array.of();function kf(e,t,n,r=32,i){dt(e),Se(r,`length`),Me(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Of:Me(n,void 0,`info`),!o)return i&&Be(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Ef.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){Df[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(Df).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(Df[0]=o,o>1&&c.update(u),c.update(n).update(Df).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&Be(u),Be(Df),r===s.length)return s;let f=s.slice(0,r);return Be(s),f}var Af=(e,t,n,r,i)=>{dt(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Ef.create(e,n).update(t);return kf(e,a.digest(),r,i,a)},jf=e=>e/2**32|0,Mf=e=>e>>>0;function Nf(e,t,n,r){let i=jf(n),a=Mf(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Pf(e,t,n){return e&t^~e&n}function Ff(e,t,n){return e&t^e&n^t&n}var If=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){Le(this),Me(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=De(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){Le(this),Ve(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),Nf(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:De(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Lf=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Rf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zf=new Uint32Array(64),Bf=class extends If{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)zf[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=zf[e-15],n=zf[e-2],r=nt(t,7)^nt(t,18)^t>>>3,i=nt(n,17)^nt(n,19)^n>>>10;zf[e]=i+zf[e-7]+r+zf[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=nt(o,6)^nt(o,11)^nt(o,25),u=l+t+Pf(o,s,c)+Rf[e]+zf[e]|0,d=(nt(n,2)^nt(n,13)^nt(n,22))+Ff(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Be(zf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Be(this.buffer)}},Vf=class extends Bf{constructor(){super(32,Lf)}},Hf=He(()=>new Vf,je(1)),Uf=new TextEncoder,Wf=new TextDecoder,Gf=new TextDecoder(`utf-8`,{fatal:!0}),Kf=2**32;function qf(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Jf(e,t,n){if(t<0||t>=Kf)throw RangeError(`value must be >= 0 and <= ${Kf-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function Yf(e){let t=Math.floor(e/Kf),n=e%Kf,r=new Uint8Array(8);return Jf(r,t,0),Jf(r,n,4),r}function Xf(e){let t=new Uint8Array(4);return Jf(t,e),t}var Zf=/[^\x00-\x7f]/;function Qf(e){if(typeof e==`string`&&e.length>=128){if(Zf.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Uf.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function $f(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function ep(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function tp(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var np=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},rp=class extends np{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ip=class extends np{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ap=class extends np{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},op=class extends np{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},sp=class extends np{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},Y=class extends np{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},cp=class extends np{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},lp=class extends np{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},up=class extends np{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},dp=class extends np{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},fp=class extends np{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},pp=class extends np{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},mp=class extends np{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},hp=class extends np{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},gp=`The input to be decoded is not correctly encoded.`;function _p(e){try{return ep(typeof e==`string`?e:Wf.decode(e),!0)}catch(e){throw TypeError(gp,{cause:e})}}function vp(e){return $f(typeof e==`string`?Uf.encode(e):e,!0)}function yp(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function bp(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function xp(e){return bp(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(bp)}function Sp(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Cp(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function wp(e,t,n){try{return _p(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Tp(e,t,n){try{return Qf(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Ep(e,t,n){let r;try{r=JSON.parse(Gf.decode(_p(e)))}catch{throw new t(n)}if(!bp(r))throw new t(n);return r}var Dp={__proto__:null,b64:!0},Op={__proto__:null};function kp(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Ap(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function jp(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new op(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Mp(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new cp(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function Np(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!bp(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var Pp=e=>e[Symbol.toStringTag],Fp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Ip(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(bp(t)){if(o=Zp(t),typeof o.kty!=`string`)throw Gp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Fp(e,o,n),o.kty===`oct`)return _p(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Hp(t))throw Gp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Bp(t))return t;if(s=t,s.type===`secret`)return s.export()}Lp||=new WeakMap;let c=t,l=Lp.get(c);if(l?.[r])return l[r];if(l||Lp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Rp[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await $p(e,o)}var Lp,Rp={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function zp(e){if(!Bp(e))throw Error(`CryptoKey instance expected`)}var Bp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Vp=e=>e?.[Symbol.toStringTag]===`KeyObject`,Hp=e=>Bp(e)||Vp(e);function Up(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Wp=(e,...t)=>Up(`Key must be `,e,...t);function Gp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Up(`Key for the ${e} algorithm must be `,t,...r))}var Kp=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function qp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Jp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Yp(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Kp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Kp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Kp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Kp(t.length,`algorithm.length`);qp(e,n)}function Xp(e){return{__proto__:null,...e}}function Zp(e){let t=Xp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function Qp(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function $p(e,t,n){if(!e.kty.includes(t.kty))throw new op(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function em(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Yp(e,t,n),e}var tm=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function nm(e,t){let n=e.byteLength<<3;if(n!==t)throw new Y(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var rm=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function im(e,t){if(t.length<<3!==e.ivBits)throw new Y(`Invalid Initialization Vector length`)}async function am(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Wp(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function om(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function sm(e,t,n,r,i){let[a,o,s]=await am(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await om(o,qf(i,r,c,Yf(i.length*8)),s),iv:r}}async function cm(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function lm(e,t,n,r,i,a){let[o,s,c]=await am(e,t,`decrypt`),l=await om(s,qf(a,r,n,Yf(a.length*8)),c);try{if(await cm(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new sp}async function um(e,t,n,r,i){if(!Bp(n)&&!(n instanceof Uint8Array))throw TypeError(Wp(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?im(e,r):r=rm(e),n instanceof Uint8Array&&nm(n,e.cekBits),e.cbc)return sm(e,t,n,r,i);let a=await em(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function dm(e,t,n,r,i,a){if(!Bp(t)&&!(t instanceof Uint8Array))throw TypeError(Wp(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new Y(`JWE Initialization Vector missing`);if(!i)throw new Y(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new Y(`Invalid Authentication Tag length`);if(im(e,r),t instanceof Uint8Array&&nm(t,e.cekBits),e.cbc)return lm(e,t,n,r,i,a);let o=await em(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,qf(n,i)))}catch{throw new sp}}function fm(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var pm=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],mm=[[],[`deriveBits`]],hm=[[],[]];function gm(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:pm,ops:[`wrapKey`,`unwrapKey`]}}function _m(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new op(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:mm,ops:[void 0,`deriveBits`]}}function vm(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:hm,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function ym(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:hm,ops:[`deriveBits`,`deriveBits`]}}var bm=fm({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:hm,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":gm(1),"RSA-OAEP-256":gm(256),"RSA-OAEP-384":gm(384),"RSA-OAEP-512":gm(512),"ECDH-ES":_m(`direct-key-agreement`),"ECDH-ES+A128KW":_m(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":_m(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":_m(`key-agreement-with-key-wrapping`),A128KW:vm(128),A192KW:vm(192),A256KW:vm(256),A128GCMKW:vm(128,!0),A192GCMKW:vm(192,!0),A256GCMKW:vm(256,!0),"PBES2-HS256+A128KW":ym(),"PBES2-HS384+A192KW":ym(),"PBES2-HS512+A256KW":ym()}),xm=[`encrypt`,`decrypt`];function Sm(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:hm,ops:xm,cekBits:e,ivBits:t?128:96,cbc:t}}var Cm=fm({A128GCM:Sm(128),A192GCM:Sm(192),A256GCM:Sm(256),"A128CBC-HS256":Sm(256,!0),"A192CBC-HS384":Sm(384,!0),"A256CBC-HS512":Sm(512,!0)});function wm(e,t){throw new op(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function Tm(e){return(typeof e==`string`?bm[e]:void 0)??wm(`alg`,`Algorithm`)}function Em(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function Dm(e){return(typeof e==`string`?Cm[e]:void 0)??wm(`enc`,`Encryption Algorithm`)}function Om(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);qp(e,t)}async function km(e,t,n){let r=await em(t,Tm(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Am(e,t,n){let r=await em(t,Tm(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function jm(e,t,n){Yp(t,Tm(e).subtle,n),Jp(e,t)}async function Mm(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new Y(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new Y(`PBES2 Count Input must be a positive integer`);let i=qf(Qf(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await em(r,Tm(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function Nm(e){return qf(Xf(e.length),e)}async function Pm(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await tp(`sha256`,qf(Xf(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Fm(e,t,n,r,i=new Uint8Array,a=new Uint8Array){Om(e),Om(t,`deriveBits`);let o=qf(Nm(Qf(n)),Nm(i),Nm(a),Xf(r));return Pm(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function Im(e){zp(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new op(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Lm(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new Y(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return wp(n,t,Y)}}function Rm(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new Y(`JOSE Header "apu" and "apv" values must be distinct`)}}function zm(e){if(e===void 0)throw new Y(`JWE Encrypted Key missing`)}function Bm(e){if(e!==void 0)throw new Y(`Encountered unexpected JWE Encrypted Key`)}function Vm(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function Hm(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return Bm(r),n;let c=s===`direct-key-agreement`;switch(c?Bm(r):zm(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!bp(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new Y(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);Im(n);let a=await $p(e,r),s=Lm(i,`apu`),l=Lm(i,`apv`);Rm(s,l);let u=await Fm(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return zp(n),jm(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new Y(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);Vm(a);let e=a??1e4;if(i.p2c>e)throw new Y(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new Y(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await Mm(wp(i.p2s,`p2s`,Y),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new Y(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new Y(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=wp(i.iv,`iv`,Y),t=wp(i.tag,`tag`,Y);if(e.byteLength!==12)throw new Y(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new Y(`Invalid Authentication Tag length`);return dm(Dm(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return Am(o.slice(-6),n,r)}async function Um(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=Em(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await Ip(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??tm(t):void 0;u&&nm(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{Im(l);let{apu:n,apv:i}=a;n!==void 0&&yp(n,`"apu"`),i!==void 0&&yp(i,`"apv"`);let c=n??Lm(r,`apu`),u=i??Lm(r,`apv`);Rm(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await Ip(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await Fm(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=vp(n)),i!==void 0&&(f.apv=vp(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:zp(l),jm(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=a;l=await Mm(t,o,e,l),f={p2c:e,p2s:vp(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await um(Dm(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:vp(t.iv),tag:vp(t.tag)}}}if(d??=await km(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function Wm(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new op(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new Y(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function Gm(e){if(typeof globalThis[e]>`u`)throw new op(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Km(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new Y(`Decompressed plaintext exceeded the configured limit`)}return qf(...i)}async function qm(e){return Gm(`CompressionStream`),Km(new CompressionStream(`deflate-raw`),e)}async function Jm(e,t){return Gm(`DecompressionStream`),Km(new DecompressionStream(`deflate-raw`),e,t)}function Ym(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=Ep(t,Y,`JWE Protected Header is invalid`)),[o,wp(n,`ciphertext`,Y),r===void 0?void 0:wp(r,`iv`,Y),i===void 0?void 0:wp(i,`tag`,Y),Tp((t??``)+(a===void 0?``:`.${a}`),`aad`,Y)]}function Xm(e){return[e&&kp(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&kp(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function Zm(e,t,n,r=Ym(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!Sp(i,l,u))throw new Y(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;jp(Y,Op,h,i,f),Wm(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new Y(`missing JWE Algorithm (alg) in JWE Header`);let x=bm[y];if(v===``&&(!x||!Em(x)))throw new Y(`JWE Encrypted Key incorrect type`);let ee=x?.mode===`integrated-encryption`;if(!ee&&(typeof b!=`string`||!b))throw new Y(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new ap(`"alg" (Algorithm) Header Parameter value not allowed`);let te;if(ee){if(b!==void 0)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new Y(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new Y(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new ap(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);te=Dm(b)}let S;if(v!==void 0)try{S=wp(v,`encrypted_key`,Y)}catch(e){if(!x||!Em(x))throw e;S=new Uint8Array}let C=!1;typeof n==`function`&&(n=await n(i,e),C=!0);let w=x??Tm(y);Em(w)&&S===void 0&&(S=new Uint8Array);let ne=await Ip(w.mode===`direct-encryption`?te:w,n,`decrypt`),T;if(w.mode===`integrated-encryption`)T=await w.decrypt(ne,S,a,c,i,f);else{let e=te,t;try{t=await Hm(w,e,ne,S,f,g),Em(w)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=tm(e))}catch(n){if(n instanceof TypeError||n instanceof Y||n instanceof op)throw n;t=tm(e)}T=await dm(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new op(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);T=await Jm(T,e).catch(e=>{throw e instanceof Y?e:new Y(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:wp(d,`aad`,Y)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...C&&{key:ne}}}async function Qm(e,t,n){if(e instanceof Uint8Array&&(e=Wf.decode(e)),typeof e!=`string`)throw new Y(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new Y(`Invalid Compact JWE`);return Zm({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function $m(e,t,n){if(!Sp(e,t,n))throw new Y(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function eh(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new Y(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&yp(o,`JWE Additional Authenticated Data`),s!==void 0&&yp(s,`JWE Content Encryption Key`),c!==void 0&&yp(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=Np(Y,r)[0],e[1]=r),i!==void 0&&(i=Np(Y,i)[0],e[2]=i),!n&&a!==void 0&&(a=Np(Y,a)[0],e[3]=a),l!==void 0&&!bp(l))throw TypeError(`JWE Key Management Parameters must be an object`);$m(r,i,a);let d={...r,...i,...a};Ap(Y,r),jp(Y,Op,u,r,d),Wm(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new Y(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=bm[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,Dm(p),m]}async function th(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??Tm(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await Ip(_,n,`encrypt`):[b,v,y]=await Um(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,$m(h,g,l));let x=h?vp(JSON.stringify(h)):``,ee=u?.byteLength?vp(u):void 0,te=Qf(ee?`${x}.${ee}`:x),S=o;r.zip===`DEF`&&(S=await qm(S).catch(e=>{throw new Y(`Failed to compress plaintext`,{cause:e})}));let C,w,ne;_.mode===`integrated-encryption`?[v,C]=await _.encrypt(b,S,te,h,r,p):{ciphertext:C,tag:w,iv:ne}=await um(i,S,b,f,te);let T={ciphertext:vp(C)};return ne&&(T.iv=vp(ne)),w&&(T.tag=vp(w)),v?.byteLength&&(T.encrypted_key=vp(v)),ee&&(T.aad=ee),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function nh(e,t,n){return th(e,eh(e,n),t)}function rh(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var ih=[[`verify`],[`sign`]];function ah(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:ih}}function oh(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:ih,minRsaBits:2048}}function sh(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:ih}}function ch(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:ih}}function lh(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:ih}}var uh=fm({HS256:ah(256),HS384:ah(384),HS512:ah(512),RS256:oh(256),RS384:oh(384),RS512:oh(512),PS256:oh(256,32),PS384:oh(384,48),PS512:oh(512,64),ES256:sh(`P-256`,256),ES384:sh(`P-384`,384),ES512:sh(`P-521`,512),EdDSA:ch(),Ed25519:ch(),"ML-DSA-44":lh(44),"ML-DSA-65":lh(65),"ML-DSA-87":lh(87)});function dh(e){let t=typeof e==`string`?uh[e]:void 0;if(!t)throw new op(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function fh(e){return[e&&kp(`algorithms`,e.algorithms),e?.crit]}function ph(e){return e===void 0?{}:Ep(e,cp,`JWS Protected Header is invalid`)}function mh(e){try{return Qf(e)}catch{throw new cp(`JWS Compact Serialization payload must use only ASCII characters`)}}async function hh(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??ph(a);if(!Sp(c,o))throw new cp(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Mp(c,jp(cp,Dp,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new cp(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new ap(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new cp(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new cp(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=dh(d),h=qf(a===void 0?new Uint8Array:Qf(a),Qf(`.`),typeof f==`string`?t[2]??=Tp(f,`payload`,cp):f),g=wp(e.signature,`signature`,cp),_=await Ip(m,n,`verify`),v=await em(_,m.subtle,`verify`);m.minRsaBits&&Jp(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new hp;let b={payload:typeof f==`string`?wp(f,`payload`,cp):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function gh(e,t,n){if(e instanceof Uint8Array&&(e=Wf.decode(e)),typeof e!=`string`)throw new cp(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new cp(`Invalid Compact JWS`);return hh({payload:i,protected:r,signature:a},t,n,mh)}var _h=e=>Math.floor(e.getTime()/1e3),vh={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},yh=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,bh=`check_failed`;function xh(){throw TypeError(`Invalid time period format`)}function Sh(e){typeof e!=`string`&&xh();let t=yh.exec(e);(!t||t[4]&&t[1])&&xh();let n=parseFloat(t[2]),r=Math.round(n*vh[t[3][0].toLowerCase()]);return Number.isFinite(r)||xh(),t[1]===`-`||t[4]===`ago`?-r:r}function Ch(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function wh(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Th(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Eh(e,t){return typeof e==`number`?Ch(t,e):e instanceof Date?Ch(t,_h(e)):_h(new Date)+Sh(e)}var Dh=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Oh=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function kh(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new rp(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Ah(e,t){throw new rp(`unexpected "${t}" claim value`,e,t,bh)}function jh(e,t,n={}){let r;try{r=JSON.parse(Gf.decode(t))}catch{}if(!bp(r))throw new lp(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||Dh(e.typ)!==Dh(i)))throw new rp(`unexpected "typ" JWT header value`,r,`typ`,bh);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new rp(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Ah(r,`iss`),s!==void 0&&r.sub!==s&&Ah(r,`sub`),c!==void 0&&!Oh(r.aud,typeof c==`string`?[c]:c)&&Ah(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Sh(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Ch(`clockTolerance option`,f);let{currentDate:p}=n,m=Ch(`currentDate option`,_h(p===void 0?new Date:p)),h=kh(r,`iat`,l!==void 0),g=kh(r,`nbf`);if(g!==void 0&&g>m+f)throw new rp(`"nbf" claim timestamp check failed`,r,`nbf`,bh);let _=kh(r,`exp`);if(_!==void 0&&_<=m-f)throw new ip(`"exp" claim timestamp check failed`,r,`exp`,bh);if(l!==void 0){let e=m-h,t=Ch(`maxTokenAge option`,typeof l==`number`?l:Sh(l));if(e-f>t)throw new ip(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,bh);if(e<-f)throw new rp(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,bh)}return r}var Mh;function Nh(e){return Mh.get(e)}function Ph(e){let t=Nh(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Uf.encode(JSON.stringify(t))}function Fh(e,t){return Nh(e)[t]}var Ih=class{constructor(e={}){if(!bp(e))throw TypeError(`JWT Claims Set MUST be an object`);(Mh||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return wh(`iss`,e),Nh(this).iss=e,this}setSubject(e){return wh(`sub`,e),Nh(this).sub=e,this}setAudience(e){return Th(e),Nh(this).aud=e,this}setJti(e){return wh(`jti`,e),Nh(this).jti=e,this}setNotBefore(e){return Nh(this).nbf=Eh(e,`setNotBefore`),this}setExpirationTime(e){return Nh(this).exp=Eh(e,`setExpirationTime`),this}setIssuedAt(e){let t=Nh(this);return t.iat=e===void 0?_h(new Date):typeof e==`string`?Ch(`setIssuedAt`,_h(new Date)+Sh(e)):Eh(e,`setIssuedAt`),this}};async function Lh(e,t,n){let[r,i]=await gh(e,fh(n),t);if(!i)throw new lp(`JWTs MUST NOT use unencoded payload`);let a=jh(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function Rh(e,t,n){let{plaintext:r,...i}=await Qm(e,Xm(n),t),{protectedHeader:a}=i,o=jh(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new rp(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function zh(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=Np(cp,i);i=e[0],s=vp(e[1])}if(a!==void 0&&(a=Np(cp,a)[0]),!i&&!a)throw new cp(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Sp(i,a))throw new cp(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Ap(cp,i);let l=Mp(i,jp(cp,Dp,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new cp(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=dh(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=vp(r),p=t[1]??=Qf(f)):(f=vp(r),m=Uf.encode(`${s}.${f}`))}m??=qf(Qf(s),Qf(`.`),p);let h=await em(await Ip(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Jp(d.alg,h);let g={signature:vp(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Bh(e,t,n,r,i){let[a]=await zh([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Vh=Ih,Hh=class extends Vh{#e;setProtectedHeader(e){return Cp(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Bh(Ph(this),this.#e,t?.crit,e,()=>{throw new lp(`JWTs MUST NOT use unencoded payload`)})}},Uh=Ih,Wh=class extends Uh{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return Cp(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return Cp(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return Cp(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return Cp(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=Ph(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?Fh(this,`iss`):void 0,sub:this.#n?Fh(this,`sub`):void 0,aud:this.#r?Fh(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,rh(await nh(r,e,t))}},Gh=`"alg" (Algorithm)`;function Kh(e=`JWK "alg" (Algorithm) Parameter`){throw new op(`Invalid or unsupported ${e} value`)}function qh(e,t){return(typeof e==`string`?uh[e]??bm[e]:void 0)??Kh(t)}async function Jh(e){if(Vp(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:vp(e)};if(!Bp(e))throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var Yh=(e,t)=>{if(typeof e!=`string`||!e)throw new up(`${t} missing or invalid`)};async function Xh(e,t){let n;if(bp(e)){if(n=Xp(e),typeof n.kty!=`string`)throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Hp(e))n=Xp(await Jh(e));else throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:Yh(n.alg,`"alg" (Algorithm) Parameter`),Yh(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:Yh(n.crv,`"crv" (Curve) Parameter`),Yh(n.x,`"x" (X Coordinate) Parameter`),Yh(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:Yh(n.crv,`"crv" (Subtype of Key Pair) Parameter`),Yh(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:Yh(n.e,`"e" (Exponent) Parameter`),Yh(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new up(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new op(`"kty" (Key Type) Parameter missing or unsupported`)}let i=Qf(JSON.stringify(r));return vp(await tp(t,i))}function Zh(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function Qh(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=$p(n,t,!0).then(e=>{if(e.type!==`public`)throw new dp(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function $h(e){let t;try{t=structuredClone(e)}catch{}if(!xp(t))throw new dp(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=Xp(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?uh[a]:void 0;if(!s||s.secret)throw new op(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Zh(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new fp;if(u!==1){let e=new pp;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Qh(r,e,s)}catch{}},e}return Qh(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function eg(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var tg;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(tg=`jose/v6.2.12`);var ng=Symbol();async function rg(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new mp:e});if(i.status!==200)throw new np(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new np(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var ig=Symbol();function ag(e,t){return Number.isFinite(e)&&Date.now()<e+t}function og(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function sg(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=og(r.cooldownDuration,3e4,`cooldownDuration`),s=og(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);tg&&!c.has(`User-Agent`)&&c.set(`User-Agent`,tg),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[ng],u=r[ig],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;ag(e,s)&&xp(t)&&(d=e,h=$h(t))}let g=async()=>{if(f&&eg()&&(f=void 0),!f){let e=++p,t=f=rg(n,c,AbortSignal.timeout(a),l).then(t=>{let n=$h(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!ag(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof fp&&!ag(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>ag(d,o),enumerable:!0},fresh:{get:()=>ag(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function cg(e,t,n){if(!bp(e))throw TypeError(`JWK must be an object`);let r=Zp(e),i=Qp(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return _p(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return $p(qh(t),r,i);case`RSA`:case`EC`:case`OKP`:return $p(qh(t),r,i);default:throw new op(`Unsupported "kty" (Key Type) Parameter value`)}}function lg(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return Ep(t,TypeError,n)}function ug(e){if(typeof e!=`string`)throw new lp(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new lp(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new lp(`Invalid JWT`);if(!t)throw new lp(`JWTs must contain a payload`);let r;try{r=_p(t)}catch{throw new lp(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Gf.decode(r))}catch{throw new lp(`Failed to parse the decoded payload as JSON`)}if(!bp(i))throw new lp(`Invalid JWT Claims Set`);return i}function dg(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new op(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function fg(e,t){let n=Qp(t?.extractable),r=qh(e,Gh);r.secret&&Kh(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new op(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new op(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:dg(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function pg(e,t,n=3600){return await new Hh(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function mg(e,t){try{return(await Lh(e,new TextEncoder().encode(t))).payload}catch{return null}}var hg=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),gg=()=>Date.now()/1e3|0,_g=`dir`,vg=`A256CBC-HS512`;function yg(e,t){return Af(Hf,new TextEncoder().encode(e),new TextEncoder().encode(t),hg,64)}function bg(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function xg(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function Sg(e,t,n,r=3600){let i=yg(bg(t),n),a=await Xh({kty:`oct`,k:vp(i)},`sha256`);return await new Wh(e).setProtectedHeader({alg:_g,enc:vg,kid:a}).setIssuedAt().setExpirationTime(gg()+r).setJti(crypto.randomUUID()).encrypt(i)}var Cg={clockTolerance:15,keyManagementAlgorithms:[_g],contentEncryptionAlgorithms:[vg,`A256GCM`]};async function wg(e,t,n){if(!e)return null;let r=!1;try{r=lg(e).kid!==void 0}catch{return null}try{let r=xg(t),{payload:i}=await Rh(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=yg(e.value,n);if(t===await Xh({kty:`oct`,k:vp(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,yg(r[0].value,n)},Cg);return i}catch{if(r)return null;let i=xg(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Rh(e,yg(r.value,n),Cg);return a}catch{continue}return null}}var Tg={N:16384,r:16,p:1,dkLen:64};function Eg(e,t){return new Promise((n,r)=>{Tt(e.normalize(`NFKC`),t,Tg.dkLen,{N:Tg.N,r:Tg.r,p:Tg.p,maxmem:128*Tg.N*Tg.r*2},(e,t)=>{e?r(e):n(t)})})}async function Dg(e){let t=wt(16).toString(`hex`);return`${t}:${(await Eg(e,t)).toString(`hex`)}`}async function Og(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await Eg(t,n)).toString(`hex`)===r}var kg=Dg,Ag=async({hash:e,password:t})=>Og(e,t),jg=ke(`a-z`,`0-9`,`A-Z`,`-_`);function Mg(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function Ng(e,t){return{digest:async n=>{let r=Ee(n),i=await Mg().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?Ie.encode(i,{padding:t!==`base64urlnopad`}):Pe.encode(i):i}}}function Pg(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var Fg=e=>e?`"${e}" `:``;function Ig(e,t=``){if(typeof e!=`boolean`)throw TypeError(Fg(t)+`expected boolean, got type=`+typeof e);return e}function Lg(e,t=``){if(typeof e!=`number`)throw TypeError(Fg(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Fg(t)+`expected integer >= 0, got `+e);return e}function Rg(e,t,n=``){if(Pg(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Lg(t,`length`);let r=Pg(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=Fg(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var zg=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function Bg(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Vg(e,t){Rg(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Hg(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ug(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Wg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Gg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Kg(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function qg(e){for(let t=0;t<e.length;t++)e[t]=Kg(e[t]);return e}var Jg=Gg?e=>e:qg,Yg=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Xg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Zg(e){if(Rg(e),Yg)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Xg[e[n]];return t}function Qg(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function $g(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(Yg)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=Qg(e.charCodeAt(i)),a=Qg(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function e_(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function t_(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function n_(e,t){if(t_(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function r_(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];Rg(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function i_(e,t){return zg(e,`defaults`),zg(t,`opts`),Object.assign(e,t)}function a_(e,t){if(e=Rg(e),t=Rg(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function o_(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var s_=(e,t)=>{function n(n,...r){if(Rg(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];Rg(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Pg(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&Rg(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);Rg(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,Rg(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(Rg(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function c_(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Rg(t,e,`output`),n&&!u_(t))throw Error(`invalid output, must be aligned`);return t}function l_(e,t,n){Lg(e),Lg(t),Ig(n);let r=new Uint8Array(16),i=Wg(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function u_(e){return e.byteOffset%4==0}function d_(e){return Uint8Array.from(Rg(e))}function f_(e=32){Lg(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function p_(e,t=f_){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;Lg(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=r_(e,t);return t_(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){Rg(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){Rg(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}var m_=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),h_=Jg(Hg(m_(`expand 16-byte k`))),g_=Jg(Hg(m_(`expand 32-byte k`)));function __(e,t){return e<<t|e>>>32-t}var v_=64,y_=16,b_=2**32-1,x_=Uint32Array.of();function S_(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(v_),u=Hg(l),d=Gg&&u_(i)&&u_(a),f=d?Hg(i):x_,p=d?Hg(a):x_;if(Gg)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=b_)throw Error(`arx: counter overflow`);let h=Math.min(v_,c-m);if(d&&h===v_){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<y_;t++)n=e+t,p[n]=f[n]^u[t];m+=v_}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),Jg(u),o>=b_)throw Error(`arx: counter overflow`);let f=Math.min(v_,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function C_(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=i_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return Lg(i),Lg(o),Ig(a),Ig(n),(t,s,c,l,u=0)=>{Rg(t,void 0,`key`),Rg(s,void 0,`nonce`),Rg(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=c_(d,l,!1),f&&n_(c,l),Lg(u),u<0||u>=b_)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=d_(t)),g=g_;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=h_,p.push(h);else throw Rg(t,32,`arx key`),Error(`invalid key size`);(!Gg||!u_(s))&&p.push(s=d_(s));let _=Hg(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(Gg)r(g,_,Hg(e),_);else{let t=Jg(Uint32Array.from(g));r(t,_,Hg(e),_),Ug(t),Jg(_)}s=s.subarray(16)}else Gg||Jg(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=Jg(Hg(s));try{return S_(e,g,_,y,c,l,u,o),l}finally{Ug(...p)}}}function w_(e,t){return e[t++]&255|(e[t++]&255)<<8}var T_=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=d_(Rg(e,32,`key`));let t=w_(e,0),n=w_(e,2),r=w_(e,4),i=w_(e,6),a=w_(e,8),o=w_(e,10),s=w_(e,12),c=w_(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=w_(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=w_(e,t+0),_=w_(e,t+2),v=w_(e,t+4),y=w_(e,t+6),b=w_(e,t+8),x=w_(e,t+10),ee=w_(e,t+12),te=w_(e,t+14),S=i[0]+(g&8191),C=i[1]+((g>>>13|_<<3)&8191),w=i[2]+((_>>>10|v<<6)&8191),ne=i[3]+((v>>>7|y<<9)&8191),T=i[4]+((y>>>4|b<<12)&8191),re=i[5]+(b>>>1&8191),ie=i[6]+((b>>>14|x<<2)&8191),E=i[7]+((x>>>11|ee<<5)&8191),ae=i[8]+((ee>>>8|te<<8)&8191),oe=i[9]+(te>>>5|r),D=0,se=D+S*o+5*h*C+5*m*w+5*p*ne+5*f*T;D=se>>>13,se&=8191,se+=5*d*re+5*u*ie+5*l*E+5*c*ae+5*s*oe,D+=se>>>13,se&=8191;let ce=D+S*s+C*o+5*h*w+5*m*ne+5*p*T;D=ce>>>13,ce&=8191,ce+=5*f*re+5*d*ie+5*u*E+5*l*ae+5*c*oe,D+=ce>>>13,ce&=8191;let O=D+S*c+C*s+w*o+5*h*ne+5*m*T;D=O>>>13,O&=8191,O+=5*p*re+5*f*ie+5*d*E+5*u*ae+5*l*oe,D+=O>>>13,O&=8191;let le=D+S*l+C*c+w*s+ne*o+5*h*T;D=le>>>13,le&=8191,le+=5*m*re+5*p*ie+5*f*E+5*d*ae+5*u*oe,D+=le>>>13,le&=8191;let ue=D+S*u+C*l+w*c+ne*s+T*o;D=ue>>>13,ue&=8191,ue+=5*h*re+5*m*ie+5*p*E+5*f*ae+5*d*oe,D+=ue>>>13,ue&=8191;let de=D+S*d+C*u+w*l+ne*c+T*s;D=de>>>13,de&=8191,de+=re*o+5*h*ie+5*m*E+5*p*ae+5*f*oe,D+=de>>>13,de&=8191;let k=D+S*f+C*d+w*u+ne*l+T*c;D=k>>>13,k&=8191,k+=re*s+ie*o+5*h*E+5*m*ae+5*p*oe,D+=k>>>13,k&=8191;let fe=D+S*p+C*f+w*d+ne*u+T*l;D=fe>>>13,fe&=8191,fe+=re*c+ie*s+E*o+5*h*ae+5*m*oe,D+=fe>>>13,fe&=8191;let pe=D+S*m+C*p+w*f+ne*d+T*u;D=pe>>>13,pe&=8191,pe+=re*l+ie*c+E*s+ae*o+5*h*oe,D+=pe>>>13,pe&=8191;let me=D+S*h+C*m+w*p+ne*f+T*d;D=me>>>13,me&=8191,me+=re*u+ie*l+E*c+ae*s+oe*o,D+=me>>>13,me&=8191,D=(D<<2)+D|0,D=D+se|0,se=D&8191,D>>>=13,ce+=D,i[0]=se,i[1]=ce,i[2]=O,i[3]=le,i[4]=ue,i[5]=de,i[6]=k,i[7]=fe,i[8]=pe,i[9]=me}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;Ug(n)}update(e){Bg(this),Rg(e),e=d_(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ug(this.h,this.r,this.buffer,this.pad)}digestInto(e){Bg(this),Vg(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},E_=o_(32,e=>new T_(e));function D_(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],ee=o,te=s,S=c,C=l,w=u,ne=d,T=f,re=p,ie=m,E=h,ae=g,oe=_,D=v,se=y,ce=b,O=x;for(let e=0;e<a;e+=2)ee=ee+w|0,D=__(D^ee,16),ie=ie+D|0,w=__(w^ie,12),ee=ee+w|0,D=__(D^ee,8),ie=ie+D|0,w=__(w^ie,7),te=te+ne|0,se=__(se^te,16),E=E+se|0,ne=__(ne^E,12),te=te+ne|0,se=__(se^te,8),E=E+se|0,ne=__(ne^E,7),S=S+T|0,ce=__(ce^S,16),ae=ae+ce|0,T=__(T^ae,12),S=S+T|0,ce=__(ce^S,8),ae=ae+ce|0,T=__(T^ae,7),C=C+re|0,O=__(O^C,16),oe=oe+O|0,re=__(re^oe,12),C=C+re|0,O=__(O^C,8),oe=oe+O|0,re=__(re^oe,7),ee=ee+ne|0,O=__(O^ee,16),ae=ae+O|0,ne=__(ne^ae,12),ee=ee+ne|0,O=__(O^ee,8),ae=ae+O|0,ne=__(ne^ae,7),te=te+T|0,D=__(D^te,16),oe=oe+D|0,T=__(T^oe,12),te=te+T|0,D=__(D^te,8),oe=oe+D|0,T=__(T^oe,7),S=S+re|0,se=__(se^S,16),ie=ie+se|0,re=__(re^ie,12),S=S+re|0,se=__(se^S,8),ie=ie+se|0,re=__(re^ie,7),C=C+w|0,ce=__(ce^C,16),E=E+ce|0,w=__(w^E,12),C=C+w|0,ce=__(ce^C,8),E=E+ce|0,w=__(w^E,7);let le=0;r[le++]=o+ee|0,r[le++]=s+te|0,r[le++]=c+S|0,r[le++]=l+C|0,r[le++]=u+w|0,r[le++]=d+ne|0,r[le++]=f+T|0,r[le++]=p+re|0,r[le++]=m+ie|0,r[le++]=h+E|0,r[le++]=g+ae|0,r[le++]=_+oe|0,r[le++]=v+D|0,r[le++]=y+se|0,r[le++]=b+ce|0,r[le++]=x+O|0}function O_(e,t,n,r){let i=Gg?e:Jg(e.slice(0,4)),a=Gg?t:Jg(t.slice(0,8)),o=Gg?n:Jg(n.slice(0,4)),s=new Uint32Array(16);D_(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,Jg(r),Gg||Ug(i,a,o),Ug(s)}var k_=C_(D_,{counterRight:!1,counterLength:8,extendNonceFn:O_,allowShortKeys:!1}),A_=new Uint8Array(16),j_=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(A_.subarray(n))},M_=new Uint8Array(32);function N_(e,t,n,r,i){i!==void 0&&Rg(i,void 0,`AAD`);let a=e(t,n,M_),o=l_(r.length,i?i.length:0,!0),s=E_.create(a);i&&j_(s,i),j_(s,r),s.update(o);let c=s.digest();return Ug(a,o),c}var P_=s_({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=c_(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=N_(e,t,n,s,r);return a.set(c,o),Ug(c),a},decrypt(i,a){a=c_(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=N_(e,t,n,o,r);if(!a_(s,c))throw Ug(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Ug(c),a}}))(k_)),F_=`$ba$`;function I_(e){if(!e.startsWith(F_))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function L_(e,t){return`${F_}${e}$${t}`}async function R_(e,t){let n=await Ng(`SHA-256`).digest(e),r=e_(t);return Zg(p_(P_)(new Uint8Array(n)).encrypt(r))}async function z_(e,t){let n=await Ng(`SHA-256`).digest(e),r=$g(t),i=p_(P_)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var B_=async({key:e,data:t})=>{if(typeof e==`string`)return R_(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await R_(n,t);return L_(e.currentVersion,r)},V_=async({key:e,data:t})=>{if(typeof e==`string`)return z_(e,t);let n=I_(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return z_(t,n.ciphertext)}if(e.legacySecret)return z_(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)};function H_(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}var U_={name:`HMAC`,hash:`SHA-256`},W_=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await H_().importKey(`raw`,t,U_,!1,[`sign`,`verify`])},G_=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await H_().verify(U_,n,i,new TextEncoder().encode(t))}catch{return!1}},K_=async(e,t)=>{let n=await W_(t),r=await H_().sign(U_.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},q_=async(e,t)=>{let n=await K_(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},J_=/^application\/([a-z0-9.+-]*\+)?json/i;async function Y_(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new Ze(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new Ze(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(J_.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new Ze(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function X_(e){return e instanceof Ze||e?.name===`APIError`}function Z_(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function Q_(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function $_(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var ev={secure:`__Secure-`,host:`__Host-`},tv=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return ev[t]+e};function nv(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,Z_(n))}n=i+1}return t}function rv(e,t,n={}){let r=tv(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function iv({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}var av=(e,t,n)=>(t=encodeURIComponent(t),iv(rv(e,t,n))),ov=async(e,t,n,r)=>(t=await q_(t,n),iv(rv(e,t,r)));async function sv(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:cv(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:cv(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function cv(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var lv=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await sv(t,e);if(o)throw new Xe(o.message,o.issues);let s=e.headers===void 0?`request`in e&&$_(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?nv(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=tv(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=tv(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await G_(s,o,await W_(t))?o:!1},setCookie:(e,t,n)=>{let i=av(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await ov(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new Ze(`FOUND`,void 0,r)),error:(e,t,n)=>new Ze(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function uv(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function dv(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function fv(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var pv=new Set(`host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function mv(e){for(let t of pv)e.delete(t)}function hv(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function gv(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);mv(n),hv(e.headers,n)}return e}if(fv(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(hv(i,r?.headers),hv(i,e.headers),t?.headers){let e=new Headers(t.headers);mv(e),hv(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(X_(e))return gv(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return mv(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):uv(e)&&(n=dv(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function _v(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new xe(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new xe(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await Q_(lv(t,{options:i,path:r}));if(o)throw o instanceof Xe?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new Ze(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(X_(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?gv(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function vv(e,t){return[...e??[],...t??[]]}_v.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return _v(n,{...r,use:vv(r.use,e?.use)},i)}let[n,r]=t;return _v({...n,use:vv(n.use,e?.use)},r)}return t};function yv(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await lv(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw X_(e)&&Object.defineProperty(e,Ne,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}yv.create=e=>{function t(t,n){if(typeof t==`function`)return yv({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return yv({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var bv={};function xv(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function Sv(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof pe&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof pe&&t.push({name:e,in:`query`,schema:{type:xv(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function Cv(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof pe||e.body instanceof re)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof pe&&(n[e]={type:xv(t),description:t.description},t instanceof re||r.push(e))}),{required:e.body instanceof re?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function wv(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function Tv(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(bv[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Sv(n),responses:wv(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=Cv(n);bv[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Sv(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:wv(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:bv}}var Ev=(e,t)=>`<!doctype html>
20
+ `;await t.execute(z`CREATE SCHEMA IF NOT EXISTS ${z.identifier(i)}`),await t.execute(a);let o=(await t.all(z`select id, hash, created_at from ${z.identifier(i)}.${z.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(z.raw(e));await t.execute(z`insert into ${z.identifier(i)}.${z.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e.replace(/"/g,`""`)}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[z`with `];for(let[n,r]of e.entries())t.push(z`${z.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(z`, `);return t.push(z` `),z.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?z` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,o=t?z` where ${t}`:void 0;return z`${i}delete from ${e}${o}${a}`}buildUpdateSet(e,t){let n=e[L.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return z.join(r.flatMap((e,r)=>{let a=n[e],o=a.onUpdateFn?.(),s=t[e]??(F(o,R)?o:z.param(o,a)),c=z`${z.identifier(this.casing.getColumnCasing(a))} = ${s}`;return r<i-1?[c,z.raw(`, `)]:[c]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[lc.Symbol.Name],l=e[lc.Symbol.Schema],u=e[lc.Symbol.OriginalName],d=c===u?void 0:c,f=z`${l?z`${z.identifier(l)}.`:void 0}${z.identifier(u)}${d&&z` ${z.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&z.join([z.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?z` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0,_=n?z` where ${n}`:void 0;return z`${s}update ${f} set ${p}${m}${h}${_}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let n=e.length,r=e.flatMap(({field:e},r)=>{let i=[];if(F(e,R.Aliased)&&e.isSelectionField)i.push(z.identifier(e.fieldAlias));else if(F(e,R.Aliased)||F(e,R)){let n=F(e,R.Aliased)?e.sql:e;t?i.push(new R(n.queryChunks.map(e=>F(e,I)?z.identifier(this.casing.getColumnCasing(e)):e))):i.push(n),F(e,R.Aliased)&&i.push(z` as ${z.identifier(e.fieldAlias)}`)}else if(F(e,Pi))t?i.push(z.identifier(this.casing.getColumnCasing(e))):i.push(e);else if(F(e,ca)){let t=Object.entries(e._.selectedFields);if(t.length===1){let n=t[0][1],r=F(n,R)?n.decoder:F(n,Pi)?{mapFromDriverValue:e=>n.mapFromDriverValue(e)}:n.sql.decoder;r&&(e._.sql.decoder=r)}i.push(e)}return r<n-1&&i.push(z`, `),i});return z.join(r)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[n,r]of e.entries()){n===0&&t.push(z` `);let i=r.table,a=r.lateral?z` lateral`:void 0,o=r.on?z` on ${r.on}`:void 0;if(F(i,lc)){let e=i[lc.Symbol.Name],n=i[lc.Symbol.Schema],s=i[lc.Symbol.OriginalName],c=e===s?void 0:r.alias;t.push(z`${z.raw(r.joinType)} join${a} ${n?z`${z.identifier(n)}.`:void 0}${z.identifier(s)}${c&&z` ${z.identifier(c)}`}${o}`)}else if(F(i,Na)){let e=i[da].name,n=i[da].schema,s=i[da].originalName,c=e===s?void 0:r.alias;t.push(z`${z.raw(r.joinType)} join${a} ${n?z`${z.identifier(n)}.`:void 0}${z.identifier(s)}${c&&z` ${z.identifier(c)}`}${o}`)}else t.push(z`${z.raw(r.joinType)} join${a} ${i}${o}`);n<e.length-1&&t.push(z` `)}return z.join(t)}buildFromTable(e){if(F(e,L)&&e[L.Symbol.IsAlias]){let t=z`${z.identifier(e[L.Symbol.OriginalName])}`;return e[L.Symbol.Schema]&&(t=z`${z.identifier(e[L.Symbol.Schema])}.${t}`),z`${t} ${z.identifier(e[L.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:n,where:r,having:i,table:a,joins:o,orderBy:s,groupBy:c,limit:l,offset:u,lockingClause:d,distinct:f,setOperators:p}){let m=n??Ha(t);for(let e of m)if(F(e.field,Pi)&&ba(e.field.table)!==(F(a,ca)?a._.alias:F(a,ml)?a[da].name:F(a,R)?void 0:ba(a))&&!(e=>o?.some(({alias:t})=>t===(e[L.Symbol.IsAlias]?ba(e):e[L.Symbol.BaseName])))(e.field.table)){let t=ba(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let h=!o||o.length===0,g=this.buildWithCTE(e),_;f&&(_=f===!0?z` distinct`:z` distinct on (${z.join(f.on,z`, `)})`);let v=this.buildSelection(m,{isSingleTable:h}),y=this.buildFromTable(a),b=this.buildJoins(o),x=r?z` where ${r}`:void 0,ee=i?z` having ${i}`:void 0,te;s&&s.length>0&&(te=z` order by ${z.join(s,z`, `)}`);let S;c&&c.length>0&&(S=z` group by ${z.join(c,z`, `)}`);let C=typeof l==`object`||typeof l==`number`&&l>=0?z` limit ${l}`:void 0,w=u?z` offset ${u}`:void 0,ne=z.empty();if(d){let e=z` for ${z.raw(d.strength)}`;d.config.of&&e.append(z` of ${z.join(Array.isArray(d.config.of)?d.config.of:[d.config.of],z`, `)}`),d.config.noWait?e.append(z` nowait`):d.config.skipLocked&&e.append(z` skip locked`),ne.append(e)}let T=z`${g}select${_} ${v} from ${y}${b}${x}${S}${ee}${te}${C}${w}${ne}`;return p.length>0?this.buildSetOperations(T,p):T}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:n,rightSelect:r,limit:i,orderBy:a,offset:o}}){let s=z`(${e.getSQL()}) `,c=z`(${r.getSQL()})`,l;if(a&&a.length>0){let e=[];for(let t of a)if(F(t,I))e.push(z.identifier(t.name));else if(F(t,R)){for(let e=0;e<t.queryChunks.length;e++){let n=t.queryChunks[e];F(n,I)&&(t.queryChunks[e]=z.identifier(n.name))}e.push(z`${t}`)}else e.push(z`${t}`);l=z` order by ${z.join(e,z`, `)} `}let u=typeof i==`object`||typeof i==`number`&&i>=0?z` limit ${i}`:void 0,d=z.raw(`${t} ${n?`all `:``}`),f=o?z` offset ${o}`:void 0;return z`${s}${d}${c}${l}${u}${f}`}buildInsertQuery({table:e,values:t,onConflict:n,returning:r,withList:i,select:a,overridingSystemValue_:o}){let s=[],c=e[L.Symbol.Columns],l=Object.entries(c).filter(([e,t])=>!t.shouldDisableInsert()),u=l.map(([,e])=>z.identifier(this.casing.getColumnCasing(e)));if(a){let e=t;F(e,R)?s.push(e):s.push(e.getSQL())}else{let e=t;s.push(z.raw(`values `));for(let[t,n]of e.entries()){let r=[];for(let[e,t]of l){let i=n[e];if(i===void 0||F(i,ka)&&i.value===void 0){if(t.defaultFn!==void 0){let e=t.defaultFn(),n=F(e,R)?e:z.param(e,t);r.push(n)}else if(!t.default&&t.onUpdateFn!==void 0){let e=t.onUpdateFn(),n=F(e,R)?e:z.param(e,t);r.push(n)}else r.push(z`default`)}else r.push(i)}s.push(r),t<e.length-1&&s.push(z`, `)}}let d=this.buildWithCTE(i),f=z.join(s),p=r?z` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,m=n?z` on conflict ${n}`:void 0,h=o===!0?z`overriding system value `:void 0;return z`${d}insert into ${e} ${u} ${h}${f}${m}${p}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){let r=t?z` concurrently`:void 0,i=n?z` with no data`:void 0;return z`refresh materialized view${r} ${e}${i}`}prepareTyping(e){return F(e,Ho)||F(e,zo)?`json`:F(e,ns)?`decimal`:F(e,Is)?`time`:F(e,zs)||F(e,Vs)?`timestamp`:F(e,So)||F(e,wo)?`date`:F(e,Us)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:r,tableConfig:i,queryConfig:a,tableAlias:o,nestedQueryRelation:s,joinOn:c}){let l=[],u,d,f=[],p,m=[];if(a===!0)l=Object.entries(i.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:La(t,o),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let r=Object.fromEntries(Object.entries(i.columns).map(([e,t])=>[e,La(t,o)]));if(a.where){let e=typeof a.where==`function`?a.where(r,rl()):a.where;p=e&&za(e,o)}let s=[],c=[];if(a.columns){let e=!1;for(let[t,n]of Object.entries(a.columns))n!==void 0&&t in i.columns&&(!e&&n===!0&&(e=!0),c.push(t));c.length>0&&(c=e?c.filter(e=>a.columns?.[e]===!0):Object.keys(i.columns).filter(e=>!c.includes(e)))}else c=Object.keys(i.columns);for(let e of c){let t=i.columns[e];s.push({tsKey:e,value:t})}let h=[];a.with&&(h=Object.entries(a.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:i.relations[e]})));let g;if(a.extras){g=typeof a.extras==`function`?a.extras(r,{sql:z}):a.extras;for(let[e,t]of Object.entries(g))s.push({tsKey:e,value:Ra(t,o)})}for(let{tsKey:e,value:t}of s)l.push({dbKey:F(t,R.Aliased)?t.fieldAlias:i.columns[e].name,tsKey:e,field:F(t,Pi)?La(t,o):t,relationTableTsKey:void 0,isJson:!1,selection:[]});let _=typeof a.orderBy==`function`?a.orderBy(r,il()):a.orderBy??[];Array.isArray(_)||(_=[_]),f=_.map(e=>F(e,Pi)?La(e,o):za(e,o)),u=a.limit,d=a.offset;for(let{tsKey:r,queryConfig:i,relation:a}of h){let s=ll(t,n,a),c=n[xa(a.referencedTable)],u=`${o}_${r}`,d=U(...s.fields.map((e,t)=>H(La(s.references[t],u),La(e,o)))),f=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:n,table:e[c],tableConfig:t[c],queryConfig:F(a,tl)?i===!0?{limit:1}:{...i,limit:1}:i,tableAlias:u,joinOn:d,nestedQueryRelation:a}),p=z`${z.identifier(u)}.${z.identifier(`data`)}`.as(r);m.push({on:z`true`,table:new ca(f.sql,{},u),alias:u,joinType:`left`,lateral:!0}),l.push({dbKey:r,tsKey:r,field:p,relationTableTsKey:c,isJson:!0,selection:f.selection})}}if(l.length===0)throw new Oc({message:`No fields selected for table "${i.tsName}" ("${o}")`});let h;if(p=U(c,p),s){let e=z`json_build_array(${z.join(l.map(({field:e,tsKey:t,isJson:n})=>n?z`${z.identifier(`${o}_${t}`)}.${z.identifier(`data`)}`:F(e,R.Aliased)?e.sql:e),z`, `)})`;F(s,nl)&&(e=z`coalesce(json_agg(${e}${f.length>0?z` order by ${z.join(f,z`, `)}`:void 0}), '[]'::json)`);let t=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:i.tsName,selection:l}];u!==void 0||d!==void 0||f.length>0?(h=this.buildSelectQuery({table:Ia(r,o),fields:{},fieldsFlat:[{path:[],field:z.raw(`*`)}],where:p,limit:u,offset:d,orderBy:f,setOperators:[]}),p=void 0,u=void 0,d=void 0,f=[]):h=Ia(r,o),h=this.buildSelectQuery({table:F(h,lc)?h:new ca(h,{},o),fields:{},fieldsFlat:t.map(({field:e})=>({path:[],field:F(e,Pi)?La(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]})}else h=this.buildSelectQuery({table:Ia(r,o),fields:{},fieldsFlat:l.map(({field:e})=>({path:[],field:F(e,Pi)?La(e,o):e})),joins:m,where:p,limit:u,offset:d,orderBy:f,setOperators:[]});return{tableTsKey:i.tsName,sql:h,selection:l}}},gl=class{static[P]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},_l=class{static[P]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,n=e,r;return r=this.fields?this.fields:F(n,ca)?Object.fromEntries(Object.keys(n._.selectedFields).map(e=>[e,n[e]])):F(n,ml)?n[da].selectedFields:F(n,R)?{}:Ka(n),new yl({table:n,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},vl=class extends gl{static[P]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=qa(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of Bl(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(n,r)=>{let i=this.tableName,a=qa(n);for(let e of Bl(n))this.usedTables.add(e);if(typeof a==`string`&&this.config.joins?.some(e=>e.alias===a))throw Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==`string`&&(this.config.fields={[i]:this.config.fields}),typeof a==`string`&&!F(n,R))){let e=F(n,ca)?n._.selectedFields:F(n,Na)?n[da].selectedFields:n[L.Symbol.Columns];this.config.fields[a]=e}if(typeof r==`function`&&(r=r(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:r,table:n,joinType:e,alias:a,lateral:t}),typeof a==`string`)switch(e){case`left`:this.joinsNotNullableMap[a]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[a]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[a]=!1}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(xl()):n;if(!Ua(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new Ba({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...Bl(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...Bl(e.table));return new Proxy(new ca(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new Ba({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},yl=class extends vl{static[P]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return ua.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=Ha(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};Ga(yl,[Ni]);function bl(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Ua(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}var xl=()=>({union:Sl,unionAll:Cl,intersect:wl,intersectAll:Tl,except:El,exceptAll:Dl}),Sl=bl(`union`,!1),Cl=bl(`union`,!0),wl=bl(`intersect`,!1),Tl=bl(`intersect`,!0),El=bl(`except`,!1),Dl=bl(`except`,!0),Ol=class{static[P]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=F(e,hl)?e:void 0,this.dialectConfig=F(e,hl)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new la(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new _l({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new _l({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new _l({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new _l({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new _l({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new _l({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new hl(this.dialectConfig),this.dialect}},kl=class{constructor(e,t){this.name=e,this.schema=t}static[P]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},Al=class extends kl{static[P]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new Ol));let t=new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Fl({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},jl=class extends kl{static[P]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Ka(dc(e,t))}existing(){return new Proxy(new Fl({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Fl({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Ml=class{constructor(e,t){this.name=e,this.schema=t}static[P]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},Nl=class extends Ml{static[P]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new Ol));let t=new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Ll({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Pl=class extends Ml{static[P]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Ka(dc(e,t))}existing(){return new Proxy(new Ll({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Ll({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new Ba({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Fl=class extends ml{static[P]=`PgView`;[Cc];constructor({pgConfig:e,config:t}){super(t),e&&(this[Cc]={with:e.with})}},Il=Symbol.for(`drizzle:PgMaterializedViewConfig`),Ll=class extends ml{static[P]=`PgMaterializedView`;[Il];constructor({pgConfig:e,config:t}){super(t),this[Il]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function Rl(e,t,n){return t?new jl(e,t,n):new Al(e,n)}function zl(e,t,n){return t?new Pl(e,t,n):new Nl(e,n)}function Bl(e){return F(e,lc)?[e[fa]?`${e[fa]}.${e[L.Symbol.BaseName]}`:e[L.Symbol.BaseName]]:F(e,ca)?e._.usedTables??[]:F(e,R)?e.usedTables??[]:[]}var Vl=class extends Ni{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[P]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[L.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Ha(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:Bl(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Hl=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[P]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let t=e.map(e=>{let t={},n=this.table[L.Symbol.Columns];for(let r of Object.keys(e)){let i=e[r];t[r]=F(i,R)?i:new ka(i,n[r])}return t});return new Ul(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e==`function`?e(new Ol):e;if(!F(t,R)&&!Ua(this.table[pa],t._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new Ul(this.table,t,this.session,this.dialect,this.withList,!0)}},Ul=class extends Ni{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[P]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[L.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Ha(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=z`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?z` where ${e.where}`:void 0;this.config.onConflict=z`(${z.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?z` where ${e.where}`:void 0,n=e.targetWhere?z` where ${e.targetWhere}`:void 0,r=e.setWhere?z` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,Wa(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=z`(${z.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:Bl(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Wl=class extends Ni{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[P]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},Gl=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[P]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new Kl(this.table,Wa(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},Kl=class extends Ni{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=qa(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[P]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=qa(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return F(e,lc)?e[L.Symbol.Columns]:F(e,ca)?e._.selectedFields:e[da].selectedFields}createJoin(e){return(t,n)=>{let r=qa(t);if(typeof r==`string`&&this.config.joins.some(e=>e.alias===r))throw Error(`Alias "${r}" is already used in this query`);if(typeof n==`function`){let e=this.config.from&&!F(this.config.from,R)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[L.Symbol.Columns],new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new Ba({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:n,table:t,joinType:e,alias:r}),typeof r==`string`)switch(e){case`left`:this.joinsNotNullableMap[r]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!0;break;case`inner`:this.joinsNotNullableMap[r]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[r]=!1}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[L.Symbol.Columns]),this.config.from)){let t=qa(this.config.from);if(typeof t==`string`&&this.config.from&&!F(this.config.from,R)){let n=this.getTableLikeFields(this.config.from);e[t]=n}for(let t of this.config.joins){let n=qa(t.table);if(typeof n==`string`&&!F(t.table,R)){let r=this.getTableLikeFields(t.table);e[n]=r}}}return this.config.returningFields=e,this.config.returning=Ha(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:Bl(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Ba({alias:ba(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},ql=class e extends R{constructor(t){super(e.buildEmbeddedCount(t.source,t.filters).queryChunks),this.params=t,this.mapWith(Number),this.session=t.session,this.sql=e.buildCount(t.source,t.filters)}sql;token;static[P]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return z`(select count(*) from ${e}${z.raw(` where `).if(t)}${t})`}static buildCount(e,t){return z`select count(*) as count from ${e}${z.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},Jl=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[P]=`PgRelationalQueryBuilder`;findMany(e){return new Yl(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new Yl(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},Yl=class extends Ni{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[P]=`PgRelationalQuery`;_prepare(e){return ua.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>dl(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return ua.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},Xl=class extends Ni{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[P]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},Zl=class{constructor(e,t,n){if(this.dialect=e,this.session=t,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[r,i]of Object.entries(this._.schema))this.query[r]=new Jl(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[r],i,e,t);this.$cache={invalidate:async e=>{}}}static[P]=`PgDatabase`;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new Ol(n.dialect))),new Proxy(new la(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new Ba({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new ql({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new _l({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new _l({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new _l({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new Gl(n,t.session,t.dialect,e)}function o(n){return new Hl(n,t.session,t.dialect,e)}function s(n){return new Vl(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new _l({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new _l({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new _l({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new Gl(e,this.session,this.dialect)}insert(e){return new Hl(e,this.session,this.dialect)}delete(e){return new Vl(e,this.session,this.dialect)}refreshMaterializedView(e){return new Wl(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?z.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new Xl(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}},Ql=class{static[P]=`Cache`},$l=class extends Ql{strategy(){return`all`}static[P]=`NoopCache`;async get(e){}async put(e,t,n,r){}async onMutate(e){}};async function eu(e,t){let n=`${e}-${JSON.stringify(t)}`,r=new TextEncoder().encode(n),i=await crypto.subtle.digest(`SHA-256`,r);return[...new Uint8Array(i)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}var tu=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[P]=`PgSequence`};function nu(e,t,n){return new tu(e,t,n)}var ru=class{constructor(e){this.schemaName=e}static[P]=`PgSchema`;table=(e,t,n)=>uc(e,t,n,this.schemaName);view=(e,t)=>Rl(e,t,this.schemaName);materializedView=(e,t)=>zl(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?oa(e,[...t],this.schemaName):sa(e,t,this.schemaName)}sequence=(e,t)=>nu(e,t,this.schemaName);getSQL(){return new R([z.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function iu(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new ru(e)}var au=class{constructor(e,t,n,r){this.query=e,this.cache=t,this.queryMetadata=n,this.cacheConfig=r,t&&t.strategy()===`all`&&r===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[P]=`PgPreparedQuery`;joinsNotNullableMap;async queryWithCache(e,t,n){if(this.cache===void 0||F(this.cache,$l)||this.queryMetadata===void 0||this.cacheConfig&&!this.cacheConfig.enable)try{return await n()}catch(n){throw new kc(e,t,n)}if((this.queryMetadata.type===`insert`||this.queryMetadata.type===`update`||this.queryMetadata.type===`delete`)&&this.queryMetadata.tables.length>0)try{let[e]=await Promise.all([n(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return e}catch(n){throw new kc(e,t,n)}if(!this.cacheConfig)try{return await n()}catch(n){throw new kc(e,t,n)}if(this.queryMetadata.type===`select`){let r=await this.cache.get(this.cacheConfig.tag??await eu(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(r===void 0){let r;try{r=await n()}catch(n){throw new kc(e,t,n)}return await this.cache.put(this.cacheConfig.tag??await eu(e,t),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return r}try{return await n()}catch(n){throw new kc(e,t,n)}}},ou=class{constructor(e){this.dialect=e}static[P]=`PgSession`;execute(e,t){return ua.startActiveSpan(`drizzle.operation`,()=>ua.startActiveSpan(`drizzle.prepareQuery`,()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let n=await this.execute(e,t);return Number(n[0].count)}},su=class extends Zl{constructor(e,t,n,r=0){super(e,t,n),this.schema=n,this.nestedIndex=r}static[P]=`PgTransaction`;rollback(){throw new Ac}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable==`boolean`&&t.push(e.deferrable?`deferrable`:`not deferrable`),z.raw(t.join(` `))}setTransaction(e){return this.session.execute(z`set transaction ${this.getTransactionConfigSQL(e)}`)}},{Pool:cu,types:lu}=ki,uu=class extends au{constructor(e,t,n,r,i,a,o,s,c,l,u){super({sql:t,params:n},i,a,o),this.client=e,this.queryString=t,this.params=n,this.logger=r,this.fields=s,this._isResponseInArrayMode=l,this.customResultMapper=u,this.rawQueryConfig={name:c,text:t,types:{getTypeParser:(e,t)=>e===lu.builtins.TIMESTAMPTZ||e===lu.builtins.TIMESTAMP||e===lu.builtins.DATE||e===lu.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:lu.getTypeParser(e,t)}},this.queryConfig={name:c,text:t,rowMode:`array`,types:{getTypeParser:(e,t)=>e===lu.builtins.TIMESTAMPTZ||e===lu.builtins.TIMESTAMP||e===lu.builtins.DATE||e===lu.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:lu.getTypeParser(e,t)}}}static[P]=`NodePgPreparedQuery`;rawQueryConfig;queryConfig;async execute(e={}){return ua.startActiveSpan(`drizzle.execute`,async()=>{let t=ja(this.params,e);this.logger.logQuery(this.rawQueryConfig.text,t);let{fields:n,rawQueryConfig:r,client:i,queryConfig:a,joinsNotNullableMap:o,customResultMapper:s}=this;if(!n&&!s)return ua.startActiveSpan(`drizzle.driver.execute`,async e=>(e?.setAttributes({"drizzle.query.name":r.name,"drizzle.query.text":r.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(r.text,t,async()=>await i.query(r,t))));let c=await ua.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":a.name,"drizzle.query.text":a.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(a.text,t,async()=>await i.query(a,t))));return ua.startActiveSpan(`drizzle.mapResponse`,()=>s?s(c.rows):c.rows.map(e=>Va(n,e,o)))})}all(e={}){return ua.startActiveSpan(`drizzle.execute`,()=>{let t=ja(this.params,e);return this.logger.logQuery(this.rawQueryConfig.text,t),ua.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":this.rawQueryConfig.name,"drizzle.query.text":this.rawQueryConfig.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(this.rawQueryConfig.text,t,async()=>this.client.query(this.rawQueryConfig,t)).then(e=>e.rows)))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},du=class e extends ou{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new Mi,this.cache=r.cache??new $l}static[P]=`NodePgSession`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new uu(this.client,e.sql,e.params,this.logger,this.cache,a,o,t,n,r,i)}async transaction(t,n){let r=this.client instanceof cu||Object.getPrototypeOf(this.client).constructor.name.includes(`Pool`),i=r?new e(await this.client.connect(),this.dialect,this.schema,this.options):this,a=new fu(this.dialect,i,this.schema);await a.execute(z`begin${n?z` ${a.getTransactionConfigSQL(n)}`:void 0}`);try{let e=await t(a);return await a.execute(z`commit`),e}catch(e){throw await a.execute(z`rollback`),e}finally{r&&i.client.release()}}async count(e){let t=await this.execute(e);return Number(t.rows[0].count)}},fu=class e extends su{static[P]=`NodePgTransaction`;async transaction(t){let n=`sp${this.nestedIndex+1}`,r=new e(this.dialect,this.session,this.schema,this.nestedIndex+1);await r.execute(z.raw(`savepoint ${n}`));try{let e=await t(r);return await r.execute(z.raw(`release savepoint ${n}`)),e}catch(e){throw await r.execute(z.raw(`rollback to savepoint ${n}`)),e}}},pu=class{constructor(e,t,n={}){this.client=e,this.dialect=t,this.options=n}static[P]=`NodePgDriver`;createSession(e){return new du(this.client,this.dialect,e,{logger:this.options.logger,cache:this.options.cache})}},mu=class extends Zl{static[P]=`NodePgDatabase`};function hu(e,t={}){let n=new hl({casing:t.casing}),r;t.logger===!0?r=new ji:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=al(t.schema,ul);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new mu(n,new pu(e,n,{logger:r,cache:t.cache}).createSession(i),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}function gu(...e){if(typeof e[0]==`string`)return hu(new ki.Pool({connectionString:e[0]}),e[1]);if(Ya(e[0])){let{connection:t,client:n,...r}=e[0];return hu(n||(typeof t==`string`?new ki.Pool({connectionString:t}):new ki.Pool(t)),r)}return hu(e[0],e[1])}(e=>{function t(e){return hu({},e)}e.mock=t})(gu||={});var _u={crossOriginEmbedderPolicy:[`Cross-Origin-Embedder-Policy`,`require-corp`],crossOriginResourcePolicy:[`Cross-Origin-Resource-Policy`,`same-origin`],crossOriginOpenerPolicy:[`Cross-Origin-Opener-Policy`,`same-origin`],originAgentCluster:[`Origin-Agent-Cluster`,`?1`],referrerPolicy:[`Referrer-Policy`,`no-referrer`],strictTransportSecurity:[`Strict-Transport-Security`,`max-age=15552000; includeSubDomains`],xContentTypeOptions:[`X-Content-Type-Options`,`nosniff`],xDnsPrefetchControl:[`X-DNS-Prefetch-Control`,`off`],xDownloadOptions:[`X-Download-Options`,`noopen`],xFrameOptions:[`X-Frame-Options`,`SAMEORIGIN`],xPermittedCrossDomainPolicies:[`X-Permitted-Cross-Domain-Policies`,`none`],xXssProtection:[`X-XSS-Protection`,`0`]},vu={crossOriginEmbedderPolicy:!1,crossOriginResourcePolicy:!0,crossOriginOpenerPolicy:!0,originAgentCluster:!0,referrerPolicy:!0,strictTransportSecurity:!0,xContentTypeOptions:!0,xDnsPrefetchControl:!0,xDownloadOptions:!0,xFrameOptions:!0,xPermittedCrossDomainPolicies:!0,xXssProtection:!0,removePoweredBy:!0,permissionsPolicy:{}},yu=e=>{let t={...vu,...e},n=bu(t),r=[];if(t.contentSecurityPolicy){let[e,i]=xu(t.contentSecurityPolicy,`Content-Security-Policy`);e&&r.push(e),n.push([`Content-Security-Policy`,i])}if(t.contentSecurityPolicyReportOnly){let[e,i]=xu(t.contentSecurityPolicyReportOnly,`Content-Security-Policy-Report-Only`);e&&r.push(e),n.push([`Content-Security-Policy-Report-Only`,i])}return t.permissionsPolicy&&Object.keys(t.permissionsPolicy).length>0&&n.push([`Permissions-Policy`,Su(t.permissionsPolicy)]),t.reportingEndpoints&&n.push([`Reporting-Endpoints`,wu(t.reportingEndpoints)]),t.reportTo&&n.push([`Report-To`,Tu(t.reportTo)]),async function(e,i){let a=r.length===0?n:r.reduce((t,n)=>n(e,t),n);await i(),Eu(e,a),t?.removePoweredBy&&e.res.headers.delete(`X-Powered-By`)}};function bu(e){return Object.entries(_u).filter(([t])=>e[t]).map(([t,n])=>{let r=e[t];return typeof r==`string`?[n[0],r]:n})}function xu(e,t){let n=[],r=[];for(let[t,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];e.forEach((e,i)=>{if(typeof e==`function`){let a=i*2+2+r.length;n.push((n,r)=>{r[a]=e(n,t)})}}),r.push(t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(e,t)=>t?`-`+e.toLowerCase():e.toLowerCase()),...e.flatMap(e=>[` `,e]),`; `)}return r.pop(),n.length===0?[void 0,r.join(``)]:[(e,r)=>r.map(r=>{if(r[0]===t){let t=r[1].slice();return n.forEach(n=>{n(e,t)}),[r[0],t.join(``)]}return r}),r]}function Su(e){return Object.entries(e).map(([e,t])=>{let n=Cu(e);return typeof t==`boolean`?`${n}=${t?`*`:`()`}`:Array.isArray(t)?t.length===0?`${n}=()`:t.length===1&&t[0]===`*`?`${n}=*`:t.length===1&&t[0]===`none`?`${n}=()`:`${n}=(${t.map(e=>[`self`,`src`].includes(e)?e:`"${e}"`).join(` `)})`:``}).filter(Boolean).join(`, `)}function Cu(e){return e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).toLowerCase()}function wu(e=[]){return e.map(e=>`${e.name}="${e.url}"`).join(`, `)}function Tu(e=[]){return e.map(e=>JSON.stringify(e)).join(`, `)}function Eu(e,t){t.forEach(([t,n])=>{e.res.headers.set(t,n)})}var Du=/^[a-z_][a-z0-9_]{0,62}$/,Ou=(()=>{let e=globalThis.process?.env?.DATABASE_SCHEMA;if(e&&e!==`public`){if(!Du.test(e))throw Error(`Invalid DATABASE_SCHEMA: ${JSON.stringify(e)}. Set it to a lowercase Postgres schema name, such as pr_141, or leave it unset.`);return e}})(),ku=Ou?iu(Ou).table:dc,Au=ku(`account`,{accessToken:B(`access_token`),accessTokenExpiresAt:V(`access_token_expires_at`),accountId:B(`account_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),idToken:B(`id_token`),password:B(`password`),providerId:B(`provider_id`).notNull(),refreshToken:B(`refresh_token`),refreshTokenExpiresAt:V(`refresh_token_expires_at`),scope:B(`scope`),updatedAt:V(`updated_at`).$onUpdate(()=>new Date).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`account_userId_idx`).on(e.userId)]),ju=ol(Au,({one:e})=>({user:e(q,{fields:[Au.userId],references:[q.id]})})),Mu=ku(`device_code`,{acr:B(`acr`),amr:B(`amr`).array(),authTime:V(`auth_time`),clientId:B(`client_id`),deviceCode:B(`device_code`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),lastPolledAt:V(`last_polled_at`),oauthClientId:B(`oauth_client_id`),pollingInterval:Po(`polling_interval`),referenceId:B(`reference_id`),resources:B(`resources`).array(),scope:B(`scope`),status:B(`status`).notNull(),userCode:B(`user_code`).notNull(),userId:B(`user_id`)},e=>[yc(`deviceCode_deviceCode_uidx`).on(e.deviceCode),vc(`deviceCode_expiresAt_idx`).on(e.expiresAt),yc(`deviceCode_userCode_uidx`).on(e.userCode)]),Nu=ku(`jwks`,{alg:B(`alg`),createdAt:V(`created_at`).notNull(),crv:B(`crv`),expiresAt:V(`expires_at`),id:B(`id`).primaryKey(),privateKey:B(`private_key`).notNull(),publicKey:B(`public_key`).notNull()}),Pu=ku(`oauth_access_token`,{authorizationCodeId:B(`authorization_code_id`),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),confirmation:Uo(`confirmation`),createdAt:V(`created_at`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),refreshId:B(`refresh_id`).references(()=>G.id,{onDelete:`cascade`}),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),revoked:V(`revoked`),scopes:B(`scopes`).array().notNull(),sessionId:B(`session_id`).references(()=>K.id,{onDelete:`set null`}),token:B(`token`).notNull().unique(),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthAccessToken_authorizationCodeId_idx`).on(e.authorizationCodeId),vc(`oauthAccessToken_clientId_idx`).on(e.clientId),vc(`oauthAccessToken_expiresAt_idx`).on(e.expiresAt),vc(`oauthAccessToken_refreshId_idx`).on(e.refreshId),vc(`oauthAccessToken_sessionId_idx`).on(e.sessionId),vc(`oauthAccessToken_userId_idx`).on(e.userId)]),Fu=ol(Pu,({one:e})=>({oauthClient:e(W,{fields:[Pu.clientId],references:[W.clientId]}),oauthRefreshToken:e(G,{fields:[Pu.refreshId],references:[G.id]}),session:e(K,{fields:[Pu.sessionId],references:[K.id]}),user:e(q,{fields:[Pu.userId],references:[q.id]})})),W=ku(`oauth_client`,{accessAudience:B(`access_audience`),applicationType:B(`application_type`),attestation:Uo(`attestation`),backchannelLogoutSessionRequired:lo(`backchannel_logout_session_required`),backchannelLogoutUri:B(`backchannel_logout_uri`),clientCredentialsScopes:B(`client_credentials_scopes`).array().default([]),clientDiscoveryId:B(`client_discovery_id`),clientId:B(`client_id`).notNull().unique(),clientSecret:B(`client_secret`),contacts:B(`contacts`).array(),createdAt:V(`created_at`),disabled:lo(`disabled`).default(!1),dpopBoundAccessTokens:lo(`dpop_bound_access_tokens`).default(!1),employee:lo(`employee`).default(!1),enableEndSession:lo(`enable_end_session`),frontchannelLogoutSessionRequired:lo(`frontchannel_logout_session_required`),frontchannelLogoutUri:B(`frontchannel_logout_uri`),grantTypes:B(`grant_types`).array(),icon:B(`icon`),id:B(`id`).primaryKey(),jwks:B(`jwks`),jwksUri:B(`jwks_uri`),metadata:Uo(`metadata`),name:B(`name`),policy:B(`policy`),postLogoutRedirectUris:B(`post_logout_redirect_uris`).array(),redirectUris:B(`redirect_uris`).array().notNull(),referenceId:B(`reference_id`),refreshTokenLifetime:Po(`refresh_token_lifetime`).default(2592e3),requirePKCE:lo(`require_pkce`),requirePushedAuthorizationRequests:lo(`require_pushed_authorization_requests`).default(!1),responseTypes:B(`response_types`).array(),scopes:B(`scopes`).array(),sectorIdentifier:B(`sector_identifier`),skipConsent:lo(`skip_consent`),softwareId:B(`software_id`),softwareStatement:B(`software_statement`),softwareVersion:B(`software_version`),subjectType:B(`subject_type`),tokenEndpointAuthMethod:B(`token_endpoint_auth_method`),tos:B(`tos`),updatedAt:V(`updated_at`),uri:B(`uri`),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthClient_userId_idx`).on(e.userId)]),Iu=ku(`oauth_client_assertion`,{expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey()},e=>[vc(`oauthClientAssertion_expiresAt_idx`).on(e.expiresAt)]),Lu=ol(W,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthClientResources:e(Ru),oauthConsents:e(Bu),oauthRefreshTokens:e(G),user:t(q,{fields:[W.userId],references:[q.id]})})),Ru=ku(`oauth_client_resource`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),createdAt:V(`created_at`),id:B(`id`).primaryKey(),metadata:Uo(`metadata`),resourceId:B(`resource_id`).notNull().references(()=>Uu.identifier,{onDelete:`cascade`})},e=>[vc(`oauthClientResource_clientId_idx`).on(e.clientId),yc(`oauthClientResource_clientId_resourceId_uidx`).on(e.clientId,e.resourceId),vc(`oauthClientResource_resourceId_idx`).on(e.resourceId)]),zu=ol(Ru,({one:e})=>({oauthClient:e(W,{fields:[Ru.clientId],references:[W.clientId]}),oauthResource:e(Uu,{fields:[Ru.resourceId],references:[Uu.identifier]})})),Bu=ku(`oauth_consent`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),createdAt:V(`created_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),scopes:B(`scopes`).array().notNull(),updatedAt:V(`updated_at`).notNull(),userId:B(`user_id`).references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthConsent_clientId_idx`).on(e.clientId),vc(`oauthConsent_userId_idx`).on(e.userId)]),Vu=ol(Bu,({one:e})=>({oauthClient:e(W,{fields:[Bu.clientId],references:[W.clientId]}),user:e(q,{fields:[Bu.userId],references:[q.id]})})),G=ku(`oauth_refresh_token`,{acr:B(`acr`),amr:B(`amr`).array(),authorizationCodeId:B(`authorization_code_id`),authTime:V(`auth_time`),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),confirmation:Uo(`confirmation`),createdAt:V(`created_at`).notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),referenceId:B(`reference_id`),requestedUserInfoClaims:B(`requested_user_info_claims`).array(),resources:B(`resources`).array(),revoked:V(`revoked`),rotatedAt:V(`rotated_at`),rotationReplayExpiresAt:V(`rotation_replay_expires_at`),rotationReplayResponse:B(`rotation_replay_response`),scopes:B(`scopes`).array().notNull(),sessionId:B(`session_id`).references(()=>K.id,{onDelete:`set null`}),token:B(`token`).notNull().unique(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`oauthRefreshToken_authorizationCodeId_idx`).on(e.authorizationCodeId),vc(`oauthRefreshToken_clientId_idx`).on(e.clientId),vc(`oauthRefreshToken_expiresAt_idx`).on(e.expiresAt),vc(`oauthRefreshToken_sessionId_idx`).on(e.sessionId),vc(`oauthRefreshToken_userId_idx`).on(e.userId)]),Hu=ol(G,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthClient:t(W,{fields:[G.clientId],references:[W.clientId]}),session:t(K,{fields:[G.sessionId],references:[K.id]}),user:t(q,{fields:[G.userId],references:[q.id]})})),Uu=ku(`oauth_resource`,{accessTokenTtl:Po(`access_token_ttl`),allowedScopes:B(`allowed_scopes`).array(),createdAt:V(`created_at`),customClaims:Uo(`custom_claims`),disabled:lo(`disabled`).default(!1),dpopBoundAccessTokensRequired:lo(`dpop_bound_access_tokens_required`).default(!1),id:B(`id`).primaryKey(),identifier:B(`identifier`).notNull().unique(),metadata:Uo(`metadata`),name:B(`name`).notNull(),policyVersion:Po(`policy_version`).default(1),refreshTokenTtl:Po(`refresh_token_ttl`),signingAlgorithm:B(`signing_algorithm`),signingKeyId:B(`signing_key_id`),updatedAt:V(`updated_at`)}),Wu=ol(Uu,({many:e})=>({oauthClientResources:e(Ru)})),K=ku(`session`,{createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),ipAddress:B(`ip_address`),token:B(`token`).notNull().unique(),updatedAt:V(`updated_at`).$onUpdate(()=>new Date).notNull(),userAgent:B(`user_agent`),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`session_expiresAt_idx`).on(e.expiresAt),vc(`session_userId_idx`).on(e.userId)]),Gu=ol(K,({many:e,one:t})=>({oauthAccessTokens:e(Pu),oauthRefreshTokens:e(G),user:t(q,{fields:[K.userId],references:[q.id]})})),q=ku(`user`,{createdAt:V(`created_at`).defaultNow().notNull(),email:B(`email`).notNull().unique(),emailVerified:lo(`email_verified`).default(!1).notNull(),id:B(`id`).primaryKey(),image:B(`image`),name:B(`name`).notNull(),updatedAt:V(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull()}),Ku=ol(q,({many:e})=>({accounts:e(Au),oauthAccessTokens:e(Pu),oauthClients:e(W),oauthConsents:e(Bu),oauthRefreshTokens:e(G),sessions:e(K)})),qu=ku(`verification`,{createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),identifier:B(`identifier`).notNull(),updatedAt:V(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull(),value:B(`value`).notNull()},e=>[vc(`verification_expiresAt_idx`).on(e.expiresAt),vc(`verification_identifier_idx`).on(e.identifier)]),Ju=r({accessKeys:()=>Yu,account:()=>Au,accountConfigs:()=>Xu,accountRelations:()=>ju,appRealms:()=>Zu,auditEvents:()=>Qu,deviceCode:()=>Mu,deviceRequests:()=>$u,firstAccounts:()=>ed,jwks:()=>Nu,keys:()=>td,oauthAccessToken:()=>Pu,oauthAccessTokenRelations:()=>Fu,oauthClient:()=>W,oauthClientAssertion:()=>Iu,oauthClientRelations:()=>Lu,oauthClientResource:()=>Ru,oauthClientResourceRelations:()=>zu,oauthConsent:()=>Bu,oauthConsentRelations:()=>Vu,oauthRefreshToken:()=>G,oauthRefreshTokenRelations:()=>Hu,oauthResource:()=>Uu,oauthResourceRelations:()=>Wu,pendingKeys:()=>nd,realmPasskeys:()=>rd,realmPrivy:()=>id,realmSecp256k1:()=>ad,realms:()=>J,revokedSigningKeys:()=>od,secp256k1Owners:()=>sd,securityEvents:()=>cd,session:()=>K,sessionRelations:()=>Gu,user:()=>q,userRelations:()=>Ku,verification:()=>qu}),Yu=ku(`access_keys`,{account:B(`account`).notNull(),address:B(`address`).notNull(),chainId:Po(`chain_id`).notNull(),clientId:B(`client_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),keyType:B(`key_type`).notNull(),limits:Uo(`limits`),realmId:B(`realm_id`),revokedAt:V(`revoked_at`),scopes:Uo(`scopes`),transaction:B(`transaction`),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`access_keys_expires_at_idx`).on(e.expiresAt),vc(`access_keys_user_id_idx`).on(e.userId,e.expiresAt),bc({columns:[e.chainId,e.account,e.address]})]),Xu=ku(`account_configs`,{address:B(`address`).notNull(),chainId:Po(`chain_id`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),key:B(`key`).notNull(),owners:Uo(`owners`).notNull(),salt:B(`salt`).notNull(),threshold:Po(`threshold`).notNull(),updatedAt:V(`updated_at`).defaultNow().notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`}),version:B(`version`).notNull()},e=>[bc({columns:[e.chainId,e.address]}),vc(`account_configs_user_id_idx`).on(e.userId)]),Zu=ku(`app_realms`,{clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),position:Po(`position`).notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id)},e=>[mc(`app_realms_position_check`,z`${e.position} >= 0`),bc({columns:[e.clientId,e.position]}),Bi(`app_realms_client_id_realm_id_unique`).on(e.clientId,e.realmId)]),Qu=ku(`audit_events`,{action:B(`action`).notNull(),actor:B(`actor`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),details:Uo(`details`).$type().notNull(),id:B(`id`).primaryKey(),requestId:B(`request_id`),targetId:B(`target_id`).notNull(),targetType:B(`target_type`).notNull()},e=>[vc(`audit_events_created_at_idx`).on(e.createdAt,e.id),vc(`audit_events_target_idx`).on(e.targetType,e.targetId)]),$u=ku(`device_requests`,{account:B(`account`),challenge:B(`challenge`),city:B(`city`),country:B(`country`),createdAt:V(`created_at`).defaultNow().notNull(),device:B(`device`),expiresAt:V(`expires_at`).notNull(),id:B(`id`).primaryKey(),ip:B(`ip`),key:Uo(`key`),keyAuthorization:Uo(`key_authorization`),location:B(`location`)},e=>[vc(`device_requests_expires_at_idx`).on(e.expiresAt)]),ed=ku(`first_accounts`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id,{onDelete:`cascade`}),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[bc({columns:[e.userId,e.realmId]})]),td=ku(`keys`,{address:B(`address`).unique(),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),publicKey:B(`public_key`).notNull(),rpId:B(`rp_id`).notNull(),source:B(`source`).notNull(),type:B(`type`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[mc(`keys_source_check`,z`${e.source} in ('registered', 'tempo-id', 'tempo-wallet', 'wallet')`),mc(`keys_type_check`,z`${e.type} = 'passkey'`),vc(`keys_user_id_idx`).on(e.userId)]),nd=ku(`pending_keys`,{account:B(`account`).notNull(),clientId:B(`client_id`).notNull().references(()=>W.clientId,{onDelete:`cascade`}),codeChallenge:B(`code_challenge`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),expiresAt:V(`expires_at`).notNull(),keyAuthorization:Uo(`key_authorization`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`pending_keys_expires_at_idx`).on(e.expiresAt),bc({columns:[e.clientId,e.codeChallenge]})]),rd=ku(`realm_passkeys`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`}),rpId:B(`rp_id`).notNull().unique()}),id=ku(`realm_privy`,{appId:B(`app_id`).notNull().unique(),appSecret:B(`app_secret`).notNull(),createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`})}),ad=ku(`realm_secp256k1`,{createdAt:V(`created_at`).defaultNow().notNull(),realmId:B(`realm_id`).primaryKey().references(()=>J.id,{onDelete:`cascade`})}),J=ku(`realms`,{createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),name:B(`name`).notNull()},e=>[mc(`realms_id_check`,z`${e.id} ~ '^[a-z0-9]+(-[a-z0-9]+)*$'`)]),od=ku(`revoked_signing_keys`,{alg:B(`alg`),id:B(`id`).primaryKey(),publicKey:B(`public_key`).notNull(),revokedAt:V(`revoked_at`).notNull(),signsUntil:V(`signs_until`).notNull()}),sd=ku(`secp256k1_owners`,{address:B(`address`).notNull().unique(),createdAt:V(`created_at`).defaultNow().notNull(),privateKey:B(`private_key`).notNull(),realmId:B(`realm_id`).notNull().references(()=>J.id,{onDelete:`cascade`}),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[bc({columns:[e.userId,e.realmId]})]),cd=ku(`security_events`,{clientId:B(`client_id`),createdAt:V(`created_at`).defaultNow().notNull(),id:B(`id`).primaryKey(),type:B(`type`).notNull(),userId:B(`user_id`).notNull().references(()=>q.id,{onDelete:`cascade`})},e=>[vc(`security_events_created_at_idx`).on(e.createdAt),vc(`security_events_user_idx`).on(e.userId,e.createdAt,e.id)]),ld=`Payload Too Large`,ud=e=>{let t=e.onError||(()=>{throw new hn(413,{res:new Response(ld,{status:413})})}),n=e.maxSize;return async function(e,r){if(!e.req.raw.body)return r();let i=e.req.raw.headers.has(`transfer-encoding`);if(e.req.raw.headers.has(`content-length`)&&!i)return parseInt(e.req.raw.headers.get(`content-length`)||`0`,10)>n?t(e):r();let a=0,o=[],s=e.req.raw.body.getReader();for(;;){let{done:r,value:i}=await s.read();if(r)break;if(a+=i.length,a>n)return t(e);o.push(i)}let c={body:new ReadableStream({start(e){for(let t of o)e.enqueue(t);e.close()}}),duplex:`half`};return e.req.raw=new Request(e.req.raw,c),r()}},dd=`https://github.com/tempoxyz/id/blob/main/docs/errors.md`,fd={already_decided:{description:`The user code was already approved or denied.`,error:`invalid_request`,status:409},app_exists:{description:`Another OAuth app already has the client ID.`,error:`invalid_request`,status:409},authorization_expired:{description:`The app's authorization request that sign-in or the approval page continues is forged or expired.`,error:`invalid_request`,status:400},backend_sign_in_not_permitted:{description:`The app may not sign users in from its backend: it is not an enabled first-party app with a client secret and backend sign-in.`,error:`unauthorized_client`,status:403},body_too_large:{description:`The request body exceeds 64 KiB.`,error:`invalid_request`,status:413},challenge_not_permitted:{description:"A request carries a challenge, and its app lacks the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},config_conflict:{description:`The chain's configuration of the account differs from the one that Tempo ID stores.`,error:`invalid_request`,status:409},configurable_accounts_disabled:{description:`The deployment has no configurable accounts, or the request names another chain.`,error:`invalid_request`,status:400},cross_site_request:{description:`A form or body-less write came from another site.`,error:`access_denied`,status:403},duplicate_limit:{description:`Two limits name the same token.`,error:`invalid_authorization_details`,status:400},duplicate_scope:{description:`Two scopes name the same call on one target, or one allows any function on a target that another names a function on.`,error:`invalid_authorization_details`,status:400},employee_required:{description:`The request carries no verified Tempo employee identity, or the identity is inactive.`,error:`access_denied`,status:401},empty_limits:{description:"`limits` is an empty list.",error:`invalid_authorization_details`,status:400},empty_scopes:{description:"`scopes` is an empty list.",error:`invalid_authorization_details`,status:400},expiry_exceeds_maximum:{description:`A headless key lasts longer than a year.`,error:`invalid_authorization_details`,status:403},expiry_passed:{description:`The key expiry has passed.`,error:`invalid_authorization_details`,status:400},foreign_account:{description:`The request names a Tempo Account that is not the user's in the app's realms.`,error:`access_denied`,status:403},invalid_app:{description:`A value of an OAuth app, such as its name or a redirect URI, is not valid, or does not fit the app's type.`,error:`invalid_request`,status:400},invalid_chain:{description:`The key chain ID is 0.`,error:`invalid_authorization_details`,status:400},invalid_client:{description:`The client authentication failed: the app is unknown or disabled, or the client secret is missing or wrong.`,error:`invalid_client`,status:401},invalid_client_attestation:{description:`A native app's client attestation, its proof, or the platform attestation behind it is missing or does not verify.`,error:`invalid_client`,status:401},invalid_code:{description:`The emailed code is wrong or expired.`,error:`invalid_grant`,status:401},invalid_dpop_proof:{description:`The DPoP proof of a code redemption is missing, invalid, replayed, or from another key than the tokens.`,error:`invalid_dpop_proof`,status:400},invalid_expiry:{description:`The key expiry is 0, which never expires.`,error:`invalid_authorization_details`,status:400},invalid_field:{description:`A field is missing or malformed.`,error:`invalid_request`,status:400},invalid_id_token_hint:{description:`The ID token hint is not an ID token that Tempo ID signed for the app.`,error:`invalid_request`,status:400},invalid_origin:{description:`A headless request came from an origin its redirect URI does not allow.`,error:`unauthorized_client`,status:403},invalid_period:{description:"A limit's `period` is not a whole number of seconds.",error:`invalid_authorization_details`,status:400},invalid_public_key:{description:`The key public key is not a valid point.`,error:`invalid_authorization_details`,status:400},invalid_realm:{description:`A value of a realm, such as its ID, name, passkey relying party, or Privy app, or a list of an app's realms, is not valid.`,error:`invalid_request`,status:400},invalid_recipients:{description:"A scope's `recipients` names the zero address or a duplicate, or is on a call other than `transfer`, `transferWithMemo`, or `approve` on a TIP-20 token.",error:`invalid_authorization_details`,status:400},limit_exceeds_maximum:{description:`A headless key limit exceeds the token’s ceiling.`,error:`invalid_authorization_details`,status:403},logout_not_permitted:{description:`The app that the ID token hint names may not end the session at the end-session endpoint.`,error:`unauthorized_client`,status:403},malformed_body:{description:`The request body is not valid JSON.`,error:`invalid_request`,status:400},missing_key:{description:`The key authorization names no key.`,error:`invalid_authorization_details`,status:400},missing_permissions:{description:"A third-party app's key request leaves out `expiry`, `limits`, or `scopes`.",error:`invalid_authorization_details`,status:400},missing_recipients:{description:"An `approve` scope names no spenders.",error:`invalid_authorization_details`,status:400},passkey_link_expired:{description:`The email step's link to a wallet.tempo passkey expired, or the browser holds no link for it.`,error:`invalid_request`,status:400},passkey_not_permitted:{description:`A passkey sign-in names an app, or reaches a realm, that holds no passkeys for Tempo ID.`,error:`unauthorized_client`,status:403},passkey_register_not_permitted:{description:"A passkey registration comes from an app's page, and no app at the page's origin holds the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},not_configurable:{description:`The account is not configurable on the chain, so no owner can join it, or no passkey owns it, so it cannot upgrade.`,error:`invalid_request`,status:400},origin_required:{description:"A request without `Origin` names an app by `client_id` alone, which proves no app.",error:`access_denied`,status:403},owner_exists:{description:`The account already holds the owner that the request adds, or is already configurable.`,error:`invalid_request`,status:409},owner_unavailable:{description:`The user's cloud wallet cannot join the account, since its own account holds a balance or live access keys, another account names it, or no realm creates one.`,error:`invalid_request`,status:409},passkey_limit:{description:`The user holds the most passkeys that Tempo ID registers for one user.`,error:`access_denied`,status:403},post_logout_redirect_not_permitted:{description:`The post-logout redirect URI is not one of the post-logout redirect URIs the app registered.`,error:`invalid_request`,status:400},privy_app_taken:{description:`Another realm holds the Privy app.`,error:`invalid_request`,status:409},public_app:{description:`The OAuth app redeems codes with PKCE alone, so it has no client secret to rotate.`,error:`invalid_request`,status:400},pushed_authorization_required:{description:`The OAuth app requires a pushed authorization request (RFC 9126) for a key, and the request carries its parameters in the URL.`,error:`invalid_request`,status:400},rate_limited:{description:`Tempo ID, or a service it depends on, is rate limiting the request.`,error:`temporarily_unavailable`,status:429},realm_exists:{description:`A realm with the ID exists.`,error:`invalid_request`,status:409},realm_in_use:{description:`An OAuth app names the realm, so it cannot be removed.`,error:`invalid_request`,status:409},reauthentication_required:{description:`The request needs a session that signed in within the last 10 minutes, such as for a passkey registration, an owner change, or a key above the headless ceiling.`,error:`login_required`,status:401},rejected:{description:`The issuer refused the authorization request.`,error:`invalid_request`,status:400},relying_party_taken:{description:`Another realm holds the passkey relying party.`,error:`invalid_request`,status:409},scope_without_limit:{description:`A scope calls a listed token that no limit names.`,error:`invalid_authorization_details`,status:400},session_changed:{description:`The signed-in session differs from the one that the approval page showed.`,error:`invalid_request`,status:409},session_required:{description:`The request needs a signed-in session.`,error:`login_required`,status:401},sign_not_permitted:{description:"A request to sign as the user's cloud wallet comes from a page that is not a first-party app with the `tempo-id:sign` scope.",error:`unauthorized_client`,status:403},sign_out_link_expired:{description:`A security email's link to sign out every session is unknown, spent, or expired.`,error:`invalid_request`,status:400},sign_up_not_permitted:{description:`The verified address has no account, and its domain is not one where the deployment creates accounts.`,error:`access_denied`,status:403},signing_key_in_use:{description:`A revocation names a signing key that signs tokens now or after the publication delay, without a rotation.`,error:`invalid_request`,status:409},too_many_signing_keys:{description:`The deployment holds the most signing keys that a rotation keeps, live or in their grace period.`,error:`invalid_request`,status:409},unexpected:{description:`An unexpected failure.`,error:`server_error`,status:500},unknown_app:{description:`No registered OAuth app has the client ID.`,error:`invalid_request`,status:404},unknown_code:{description:`The user code is wrong or expired.`,error:`invalid_request`,status:404},unknown_endpoint:{description:`No API endpoint matches this method and path.`,error:`invalid_request`,status:404},unknown_key:{description:`The signed-in user holds no live access key with the address on the account and chain.`,error:`invalid_request`,status:404},unknown_realm:{description:`No realm has the ID.`,error:`invalid_request`,status:404},unknown_session:{description:`The user has no session with the ID.`,error:`invalid_request`,status:404},unknown_signing_key:{description:`No signing key that is not revoked has the ID.`,error:`invalid_request`,status:404},unknown_user:{description:`No user has the ID.`,error:`invalid_request`,status:404},unsupported_call:{description:`A selector does not parse, a scope allows any function on a TIP-20 token, or a headless scope names an unrecognized call.`,error:`invalid_authorization_details`,status:400},unsupported_token:{description:`A limit names a token that is not supported on the chain.`,error:`invalid_authorization_details`,status:400},upgrade_required:{description:`A key authorization names a wallet.tempo passkey's account on a chain whose accounts are configurable, before its upgrade.`,error:`interaction_required`,status:403},upstream_unavailable:{description:`A service Tempo ID depends on failed or did not respond.`,error:`temporarily_unavailable`,status:503},webauthn_rejected:{description:`A passkey ceremony failed: its challenge is unknown, spent, or expired, or its response does not verify.`,error:`access_denied`,status:401},webauthn_required:{description:`A request without a page names a Tempo Account whose passkey signs only on a Tempo ID page.`,error:`interaction_required`,status:403}},pd=class extends hn{name=`ErrorResponse.ResponseError`;response;constructor(e){let t=fd[e.reason].status;super(t,{res:Response.json(e,{status:t})}),this.response=e}};function md(e){return class extends pd{static reason=e;constructor(t){super(Sd({...t,reason:e}))}}}var hd=class extends md(`cross_site_request`){name=`ErrorResponse.CrossSiteRequestError`;constructor(){super({error_description:`Cross-site request refused. Send JSON from an allowed origin.`})}},gd=class extends md(`malformed_body`){name=`ErrorResponse.MalformedBodyError`;constructor(){super({error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."})}},_d=class extends md(`rate_limited`){name=`ErrorResponse.RateLimitedError`;retryAfter;constructor(e={}){let{retryAfter:t}=e;super({error_description:`Rate limited by an upstream service. Try again ${t?`in ${Ed({seconds:t})}`:`later`}.`,...t?{meta:{retryAfter:t}}:{}}),this.retryAfter=t}},vd=class extends md(`unexpected`){name=`ErrorResponse.UnexpectedError`;constructor(){super({error_description:`Unexpected error. Try again.`})}},yd=class extends md(`unknown_endpoint`){name=`ErrorResponse.UnknownEndpointError`;constructor(){super({error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`})}},bd=class extends md(`upstream_unavailable`){name=`ErrorResponse.UpstreamUnavailableError`;constructor(){super({error_description:`An upstream service is unavailable. Retry later.`})}},xd;(function(e){let t=e.base=v({error:y().meta({description:"The OAuth error code (RFC 6749, OIDC Core, RFC 8628, RFC 9396), which `reason` determines."}),error_description:y().meta({description:`What went wrong and how to fix it, for people. Its wording may change.`}),error_uri:se().meta({description:"The errors page, at the refusal’s `reason`."}),field:y().optional().meta({description:`Extension: the request field at fault, as a dotted path.`}),meta:C(y(),ce([S(),y()])).readonly().optional().meta({description:`Extension: the values the refusal compared. Base units are decimal strings.`}),reason:y().meta({description:`Extension: a stable name for the refusal, to branch on.`}),request_id:y().optional().meta({description:"Extension: the request ID, which `X-Request-Id` also carries. The Worker adds it to every error response."})}),n={already_decided:{error_description:`Code already approved or denied.`,field:`code`},app_exists:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T already exists. Update it, or choose another client ID.`,field:`clientId`},authorization_expired:{error_description:`Expired authorization request: the request from the app is no longer valid. Return to the app, and start again.`,field:`oauth_query`},backend_sign_in_not_permitted:{error_description:"Backend sign-in not permitted: the app does not hold backend sign-in. Grant it with `tempo-id admin apps clientId patch <client-id> --backend-sign-in true`.",field:`client_id`},body_too_large:{error_description:`Invalid request body: exceeds the 65536-byte maximum. Send a body of 65536 bytes or fewer.`},challenge_not_permitted:{error_description:"Challenge not permitted: the app lacks the `tempo-id:sign` scope. Remove `challenge`, or grant the app the scope.",field:`challenge`},config_conflict:{error_description:`Configuration conflict: the chain's configuration of 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c differs from the stored one. Reload the account, and try again.`,field:`account`},configurable_accounts_disabled:{error_description:"Configurable accounts are not available on the chain `testnet`. Select the chain `t14`.",field:`chain`},cross_site_request:{error_description:`Cross-site request refused. Send JSON from an allowed origin.`},duplicate_limit:{error_description:`Duplicate limit for 0x20c0000000000000000000000000000000000001. Limit each token once.`,field:`key_authorization.limits.1.token`},duplicate_scope:{error_description:`Duplicate scope for 0xa9059cbb on OUSD. Name each call on a target once.`,field:`key_authorization.scopes.1.selector`},employee_required:{error_description:`Employee identity required: the Cf-Access-Jwt-Assertion header holds no verified employee identity for this app. Forward the access assertion of a request that the app's access policy admitted.`,field:`Cf-Access-Jwt-Assertion`},empty_limits:{error_description:"Empty `limits`. Name at least one token, or omit `limits`.",field:`key_authorization.limits`},empty_scopes:{error_description:"Empty `scopes`. Name at least one call, or omit `scopes`.",field:`key_authorization.scopes`},expiry_exceeds_maximum:{error_description:"Invalid `expiry`: Sat, 01 Jan 2028 00:00:00 GMT exceeds the one-year maximum. Use an earlier expiry, or authorize through a redirect or device grant.",field:`key_authorization.expiry`},expiry_passed:{error_description:"Invalid `expiry`: Wed, 01 Jan 2025 00:00:00 GMT has passed. Use a future Unix time.",field:`key_authorization.expiry`},foreign_account:{error_description:`Access denied to Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Name one of the user's accounts in the app's realms.`,field:`account`},invalid_app:{error_description:`Invalid redirect URI: http://app.example/callback uses http. Use an https URI.`},invalid_chain:{error_description:"Invalid `chainId`: 0. Use a Tempo chain ID, such as 4217.",field:`key_authorization.chainId`},invalid_client:{error_description:`Client authentication failed. Send the client ID and secret, or a client assertion, of an enabled app.`,field:`client_secret`},invalid_client_attestation:{error_description:"Invalid client attestation: the proof is too old, or issued in the future. Attest the app again at `POST /v1/attestation`, and send a new proof.",field:`OAuth-Client-Attestation-PoP`},invalid_code:{error_description:`Invalid or expired code. Request a new one.`,field:`code`},invalid_dpop_proof:{error_description:`Invalid DPoP proof: DPoP proof jti has already been used. Send a new proof for POST /oauth2/token from the key of the app.`,field:`dpop`},invalid_expiry:{error_description:"Invalid `expiry`: 0 never expires. Use a future Unix time.",field:`key_authorization.expiry`},invalid_field:{error_description:"Invalid request. `email`: Invalid email address.",field:`email`},invalid_id_token_hint:{error_description:`Invalid id_token_hint: it is not an ID token that this issuer signed for the app. Send the ID token that the app received at sign-in.`,field:`id_token_hint`},invalid_origin:{error_description:"Invalid `Origin`: https://other.example.com. Requests for this redirect URI must come from https://app.example.com.",field:`Origin`},invalid_period:{error_description:"Invalid `period` on the OUSD limit: 1.5. Use a whole number of seconds, or 0 for a one-time limit.",field:`key_authorization.limits.0.period`},invalid_public_key:{error_description:"Invalid `publicKey`. Provide an uncompressed public key, or `address`.",field:`key_authorization.publicKey`},invalid_realm:{error_description:`Invalid id: Use lowercase kebab case, such as tempo-cash.`},invalid_recipients:{error_description:`Invalid recipient 0x0000000000000000000000000000000000000000 for 0x095ea7b3 on OUSD. Name each recipient once, and never the zero address.`,field:`key_authorization.scopes.0.recipients.0`},limit_exceeds_maximum:{error_description:`Invalid OUSD limit: 5000 exceeds the 1000 maximum. Lower the limit, or authorize through a redirect or device grant.`,field:`key_authorization.limits.0.limit`},logout_not_permitted:{error_description:`Logout not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T may not end the session. Register the app for logout, then retry.`},malformed_body:{error_description:"Malformed request body. Send a JSON object with `Content-Type: application/json`."},missing_key:{error_description:"Missing `address` or `publicKey`. Provide the access key.",field:`key_authorization.address`},missing_permissions:{error_description:"Missing `limits` and `scopes`. Name the expiry, limits, and scopes of the key. Without `limits` and `scopes`, a key spends any amount or makes any call.",field:`key_authorization.limits`},missing_recipients:{error_description:"Missing `recipients` for `approve` on OUSD. Name the allowed spenders.",field:`key_authorization.scopes.0.recipients`},passkey_link_expired:{error_description:`Expired passkey sign-in: the link from the passkey step is no longer valid. Enter the code again to sign in with email only, or sign in with the passkey again.`,field:`link`},passkey_not_permitted:{error_description:`Passkey not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T holds no passkeys. Sign in with an emailed code.`},passkey_register_not_permitted:{error_description:"Passkey registration not permitted: no app at https://app.example.com holds the `tempo-id:sign` scope. Register the passkey on Tempo ID, or grant the app the scope."},not_configurable:{error_description:`Not configurable: 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account yet. Upgrade it with its passkey, then add the owner.`,field:`account`},origin_required:{error_description:`Origin required: the request names the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T without an Origin header. Send it from a page at a redirect URI of the app, or leave out client_id.`,field:`client_id`},owner_exists:{error_description:`Owner exists: a cloud wallet already owns 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c. Use the account as it is.`,field:`wallet`},owner_unavailable:{error_description:"Owner unavailable: the cloud wallet 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c holds a balance on its own account, so it cannot join 0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f. Move the balance to another account, or upgrade without `add_owner`.",field:`add_owner`},passkey_limit:{error_description:`Passkey limit reached: the user holds 10 registered passkeys, the most that Tempo ID registers. Sign in with one of them.`},post_logout_redirect_not_permitted:{error_description:`Invalid post_logout_redirect_uri: https://app.example/elsewhere is not registered for the app. Use one of its post-logout redirect URIs, or leave it out.`,field:`post_logout_redirect_uri`},privy_app_taken:{error_description:`Privy app cm0000000000000000000000 belongs to another realm. Give each realm its own Privy app.`,field:`appId`},public_app:{error_description:`App client_01JZ8Q6W3N1R5B4V7C2X9K0M3T has no client secret. Rotate the secret of an app with a backend.`,field:`clientId`},pushed_authorization_required:{error_description:"Pushed authorization request required: the app sends `key_authorization` only through `/oauth2/par`. Push the request, and send its `request_uri` to `/oauth2/authorize`.",field:`key_authorization`},rate_limited:{error_description:`Too many requests. Try again in 30 seconds.`},realm_exists:{error_description:`Realm tempo-cash exists. Choose another ID.`,field:`id`},realm_in_use:{error_description:`Realm tempo-cash is in use. Remove it from the realms of each app first.`,field:`id`},reauthentication_required:{error_description:`Sign in again: this action needs a sign-in within the last 10 minutes. Confirm the sign-in with a passkey or an emailed code, then retry.`},rejected:{error_description:"Authorization request rejected. Check `client_id`, `redirect_uri`, and `scope` against the app's registration."},relying_party_taken:{error_description:`Relying party example.com belongs to another realm. Give each realm its own relying party.`,field:`rpId`},scope_without_limit:{error_description:`Scope on 0x20c0000000000000000000000000000000000002 has no limit. Add a limit for it, or remove the scope.`,field:`key_authorization.scopes.0.address`},session_changed:{error_description:`Changed session: the signed-in account differs from the one that this page showed. Reload the page, and check the account before the decision.`,field:`session_id`},session_required:{error_description:`Sign in first.`},sign_not_permitted:{error_description:"Signing not permitted: the app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T at https://app.example.com does not hold the `tempo-id:sign` scope. Grant the app the scope, or sign with the account's passkey.",field:`client_id`},sign_out_link_expired:{error_description:`Expired link: the link to sign out every session is spent or older than 7 days. Sign in, and review the passkeys and apps of the account.`,field:`token`},sign_up_not_permitted:{error_description:`Sign-up not permitted: new accounts need an address at example.com. Sign in with an existing account, or with an address at example.com.`,field:`email`},signing_key_in_use:{error_description:`Invalid revocation of signing key 0b5c2f0e-4f7a-4a8e-9a43-3f1d7b8c6e21: the key signs tokens now or after the 5-minute publication delay. Set rotate to true to replace the key in the same operation.`,field:`rotate`},too_many_signing_keys:{error_description:`Too many signing keys: 100 are live or in their grace period. Rotate again after the grace period of the oldest key ends.`},unexpected:{error_description:`Unexpected error. Try again.`},unknown_app:{error_description:`Unknown app client_01JZ8Q6W3N1R5B4V7C2X9K0M3T. Name a registered OAuth app.`,field:`clientId`},unknown_code:{error_description:`Invalid or expired code. Check the code in the terminal.`,field:`code`},unknown_endpoint:{error_description:`Unknown endpoint. Check the method and path against the API reference at /openapi.json.`},unknown_key:{error_description:`Unknown access key 0x81C0f22bD173C115d18eeeA0F6a38E935ecF52fB: no live key with this address acts for the account on the chain. Reload the keys, and name a listed one.`,field:`address`},unknown_realm:{error_description:`Unknown realm tempo-cash. Add it first.`,field:`id`},unknown_session:{error_description:`Unknown session 9fQe2hXc7mLk. Name a live session from GET /users/user_01JZ8Q6W3N1R5B4V7C2X9K0M3T.`,field:`sessionId`},unknown_signing_key:{error_description:`Unknown signing key 0b5c2f0e-4f7a-4a8e-9a43-3f1d7b8c6e21: no live, retired, or expired key has the ID. List the keys, and name a key that is not revoked.`,field:`kid`},unknown_user:{error_description:`Unknown user user_01JZ8Q6W3N1R5B4V7C2X9K0M3T. Name a user that exists.`,field:`id`},unsupported_call:{error_description:"Unsupported call on OUSD: any function, which includes `approve` without spenders. Name each function in `selector`, such as `transfer`.",field:`key_authorization.scopes.0.selector`},unsupported_token:{error_description:`Unsupported token on chain 4217: 0x20c00000000000000000000000000000000000ff. Use a supported token, such as OUSD.`,field:`key_authorization.limits.0.token`},upgrade_required:{error_description:`Upgrade required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c is not a configurable account on this chain yet. Upgrade it on the account page, then authorize again.`,field:`key_authorization.account`},upstream_unavailable:{error_description:`An upstream service is unavailable. Retry later.`},webauthn_rejected:{error_description:`Passkey rejected. Request new options, then try again with the same passkey or another one.`},webauthn_required:{error_description:`Passkey required: Tempo Account 0x8C3b5d0e2A4f6B1c9D7e3F5a0B2c4D6e8F1a3B5c signs key authorizations only with its passkey, on a Tempo ID page. Authorize through a redirect, popup, or device grant, or name another account.`,field:`key_authorization.account`}},r=new Map(Object.entries(fd).map(([e,r])=>{let i=n[e],a=t.extend({error:ve(r.error).meta(t.shape.error.meta()),error_description:t.shape.error_description.meta({...t.shape.error_description.meta(),examples:[i.error_description]}),error_uri:t.shape.error_uri.meta({...t.shape.error_uri.meta(),examples:[`${dd}#${e}`]}),reason:ve(e).meta(t.shape.reason.meta()),request_id:t.shape.request_id.meta({...t.shape.request_id.meta(),examples:[`8f1c2a3b4d5e6f70-SJC`]})});return[e,(i.field?a.extend({field:t.shape.field.meta({...t.shape.field.meta(),examples:[i.field]})}):a.omit({field:!0})).meta({description:`\`${r.error}\` (${r.status}): ${r.description}`,id:`ErrorResponse.${e}`})]}));function i(e){return r.get(e)}e.of=i})(xd||={});function Sd(e){let{error_description:t,field:n,meta:r,reason:i}=e;return{error:fd[i].error,error_description:t,error_uri:`${dd}#${i}`,...n?{field:n}:{},...r?{meta:r}:{},reason:i}}function Cd(e){if(e instanceof hn)return;let t=`status`in e?e.status:void 0;if(t===429)return new _d({retryAfter:(()=>{if(e instanceof Response){let t=Number(e.headers.get(`retry-after`));return Number.isInteger(t)&&t>0?t:void 0}return`retryAfter`in e&&typeof e.retryAfter==`number`?e.retryAfter:void 0})()});let n=`status`in e&&t===void 0;if(typeof t==`number`&&(t===408||t>=500)||n||e instanceof Error&&e.name===`TimeoutError`)return new bd}(function(e){e.errors=[_d,bd]})(Cd||={});function wd(e,t){if(e instanceof pd)return Td(t,e);if(e instanceof hn&&e.status===400)return Td(t,new gd);if(e instanceof hn&&e.status===403)return Td(t,new hd);let n=Cd(e);return n?(gr(t,{error:e,message:`An upstream service refused a request.`}),Td(t,n)):(pr(t,{error:e,message:`The API failed a request.`}),Td(t,new vd))}function Td(e,t){let{response:n}=t;return t instanceof _d&&t.retryAfter&&e.header(`retry-after`,String(t.retryAfter)),e.json(n,fd[n.reason].status)}function Ed(e){let{seconds:t}=e,[n,r]=t<60?[t,`second`]:t<3600?[Math.ceil(t/60),`minute`]:[Math.ceil(t/3600),`hour`];return new Intl.NumberFormat(`en`,{style:`unit`,unit:r,unitDisplay:`long`}).format(n)}var Dd=class extends md(`body_too_large`){name=`BodyLimit.BodyTooLargeError`;constructor(e={}){let{maximum:t=Od}=e;super({error_description:`Invalid request body: exceeds the ${t}-byte maximum. Send a body of ${t} bytes or fewer.`,meta:{maximum:t}})}},Od=65536,kd=ud({maxSize:Od,onError:e=>Td(e,new Dd)}),Ad=e=>e.__COMPOSED_HANDLER?Ad(e[Ln]):e,jd=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;return n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t),h(r,e)[e]}return r?h(r):{}},Md=(e,t,n)=>{let r;return r=n?.prefix===`secure`?d(`__Secure-`+e,t,{path:`/`,...n,secure:!0}):n?.prefix===`host`?d(`__Host-`+e,t,{...n,path:`/`,secure:!0,domain:void 0}):d(e,t,{path:`/`,...n}),r},Nd=(e,t,n,r)=>{let i=Md(t,n,r);e.header(`Set-Cookie`,i,{append:!0})},Pd=(e,t,n)=>{let r=jd(e,t,n?.prefix);return Nd(e,t,``,{...n,maxAge:0}),r},Fd=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,Id=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/i,Ld=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/i,Rd=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Fd.test(a))break;try{i=await n.req.json()}catch{throw new hn(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(Id.test(a)||Ld.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{e=await _n(await n.req.arrayBuffer(),a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new hn(400,{message:t})}let t=Object.create(null);e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):Object.hasOwn(t,n)?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=jd(n)}let o=await t(i,n);return o instanceof Response?o:(n.req.addValidatedData(e,o),await r())},zd={header:[`cookie`]};function Bd(e,t,n){if(!(n in zd))return e;let r=zd[n]||[];return t===`arktype`?Vd(e,r):t===`valibot`?Hd(e,r):e}function Vd(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`data`in e&&typeof e.data==`object`&&e.data!==null&&!Array.isArray(e.data)){let n={...e.data};for(let e of t)delete n[e];let r=Object.create(Object.getPrototypeOf(e));return Object.assign(r,e,{data:n}),r}return e})}function Hd(e,t){return e.map(e=>{if(e&&typeof e==`object`&&`path`in e&&Array.isArray(e.path)){for(let n of e.path)if(typeof n==`object`&&`input`in n&&typeof n.input==`object`&&n.input!==null&&!Array.isArray(n.input))for(let e of t)delete n.input[e]}return e})}var Ud=(e,t,n)=>Rd(e,async(r,i)=>{let a=await t[`~standard`].validate(r);if(n){let t=await n(a.issues?{data:r,error:a.issues,success:!1,target:e}:{data:r,success:!0,target:e},i);if(t){if(t instanceof Response)return t;if(typeof t==`object`&&`response`in t)return t.response}}if(a.issues){let n=Bd(a.issues,t[`~standard`].vendor,e);return i.json({data:r,error:n,success:!1},400)}return a.value}),Wd=Symbol(`openapi`),Gd=`__HonoOpenAPIValidator__`,Kd=[`GET`,`PUT`,`POST`,`DELETE`,`OPTIONS`,`HEAD`,`PATCH`,`TRACE`],qd=e=>{let t=e;if(t.startsWith(`:`)){let e=t.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);e?t=`{${e[1]}}`:(t=t.slice(1,t.length),t.endsWith(`?`)&&(t=t.slice(0,-1)),t=`{${t}}`)}return t},Jd=e=>e.split(`/`).map(qd).join(`/`),Yd=e=>e.split(/[\W_]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``),Xd=e=>{let t=e.method.toLowerCase();if(e.path===`/`)return`${t}Index`;for(let n of e.path.split(`/`)){let e=qd(n);e.charCodeAt(0)===123?t+=`By${Yd(e.slice(1,-1))}`:t+=Yd(e)}return t},Zd=e=>`$ref`in e?e.$ref:`${e.in} ${e.name}`;function Qd(...e){let t=e.flatMap(e=>e??[]).reduce((e,t)=>(e.set(Zd(t),t),e),new Map);return Array.from(t.values())}var $d=new Map;function ef(e,t){let n=[];for(let[r,i]of t){if(!i)continue;let t=r.endsWith(`/*`)?r.slice(0,-2):r;(e===t||e.startsWith(`${t}/`))&&n.push(i)}return n}function tf(e,t){return!e||!t||`$ref`in e||`$ref`in t?t:{...e,...t,content:{...e.content,...t.content}}}function nf(e,...t){return t.reduce((t,n)=>{if(!n||!t)return t;for(let[r,i]of Object.entries(n))if(i!=null){if(r in t&&(typeof i==`object`||typeof i==`function`&&r===`operationId`)){if(Array.isArray(i)){let e=[...t[r]??[],...i];t[r]=r===`tags`?Array.from(new Set(e)):r===`parameters`?Qd(e):e}else typeof i==`function`?t[r]=i(e):r===`parameters`?t[r]=Qd(t[r],i):r===`requestBody`?t.requestBody=tf(t.requestBody,i):t[r]={...t[r],...i}}else t[r]=i}return t},{operationId:Xd(e)})}function rf({route:e,specs:t,paths:n},r=$d){let i=Jd(e.path),a=e.method.toLowerCase();if(a===`all`){if(!t)return;if(r.has(i)){let n=r.get(i)??{};r.set(i,nf(e,n,t))}else r.set(i,t)}else{let o=ef(i,r);i in n||(n[i]={}),n[i]&&(n[i][a]=nf(e,...o,n[i]?.[a],t))}}function af(e,t){let{exclude:n,excludeStaticFile:r}=t.options,i={},a=Array.isArray(n)?n:[n];for(let[n,o]of Object.entries(e)){if(o==null||a.some(e=>typeof e==`string`?n===e:e.test(n))||n.includes(`*`)&&!n.includes(`{`))continue;if(r){let e=n.includes(`{`),t=(n.split(`/`).pop()||``).includes(`.`);if(!e&&t)continue}for(let e of Object.keys(o)){let r=o[e];if(r==null)continue;let i=r[Gd]===!0;if(delete r[Gd],n.includes(`{`)){r.parameters=r.parameters?[...r.parameters]:[];let e=n.split(`/`).filter(e=>e.startsWith(`{`)&&!r.parameters.find(t=>t.in===`path`&&t.name===e.slice(1,e.length-1)));for(let n of e){let e=n.slice(1,n.length-1);r.parameters.findIndex(n=>{if(`$ref`in n){let r=n.$ref.split(`/`).pop();if(r){let n=t.components.parameters?.[r];if(n&&!(`$ref`in n))return n.in===`path`&&n.name===e}return!1}return n.in===`path`&&n.name===e})===-1&&r.parameters.push({schema:{type:`string`},in:`path`,name:e,required:!0})}}if(r.responses||={200:{}},i&&t.options.defaultValidationErrorResponse!==!1&&!r.responses[400]){let e=t.options.defaultValidationErrorResponse;typeof e==`object`?r.responses[400]=structuredClone(e):t.validationErrorResponse&&(r.responses[400]=structuredClone(t.validationErrorResponse))}}let e={};for(let t of Object.keys(o))o[t]!=null&&(e[t]=o[t]);Object.keys(e).length>0&&(i[n]=e)}return i}var of={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:[`OPTIONS`],excludeTags:[],defaultValidationErrorResponse:!0},sf={description:`Validation Error`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,enum:[!1]},error:{type:`array`,items:{}},data:{}},required:[`success`,`error`,`data`]}}}};async function cf(e,t=of,n){let r={components:{},options:{...of,...t},validationErrorResponse:sf},i=r.options.documentation??{},a={...i,components:i.components&&{...i.components}},o=await lf(e,r);for(let e in o)for(let t in o[e])uf({valueOrFunc:o[e][t]?.hide,method:t,path:e,c:n})&&(o[e][t]=void 0);let s=a.components?.responses?await hf(a.components.responses):void 0;s&&a.components&&(a.components.responses=s.responses);let c=_f(a.components,s?.components,r.components);return{openapi:`3.1.0`,...a,tags:a.tags?.filter(e=>!r.options.excludeTags?.includes(e?.name)),info:{title:`Hono Documentation`,description:`Development documentation`,version:`0.0.0`,...a.info},paths:{...af(o,r),...a.paths},components:c}}async function lf(e,t){let n={},r=new Map;for(let i of e.routes){let e=Ad(i.handler)[Wd];if(!e){t.options.includeEmptyPaths&&rf({route:i,paths:n},r);continue}let a=i.method;if(a!==`ALL`&&(t.options.excludeMethods?.includes(a)||!Kd.includes(a)))continue;let{schema:o,components:s={}}=await df(e,t.options.defaultOptions?.[a]&&{...t.options.defaultOptions[a]},t.components.parameters);t.components=_f(t.components,s),rf({route:i,specs:o,paths:n},r)}return n}function uf(e){let{valueOrFunc:t,c:n,method:r,path:i}=e;if(t!=null){if(typeof t==`boolean`)return t;if(typeof t==`function`)return t({c:n,method:r,path:i})}return!1}async function df(e,t,n){if(`spec`in e){let n={...t,...e.spec,responses:{...t?.responses,...e.spec.responses}},r={};if(n.responses){let e=await hf(n.responses);n.responses=e.responses,r=e.components}if(n.requestBody&&`content`in n.requestBody){let e=await mf(n.requestBody.content);n.requestBody={...n.requestBody,content:e.content},r=_f(r,e.components)}return{schema:n,components:r}}let r=await e.toOpenAPISchema();gf(r);let i={...t,[Gd]:!0};if(e.target===`form`||e.target===`json`){let t=e.options?.media??(e.target===`json`?`application/json`:`multipart/form-data`);!i.requestBody||!(`content`in i.requestBody)||!i.requestBody.content?i.requestBody={required:!0,content:{[t]:{schema:r.schema}}}:i.requestBody.content[t]={schema:r.schema}}else{let t=[];if(`$ref`in r.schema){let i=r.schema.$ref.split(`/`).pop();if(i&&r.components?.schemas?.[i]){let a=r.components.schemas[i],o=ff(e.target,a,r.components.schemas),s=o.length===1?o[0]:void 0,c=n?.[i];s&&(!c||`in`in c&&c.in===s.in&&c.name===s.name)?(r.components.parameters??={},r.components.parameters[i]=s,t.push({$ref:`#/components/parameters/${i}`}),delete r.components.schemas[i]):t=o}}else t=ff(e.target,r.schema,r.components?.schemas);i.parameters=t}return{schema:i,components:r.components}}function ff(e,t,n){let r=[];for(let[i,a]of pf(t,n)){let t={in:e===`param`?`path`:e,name:i,schema:a.schema};a.required&&(t.required=!0),t.schema&&`description`in t.schema&&t.schema.description&&(t.description=t.schema.description,t.schema={...t.schema,description:void 0}),r.push(t)}return r}function pf(e,t){let n=new Map,r=new Set,i=e=>{for(let[t,r]of Object.entries(e.properties??{})){let i=n.get(t);n.set(t,{schema:i?{allOf:[i.schema,r]}:r,required:!!e.required?.includes(t)||i?.required})}for(let n of e.allOf??[])if(`$ref`in n){if(!n.$ref.startsWith(`#/components/schemas/`))continue;let e=n.$ref.slice(21).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`),a=t?.[e];a&&!r.has(e)&&(r.add(e),i(a),r.delete(e))}else i(n)};return i(e),n}async function mf(e){let t={},n={};for(let[r,i]of Object.entries(e))if(i){if(i.schema&&`toOpenAPISchema`in i.schema){let e=await i.schema.toOpenAPISchema();gf(e),n[r]={...i,schema:e.schema},e.components&&(t=_f(t,e.components))}else n[r]=i}return{content:n,components:t}}async function hf(e){let t={},n={};for(let[r,i]of Object.entries(e)){if(!i||!(`content`in i)||!i.content){n[r]=i;continue}let e=await mf(i.content);n[r]={...i,content:e.content},t=_f(t,e.components)}return{responses:n,components:t}}function gf(e){let t=e.schema.$defs;t&&typeof t==`object`&&(e.components??={},e.components.schemas={...t,...e.components.schemas},delete e.schema.$defs)}function _f(...e){return e.reduce((e,t,n)=>(t==null||n===0||((e.schemas&&Object.keys(e.schemas).length>0||t.schemas&&Object.keys(t.schemas).length>0)&&(e.schemas={...e.schemas,...t.schemas}),(e.parameters&&Object.keys(e.parameters).length>0||t.parameters&&Object.keys(t.parameters).length>0)&&(e.parameters={...e.parameters,...t.parameters})),e),e[0]??{})}var vf=e=>e.base,yf=e=>{e.zodSchema._zod.def.type===`date`&&(e.jsonSchema.type=`string`,e.jsonSchema.format=`date-time`)};function bf(e,t){let n=e[`~standard`].vendor;return{vendor:n,validate:e[`~standard`].validate,toJSONSchema:n=>ye(e,{...t,...n}),toOpenAPISchema:r=>be(e,{...t,...r,...n===`arktype`?xf(t,r):void 0,...n===`zod`?Sf(e,t,r):void 0})}}function xf(e,t){let n=e?.options,r=t?.options;if(!(e?.fallback||n?.fallback||t?.fallback||r?.fallback))return{options:{fallback:vf,...n,...r}}}function Sf(e,t,n){if(!(`_zod`in e))return;let r=t?.options,i=n?.options;if(!(t?.override||r?.override||n?.override||i?.override))return{options:{unrepresentable:`any`,override:yf,...r,...i}}}function Cf(e,t,n,r){let i=Ud(e,t,n);return Object.defineProperty(i,"name",{value:`validator`,configurable:!0}),Object.assign(i,{[Wd]:{target:e,...bf(t,r),options:r}})}function wf(e){let t=async(e,t)=>{await t()};return Object.defineProperty(t,"name",{value:`describeRoute`,configurable:!0}),Object.assign(t,{[Wd]:{spec:e}})}var Tf=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(dt(e),Me(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Be(r)}update(e){return Le(this),this.iHash.update(e),this}digestInto(e){Le(this),Ve(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ef=(()=>{let e=((e,t,n)=>new Tf(e,t).update(n).digest());return e.create=(e,t)=>new Tf(e,t),e})(),Df=Uint8Array.of(0),Of=Uint8Array.of();function kf(e,t,n,r=32,i){dt(e),Se(r,`length`),Me(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Of:Me(n,void 0,`info`),!o)return i&&Be(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Ef.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){Df[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(Df).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(Df[0]=o,o>1&&c.update(u),c.update(n).update(Df).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&Be(u),Be(Df),r===s.length)return s;let f=s.slice(0,r);return Be(s),f}var Af=(e,t,n,r,i)=>{dt(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Ef.create(e,n).update(t);return kf(e,a.digest(),r,i,a)},jf=e=>e/2**32|0,Mf=e=>e>>>0;function Nf(e,t,n,r){let i=jf(n),a=Mf(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Pf(e,t,n){return e&t^~e&n}function Ff(e,t,n){return e&t^e&n^t&n}var If=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=De(this.buffer)}update(e){Le(this),Me(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=De(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){Le(this),Ve(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),Nf(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:De(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},Lf=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Rf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zf=new Uint32Array(64),Bf=class extends If{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)zf[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=zf[e-15],n=zf[e-2],r=nt(t,7)^nt(t,18)^t>>>3,i=nt(n,17)^nt(n,19)^n>>>10;zf[e]=i+zf[e-7]+r+zf[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=nt(o,6)^nt(o,11)^nt(o,25),u=l+t+Pf(o,s,c)+Rf[e]+zf[e]|0,d=(nt(n,2)^nt(n,13)^nt(n,22))+Ff(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Be(zf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Be(this.buffer)}},Vf=class extends Bf{constructor(){super(32,Lf)}},Hf=He(()=>new Vf,je(1)),Uf=new TextEncoder,Wf=new TextDecoder,Gf=new TextDecoder(`utf-8`,{fatal:!0}),Kf=2**32;function qf(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Jf(e,t,n){if(t<0||t>=Kf)throw RangeError(`value must be >= 0 and <= ${Kf-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function Yf(e){let t=Math.floor(e/Kf),n=e%Kf,r=new Uint8Array(8);return Jf(r,t,0),Jf(r,n,4),r}function Xf(e){let t=new Uint8Array(4);return Jf(t,e),t}var Zf=/[^\x00-\x7f]/;function Qf(e){if(typeof e==`string`&&e.length>=128){if(Zf.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Uf.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function $f(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function ep(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function tp(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var np=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},rp=class extends np{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ip=class extends np{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ap=class extends np{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},op=class extends np{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},sp=class extends np{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},Y=class extends np{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},cp=class extends np{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},lp=class extends np{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},up=class extends np{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},dp=class extends np{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},fp=class extends np{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},pp=class extends np{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},mp=class extends np{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},hp=class extends np{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},gp=`The input to be decoded is not correctly encoded.`;function _p(e){try{return ep(typeof e==`string`?e:Wf.decode(e),!0)}catch(e){throw TypeError(gp,{cause:e})}}function vp(e){return $f(typeof e==`string`?Uf.encode(e):e,!0)}function yp(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function bp(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function xp(e){return bp(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(bp)}function Sp(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Cp(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function wp(e,t,n){try{return _p(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Tp(e,t,n){try{return Qf(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Ep(e,t,n){let r;try{r=JSON.parse(Gf.decode(_p(e)))}catch{throw new t(n)}if(!bp(r))throw new t(n);return r}var Dp={__proto__:null,b64:!0},Op={__proto__:null};function kp(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Ap(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function jp(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new op(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Mp(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new cp(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function Np(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!bp(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var Pp=e=>e[Symbol.toStringTag],Fp=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Ip(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(bp(t)){if(o=Zp(t),typeof o.kty!=`string`)throw Gp(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Fp(e,o,n),o.kty===`oct`)return _p(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Hp(t))throw Gp(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Pp(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Bp(t))return t;if(s=t,s.type===`secret`)return s.export()}Lp||=new WeakMap;let c=t,l=Lp.get(c);if(l?.[r])return l[r];if(l||Lp.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Rp[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await $p(e,o)}var Lp,Rp={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function zp(e){if(!Bp(e))throw Error(`CryptoKey instance expected`)}var Bp=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Vp=e=>e?.[Symbol.toStringTag]===`KeyObject`,Hp=e=>Bp(e)||Vp(e);function Up(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Wp=(e,...t)=>Up(`Key must be `,e,...t);function Gp(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Up(`Key for the ${e} algorithm must be `,t,...r))}var Kp=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function qp(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Jp(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function Yp(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Kp(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Kp(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Kp(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Kp(t.length,`algorithm.length`);qp(e,n)}function Xp(e){return{__proto__:null,...e}}function Zp(e){let t=Xp(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function Qp(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function $p(e,t,n){if(!e.kty.includes(t.kty))throw new op(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function em(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),Yp(e,t,n),e}var tm=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function nm(e,t){let n=e.byteLength<<3;if(n!==t)throw new Y(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var rm=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function im(e,t){if(t.length<<3!==e.ivBits)throw new Y(`Invalid Initialization Vector length`)}async function am(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Wp(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function om(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function sm(e,t,n,r,i){let[a,o,s]=await am(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await om(o,qf(i,r,c,Yf(i.length*8)),s),iv:r}}async function cm(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function lm(e,t,n,r,i,a){let[o,s,c]=await am(e,t,`decrypt`),l=await om(s,qf(a,r,n,Yf(a.length*8)),c);try{if(await cm(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new sp}async function um(e,t,n,r,i){if(!Bp(n)&&!(n instanceof Uint8Array))throw TypeError(Wp(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?im(e,r):r=rm(e),n instanceof Uint8Array&&nm(n,e.cekBits),e.cbc)return sm(e,t,n,r,i);let a=await em(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function dm(e,t,n,r,i,a){if(!Bp(t)&&!(t instanceof Uint8Array))throw TypeError(Wp(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new Y(`JWE Initialization Vector missing`);if(!i)throw new Y(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new Y(`Invalid Authentication Tag length`);if(im(e,r),t instanceof Uint8Array&&nm(t,e.cekBits),e.cbc)return lm(e,t,n,r,i,a);let o=await em(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,qf(n,i)))}catch{throw new sp}}function fm(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var pm=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],mm=[[],[`deriveBits`]],hm=[[],[]];function gm(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:pm,ops:[`wrapKey`,`unwrapKey`]}}function _m(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new op(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:mm,ops:[void 0,`deriveBits`]}}function vm(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:hm,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function ym(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:hm,ops:[`deriveBits`,`deriveBits`]}}var bm=fm({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:hm,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":gm(1),"RSA-OAEP-256":gm(256),"RSA-OAEP-384":gm(384),"RSA-OAEP-512":gm(512),"ECDH-ES":_m(`direct-key-agreement`),"ECDH-ES+A128KW":_m(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":_m(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":_m(`key-agreement-with-key-wrapping`),A128KW:vm(128),A192KW:vm(192),A256KW:vm(256),A128GCMKW:vm(128,!0),A192GCMKW:vm(192,!0),A256GCMKW:vm(256,!0),"PBES2-HS256+A128KW":ym(),"PBES2-HS384+A192KW":ym(),"PBES2-HS512+A256KW":ym()}),xm=[`encrypt`,`decrypt`];function Sm(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:hm,ops:xm,cekBits:e,ivBits:t?128:96,cbc:t}}var Cm=fm({A128GCM:Sm(128),A192GCM:Sm(192),A256GCM:Sm(256),"A128CBC-HS256":Sm(256,!0),"A192CBC-HS384":Sm(384,!0),"A256CBC-HS512":Sm(512,!0)});function wm(e,t){throw new op(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function Tm(e){return(typeof e==`string`?bm[e]:void 0)??wm(`alg`,`Algorithm`)}function Em(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function Dm(e){return(typeof e==`string`?Cm[e]:void 0)??wm(`enc`,`Encryption Algorithm`)}function Om(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);qp(e,t)}async function km(e,t,n){let r=await em(t,Tm(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Am(e,t,n){let r=await em(t,Tm(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function jm(e,t,n){Yp(t,Tm(e).subtle,n),Jp(e,t)}async function Mm(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new Y(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new Y(`PBES2 Count Input must be a positive integer`);let i=qf(Qf(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await em(r,Tm(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function Nm(e){return qf(Xf(e.length),e)}async function Pm(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await tp(`sha256`,qf(Xf(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Fm(e,t,n,r,i=new Uint8Array,a=new Uint8Array){Om(e),Om(t,`deriveBits`);let o=qf(Nm(Qf(n)),Nm(i),Nm(a),Xf(r));return Pm(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function Im(e){zp(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new op(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Lm(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new Y(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return wp(n,t,Y)}}function Rm(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new Y(`JOSE Header "apu" and "apv" values must be distinct`)}}function zm(e){if(e===void 0)throw new Y(`JWE Encrypted Key missing`)}function Bm(e){if(e!==void 0)throw new Y(`Encountered unexpected JWE Encrypted Key`)}function Vm(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function Hm(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return Bm(r),n;let c=s===`direct-key-agreement`;switch(c?Bm(r):zm(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!bp(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new Y(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);Im(n);let a=await $p(e,r),s=Lm(i,`apu`),l=Lm(i,`apv`);Rm(s,l);let u=await Fm(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return zp(n),jm(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new Y(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);Vm(a);let e=a??1e4;if(i.p2c>e)throw new Y(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new Y(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await Mm(wp(i.p2s,`p2s`,Y),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new Y(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new Y(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=wp(i.iv,`iv`,Y),t=wp(i.tag,`tag`,Y);if(e.byteLength!==12)throw new Y(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new Y(`Invalid Authentication Tag length`);return dm(Dm(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return Am(o.slice(-6),n,r)}async function Um(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=Em(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await Ip(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??tm(t):void 0;u&&nm(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{Im(l);let{apu:n,apv:i}=a;n!==void 0&&yp(n,`"apu"`),i!==void 0&&yp(i,`"apv"`);let c=n??Lm(r,`apu`),u=i??Lm(r,`apv`);Rm(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await Ip(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await Fm(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=vp(n)),i!==void 0&&(f.apv=vp(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:zp(l),jm(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=a;l=await Mm(t,o,e,l),f={p2c:e,p2s:vp(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await um(Dm(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:vp(t.iv),tag:vp(t.tag)}}}if(d??=await km(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function Wm(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new op(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new Y(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function Gm(e){if(typeof globalThis[e]>`u`)throw new op(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Km(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new Y(`Decompressed plaintext exceeded the configured limit`)}return qf(...i)}async function qm(e){return Gm(`CompressionStream`),Km(new CompressionStream(`deflate-raw`),e)}async function Jm(e,t){return Gm(`DecompressionStream`),Km(new DecompressionStream(`deflate-raw`),e,t)}function Ym(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=Ep(t,Y,`JWE Protected Header is invalid`)),[o,wp(n,`ciphertext`,Y),r===void 0?void 0:wp(r,`iv`,Y),i===void 0?void 0:wp(i,`tag`,Y),Tp((t??``)+(a===void 0?``:`.${a}`),`aad`,Y)]}function Xm(e){return[e&&kp(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&kp(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function Zm(e,t,n,r=Ym(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!Sp(i,l,u))throw new Y(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;jp(Y,Op,h,i,f),Wm(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new Y(`missing JWE Algorithm (alg) in JWE Header`);let x=bm[y];if(v===``&&(!x||!Em(x)))throw new Y(`JWE Encrypted Key incorrect type`);let ee=x?.mode===`integrated-encryption`;if(!ee&&(typeof b!=`string`||!b))throw new Y(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new ap(`"alg" (Algorithm) Header Parameter value not allowed`);let te;if(ee){if(b!==void 0)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new Y(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new Y(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new ap(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);te=Dm(b)}let S;if(v!==void 0)try{S=wp(v,`encrypted_key`,Y)}catch(e){if(!x||!Em(x))throw e;S=new Uint8Array}let C=!1;typeof n==`function`&&(n=await n(i,e),C=!0);let w=x??Tm(y);Em(w)&&S===void 0&&(S=new Uint8Array);let ne=await Ip(w.mode===`direct-encryption`?te:w,n,`decrypt`),T;if(w.mode===`integrated-encryption`)T=await w.decrypt(ne,S,a,c,i,f);else{let e=te,t;try{t=await Hm(w,e,ne,S,f,g),Em(w)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=tm(e))}catch(n){if(n instanceof TypeError||n instanceof Y||n instanceof op)throw n;t=tm(e)}T=await dm(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new op(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);T=await Jm(T,e).catch(e=>{throw e instanceof Y?e:new Y(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:wp(d,`aad`,Y)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...C&&{key:ne}}}async function Qm(e,t,n){if(e instanceof Uint8Array&&(e=Wf.decode(e)),typeof e!=`string`)throw new Y(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new Y(`Invalid Compact JWE`);return Zm({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function $m(e,t,n){if(!Sp(e,t,n))throw new Y(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function eh(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new Y(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&yp(o,`JWE Additional Authenticated Data`),s!==void 0&&yp(s,`JWE Content Encryption Key`),c!==void 0&&yp(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=Np(Y,r)[0],e[1]=r),i!==void 0&&(i=Np(Y,i)[0],e[2]=i),!n&&a!==void 0&&(a=Np(Y,a)[0],e[3]=a),l!==void 0&&!bp(l))throw TypeError(`JWE Key Management Parameters must be an object`);$m(r,i,a);let d={...r,...i,...a};Ap(Y,r),jp(Y,Op,u,r,d),Wm(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new Y(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=bm[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new Y(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,Dm(p),m]}async function th(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??Tm(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await Ip(_,n,`encrypt`):[b,v,y]=await Um(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,$m(h,g,l));let x=h?vp(JSON.stringify(h)):``,ee=u?.byteLength?vp(u):void 0,te=Qf(ee?`${x}.${ee}`:x),S=o;r.zip===`DEF`&&(S=await qm(S).catch(e=>{throw new Y(`Failed to compress plaintext`,{cause:e})}));let C,w,ne;_.mode===`integrated-encryption`?[v,C]=await _.encrypt(b,S,te,h,r,p):{ciphertext:C,tag:w,iv:ne}=await um(i,S,b,f,te);let T={ciphertext:vp(C)};return ne&&(T.iv=vp(ne)),w&&(T.tag=vp(w)),v?.byteLength&&(T.encrypted_key=vp(v)),ee&&(T.aad=ee),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function nh(e,t,n){return th(e,eh(e,n),t)}function rh(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var ih=[[`verify`],[`sign`]];function ah(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:ih}}function oh(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:ih,minRsaBits:2048}}function sh(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:ih}}function ch(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:ih}}function lh(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:ih}}var uh=fm({HS256:ah(256),HS384:ah(384),HS512:ah(512),RS256:oh(256),RS384:oh(384),RS512:oh(512),PS256:oh(256,32),PS384:oh(384,48),PS512:oh(512,64),ES256:sh(`P-256`,256),ES384:sh(`P-384`,384),ES512:sh(`P-521`,512),EdDSA:ch(),Ed25519:ch(),"ML-DSA-44":lh(44),"ML-DSA-65":lh(65),"ML-DSA-87":lh(87)});function dh(e){let t=typeof e==`string`?uh[e]:void 0;if(!t)throw new op(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function fh(e){return[e&&kp(`algorithms`,e.algorithms),e?.crit]}function ph(e){return e===void 0?{}:Ep(e,cp,`JWS Protected Header is invalid`)}function mh(e){try{return Qf(e)}catch{throw new cp(`JWS Compact Serialization payload must use only ASCII characters`)}}async function hh(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??ph(a);if(!Sp(c,o))throw new cp(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Mp(c,jp(cp,Dp,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new cp(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new ap(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new cp(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new cp(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=dh(d),h=qf(a===void 0?new Uint8Array:Qf(a),Qf(`.`),typeof f==`string`?t[2]??=Tp(f,`payload`,cp):f),g=wp(e.signature,`signature`,cp),_=await Ip(m,n,`verify`),v=await em(_,m.subtle,`verify`);m.minRsaBits&&Jp(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new hp;let b={payload:typeof f==`string`?wp(f,`payload`,cp):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function gh(e,t,n){if(e instanceof Uint8Array&&(e=Wf.decode(e)),typeof e!=`string`)throw new cp(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new cp(`Invalid Compact JWS`);return hh({payload:i,protected:r,signature:a},t,n,mh)}var _h=e=>Math.floor(e.getTime()/1e3),vh={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},yh=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,bh=`check_failed`;function xh(){throw TypeError(`Invalid time period format`)}function Sh(e){typeof e!=`string`&&xh();let t=yh.exec(e);(!t||t[4]&&t[1])&&xh();let n=parseFloat(t[2]),r=Math.round(n*vh[t[3][0].toLowerCase()]);return Number.isFinite(r)||xh(),t[1]===`-`||t[4]===`ago`?-r:r}function Ch(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function wh(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Th(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Eh(e,t){return typeof e==`number`?Ch(t,e):e instanceof Date?Ch(t,_h(e)):_h(new Date)+Sh(e)}var Dh=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Oh=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function kh(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new rp(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Ah(e,t){throw new rp(`unexpected "${t}" claim value`,e,t,bh)}function jh(e,t,n={}){let r;try{r=JSON.parse(Gf.decode(t))}catch{}if(!bp(r))throw new lp(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||Dh(e.typ)!==Dh(i)))throw new rp(`unexpected "typ" JWT header value`,r,`typ`,bh);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new rp(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Ah(r,`iss`),s!==void 0&&r.sub!==s&&Ah(r,`sub`),c!==void 0&&!Oh(r.aud,typeof c==`string`?[c]:c)&&Ah(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Sh(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Ch(`clockTolerance option`,f);let{currentDate:p}=n,m=Ch(`currentDate option`,_h(p===void 0?new Date:p)),h=kh(r,`iat`,l!==void 0),g=kh(r,`nbf`);if(g!==void 0&&g>m+f)throw new rp(`"nbf" claim timestamp check failed`,r,`nbf`,bh);let _=kh(r,`exp`);if(_!==void 0&&_<=m-f)throw new ip(`"exp" claim timestamp check failed`,r,`exp`,bh);if(l!==void 0){let e=m-h,t=Ch(`maxTokenAge option`,typeof l==`number`?l:Sh(l));if(e-f>t)throw new ip(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,bh);if(e<-f)throw new rp(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,bh)}return r}var Mh;function Nh(e){return Mh.get(e)}function Ph(e){let t=Nh(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return Uf.encode(JSON.stringify(t))}function Fh(e,t){return Nh(e)[t]}var Ih=class{constructor(e={}){if(!bp(e))throw TypeError(`JWT Claims Set MUST be an object`);(Mh||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return wh(`iss`,e),Nh(this).iss=e,this}setSubject(e){return wh(`sub`,e),Nh(this).sub=e,this}setAudience(e){return Th(e),Nh(this).aud=e,this}setJti(e){return wh(`jti`,e),Nh(this).jti=e,this}setNotBefore(e){return Nh(this).nbf=Eh(e,`setNotBefore`),this}setExpirationTime(e){return Nh(this).exp=Eh(e,`setExpirationTime`),this}setIssuedAt(e){let t=Nh(this);return t.iat=e===void 0?_h(new Date):typeof e==`string`?Ch(`setIssuedAt`,_h(new Date)+Sh(e)):Eh(e,`setIssuedAt`),this}};async function Lh(e,t,n){let[r,i]=await gh(e,fh(n),t);if(!i)throw new lp(`JWTs MUST NOT use unencoded payload`);let a=jh(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function Rh(e,t,n){let{plaintext:r,...i}=await Qm(e,Xm(n),t),{protectedHeader:a}=i,o=jh(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new rp(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function zh(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=Np(cp,i);i=e[0],s=vp(e[1])}if(a!==void 0&&(a=Np(cp,a)[0]),!i&&!a)throw new cp(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Sp(i,a))throw new cp(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Ap(cp,i);let l=Mp(i,jp(cp,Dp,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new cp(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=dh(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=vp(r),p=t[1]??=Qf(f)):(f=vp(r),m=Uf.encode(`${s}.${f}`))}m??=qf(Qf(s),Qf(`.`),p);let h=await em(await Ip(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&Jp(d.alg,h);let g={signature:vp(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Bh(e,t,n,r,i){let[a]=await zh([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Vh=Ih,Hh=class extends Vh{#e;setProtectedHeader(e){return Cp(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Bh(Ph(this),this.#e,t?.crit,e,()=>{throw new lp(`JWTs MUST NOT use unencoded payload`)})}},Uh=Ih,Wh=class extends Uh{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return Cp(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return Cp(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return Cp(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return Cp(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=Ph(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?Fh(this,`iss`):void 0,sub:this.#n?Fh(this,`sub`):void 0,aud:this.#r?Fh(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,rh(await nh(r,e,t))}},Gh=`"alg" (Algorithm)`;function Kh(e=`JWK "alg" (Algorithm) Parameter`){throw new op(`Invalid or unsupported ${e} value`)}function qh(e,t){return(typeof e==`string`?uh[e]??bm[e]:void 0)??Kh(t)}async function Jh(e){if(Vp(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:vp(e)};if(!Bp(e))throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var Yh=(e,t)=>{if(typeof e!=`string`||!e)throw new up(`${t} missing or invalid`)};async function Xh(e,t){let n;if(bp(e)){if(n=Xp(e),typeof n.kty!=`string`)throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Hp(e))n=Xp(await Jh(e));else throw TypeError(Wp(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:Yh(n.alg,`"alg" (Algorithm) Parameter`),Yh(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:Yh(n.crv,`"crv" (Curve) Parameter`),Yh(n.x,`"x" (X Coordinate) Parameter`),Yh(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:Yh(n.crv,`"crv" (Subtype of Key Pair) Parameter`),Yh(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:Yh(n.e,`"e" (Exponent) Parameter`),Yh(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new up(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new op(`"kty" (Key Type) Parameter missing or unsupported`)}let i=Qf(JSON.stringify(r));return vp(await tp(t,i))}function Zh(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function Qh(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=$p(n,t,!0).then(e=>{if(e.type!==`public`)throw new dp(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function $h(e){let t;try{t=structuredClone(e)}catch{}if(!xp(t))throw new dp(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=Xp(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?uh[a]:void 0;if(!s||s.secret)throw new op(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Zh(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new fp;if(u!==1){let e=new pp;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Qh(r,e,s)}catch{}},e}return Qh(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function eg(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var tg;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(tg=`jose/v6.2.12`);var ng=Symbol();async function rg(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new mp:e});if(i.status!==200)throw new np(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new np(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var ig=Symbol();function ag(e,t){return Number.isFinite(e)&&Date.now()<e+t}function og(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function sg(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=og(r.cooldownDuration,3e4,`cooldownDuration`),s=og(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);tg&&!c.has(`User-Agent`)&&c.set(`User-Agent`,tg),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[ng],u=r[ig],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;ag(e,s)&&xp(t)&&(d=e,h=$h(t))}let g=async()=>{if(f&&eg()&&(f=void 0),!f){let e=++p,t=f=rg(n,c,AbortSignal.timeout(a),l).then(t=>{let n=$h(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!ag(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof fp&&!ag(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>ag(d,o),enumerable:!0},fresh:{get:()=>ag(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function cg(e,t,n){if(!bp(e))throw TypeError(`JWK must be an object`);let r=Zp(e),i=Qp(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return _p(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return $p(qh(t),r,i);case`RSA`:case`EC`:case`OKP`:return $p(qh(t),r,i);default:throw new op(`Unsupported "kty" (Key Type) Parameter value`)}}function lg(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return Ep(t,TypeError,n)}function ug(e){if(typeof e!=`string`)throw new lp(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new lp(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new lp(`Invalid JWT`);if(!t)throw new lp(`JWTs must contain a payload`);let r;try{r=_p(t)}catch{throw new lp(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Gf.decode(r))}catch{throw new lp(`Failed to parse the decoded payload as JSON`)}if(!bp(i))throw new lp(`Invalid JWT Claims Set`);return i}function dg(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new op(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function fg(e,t){let n=Qp(t?.extractable),r=qh(e,Gh);r.secret&&Kh(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new op(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new op(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:dg(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function pg(e,t,n=3600){return await new Hh(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function mg(e,t){try{return(await Lh(e,new TextEncoder().encode(t))).payload}catch{return null}}var hg=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),gg=()=>Date.now()/1e3|0,_g=`dir`,vg=`A256CBC-HS512`;function yg(e,t){return Af(Hf,new TextEncoder().encode(e),new TextEncoder().encode(t),hg,64)}function bg(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function xg(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function Sg(e,t,n,r=3600){let i=yg(bg(t),n),a=await Xh({kty:`oct`,k:vp(i)},`sha256`);return await new Wh(e).setProtectedHeader({alg:_g,enc:vg,kid:a}).setIssuedAt().setExpirationTime(gg()+r).setJti(crypto.randomUUID()).encrypt(i)}var Cg={clockTolerance:15,keyManagementAlgorithms:[_g],contentEncryptionAlgorithms:[vg,`A256GCM`]};async function wg(e,t,n){if(!e)return null;let r=!1;try{r=lg(e).kid!==void 0}catch{return null}try{let r=xg(t),{payload:i}=await Rh(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=yg(e.value,n);if(t===await Xh({kty:`oct`,k:vp(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,yg(r[0].value,n)},Cg);return i}catch{if(r)return null;let i=xg(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Rh(e,yg(r.value,n),Cg);return a}catch{continue}return null}}var Tg={N:16384,r:16,p:1,dkLen:64};function Eg(e,t){return new Promise((n,r)=>{Tt(e.normalize(`NFKC`),t,Tg.dkLen,{N:Tg.N,r:Tg.r,p:Tg.p,maxmem:128*Tg.N*Tg.r*2},(e,t)=>{e?r(e):n(t)})})}async function Dg(e){let t=wt(16).toString(`hex`);return`${t}:${(await Eg(e,t)).toString(`hex`)}`}async function Og(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await Eg(t,n)).toString(`hex`)===r}var kg=Dg,Ag=async({hash:e,password:t})=>Og(e,t),jg=ke(`a-z`,`0-9`,`A-Z`,`-_`);function Mg(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function Ng(e,t){return{digest:async n=>{let r=Ee(n),i=await Mg().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?Ie.encode(i,{padding:t!==`base64urlnopad`}):Pe.encode(i):i}}}function Pg(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var Fg=e=>e?`"${e}" `:``;function Ig(e,t=``){if(typeof e!=`boolean`)throw TypeError(Fg(t)+`expected boolean, got type=`+typeof e);return e}function Lg(e,t=``){if(typeof e!=`number`)throw TypeError(Fg(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Fg(t)+`expected integer >= 0, got `+e);return e}function Rg(e,t,n=``){if(Pg(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Lg(t,`length`);let r=Pg(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=Fg(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var zg=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function Bg(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Vg(e,t){Rg(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Hg(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ug(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Wg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Gg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Kg(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function qg(e){for(let t=0;t<e.length;t++)e[t]=Kg(e[t]);return e}var Jg=Gg?e=>e:qg,Yg=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,Xg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Zg(e){if(Rg(e),Yg)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=Xg[e[n]];return t}function Qg(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function $g(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(Yg)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=Qg(e.charCodeAt(i)),a=Qg(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function e_(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function t_(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function n_(e,t){if(t_(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function r_(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];Rg(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function i_(e,t){return zg(e,`defaults`),zg(t,`opts`),Object.assign(e,t)}function a_(e,t){if(e=Rg(e),t=Rg(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function o_(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var s_=(e,t)=>{function n(n,...r){if(Rg(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];Rg(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Pg(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&Rg(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);Rg(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,Rg(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(Rg(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function c_(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Rg(t,e,`output`),n&&!u_(t))throw Error(`invalid output, must be aligned`);return t}function l_(e,t,n){Lg(e),Lg(t),Ig(n);let r=new Uint8Array(16),i=Wg(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function u_(e){return e.byteOffset%4==0}function d_(e){return Uint8Array.from(Rg(e))}function f_(e=32){Lg(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function p_(e,t=f_){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;Lg(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=r_(e,t);return t_(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){Rg(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){Rg(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}var m_=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),h_=Jg(Hg(m_(`expand 16-byte k`))),g_=Jg(Hg(m_(`expand 32-byte k`)));function __(e,t){return e<<t|e>>>32-t}var v_=64,y_=16,b_=2**32-1,x_=Uint32Array.of();function S_(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(v_),u=Hg(l),d=Gg&&u_(i)&&u_(a),f=d?Hg(i):x_,p=d?Hg(a):x_;if(Gg)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=b_)throw Error(`arx: counter overflow`);let h=Math.min(v_,c-m);if(d&&h===v_){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<y_;t++)n=e+t,p[n]=f[n]^u[t];m+=v_}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),Jg(u),o>=b_)throw Error(`arx: counter overflow`);let f=Math.min(v_,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function C_(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=i_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return Lg(i),Lg(o),Ig(a),Ig(n),(t,s,c,l,u=0)=>{Rg(t,void 0,`key`),Rg(s,void 0,`nonce`),Rg(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=c_(d,l,!1),f&&n_(c,l),Lg(u),u<0||u>=b_)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=d_(t)),g=g_;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=h_,p.push(h);else throw Rg(t,32,`arx key`),Error(`invalid key size`);(!Gg||!u_(s))&&p.push(s=d_(s));let _=Hg(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(Gg)r(g,_,Hg(e),_);else{let t=Jg(Uint32Array.from(g));r(t,_,Hg(e),_),Ug(t),Jg(_)}s=s.subarray(16)}else Gg||Jg(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=Jg(Hg(s));try{return S_(e,g,_,y,c,l,u,o),l}finally{Ug(...p)}}}function w_(e,t){return e[t++]&255|(e[t++]&255)<<8}var T_=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=d_(Rg(e,32,`key`));let t=w_(e,0),n=w_(e,2),r=w_(e,4),i=w_(e,6),a=w_(e,8),o=w_(e,10),s=w_(e,12),c=w_(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=w_(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=w_(e,t+0),_=w_(e,t+2),v=w_(e,t+4),y=w_(e,t+6),b=w_(e,t+8),x=w_(e,t+10),ee=w_(e,t+12),te=w_(e,t+14),S=i[0]+(g&8191),C=i[1]+((g>>>13|_<<3)&8191),w=i[2]+((_>>>10|v<<6)&8191),ne=i[3]+((v>>>7|y<<9)&8191),T=i[4]+((y>>>4|b<<12)&8191),re=i[5]+(b>>>1&8191),ie=i[6]+((b>>>14|x<<2)&8191),E=i[7]+((x>>>11|ee<<5)&8191),ae=i[8]+((ee>>>8|te<<8)&8191),oe=i[9]+(te>>>5|r),D=0,se=D+S*o+5*h*C+5*m*w+5*p*ne+5*f*T;D=se>>>13,se&=8191,se+=5*d*re+5*u*ie+5*l*E+5*c*ae+5*s*oe,D+=se>>>13,se&=8191;let ce=D+S*s+C*o+5*h*w+5*m*ne+5*p*T;D=ce>>>13,ce&=8191,ce+=5*f*re+5*d*ie+5*u*E+5*l*ae+5*c*oe,D+=ce>>>13,ce&=8191;let O=D+S*c+C*s+w*o+5*h*ne+5*m*T;D=O>>>13,O&=8191,O+=5*p*re+5*f*ie+5*d*E+5*u*ae+5*l*oe,D+=O>>>13,O&=8191;let le=D+S*l+C*c+w*s+ne*o+5*h*T;D=le>>>13,le&=8191,le+=5*m*re+5*p*ie+5*f*E+5*d*ae+5*u*oe,D+=le>>>13,le&=8191;let ue=D+S*u+C*l+w*c+ne*s+T*o;D=ue>>>13,ue&=8191,ue+=5*h*re+5*m*ie+5*p*E+5*f*ae+5*d*oe,D+=ue>>>13,ue&=8191;let de=D+S*d+C*u+w*l+ne*c+T*s;D=de>>>13,de&=8191,de+=re*o+5*h*ie+5*m*E+5*p*ae+5*f*oe,D+=de>>>13,de&=8191;let k=D+S*f+C*d+w*u+ne*l+T*c;D=k>>>13,k&=8191,k+=re*s+ie*o+5*h*E+5*m*ae+5*p*oe,D+=k>>>13,k&=8191;let fe=D+S*p+C*f+w*d+ne*u+T*l;D=fe>>>13,fe&=8191,fe+=re*c+ie*s+E*o+5*h*ae+5*m*oe,D+=fe>>>13,fe&=8191;let pe=D+S*m+C*p+w*f+ne*d+T*u;D=pe>>>13,pe&=8191,pe+=re*l+ie*c+E*s+ae*o+5*h*oe,D+=pe>>>13,pe&=8191;let me=D+S*h+C*m+w*p+ne*f+T*d;D=me>>>13,me&=8191,me+=re*u+ie*l+E*c+ae*s+oe*o,D+=me>>>13,me&=8191,D=(D<<2)+D|0,D=D+se|0,se=D&8191,D>>>=13,ce+=D,i[0]=se,i[1]=ce,i[2]=O,i[3]=le,i[4]=ue,i[5]=de,i[6]=k,i[7]=fe,i[8]=pe,i[9]=me}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;Ug(n)}update(e){Bg(this),Rg(e),e=d_(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ug(this.h,this.r,this.buffer,this.pad)}digestInto(e){Bg(this),Vg(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},E_=o_(32,e=>new T_(e));function D_(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],ee=o,te=s,S=c,C=l,w=u,ne=d,T=f,re=p,ie=m,E=h,ae=g,oe=_,D=v,se=y,ce=b,O=x;for(let e=0;e<a;e+=2)ee=ee+w|0,D=__(D^ee,16),ie=ie+D|0,w=__(w^ie,12),ee=ee+w|0,D=__(D^ee,8),ie=ie+D|0,w=__(w^ie,7),te=te+ne|0,se=__(se^te,16),E=E+se|0,ne=__(ne^E,12),te=te+ne|0,se=__(se^te,8),E=E+se|0,ne=__(ne^E,7),S=S+T|0,ce=__(ce^S,16),ae=ae+ce|0,T=__(T^ae,12),S=S+T|0,ce=__(ce^S,8),ae=ae+ce|0,T=__(T^ae,7),C=C+re|0,O=__(O^C,16),oe=oe+O|0,re=__(re^oe,12),C=C+re|0,O=__(O^C,8),oe=oe+O|0,re=__(re^oe,7),ee=ee+ne|0,O=__(O^ee,16),ae=ae+O|0,ne=__(ne^ae,12),ee=ee+ne|0,O=__(O^ee,8),ae=ae+O|0,ne=__(ne^ae,7),te=te+T|0,D=__(D^te,16),oe=oe+D|0,T=__(T^oe,12),te=te+T|0,D=__(D^te,8),oe=oe+D|0,T=__(T^oe,7),S=S+re|0,se=__(se^S,16),ie=ie+se|0,re=__(re^ie,12),S=S+re|0,se=__(se^S,8),ie=ie+se|0,re=__(re^ie,7),C=C+w|0,ce=__(ce^C,16),E=E+ce|0,w=__(w^E,12),C=C+w|0,ce=__(ce^C,8),E=E+ce|0,w=__(w^E,7);let le=0;r[le++]=o+ee|0,r[le++]=s+te|0,r[le++]=c+S|0,r[le++]=l+C|0,r[le++]=u+w|0,r[le++]=d+ne|0,r[le++]=f+T|0,r[le++]=p+re|0,r[le++]=m+ie|0,r[le++]=h+E|0,r[le++]=g+ae|0,r[le++]=_+oe|0,r[le++]=v+D|0,r[le++]=y+se|0,r[le++]=b+ce|0,r[le++]=x+O|0}function O_(e,t,n,r){let i=Gg?e:Jg(e.slice(0,4)),a=Gg?t:Jg(t.slice(0,8)),o=Gg?n:Jg(n.slice(0,4)),s=new Uint32Array(16);D_(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,Jg(r),Gg||Ug(i,a,o),Ug(s)}var k_=C_(D_,{counterRight:!1,counterLength:8,extendNonceFn:O_,allowShortKeys:!1}),A_=new Uint8Array(16),j_=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(A_.subarray(n))},M_=new Uint8Array(32);function N_(e,t,n,r,i){i!==void 0&&Rg(i,void 0,`AAD`);let a=e(t,n,M_),o=l_(r.length,i?i.length:0,!0),s=E_.create(a);i&&j_(s,i),j_(s,r),s.update(o);let c=s.digest();return Ug(a,o),c}var P_=s_({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=c_(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=N_(e,t,n,s,r);return a.set(c,o),Ug(c),a},decrypt(i,a){a=c_(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=N_(e,t,n,o,r);if(!a_(s,c))throw Ug(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Ug(c),a}}))(k_)),F_=`$ba$`;function I_(e){if(!e.startsWith(F_))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function L_(e,t){return`${F_}${e}$${t}`}async function R_(e,t){let n=await Ng(`SHA-256`).digest(e),r=e_(t);return Zg(p_(P_)(new Uint8Array(n)).encrypt(r))}async function z_(e,t){let n=await Ng(`SHA-256`).digest(e),r=$g(t),i=p_(P_)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var B_=async({key:e,data:t})=>{if(typeof e==`string`)return R_(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await R_(n,t);return L_(e.currentVersion,r)},V_=async({key:e,data:t})=>{if(typeof e==`string`)return z_(e,t);let n=I_(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return z_(t,n.ciphertext)}if(e.legacySecret)return z_(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)};function H_(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}var U_={name:`HMAC`,hash:`SHA-256`},W_=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await H_().importKey(`raw`,t,U_,!1,[`sign`,`verify`])},G_=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await H_().verify(U_,n,i,new TextEncoder().encode(t))}catch{return!1}},K_=async(e,t)=>{let n=await W_(t),r=await H_().sign(U_.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},q_=async(e,t)=>{let n=await K_(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},J_=/^application\/([a-z0-9.+-]*\+)?json/i;async function Y_(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new Ze(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new Ze(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(J_.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new Ze(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function X_(e){return e instanceof Ze||e?.name===`APIError`}function Z_(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function Q_(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function $_(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var ev={secure:`__Secure-`,host:`__Host-`},tv=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return ev[t]+e};function nv(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,Z_(n))}n=i+1}return t}function rv(e,t,n={}){let r=tv(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function iv({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}var av=(e,t,n)=>(t=encodeURIComponent(t),iv(rv(e,t,n))),ov=async(e,t,n,r)=>(t=await q_(t,n),iv(rv(e,t,r)));async function sv(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:cv(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:cv(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function cv(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var lv=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await sv(t,e);if(o)throw new Xe(o.message,o.issues);let s=e.headers===void 0?`request`in e&&$_(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?nv(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=tv(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=tv(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await G_(s,o,await W_(t))?o:!1},setCookie:(e,t,n)=>{let i=av(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await ov(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new Ze(`FOUND`,void 0,r)),error:(e,t,n)=>new Ze(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function uv(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function dv(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function fv(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var pv=new Set(`host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function mv(e){for(let t of pv)e.delete(t)}function hv(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function gv(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);mv(n),hv(e.headers,n)}return e}if(fv(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(hv(i,r?.headers),hv(i,e.headers),t?.headers){let e=new Headers(t.headers);mv(e),hv(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(X_(e))return gv(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return mv(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):uv(e)&&(n=dv(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function _v(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new xe(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new xe(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await Q_(lv(t,{options:i,path:r}));if(o)throw o instanceof Xe?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new Ze(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(X_(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?gv(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function vv(e,t){return[...e??[],...t??[]]}_v.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return _v(n,{...r,use:vv(r.use,e?.use)},i)}let[n,r]=t;return _v({...n,use:vv(n.use,e?.use)},r)}return t};function yv(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await lv(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw X_(e)&&Object.defineProperty(e,Ne,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}yv.create=e=>{function t(t,n){if(typeof t==`function`)return yv({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return yv({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var bv={};function xv(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function Sv(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof pe&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof pe&&t.push({name:e,in:`query`,schema:{type:xv(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function Cv(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof pe||e.body instanceof re)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof pe&&(n[e]={type:xv(t),description:t.description},t instanceof re||r.push(e))}),{required:e.body instanceof re?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function wv(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function Tv(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(bv[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Sv(n),responses:wv(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=Cv(n);bv[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Sv(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:wv(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:bv}}var Ev=(e,t)=>`<!doctype html>
21
21
  <html>
22
22
  <head>
23
23
  <title>Scalar API Reference</title>