authhero 4.61.0 → 4.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/authhero.cjs CHANGED
@@ -64,7 +64,7 @@
64
64
 
65
65
  </html>`;return e.html(s,{headers:i})}const hl=["openid","profile","email","address","phone"];async function x9(e,t,n,r){const i=[];if(!(await e.env.data.tenants.get(t))?.flags?.inherit_global_permissions_in_organizations)return[];const a=await e.env.data.userRoles.list(t,n,void 0,"");for(const c of a)(await e.env.data.rolePermissions.list(t,c.id,{per_page:1e3})).forEach(u=>{u.resource_server_identifier===r&&i.push(u.permission_name)});return[...new Set(i)]}async function z9(e,t){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=t,a=s.filter(v=>hl.includes(v)),c=s.filter(v=>!hl.includes(v)),u=(await e.env.data.resourceServers.list(n)).resource_servers.filter(v=>v.identifier===i);if(u.length===0)return{scopes:a,permissions:[]};const d=u[0];if(!d)return{scopes:a,permissions:[]};const f=d.options?.enforce_policies===!0,p=d.options?.token_dialect||"access_token",_=(await e.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find(v=>v.audience===i);if(!_)return{scopes:a,permissions:[]};const g=_.scope||[],y=(d.scopes||[]).map(v=>v.value);if(c.length>0){const v=c.filter(x=>!g.includes(x));if(v.length>0)throw new X(403,{error:"access_denied",error_description:`Client is not authorized for scope(s): ${v.join(", ")}`})}const m=g.filter(v=>y.includes(v)),w=c.length===0?m:c.filter(v=>m.includes(v));if(!f)return{scopes:[...new Set([...a,...w])],permissions:[]};const k=w;return p==="access_token_authz"?{scopes:[...new Set([...a,...w])],permissions:k}:{scopes:[...new Set([...a,...w])],permissions:[]}}async function ia(e,t){if(t.grantType===an.ClientCredential)return await z9(e,{tenantId:t.tenantId,clientId:t.clientId,audience:t.audience,requestedScopes:t.requestedScopes});const{tenantId:n,userId:r,audience:i,requestedScopes:s,organizationId:a}=t;let c=!1;if(a){if((await e.env.data.tenants.get(n))?.flags?.inherit_global_permissions_in_organizations){const R=await e.env.data.userRoles.list(n,r,void 0,"");for(const B of R)if((await e.env.data.rolePermissions.list(n,B.id,{per_page:1e3})).some(Q=>Q.permission_name==="admin:organizations"&&Q.resource_server_identifier===i)){c=!0;break}}if(!c&&!(await e.env.data.userOrganizations.list(n,{q:`user_id:${r}`,per_page:1e3})).userOrganizations.some(V=>V.organization_id===a))throw new X(403,{error:"access_denied",error_description:"User is not a member of the specified organization"})}const l=s.filter(C=>hl.includes(C)),d=(await e.env.data.resourceServers.list(n)).resource_servers.filter(C=>C.identifier===i);if(d.length===0)return{scopes:s,permissions:[]};const f=d[0];if(!f)return{scopes:s,permissions:[]};const p=(f.scopes||[]).map(C=>C.value),h=f.options?.enforce_policies===!0,_=f.options?.token_dialect||"access_token";if(!h)return{scopes:s,permissions:[]};const g=await e.env.data.userPermissions.list(n,r,void 0,a),y=await e.env.data.userRoles.list(n,r,void 0,""),m=a?await e.env.data.userRoles.list(n,r,void 0,a):[],w=[...y,...m],k=a?await x9(e,n,r,i):[],S=[];for(const C of w)(await e.env.data.rolePermissions.list(n,C.id,{per_page:1e3})).forEach(B=>{B.resource_server_identifier===i&&S.push(B.permission_name)});const v=new Set;g.forEach(C=>{C.resource_server_identifier===i&&v.add(C.permission_name)}),S.forEach(C=>{v.add(C)}),k.forEach(C=>{v.add(C)});const x=Array.from(v),A=x.filter(C=>p.includes(C)),E=s.filter(C=>!p.includes(C)&&!hl.includes(C));if(_==="access_token_authz")return{scopes:[...new Set([...l,...E])],permissions:A};const P=s.filter(C=>p.includes(C)&&x.includes(C));return{scopes:[...new Set([...l,...P,...E])],permissions:[]}}function A9(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function E9(){const e=A9();if(e.__xstate__)return e.__xstate__}const C9=e=>{if(typeof window>"u")return;const t=E9();t&&t.register(e)};class Dm{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const t2=".",I9="",n2="",j9="#",N9="*",r2="xstate.init",T9="xstate.error",yf="xstate.stop";function P9(e,t){return{type:`xstate.after.${e}.${t}`}}function bf(e,t){return{type:`xstate.done.state.${e}`,output:t}}function O9(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function i2(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function o2(e){return{type:r2,input:e}}function wn(e){setTimeout(()=>{throw e})}const R9=typeof Symbol=="function"&&Symbol.observable||"@@observable";function s2(e,t){const n=Um(e),r=Um(t);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(i=>i in r?s2(n[i],r[i]):!1)}function A0(e){if(c2(e))return e;const t=[];let n="";for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n="";continue}n+=e[r]}return t.push(n),t}function Um(e){if(gA(e))return e.value;if(typeof e!="string")return e;const t=A0(e);return L9(t)}function L9(e){if(e.length===1)return e[0];const t={};let n=t;for(let r=0;r<e.length-1;r++)if(r===e.length-2)n[e[r]]=e[r+1];else{const i=n;n={},i[e[r]]=n}return t}function Bm(e,t){const n={},r=Object.keys(e);for(let i=0;i<r.length;i++){const s=r[i];n[s]=t(e[s],s,e,i)}return n}function a2(e){return c2(e)?e:[e]}function gr(e){return e===void 0?[]:a2(e)}function vf(e,t,n,r){return typeof e=="function"?e({context:t,event:n,self:r}):e}function c2(e){return Array.isArray(e)}function D9(e){return e.type.startsWith("xstate.error.actor")}function Ji(e){return a2(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function l2(e){if(!(e===void 0||e===I9))return gr(e)}function wf(e,t,n){const r=typeof e=="object",i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function Mm(e,t){return`${t}.${e}`}function E0(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,r,i]=n,a=e.getStateNodeById(i).config.invoke;return(Array.isArray(a)?a[r]:a).src}function U9(e,t){if(t===e||t===N9)return!0;if(!t.endsWith(".*"))return!1;const n=t.split("."),r=e.split(".");for(let i=0;i<n.length;i++){const s=n[i],a=r[i];if(s==="*")return i===n.length-1;if(s!==a)return!1}return!0}function qm(e,t){return`${e.sessionId}.${t}`}let B9=0;function M9(e,t){const n=new Map,r=new Map,i=new WeakMap,s=new Set,a={},{clock:c,logger:l}=t,u={schedule:(p,h,_,g,y=Math.random().toString(36).slice(2))=>{const m={source:p,target:h,event:_,delay:g,id:y,startedAt:Date.now()},w=qm(p,y);f._snapshot._scheduledEvents[w]=m;const k=c.setTimeout(()=>{delete a[w],delete f._snapshot._scheduledEvents[w],f._relay(p,h,_)},g);a[w]=k},cancel:(p,h)=>{const _=qm(p,h),g=a[_];delete a[_],delete f._snapshot._scheduledEvents[_],g!==void 0&&c.clearTimeout(g)},cancelAll:p=>{for(const h in f._snapshot._scheduledEvents){const _=f._snapshot._scheduledEvents[h];_.source===p&&u.cancel(p,_.id)}}},d=p=>{if(!s.size)return;const h={...p,rootId:e.sessionId};s.forEach(_=>_.next?.(h))},f={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${B9++}`,_register:(p,h)=>(n.set(p,h),p),_unregister:p=>{n.delete(p.sessionId);const h=i.get(p);h!==void 0&&(r.delete(h),i.delete(p))},get:p=>r.get(p),getAll:()=>Object.fromEntries(r.entries()),_set:(p,h)=>{const _=r.get(p);if(_&&_!==h)throw new Error(`Actor with system ID '${p}' already exists.`);r.set(p,h),i.set(h,p)},inspect:p=>{const h=wf(p);return s.add(h),{unsubscribe(){s.delete(h)}}},_sendInspectionEvent:d,_relay:(p,h,_)=>{f._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:h,event:_}),h._send(_)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...f._snapshot._scheduledEvents}}),start:()=>{const p=f._snapshot._scheduledEvents;f._snapshot._scheduledEvents={};for(const h in p){const{source:_,target:g,event:y,delay:m,id:w}=p[h];u.schedule(_,g,y,m,w)}},_clock:c,_logger:l};return f}let Kd=!1;const C0=1;let Ct=(function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e})({});const q9={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class F9{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Dm(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ct.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const r={...q9,...n},{clock:i,logger:s,parent:a,syncSnapshot:c,id:l,systemId:u,inspect:d}=r;this.system=a?a.system:M9(this,{clock:i,logger:s}),d&&!a&&this.system.inspect(wf(d)),this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=n?.logger??this.system._logger,this.clock=n?.clock??this.system._clock,this._parent=a,this._syncSnapshot=c,this.options=r,this.src=r.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:f=>{this._deferred.push(f)},system:this.system,stopChild:f=>{if(f._parent!==this)throw new Error(`Cannot stop child actor ${f.id} of ${this.id} because it is not a child`);f._stop()},emit:f=>{const p=this.eventListeners.get(f.type),h=this.eventListeners.get("*");if(!p&&!h)return;const _=[...p?p.values():[],...h?h.values():[]];for(const g of _)try{g(f)}catch(y){wn(y)}},actionExecutor:f=>{const p=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:f.type,params:f.params}}),!f.exec)return;const h=Kd;try{Kd=!0,f.exec(f.info,f.params)}finally{Kd=h}};this._processingStatus===Ct.Running?p():this._deferred.push(p)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(n?.snapshot??n?.state),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,n){this._snapshot=t;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(s){wn(s)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(s){wn(s)}this._stopProcedure(),this._complete(),this._doneEvent=O9(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,r){const i=wf(t,n,r);if(this._processingStatus!==Ct.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(s){wn(s)}break;case"error":{const s=this._snapshot.error;if(!i.error)wn(s);else try{i.error(s)}catch(a){wn(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,n){let r=this.eventListeners.get(t);r||(r=new Set,this.eventListeners.set(t,r));const i=n.bind(void 0);return r.add(i),{unsubscribe:()=>{r.delete(i)}}}start(){if(this._processingStatus===Ct.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=Ct.Running;const t=o2(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,r;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){r={err:i}}if(r){const{err:i}=r;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(n,t),t.type===yf&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Ct.Stopped?this:(this.mailbox.clear(),this._processingStatus===Ct.NotStarted?(this._processingStatus=Ct.Stopped,this):(this.mailbox.enqueue({type:yf}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(n){wn(n)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size){this._parent||wn(t),this.eventListeners.clear();return}let n=!1;for(const r of this.observers){const i=r.error;n||=!i;try{i?.(t)}catch(s){wn(s)}}this.observers.clear(),this.eventListeners.clear(),n&&wn(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,i2(this.id,t))}_stopProcedure(){return this._processingStatus!==Ct.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Dm(this._process.bind(this)),this._processingStatus=Ct.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==Ct.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:C9)(this)}toJSON(){return{xstate$$type:C0,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[R9](){return this}getSnapshot(){return this._snapshot}}function oa(e,...[t]){return new F9(e,t)}function H9(e,t,n,r,{sendId:i}){const s=typeof i=="function"?i(n,r):i;return[t,{sendId:s},void 0]}function V9(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function I0(e){function t(n,r){}return t.type="xstate.cancel",t.sendId=e,t.resolve=H9,t.execute=V9,t}function K9(e,t,n,r,{id:i,systemId:s,src:a,input:c,syncSnapshot:l}){const u=typeof a=="string"?E0(t.machine,a):a,d=typeof i=="function"?i(n):i;let f,p;return u&&(p=typeof c=="function"?c({context:t.context,event:n.event,self:e.self}):c,f=oa(u,{id:d,src:a,parent:e.self,syncSnapshot:l,systemId:s,input:p})),[fi(t,{children:{...t.children,[d]:f}}),{id:i,systemId:s,actorRef:f,src:a,input:p},void 0]}function G9(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==Ct.Stopped&&t.start()})}function j0(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function s(a,c){}return s.type="xstate.spawnChild",s.id=t,s.systemId=n,s.src=e,s.input=r,s.syncSnapshot=i,s.resolve=K9,s.execute=G9,s}function W9(e,t,n,r,{actorRef:i}){const s=typeof i=="function"?i(n,r):i,a=typeof s=="string"?t.children[s]:s;let c=t.children;return a&&(c={...c},delete c[a.id]),[fi(t,{children:c}),a,void 0]}function u2(e,t){const n=t.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))u2(e,r);e.system._unregister(t)}function J9(e,t){if(t){if(u2(e,t),t._processingStatus!==Ct.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function wu(e){function t(n,r){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=W9,t.execute=J9,t}function ku(e,t,n,r){const{machine:i}=r,s=typeof e=="function",a=s?e:i.implementations.guards[typeof e=="string"?e:e.type];if(!s&&!a)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof a!="function")return ku(a,t,n,r);const c={context:t,event:n},l=s||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in a?a.check(r,c,a):a(c,l)}function N0(e){return e.type==="atomic"||e.type==="final"}function wo(e){return Object.values(e.states).filter(t=>t.type!=="history")}function Ta(e,t){const n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function _l(e){const t=new Set(e),n=p2(t);for(const r of t)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))Fm(r).forEach(i=>t.add(i));else if(r.type==="parallel"){for(const i of wo(r))if(i.type!=="history"&&!t.has(i)){const s=Fm(i);for(const a of s)t.add(a)}}for(const r of t){let i=r.parent;for(;i;)t.add(i),i=i.parent}return t}function d2(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const i=n[0];if(i){if(N0(i))return i.key}else return{}}const r={};for(const i of n)r[i.key]=d2(i,t);return r}function p2(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function f2(e,t){const n=_l(t);return d2(e,p2(n))}function T0(e,t){return t.type==="compound"?wo(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?wo(t).every(n=>T0(e,n)):t.type==="final"}const $u=e=>e[0]===j9;function Z9(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(r=>U9(t,r)).sort((r,i)=>i.length-r.length).flatMap(r=>e.transitions.get(r))}function X9(e){const t=e.config.after;if(!t)return[];const n=i=>{const s=P9(i,e.id),a=s.type;return e.entry.push(R0(s,{id:a,delay:i})),e.exit.push(I0(a)),a};return Object.keys(t).flatMap(i=>{const s=t[i],a=typeof s=="string"?{target:s}:s,c=Number.isNaN(+i)?i:+i,l=n(c);return gr(a).map(u=>({...u,event:l,delay:c}))}).map(i=>{const{delay:s}=i;return{...hr(e,i.event,i),delay:s}})}function hr(e,t,n){const r=l2(n.target),i=n.reenter??!1,s=tA(e,r),a={...n,actions:gr(n.actions),guard:n.guard,target:s,source:e,reenter:i,eventType:t,toJSON:()=>({...a,source:`#${e.id}`,target:s?s.map(c=>`#${c.id}`):void 0})};return a}function Y9(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===n2)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=e.config.on[n];t.set(n,Ji(r).map(i=>hr(e,n,i)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,Ji(e.config.onDone).map(r=>hr(e,n,r)))}for(const n of e.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;t.set(r,Ji(n.onDone).map(i=>hr(e,r,i)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;t.set(r,Ji(n.onError).map(i=>hr(e,r,i)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;t.set(r,Ji(n.onSnapshot).map(i=>hr(e,r,i)))}}for(const n of e.after){let r=t.get(n.eventType);r||(r=[],t.set(n.eventType,r)),r.push(n)}return t}function Q9(e){const t=[],n=r=>{Object.values(r).forEach(i=>{if(i.config.route&&i.config.id){const s=i.config.id,a=i.config.route.guard,c=(u,d)=>u.event.to!==`#${s}`?!1:a&&typeof a=="function"?a(u,d):!0,l={...i.config.route,guard:c,target:`#${s}`};t.push(hr(e,"xstate.route",l))}i.states&&n(i.states)})};n(e.states),t.length>0&&e.transitions.set("xstate.route",t)}function eA(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const r={source:e,actions:!t||typeof t=="string"?[]:gr(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function tA(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if($u(n))return e.machine.getStateNodeById(n);const r=n[0]===t2;if(r&&!e.parent)return ml(e,n.slice(1));const i=r?e.key+n:n;if(e.parent)try{return ml(e.parent,i)}catch(s){throw new Error(`Invalid transition definition for state node '${e.id}':
66
66
  ${s.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function h2(e){const t=l2(e.config.target);return t?{target:t.map(n=>typeof n=="string"?ml(e.parent,n):n)}:e.parent.initial}function oi(e){return e.type==="history"}function Fm(e){const t=_2(e);for(const n of t)for(const r of Ta(n,e))t.add(r);return t}function _2(e){const t=new Set;function n(r){if(!t.has(r)){if(t.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const i of wo(r))n(i)}}return n(e),t}function ko(e,t){if($u(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function ml(e,t){if(typeof t=="string"&&$u(t))try{return e.machine.getStateNodeById(t)}catch{}const n=A0(t).slice();let r=e;for(;n.length;){const i=n.shift();if(!i.length)break;r=ko(r,i)}return r}function gl(e,t){if(typeof t=="string"){const i=e.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}const n=Object.keys(t),r=n.map(i=>ko(e,i)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((i,s)=>{const a=ko(e,s);if(!a)return i;const c=gl(a,t[s]);return i.concat(c)},[]))}function nA(e,t,n,r){const s=ko(e,t).next(n,r);return!s||!s.length?e.next(n,r):s}function rA(e,t,n,r){const i=Object.keys(t),s=ko(e,i[0]),a=P0(s,t[i[0]],n,r);return!a||!a.length?e.next(n,r):a}function iA(e,t,n,r){const i=[];for(const s of Object.keys(t)){const a=t[s];if(!a)continue;const c=ko(e,s),l=P0(c,a,n,r);l&&i.push(...l)}return i.length?i:e.next(n,r)}function P0(e,t,n,r){return typeof t=="string"?nA(e,t,n,r):Object.keys(t).length===1?rA(e,t,n,r):iA(e,t,n,r)}function oA(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function xr(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function sA(e,t){const n=new Set(e),r=new Set(t);for(const i of n)if(r.has(i))return!0;for(const i of r)if(n.has(i))return!0;return!1}function m2(e,t,n){const r=new Set;for(const i of e){let s=!1;const a=new Set;for(const c of r)if(sA(kf([i],t,n),kf([c],t,n)))if(xr(i.source,c.source))a.add(c);else{s=!0;break}if(!s){for(const c of a)r.delete(c);r.add(i)}}return Array.from(r)}function aA(e){const[t,...n]=e;for(const r of Ta(t,void 0))if(n.every(i=>xr(i,r)))return r}function O0(e,t){if(!e.target)return[];const n=new Set;for(const r of e.target)if(oi(r))if(t[r.id])for(const i of t[r.id])n.add(i);else for(const i of O0(h2(r),t))n.add(i);else n.add(r);return[...n]}function g2(e,t){const n=O0(e,t);if(!n)return;if(!e.reenter&&n.every(i=>i===e.source||xr(i,e.source)))return e.source;const r=aA(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function kf(e,t,n){const r=new Set;for(const i of e)if(i.target?.length){const s=g2(i,n);i.reenter&&i.source===s&&r.add(s);for(const a of t)xr(a,s)&&r.add(a)}return[...r]}function cA(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function lA(e,t,n,r,i){return $f([{target:[..._2(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,r,!0,i)}function $f(e,t,n,r,i,s){const a=[];if(!e.length)return[t,a];const c=n.actionExecutor;n.actionExecutor=l=>{a.push(l),c(l)};try{const l=new Set(t._nodes);let u=t.historyValue;const d=m2(e,l,u);let f=t;i||([f,u]=fA(f,r,n,d,l,u,s,n.actionExecutor)),f=$o(f,r,n,d.flatMap(h=>h.actions),s,void 0),f=dA(f,r,n,d,l,s,u,i);const p=[...l];f.status==="done"&&(f=$o(f,r,n,p.sort((h,_)=>_.order-h.order).flatMap(h=>h.exit),s,void 0));try{return u===t.historyValue&&cA(t._nodes,l)?[f,a]:[fi(f,{_nodes:p,historyValue:u}),a]}catch(h){throw h}}finally{n.actionExecutor=c}}function uA(e,t,n,r,i){if(r.output===void 0)return;const s=bf(i.id,i.output!==void 0&&i.parent?vf(i.output,e.context,t,n.self):void 0);return vf(r.output,e.context,s,n.self)}function dA(e,t,n,r,i,s,a,c){let l=e;const u=new Set,d=new Set;pA(r,a,d,u),c&&d.add(e.machine.root);const f=new Set;for(const p of[...u].sort((h,_)=>h.order-_.order)){i.add(p);const h=[];h.push(...p.entry);for(const _ of p.invoke)h.push(j0(_.src,{..._,syncSnapshot:!!_.onSnapshot}));if(d.has(p)){const _=p.initial.actions;h.push(..._)}if(l=$o(l,t,n,h,s,p.invoke.map(_=>_.id)),p.type==="final"){const _=p.parent;let g=_?.type==="parallel"?_:_?.parent,y=g||p;for(_?.type==="compound"&&s.push(bf(_.id,p.output!==void 0?vf(p.output,l.context,t,n.self):void 0));g?.type==="parallel"&&!f.has(g)&&T0(i,g);)f.add(g),s.push(bf(g.id)),y=g,g=g.parent;if(g)continue;l=fi(l,{status:"done",output:uA(l,t,n,l.machine.root,y)})}}return l}function pA(e,t,n,r){for(const i of e){const s=g2(i,t);for(const c of i.target||[])!oi(c)&&(i.source!==c||i.source!==s||i.reenter)&&(r.add(c),n.add(c)),lo(c,t,n,r);const a=O0(i,t);for(const c of a){const l=Ta(c,s);s?.type==="parallel"&&l.push(s),y2(r,t,n,l,!i.source.parent&&i.reenter?void 0:s)}}}function lo(e,t,n,r){if(oi(e))if(t[e.id]){const i=t[e.id];for(const s of i)r.add(s),lo(s,t,n,r);for(const s of i)Gd(s,e.parent,r,t,n)}else{const i=h2(e);for(const s of i.target)r.add(s),i===e.parent?.initial&&n.add(e.parent),lo(s,t,n,r);for(const s of i.target)Gd(s,e.parent,r,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;oi(i)||(r.add(i),n.add(i)),lo(i,t,n,r),Gd(i,e,r,t,n)}else if(e.type==="parallel")for(const i of wo(e).filter(s=>!oi(s)))[...r].some(s=>xr(s,i))||(oi(i)||(r.add(i),n.add(i)),lo(i,t,n,r))}function y2(e,t,n,r,i){for(const s of r)if((!i||xr(s,i))&&e.add(s),s.type==="parallel")for(const a of wo(s).filter(c=>!oi(c)))[...e].some(c=>xr(c,a))||(e.add(a),lo(a,t,n,e))}function Gd(e,t,n,r,i){y2(n,r,i,Ta(e,t))}function fA(e,t,n,r,i,s,a,c){let l=e;const u=kf(r,i,s);u.sort((f,p)=>p.order-f.order);let d;for(const f of u)for(const p of oA(f)){let h;p.history==="deep"?h=_=>N0(_)&&xr(_,f):h=_=>_.parent===f,d??={...s},d[p.id]=Array.from(i).filter(h)}for(const f of u)l=$o(l,t,n,[...f.exit,...f.invoke.map(p=>wu(p.id))],a,void 0),i.delete(f);return[l,d||s]}function hA(e,t){return e.implementations.actions[t]}function b2(e,t,n,r,i,s){const{machine:a}=e;let c=e;for(const l of r){const u=typeof l=="function",d=u?l:hA(a,typeof l=="string"?l:l.type),f={context:c.context,event:t,self:n.self,system:n.system},p=u||typeof l=="string"?void 0:"params"in l?typeof l.params=="function"?l.params({context:c.context,event:t}):l.params:void 0;if(!d||!("resolve"in d)){n.actionExecutor({type:typeof l=="string"?l:typeof l=="object"?l.type:l.name||"(anonymous)",info:f,params:p,exec:d});continue}const h=d,[_,g,y]=h.resolve(n,c,f,p,d,i);c=_,"retryResolve"in h&&s?.push([h,g]),"execute"in h&&n.actionExecutor({type:h.type,info:f,params:g,exec:h.execute.bind(null,n,g)}),y&&(c=b2(c,t,n,y,i,s))}return c}function $o(e,t,n,r,i,s){const a=s?[]:void 0,c=b2(e,t,n,r,{internalQueue:i,deferredActorIds:s},a);return a?.forEach(([l,u])=>{l.retryResolve(n,c,u)}),c}function Wd(e,t,n,r){let i=e;const s=[];function a(u,d,f){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:d,snapshot:u[0],_transitions:f}),s.push(u)}if(t.type===yf)return i=fi(Hm(i,t,n),{status:"stopped"}),a([i,[]],t,[]),{snapshot:i,microsteps:s};let c=t;if(c.type!==r2){const u=c,d=D9(u),f=Vm(u,i);if(d&&!f.length)return i=fi(e,{status:"error",error:u.error}),a([i,[]],u,[]),{snapshot:i,microsteps:s};const p=$f(f,e,n,c,!1,r);i=p[0],a(p,u,f)}let l=!0;for(;i.status==="active";){let u=l?_A(i,c):[];const d=u.length?i:void 0;if(!u.length){if(!r.length)break;c=r.shift(),u=Vm(c,i)}const f=$f(u,i,n,c,!1,r);i=f[0],l=i!==d,a(f,c,u)}return i.status!=="active"&&Hm(i,c,n),{snapshot:i,microsteps:s}}function Hm(e,t,n){return $o(e,t,n,Object.values(e.children).map(r=>wu(r)),[],void 0)}function Vm(e,t){return t.machine.getTransitionData(t,e)}function _A(e,t){const n=new Set,r=e._nodes.filter(N0);for(const i of r)e:for(const s of[i].concat(Ta(i,void 0)))if(s.always){for(const a of s.always)if(a.guard===void 0||ku(a.guard,e.context,t,e)){n.add(a);break e}}return m2(Array.from(n),new Set(e._nodes),e.historyValue)}function mA(e,t){const n=_l(gl(e,t));return f2(e,[...n])}function gA(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const yA=function(t){return s2(t,this.value)},bA=function(t){return this.tags.has(t)},vA=function(t){const n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some(r=>r.target!==void 0||r.actions.length)},wA=function(){const{_nodes:t,tags:n,machine:r,getMeta:i,toJSON:s,can:a,hasTag:c,matches:l,...u}=this;return{...u,tags:Array.from(n)}},kA=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Rc(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:f2(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:yA,hasTag:bA,can:vA,getMeta:kA,toJSON:wA}}function fi(e,t={}){return Rc({...e,...t},e.machine)}function $A(e){if(typeof e!="object"||e===null)return{};const t={};for(const n in e){const r=e[n];Array.isArray(r)&&(t[n]=r.map(i=>({id:i.id})))}return t}function SA(e,t){const{_nodes:n,tags:r,machine:i,children:s,context:a,can:c,hasTag:l,matches:u,getMeta:d,toJSON:f,...p}=e,h={};for(const g in s){const y=s[g];h[g]={snapshot:y.getPersistedSnapshot(t),src:y.src,systemId:y.systemId,syncSnapshot:y._syncSnapshot}}return{...p,context:v2(a),children:h,historyValue:$A(p.historyValue)}}function v2(e){let t;for(const n in e){const r=e[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:C0,id:r.id};else{const i=v2(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}return t??e}function xA(e,t,n,r,{event:i,id:s,delay:a},{internalQueue:c}){const l=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const u=typeof i=="function"?i(n,r):i;let d;if(typeof a=="string"){const f=l&&l[a];d=typeof f=="function"?f(n,r):f}else d=typeof a=="function"?a(n,r):a;return typeof d!="number"&&c.push(u),[t,{event:u,id:s,delay:d},void 0]}function zA(e,t){const{event:n,delay:r,id:i}=t;if(typeof r=="number"){e.defer(()=>{const s=e.self;e.system.scheduler.schedule(s,s,n,r,i)});return}}function R0(e,t){function n(r,i){}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=xA,n.execute=zA,n}function AA(e,{machine:t,context:n},r,i){const s=(a,c)=>{if(typeof a=="string"){const l=E0(t,a);if(!l)throw new Error(`Actor logic '${a}' not implemented in machine '${t.id}'`);const u=oa(l,{id:c?.id,parent:e.self,syncSnapshot:c?.syncSnapshot,input:typeof c?.input=="function"?c.input({context:n,event:r,self:e.self}):c?.input,src:a,systemId:c?.systemId});return i[u.id]=u,u}else return oa(a,{id:c?.id,parent:e.self,syncSnapshot:c?.syncSnapshot,input:c?.input,src:a,systemId:c?.systemId})};return(a,c)=>{const l=s(a,c);return i[l.id]=l,e.defer(()=>{l._processingStatus!==Ct.Stopped&&l.start()}),l}}function EA(e,t,n,r,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const s={},a={context:t.context,event:n.event,spawn:AA(e,t,n.event,s),self:e.self,system:e.system};let c={};if(typeof i=="function")c=i(a,r);else for(const u of Object.keys(i)){const d=i[u];c[u]=typeof d=="function"?d(a,r):d}const l=Object.assign({},t.context,c);return[fi(t,{context:l,children:Object.keys(s).length?{...t.children,...s}:t.children}),void 0,void 0]}function Gn(e){function t(n,r){}return t.type="xstate.assign",t.assignment=e,t.resolve=EA,t}const Km=new WeakMap;function Hi(e,t,n){let r=Km.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Km.set(e,r)),r[t]}const CA={},ds=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class yl{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(t2),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Bm(this.config.states,(r,i)=>new yl(r,{_parent:this,_key:i,_machine:this.machine})):CA,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=gr(this.config.entry).slice(),this.exit=gr(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=gr(t.tags).slice()}_initialize(){this.transitions=Y9(this),this.config.always&&(this.always=Ji(this.config.always).map(t=>hr(this,n2,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ds),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ds),eventType:null})}:void 0,history:this.history,states:Bm(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ds)})),entry:this.entry.map(ds),exit:this.exit.map(ds),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Hi(this,"invoke",()=>gr(this.config.invoke).map((t,n)=>{const{src:r,systemId:i}=t,s=t.id??Mm(this.id,n),a=typeof r=="string"?r:`xstate.invoke.${Mm(this.id,n)}`;return{...t,src:a,id:s,systemId:i,toJSON(){const{onDone:c,onError:l,...u}=t;return{...u,type:"xstate.invoke",src:a,id:s}}}}))}get on(){return Hi(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(i=>[n,i])).reduce((n,[r,i])=>(n[r]=n[r]||[],n[r].push(i),n),{}))}get after(){return Hi(this,"delayedTransitions",()=>X9(this))}get initial(){return Hi(this,"initial",()=>eA(this,this.config.initial))}next(t,n){const r=n.type,i=[];let s;const a=Hi(this,`candidates-${r}`,()=>Z9(this,r));for(const c of a){const{guard:l}=c,u=t.context;let d=!1;try{d=!l||ku(l,u,n,t)}catch(f){const p=typeof l=="string"?l:typeof l=="object"?l.type:void 0;throw new Error(`Unable to evaluate guard ${p?`'${p}' `:""}in transition for event '${r}' in state node '${this.id}':
67
- ${f.message}`)}if(d){i.push(...c.actions),s=c;break}}return s?[s]:void 0}get events(){return Hi(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const s of i.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),n=new Set(t.filter(r=>this.transitions.get(r).some(i=>!(!i.target&&!i.actions.length&&!i.reenter))));return Array.from(n)}}const IA="#";class L0{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new yl(t,{_key:this.id,_machine:this}),this.root._initialize(),Q9(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:s}=this.implementations;return new L0(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...s,...t.delays}})}resolveState(t){const n=mA(this.root,t.value),r=_l(gl(this.root,n));return Rc({_nodes:[...r],context:t.context||{},children:{},status:T0(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return Wd(t,n,r,[]).snapshot}microstep(t,n,r){return Wd(t,n,r,[]).microsteps.map(([i])=>i)}getTransitionData(t,n){return P0(this.root,t.value,t,n)||[]}_getPreInitialState(t,n,r){const{context:i}=this.config,s=Rc({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?$o(s,n,t,[Gn(({spawn:c,event:l,self:u})=>i({spawn:c,input:l.input,self:u}))],r,void 0):s}getInitialSnapshot(t,n){const r=o2(n),i=[],s=this._getPreInitialState(t,r,i),[a]=lA(this.root,s,t,r,i),{snapshot:c}=Wd(a,r,t,i);return c}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=A0(t),r=n.slice(1),i=$u(n[0])?n[0].slice(IA.length):n[0],s=this.idMap.get(i);if(!s)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return ml(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return SA(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(f=>{const p=i[f],h=p.snapshot,_=p.src,g=typeof _=="string"?E0(this,_):_;if(!g)return;const y=oa(g,{id:f,parent:n.self,syncSnapshot:p.syncSnapshot,snapshot:h,src:_,systemId:p.systemId});r[f]=y});function s(f,p){if(p instanceof yl)return p;try{return f.machine.getStateNodeById(p.id)}catch{}}function a(f,p){if(!p||typeof p!="object")return{};const h={};for(const _ in p){const g=p[_];for(const y of g){const m=s(f,y);m&&(h[_]??=[],h[_].push(m))}}return h}const c=a(this.root,t.historyValue),l=Rc({...t,children:r,_nodes:Array.from(_l(gl(this.root,t.value))),historyValue:c},this),u=new Set;function d(f,p){if(!u.has(f)){u.add(f);for(const h in f){const _=f[h];if(_&&typeof _=="object"){if("xstate$$type"in _&&_.xstate$$type===C0){f[h]=p[_.id];continue}d(_,p)}}}}return d(l.context,r),l}}function jA(e,t,n,r,{event:i}){const s=typeof i=="function"?i(n,r):i;return[t,{event:s},void 0]}function NA(e,{event:t}){e.defer(()=>e.emit(t))}function w2(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=jA,t.execute=NA,t}let Sf=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function TA(e,t,n,r,{to:i,event:s,id:a,delay:c},l){const u=t.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const d=typeof s=="function"?s(n,r):s;let f;if(typeof c=="string"){const _=u&&u[c];f=typeof _=="function"?_(n,r):_}else f=typeof c=="function"?c(n,r):c;const p=typeof i=="function"?i(n,r):i;let h;if(typeof p=="string"){if(p===Sf.Parent?h=e.self._parent:p===Sf.Internal?h=e.self:p.startsWith("#_")?h=t.children[p.slice(2)]:h=l.deferredActorIds?.includes(p)?p:t.children[p],!h)throw new Error(`Unable to send event to actor '${p}' from machine '${t.machine.id}'.`)}else h=p||e.self;return[t,{to:h,targetId:typeof p=="string"?p:void 0,event:d,id:a,delay:f},void 0]}function PA(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function OA(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:s}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,s);return}e.system._relay(e.self,n,r.type===T9?i2(e.self.id,r.data):r)})}function D0(e,t,n){function r(i,s){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=TA,r.retryResolve=PA,r.execute=OA,r}function RA(e,t){return D0(Sf.Parent,e,t)}function LA(e,t,n,r,{collect:i}){const s=[],a=function(l){s.push(l)};return a.assign=(...c)=>{s.push(Gn(...c))},a.cancel=(...c)=>{s.push(I0(...c))},a.raise=(...c)=>{s.push(R0(...c))},a.sendTo=(...c)=>{s.push(D0(...c))},a.sendParent=(...c)=>{s.push(RA(...c))},a.spawnChild=(...c)=>{s.push(j0(...c))},a.stopChild=(...c)=>{s.push(wu(...c))},a.emit=(...c)=>{s.push(w2(...c))},i({context:n.context,event:n.event,enqueue:a,check:c=>ku(c,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,s]}function DA(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=LA,t}function UA(e,t,n,r,{value:i,label:s}){return[t,{value:typeof i=="function"?i(n,r):i,label:s},void 0]}function BA({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function MA(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=UA,n.execute=BA,n}function qA(e,t){return new L0(e,t)}function FA(e){const t=oa(e);return{self:t,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:t.system,emit:()=>{},actionExecutor:()=>{}}}function k2({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Gn,sendTo:D0,raise:R0,log:MA,cancel:I0,stopChild:wu,enqueueActions:DA,emit:w2,spawnChild:j0,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>qA({...s,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:s=>k2({schemas:e,actors:t,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...i,...s.delays}})}}function HA(e,t,n){const r=[],i=FA(e);return i.actionExecutor=a=>{r.push(a)},[e.transition(t,n,i),r]}var Pr=(e=>(e.AUTHENTICATE="AUTHENTICATE",e.REQUIRE_EMAIL_VERIFICATION="REQUIRE_EMAIL_VERIFICATION",e.START_HOOK="START_HOOK",e.COMPLETE_HOOK="COMPLETE_HOOK",e.START_CONTINUATION="START_CONTINUATION",e.COMPLETE_CONTINUATION="COMPLETE_CONTINUATION",e.COMPLETE="COMPLETE",e.FAIL="FAIL",e.EXPIRE="EXPIRE",e))(Pr||{});const $2=k2({actions:{setUserId:Gn(({event:e})=>e.type==="AUTHENTICATE"?{userId:e.userId}:{}),setHookId:Gn(({event:e})=>e.type==="START_HOOK"?{hookId:e.hookId}:{}),clearHookId:Gn({hookId:void 0}),setContinuationScope:Gn(({event:e})=>e.type==="START_CONTINUATION"?{continuationScope:e.scope}:{}),clearContinuationScope:Gn({continuationScope:void 0}),setFailureReason:Gn(({event:e})=>e.type==="FAIL"?{failureReason:e.reason}:{})}}).createMachine({id:"loginSession",initial:"pending",context:{},states:{pending:{on:{AUTHENTICATE:{target:"authenticated",actions:"setUserId"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},authenticated:{on:{REQUIRE_EMAIL_VERIFICATION:{target:"awaiting_email_verification"},START_HOOK:{target:"awaiting_hook",actions:"setHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},COMPLETE:{target:"completed"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_email_verification:{on:{COMPLETE:{target:"authenticated"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_hook:{on:{COMPLETE_HOOK:{target:"authenticated",actions:"clearHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_continuation:{on:{COMPLETE_CONTINUATION:{target:"authenticated",actions:"clearContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},completed:{type:"final"},failed:{type:"final"},expired:{type:"final"}}});function VA(e,t={}){return $2.resolveState({value:e,context:t})}function Oi(e,t,n={}){const r=VA(e,n),[i]=HA($2,r,t),s={},a=i.context,c=n;return a.userId!==c.userId&&(s.userId=a.userId),a.hookId!==c.hookId&&(s.hookId=a.hookId),a.continuationScope!==c.continuationScope&&(s.continuationScope=a.continuationScope),a.failureReason!==c.failureReason&&(s.failureReason=a.failureReason),{state:i.value,context:s}}function S2(e,t){Object.keys(t).forEach(n=>{const r=t[n];r!=null&&r.length&&e.searchParams.set(n,r)})}function KA(e){try{const t=typeof e=="string"?new URL(e):e;let n=`${t.protocol}//${t.host}${t.pathname}`;if(t.search){const r=Array.from(t.searchParams.keys()).map(i=>`${i}=[REDACTED]`).join("&");n+=`?${r}`}return t.hash&&(n+="#[REDACTED]"),n}catch{const n=(typeof e=="string"?e:e.toString()).match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!n)return"[invalid-url]";const[,r="",i,s]=n;let a=r;if(i){const c=i.substring(1).split("&").map(l=>{const[u]=l.split("=");return`${u}=[REDACTED]`}).join("&");a+=`?${c}`}return s&&(a+="#[REDACTED]"),a}}const xf=["sub","iss","aud","exp","nbf","iat","jti"];function Gm(e,t,n){return{accessToken:{setCustomClaim:(r,i)=>{if(xf.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);t[r]=i}},idToken:{setCustomClaim:(r,i)=>{if(xf.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);n&&(n[r]=i)}},access:{deny:r=>{throw new X(400,{message:`Access denied: ${r}`})}},token:{createServiceToken:async r=>(await zu(e,e.var.tenant_id,r.scope,r.expiresInSeconds,r.customClaims)).access_token}}}async function Su(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l,auth_time:u}=t,{signingKeys:d}=await e.env.data.keys.list({q:"type:jwt_signing"}),f=d.filter(B=>!B.revoked_at||new Date(B.revoked_at)>new Date),p=f[f.length-1];if(!p?.pkcs7)throw new X(500,{message:"No signing key available"});const h=Pz(p.pkcs7),_=Pi(e.env,e.var.custom_domain),g=n.audience||i.tenant.audience;if(!g)throw new X(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const y={aud:g,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:e.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,org_name:a&&i.tenant.allow_organization_name_in_authentication_api?a.name.toLowerCase():void 0,permissions:c,...t.customClaims};if(t.customClaims){for(const B of xf)if(B in t.customClaims)throw new Error(`Cannot overwrite reserved claim '${B}'`)}const m=n.scope?.split(" ")||[],w=m.includes("openid"),k=m.includes("profile"),S=m.includes("email"),v=n.response_type===st.ID_TOKEN,x=i.auth0_conformant!==!1||v,A=r&&w?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,...n.max_age!==void 0&&u!==void 0?{auth_time:u}:{},...n.acr_values?{acr:n.acr_values.split(" ")[0]}:{},...k&&x&&{given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name},...S&&x&&{email:r.email,email_verified:r.email_verified},act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name.toLowerCase()}:void 0,E=t.loginSession?.auth_connection||t.authConnection||e.var.connection;let P;if(E)try{const B=await e.env.data.connections.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1}),V=B.connections.find(L=>L.name===E)??B.connections.find(L=>L.name.toLowerCase()===E.toLowerCase());V&&(P={id:V.id||V.name,name:V.name,strategy:V.strategy||r?.provider||"auth0",metadata:V.options||{}})}catch(B){console.error("Error fetching connection info:",B)}e.env.hooks?.onExecuteCredentialsExchange&&await e.env.hooks.onExecuteCredentialsExchange({ctx:e,client:i,user:r,request:{ip:e.var.ip||"",user_agent:e.var.useragent||"",method:e.req.method,url:e.req.url},scope:n.scope||"",grant_type:"",connection:P||(E?{id:E,name:E,strategy:r?.provider||"auth0"}:void 0)},Gm(e,y,A));{const{hooks:B}=await e.env.data.hooks.list(e.var.tenant_id,{q:"trigger_id:credentials-exchange",page:0,per_page:100,include_totals:!1}),V=B.filter(Q=>Q.enabled&&fl(Q)),L=Gm(e,y,A);if(r){for(const Q of V)if(fl(Q))try{await S9(e,Q.template_id,r,L)}catch(ae){if(ae instanceof I)throw ae;console.warn(`[credentials-exchange] Failed to execute template hook: ${Q.template_id}`,ae)}}}const D={expiresIn:l?new dl(1,"h"):new dl(1,"d"),headers:{kid:p.kid}},C=await Im("RS256",h,y,D),R=A?await Im("RS256",h,A,D):void 0;return{access_token:C,refresh_token:t.refresh_token,id_token:R,token_type:"Bearer",expires_in:l?3600:86400}}async function x2(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Oe(32),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+Lz*1e3).toISOString(),code_challenge:t.authParams.code_challenge,code_challenge_method:t.authParams.code_challenge_method,redirect_uri:t.authParams.redirect_uri,state:t.authParams.state,nonce:t.authParams.nonce})).code_id,state:t.authParams.state}}async function z2(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,login_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Vw(),login_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+bu*1e3).toISOString(),user_id:t.user.user_id,device:{last_ip:e.var.ip,initial_ip:e.var.ip,last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Wm(e,{user:t,client:n,loginSession:r}){return await e.env.data.sessions.create(n.tenant.id,{id:Vw(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+bu*1e3).toISOString(),device:{last_ip:e.var.ip||"",initial_ip:e.var.ip||"",last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]})}async function GA(e,{user:t,client:n,loginSession:r,existingSessionId:i,authConnection:s}){const a=await e.env.data.loginSessions.get(n.tenant.id,r.id);if(!a)throw new I(400,{message:`Login session ${r.id} not found`});const c=a.state||We.PENDING;if(c===We.FAILED||c===We.EXPIRED||c===We.COMPLETED)throw new I(400,{message:`Cannot authenticate login session in ${c} state`});if(c===We.AUTHENTICATED){if(a.session_id)return a.session_id;throw new I(500,{message:"Login session is authenticated but has no session_id"})}let l;if(i){const f=await e.env.data.sessions.get(n.tenant.id,i);!f||f.revoked_at?l=(await Wm(e,{user:t,client:n,loginSession:r})).id:(l=i,f.clients.includes(n.client_id)||await e.env.data.sessions.update(n.tenant.id,i,{clients:[...f.clients,n.client_id]}))}else l=(await Wm(e,{user:t,client:n,loginSession:r})).id;const{state:u}=Oi(c,{type:Pr.AUTHENTICATE,userId:t.user_id}),d=s||e.var.connection;return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:l,state:u,user_id:t.user_id,...d?{auth_connection:d}:{}}),l}async function WA(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as failed`);return}const s=i.state||We.PENDING,{state:a,context:c}=Oi(s,{type:Pr.FAIL,reason:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,failure_reason:c.failureReason})}async function bl(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to start hook`);return}const s=i.state||We.PENDING,{state:a,context:c}=Oi(s,{type:Pr.START_HOOK,hookId:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:c.hookId?JSON.stringify({hookId:c.hookId}):void 0})}async function sa(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete hook`);return}const i=r.state||We.PENDING,{state:s}=Oi(i,{type:Pr.COMPLETE_HOOK});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s,state_data:void 0})}async function Jm(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as completed`);return}const s=i.state||We.PENDING,{state:a}=Oi(s,{type:Pr.COMPLETE});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,...r?{auth_connection:r}:{}})}async function xu(e,t,n,r,i){const s=await e.env.data.loginSessions.get(t,n.id);if(!s){console.warn(`Login session ${n.id} not found when trying to start continuation`);return}const a=s.state||We.PENDING,{state:c}=Oi(a,{type:Pr.START_CONTINUATION,scope:r});c!==a?await e.env.data.loginSessions.update(t,n.id,{state:c,state_data:JSON.stringify({continuationScope:r,continuationReturnUrl:i})}):console.warn(`Failed to start continuation for login session ${n.id}: cannot transition from ${a} to AWAITING_CONTINUATION. Scope: ${JSON.stringify(r)}, Return URL: ${KA(i)}`)}async function JA(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete continuation`);return}let i;if(r.state_data)try{i=JSON.parse(r.state_data).continuationReturnUrl}catch{}const s=r.state||We.PENDING,{state:a}=Oi(s,{type:Pr.COMPLETE_CONTINUATION});return a!==s?await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:void 0}):console.warn(`completeLoginSessionContinuation: State transition from ${s} with COMPLETE_CONTINUATION was invalid or no-op`),i}function ZA(e){if(!e.state_data)return null;try{return JSON.parse(e.state_data).continuationScope||null}catch{return null}}function XA(e,t){if(e.state!==We.AWAITING_CONTINUATION)return!1;const n=ZA(e);return n?n.includes(t):!1}async function mt(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||st.CODE,c=n.response_mode||fn.QUERY;if(i){if(!t.loginSession)throw new X(500,{message:"Login session not found for ticket auth."});s&&!t.skipHooks&&(t.authStrategy&&s.app_metadata?.strategy!==t.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:t.authStrategy.strategy}})),await A2(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=Tz(),_=Oe(12),g=await e.env.data.codes.create(r.tenant.id,{code_id:Oe(32),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+Uz).toISOString(),code_verifier:[_,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:g.code_id,co_verifier:h,co_id:_})}let l=t.refreshToken,u;if(t.loginSession){const h=await e.env.data.loginSessions.get(r.tenant.id,t.loginSession.id);if(!h)throw new X(500,{message:"Login session not found."});const _=h.state||We.PENDING;if(_===We.COMPLETED)throw new X(400,{error:"invalid_request",error_description:"Login session has already been completed"});if(_===We.FAILED)throw new X(400,{error:"access_denied",error_description:`Login session failed: ${h.failure_reason||"unknown reason"}`});if(_===We.EXPIRED)throw new X(400,{error:"invalid_request",error_description:"Login session has expired"});if(_===We.PENDING)u=await GA(e,{user:s,client:r,loginSession:t.loginSession,existingSessionId:t.existingSessionIdToLink,authConnection:t.authConnection});else if(u=h.session_id,!u)throw new X(500,{message:`Login session in ${_} state but has no session_id`})}else throw new X(500,{message:"loginSession must be provided for front-channel auth responses."});if(!l&&n.scope?.split(" ").includes("offline_access")&&![st.TOKEN,st.CODE].includes(a)&&!t.impersonatingUser&&(l=(await z2(e,{user:s,client:r,login_id:t.loginSession?.id||"",scope:n.scope,audience:n.audience})).id),c===fn.SAML_POST){if(!u)throw new I(500,{message:"Session ID not available for SAML response"});return m9(e,t.client,t.authParams,s,u)}const d=await YA(e,{authParams:n,user:s,client:r,session_id:u,refresh_token:l,authStrategy:t.authStrategy,authConnection:t.authConnection,loginSession:t.loginSession,responseType:a,skipHooks:t.skipHooks,organization:t.organization,impersonatingUser:t.impersonatingUser});if(d instanceof Response)return d;if(c===fn.WEB_MESSAGE){if(!n.redirect_uri)throw new X(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const h=new Headers;u?pl(r.tenant.id,u,e.var.host||"").forEach(m=>{h.append("set-cookie",m)}):console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const _=new URL(n.redirect_uri),g=`${_.protocol}//${_.host}`;return gf(e,g,JSON.stringify({...d,state:n.state}),h)}if(!n.redirect_uri)throw new X(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;u&&pl(r.tenant.id,u,e.var.custom_domain||e.req.header("host")||"").forEach(_=>{f.append("set-cookie",_)});const p=new URL(n.redirect_uri);if("code"in d)p.searchParams.set("code",d.code),d.state&&p.searchParams.set("state",d.state);else if("access_token"in d)p.hash=new URLSearchParams({access_token:d.access_token,...d.id_token&&{id_token:d.id_token},token_type:d.token_type,expires_in:d.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new X(500,{message:"Invalid token response for implicit flow."});return f.set("location",p.toString()),new Response("Redirecting",{status:302,headers:f})}async function YA(e,t){let{user:n}=t;const r=t.responseType||st.TOKEN;if(n&&t.organization&&!(await e.env.data.userOrganizations.list(t.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(d=>d.organization_id===t.organization.id))throw new X(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=t.authParams.scope||"",s=[];if(t.authParams.audience)try{let l;if(t.grantType===an.ClientCredential||!n&&!t.user)l=await ia(e,{grantType:an.ClientCredential,tenantId:t.client.tenant.id,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id});else{const u=n?.user_id||t.user?.user_id;if(!u)throw new X(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});l=await ia(e,{grantType:t.grantType,tenantId:t.client.tenant.id,userId:u,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id})}i=l.scopes.join(" "),s=l.permissions}catch(l){if(l instanceof I)throw l}const a={...t.authParams,scope:i};if(t.loginSession&&n&&!t.skipHooks){t.authStrategy&&n.app_metadata?.strategy!==t.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(t.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:t.authStrategy.strategy}}));const l=await A2(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(l instanceof Response)return l;n=l}const c=t.loginSession?.auth_connection||t.authConnection||e.var.connection;if(r===st.CODE){if(!n||!t.loginSession)throw new X(500,{message:"User and loginSession is required for code flow"});const l=await x2(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id});return await Jm(e,t.client.tenant.id,t.loginSession,c),l}else{const l=await Su(e,{...t,user:n,authParams:a,permissions:s});return t.loginSession&&await Jm(e,t.client.tenant.id,t.loginSession,c),l}}const Zm="auth-service";async function zu(e,t,n,r,i){const s=await e.env.data.tenants.get(t);if(!s)throw new Error(`Tenant not found: ${t}`);const c=await Su(e,{client:{client_id:Zm,tenant:s,auth0_conformant:!0},authParams:{client_id:Zm,response_type:st.TOKEN,scope:n},customClaims:i});return{access_token:c.access_token,token_type:c.token_type,expires_in:r||3600}}async function Pa(e,t,n){const r=e.env.webhookInvoker,i=async(s="webhook")=>(await zu(e,n.tenant_id,s)).access_token;for await(const s of t.filter(a=>"url"in a)){let a,c;try{const l=performance.now(),u=r?await r({hook:s,data:n,tenant_id:n.tenant_id,createServiceToken:i}):await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${await i()}`,"Content-Type":"application/json"},body:JSON.stringify(n)}),d=performance.now()-l,f=e.res.headers.get("Server-Timing")||"",p=`webhook-${s.hook_id};dur=${d.toFixed(2)}`;if(e.res.headers.set("Server-Timing",f?`${f}, ${p}`:p),c=u.status,!u.ok){try{a=await u.text()}catch{}const h=`Failed to invoke hook ${s.hook_id} - ${u.status} ${u.statusText}`;console.error(h,{hook_url:s.url,body:a?.substring(0,512)}),await fe(e,n.tenant_id,{type:pe.FAILED_HOOK,description:h,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:s.hook_id,hook_url:s.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,response:{statusCode:c,body:a?.substring(0,512)}},connection:n.user?.connection,waitForCompletion:!0})}}catch(l){const u=`Failed to invoke hook ${s.hook_id} - ${l instanceof Error?l.message:"Unknown error"}`;console.error(u,l),await fe(e,n.tenant_id,{type:pe.FAILED_HOOK,description:u,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:s.hook_id,hook_url:s.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,error:l instanceof Error?l.message:String(l)},connection:n.user?.connection,waitForCompletion:!0})}}}function QA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="post-user-registration");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function eE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="pre-user-registration");await Pa(e,i,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function tE(e,t){const{hooks:n}=await e.env.data.hooks.list(t);return n.find(r=>r.trigger_id==="validate-registration-username"&&"url"in r&&r.enabled)||null}function nE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="pre-user-deletion");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function rE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="post-user-deletion");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}o.z.object({...ti.shape,tenant:sl,connections:o.z.array(_r)});async function qe(e,t,n){let r,i=n;if(!i){const p=await e.data.clients.getByClientId(t);if(!p)throw new X(403,{message:"Client not found"});const{tenant_id:h,..._}=p;r=_,i=h}const[s,a,c,l]=await Promise.all([r?Promise.resolve(r):e.data.clients.get(i,t),e.data.tenants.get(i),e.data.clientConnections.listByClient(i,t),e.data.connections.list(i)]),u=r||s;if(!u)throw new X(403,{message:"Client not found"});if(!a)throw new X(404,{message:"Tenant not found"});const d=c.length>0?c:l.connections||[],f=wt(e);return{...u,web_origins:[...u.web_origins||[],`${f}login`],allowed_logout_urls:[...u.allowed_logout_urls||[],e.ISSUER],callbacks:[...u.callbacks||[],`${f}info`],tenant:a,connections:d}}function Xm(e){return typeof e.form_id=="string"}function So(e,t){const n=e.match(/^\{\{context\.user\.(.+)\}\}$/);if(n&&n[1])return Ym(t.user,n[1]);const r=e.match(/^\{\{user\.(.+)\}\}$/);if(r&&r[1])return Ym(t.user,r[1]);const i=e.match(/^\{\{\$form\.(.+)\}\}$/);if(i&&i[1]&&t.submittedFields){const s=t.submittedFields[i[1]];return s!==void 0?String(s):void 0}return e}function Ym(e,t){const n=t.split(".");let r=e;for(const i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return typeof r=="string"?r:r==null?void 0:String(r)}function iE(e,t){const n={};for(const[r,i]of Object.entries(e))if(typeof i=="string"){const s=So(i,t);s!==void 0&&(n[r]=s)}else i!=null&&(n[r]=String(i));return n}function Qm(e,t){const n=e.operator?.toLowerCase(),r=e.field?So(e.field,t):"",i=e.value||"";switch(n){case"exists":return r!=null&&r!=="";case"not_exists":return r==null||r==="";case"ends_with":return typeof r=="string"&&r.endsWith(i);case"starts_with":return typeof r=="string"&&r.startsWith(i);case"contains":return typeof r=="string"&&r.includes(i);case"not_contains":return typeof r!="string"||!r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(e.operands&&Array.isArray(e.operands)){for(const s of e.operands)if(s.operator==="ENDS_WITH"&&Array.isArray(s.operands)&&s.operands.length>=2){const a=s.operands[0],c=s.operands[1];if(a&&c){const l=So(`{{context.user.${a}}}`,t);if(typeof l=="string"&&l.endsWith(c))return!0}}}return!1}}function oE(e,t){return e.type==="and"&&Array.isArray(e.conditions)?e.conditions.every(n=>Qm(n,t)):Qm(e,t)}function Au(e,t){const n={};for(const[r,i]of Object.entries(e))if(r.startsWith("user_metadata.")||r.startsWith("metadata.")){const s=r.startsWith("user_metadata.")?r.slice(14):r.slice(9),a=t.user_metadata||{};n.user_metadata={...a,...n.user_metadata||{},[s]:i}}else if(r.startsWith("address.")){const s=r.slice(8),a=t.address||{};n.address={...a,...n.address||{},[s]:i}}else n[r]=i;return n}function Eu(e){const t=new Map;for(const n of e){const r=t.get(n.user_id);r?r.changes={...r.changes,...n.changes}:t.set(n.user_id,{user_id:n.user_id,changes:{...n.changes}})}return Array.from(t.values())}function Cu(e,t,n){switch(e){case"change-email":return`/u/account/change-email?state=${encodeURIComponent(n)}`;case"account":return`/u/account?state=${encodeURIComponent(n)}`;case"custom":if(!t)throw new I(400,{message:"Custom URL is required for custom redirect target"});const r=new URL(t,"http://placeholder");return r.searchParams.set("state",n),r.pathname+r.search;default:throw new I(400,{message:`Unknown redirect target: ${e}`})}}async function Iu(e,t,n,r,i=10){let s=t,a=0;const c=[];for(;a<i;){if(s==="$ending")return{type:"end",userUpdates:c.length>0?c:void 0};const l=e.find(u=>u.id===s);if(!l)return null;if(l.type==="STEP")return{type:"step",nodeId:l.id,userUpdates:c.length>0?c:void 0};if(l.type==="ACTION"){const u=l;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url,userUpdates:c.length>0?c:void 0};s=u.config.next_node,a++;continue}if(l.type==="ROUTER"){const u=l;let d=null;for(const f of u.config.rules)if(oE(f.condition,n)){d=f.next_node;break}if(d||(d=u.config.fallback),!d)return null;s=d,a++;continue}if(l.type==="FLOW"){const u=l;if(r&&u.config.flow_id){const d=await r(u.config.flow_id);if(d&&d.actions&&d.actions.length>0)for(const f of d.actions){if(f.type==="REDIRECT"&&f.action==="REDIRECT_USER"){const p=f.params?.target;if(p)return{type:"redirect",target:p,customUrl:f.params?.custom_url,userUpdates:c.length>0?c:void 0}}if(f.type==="AUTH0"&&f.action==="UPDATE_USER"&&f.params){const p=f.params.user_id&&So(f.params.user_id,n)||n.user.user_id,h=f.params.changes?iE(f.params.changes,n):{};Object.keys(h).length>0&&c.push({user_id:p,changes:h})}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end",userUpdates:c.length>0?c:void 0}}return null}return null}async function sE(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});const c=i?.client_metadata?.universal_login_version==="2"?"/u2":"/u",l=await s.forms.get(a,t);if(!l)throw new I(404,{message:"Form not found for post-user-login hook"});let u=l.start?.next_node;if(!u&&l.nodes&&l.nodes.length>0&&(u=l.nodes.find(p=>p.type==="STEP")?.id),!u)throw new I(400,{message:"No start node found in form"});if(r&&l.nodes){const f=async h=>{const _=await s.flows.get(a,h);return _?{actions:_.actions?.map(g=>({type:g.type,action:g.action,params:"params"in g&&g.params?g.params:void 0}))}:null},p=await Iu(l.nodes,u,{user:r},f);if(p&&p.userUpdates&&p.userUpdates.length>0){const h=Eu(p.userUpdates);for(const _ of h){const g=Au(_.changes,r);await s.users.update(a,_.user_id,g)}}if(!p||p.type==="end")return r;if(p.type==="redirect"){const h=p.target,_=Cu(h,p.customUrl,n.id);if(h==="change-email"||h==="account"){const g=`${c}/continue?state=${encodeURIComponent(n.id)}`;await xu(e,a,n,[h],g)}else await bl(e,a,n,`form:${t}`);return new Response(null,{status:302,headers:{location:_}})}u=p.nodeId}await bl(e,a,n,`form:${t}`);let d=`${c}/forms/${l.id}/nodes/${u}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:d}})}function eg(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function aE(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(f=>f.permission_name===i))return r;await bl(e,a,n,`page:${t}`);let c="/u";if(n.authParams.client_id)try{(await qe(e.env,n.authParams.client_id,a))?.client_metadata?.universal_login_version==="2"&&(c="/u2")}catch{}let l=`${c}/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function hi(e,t){return{createServiceToken:async n=>(await zu(e,t,n.scope,n.expiresInSeconds,n.customClaims)).access_token}}function cE(e){return typeof e.url=="string"}function lE(e,t){return async(n,r)=>{if(e.var.client_id){const a=await qe(e.env,e.var.client_id,e.var.tenant_id);r.email&&await dE(e,a,t,r.email)}const i={method:e.req.method,ip:e.req.query("x-real-ip")||"",user_agent:e.req.query("user-agent"),url:e.var.loginSession?.authorization_url||e.req.url};if(e.env.hooks?.onExecutePreUserRegistration)try{await e.env.hooks.onExecutePreUserRegistration({ctx:e,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c},setLinkedTo:a=>{r.linked_to=a}},token:hi(e,n)})}catch{fe(e,n,{type:pe.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await mz(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:hi(e,n)})}catch{fe(e,n,{type:pe.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await QA(e)(n,s),s}}function uE(e,t){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return t.users.update(n,r,i);const s=await t.users.get(n,r);if(!s)throw new X(404,{message:"User not found"});const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserUpdate)try{await e.env.hooks.onExecutePreUserUpdate({ctx:e,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new X(400,{message:"User update cancelled by pre-update hook"})},token:hi(e,n)})}catch(c){throw fe(e,n,{type:pe.ACTIONS_EXECUTION_FAILED,description:`Pre user update hook failed: ${c instanceof Error?c.message:"Unknown error"}`,userId:r}),new X(400,{message:"Pre user update hook failed"})}if(await t.users.update(n,r,i),i.email||i.email_verified){const c=await t.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),u=l.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);u.length>0&&await t.users.update(n,r,{linked_to:u[0].user_id})}}return i.email&&fe(e,n,{type:pe.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function ju(e,t,n,r,i="email"){if(t.client_metadata?.disable_sign_ups==="true"){const a=e.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await Vo({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"User account does not exist"}}if(e.env.hooks?.onExecuteValidateRegistrationUsername){const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};let c=!1,l;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:u=>{c=!0,l=u},token:hi(e,t.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await tE(e,t.tenant.id);if(s&&"url"in s)try{const a=await zu(e,t.tenant.id,"webhook"),c=await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({tenant_id:t.tenant.id,email:r,connection:i,client_id:t.client_id,trigger_id:"validate-registration-username"})});if(!c.ok)return{allowed:!1,reason:await c.text()||"Signup not allowed by webhook"};const l=await c.json();if(l.allowed===!1)return{allowed:!1,reason:l.reason||"Signup not allowed by webhook"}}catch{fe(e,t.tenant.id,{type:pe.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function dE(e,t,n,r){const i=await ju(e,t,n,r);if(!i.allowed)throw fe(e,t.tenant.id,{type:pe.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new X(400,{message:i.reason||"Signups are disabled for this client"});await eE(e)(t.tenant.id,r)}function pE(e,t){return async(n,r)=>{const i=await t.users.get(n,r);if(!i)return!1;const s={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserDeletion)try{await e.env.hooks.onExecutePreUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new X(400,{message:"User deletion cancelled by pre-deletion hook"})},token:hi(e,n)})}catch(l){throw l instanceof I?l:(fe(e,n,{type:pe.FAILED_HOOK,description:`Pre user deletion hook failed: ${l instanceof Error?l.message:String(l)}`}),new X(400,{message:"Pre user deletion hook failed"}))}try{await nE(e)(n,i)}catch(l){throw fe(e,n,{type:pe.FAILED_HOOK,description:`Pre user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`}),new X(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.list(n,{q:`linked_to:${r}`});for(const l of a.users){const[u,...d]=l.user_id.split("|");u&&await t.users.unlink(n,r,u,d.join("|"))}const c=await t.users.remove(n,r);if(c){fe(e,n,{type:pe.SUCCESS_USER_DELETION,description:`Deleted user: ${i.email||r}`,userId:r,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await rE(e)(n,i)}catch(l){fe(e,n,{type:pe.FAILED_HOOK,description:`Post user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`})}}if(c&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:hi(e,n)})}catch(l){fe(e,n,{type:pe.FAILED_HOOK,description:`Post user deletion hook failed: ${l instanceof Error?l.message:String(l)}`})}return c}}function Ho(e,t){const n=t;return{...t,users:{...t.users,create:lE(e,n),update:uE(e,n),remove:pE(e,n)}}}async function fE(e,t,n,r,i,s){let a=[];try{a=(await t.userRoles.list(n,r.user_id,void 0,"")).map(p=>p.name||p.id)}catch(d){console.error("Error fetching user roles:",d)}let c={};if(r.connection)try{const f=(await t.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(p=>p.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(d){console.error("Error fetching connection info:",d)}let l;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(l={id:d.id,name:d.name,display_name:d.display_name||d.name,metadata:d.metadata||{}})}}catch(d){console.error("Error fetching organization info:",d)}const u=e.get("countryCode");return{ctx:e,client:s.client,user:r,request:{asn:void 0,ip:e.get("ip")||"",user_agent:e.get("useragent"),method:e.req.method,url:e.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:u||void 0,countryName:void 0,latitude:void 0,longitude:void 0,timeZone:void 0}},transaction:{id:i.id,locale:i.authParams?.ui_locales||"en",login_hint:void 0,prompt:i.authParams?.prompt,redirect_uri:i.authParams?.redirect_uri,requested_scopes:i.authParams?.scope?.split(" ")||[],response_mode:i.authParams?.response_mode,response_type:i.authParams?.response_type,state:i.authParams?.state,ui_locales:i.authParams?.ui_locales},scope:s.authParams?.scope||"",grant_type:s.authParams?.grant_type||"",audience:s.authParams?.audience,authentication:{methods:[{name:r.is_social?"federated":"pwd",timestamp:new Date().toISOString()}]},authorization:{roles:a},connection:Object.keys(c).length>0?c:{id:r.connection||"Username-Password-Authentication",name:r.connection||"Username-Password-Authentication",strategy:r.provider||"auth0"},organization:l,resource_server:s.authParams?.audience?{identifier:s.authParams.audience}:void 0,stats:{logins_count:r.login_count||0},tenant:{id:n},session:{id:i.id,created_at:i.created_at,authenticated_at:new Date().toISOString(),clients:[{client_id:s.client.client_id}],device:{initial_ip:e.get("ip"),initial_user_agent:e.get("useragent"),last_ip:r.last_ip||e.get("ip"),last_user_agent:e.get("useragent")}}}}async function A2(e,t,n,r,i,s){const a=s?.authStrategy?.strategy_type?s.authStrategy.strategy_type:r.is_social?"social":"database",c=s?.authStrategy?.strategy||r.connection||"";if(fe(e,n,{type:pe.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id,strategy_type:a,strategy:c,connection:c,audience:s?.authParams?.audience,scope:s?.authParams?.scope}),await t.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:e.var.ip||"",login_count:r.login_count+1}),e.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let p=null;const h=await fE(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(h,{prompt:{render:_=>{}},redirect:{sendUserTo:(_,g)=>{const y=new URL(_,e.req.url);y.searchParams.set("state",i.id),g?.query&&Object.entries(g.query).forEach(([m,w])=>{y.searchParams.set(m,w)}),p=y.toString()},encodeToken:_=>JSON.stringify({payload:_.payload,exp:Date.now()+(_.expiresInSeconds||900)*1e3}),validateToken:_=>null},token:hi(e,n)}),p)return await bl(e,n,i,"onExecutePostLogin"),new Response(null,{status:302,headers:{location:p}})}const{hooks:l}=await t.hooks.list(n),u=l.filter(p=>p.trigger_id==="post-user-login");if(i){const p=u.find(_=>_.enabled&&Xm(_));if(p&&Xm(p))return sE(e,p.form_id,i,r,s?.client);const h=u.find(_=>_.enabled&&eg(_));if(h&&eg(h))return aE(e,h.page_id,i,r,h.permission_required)}const d=u.filter(p=>p.enabled&&fl(p));for(const p of d)if(fl(p))try{r=await $9(e,p.template_id,r)}catch{fe(e,n,{type:pe.FAILED_HOOK,description:`Failed to execute template hook: ${p.template_id}`})}const f=u.filter(p=>p.enabled&&cE(p));return await Pa(e,f,{tenant_id:n,user:r,trigger_id:"post-user-login"}),r}function hE(e){return Ho(e,e.env.data)}async function U0(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Or({userAdapter:e,tenant_id:t,username:n,provider:r}){let i;r==="sms"?i=`phone_number:${n}`:n.includes("@")?i=`email:${n}`:i=`username:${n}`;const{users:s}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`${i} provider:${r}`});return s.length>1&&console.error("More than one user found for same username and provider"),s[0]||null}async function Vo({userAdapter:e,tenant_id:t,email:n}){const{users:r}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`});if(r.length===0)return;const i=r.filter(a=>!a.linked_to);if(i.length>0)return i.length>1&&console.error("More than one primary user found for same email"),i[0];const s=await e.get(t,r[0]?.linked_to);if(!s)throw new Error("Primary account not found");return s}async function Pn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Or({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Nu(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:u=""}=t;let d=await Pn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||Ti()}`,email:i!=="sms"&&n.includes("@")?n:void 0,phone_number:i==="sms"?n:void 0,username:!n.includes("@")&&i!=="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:u,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};d=await hE(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const it=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"Return results inside an object that contains the total result count (true) or as a direct array of results (false, default)."}),from:o.z.string().optional().openapi({description:"Optional Id from which to start selection."}),take:o.z.string().optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. e.g. created_at:1."}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function ft(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}const E2={},_E=Object.freeze(Object.defineProperty({__proto__:null,default:E2},Symbol.toStringTag,{value:"Module"}));var zf=null;function mE(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return E2.randomBytes(e)}catch{}if(!zf)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return zf(e)}function gE(e){zf=e}function B0(e,t){if(e=e||M0,typeof e!="number")throw Error("Illegal arguments: "+typeof e+", "+typeof t);e<4?e=4:e>31&&(e=31);var n=[];return n.push("$2b$"),e<10&&n.push("0"),n.push(e.toString()),n.push("$"),n.push(vl(mE(aa),aa)),n.join("")}function C2(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=M0;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){cn(function(){try{i(null,B0(e))}catch(s){i(s)}})}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);r(n)}else return new Promise(function(i,s){r(function(a,c){if(a){s(a);return}i(c)})})}function I2(e,t){if(typeof t>"u"&&(t=M0),typeof t=="number"&&(t=B0(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return Af(e,t)}function j2(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?C2(t,function(a,c){Af(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?Af(e,t,s,r):cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)))}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function N2(e,t){for(var n=e.length^t.length,r=0;r<e.length;++r)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function yE(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:N2(I2(e,t.substring(0,t.length-31)),t)}function bE(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){cn(s.bind(this,null,!1));return}j2(e,t.substring(0,29),function(a,c){a?s(a):s(null,N2(c,t))},r)}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function vE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function wE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);if(e.length!==60)throw Error("Illegal hash length: "+e.length+" != 60");return e.substring(0,29)}function kE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return T2(e)>72}var cn=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function T2(e){for(var t=0,n=0,r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function $E(e){for(var t=0,n,r,i=new Array(T2(e)),s=0,a=e.length;s<a;++s)n=e.charCodeAt(s),n<128?i[t++]=n:n<2048?(i[t++]=n>>6|192,i[t++]=n&63|128):(n&64512)===55296&&((r=e.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[t++]=n>>18|240,i[t++]=n>>12&63|128,i[t++]=n>>6&63|128,i[t++]=n&63|128):(i[t++]=n>>12|224,i[t++]=n>>6&63|128,i[t++]=n&63|128);return i}var Vi="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),lr=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1];function vl(e,t){var n=0,r=[],i,s;if(t<=0||t>e.length)throw Error("Illegal len: "+t);for(;n<t;){if(i=e[n++]&255,r.push(Vi[i>>2&63]),i=(i&3)<<4,n>=t){r.push(Vi[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(Vi[i&63]),i=(s&15)<<2,n>=t){r.push(Vi[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(Vi[i&63]),r.push(Vi[s&63])}return r.join("")}function P2(e,t){var n=0,r=e.length,i=0,s=[],a,c,l,u,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<lr.length?lr[f]:-1,f=e.charCodeAt(n++),c=f<lr.length?lr[f]:-1,!(a==-1||c==-1||(d=a<<2>>>0,d|=(c&48)>>4,s.push(String.fromCharCode(d)),++i>=t||n>=r)||(f=e.charCodeAt(n++),l=f<lr.length?lr[f]:-1,l==-1)||(d=(c&15)<<4>>>0,d|=(l&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),u=f<lr.length?lr[f]:-1,d=(l&3)<<6>>>0,d|=u,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var aa=16,M0=10,SE=16,xE=100,tg=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],ng=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],O2=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function ca(e,t,n,r){var i,s=e[t],a=e[t+1];return s^=n[0],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[1],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[2],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[3],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[4],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[5],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[6],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[7],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[8],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[9],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[10],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[11],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[12],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[13],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[14],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[15],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[16],e[t]=a^n[SE+1],e[t+1]=s,e}function Zi(e,t){for(var n=0,r=0;n<4;++n)r=r<<8|e[t]&255,t=(t+1)%e.length;return{key:r,offp:t}}function rg(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,l=0;l<s;l++)c=Zi(e,r),r=c.offp,t[l]=t[l]^c.key;for(l=0;l<s;l+=2)i=ca(i,0,t,n),t[l]=i[0],t[l+1]=i[1];for(l=0;l<a;l+=2)i=ca(i,0,t,n),n[l]=i[0],n[l+1]=i[1]}function zE(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,u=0;u<a;u++)l=Zi(t,i),i=l.offp,n[u]=n[u]^l.key;for(i=0,u=0;u<a;u+=2)l=Zi(e,i),i=l.offp,s[0]^=l.key,l=Zi(e,i),i=l.offp,s[1]^=l.key,s=ca(s,0,n,r),n[u]=s[0],n[u+1]=s[1];for(u=0;u<c;u+=2)l=Zi(e,i),i=l.offp,s[0]^=l.key,l=Zi(e,i),i=l.offp,s[1]^=l.key,s=ca(s,0,n,r),r[u]=s[0],r[u+1]=s[1]}function ig(e,t,n,r,i){var s=O2.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){cn(r.bind(this,c));return}else throw c;if(t.length!==aa)if(c=Error("Illegal salt length: "+t.length+" != "+aa),r){cn(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,u,d=0,f;typeof Int32Array=="function"?(l=new Int32Array(tg),u=new Int32Array(ng)):(l=tg.slice(),u=ng.slice()),zE(t,e,l,u);function p(){if(i&&i(d/n),d<n)for(var _=Date.now();d<n&&(d=d+1,rg(e,l,u),rg(t,l,u),!(Date.now()-_>xE)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)ca(s,f<<1,l,u);var g=[];for(d=0;d<a;d++)g.push((s[d]>>24&255)>>>0),g.push((s[d]>>16&255)>>>0),g.push((s[d]>>8&255)>>>0),g.push((s[d]&255)>>>0);if(r){r(null,g);return}else return g}r&&cn(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function Af(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){cn(n.bind(this,i));return}else throw i;var s,a;if(t.charAt(0)!=="$"||t.charAt(1)!=="2")if(i=Error("Invalid salt version: "+t.substring(0,2)),n){cn(n.bind(this,i));return}else throw i;if(t.charAt(2)==="$")s="\0",a=3;else{if(s=t.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||t.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+t.substring(2,4)),n){cn(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){cn(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,l=parseInt(t.substring(a+1,a+2),10),u=c+l,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=$E(e),p=P2(d,aa);function h(_){var g=[];return g.push("$2"),s>="a"&&g.push(s),g.push("$"),u<10&&g.push("0"),g.push(u.toString()),g.push("$"),g.push(vl(p,p.length)),g.push(vl(_,O2.length*4-1)),g.join("")}if(typeof n>"u")return h(ig(f,p,u));ig(f,p,u,function(_,g){_?n(_,null):n(null,h(g))},r)}function AE(e,t){return vl(e,t)}function EE(e,t){return P2(e,t)}const Ko={setRandomFallback:gE,genSaltSync:B0,genSalt:C2,hashSync:I2,hash:j2,compareSync:yE,compare:bE,getRounds:vE,getSalt:wE,truncates:kE,encodeBase64:AE,decodeBase64:EE},ur={TOO_SHORT:"password_too_short",MISSING_LOWERCASE:"password_missing_lowercase",MISSING_UPPERCASE:"password_missing_uppercase",MISSING_NUMBER:"password_missing_number",MISSING_SPECIAL:"password_missing_special",REUSED:"password_reused",CONTAINS_PERSONAL_INFO:"password_contains_personal_info",CONTAINS_FORBIDDEN_WORD:"password_contains_forbidden_word"};class jn extends Error{code;params;constructor(t,n,r){super(n),this.code=t,this.params=r,this.name="PasswordPolicyError"}}async function Oa(e,t){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=t,c=e.passwordPolicy!==void 0||e.password_complexity_options!==void 0||e.password_history!==void 0||e.password_no_personal_info!==void 0||e.password_dictionary!==void 0,l=c?e.passwordPolicy:"good",u=c?e.password_complexity_options?.min_length:8;if(u&&n.length<u)throw new jn(ur.TOO_SHORT,`Password must be at least ${u} characters`,{minLength:u});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new jn(ur.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new jn(ur.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new jn(ur.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new jn(ur.MISSING_SPECIAL,"Password must contain at least one special character")}if(e.password_history?.enable){const d=e.password_history.size||5,f=await i.passwords.list(s,a,d);for(const p of f)if(await Ko.compare(n,p.password))throw new jn(ur.REUSED,"Password was used recently and cannot be reused",{historySize:d})}if(e.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new jn(ur.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(e.password_dictionary?.enable&&e.password_dictionary.dictionary&&e.password_dictionary.dictionary.some(d=>n.toLowerCase().includes(d.toLowerCase())))throw new jn(ur.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Ra(e,t,n){const{connections:r}=await e.connections.list(t,{page:0,per_page:100});return r.find(s=>s.name===n)?.options||{}}async function la(e){return{hash:await Ko.hash(e,10),algorithm:"bcrypt"}}var og;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(og||(og={}));var sg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(sg||(sg={}));function CE(e){return R2(e,IE,ua.Include)}function q0(e){return R2(e,jE,ua.None)}function R2(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===ua.Include&&(r+="=")}return r}const IE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ua;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ua||(ua={}));var ag;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(ag||(ag={}));class NE{uint8(t,n){if(t.byteLength<n+1)throw new TypeError("Insufficient bytes");return t[n]}uint16(t,n){if(t.byteLength<n+2)throw new TypeError("Insufficient bytes");return t[n]<<8|t[n+1]}uint32(t,n){if(t.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=t[n+i]<<24-i*8;return r}uint64(t,n){if(t.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(t[n+i])<<BigInt(56-i*8);return r}putUint8(t,n,r){if(t.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");t[r]=n}putUint16(t,n,r){if(t.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");t[r]=n>>8,t[r+1]=n&255}putUint32(t,n,r){if(t.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)t[r+i]=n>>(3-i)*8&255}putUint64(t,n,r){if(t.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)t[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const cg=new NE;function kn(e,t){return(e<<32-t|e>>>t)>>>0}function TE(e){const t=new PE;return t.update(e),t.digest()}class PE{blockSize=64;size=32;blocks=new Uint8Array(64);currentBlockSize=0;H=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);l=0n;w=new Uint32Array(64);update(t){if(this.l+=BigInt(t.byteLength)*8n,this.currentBlockSize+t.byteLength<64){this.blocks.set(t,this.currentBlockSize),this.currentBlockSize+=t.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=t.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=t.byteLength;){const r=t.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(t.byteLength-n>0){const r=t.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),cg.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)cg.putUint32(t,this.H[n],n*4);return t}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const d=(kn(this.w[u-2],17)^kn(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,f=(kn(this.w[u-15],7)^kn(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=d+this.w[u-7]+f+this.w[u-16]|0}let t=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const d=(kn(s,6)^kn(s,11)^kn(s,25))>>>0,f=(s&a^~s&c)>>>0,p=l+d+f+OE[u]+this.w[u]|0,h=(kn(t,2)^kn(t,13)^kn(t,22))>>>0,_=(t&n^t&r^n&r)>>>0,g=h+_|0;l=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+g|0}this.H[0]=t+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const OE=new Uint32Array([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]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class L2{data;constructor(t){this.data=t}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function D2(e){const t=TE(new TextEncoder().encode(e));return q0(t)}function Tu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),q0(e)}function U2(){const e=new Uint8Array(32);return crypto.getRandomValues(e),q0(e)}function RE(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<e.length&&e[n]===t;)n++;return e.slice(n)}function lg(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=e.length;for(;n>0&&e[n-1]===t;)n--;return e.slice(0,n)}function ug(e,...t){let n=lg(e,"/");for(const r of t)n=lg(n,"/")+"/"+RE(r,"/");return n}function Xn(e,t){const n=new TextEncoder().encode(t.toString()),r=new Request(e,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function ci(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return CE(n)}async function xo(e){let t;try{t=await fetch(e)}catch(n){throw new H0(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=F0(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);return new L2(n)}throw t.body!==null&&await t.body.cancel(),new _o(t.status)}async function LE(e){let t;try{t=await fetch(e)}catch(n){throw new H0(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new kr(t.status,null)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=F0(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){t.body!==null&&await t.body.cancel();return}throw t.body!==null&&await t.body.cancel(),new _o(t.status)}function F0(e){let t;if("error"in e&&typeof e.error=="string")t=e.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in e){if(typeof e.error_description!="string")throw new Error("Invalid data");n=e.error_description}if("error_uri"in e){if(typeof e.error_uri!="string")throw new Error("Invalid data");r=e.error_uri}if("state"in e){if(typeof e.state!="string")throw new Error("Invalid data");i=e.state}return new DE(t,n,r,i)}class H0 extends Error{constructor(t){super("Failed to send request",{cause:t})}}class DE extends Error{code;description;uri;state;constructor(t,n,r,i){super(`OAuth request error: ${t}`),this.code=t,this.description=n,this.uri=r,this.state=i}}class _o extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class kr extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Ri{clientId;clientPassword;redirectURI;constructor(t,n,r){this.clientId=t,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(t,n,r){const i=new URL(t);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(t,n,r,i,s){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===_i.S256){const c=D2(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===_i.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(t,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Xn(t,i);if(this.clientPassword!==null){const c=ci(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await xo(s)}async refreshAccessToken(t,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Xn(t,i);if(this.clientPassword!==null){const c=ci(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await xo(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Xn(t,r);if(this.clientPassword!==null){const s=ci(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await LE(i)}}var _i;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(_i||(_i={}));var dg;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(dg||(dg={}));var pg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(pg||(pg={}));function Hs(e){return UE(e,BE,wl.None)}function UE(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===wl.Include&&(r+="=")}return r}const BE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var wl;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(wl||(wl={}));var fg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(fg||(fg={}));function ME(e,t,n){const r=Hs(new TextEncoder().encode(e)),i=Hs(new TextEncoder().encode(t)),s=Hs(n);return r+"."+i+"."+s}function qE(e,t){const n=Hs(new TextEncoder().encode(e)),r=Hs(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const FE="https://appleid.apple.com/auth/authorize",HE="https://appleid.apple.com/auth/token";class B2{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(t,n,r,i,s){this.clientId=t,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(t,n){const r=new URL(FE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Xn(HE,n);return await xo(i)}async createClientSecret(){const t=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+300,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,qE(r,i)));return ME(r,i,s)}}const VE="https://www.facebook.com/v16.0/dialog/oauth",KE="https://graph.facebook.com/v16.0/oauth/access_token";class M2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(VE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Xn(KE,n);return await xo(r)}}const GE="https://github.com/login/oauth/authorize",hg="https://github.com/login/oauth/access_token";class q2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(GE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=Xn(hg,n),i=ci(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await _g(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Xn(hg,n),i=ci(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await _g(r)}}async function _g(e){let t;try{t=await fetch(e)}catch(i){throw new H0(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new _o(t.status);let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=F0(n)}catch{throw new kr(t.status,n)}throw i}return new L2(n)}const WE="https://accounts.google.com/o/oauth2/v2/auth",mg="https://oauth2.googleapis.com/token",JE="https://oauth2.googleapis.com/revoke";let F2=class{client;constructor(t,n,r){this.client=new Ri(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(WE,t,_i.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(mg,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(mg,t,[])}async revokeToken(t){await this.client.revokeToken(JE,t)}};class H2{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=ug("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=ug("https://login.microsoftonline.com",t,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(t,n,r){const i=new URL(this.authorizationEndpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",t);const s=D2(n);return i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",s),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}async validateAuthorizationCode(t,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",t),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=Xn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=ci(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await xo(i)}async refreshAccessToken(t,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=Xn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=ci(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await xo(i)}}const Go=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Go.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});const ZE="Apple",XE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%200H0V45H45V0Z%22%20fill%3D%22white%22%2F%3E%3Cpath%20d%3D%22M23.5344%2010.3846C25.5313%2010.3846%2028.0344%209.01144%2029.525%207.18055C30.875%205.5213%2031.8594%203.20407%2031.8594%200.886839C31.8594%200.572154%2031.8313%200.25747%2031.775%200C29.5531%200.0858233%2026.8813%201.51621%2025.2781%203.43293C24.0125%204.89193%2022.8594%207.18055%2022.8594%209.52638C22.8594%209.86968%2022.9156%2010.213%2022.9438%2010.3274C23.0844%2010.356%2023.3094%2010.3846%2023.5344%2010.3846ZM16.5031%2045C19.2313%2045%2020.4406%2043.1405%2023.8438%2043.1405C27.3031%2043.1405%2028.0625%2044.9428%2031.1%2044.9428C34.0813%2044.9428%2036.0781%2042.1392%2037.9625%2039.3929C40.0719%2036.246%2040.9438%2033.1564%2041%2033.0134C40.8031%2032.9561%2035.0938%2030.5817%2035.0938%2023.9161C35.0938%2018.1373%2039.5938%2015.534%2039.8469%2015.3338C36.8656%2010.9854%2032.3375%2010.8709%2031.1%2010.8709C27.7531%2010.8709%2025.025%2012.9307%2023.3094%2012.9307C21.4531%2012.9307%2019.0063%2010.9854%2016.1094%2010.9854C10.5969%2010.9854%205%2015.6198%205%2024.3738C5%2029.8093%207.08125%2035.5594%209.64063%2039.2784C11.8344%2042.4253%2013.7469%2045%2016.5031%2045Z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";function V2(e){const{options:t}=e;if(!t||!t.client_id||!t.team_id||!t.kid||!t.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(t.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:t,keyArray:i}}async function YE(e,t){const{options:n,keyArray:r}=V2(t),i=`${Le(e.env)}callback`,s=new B2(n.client_id,n.team_id,n.kid,r,i),a=Oe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(u=>["email","name"].includes(u))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function QE(e,t,n){const{options:r,keyArray:i}=V2(t),a=await new B2(r.client_id,r.team_id,r.kid,i,`${Le(e.env)}callback`).validateAuthorizationCode(n),c=Na(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Go.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const e7=Object.freeze(Object.defineProperty({__proto__:null,displayName:ZE,getRedirect:YE,logoDataUri:XE,validateAuthorizationCodeAndGetUser:QE},Symbol.toStringTag,{value:"Module"})),t7="Facebook",n7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%2022.5C45%2010.0736%2034.9264%200%2022.5%200C10.0736%200%200%2010.0736%200%2022.5C0%2033.7031%208.23242%2042.9785%2019.0039%2044.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039%2011.8945%2022.3828%208.75977%2027.5391%208.75977C29.9658%208.75977%2032.5049%209.19922%2032.5049%209.19922V14.7656H29.7012C26.9414%2014.7656%2026.0156%2016.4824%2026.0156%2018.2432V22.5H32.2412L31.2012%2028.9746H26.0156V44.6953C36.7871%2042.9785%2045%2033.7031%2045%2022.5Z%22%20fill%3D%22%231877F2%22%2F%3E%3Cpath%20d%3D%22M31.2012%2028.9746L32.2412%2022.5H26.0156V18.2432C26.0156%2016.4824%2026.9414%2014.7656%2029.7012%2014.7656H32.5049V9.19922C32.5049%209.19922%2029.9658%208.75977%2027.5391%208.75977C22.3828%208.75977%2019.0039%2011.8945%2019.0039%2017.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562%2044.8984%2021.3203%2045%2022.5%2045C23.6797%2045%2024.8438%2044.8984%2026.0156%2044.6953V28.9746H31.2012Z%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E";async function r7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Le(e.env)}callback`,i=new M2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function i7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new M2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v22.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return e.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const o7=Object.freeze(Object.defineProperty({__proto__:null,displayName:t7,getRedirect:r7,logoDataUri:n7,validateAuthorizationCodeAndGetUser:i7},Symbol.toStringTag,{value:"Module"})),s7="Google",a7=!0,c7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M44.1035%2023.0123C44.1054%2021.4791%2043.9758%2019.9486%2043.716%2018.4375H22.498V27.1028H34.6507C34.4021%2028.4868%2033.8757%2029.8061%2033.1034%2030.9812C32.3311%2032.1562%2031.3289%2033.1628%2030.1571%2033.9401V39.5649H37.41C41.6567%2035.6494%2044.1035%2029.859%2044.1035%2023.0123Z%22%20fill%3D%22%234285F4%22%2F%3E%3Cpath%20d%3D%22M22.4982%2044.9997C28.5698%2044.9997%2033.6821%2043.0061%2037.4101%2039.5687L30.1573%2033.9439C28.1386%2035.3126%2025.5387%2036.0938%2022.4982%2036.0938C16.6296%2036.0938%2011.6485%2032.1377%209.86736%2026.8066H2.39575V32.6033C4.26839%2036.3297%207.13989%2039.4622%2010.6896%2041.6512C14.2394%2043.8402%2018.3277%2044.9995%2022.4982%2044.9997Z%22%20fill%3D%22%2334A853%22%2F%3E%3Cpath%20d%3D%22M9.86737%2026.8073C8.92572%2024.0138%208.92572%2020.9886%209.86737%2018.1951V12.3984H2.39576C0.820432%2015.5332%200%2018.9929%200%2022.5012C0%2026.0095%200.820432%2029.4692%202.39576%2032.604L9.86737%2026.8073Z%22%20fill%3D%22%23FBBC04%22%2F%3E%3Cpath%20d%3D%22M22.4982%208.90741C25.7068%208.85499%2028.8071%2010.0673%2031.1291%2012.2823L37.5507%205.86064C33.4788%202.03602%2028.0843%20-0.0637686%2022.4982%200.00147616C18.3277%200.00166623%2014.2394%201.16098%2010.6896%203.34999C7.13989%205.539%204.26839%208.67155%202.39575%2012.3979L9.86736%2018.1946C11.6485%2012.8635%2016.6296%208.90741%2022.4982%208.90741Z%22%20fill%3D%22%23EA4335%22%2F%3E%3C%2Fsvg%3E";async function l7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Le(e.env)}callback`,i=new F2(n.client_id,n.client_secret,r),s=Oe(),a=Tu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function u7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new F2(i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),c=Na(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Go.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const d7=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:a7,displayName:s7,getRedirect:l7,logoDataUri:c7,validateAuthorizationCodeAndGetUser:u7},Symbol.toStringTag,{value:"Module"})),p7="Vipps",f7="data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%20width%3D%2245%22%20height%3D%2245%22%3E%3Cpath%20fill%3D%22%23FF5B24%22%20d%3D%22M3.5%2C8h41c1.9%2C0%2C3.5%2C1.6%2C3.5%2C3.5v25c0%2C1.9-1.6%2C3.5-3.5%2C3.5h-41C1.6%2C40%2C0%2C38.4%2C0%2C36.5v-25C0%2C9.6%2C1.6%2C8%2C3.5%2C8z%22%2F%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20fill%3D%22%23FFFFFF%22%20d%3D%22M27.9%2C20.3c1.4%2C0%2C2.6-1%2C2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4%2C0-2.6%2C1-2.6%2C2.5C25.3%2C19.2%2C26.5%2C20.3%2C27.9%2C20.3z%20M31.2%2C24.4c-1.7%2C2.2-3.5%2C3.8-6.7%2C3.8h0c-3.2%2C0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8%2C0.6-1%2C1.8-0.3%2C2.9%20c2.7%2C4.1%2C6.5%2C6.6%2C10.9%2C6.6c4%2C0%2C7.2-2%2C9.6-5.2c0.9-1.2%2C0.9-2.5%2C0-3.1C33.3%2C22.9%2C32.1%2C23.2%2C31.2%2C24.4z%22%2F%3E%3C%2Fsvg%3E";async function h7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Ri(n.client_id,n.client_secret,`${Le(e.env)}callback`),i=Oe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,n.scope?.split(" ")||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function _7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Ri(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=Na(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Go.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new X(400,{message:"Failed to get user from vipps"});return await l.json()}const m7=Object.freeze(Object.defineProperty({__proto__:null,displayName:p7,getRedirect:h7,logoDataUri:f7,validateAuthorizationCodeAndGetUser:_7},Symbol.toStringTag,{value:"Module"})),g7="GitHub",y7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M22.5%200C10.074%200%200%2010.335%200%2023.077C0%2033.266%206.444%2041.895%2015.39%2044.955C16.515%2045.165%2016.935%2044.46%2016.935%2043.857C16.935%2043.32%2016.92%2041.865%2016.905%2039.99C10.65%2041.355%209.33%2036.99%209.33%2036.99C8.31%2034.32%206.825%2033.615%206.825%2033.615C4.77%2032.205%206.975%2032.235%206.975%2032.235C9.24%2032.385%2010.425%2034.59%2010.425%2034.59C12.45%2038.13%2015.75%2037.125%2017.01%2036.555C17.22%2035.07%2017.82%2034.065%2018.48%2033.51C13.455%2032.94%208.19%2030.93%208.19%2022.035C8.19%2019.5%209.075%2017.43%2010.47%2015.81C10.23%2015.24%209.435%2012.87%2010.695%209.66C10.695%209.66%2012.585%209.045%2016.875%2012.06C18.675%2011.565%2020.595%2011.31%2022.5%2011.31C24.405%2011.31%2026.325%2011.565%2028.125%2012.06C32.415%209.045%2034.305%209.66%2034.305%209.66C35.565%2012.87%2034.77%2015.24%2034.53%2015.81C35.925%2017.43%2036.81%2019.5%2036.81%2022.035C36.81%2030.96%2031.53%2032.925%2026.49%2033.48C27.33%2034.2%2028.095%2035.625%2028.095%2037.815C28.095%2040.95%2028.065%2043.47%2028.065%2043.857C28.065%2044.46%2028.485%2045.18%2029.625%2044.955C38.571%2041.88%2045%2033.252%2045%2023.077C45%2010.335%2034.926%200%2022.5%200Z%22%20fill%3D%22%23181717%22%2F%3E%3C%2Fsvg%3E";async function b7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${Le(e.env)}callback`,i=new q2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function v7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new q2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json(),l=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});let u=c.email;if(l.ok){const d=await l.json(),f=d.find(p=>p.primary&&p.verified)||d.find(p=>p.verified);f&&(u=f.email)}return e.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:u,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const w7=Object.freeze(Object.defineProperty({__proto__:null,displayName:g7,getRedirect:b7,logoDataUri:y7,validateAuthorizationCodeAndGetUser:v7},Symbol.toStringTag,{value:"Module"})),k7="Microsoft",$7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22%23F25022%22%20d%3D%22M0%200H21.43V21.43H0V0Z%22%2F%3E%3Cpath%20fill%3D%22%237FBA00%22%20d%3D%22M23.57%200H45V21.43H23.57V0Z%22%2F%3E%3Cpath%20fill%3D%22%2300A4EF%22%20d%3D%22M0%2023.57H21.43V45H0V23.57Z%22%2F%3E%3Cpath%20fill%3D%22%23FFB900%22%20d%3D%22M23.57%2023.57H45V45H23.57V23.57Z%22%2F%3E%3C%2Fsvg%3E";async function S7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${Le(e.env)}callback`,i=n.realms||"common",s=new H2(i,n.client_id,n.client_secret,r),a=Oe(),c=Tu();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function x7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new H2(s,i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),l=Na(c.idToken());if(!l)throw new Error("Invalid ID token");const u=Go.parse(l.payload);return e.set("log",`Microsoft user: ${JSON.stringify(u)}`),{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture}}const z7=Object.freeze(Object.defineProperty({__proto__:null,displayName:k7,getRedirect:S7,logoDataUri:$7,validateAuthorizationCodeAndGetUser:x7},Symbol.toStringTag,{value:"Module"})),A7="OpenID Connect",E7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C10.074%200%200%2010.074%200%2022.5S10.074%2045%2022.5%2045%2045%2034.926%2045%2022.5%2034.926%200%2022.5%200zm0%2040.5c-9.941%200-18-8.059-18-18s8.059-18%2018-18%2018%208.059%2018%2018-8.059%2018-18%2018z%22%20fill%3D%22%23F7931E%22%2F%3E%3Cpath%20d%3D%22M22.5%209c-7.456%200-13.5%206.044-13.5%2013.5S15.044%2036%2022.5%2036%2036%2029.956%2036%2022.5%2029.956%209%2022.5%209zm0%2022.5c-4.971%200-9-4.029-9-9s4.029-9%209-9%209%204.029%209%209-4.029%209-9%209z%22%20fill%3D%22%23F7931E%22%2F%3E%3C%2Fsvg%3E";async function C7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${Le(e.env)}callback`,i=new Ri(n.client_id,n.client_secret||null,r),s=U2(),a=Tu(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,_i.S256,a,c).href,code:s,codeVerifier:a}}async function I7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ri(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const u=Na(c.idToken());if(u?.payload){const d=Go.passthrough().parse(u.payload);return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}}if(i.userinfo_endpoint){const u=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!u.ok)throw new Error("Failed to fetch user info");const d=await u.json();if(!d.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const j7=Object.freeze(Object.defineProperty({__proto__:null,displayName:A7,getRedirect:C7,logoDataUri:E7,validateAuthorizationCodeAndGetUser:I7},Symbol.toStringTag,{value:"Module"})),N7="OAuth 2.0",T7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C14.492%200%208%206.492%208%2014.5V18H5v22h35V18h-3v-3.5C37%206.492%2030.508%200%2022.5%200zm0%204c5.799%200%2010.5%204.701%2010.5%2010.5V18h-21v-3.5C12%208.701%2016.701%204%2022.5%204z%22%20fill%3D%22%236B7280%22%2F%3E%3Ccircle%20cx%3D%2222.5%22%20cy%3D%2229%22%20r%3D%223%22%20fill%3D%22%236B7280%22%2F%3E%3C%2Fsvg%3E";async function P7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${Le(e.env)}callback`,i=new Ri(n.client_id,n.client_secret||null,r),s=U2(),a=Tu(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,_i.S256,a,c).href,code:s,codeVerifier:a}}async function O7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ri(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(!i.userinfo_endpoint)throw new Error("Missing userinfo_endpoint for OAuth2 provider");const l=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!l.ok)throw new Error("Failed to fetch user info");const u=await l.json(),d=u.sub||u.id||u.user_id;if(!d)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:d,email:u.email,given_name:u.given_name||u.first_name,family_name:u.family_name||u.last_name,name:u.name||`${u.given_name||u.first_name||""} ${u.family_name||u.last_name||""}`.trim()}}const R7=Object.freeze(Object.defineProperty({__proto__:null,displayName:N7,getRedirect:P7,logoDataUri:T7,validateAuthorizationCodeAndGetUser:O7},Symbol.toStringTag,{value:"Module"})),Pu={apple:e7,facebook:o7,"google-oauth2":d7,vipps:m7,github:w7,microsoft:z7,oidc:j7,oauth2:R7};function K2(e,t){const n=e.env.STRATEGIES||{},i={...Pu,...n}[t];if(!i)throw new Error(`Strategy ${t} not found`);return i}const L7=new Set(["oidc","samlp","waad","adfs","oauth2"]);function G2(e){return L7.has(e.strategy)?e.name:e.strategy}function W2(e){return e.options?.icon_url?e.options.icon_url:Pu[e.strategy]?.logoDataUri}const D7=["email","email_verified","phone_number","phone_verified","username"];function gg(e){const t={connection:e.connection,provider:e.provider,user_id:ff(e.user_id),isSocial:e.is_social};for(const n of D7)e[n]!==void 0&&e[n]!==null&&(t[n]=e[n]);return t}const yg=Nt.extend({users:o.z.array(In)}),U7=Nt.extend({sessions:o.z.array(yu)}),B7=Nt.extend({organizations:o.z.array(mr)}),M7=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:it,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(In),yg])}},description:"List of users"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query");if(s?.includes("identities.profileData.email")){const u=s.split("=")[1],f=(await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,q:`email:${u}`})).users.filter(_=>_.linked_to),[p]=f;if(!p)return e.json([]);const h=await e.env.data.users.get(e.var.tenant_id,p.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return e.json([In.parse(h)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ft(i),q:a.join(" ")}),l=c.users.filter(u=>!u.linked_to);return r?e.json(yg.parse({users:l,length:c.length,start:c.start,limit:c.limit})):e.json(o.z.array(In).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:In}},description:"List of users"}}}),async e=>{const{user_id:t}=e.req.valid("param"),n=await e.env.data.users.get(e.var.tenant_id,t);if(!n)throw new I(404);if(n.linked_to)throw new I(404,{message:"User is linked to another user"});return e.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["delete:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.remove(e.var.tenant_id,t))throw new I(404);return await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),e.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...el.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["create:users","auth:write"]}],responses:{201:{content:{"application/json":{schema:In}},description:"Status"}}}),async e=>{const t=e.req.valid("json");e.set("body",t);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:u}=t,d=await e.env.data.connections.get(e.var.tenant_id,l),f=d?G2(d):c||l,p=t.user_id,h=p?ff(p):Ti(),_=`${f}|${h}`;try{let g;u&&(g=await la(u));const y={email:n,user_id:_,name:i||n||r,phone_number:r,provider:f,connection:l,linked_to:s??void 0,email_verified:a||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString(),...g&&{password:g}},m=await e.env.data.users.create(e.var.tenant_id,y);e.set("user_id",m.user_id),await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"User created"});const w=m.identities?m:{...m,identities:[gg(m)]};return e.json(In.parse(w),{status:201})}catch(g){throw g.message==="User already exists"?new I(409,{message:"User already exists"}):g}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...el.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{data:t}=e.env,n=e.req.valid("json"),{user_id:r}=e.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await t.users.get(e.var.tenant_id,r);if(!l)throw new I(404);if(l.linked_to)throw new I(404,{message:"User is linked to another user"});let u=r,d=l;if(a)if(l.connection===a)u=r,d=l;else{const h=(await t.users.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(_=>_.connection===a);if(!h)throw new I(404,{message:`No identity found with connection: ${a}`});u=h.user_id,d=h}if(c.email&&c.email!==d.email){const p=await U0(e.env.data.users,e.var.tenant_id,c.email);if(p.length&&p.some(h=>h.user_id!==u))throw new I(409,{message:"Another user with the same email address already exists."})}if(await e.env.data.users.update(e.var.tenant_id,u,c),s){let p;if(a)if(a==="Username-Password-Authentication")p={provider:d.provider,user_id:ff(u)};else throw new I(400,{message:`Cannot set password for connection: ${a}`});else if(p=l.identities?.find(m=>m.connection==="Username-Password-Authentication"),!p)throw new I(400,{message:"User does not have a password identity"});const h=`${p.provider}|${p.user_id}`,_=await t.passwords.get(e.var.tenant_id,h);_&&await t.passwords.update(e.var.tenant_id,{id:_.id,user_id:h,password:_.password,algorithm:_.algorithm,is_current:!1});const{hash:g,algorithm:y}=await la(s);await t.passwords.create(e.var.tenant_id,{user_id:h,password:g,algorithm:y,is_current:!0})}const f=await e.env.data.users.get(e.var.tenant_id,r);if(!f)throw new I(500);return await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),e.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.array(Qc)}},description:"Status"}}}),async e=>{const t=e.req.valid("json"),{user_id:n}=e.req.valid("param"),r="link_with"in t?t.link_with:t.user_id,i=await e.env.data.users.get(e.var.tenant_id,n);if(!i)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await e.env.data.users.update(e.var.tenant_id,r,{linked_to:n});const s=await e.env.data.users.list(e.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(gg);return e.json(o.z.array(Qc).parse(a),{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(In)}},description:"Status"}}}),async e=>{const{user_id:t,provider:n,linked_user_id:r}=e.req.valid("param");await e.env.data.users.unlink(e.var.tenant_id,t,n,r);const i=await e.env.data.users.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json([In.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:it,headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(yu),U7])}},description:"List of sessions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{include_totals:n,page:r,per_page:i}=e.req.valid("query"),s=await e.env.data.sessions.list(e.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${t}`});return n?e.json(s):e.json(s.sessions)}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:it},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:Iw}},description:"User permissions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userPermissions.list(e.var.tenant_id,t,{page:n,per_page:r,include_totals:!1,sort:ft(i),q:s});return e.json(c)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.create(e.var.tenant_id,t,{user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new I(500,{message:"Failed to assign permissions to user"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.remove(e.var.tenant_id,t,i))throw new I(500,{message:"Failed to remove permissions from user"});return e.json({message:"Permissions removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:ll}},description:"User roles"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const r=await e.env.data.userRoles.list(e.var.tenant_id,t,void 0,"");return e.json(r)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.create(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to assign roles to user"});return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.remove(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to remove roles from user"});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/organizations",request:{params:o.z.object({user_id:o.z.string()}),query:it,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([B7,o.z.array(mr)])}},description:"List of user organizations"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userOrganizations.listUserOrganizations(e.var.tenant_id,t,{page:n,per_page:r,sort:ft(s)});return i?e.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):e.json(c.organizations)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/organizations/{organization_id}",request:{params:o.z.object({user_id:o.z.string(),organization_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async e=>{const{user_id:t,organization_id:n}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const s=(await e.env.data.userOrganizations.list(e.var.tenant_id,{q:`user_id:${t}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new I(404,{message:"User is not a member of this organization"});return await e.env.data.userOrganizations.remove(e.var.tenant_id,s.id),e.json({message:"User removed from organization successfully"})});var bg={};var vg;function q7(){if(vg)return bg;vg=1;var e;return(function(t){(function(n){var r=typeof globalThis=="object"?globalThis:typeof Nm=="object"?Nm:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(t);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(u,d){return function(f,p){Object.defineProperty(u,f,{configurable:!0,writable:!0,value:p}),d&&d(f,p)}}function a(){try{return Function("return this;")()}catch{}}function c(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return a()||c()}})(function(n,r){var i=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",a=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",c=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!l&&!u,f={create:l?function(){return qd(Object.create(null))}:u?function(){return qd({__proto__:null})}:function(){return qd({})},has:d?function(O,U){return i.call(O,U)}:function(O,U){return U in O},get:d?function(O,U){return i.call(O,U)?O[U]:void 0}:function(O,U){return O[U]}},p=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:pc(),_=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Md(),g=typeof WeakMap=="function"?WeakMap:gS(),y=s?Symbol.for("@reflect-metadata:registry"):void 0,m=Mn(),w=Zt(m);function k(O,U,q,Z){if(F(q)){if(!Y(O))throw new TypeError;if(!me(U))throw new TypeError;return B(O,U)}else{if(!Y(O))throw new TypeError;if(!ue(U))throw new TypeError;if(!ue(Z)&&!F(Z)&&!Pe(Z))throw new TypeError;return Pe(Z)&&(Z=void 0),q=M(q),V(O,U,q,Z)}}n("decorate",k);function S(O,U){function q(Z,de){if(!ue(Z))throw new TypeError;if(!F(de)&&!Ye(de))throw new TypeError;ve(O,U,Z,de)}return q}n("metadata",S);function v(O,U,q,Z){if(!ue(q))throw new TypeError;return F(Z)||(Z=M(Z)),ve(O,U,q,Z)}n("defineMetadata",v);function x(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),L(O,U,q)}n("hasMetadata",x);function A(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),Q(O,U,q)}n("hasOwnMetadata",A);function E(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),ae(O,U,q)}n("getMetadata",E);function P(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),ce(O,U,q)}n("getOwnMetadata",P);function D(O,U){if(!ue(O))throw new TypeError;return F(U)||(U=M(U)),Ee(O,U)}n("getMetadataKeys",D);function C(O,U){if(!ue(O))throw new TypeError;return F(U)||(U=M(U)),le(O,U)}n("getOwnMetadataKeys",C);function R(O,U,q){if(!ue(U))throw new TypeError;if(F(q)||(q=M(q)),!ue(U))throw new TypeError;F(q)||(q=M(q));var Z=Vr(U,q,!1);return F(Z)?!1:Z.OrdinaryDeleteMetadata(O,U,q)}n("deleteMetadata",R);function B(O,U){for(var q=O.length-1;q>=0;--q){var Z=O[q],de=Z(U);if(!F(de)&&!Pe(de)){if(!me(de))throw new TypeError;U=de}}return U}function V(O,U,q,Z){for(var de=O.length-1;de>=0;--de){var nt=O[de],et=nt(U,q,Z);if(!F(et)&&!Pe(et)){if(!ue(et))throw new TypeError;Z=et}}return Z}function L(O,U,q){var Z=Q(O,U,q);if(Z)return!0;var de=ze(U);return Pe(de)?!1:L(O,de,q)}function Q(O,U,q){var Z=Vr(U,q,!1);return F(Z)?!1:Mi(Z.OrdinaryHasOwnMetadata(O,U,q))}function ae(O,U,q){var Z=Q(O,U,q);if(Z)return ce(O,U,q);var de=ze(U);if(!Pe(de))return ae(O,de,q)}function ce(O,U,q){var Z=Vr(U,q,!1);if(!F(Z))return Z.OrdinaryGetOwnMetadata(O,U,q)}function ve(O,U,q,Z){var de=Vr(q,Z,!0);de.OrdinaryDefineOwnMetadata(O,U,q,Z)}function Ee(O,U){var q=le(O,U),Z=ze(O);if(Z===null)return q;var de=Ee(Z,U);if(de.length<=0)return q;if(q.length<=0)return de;for(var nt=new _,et=[],we=0,ee=q;we<ee.length;we++){var re=ee[we],oe=nt.has(re);oe||(nt.add(re),et.push(re))}for(var se=0,ke=de;se<ke.length;se++){var re=ke[se],oe=nt.has(re);oe||(nt.add(re),et.push(re))}return et}function le(O,U){var q=Vr(O,U,!1);return q?q.OrdinaryOwnMetadataKeys(O,U):[]}function Se(O){if(O===null)return 1;switch(typeof O){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return O===null?1:6;default:return 6}}function F(O){return O===void 0}function Pe(O){return O===null}function xt(O){return typeof O=="symbol"}function ue(O){return typeof O=="object"?O!==null:typeof O=="function"}function Xe(O,U){switch(Se(O)){case 0:return O;case 1:return O;case 2:return O;case 3:return O;case 4:return O;case 5:return O}var q="string",Z=Ud(O,a);if(Z!==void 0){var de=Z.call(O,q);if(ue(de))throw new TypeError;return de}return Hr(O)}function Hr(O,U){var q,Z;{var de=O.toString;if(G(de)){var Z=de.call(O);if(!ue(Z))return Z}var q=O.valueOf;if(G(q)){var Z=q.call(O);if(!ue(Z))return Z}}throw new TypeError}function Mi(O){return!!O}function qi(O){return""+O}function M(O){var U=Xe(O);return xt(U)?U:qi(U)}function Y(O){return Array.isArray?Array.isArray(O):O instanceof Object?O instanceof Array:Object.prototype.toString.call(O)==="[object Array]"}function G(O){return typeof O=="function"}function me(O){return typeof O=="function"}function Ye(O){switch(Se(O)){case 3:return!0;case 4:return!0;default:return!1}}function Qe(O,U){return O===U||O!==O&&U!==U}function Ud(O,U){var q=O[U];if(q!=null){if(!G(q))throw new TypeError;return q}}function Bd(O){var U=Ud(O,c);if(!G(U))throw new TypeError;var q=U.call(O);if(!ue(q))throw new TypeError;return q}function Ie(O){return O.value}function xe(O){var U=O.next();return U.done?!1:U}function Fi(O){var U=O.return;U&&U.call(O)}function ze(O){var U=Object.getPrototypeOf(O);if(typeof O!="function"||O===p||U!==p)return U;var q=O.prototype,Z=q&&Object.getPrototypeOf(q);if(Z==null||Z===Object.prototype)return U;var de=Z.constructor;return typeof de!="function"||de===O?U:de}function je(){var O;!F(y)&&typeof r.Reflect<"u"&&!(y in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(O=Ot(r.Reflect));var U,q,Z,de=new g,nt={registerProvider:et,getProvider:ee,setProvider:oe};return nt;function et(se){if(!Object.isExtensible(nt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case O===se:break;case F(U):U=se;break;case U===se:break;case F(q):q=se;break;case q===se:break;default:Z===void 0&&(Z=new _),Z.add(se);break}}function we(se,ke){if(!F(U)){if(U.isProviderFor(se,ke))return U;if(!F(q)){if(q.isProviderFor(se,ke))return U;if(!F(Z))for(var Re=Bd(Z);;){var Ke=xe(Re);if(!Ke)return;var Xt=Ie(Ke);if(Xt.isProviderFor(se,ke))return Fi(Re),Xt}}}if(!F(O)&&O.isProviderFor(se,ke))return O}function ee(se,ke){var Re=de.get(se),Ke;return F(Re)||(Ke=Re.get(ke)),F(Ke)&&(Ke=we(se,ke),F(Ke)||(F(Re)&&(Re=new h,de.set(se,Re)),Re.set(ke,Ke))),Ke}function re(se){if(F(se))throw new TypeError;return U===se||q===se||!F(Z)&&Z.has(se)}function oe(se,ke,Re){if(!re(Re))throw new Error("Metadata provider not registered.");var Ke=ee(se,ke);if(Ke!==Re){if(!F(Ke))return!1;var Xt=de.get(se);F(Xt)&&(Xt=new h,de.set(se,Xt)),Xt.set(ke,Re)}return!0}}function Mn(){var O;return!F(y)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&(O=r.Reflect[y]),F(O)&&(O=je()),!F(y)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:O}),O}function Zt(O){var U=new g,q={isProviderFor:function(re,oe){var se=U.get(re);return F(se)?!1:se.has(oe)},OrdinaryDefineOwnMetadata:et,OrdinaryHasOwnMetadata:de,OrdinaryGetOwnMetadata:nt,OrdinaryOwnMetadataKeys:we,OrdinaryDeleteMetadata:ee};return m.registerProvider(q),q;function Z(re,oe,se){var ke=U.get(re),Re=!1;if(F(ke)){if(!se)return;ke=new h,U.set(re,ke),Re=!0}var Ke=ke.get(oe);if(F(Ke)){if(!se)return;if(Ke=new h,ke.set(oe,Ke),!O.setProvider(re,oe,q))throw ke.delete(oe),Re&&U.delete(re),new Error("Wrong provider for target.")}return Ke}function de(re,oe,se){var ke=Z(oe,se,!1);return F(ke)?!1:Mi(ke.has(re))}function nt(re,oe,se){var ke=Z(oe,se,!1);if(!F(ke))return ke.get(re)}function et(re,oe,se,ke){var Re=Z(se,ke,!0);Re.set(re,oe)}function we(re,oe){var se=[],ke=Z(re,oe,!1);if(F(ke))return se;for(var Re=ke.keys(),Ke=Bd(Re),Xt=0;;){var pm=xe(Ke);if(!pm)return se.length=Xt,se;var yS=Ie(pm);try{se[Xt]=yS}catch(bS){try{Fi(Ke)}finally{throw bS}}Xt++}}function ee(re,oe,se){var ke=Z(oe,se,!1);if(F(ke)||!ke.delete(re))return!1;if(ke.size===0){var Re=U.get(oe);F(Re)||(Re.delete(se),Re.size===0&&U.delete(Re))}return!0}}function Ot(O){var U=O.defineMetadata,q=O.hasOwnMetadata,Z=O.getOwnMetadata,de=O.getOwnMetadataKeys,nt=O.deleteMetadata,et=new g,we={isProviderFor:function(ee,re){var oe=et.get(ee);return!F(oe)&&oe.has(re)?!0:de(ee,re).length?(F(oe)&&(oe=new _,et.set(ee,oe)),oe.add(re),!0):!1},OrdinaryDefineOwnMetadata:U,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:Z,OrdinaryOwnMetadataKeys:de,OrdinaryDeleteMetadata:nt};return we}function Vr(O,U,q){var Z=m.getProvider(O,U);if(!F(Z))return Z;if(q){if(m.setProvider(O,U,w))return w;throw new Error("Illegal state.")}}function pc(){var O={},U=[],q=(function(){function we(ee,re,oe){this._index=0,this._keys=ee,this._values=re,this._selector=oe}return we.prototype["@@iterator"]=function(){return this},we.prototype[c]=function(){return this},we.prototype.next=function(){var ee=this._index;if(ee>=0&&ee<this._keys.length){var re=this._selector(this._keys[ee],this._values[ee]);return ee+1>=this._keys.length?(this._index=-1,this._keys=U,this._values=U):this._index++,{value:re,done:!1}}return{value:void 0,done:!0}},we.prototype.throw=function(ee){throw this._index>=0&&(this._index=-1,this._keys=U,this._values=U),ee},we.prototype.return=function(ee){return this._index>=0&&(this._index=-1,this._keys=U,this._values=U),{value:ee,done:!0}},we})(),Z=(function(){function we(){this._keys=[],this._values=[],this._cacheKey=O,this._cacheIndex=-2}return Object.defineProperty(we.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),we.prototype.has=function(ee){return this._find(ee,!1)>=0},we.prototype.get=function(ee){var re=this._find(ee,!1);return re>=0?this._values[re]:void 0},we.prototype.set=function(ee,re){var oe=this._find(ee,!0);return this._values[oe]=re,this},we.prototype.delete=function(ee){var re=this._find(ee,!1);if(re>=0){for(var oe=this._keys.length,se=re+1;se<oe;se++)this._keys[se-1]=this._keys[se],this._values[se-1]=this._values[se];return this._keys.length--,this._values.length--,Qe(ee,this._cacheKey)&&(this._cacheKey=O,this._cacheIndex=-2),!0}return!1},we.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=O,this._cacheIndex=-2},we.prototype.keys=function(){return new q(this._keys,this._values,de)},we.prototype.values=function(){return new q(this._keys,this._values,nt)},we.prototype.entries=function(){return new q(this._keys,this._values,et)},we.prototype["@@iterator"]=function(){return this.entries()},we.prototype[c]=function(){return this.entries()},we.prototype._find=function(ee,re){if(!Qe(this._cacheKey,ee)){this._cacheIndex=-1;for(var oe=0;oe<this._keys.length;oe++)if(Qe(this._keys[oe],ee)){this._cacheIndex=oe;break}}return this._cacheIndex<0&&re&&(this._cacheIndex=this._keys.length,this._keys.push(ee),this._values.push(void 0)),this._cacheIndex},we})();return Z;function de(we,ee){return we}function nt(we,ee){return ee}function et(we,ee){return[we,ee]}}function Md(){var O=(function(){function U(){this._map=new h}return Object.defineProperty(U.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),U.prototype.has=function(q){return this._map.has(q)},U.prototype.add=function(q){return this._map.set(q,q),this},U.prototype.delete=function(q){return this._map.delete(q)},U.prototype.clear=function(){this._map.clear()},U.prototype.keys=function(){return this._map.keys()},U.prototype.values=function(){return this._map.keys()},U.prototype.entries=function(){return this._map.entries()},U.prototype["@@iterator"]=function(){return this.keys()},U.prototype[c]=function(){return this.keys()},U})();return O}function gS(){var O=16,U=f.create(),q=Z();return(function(){function ee(){this._key=Z()}return ee.prototype.has=function(re){var oe=de(re,!1);return oe!==void 0?f.has(oe,this._key):!1},ee.prototype.get=function(re){var oe=de(re,!1);return oe!==void 0?f.get(oe,this._key):void 0},ee.prototype.set=function(re,oe){var se=de(re,!0);return se[this._key]=oe,this},ee.prototype.delete=function(re){var oe=de(re,!1);return oe!==void 0?delete oe[this._key]:!1},ee.prototype.clear=function(){this._key=Z()},ee})();function Z(){var ee;do ee="@@WeakMap@@"+we();while(f.has(U,ee));return U[ee]=!0,ee}function de(ee,re){if(!i.call(ee,q)){if(!re)return;Object.defineProperty(ee,q,{value:f.create()})}return ee[q]}function nt(ee,re){for(var oe=0;oe<re;++oe)ee[oe]=Math.random()*255|0;return ee}function et(ee){if(typeof Uint8Array=="function"){var re=new Uint8Array(ee);return typeof crypto<"u"?crypto.getRandomValues(re):typeof msCrypto<"u"?msCrypto.getRandomValues(re):nt(re,ee),re}return nt(new Array(ee),ee)}function we(){var ee=et(O);ee[6]=ee[6]&79|64,ee[8]=ee[8]&191|128;for(var re="",oe=0;oe<O;++oe){var se=ee[oe];(oe===4||oe===6||oe===8)&&(re+="-"),se<16&&(re+="0"),re+=se.toString(16).toLowerCase()}return re}}function qd(O){return O.__=void 0,delete O.__,O}})})(e||(e={})),bg}q7();const F7="[object ArrayBuffer]";class J{static isArrayBuffer(t){return Object.prototype.toString.call(t)===F7}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,n){if(t.constructor===n)return t;if(this.isArrayBuffer(t))return new n(t);if(this.isArrayBufferView(t))return new n(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,n){const r=J.toUint8Array(t),i=J.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let s=0;s<r.length;s++)if(r[s]!==i[s])return!1;return!0}static concat(...t){let n;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?n=t[0]:t[t.length-1]instanceof Function?n=t.slice(0,t.length-1):n=t;let r=0;for(const a of n)r+=a.byteLength;const i=new Uint8Array(r);let s=0;for(const a of n){const c=this.toUint8Array(a);i.set(c,s),s+=c.length}return t[t.length-1]instanceof Function?this.toView(i,t[t.length-1]):i.buffer}}const Jd="string",H7=/^[0-9a-f\s]+$/i,V7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,K7=/^[a-zA-Z0-9-_]+$/;class wg{static fromString(t){const n=unescape(encodeURIComponent(t)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(t){const n=J.toUint8Array(t);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class $n{static toString(t,n=!1){const r=J.toArrayBuffer(t),i=new DataView(r);let s="";for(let a=0;a<r.byteLength;a+=2){const c=i.getUint16(a,n);s+=String.fromCharCode(c)}return s}static fromString(t,n=!1){const r=new ArrayBuffer(t.length*2),i=new DataView(r);for(let s=0;s<t.length;s++)i.setUint16(s*2,t.charCodeAt(s),n);return r}}class ie{static isHex(t){return typeof t===Jd&&H7.test(t)}static isBase64(t){return typeof t===Jd&&V7.test(t)}static isBase64Url(t){return typeof t===Jd&&K7.test(t)}static ToString(t,n="utf8"){const r=J.toUint8Array(t);switch(n.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return $n.toString(r,!0);case"utf16":case"utf16be":return $n.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(t,n="utf8"){if(!t)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return $n.fromString(t,!0);case"utf16":case"utf16be":return $n.fromString(t);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(t){const n=J.toUint8Array(t);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64(n))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,"base64")).buffer}static FromBase64Url(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(t);case"utf8":return wg.fromString(t);case"utf16":case"utf16be":return $n.fromString(t);case"utf16le":case"usc2":return $n.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(t);case"utf8":return wg.toString(t);case"utf16":case"utf16be":return $n.toString(t);case"utf16le":case"usc2":return $n.toString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(t){const n=t.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=t.charCodeAt(i);return r.buffer}static ToBinary(t){const n=J.toUint8Array(t);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(t){const n=J.toUint8Array(t);let r="";const i=n.length;for(let s=0;s<i;s++){const a=n[s];a<16&&(r+="0"),r+=a.toString(16)}return r}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isHex(n))throw new TypeError("Argument 'hexString' is not HEX encoded");n.length%2&&(n=`0${n}`);const r=new Uint8Array(n.length/2);for(let i=0;i<n.length;i=i+2){const s=n.slice(i,i+2);r[i/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(t,n=!1){return $n.toString(t,n)}static FromUtf16String(t,n=!1){return $n.fromString(t,n)}static Base64Padding(t){const n=4-t.length%4;if(n<4)for(let r=0;r<n;r++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}}ie.DEFAULT_UTF8_ENCODING="utf8";function G7(...e){const t=e.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(t);let r=0;return e.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function J2(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<e.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function zo(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*Math.pow(2,t*r);return n}function mi(e,t,n=-1){const r=n;let i=e,s=0,a=Math.pow(2,t);for(let c=1;c<8;c++){if(e<a){let l;if(r<0)l=new ArrayBuffer(c),s=c;else{if(r<c)return new ArrayBuffer(0);l=new ArrayBuffer(r),s=r}const u=new Uint8Array(l);for(let d=c-1;d>=0;d--){const f=Math.pow(2,d*t);u[s-d-1]=Math.floor(i/f),i-=u[s-d-1]*f}return l}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ef(...e){let t=0,n=0;for(const s of e)t+=s.length;const r=new ArrayBuffer(t),i=new Uint8Array(r);for(const s of e)i.set(s,n),n+=s.length;return i}function Z2(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=e[0]===255&&e[1]&128,l=e[0]===0&&(e[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=e[0]&128;const r=zo(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=e[c];return s[0]&=127,zo(s,8)-r}function W7(e){const t=e<0?e*-1:e;let n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){const a=n-t,c=mi(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=mi(t,8,r),s=new Uint8Array(i);if(s[0]&128){const a=i.slice(0),c=new Uint8Array(a);i=new ArrayBuffer(i.byteLength+1),s=new Uint8Array(i);for(let l=0;l<a.byteLength;l++)s[l+1]=c[l];s[0]=0}return i}n*=Math.pow(2,8)}return new ArrayBuffer(0)}function J7(e,t){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function Rt(e,t){const n=e.toString(10);if(t<n.length)return"";const r=t-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function kl(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function V0(e){let t=0,n=0;for(let i=0;i<e.length;i++){const s=e[i];t+=s.byteLength}const r=new Uint8Array(t);for(let i=0;i<e.length;i++){const s=e[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function or(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-n-r<0?(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Ou{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return V0(this.items)}}const ps=[new Uint8Array([1])],kg="0123456789",Zd="name",$g="valueHexView",Z7="isHexOnly",X7="idBlock",Y7="tagClass",Q7="tagNumber",eC="isConstructed",tC="fromBER",nC="toBER",rC="local",It="",Ln=new ArrayBuffer(0),Ru=new Uint8Array(0),da="EndOfContent",X2="OCTET STRING",Y2="BIT STRING";function Dn(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(r){this.valueHexView=new Uint8Array(r)}constructor(...r){var i;super(...r);const s=r[0]||{};this.isHexOnly=(i=s.isHexOnly)!==null&&i!==void 0?i:!1,this.valueHexView=s.valueHex?J.toUint8Array(s.valueHex):Ru}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!or(this,a,i,s))return-1;const c=i+s;return this.valueHexView=a.subarray(i,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),i)}toBER(r=!1){return this.isHexOnly?r?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Ln)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ie.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Li{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}constructor({blockLength:t=0,error:n=It,warnings:r=[],valueBeforeDecode:i=Ru}={}){this.blockLength=t,this.error=n,this.warnings=r,this.valueBeforeDecodeView=J.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ie.ToHex(this.valueBeforeDecodeView)}}}Li.NAME="baseBlock";class $t extends Li{fromBER(t,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}$t.NAME="valueBlock";class Q2 extends Dn(Li){constructor({idBlock:t={}}={}){var n,r,i,s;super(),t?(this.isHexOnly=(n=t.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=t.valueHex?J.toUint8Array(t.valueHex):Ru,this.tagClass=(r=t.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=t.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let n=0;switch(this.tagClass){case 1:n|=0;break;case 2:n|=64;break;case 3:n|=128;break;case 4:n|=192;break;default:return this.error="Unknown tag class",Ln}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=mi(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!t){for(let l=0;l<a-1;l++)c[l+1]=s[l]|128;c[a]=s[a-1]}return c.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=n|31,!t){const i=this.valueHexView;for(let s=0;s<i.length-1;s++)r[s+1]=i[s]|128;r[this.valueHexView.byteLength]=i[i.length-1]}return r.buffer}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const c=s[0]&31;if(c!==31)this.tagNumber=c,this.blockLength=1;else{let l=1,u=this.valueHexView=new Uint8Array(255),d=255;for(;s[l]&128;){if(u[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===d){d+=255;const p=new Uint8Array(d);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(d)}}this.blockLength=l+1,u[l-1]=s[l]&127;const f=new Uint8Array(l);for(let p=0;p<l;p++)f[p]=u[p];u=this.valueHexView=new Uint8Array(l),u.set(f),this.blockLength<=9?this.tagNumber=zo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return n+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Q2.NAME="identificationBlock";class e3 extends Li{constructor({lenBlock:t={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=t.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=t.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=t.length)!==null&&i!==void 0?i:0}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,n+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,n+this.blockLength;const a=s[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const c=n+1,l=i.subarray(c,c+a);return l[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=zo(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(t=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=mi(this.length,8);if(i.byteLength>127)return this.error="Too big length",Ln;if(n=new ArrayBuffer(i.byteLength+1),t)return n;const s=new Uint8Array(i);r=new Uint8Array(n),r[0]=i.byteLength|128;for(let a=0;a<i.byteLength;a++)r[a+1]=s[a];return n}return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}e3.NAME="lengthBlock";const ne={};class ct extends Li{constructor({name:t=It,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=t,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new Q2(i),this.lenBlock=new e3(i),this.valueBlock=s?new s(i):new $t(i)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(t,n){const r=n||new Ou;n||t3(this);const i=this.idBlock.toBER(t);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(t);r.write(a),r.write(s)}return n?Ln:r.final()}toJSON(){const t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():ie.ToHex(this.toBER())}onAsciiEncoding(){const t=this.constructor.NAME,n=ie.ToHex(this.valueBlock.valueBeforeDecodeView);return`${t} : ${n}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;const n=this.toBER(),r=t.toBER();return J7(n,r)}}ct.NAME="BaseBlock";function t3(e){var t;if(e instanceof ne.Constructed)for(const n of e.valueBlock.value)t3(n)&&(e.lenBlock.isIndefiniteForm=!0);return!!(!((t=e.lenBlock)===null||t===void 0)&&t.isIndefiniteForm)}class K0 extends ct{getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}constructor({value:t=It,...n}={},r){super(n,r),t&&this.fromString(t)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}K0.NAME="BaseStringBlock";class n3 extends Dn($t){constructor({isHexOnly:t=!0,...n}={}){super(n),this.isHexOnly=t}}n3.NAME="PrimitiveValueBlock";var r3;class La extends ct{constructor(t={}){super(t,n3),this.idBlock.isConstructed=!1}}r3=La;ne.Primitive=r3;La.NAME="PRIMITIVE";function iC(e,t){if(e instanceof t)return e;const n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function Wo(e,t=0,n=e.length){const r=t;let i=new ct({},$t);const s=new Li;if(!or(s,e,t,n))return i.error=s.error,{offset:-1,result:i};if(!e.subarray(t,t+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(e,t,n);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),c===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(e,t,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=c,n-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let l=ct;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};l=ne.EndOfContent;break;case 1:l=ne.Boolean;break;case 2:l=ne.Integer;break;case 3:l=ne.BitString;break;case 4:l=ne.OctetString;break;case 5:l=ne.Null;break;case 6:l=ne.ObjectIdentifier;break;case 10:l=ne.Enumerated;break;case 12:l=ne.Utf8String;break;case 13:l=ne.RelativeObjectIdentifier;break;case 14:l=ne.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=ne.Sequence;break;case 17:l=ne.Set;break;case 18:l=ne.NumericString;break;case 19:l=ne.PrintableString;break;case 20:l=ne.TeletexString;break;case 21:l=ne.VideotexString;break;case 22:l=ne.IA5String;break;case 23:l=ne.UTCTime;break;case 24:l=ne.GeneralizedTime;break;case 25:l=ne.GraphicString;break;case 26:l=ne.VisibleString;break;case 27:l=ne.GeneralString;break;case 28:l=ne.UniversalString;break;case 29:l=ne.CharacterString;break;case 30:l=ne.BmpString;break;case 31:l=ne.DATE;break;case 32:l=ne.TimeOfDay;break;case 33:l=ne.DateTime;break;case 34:l=ne.Duration;break;default:{const u=i.idBlock.isConstructed?new ne.Constructed:new ne.Primitive;u.idBlock=i.idBlock,u.lenBlock=i.lenBlock,u.warnings=i.warnings,i=u}}break;default:l=i.idBlock.isConstructed?ne.Constructed:ne.Primitive}return i=iC(i,l),c=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(r,r+i.blockLength),{offset:c,result:i}}function mo(e){if(!e.byteLength){const t=new ct({},$t);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Wo(J.toUint8Array(e).slice(),0,e.byteLength)}function oC(e,t){return e?1:t}class $r extends $t{constructor({value:t=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=t,this.isIndefiniteForm=n}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;if(this.valueBeforeDecodeView=i.subarray(n,n+r),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),n;let s=n;for(;oC(this.isIndefiniteForm,r)>0;){const a=Wo(i,s,r);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(s=a.offset,this.blockLength+=a.result.blockLength,r-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===da)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===da?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,n){const r=n||new Ou;for(let i=0;i<this.value.length;i++)this.value[i].toBER(t,r);return n?Ln:r.final()}toJSON(){const t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)t.value.push(n.toJSON());return t}}$r.NAME="ConstructedValueBlock";var i3;class kt extends ct{constructor(t={}){super(t,$r),this.idBlock.isConstructed=!0}fromBER(t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){const t=[];for(const r of this.valueBlock.value)t.push(r.toString("ascii").split(`
67
+ ${f.message}`)}if(d){i.push(...c.actions),s=c;break}}return s?[s]:void 0}get events(){return Hi(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const s of i.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),n=new Set(t.filter(r=>this.transitions.get(r).some(i=>!(!i.target&&!i.actions.length&&!i.reenter))));return Array.from(n)}}const IA="#";class L0{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new yl(t,{_key:this.id,_machine:this}),this.root._initialize(),Q9(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:s}=this.implementations;return new L0(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...s,...t.delays}})}resolveState(t){const n=mA(this.root,t.value),r=_l(gl(this.root,n));return Rc({_nodes:[...r],context:t.context||{},children:{},status:T0(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return Wd(t,n,r,[]).snapshot}microstep(t,n,r){return Wd(t,n,r,[]).microsteps.map(([i])=>i)}getTransitionData(t,n){return P0(this.root,t.value,t,n)||[]}_getPreInitialState(t,n,r){const{context:i}=this.config,s=Rc({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?$o(s,n,t,[Gn(({spawn:c,event:l,self:u})=>i({spawn:c,input:l.input,self:u}))],r,void 0):s}getInitialSnapshot(t,n){const r=o2(n),i=[],s=this._getPreInitialState(t,r,i),[a]=lA(this.root,s,t,r,i),{snapshot:c}=Wd(a,r,t,i);return c}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=A0(t),r=n.slice(1),i=$u(n[0])?n[0].slice(IA.length):n[0],s=this.idMap.get(i);if(!s)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return ml(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return SA(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(f=>{const p=i[f],h=p.snapshot,_=p.src,g=typeof _=="string"?E0(this,_):_;if(!g)return;const y=oa(g,{id:f,parent:n.self,syncSnapshot:p.syncSnapshot,snapshot:h,src:_,systemId:p.systemId});r[f]=y});function s(f,p){if(p instanceof yl)return p;try{return f.machine.getStateNodeById(p.id)}catch{}}function a(f,p){if(!p||typeof p!="object")return{};const h={};for(const _ in p){const g=p[_];for(const y of g){const m=s(f,y);m&&(h[_]??=[],h[_].push(m))}}return h}const c=a(this.root,t.historyValue),l=Rc({...t,children:r,_nodes:Array.from(_l(gl(this.root,t.value))),historyValue:c},this),u=new Set;function d(f,p){if(!u.has(f)){u.add(f);for(const h in f){const _=f[h];if(_&&typeof _=="object"){if("xstate$$type"in _&&_.xstate$$type===C0){f[h]=p[_.id];continue}d(_,p)}}}}return d(l.context,r),l}}function jA(e,t,n,r,{event:i}){const s=typeof i=="function"?i(n,r):i;return[t,{event:s},void 0]}function NA(e,{event:t}){e.defer(()=>e.emit(t))}function w2(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=jA,t.execute=NA,t}let Sf=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function TA(e,t,n,r,{to:i,event:s,id:a,delay:c},l){const u=t.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const d=typeof s=="function"?s(n,r):s;let f;if(typeof c=="string"){const _=u&&u[c];f=typeof _=="function"?_(n,r):_}else f=typeof c=="function"?c(n,r):c;const p=typeof i=="function"?i(n,r):i;let h;if(typeof p=="string"){if(p===Sf.Parent?h=e.self._parent:p===Sf.Internal?h=e.self:p.startsWith("#_")?h=t.children[p.slice(2)]:h=l.deferredActorIds?.includes(p)?p:t.children[p],!h)throw new Error(`Unable to send event to actor '${p}' from machine '${t.machine.id}'.`)}else h=p||e.self;return[t,{to:h,targetId:typeof p=="string"?p:void 0,event:d,id:a,delay:f},void 0]}function PA(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function OA(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:s}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,s);return}e.system._relay(e.self,n,r.type===T9?i2(e.self.id,r.data):r)})}function D0(e,t,n){function r(i,s){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=TA,r.retryResolve=PA,r.execute=OA,r}function RA(e,t){return D0(Sf.Parent,e,t)}function LA(e,t,n,r,{collect:i}){const s=[],a=function(l){s.push(l)};return a.assign=(...c)=>{s.push(Gn(...c))},a.cancel=(...c)=>{s.push(I0(...c))},a.raise=(...c)=>{s.push(R0(...c))},a.sendTo=(...c)=>{s.push(D0(...c))},a.sendParent=(...c)=>{s.push(RA(...c))},a.spawnChild=(...c)=>{s.push(j0(...c))},a.stopChild=(...c)=>{s.push(wu(...c))},a.emit=(...c)=>{s.push(w2(...c))},i({context:n.context,event:n.event,enqueue:a,check:c=>ku(c,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,s]}function DA(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=LA,t}function UA(e,t,n,r,{value:i,label:s}){return[t,{value:typeof i=="function"?i(n,r):i,label:s},void 0]}function BA({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function MA(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=UA,n.execute=BA,n}function qA(e,t){return new L0(e,t)}function FA(e){const t=oa(e);return{self:t,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:t.system,emit:()=>{},actionExecutor:()=>{}}}function k2({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Gn,sendTo:D0,raise:R0,log:MA,cancel:I0,stopChild:wu,enqueueActions:DA,emit:w2,spawnChild:j0,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>qA({...s,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:s=>k2({schemas:e,actors:t,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...i,...s.delays}})}}function HA(e,t,n){const r=[],i=FA(e);return i.actionExecutor=a=>{r.push(a)},[e.transition(t,n,i),r]}var Pr=(e=>(e.AUTHENTICATE="AUTHENTICATE",e.REQUIRE_EMAIL_VERIFICATION="REQUIRE_EMAIL_VERIFICATION",e.START_HOOK="START_HOOK",e.COMPLETE_HOOK="COMPLETE_HOOK",e.START_CONTINUATION="START_CONTINUATION",e.COMPLETE_CONTINUATION="COMPLETE_CONTINUATION",e.COMPLETE="COMPLETE",e.FAIL="FAIL",e.EXPIRE="EXPIRE",e))(Pr||{});const $2=k2({actions:{setUserId:Gn(({event:e})=>e.type==="AUTHENTICATE"?{userId:e.userId}:{}),setHookId:Gn(({event:e})=>e.type==="START_HOOK"?{hookId:e.hookId}:{}),clearHookId:Gn({hookId:void 0}),setContinuationScope:Gn(({event:e})=>e.type==="START_CONTINUATION"?{continuationScope:e.scope}:{}),clearContinuationScope:Gn({continuationScope:void 0}),setFailureReason:Gn(({event:e})=>e.type==="FAIL"?{failureReason:e.reason}:{})}}).createMachine({id:"loginSession",initial:"pending",context:{},states:{pending:{on:{AUTHENTICATE:{target:"authenticated",actions:"setUserId"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},authenticated:{on:{REQUIRE_EMAIL_VERIFICATION:{target:"awaiting_email_verification"},START_HOOK:{target:"awaiting_hook",actions:"setHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},COMPLETE:{target:"completed"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_email_verification:{on:{COMPLETE:{target:"authenticated"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_hook:{on:{COMPLETE_HOOK:{target:"authenticated",actions:"clearHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_continuation:{on:{COMPLETE_CONTINUATION:{target:"authenticated",actions:"clearContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},completed:{type:"final"},failed:{type:"final"},expired:{type:"final"}}});function VA(e,t={}){return $2.resolveState({value:e,context:t})}function Oi(e,t,n={}){const r=VA(e,n),[i]=HA($2,r,t),s={},a=i.context,c=n;return a.userId!==c.userId&&(s.userId=a.userId),a.hookId!==c.hookId&&(s.hookId=a.hookId),a.continuationScope!==c.continuationScope&&(s.continuationScope=a.continuationScope),a.failureReason!==c.failureReason&&(s.failureReason=a.failureReason),{state:i.value,context:s}}function S2(e,t){Object.keys(t).forEach(n=>{const r=t[n];r!=null&&r.length&&e.searchParams.set(n,r)})}function KA(e){try{const t=typeof e=="string"?new URL(e):e;let n=`${t.protocol}//${t.host}${t.pathname}`;if(t.search){const r=Array.from(t.searchParams.keys()).map(i=>`${i}=[REDACTED]`).join("&");n+=`?${r}`}return t.hash&&(n+="#[REDACTED]"),n}catch{const n=(typeof e=="string"?e:e.toString()).match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!n)return"[invalid-url]";const[,r="",i,s]=n;let a=r;if(i){const c=i.substring(1).split("&").map(l=>{const[u]=l.split("=");return`${u}=[REDACTED]`}).join("&");a+=`?${c}`}return s&&(a+="#[REDACTED]"),a}}const xf=["sub","iss","aud","exp","nbf","iat","jti"];function Gm(e,t,n){return{accessToken:{setCustomClaim:(r,i)=>{if(xf.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);t[r]=i}},idToken:{setCustomClaim:(r,i)=>{if(xf.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);n&&(n[r]=i)}},access:{deny:r=>{throw new X(400,{message:`Access denied: ${r}`})}},token:{createServiceToken:async r=>(await zu(e,e.var.tenant_id,r.scope,r.expiresInSeconds,r.customClaims)).access_token}}}async function Su(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l,auth_time:u}=t,{signingKeys:d}=await e.env.data.keys.list({q:"type:jwt_signing"}),f=d.filter(B=>!B.revoked_at||new Date(B.revoked_at)>new Date),p=f[f.length-1];if(!p?.pkcs7)throw new X(500,{message:"No signing key available"});const h=Pz(p.pkcs7),_=Pi(e.env,e.var.custom_domain),g=n.audience||i.tenant.audience;if(!g)throw new X(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const y={aud:g,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:e.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,org_name:a&&i.tenant.allow_organization_name_in_authentication_api?a.name.toLowerCase():void 0,permissions:c,...t.customClaims};if(t.customClaims){for(const B of xf)if(B in t.customClaims)throw new Error(`Cannot overwrite reserved claim '${B}'`)}const m=n.scope?.split(" ")||[],w=m.includes("openid"),k=m.includes("profile"),S=m.includes("email"),v=n.response_type===st.ID_TOKEN,x=i.auth0_conformant!==!1||v,A=r&&w?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,...n.max_age!==void 0&&u!==void 0?{auth_time:u}:{},...n.acr_values?{acr:n.acr_values.split(" ")[0]}:{},...k&&x&&{given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name},...S&&x&&{email:r.email,email_verified:r.email_verified},act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name.toLowerCase()}:void 0,E=t.loginSession?.auth_connection||t.authConnection||e.var.connection;let P;if(E)try{const B=await e.env.data.connections.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1}),V=B.connections.find(L=>L.name===E)??B.connections.find(L=>L.name.toLowerCase()===E.toLowerCase());V&&(P={id:V.id||V.name,name:V.name,strategy:V.strategy||r?.provider||"auth0",metadata:V.options||{}})}catch(B){console.error("Error fetching connection info:",B)}e.env.hooks?.onExecuteCredentialsExchange&&await e.env.hooks.onExecuteCredentialsExchange({ctx:e,client:i,user:r,request:{ip:e.var.ip||"",user_agent:e.var.useragent||"",method:e.req.method,url:e.req.url},scope:n.scope||"",grant_type:"",connection:P||(E?{id:E,name:E,strategy:r?.provider||"auth0"}:void 0)},Gm(e,y,A));{const{hooks:B}=await e.env.data.hooks.list(e.var.tenant_id,{q:"trigger_id:credentials-exchange",page:0,per_page:100,include_totals:!1}),V=B.filter(Q=>Q.enabled&&fl(Q)),L=Gm(e,y,A);if(r){for(const Q of V)if(fl(Q))try{await S9(e,Q.template_id,r,L)}catch(ae){if(ae instanceof I)throw ae;console.warn(`[credentials-exchange] Failed to execute template hook: ${Q.template_id}`,ae)}}}const D={expiresIn:l?new dl(1,"h"):new dl(1,"d"),headers:{kid:p.kid}},C=await Im("RS256",h,y,D),R=A?await Im("RS256",h,A,D):void 0;return{access_token:C,refresh_token:t.refresh_token,id_token:R,token_type:"Bearer",expires_in:l?3600:86400}}async function x2(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Oe(32),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+Lz*1e3).toISOString(),code_challenge:t.authParams.code_challenge,code_challenge_method:t.authParams.code_challenge_method,redirect_uri:t.authParams.redirect_uri,state:t.authParams.state,nonce:t.authParams.nonce})).code_id,state:t.authParams.state}}async function z2(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,login_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Vw(),login_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+bu*1e3).toISOString(),user_id:t.user.user_id,device:{last_ip:e.var.ip,initial_ip:e.var.ip,last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Wm(e,{user:t,client:n,loginSession:r}){return await e.env.data.sessions.create(n.tenant.id,{id:Vw(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+bu*1e3).toISOString(),device:{last_ip:e.var.ip||"",initial_ip:e.var.ip||"",last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]})}async function GA(e,{user:t,client:n,loginSession:r,existingSessionId:i,authConnection:s}){const a=await e.env.data.loginSessions.get(n.tenant.id,r.id);if(!a)throw new I(400,{message:`Login session ${r.id} not found`});const c=a.state||We.PENDING;if(c===We.FAILED||c===We.EXPIRED||c===We.COMPLETED)throw new I(400,{message:`Cannot authenticate login session in ${c} state`});if(c===We.AUTHENTICATED){if(a.session_id)return a.session_id;throw new I(500,{message:"Login session is authenticated but has no session_id"})}let l;if(i){const f=await e.env.data.sessions.get(n.tenant.id,i);!f||f.revoked_at?l=(await Wm(e,{user:t,client:n,loginSession:r})).id:(l=i,f.clients.includes(n.client_id)||await e.env.data.sessions.update(n.tenant.id,i,{clients:[...f.clients,n.client_id]}))}else l=(await Wm(e,{user:t,client:n,loginSession:r})).id;const{state:u}=Oi(c,{type:Pr.AUTHENTICATE,userId:t.user_id}),d=s||e.var.connection;return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:l,state:u,user_id:t.user_id,...d?{auth_connection:d}:{}}),l}async function WA(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as failed`);return}const s=i.state||We.PENDING,{state:a,context:c}=Oi(s,{type:Pr.FAIL,reason:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,failure_reason:c.failureReason})}async function bl(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to start hook`);return}const s=i.state||We.PENDING,{state:a,context:c}=Oi(s,{type:Pr.START_HOOK,hookId:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:c.hookId?JSON.stringify({hookId:c.hookId}):void 0})}async function sa(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete hook`);return}const i=r.state||We.PENDING,{state:s}=Oi(i,{type:Pr.COMPLETE_HOOK});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s,state_data:void 0})}async function Jm(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as completed`);return}const s=i.state||We.PENDING,{state:a}=Oi(s,{type:Pr.COMPLETE});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,...r?{auth_connection:r}:{}})}async function xu(e,t,n,r,i){const s=await e.env.data.loginSessions.get(t,n.id);if(!s){console.warn(`Login session ${n.id} not found when trying to start continuation`);return}const a=s.state||We.PENDING,{state:c}=Oi(a,{type:Pr.START_CONTINUATION,scope:r});c!==a?await e.env.data.loginSessions.update(t,n.id,{state:c,state_data:JSON.stringify({continuationScope:r,continuationReturnUrl:i})}):console.warn(`Failed to start continuation for login session ${n.id}: cannot transition from ${a} to AWAITING_CONTINUATION. Scope: ${JSON.stringify(r)}, Return URL: ${KA(i)}`)}async function JA(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete continuation`);return}let i;if(r.state_data)try{i=JSON.parse(r.state_data).continuationReturnUrl}catch{}const s=r.state||We.PENDING,{state:a}=Oi(s,{type:Pr.COMPLETE_CONTINUATION});return a!==s?await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:void 0}):console.warn(`completeLoginSessionContinuation: State transition from ${s} with COMPLETE_CONTINUATION was invalid or no-op`),i}function ZA(e){if(!e.state_data)return null;try{return JSON.parse(e.state_data).continuationScope||null}catch{return null}}function XA(e,t){if(e.state!==We.AWAITING_CONTINUATION)return!1;const n=ZA(e);return n?n.includes(t):!1}async function mt(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||st.CODE,c=n.response_mode||fn.QUERY;if(i){if(!t.loginSession)throw new X(500,{message:"Login session not found for ticket auth."});s&&!t.skipHooks&&(t.authStrategy&&s.app_metadata?.strategy!==t.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:t.authStrategy.strategy}})),await A2(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=Tz(),_=Oe(12),g=await e.env.data.codes.create(r.tenant.id,{code_id:Oe(32),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+Uz).toISOString(),code_verifier:[_,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:g.code_id,co_verifier:h,co_id:_})}let l=t.refreshToken,u;if(t.loginSession){const h=await e.env.data.loginSessions.get(r.tenant.id,t.loginSession.id);if(!h)throw new X(500,{message:"Login session not found."});const _=h.state||We.PENDING;if(_===We.COMPLETED)throw new X(400,{error:"invalid_request",error_description:"Login session has already been completed"});if(_===We.FAILED)throw new X(400,{error:"access_denied",error_description:`Login session failed: ${h.failure_reason||"unknown reason"}`});if(_===We.EXPIRED)throw new X(400,{error:"invalid_request",error_description:"Login session has expired"});if(_===We.PENDING)u=await GA(e,{user:s,client:r,loginSession:t.loginSession,existingSessionId:t.existingSessionIdToLink,authConnection:t.authConnection});else if(u=h.session_id,!u)throw new X(500,{message:`Login session in ${_} state but has no session_id`})}else throw new X(500,{message:"loginSession must be provided for front-channel auth responses."});if(!l&&n.scope?.split(" ").includes("offline_access")&&![st.TOKEN,st.CODE].includes(a)&&!t.impersonatingUser&&(l=(await z2(e,{user:s,client:r,login_id:t.loginSession?.id||"",scope:n.scope,audience:n.audience})).id),c===fn.SAML_POST){if(!u)throw new I(500,{message:"Session ID not available for SAML response"});return m9(e,t.client,t.authParams,s,u)}const d=await YA(e,{authParams:n,user:s,client:r,session_id:u,refresh_token:l,authStrategy:t.authStrategy,authConnection:t.authConnection,loginSession:t.loginSession,responseType:a,skipHooks:t.skipHooks,organization:t.organization,impersonatingUser:t.impersonatingUser});if(d instanceof Response)return d;if(c===fn.WEB_MESSAGE){if(!n.redirect_uri)throw new X(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const h=new Headers;u?pl(r.tenant.id,u,e.var.host||"").forEach(m=>{h.append("set-cookie",m)}):console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const _=new URL(n.redirect_uri),g=`${_.protocol}//${_.host}`;return gf(e,g,JSON.stringify({...d,state:n.state}),h)}if(!n.redirect_uri)throw new X(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;u&&pl(r.tenant.id,u,e.var.custom_domain||e.req.header("host")||"").forEach(_=>{f.append("set-cookie",_)});const p=new URL(n.redirect_uri);if("code"in d)p.searchParams.set("code",d.code),d.state&&p.searchParams.set("state",d.state);else if("access_token"in d)p.hash=new URLSearchParams({access_token:d.access_token,...d.id_token&&{id_token:d.id_token},token_type:d.token_type,expires_in:d.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new X(500,{message:"Invalid token response for implicit flow."});return f.set("location",p.toString()),new Response("Redirecting",{status:302,headers:f})}async function YA(e,t){let{user:n}=t;const r=t.responseType||st.TOKEN;if(n&&t.organization&&!(await e.env.data.userOrganizations.list(t.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(d=>d.organization_id===t.organization.id))throw new X(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=t.authParams.scope||"",s=[];if(t.authParams.audience)try{let l;if(t.grantType===an.ClientCredential||!n&&!t.user)l=await ia(e,{grantType:an.ClientCredential,tenantId:t.client.tenant.id,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id});else{const u=n?.user_id||t.user?.user_id;if(!u)throw new X(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});l=await ia(e,{grantType:t.grantType,tenantId:t.client.tenant.id,userId:u,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id})}i=l.scopes.join(" "),s=l.permissions}catch(l){if(l instanceof I)throw l}const a={...t.authParams,scope:i};if(t.loginSession&&n&&!t.skipHooks){t.authStrategy&&n.app_metadata?.strategy!==t.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(t.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:t.authStrategy.strategy}}));const l=await A2(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(l instanceof Response)return l;n=l}const c=t.loginSession?.auth_connection||t.authConnection||e.var.connection;if(r===st.CODE){if(!n||!t.loginSession)throw new X(500,{message:"User and loginSession is required for code flow"});const l=await x2(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id});return await Jm(e,t.client.tenant.id,t.loginSession,c),l}else{const l=await Su(e,{...t,user:n,authParams:a,permissions:s});return t.loginSession&&await Jm(e,t.client.tenant.id,t.loginSession,c),l}}const Zm="auth-service";async function zu(e,t,n,r,i){const s=await e.env.data.tenants.get(t);if(!s)throw new Error(`Tenant not found: ${t}`);const c=await Su(e,{client:{client_id:Zm,tenant:s,auth0_conformant:!0},authParams:{client_id:Zm,response_type:st.TOKEN,scope:n},customClaims:i});return{access_token:c.access_token,token_type:c.token_type,expires_in:r||3600}}async function Pa(e,t,n){const r=e.env.webhookInvoker,i=async(s="webhook")=>(await zu(e,n.tenant_id,s)).access_token;for await(const s of t.filter(a=>"url"in a)){let a,c;try{const l=performance.now(),u=r?await r({hook:s,data:n,tenant_id:n.tenant_id,createServiceToken:i}):await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${await i()}`,"Content-Type":"application/json"},body:JSON.stringify(n)}),d=performance.now()-l,f=e.res.headers.get("Server-Timing")||"",p=`webhook-${s.hook_id};dur=${d.toFixed(2)}`;if(e.res.headers.set("Server-Timing",f?`${f}, ${p}`:p),c=u.status,!u.ok){try{a=await u.text()}catch{}const h=`Failed to invoke hook ${s.hook_id} - ${u.status} ${u.statusText}`;console.error(h,{hook_url:s.url,body:a?.substring(0,512)}),await fe(e,n.tenant_id,{type:pe.FAILED_HOOK,description:h,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:s.hook_id,hook_url:s.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,response:{statusCode:c,body:a?.substring(0,512)}},connection:n.user?.connection,waitForCompletion:!0})}}catch(l){const u=`Failed to invoke hook ${s.hook_id} - ${l instanceof Error?l.message:"Unknown error"}`;console.error(u,l),await fe(e,n.tenant_id,{type:pe.FAILED_HOOK,description:u,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:s.hook_id,hook_url:s.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,error:l instanceof Error?l.message:String(l)},connection:n.user?.connection,waitForCompletion:!0})}}}function QA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="post-user-registration");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function eE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="pre-user-registration");await Pa(e,i,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function tE(e,t){const{hooks:n}=await e.env.data.hooks.list(t);return n.find(r=>r.trigger_id==="validate-registration-username"&&"url"in r&&r.enabled)||null}function nE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="pre-user-deletion");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function rE(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t),i=r.filter(s=>s.trigger_id==="post-user-deletion");return await Pa(e,i,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}o.z.object({...ti.shape,tenant:sl,connections:o.z.array(_r)});async function qe(e,t,n){let r,i=n;if(!i){const p=await e.data.clients.getByClientId(t);if(!p)throw new X(403,{message:"Client not found"});const{tenant_id:h,..._}=p;r=_,i=h}const[s,a,c,l]=await Promise.all([r?Promise.resolve(r):e.data.clients.get(i,t),e.data.tenants.get(i),e.data.clientConnections.listByClient(i,t),e.data.connections.list(i)]),u=r||s;if(!u)throw new X(403,{message:"Client not found"});if(!a)throw new X(404,{message:"Tenant not found"});const d=c.length>0?c:l.connections||[],f=wt(e);return{...u,web_origins:[...u.web_origins||[],`${f}login`],allowed_logout_urls:[...u.allowed_logout_urls||[],e.ISSUER],callbacks:[...u.callbacks||[],`${f}info`],tenant:a,connections:d}}function Xm(e){return typeof e.form_id=="string"}function So(e,t){const n=e.match(/^\{\{context\.user\.(.+)\}\}$/);if(n&&n[1])return Ym(t.user,n[1]);const r=e.match(/^\{\{user\.(.+)\}\}$/);if(r&&r[1])return Ym(t.user,r[1]);const i=e.match(/^\{\{\$form\.(.+)\}\}$/);if(i&&i[1]&&t.submittedFields){const s=t.submittedFields[i[1]];return s!==void 0?String(s):void 0}return e}function Ym(e,t){const n=t.split(".");let r=e;for(const i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return typeof r=="string"?r:r==null?void 0:String(r)}function iE(e,t){const n={};for(const[r,i]of Object.entries(e))if(typeof i=="string"){const s=So(i,t);s!==void 0&&(n[r]=s)}else i!=null&&(n[r]=String(i));return n}function Qm(e,t){const n=e.operator?.toLowerCase(),r=e.field?So(e.field,t):"",i=e.value||"";switch(n){case"exists":return r!=null&&r!=="";case"not_exists":return r==null||r==="";case"ends_with":return typeof r=="string"&&r.endsWith(i);case"starts_with":return typeof r=="string"&&r.startsWith(i);case"contains":return typeof r=="string"&&r.includes(i);case"not_contains":return typeof r!="string"||!r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(e.operands&&Array.isArray(e.operands)){for(const s of e.operands)if(s.operator==="ENDS_WITH"&&Array.isArray(s.operands)&&s.operands.length>=2){const a=s.operands[0],c=s.operands[1];if(a&&c){const l=So(`{{context.user.${a}}}`,t);if(typeof l=="string"&&l.endsWith(c))return!0}}}return!1}}function oE(e,t){return e.type==="and"&&Array.isArray(e.conditions)?e.conditions.every(n=>Qm(n,t)):Qm(e,t)}function Au(e,t){const n={};for(const[r,i]of Object.entries(e))if(r.startsWith("user_metadata.")||r.startsWith("metadata.")){const s=r.startsWith("user_metadata.")?r.slice(14):r.slice(9),a=t.user_metadata||{};n.user_metadata={...a,...n.user_metadata||{},[s]:i}}else if(r.startsWith("address.")){const s=r.slice(8),a=t.address||{};n.address={...a,...n.address||{},[s]:i}}else n[r]=i;return n}function Eu(e){const t=new Map;for(const n of e){const r=t.get(n.user_id);r?r.changes={...r.changes,...n.changes}:t.set(n.user_id,{user_id:n.user_id,changes:{...n.changes}})}return Array.from(t.values())}function Cu(e,t,n){switch(e){case"change-email":return`/u/account/change-email?state=${encodeURIComponent(n)}`;case"account":return`/u/account?state=${encodeURIComponent(n)}`;case"custom":if(!t)throw new I(400,{message:"Custom URL is required for custom redirect target"});const r=new URL(t,"http://placeholder");return r.searchParams.set("state",n),r.pathname+r.search;default:throw new I(400,{message:`Unknown redirect target: ${e}`})}}async function Iu(e,t,n,r,i=10){let s=t,a=0;const c=[];for(;a<i;){if(s==="$ending")return{type:"end",userUpdates:c.length>0?c:void 0};const l=e.find(u=>u.id===s);if(!l)return null;if(l.type==="STEP")return{type:"step",nodeId:l.id,userUpdates:c.length>0?c:void 0};if(l.type==="ACTION"){const u=l;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url,userUpdates:c.length>0?c:void 0};s=u.config.next_node,a++;continue}if(l.type==="ROUTER"){const u=l;let d=null;for(const f of u.config.rules)if(oE(f.condition,n)){d=f.next_node;break}if(d||(d=u.config.fallback),!d)return null;s=d,a++;continue}if(l.type==="FLOW"){const u=l;if(r&&u.config.flow_id){const d=await r(u.config.flow_id);if(d&&d.actions&&d.actions.length>0)for(const f of d.actions){if(f.type==="REDIRECT"&&f.action==="REDIRECT_USER"){const p=f.params?.target;if(p)return{type:"redirect",target:p,customUrl:f.params?.custom_url,userUpdates:c.length>0?c:void 0}}if(f.type==="AUTH0"&&f.action==="UPDATE_USER"&&f.params){const p=f.params.user_id&&So(f.params.user_id,n)||n.user.user_id,h=f.params.changes?iE(f.params.changes,n):{};Object.keys(h).length>0&&c.push({user_id:p,changes:h})}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end",userUpdates:c.length>0?c:void 0}}return null}return null}async function sE(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});const c=i?.client_metadata?.universal_login_version==="2"?"/u2":"/u",l=await s.forms.get(a,t);if(!l)throw new I(404,{message:"Form not found for post-user-login hook"});let u=l.start?.next_node;if(!u&&l.nodes&&l.nodes.length>0&&(u=l.nodes.find(p=>p.type==="STEP")?.id),!u)throw new I(400,{message:"No start node found in form"});if(r&&l.nodes){const f=async h=>{const _=await s.flows.get(a,h);return _?{actions:_.actions?.map(g=>({type:g.type,action:g.action,params:"params"in g&&g.params?g.params:void 0}))}:null},p=await Iu(l.nodes,u,{user:r},f);if(p&&p.userUpdates&&p.userUpdates.length>0){const h=Eu(p.userUpdates);for(const _ of h){const g=Au(_.changes,r);await s.users.update(a,_.user_id,g)}}if(!p||p.type==="end")return r;if(p.type==="redirect"){const h=p.target,_=Cu(h,p.customUrl,n.id);if(h==="change-email"||h==="account"){const g=`${c}/continue?state=${encodeURIComponent(n.id)}`;await xu(e,a,n,[h],g)}else await bl(e,a,n,`form:${t}`);return new Response(null,{status:302,headers:{location:_}})}u=p.nodeId}await bl(e,a,n,`form:${t}`);let d=`${c}/forms/${l.id}/nodes/${u}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:d}})}function eg(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function aE(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(f=>f.permission_name===i))return r;await bl(e,a,n,`page:${t}`);let c="/u";if(n.authParams.client_id)try{(await qe(e.env,n.authParams.client_id,a))?.client_metadata?.universal_login_version==="2"&&(c="/u2")}catch{}let l=`${c}/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function hi(e,t){return{createServiceToken:async n=>(await zu(e,t,n.scope,n.expiresInSeconds,n.customClaims)).access_token}}function cE(e){return typeof e.url=="string"}function lE(e,t){return async(n,r)=>{if(e.var.client_id){const a=await qe(e.env,e.var.client_id,e.var.tenant_id);r.email&&await dE(e,a,t,r.email,r.connection)}const i={method:e.req.method,ip:e.req.query("x-real-ip")||"",user_agent:e.req.query("user-agent"),url:e.var.loginSession?.authorization_url||e.req.url};if(e.env.hooks?.onExecutePreUserRegistration)try{await e.env.hooks.onExecutePreUserRegistration({ctx:e,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c},setLinkedTo:a=>{r.linked_to=a}},token:hi(e,n)})}catch{fe(e,n,{type:pe.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await mz(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:hi(e,n)})}catch{fe(e,n,{type:pe.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await QA(e)(n,s),s}}function uE(e,t){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return t.users.update(n,r,i);const s=await t.users.get(n,r);if(!s)throw new X(404,{message:"User not found"});const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserUpdate)try{await e.env.hooks.onExecutePreUserUpdate({ctx:e,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new X(400,{message:"User update cancelled by pre-update hook"})},token:hi(e,n)})}catch(c){throw fe(e,n,{type:pe.ACTIONS_EXECUTION_FAILED,description:`Pre user update hook failed: ${c instanceof Error?c.message:"Unknown error"}`,userId:r}),new X(400,{message:"Pre user update hook failed"})}if(await t.users.update(n,r,i),i.email||i.email_verified){const c=await t.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),u=l.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);u.length>0&&await t.users.update(n,r,{linked_to:u[0].user_id})}}return i.email&&fe(e,n,{type:pe.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function ju(e,t,n,r,i="email"){if(t.client_metadata?.disable_sign_ups==="true"){const a=e.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await Vo({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"User account does not exist"}}if(e.env.hooks?.onExecuteValidateRegistrationUsername){const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};let c=!1,l;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:u=>{c=!0,l=u},token:hi(e,t.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await tE(e,t.tenant.id);if(s&&"url"in s)try{const a=await zu(e,t.tenant.id,"webhook"),c=await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({tenant_id:t.tenant.id,email:r,connection:i,client_id:t.client_id,trigger_id:"validate-registration-username"})});if(!c.ok)return{allowed:!1,reason:await c.text()||"Signup not allowed by webhook"};const l=await c.json();if(l.allowed===!1)return{allowed:!1,reason:l.reason||"Signup not allowed by webhook"}}catch{fe(e,t.tenant.id,{type:pe.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function dE(e,t,n,r,i){const s=await ju(e,t,n,r,i);if(!s.allowed)throw fe(e,t.tenant.id,{type:pe.FAILED_SIGNUP,description:s.reason||"Signup not allowed"}),new X(400,{message:s.reason||"Signups are disabled for this client"});await eE(e)(t.tenant.id,r)}function pE(e,t){return async(n,r)=>{const i=await t.users.get(n,r);if(!i)return!1;const s={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserDeletion)try{await e.env.hooks.onExecutePreUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new X(400,{message:"User deletion cancelled by pre-deletion hook"})},token:hi(e,n)})}catch(l){throw l instanceof I?l:(fe(e,n,{type:pe.FAILED_HOOK,description:`Pre user deletion hook failed: ${l instanceof Error?l.message:String(l)}`}),new X(400,{message:"Pre user deletion hook failed"}))}try{await nE(e)(n,i)}catch(l){throw fe(e,n,{type:pe.FAILED_HOOK,description:`Pre user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`}),new X(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.list(n,{q:`linked_to:${r}`});for(const l of a.users){const[u,...d]=l.user_id.split("|");u&&await t.users.unlink(n,r,u,d.join("|"))}const c=await t.users.remove(n,r);if(c){fe(e,n,{type:pe.SUCCESS_USER_DELETION,description:`Deleted user: ${i.email||r}`,userId:r,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await rE(e)(n,i)}catch(l){fe(e,n,{type:pe.FAILED_HOOK,description:`Post user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`})}}if(c&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:hi(e,n)})}catch(l){fe(e,n,{type:pe.FAILED_HOOK,description:`Post user deletion hook failed: ${l instanceof Error?l.message:String(l)}`})}return c}}function Ho(e,t){const n=t;return{...t,users:{...t.users,create:lE(e,n),update:uE(e,n),remove:pE(e,n)}}}async function fE(e,t,n,r,i,s){let a=[];try{a=(await t.userRoles.list(n,r.user_id,void 0,"")).map(p=>p.name||p.id)}catch(d){console.error("Error fetching user roles:",d)}let c={};if(r.connection)try{const f=(await t.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(p=>p.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(d){console.error("Error fetching connection info:",d)}let l;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(l={id:d.id,name:d.name,display_name:d.display_name||d.name,metadata:d.metadata||{}})}}catch(d){console.error("Error fetching organization info:",d)}const u=e.get("countryCode");return{ctx:e,client:s.client,user:r,request:{asn:void 0,ip:e.get("ip")||"",user_agent:e.get("useragent"),method:e.req.method,url:e.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:u||void 0,countryName:void 0,latitude:void 0,longitude:void 0,timeZone:void 0}},transaction:{id:i.id,locale:i.authParams?.ui_locales||"en",login_hint:void 0,prompt:i.authParams?.prompt,redirect_uri:i.authParams?.redirect_uri,requested_scopes:i.authParams?.scope?.split(" ")||[],response_mode:i.authParams?.response_mode,response_type:i.authParams?.response_type,state:i.authParams?.state,ui_locales:i.authParams?.ui_locales},scope:s.authParams?.scope||"",grant_type:s.authParams?.grant_type||"",audience:s.authParams?.audience,authentication:{methods:[{name:r.is_social?"federated":"pwd",timestamp:new Date().toISOString()}]},authorization:{roles:a},connection:Object.keys(c).length>0?c:{id:r.connection||"Username-Password-Authentication",name:r.connection||"Username-Password-Authentication",strategy:r.provider||"auth0"},organization:l,resource_server:s.authParams?.audience?{identifier:s.authParams.audience}:void 0,stats:{logins_count:r.login_count||0},tenant:{id:n},session:{id:i.id,created_at:i.created_at,authenticated_at:new Date().toISOString(),clients:[{client_id:s.client.client_id}],device:{initial_ip:e.get("ip"),initial_user_agent:e.get("useragent"),last_ip:r.last_ip||e.get("ip"),last_user_agent:e.get("useragent")}}}}async function A2(e,t,n,r,i,s){const a=s?.authStrategy?.strategy_type?s.authStrategy.strategy_type:r.is_social?"social":"database",c=s?.authStrategy?.strategy||r.connection||"";if(fe(e,n,{type:pe.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id,strategy_type:a,strategy:c,connection:c,audience:s?.authParams?.audience,scope:s?.authParams?.scope}),await t.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:e.var.ip||"",login_count:r.login_count+1}),e.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let p=null;const h=await fE(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(h,{prompt:{render:_=>{}},redirect:{sendUserTo:(_,g)=>{const y=new URL(_,e.req.url);y.searchParams.set("state",i.id),g?.query&&Object.entries(g.query).forEach(([m,w])=>{y.searchParams.set(m,w)}),p=y.toString()},encodeToken:_=>JSON.stringify({payload:_.payload,exp:Date.now()+(_.expiresInSeconds||900)*1e3}),validateToken:_=>null},token:hi(e,n)}),p)return await bl(e,n,i,"onExecutePostLogin"),new Response(null,{status:302,headers:{location:p}})}const{hooks:l}=await t.hooks.list(n),u=l.filter(p=>p.trigger_id==="post-user-login");if(i){const p=u.find(_=>_.enabled&&Xm(_));if(p&&Xm(p))return sE(e,p.form_id,i,r,s?.client);const h=u.find(_=>_.enabled&&eg(_));if(h&&eg(h))return aE(e,h.page_id,i,r,h.permission_required)}const d=u.filter(p=>p.enabled&&fl(p));for(const p of d)if(fl(p))try{r=await $9(e,p.template_id,r)}catch{fe(e,n,{type:pe.FAILED_HOOK,description:`Failed to execute template hook: ${p.template_id}`})}const f=u.filter(p=>p.enabled&&cE(p));return await Pa(e,f,{tenant_id:n,user:r,trigger_id:"post-user-login"}),r}function hE(e){return Ho(e,e.env.data)}async function U0(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Or({userAdapter:e,tenant_id:t,username:n,provider:r}){let i;r==="sms"?i=`phone_number:${n}`:n.includes("@")?i=`email:${n}`:i=`username:${n}`;const{users:s}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`${i} provider:${r}`});return s.length>1&&console.error("More than one user found for same username and provider"),s[0]||null}async function Vo({userAdapter:e,tenant_id:t,email:n}){const{users:r}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`});if(r.length===0)return;const i=r.filter(a=>!a.linked_to);if(i.length>0)return i.length>1&&console.error("More than one primary user found for same email"),i[0];const s=await e.get(t,r[0]?.linked_to);if(!s)throw new Error("Primary account not found");return s}async function Pn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Or({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Nu(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:u=""}=t;let d=await Pn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||Ti()}`,email:i!=="sms"&&n.includes("@")?n:void 0,phone_number:i==="sms"?n:void 0,username:!n.includes("@")&&i!=="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:u,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};d=await hE(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const it=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"Return results inside an object that contains the total result count (true) or as a direct array of results (false, default)."}),from:o.z.string().optional().openapi({description:"Optional Id from which to start selection."}),take:o.z.string().optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. e.g. created_at:1."}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function ft(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}const E2={},_E=Object.freeze(Object.defineProperty({__proto__:null,default:E2},Symbol.toStringTag,{value:"Module"}));var zf=null;function mE(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return E2.randomBytes(e)}catch{}if(!zf)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return zf(e)}function gE(e){zf=e}function B0(e,t){if(e=e||M0,typeof e!="number")throw Error("Illegal arguments: "+typeof e+", "+typeof t);e<4?e=4:e>31&&(e=31);var n=[];return n.push("$2b$"),e<10&&n.push("0"),n.push(e.toString()),n.push("$"),n.push(vl(mE(aa),aa)),n.join("")}function C2(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=M0;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){cn(function(){try{i(null,B0(e))}catch(s){i(s)}})}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);r(n)}else return new Promise(function(i,s){r(function(a,c){if(a){s(a);return}i(c)})})}function I2(e,t){if(typeof t>"u"&&(t=M0),typeof t=="number"&&(t=B0(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return Af(e,t)}function j2(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?C2(t,function(a,c){Af(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?Af(e,t,s,r):cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)))}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function N2(e,t){for(var n=e.length^t.length,r=0;r<e.length;++r)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function yE(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:N2(I2(e,t.substring(0,t.length-31)),t)}function bE(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){cn(s.bind(this,null,!1));return}j2(e,t.substring(0,29),function(a,c){a?s(a):s(null,N2(c,t))},r)}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function vE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function wE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);if(e.length!==60)throw Error("Illegal hash length: "+e.length+" != 60");return e.substring(0,29)}function kE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return T2(e)>72}var cn=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function T2(e){for(var t=0,n=0,r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function $E(e){for(var t=0,n,r,i=new Array(T2(e)),s=0,a=e.length;s<a;++s)n=e.charCodeAt(s),n<128?i[t++]=n:n<2048?(i[t++]=n>>6|192,i[t++]=n&63|128):(n&64512)===55296&&((r=e.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[t++]=n>>18|240,i[t++]=n>>12&63|128,i[t++]=n>>6&63|128,i[t++]=n&63|128):(i[t++]=n>>12|224,i[t++]=n>>6&63|128,i[t++]=n&63|128);return i}var Vi="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),lr=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1];function vl(e,t){var n=0,r=[],i,s;if(t<=0||t>e.length)throw Error("Illegal len: "+t);for(;n<t;){if(i=e[n++]&255,r.push(Vi[i>>2&63]),i=(i&3)<<4,n>=t){r.push(Vi[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(Vi[i&63]),i=(s&15)<<2,n>=t){r.push(Vi[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(Vi[i&63]),r.push(Vi[s&63])}return r.join("")}function P2(e,t){var n=0,r=e.length,i=0,s=[],a,c,l,u,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<lr.length?lr[f]:-1,f=e.charCodeAt(n++),c=f<lr.length?lr[f]:-1,!(a==-1||c==-1||(d=a<<2>>>0,d|=(c&48)>>4,s.push(String.fromCharCode(d)),++i>=t||n>=r)||(f=e.charCodeAt(n++),l=f<lr.length?lr[f]:-1,l==-1)||(d=(c&15)<<4>>>0,d|=(l&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),u=f<lr.length?lr[f]:-1,d=(l&3)<<6>>>0,d|=u,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var aa=16,M0=10,SE=16,xE=100,tg=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],ng=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],O2=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function ca(e,t,n,r){var i,s=e[t],a=e[t+1];return s^=n[0],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[1],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[2],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[3],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[4],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[5],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[6],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[7],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[8],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[9],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[10],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[11],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[12],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[13],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[14],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[15],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[16],e[t]=a^n[SE+1],e[t+1]=s,e}function Zi(e,t){for(var n=0,r=0;n<4;++n)r=r<<8|e[t]&255,t=(t+1)%e.length;return{key:r,offp:t}}function rg(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,l=0;l<s;l++)c=Zi(e,r),r=c.offp,t[l]=t[l]^c.key;for(l=0;l<s;l+=2)i=ca(i,0,t,n),t[l]=i[0],t[l+1]=i[1];for(l=0;l<a;l+=2)i=ca(i,0,t,n),n[l]=i[0],n[l+1]=i[1]}function zE(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,u=0;u<a;u++)l=Zi(t,i),i=l.offp,n[u]=n[u]^l.key;for(i=0,u=0;u<a;u+=2)l=Zi(e,i),i=l.offp,s[0]^=l.key,l=Zi(e,i),i=l.offp,s[1]^=l.key,s=ca(s,0,n,r),n[u]=s[0],n[u+1]=s[1];for(u=0;u<c;u+=2)l=Zi(e,i),i=l.offp,s[0]^=l.key,l=Zi(e,i),i=l.offp,s[1]^=l.key,s=ca(s,0,n,r),r[u]=s[0],r[u+1]=s[1]}function ig(e,t,n,r,i){var s=O2.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){cn(r.bind(this,c));return}else throw c;if(t.length!==aa)if(c=Error("Illegal salt length: "+t.length+" != "+aa),r){cn(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,u,d=0,f;typeof Int32Array=="function"?(l=new Int32Array(tg),u=new Int32Array(ng)):(l=tg.slice(),u=ng.slice()),zE(t,e,l,u);function p(){if(i&&i(d/n),d<n)for(var _=Date.now();d<n&&(d=d+1,rg(e,l,u),rg(t,l,u),!(Date.now()-_>xE)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)ca(s,f<<1,l,u);var g=[];for(d=0;d<a;d++)g.push((s[d]>>24&255)>>>0),g.push((s[d]>>16&255)>>>0),g.push((s[d]>>8&255)>>>0),g.push((s[d]&255)>>>0);if(r){r(null,g);return}else return g}r&&cn(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function Af(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){cn(n.bind(this,i));return}else throw i;var s,a;if(t.charAt(0)!=="$"||t.charAt(1)!=="2")if(i=Error("Invalid salt version: "+t.substring(0,2)),n){cn(n.bind(this,i));return}else throw i;if(t.charAt(2)==="$")s="\0",a=3;else{if(s=t.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||t.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+t.substring(2,4)),n){cn(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){cn(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,l=parseInt(t.substring(a+1,a+2),10),u=c+l,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=$E(e),p=P2(d,aa);function h(_){var g=[];return g.push("$2"),s>="a"&&g.push(s),g.push("$"),u<10&&g.push("0"),g.push(u.toString()),g.push("$"),g.push(vl(p,p.length)),g.push(vl(_,O2.length*4-1)),g.join("")}if(typeof n>"u")return h(ig(f,p,u));ig(f,p,u,function(_,g){_?n(_,null):n(null,h(g))},r)}function AE(e,t){return vl(e,t)}function EE(e,t){return P2(e,t)}const Ko={setRandomFallback:gE,genSaltSync:B0,genSalt:C2,hashSync:I2,hash:j2,compareSync:yE,compare:bE,getRounds:vE,getSalt:wE,truncates:kE,encodeBase64:AE,decodeBase64:EE},ur={TOO_SHORT:"password_too_short",MISSING_LOWERCASE:"password_missing_lowercase",MISSING_UPPERCASE:"password_missing_uppercase",MISSING_NUMBER:"password_missing_number",MISSING_SPECIAL:"password_missing_special",REUSED:"password_reused",CONTAINS_PERSONAL_INFO:"password_contains_personal_info",CONTAINS_FORBIDDEN_WORD:"password_contains_forbidden_word"};class jn extends Error{code;params;constructor(t,n,r){super(n),this.code=t,this.params=r,this.name="PasswordPolicyError"}}async function Oa(e,t){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=t,c=e.passwordPolicy!==void 0||e.password_complexity_options!==void 0||e.password_history!==void 0||e.password_no_personal_info!==void 0||e.password_dictionary!==void 0,l=c?e.passwordPolicy:"good",u=c?e.password_complexity_options?.min_length:8;if(u&&n.length<u)throw new jn(ur.TOO_SHORT,`Password must be at least ${u} characters`,{minLength:u});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new jn(ur.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new jn(ur.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new jn(ur.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new jn(ur.MISSING_SPECIAL,"Password must contain at least one special character")}if(e.password_history?.enable){const d=e.password_history.size||5,f=await i.passwords.list(s,a,d);for(const p of f)if(await Ko.compare(n,p.password))throw new jn(ur.REUSED,"Password was used recently and cannot be reused",{historySize:d})}if(e.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new jn(ur.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(e.password_dictionary?.enable&&e.password_dictionary.dictionary&&e.password_dictionary.dictionary.some(d=>n.toLowerCase().includes(d.toLowerCase())))throw new jn(ur.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Ra(e,t,n){const{connections:r}=await e.connections.list(t,{page:0,per_page:100});return r.find(s=>s.name===n)?.options||{}}async function la(e){return{hash:await Ko.hash(e,10),algorithm:"bcrypt"}}var og;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(og||(og={}));var sg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(sg||(sg={}));function CE(e){return R2(e,IE,ua.Include)}function q0(e){return R2(e,jE,ua.None)}function R2(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===ua.Include&&(r+="=")}return r}const IE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ua;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ua||(ua={}));var ag;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(ag||(ag={}));class NE{uint8(t,n){if(t.byteLength<n+1)throw new TypeError("Insufficient bytes");return t[n]}uint16(t,n){if(t.byteLength<n+2)throw new TypeError("Insufficient bytes");return t[n]<<8|t[n+1]}uint32(t,n){if(t.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=t[n+i]<<24-i*8;return r}uint64(t,n){if(t.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(t[n+i])<<BigInt(56-i*8);return r}putUint8(t,n,r){if(t.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");t[r]=n}putUint16(t,n,r){if(t.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");t[r]=n>>8,t[r+1]=n&255}putUint32(t,n,r){if(t.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)t[r+i]=n>>(3-i)*8&255}putUint64(t,n,r){if(t.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)t[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const cg=new NE;function kn(e,t){return(e<<32-t|e>>>t)>>>0}function TE(e){const t=new PE;return t.update(e),t.digest()}class PE{blockSize=64;size=32;blocks=new Uint8Array(64);currentBlockSize=0;H=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);l=0n;w=new Uint32Array(64);update(t){if(this.l+=BigInt(t.byteLength)*8n,this.currentBlockSize+t.byteLength<64){this.blocks.set(t,this.currentBlockSize),this.currentBlockSize+=t.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=t.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=t.byteLength;){const r=t.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(t.byteLength-n>0){const r=t.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),cg.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)cg.putUint32(t,this.H[n],n*4);return t}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const d=(kn(this.w[u-2],17)^kn(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,f=(kn(this.w[u-15],7)^kn(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=d+this.w[u-7]+f+this.w[u-16]|0}let t=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const d=(kn(s,6)^kn(s,11)^kn(s,25))>>>0,f=(s&a^~s&c)>>>0,p=l+d+f+OE[u]+this.w[u]|0,h=(kn(t,2)^kn(t,13)^kn(t,22))>>>0,_=(t&n^t&r^n&r)>>>0,g=h+_|0;l=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+g|0}this.H[0]=t+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const OE=new Uint32Array([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]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class L2{data;constructor(t){this.data=t}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function D2(e){const t=TE(new TextEncoder().encode(e));return q0(t)}function Tu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),q0(e)}function U2(){const e=new Uint8Array(32);return crypto.getRandomValues(e),q0(e)}function RE(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<e.length&&e[n]===t;)n++;return e.slice(n)}function lg(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=e.length;for(;n>0&&e[n-1]===t;)n--;return e.slice(0,n)}function ug(e,...t){let n=lg(e,"/");for(const r of t)n=lg(n,"/")+"/"+RE(r,"/");return n}function Xn(e,t){const n=new TextEncoder().encode(t.toString()),r=new Request(e,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function ci(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return CE(n)}async function xo(e){let t;try{t=await fetch(e)}catch(n){throw new H0(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=F0(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);return new L2(n)}throw t.body!==null&&await t.body.cancel(),new _o(t.status)}async function LE(e){let t;try{t=await fetch(e)}catch(n){throw new H0(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new kr(t.status,null)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=F0(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){t.body!==null&&await t.body.cancel();return}throw t.body!==null&&await t.body.cancel(),new _o(t.status)}function F0(e){let t;if("error"in e&&typeof e.error=="string")t=e.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in e){if(typeof e.error_description!="string")throw new Error("Invalid data");n=e.error_description}if("error_uri"in e){if(typeof e.error_uri!="string")throw new Error("Invalid data");r=e.error_uri}if("state"in e){if(typeof e.state!="string")throw new Error("Invalid data");i=e.state}return new DE(t,n,r,i)}class H0 extends Error{constructor(t){super("Failed to send request",{cause:t})}}class DE extends Error{code;description;uri;state;constructor(t,n,r,i){super(`OAuth request error: ${t}`),this.code=t,this.description=n,this.uri=r,this.state=i}}class _o extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class kr extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Ri{clientId;clientPassword;redirectURI;constructor(t,n,r){this.clientId=t,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(t,n,r){const i=new URL(t);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(t,n,r,i,s){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===_i.S256){const c=D2(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===_i.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(t,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Xn(t,i);if(this.clientPassword!==null){const c=ci(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await xo(s)}async refreshAccessToken(t,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Xn(t,i);if(this.clientPassword!==null){const c=ci(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await xo(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Xn(t,r);if(this.clientPassword!==null){const s=ci(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await LE(i)}}var _i;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(_i||(_i={}));var dg;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(dg||(dg={}));var pg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(pg||(pg={}));function Hs(e){return UE(e,BE,wl.None)}function UE(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===wl.Include&&(r+="=")}return r}const BE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var wl;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(wl||(wl={}));var fg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(fg||(fg={}));function ME(e,t,n){const r=Hs(new TextEncoder().encode(e)),i=Hs(new TextEncoder().encode(t)),s=Hs(n);return r+"."+i+"."+s}function qE(e,t){const n=Hs(new TextEncoder().encode(e)),r=Hs(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const FE="https://appleid.apple.com/auth/authorize",HE="https://appleid.apple.com/auth/token";class B2{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(t,n,r,i,s){this.clientId=t,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(t,n){const r=new URL(FE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Xn(HE,n);return await xo(i)}async createClientSecret(){const t=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+300,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,qE(r,i)));return ME(r,i,s)}}const VE="https://www.facebook.com/v16.0/dialog/oauth",KE="https://graph.facebook.com/v16.0/oauth/access_token";class M2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(VE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Xn(KE,n);return await xo(r)}}const GE="https://github.com/login/oauth/authorize",hg="https://github.com/login/oauth/access_token";class q2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(GE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=Xn(hg,n),i=ci(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await _g(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Xn(hg,n),i=ci(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await _g(r)}}async function _g(e){let t;try{t=await fetch(e)}catch(i){throw new H0(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new _o(t.status);let n;try{n=await t.json()}catch{throw new _o(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=F0(n)}catch{throw new kr(t.status,n)}throw i}return new L2(n)}const WE="https://accounts.google.com/o/oauth2/v2/auth",mg="https://oauth2.googleapis.com/token",JE="https://oauth2.googleapis.com/revoke";let F2=class{client;constructor(t,n,r){this.client=new Ri(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(WE,t,_i.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(mg,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(mg,t,[])}async revokeToken(t){await this.client.revokeToken(JE,t)}};class H2{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=ug("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=ug("https://login.microsoftonline.com",t,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(t,n,r){const i=new URL(this.authorizationEndpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",t);const s=D2(n);return i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",s),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}async validateAuthorizationCode(t,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",t),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=Xn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=ci(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await xo(i)}async refreshAccessToken(t,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=Xn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=ci(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await xo(i)}}const Go=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Go.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});const ZE="Apple",XE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%200H0V45H45V0Z%22%20fill%3D%22white%22%2F%3E%3Cpath%20d%3D%22M23.5344%2010.3846C25.5313%2010.3846%2028.0344%209.01144%2029.525%207.18055C30.875%205.5213%2031.8594%203.20407%2031.8594%200.886839C31.8594%200.572154%2031.8313%200.25747%2031.775%200C29.5531%200.0858233%2026.8813%201.51621%2025.2781%203.43293C24.0125%204.89193%2022.8594%207.18055%2022.8594%209.52638C22.8594%209.86968%2022.9156%2010.213%2022.9438%2010.3274C23.0844%2010.356%2023.3094%2010.3846%2023.5344%2010.3846ZM16.5031%2045C19.2313%2045%2020.4406%2043.1405%2023.8438%2043.1405C27.3031%2043.1405%2028.0625%2044.9428%2031.1%2044.9428C34.0813%2044.9428%2036.0781%2042.1392%2037.9625%2039.3929C40.0719%2036.246%2040.9438%2033.1564%2041%2033.0134C40.8031%2032.9561%2035.0938%2030.5817%2035.0938%2023.9161C35.0938%2018.1373%2039.5938%2015.534%2039.8469%2015.3338C36.8656%2010.9854%2032.3375%2010.8709%2031.1%2010.8709C27.7531%2010.8709%2025.025%2012.9307%2023.3094%2012.9307C21.4531%2012.9307%2019.0063%2010.9854%2016.1094%2010.9854C10.5969%2010.9854%205%2015.6198%205%2024.3738C5%2029.8093%207.08125%2035.5594%209.64063%2039.2784C11.8344%2042.4253%2013.7469%2045%2016.5031%2045Z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";function V2(e){const{options:t}=e;if(!t||!t.client_id||!t.team_id||!t.kid||!t.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(t.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:t,keyArray:i}}async function YE(e,t){const{options:n,keyArray:r}=V2(t),i=`${Le(e.env)}callback`,s=new B2(n.client_id,n.team_id,n.kid,r,i),a=Oe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(u=>["email","name"].includes(u))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function QE(e,t,n){const{options:r,keyArray:i}=V2(t),a=await new B2(r.client_id,r.team_id,r.kid,i,`${Le(e.env)}callback`).validateAuthorizationCode(n),c=Na(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Go.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const e7=Object.freeze(Object.defineProperty({__proto__:null,displayName:ZE,getRedirect:YE,logoDataUri:XE,validateAuthorizationCodeAndGetUser:QE},Symbol.toStringTag,{value:"Module"})),t7="Facebook",n7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%2022.5C45%2010.0736%2034.9264%200%2022.5%200C10.0736%200%200%2010.0736%200%2022.5C0%2033.7031%208.23242%2042.9785%2019.0039%2044.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039%2011.8945%2022.3828%208.75977%2027.5391%208.75977C29.9658%208.75977%2032.5049%209.19922%2032.5049%209.19922V14.7656H29.7012C26.9414%2014.7656%2026.0156%2016.4824%2026.0156%2018.2432V22.5H32.2412L31.2012%2028.9746H26.0156V44.6953C36.7871%2042.9785%2045%2033.7031%2045%2022.5Z%22%20fill%3D%22%231877F2%22%2F%3E%3Cpath%20d%3D%22M31.2012%2028.9746L32.2412%2022.5H26.0156V18.2432C26.0156%2016.4824%2026.9414%2014.7656%2029.7012%2014.7656H32.5049V9.19922C32.5049%209.19922%2029.9658%208.75977%2027.5391%208.75977C22.3828%208.75977%2019.0039%2011.8945%2019.0039%2017.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562%2044.8984%2021.3203%2045%2022.5%2045C23.6797%2045%2024.8438%2044.8984%2026.0156%2044.6953V28.9746H31.2012Z%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E";async function r7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Le(e.env)}callback`,i=new M2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function i7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new M2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v22.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return e.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const o7=Object.freeze(Object.defineProperty({__proto__:null,displayName:t7,getRedirect:r7,logoDataUri:n7,validateAuthorizationCodeAndGetUser:i7},Symbol.toStringTag,{value:"Module"})),s7="Google",a7=!0,c7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M44.1035%2023.0123C44.1054%2021.4791%2043.9758%2019.9486%2043.716%2018.4375H22.498V27.1028H34.6507C34.4021%2028.4868%2033.8757%2029.8061%2033.1034%2030.9812C32.3311%2032.1562%2031.3289%2033.1628%2030.1571%2033.9401V39.5649H37.41C41.6567%2035.6494%2044.1035%2029.859%2044.1035%2023.0123Z%22%20fill%3D%22%234285F4%22%2F%3E%3Cpath%20d%3D%22M22.4982%2044.9997C28.5698%2044.9997%2033.6821%2043.0061%2037.4101%2039.5687L30.1573%2033.9439C28.1386%2035.3126%2025.5387%2036.0938%2022.4982%2036.0938C16.6296%2036.0938%2011.6485%2032.1377%209.86736%2026.8066H2.39575V32.6033C4.26839%2036.3297%207.13989%2039.4622%2010.6896%2041.6512C14.2394%2043.8402%2018.3277%2044.9995%2022.4982%2044.9997Z%22%20fill%3D%22%2334A853%22%2F%3E%3Cpath%20d%3D%22M9.86737%2026.8073C8.92572%2024.0138%208.92572%2020.9886%209.86737%2018.1951V12.3984H2.39576C0.820432%2015.5332%200%2018.9929%200%2022.5012C0%2026.0095%200.820432%2029.4692%202.39576%2032.604L9.86737%2026.8073Z%22%20fill%3D%22%23FBBC04%22%2F%3E%3Cpath%20d%3D%22M22.4982%208.90741C25.7068%208.85499%2028.8071%2010.0673%2031.1291%2012.2823L37.5507%205.86064C33.4788%202.03602%2028.0843%20-0.0637686%2022.4982%200.00147616C18.3277%200.00166623%2014.2394%201.16098%2010.6896%203.34999C7.13989%205.539%204.26839%208.67155%202.39575%2012.3979L9.86736%2018.1946C11.6485%2012.8635%2016.6296%208.90741%2022.4982%208.90741Z%22%20fill%3D%22%23EA4335%22%2F%3E%3C%2Fsvg%3E";async function l7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Le(e.env)}callback`,i=new F2(n.client_id,n.client_secret,r),s=Oe(),a=Tu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function u7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new F2(i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),c=Na(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Go.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const d7=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:a7,displayName:s7,getRedirect:l7,logoDataUri:c7,validateAuthorizationCodeAndGetUser:u7},Symbol.toStringTag,{value:"Module"})),p7="Vipps",f7="data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%20width%3D%2245%22%20height%3D%2245%22%3E%3Cpath%20fill%3D%22%23FF5B24%22%20d%3D%22M3.5%2C8h41c1.9%2C0%2C3.5%2C1.6%2C3.5%2C3.5v25c0%2C1.9-1.6%2C3.5-3.5%2C3.5h-41C1.6%2C40%2C0%2C38.4%2C0%2C36.5v-25C0%2C9.6%2C1.6%2C8%2C3.5%2C8z%22%2F%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20fill%3D%22%23FFFFFF%22%20d%3D%22M27.9%2C20.3c1.4%2C0%2C2.6-1%2C2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4%2C0-2.6%2C1-2.6%2C2.5C25.3%2C19.2%2C26.5%2C20.3%2C27.9%2C20.3z%20M31.2%2C24.4c-1.7%2C2.2-3.5%2C3.8-6.7%2C3.8h0c-3.2%2C0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8%2C0.6-1%2C1.8-0.3%2C2.9%20c2.7%2C4.1%2C6.5%2C6.6%2C10.9%2C6.6c4%2C0%2C7.2-2%2C9.6-5.2c0.9-1.2%2C0.9-2.5%2C0-3.1C33.3%2C22.9%2C32.1%2C23.2%2C31.2%2C24.4z%22%2F%3E%3C%2Fsvg%3E";async function h7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Ri(n.client_id,n.client_secret,`${Le(e.env)}callback`),i=Oe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,n.scope?.split(" ")||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function _7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Ri(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=Na(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Go.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new X(400,{message:"Failed to get user from vipps"});return await l.json()}const m7=Object.freeze(Object.defineProperty({__proto__:null,displayName:p7,getRedirect:h7,logoDataUri:f7,validateAuthorizationCodeAndGetUser:_7},Symbol.toStringTag,{value:"Module"})),g7="GitHub",y7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M22.5%200C10.074%200%200%2010.335%200%2023.077C0%2033.266%206.444%2041.895%2015.39%2044.955C16.515%2045.165%2016.935%2044.46%2016.935%2043.857C16.935%2043.32%2016.92%2041.865%2016.905%2039.99C10.65%2041.355%209.33%2036.99%209.33%2036.99C8.31%2034.32%206.825%2033.615%206.825%2033.615C4.77%2032.205%206.975%2032.235%206.975%2032.235C9.24%2032.385%2010.425%2034.59%2010.425%2034.59C12.45%2038.13%2015.75%2037.125%2017.01%2036.555C17.22%2035.07%2017.82%2034.065%2018.48%2033.51C13.455%2032.94%208.19%2030.93%208.19%2022.035C8.19%2019.5%209.075%2017.43%2010.47%2015.81C10.23%2015.24%209.435%2012.87%2010.695%209.66C10.695%209.66%2012.585%209.045%2016.875%2012.06C18.675%2011.565%2020.595%2011.31%2022.5%2011.31C24.405%2011.31%2026.325%2011.565%2028.125%2012.06C32.415%209.045%2034.305%209.66%2034.305%209.66C35.565%2012.87%2034.77%2015.24%2034.53%2015.81C35.925%2017.43%2036.81%2019.5%2036.81%2022.035C36.81%2030.96%2031.53%2032.925%2026.49%2033.48C27.33%2034.2%2028.095%2035.625%2028.095%2037.815C28.095%2040.95%2028.065%2043.47%2028.065%2043.857C28.065%2044.46%2028.485%2045.18%2029.625%2044.955C38.571%2041.88%2045%2033.252%2045%2023.077C45%2010.335%2034.926%200%2022.5%200Z%22%20fill%3D%22%23181717%22%2F%3E%3C%2Fsvg%3E";async function b7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${Le(e.env)}callback`,i=new q2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function v7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new q2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json(),l=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});let u=c.email;if(l.ok){const d=await l.json(),f=d.find(p=>p.primary&&p.verified)||d.find(p=>p.verified);f&&(u=f.email)}return e.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:u,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const w7=Object.freeze(Object.defineProperty({__proto__:null,displayName:g7,getRedirect:b7,logoDataUri:y7,validateAuthorizationCodeAndGetUser:v7},Symbol.toStringTag,{value:"Module"})),k7="Microsoft",$7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22%23F25022%22%20d%3D%22M0%200H21.43V21.43H0V0Z%22%2F%3E%3Cpath%20fill%3D%22%237FBA00%22%20d%3D%22M23.57%200H45V21.43H23.57V0Z%22%2F%3E%3Cpath%20fill%3D%22%2300A4EF%22%20d%3D%22M0%2023.57H21.43V45H0V23.57Z%22%2F%3E%3Cpath%20fill%3D%22%23FFB900%22%20d%3D%22M23.57%2023.57H45V45H23.57V23.57Z%22%2F%3E%3C%2Fsvg%3E";async function S7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${Le(e.env)}callback`,i=n.realms||"common",s=new H2(i,n.client_id,n.client_secret,r),a=Oe(),c=Tu();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function x7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new H2(s,i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),l=Na(c.idToken());if(!l)throw new Error("Invalid ID token");const u=Go.parse(l.payload);return e.set("log",`Microsoft user: ${JSON.stringify(u)}`),{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture}}const z7=Object.freeze(Object.defineProperty({__proto__:null,displayName:k7,getRedirect:S7,logoDataUri:$7,validateAuthorizationCodeAndGetUser:x7},Symbol.toStringTag,{value:"Module"})),A7="OpenID Connect",E7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C10.074%200%200%2010.074%200%2022.5S10.074%2045%2022.5%2045%2045%2034.926%2045%2022.5%2034.926%200%2022.5%200zm0%2040.5c-9.941%200-18-8.059-18-18s8.059-18%2018-18%2018%208.059%2018%2018-8.059%2018-18%2018z%22%20fill%3D%22%23F7931E%22%2F%3E%3Cpath%20d%3D%22M22.5%209c-7.456%200-13.5%206.044-13.5%2013.5S15.044%2036%2022.5%2036%2036%2029.956%2036%2022.5%2029.956%209%2022.5%209zm0%2022.5c-4.971%200-9-4.029-9-9s4.029-9%209-9%209%204.029%209%209-4.029%209-9%209z%22%20fill%3D%22%23F7931E%22%2F%3E%3C%2Fsvg%3E";async function C7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${Le(e.env)}callback`,i=new Ri(n.client_id,n.client_secret||null,r),s=U2(),a=Tu(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,_i.S256,a,c).href,code:s,codeVerifier:a}}async function I7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ri(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const u=Na(c.idToken());if(u?.payload){const d=Go.passthrough().parse(u.payload);return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}}if(i.userinfo_endpoint){const u=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!u.ok)throw new Error("Failed to fetch user info");const d=await u.json();if(!d.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const j7=Object.freeze(Object.defineProperty({__proto__:null,displayName:A7,getRedirect:C7,logoDataUri:E7,validateAuthorizationCodeAndGetUser:I7},Symbol.toStringTag,{value:"Module"})),N7="OAuth 2.0",T7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C14.492%200%208%206.492%208%2014.5V18H5v22h35V18h-3v-3.5C37%206.492%2030.508%200%2022.5%200zm0%204c5.799%200%2010.5%204.701%2010.5%2010.5V18h-21v-3.5C12%208.701%2016.701%204%2022.5%204z%22%20fill%3D%22%236B7280%22%2F%3E%3Ccircle%20cx%3D%2222.5%22%20cy%3D%2229%22%20r%3D%223%22%20fill%3D%22%236B7280%22%2F%3E%3C%2Fsvg%3E";async function P7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${Le(e.env)}callback`,i=new Ri(n.client_id,n.client_secret||null,r),s=U2(),a=Tu(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,_i.S256,a,c).href,code:s,codeVerifier:a}}async function O7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ri(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(!i.userinfo_endpoint)throw new Error("Missing userinfo_endpoint for OAuth2 provider");const l=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!l.ok)throw new Error("Failed to fetch user info");const u=await l.json(),d=u.sub||u.id||u.user_id;if(!d)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:d,email:u.email,given_name:u.given_name||u.first_name,family_name:u.family_name||u.last_name,name:u.name||`${u.given_name||u.first_name||""} ${u.family_name||u.last_name||""}`.trim()}}const R7=Object.freeze(Object.defineProperty({__proto__:null,displayName:N7,getRedirect:P7,logoDataUri:T7,validateAuthorizationCodeAndGetUser:O7},Symbol.toStringTag,{value:"Module"})),Pu={apple:e7,facebook:o7,"google-oauth2":d7,vipps:m7,github:w7,microsoft:z7,oidc:j7,oauth2:R7};function K2(e,t){const n=e.env.STRATEGIES||{},i={...Pu,...n}[t];if(!i)throw new Error(`Strategy ${t} not found`);return i}const L7=new Set(["oidc","samlp","waad","adfs","oauth2"]);function G2(e){return L7.has(e.strategy)?e.name:e.strategy}function W2(e){return e.options?.icon_url?e.options.icon_url:Pu[e.strategy]?.logoDataUri}const D7=["email","email_verified","phone_number","phone_verified","username"];function gg(e){const t={connection:e.connection,provider:e.provider,user_id:ff(e.user_id),isSocial:e.is_social};for(const n of D7)e[n]!==void 0&&e[n]!==null&&(t[n]=e[n]);return t}const yg=Nt.extend({users:o.z.array(In)}),U7=Nt.extend({sessions:o.z.array(yu)}),B7=Nt.extend({organizations:o.z.array(mr)}),M7=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:it,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(In),yg])}},description:"List of users"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query");if(s?.includes("identities.profileData.email")){const u=s.split("=")[1],f=(await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,q:`email:${u}`})).users.filter(_=>_.linked_to),[p]=f;if(!p)return e.json([]);const h=await e.env.data.users.get(e.var.tenant_id,p.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return e.json([In.parse(h)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ft(i),q:a.join(" ")}),l=c.users.filter(u=>!u.linked_to);return r?e.json(yg.parse({users:l,length:c.length,start:c.start,limit:c.limit})):e.json(o.z.array(In).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:In}},description:"List of users"}}}),async e=>{const{user_id:t}=e.req.valid("param"),n=await e.env.data.users.get(e.var.tenant_id,t);if(!n)throw new I(404);if(n.linked_to)throw new I(404,{message:"User is linked to another user"});return e.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["delete:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.remove(e.var.tenant_id,t))throw new I(404);return await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),e.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...el.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["create:users","auth:write"]}],responses:{201:{content:{"application/json":{schema:In}},description:"Status"}}}),async e=>{const t=e.req.valid("json");e.set("body",t);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:u}=t,d=await e.env.data.connections.get(e.var.tenant_id,l),f=d?G2(d):c||l,p=t.user_id,h=p?ff(p):Ti(),_=`${f}|${h}`;try{let g;u&&(g=await la(u));const y={email:n,user_id:_,name:i||n||r,phone_number:r,provider:f,connection:l,linked_to:s??void 0,email_verified:a||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString(),...g&&{password:g}},m=await e.env.data.users.create(e.var.tenant_id,y);e.set("user_id",m.user_id),await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"User created"});const w=m.identities?m:{...m,identities:[gg(m)]};return e.json(In.parse(w),{status:201})}catch(g){throw g.message==="User already exists"?new I(409,{message:"User already exists"}):g}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...el.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{data:t}=e.env,n=e.req.valid("json"),{user_id:r}=e.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await t.users.get(e.var.tenant_id,r);if(!l)throw new I(404);if(l.linked_to)throw new I(404,{message:"User is linked to another user"});let u=r,d=l;if(a)if(l.connection===a)u=r,d=l;else{const h=(await t.users.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(_=>_.connection===a);if(!h)throw new I(404,{message:`No identity found with connection: ${a}`});u=h.user_id,d=h}if(c.email&&c.email!==d.email){const p=await U0(e.env.data.users,e.var.tenant_id,c.email);if(p.length&&p.some(h=>h.user_id!==u))throw new I(409,{message:"Another user with the same email address already exists."})}if(await e.env.data.users.update(e.var.tenant_id,u,c),s){let p;if(a)if(a==="Username-Password-Authentication")p={provider:d.provider,user_id:ff(u)};else throw new I(400,{message:`Cannot set password for connection: ${a}`});else if(p=l.identities?.find(m=>m.connection==="Username-Password-Authentication"),!p)throw new I(400,{message:"User does not have a password identity"});const h=`${p.provider}|${p.user_id}`,_=await t.passwords.get(e.var.tenant_id,h);_&&await t.passwords.update(e.var.tenant_id,{id:_.id,user_id:h,password:_.password,algorithm:_.algorithm,is_current:!1});const{hash:g,algorithm:y}=await la(s);await t.passwords.create(e.var.tenant_id,{user_id:h,password:g,algorithm:y,is_current:!0})}const f=await e.env.data.users.get(e.var.tenant_id,r);if(!f)throw new I(500);return await fe(e,e.var.tenant_id,{type:pe.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),e.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.array(Qc)}},description:"Status"}}}),async e=>{const t=e.req.valid("json"),{user_id:n}=e.req.valid("param"),r="link_with"in t?t.link_with:t.user_id,i=await e.env.data.users.get(e.var.tenant_id,n);if(!i)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await e.env.data.users.update(e.var.tenant_id,r,{linked_to:n});const s=await e.env.data.users.list(e.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(gg);return e.json(o.z.array(Qc).parse(a),{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(In)}},description:"Status"}}}),async e=>{const{user_id:t,provider:n,linked_user_id:r}=e.req.valid("param");await e.env.data.users.unlink(e.var.tenant_id,t,n,r);const i=await e.env.data.users.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json([In.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:it,headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(yu),U7])}},description:"List of sessions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{include_totals:n,page:r,per_page:i}=e.req.valid("query"),s=await e.env.data.sessions.list(e.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${t}`});return n?e.json(s):e.json(s.sessions)}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:it},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:Iw}},description:"User permissions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userPermissions.list(e.var.tenant_id,t,{page:n,per_page:r,include_totals:!1,sort:ft(i),q:s});return e.json(c)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.create(e.var.tenant_id,t,{user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new I(500,{message:"Failed to assign permissions to user"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.remove(e.var.tenant_id,t,i))throw new I(500,{message:"Failed to remove permissions from user"});return e.json({message:"Permissions removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:ll}},description:"User roles"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const r=await e.env.data.userRoles.list(e.var.tenant_id,t,void 0,"");return e.json(r)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.create(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to assign roles to user"});return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.remove(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to remove roles from user"});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/organizations",request:{params:o.z.object({user_id:o.z.string()}),query:it,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([B7,o.z.array(mr)])}},description:"List of user organizations"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userOrganizations.listUserOrganizations(e.var.tenant_id,t,{page:n,per_page:r,sort:ft(s)});return i?e.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):e.json(c.organizations)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/organizations/{organization_id}",request:{params:o.z.object({user_id:o.z.string(),organization_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async e=>{const{user_id:t,organization_id:n}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const s=(await e.env.data.userOrganizations.list(e.var.tenant_id,{q:`user_id:${t}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new I(404,{message:"User is not a member of this organization"});return await e.env.data.userOrganizations.remove(e.var.tenant_id,s.id),e.json({message:"User removed from organization successfully"})});var bg={};var vg;function q7(){if(vg)return bg;vg=1;var e;return(function(t){(function(n){var r=typeof globalThis=="object"?globalThis:typeof Nm=="object"?Nm:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(t);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(u,d){return function(f,p){Object.defineProperty(u,f,{configurable:!0,writable:!0,value:p}),d&&d(f,p)}}function a(){try{return Function("return this;")()}catch{}}function c(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return a()||c()}})(function(n,r){var i=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",a=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",c=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!l&&!u,f={create:l?function(){return qd(Object.create(null))}:u?function(){return qd({__proto__:null})}:function(){return qd({})},has:d?function(O,U){return i.call(O,U)}:function(O,U){return U in O},get:d?function(O,U){return i.call(O,U)?O[U]:void 0}:function(O,U){return O[U]}},p=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:pc(),_=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Md(),g=typeof WeakMap=="function"?WeakMap:gS(),y=s?Symbol.for("@reflect-metadata:registry"):void 0,m=Mn(),w=Zt(m);function k(O,U,q,Z){if(F(q)){if(!Y(O))throw new TypeError;if(!me(U))throw new TypeError;return B(O,U)}else{if(!Y(O))throw new TypeError;if(!ue(U))throw new TypeError;if(!ue(Z)&&!F(Z)&&!Pe(Z))throw new TypeError;return Pe(Z)&&(Z=void 0),q=M(q),V(O,U,q,Z)}}n("decorate",k);function S(O,U){function q(Z,de){if(!ue(Z))throw new TypeError;if(!F(de)&&!Ye(de))throw new TypeError;ve(O,U,Z,de)}return q}n("metadata",S);function v(O,U,q,Z){if(!ue(q))throw new TypeError;return F(Z)||(Z=M(Z)),ve(O,U,q,Z)}n("defineMetadata",v);function x(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),L(O,U,q)}n("hasMetadata",x);function A(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),Q(O,U,q)}n("hasOwnMetadata",A);function E(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),ae(O,U,q)}n("getMetadata",E);function P(O,U,q){if(!ue(U))throw new TypeError;return F(q)||(q=M(q)),ce(O,U,q)}n("getOwnMetadata",P);function D(O,U){if(!ue(O))throw new TypeError;return F(U)||(U=M(U)),Ee(O,U)}n("getMetadataKeys",D);function C(O,U){if(!ue(O))throw new TypeError;return F(U)||(U=M(U)),le(O,U)}n("getOwnMetadataKeys",C);function R(O,U,q){if(!ue(U))throw new TypeError;if(F(q)||(q=M(q)),!ue(U))throw new TypeError;F(q)||(q=M(q));var Z=Vr(U,q,!1);return F(Z)?!1:Z.OrdinaryDeleteMetadata(O,U,q)}n("deleteMetadata",R);function B(O,U){for(var q=O.length-1;q>=0;--q){var Z=O[q],de=Z(U);if(!F(de)&&!Pe(de)){if(!me(de))throw new TypeError;U=de}}return U}function V(O,U,q,Z){for(var de=O.length-1;de>=0;--de){var nt=O[de],et=nt(U,q,Z);if(!F(et)&&!Pe(et)){if(!ue(et))throw new TypeError;Z=et}}return Z}function L(O,U,q){var Z=Q(O,U,q);if(Z)return!0;var de=ze(U);return Pe(de)?!1:L(O,de,q)}function Q(O,U,q){var Z=Vr(U,q,!1);return F(Z)?!1:Mi(Z.OrdinaryHasOwnMetadata(O,U,q))}function ae(O,U,q){var Z=Q(O,U,q);if(Z)return ce(O,U,q);var de=ze(U);if(!Pe(de))return ae(O,de,q)}function ce(O,U,q){var Z=Vr(U,q,!1);if(!F(Z))return Z.OrdinaryGetOwnMetadata(O,U,q)}function ve(O,U,q,Z){var de=Vr(q,Z,!0);de.OrdinaryDefineOwnMetadata(O,U,q,Z)}function Ee(O,U){var q=le(O,U),Z=ze(O);if(Z===null)return q;var de=Ee(Z,U);if(de.length<=0)return q;if(q.length<=0)return de;for(var nt=new _,et=[],we=0,ee=q;we<ee.length;we++){var re=ee[we],oe=nt.has(re);oe||(nt.add(re),et.push(re))}for(var se=0,ke=de;se<ke.length;se++){var re=ke[se],oe=nt.has(re);oe||(nt.add(re),et.push(re))}return et}function le(O,U){var q=Vr(O,U,!1);return q?q.OrdinaryOwnMetadataKeys(O,U):[]}function Se(O){if(O===null)return 1;switch(typeof O){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return O===null?1:6;default:return 6}}function F(O){return O===void 0}function Pe(O){return O===null}function xt(O){return typeof O=="symbol"}function ue(O){return typeof O=="object"?O!==null:typeof O=="function"}function Xe(O,U){switch(Se(O)){case 0:return O;case 1:return O;case 2:return O;case 3:return O;case 4:return O;case 5:return O}var q="string",Z=Ud(O,a);if(Z!==void 0){var de=Z.call(O,q);if(ue(de))throw new TypeError;return de}return Hr(O)}function Hr(O,U){var q,Z;{var de=O.toString;if(G(de)){var Z=de.call(O);if(!ue(Z))return Z}var q=O.valueOf;if(G(q)){var Z=q.call(O);if(!ue(Z))return Z}}throw new TypeError}function Mi(O){return!!O}function qi(O){return""+O}function M(O){var U=Xe(O);return xt(U)?U:qi(U)}function Y(O){return Array.isArray?Array.isArray(O):O instanceof Object?O instanceof Array:Object.prototype.toString.call(O)==="[object Array]"}function G(O){return typeof O=="function"}function me(O){return typeof O=="function"}function Ye(O){switch(Se(O)){case 3:return!0;case 4:return!0;default:return!1}}function Qe(O,U){return O===U||O!==O&&U!==U}function Ud(O,U){var q=O[U];if(q!=null){if(!G(q))throw new TypeError;return q}}function Bd(O){var U=Ud(O,c);if(!G(U))throw new TypeError;var q=U.call(O);if(!ue(q))throw new TypeError;return q}function Ie(O){return O.value}function xe(O){var U=O.next();return U.done?!1:U}function Fi(O){var U=O.return;U&&U.call(O)}function ze(O){var U=Object.getPrototypeOf(O);if(typeof O!="function"||O===p||U!==p)return U;var q=O.prototype,Z=q&&Object.getPrototypeOf(q);if(Z==null||Z===Object.prototype)return U;var de=Z.constructor;return typeof de!="function"||de===O?U:de}function je(){var O;!F(y)&&typeof r.Reflect<"u"&&!(y in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(O=Ot(r.Reflect));var U,q,Z,de=new g,nt={registerProvider:et,getProvider:ee,setProvider:oe};return nt;function et(se){if(!Object.isExtensible(nt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case O===se:break;case F(U):U=se;break;case U===se:break;case F(q):q=se;break;case q===se:break;default:Z===void 0&&(Z=new _),Z.add(se);break}}function we(se,ke){if(!F(U)){if(U.isProviderFor(se,ke))return U;if(!F(q)){if(q.isProviderFor(se,ke))return U;if(!F(Z))for(var Re=Bd(Z);;){var Ke=xe(Re);if(!Ke)return;var Xt=Ie(Ke);if(Xt.isProviderFor(se,ke))return Fi(Re),Xt}}}if(!F(O)&&O.isProviderFor(se,ke))return O}function ee(se,ke){var Re=de.get(se),Ke;return F(Re)||(Ke=Re.get(ke)),F(Ke)&&(Ke=we(se,ke),F(Ke)||(F(Re)&&(Re=new h,de.set(se,Re)),Re.set(ke,Ke))),Ke}function re(se){if(F(se))throw new TypeError;return U===se||q===se||!F(Z)&&Z.has(se)}function oe(se,ke,Re){if(!re(Re))throw new Error("Metadata provider not registered.");var Ke=ee(se,ke);if(Ke!==Re){if(!F(Ke))return!1;var Xt=de.get(se);F(Xt)&&(Xt=new h,de.set(se,Xt)),Xt.set(ke,Re)}return!0}}function Mn(){var O;return!F(y)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&(O=r.Reflect[y]),F(O)&&(O=je()),!F(y)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:O}),O}function Zt(O){var U=new g,q={isProviderFor:function(re,oe){var se=U.get(re);return F(se)?!1:se.has(oe)},OrdinaryDefineOwnMetadata:et,OrdinaryHasOwnMetadata:de,OrdinaryGetOwnMetadata:nt,OrdinaryOwnMetadataKeys:we,OrdinaryDeleteMetadata:ee};return m.registerProvider(q),q;function Z(re,oe,se){var ke=U.get(re),Re=!1;if(F(ke)){if(!se)return;ke=new h,U.set(re,ke),Re=!0}var Ke=ke.get(oe);if(F(Ke)){if(!se)return;if(Ke=new h,ke.set(oe,Ke),!O.setProvider(re,oe,q))throw ke.delete(oe),Re&&U.delete(re),new Error("Wrong provider for target.")}return Ke}function de(re,oe,se){var ke=Z(oe,se,!1);return F(ke)?!1:Mi(ke.has(re))}function nt(re,oe,se){var ke=Z(oe,se,!1);if(!F(ke))return ke.get(re)}function et(re,oe,se,ke){var Re=Z(se,ke,!0);Re.set(re,oe)}function we(re,oe){var se=[],ke=Z(re,oe,!1);if(F(ke))return se;for(var Re=ke.keys(),Ke=Bd(Re),Xt=0;;){var pm=xe(Ke);if(!pm)return se.length=Xt,se;var yS=Ie(pm);try{se[Xt]=yS}catch(bS){try{Fi(Ke)}finally{throw bS}}Xt++}}function ee(re,oe,se){var ke=Z(oe,se,!1);if(F(ke)||!ke.delete(re))return!1;if(ke.size===0){var Re=U.get(oe);F(Re)||(Re.delete(se),Re.size===0&&U.delete(Re))}return!0}}function Ot(O){var U=O.defineMetadata,q=O.hasOwnMetadata,Z=O.getOwnMetadata,de=O.getOwnMetadataKeys,nt=O.deleteMetadata,et=new g,we={isProviderFor:function(ee,re){var oe=et.get(ee);return!F(oe)&&oe.has(re)?!0:de(ee,re).length?(F(oe)&&(oe=new _,et.set(ee,oe)),oe.add(re),!0):!1},OrdinaryDefineOwnMetadata:U,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:Z,OrdinaryOwnMetadataKeys:de,OrdinaryDeleteMetadata:nt};return we}function Vr(O,U,q){var Z=m.getProvider(O,U);if(!F(Z))return Z;if(q){if(m.setProvider(O,U,w))return w;throw new Error("Illegal state.")}}function pc(){var O={},U=[],q=(function(){function we(ee,re,oe){this._index=0,this._keys=ee,this._values=re,this._selector=oe}return we.prototype["@@iterator"]=function(){return this},we.prototype[c]=function(){return this},we.prototype.next=function(){var ee=this._index;if(ee>=0&&ee<this._keys.length){var re=this._selector(this._keys[ee],this._values[ee]);return ee+1>=this._keys.length?(this._index=-1,this._keys=U,this._values=U):this._index++,{value:re,done:!1}}return{value:void 0,done:!0}},we.prototype.throw=function(ee){throw this._index>=0&&(this._index=-1,this._keys=U,this._values=U),ee},we.prototype.return=function(ee){return this._index>=0&&(this._index=-1,this._keys=U,this._values=U),{value:ee,done:!0}},we})(),Z=(function(){function we(){this._keys=[],this._values=[],this._cacheKey=O,this._cacheIndex=-2}return Object.defineProperty(we.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),we.prototype.has=function(ee){return this._find(ee,!1)>=0},we.prototype.get=function(ee){var re=this._find(ee,!1);return re>=0?this._values[re]:void 0},we.prototype.set=function(ee,re){var oe=this._find(ee,!0);return this._values[oe]=re,this},we.prototype.delete=function(ee){var re=this._find(ee,!1);if(re>=0){for(var oe=this._keys.length,se=re+1;se<oe;se++)this._keys[se-1]=this._keys[se],this._values[se-1]=this._values[se];return this._keys.length--,this._values.length--,Qe(ee,this._cacheKey)&&(this._cacheKey=O,this._cacheIndex=-2),!0}return!1},we.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=O,this._cacheIndex=-2},we.prototype.keys=function(){return new q(this._keys,this._values,de)},we.prototype.values=function(){return new q(this._keys,this._values,nt)},we.prototype.entries=function(){return new q(this._keys,this._values,et)},we.prototype["@@iterator"]=function(){return this.entries()},we.prototype[c]=function(){return this.entries()},we.prototype._find=function(ee,re){if(!Qe(this._cacheKey,ee)){this._cacheIndex=-1;for(var oe=0;oe<this._keys.length;oe++)if(Qe(this._keys[oe],ee)){this._cacheIndex=oe;break}}return this._cacheIndex<0&&re&&(this._cacheIndex=this._keys.length,this._keys.push(ee),this._values.push(void 0)),this._cacheIndex},we})();return Z;function de(we,ee){return we}function nt(we,ee){return ee}function et(we,ee){return[we,ee]}}function Md(){var O=(function(){function U(){this._map=new h}return Object.defineProperty(U.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),U.prototype.has=function(q){return this._map.has(q)},U.prototype.add=function(q){return this._map.set(q,q),this},U.prototype.delete=function(q){return this._map.delete(q)},U.prototype.clear=function(){this._map.clear()},U.prototype.keys=function(){return this._map.keys()},U.prototype.values=function(){return this._map.keys()},U.prototype.entries=function(){return this._map.entries()},U.prototype["@@iterator"]=function(){return this.keys()},U.prototype[c]=function(){return this.keys()},U})();return O}function gS(){var O=16,U=f.create(),q=Z();return(function(){function ee(){this._key=Z()}return ee.prototype.has=function(re){var oe=de(re,!1);return oe!==void 0?f.has(oe,this._key):!1},ee.prototype.get=function(re){var oe=de(re,!1);return oe!==void 0?f.get(oe,this._key):void 0},ee.prototype.set=function(re,oe){var se=de(re,!0);return se[this._key]=oe,this},ee.prototype.delete=function(re){var oe=de(re,!1);return oe!==void 0?delete oe[this._key]:!1},ee.prototype.clear=function(){this._key=Z()},ee})();function Z(){var ee;do ee="@@WeakMap@@"+we();while(f.has(U,ee));return U[ee]=!0,ee}function de(ee,re){if(!i.call(ee,q)){if(!re)return;Object.defineProperty(ee,q,{value:f.create()})}return ee[q]}function nt(ee,re){for(var oe=0;oe<re;++oe)ee[oe]=Math.random()*255|0;return ee}function et(ee){if(typeof Uint8Array=="function"){var re=new Uint8Array(ee);return typeof crypto<"u"?crypto.getRandomValues(re):typeof msCrypto<"u"?msCrypto.getRandomValues(re):nt(re,ee),re}return nt(new Array(ee),ee)}function we(){var ee=et(O);ee[6]=ee[6]&79|64,ee[8]=ee[8]&191|128;for(var re="",oe=0;oe<O;++oe){var se=ee[oe];(oe===4||oe===6||oe===8)&&(re+="-"),se<16&&(re+="0"),re+=se.toString(16).toLowerCase()}return re}}function qd(O){return O.__=void 0,delete O.__,O}})})(e||(e={})),bg}q7();const F7="[object ArrayBuffer]";class J{static isArrayBuffer(t){return Object.prototype.toString.call(t)===F7}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,n){if(t.constructor===n)return t;if(this.isArrayBuffer(t))return new n(t);if(this.isArrayBufferView(t))return new n(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,n){const r=J.toUint8Array(t),i=J.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let s=0;s<r.length;s++)if(r[s]!==i[s])return!1;return!0}static concat(...t){let n;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?n=t[0]:t[t.length-1]instanceof Function?n=t.slice(0,t.length-1):n=t;let r=0;for(const a of n)r+=a.byteLength;const i=new Uint8Array(r);let s=0;for(const a of n){const c=this.toUint8Array(a);i.set(c,s),s+=c.length}return t[t.length-1]instanceof Function?this.toView(i,t[t.length-1]):i.buffer}}const Jd="string",H7=/^[0-9a-f\s]+$/i,V7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,K7=/^[a-zA-Z0-9-_]+$/;class wg{static fromString(t){const n=unescape(encodeURIComponent(t)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(t){const n=J.toUint8Array(t);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class $n{static toString(t,n=!1){const r=J.toArrayBuffer(t),i=new DataView(r);let s="";for(let a=0;a<r.byteLength;a+=2){const c=i.getUint16(a,n);s+=String.fromCharCode(c)}return s}static fromString(t,n=!1){const r=new ArrayBuffer(t.length*2),i=new DataView(r);for(let s=0;s<t.length;s++)i.setUint16(s*2,t.charCodeAt(s),n);return r}}class ie{static isHex(t){return typeof t===Jd&&H7.test(t)}static isBase64(t){return typeof t===Jd&&V7.test(t)}static isBase64Url(t){return typeof t===Jd&&K7.test(t)}static ToString(t,n="utf8"){const r=J.toUint8Array(t);switch(n.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return $n.toString(r,!0);case"utf16":case"utf16be":return $n.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(t,n="utf8"){if(!t)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return $n.fromString(t,!0);case"utf16":case"utf16be":return $n.fromString(t);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(t){const n=J.toUint8Array(t);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64(n))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,"base64")).buffer}static FromBase64Url(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(t);case"utf8":return wg.fromString(t);case"utf16":case"utf16be":return $n.fromString(t);case"utf16le":case"usc2":return $n.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(t);case"utf8":return wg.toString(t);case"utf16":case"utf16be":return $n.toString(t);case"utf16le":case"usc2":return $n.toString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(t){const n=t.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=t.charCodeAt(i);return r.buffer}static ToBinary(t){const n=J.toUint8Array(t);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(t){const n=J.toUint8Array(t);let r="";const i=n.length;for(let s=0;s<i;s++){const a=n[s];a<16&&(r+="0"),r+=a.toString(16)}return r}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isHex(n))throw new TypeError("Argument 'hexString' is not HEX encoded");n.length%2&&(n=`0${n}`);const r=new Uint8Array(n.length/2);for(let i=0;i<n.length;i=i+2){const s=n.slice(i,i+2);r[i/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(t,n=!1){return $n.toString(t,n)}static FromUtf16String(t,n=!1){return $n.fromString(t,n)}static Base64Padding(t){const n=4-t.length%4;if(n<4)for(let r=0;r<n;r++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}}ie.DEFAULT_UTF8_ENCODING="utf8";function G7(...e){const t=e.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(t);let r=0;return e.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function J2(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<e.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function zo(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*Math.pow(2,t*r);return n}function mi(e,t,n=-1){const r=n;let i=e,s=0,a=Math.pow(2,t);for(let c=1;c<8;c++){if(e<a){let l;if(r<0)l=new ArrayBuffer(c),s=c;else{if(r<c)return new ArrayBuffer(0);l=new ArrayBuffer(r),s=r}const u=new Uint8Array(l);for(let d=c-1;d>=0;d--){const f=Math.pow(2,d*t);u[s-d-1]=Math.floor(i/f),i-=u[s-d-1]*f}return l}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ef(...e){let t=0,n=0;for(const s of e)t+=s.length;const r=new ArrayBuffer(t),i=new Uint8Array(r);for(const s of e)i.set(s,n),n+=s.length;return i}function Z2(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=e[0]===255&&e[1]&128,l=e[0]===0&&(e[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=e[0]&128;const r=zo(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=e[c];return s[0]&=127,zo(s,8)-r}function W7(e){const t=e<0?e*-1:e;let n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){const a=n-t,c=mi(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=mi(t,8,r),s=new Uint8Array(i);if(s[0]&128){const a=i.slice(0),c=new Uint8Array(a);i=new ArrayBuffer(i.byteLength+1),s=new Uint8Array(i);for(let l=0;l<a.byteLength;l++)s[l+1]=c[l];s[0]=0}return i}n*=Math.pow(2,8)}return new ArrayBuffer(0)}function J7(e,t){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function Rt(e,t){const n=e.toString(10);if(t<n.length)return"";const r=t-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function kl(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function V0(e){let t=0,n=0;for(let i=0;i<e.length;i++){const s=e[i];t+=s.byteLength}const r=new Uint8Array(t);for(let i=0;i<e.length;i++){const s=e[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function or(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-n-r<0?(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Ou{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return V0(this.items)}}const ps=[new Uint8Array([1])],kg="0123456789",Zd="name",$g="valueHexView",Z7="isHexOnly",X7="idBlock",Y7="tagClass",Q7="tagNumber",eC="isConstructed",tC="fromBER",nC="toBER",rC="local",It="",Ln=new ArrayBuffer(0),Ru=new Uint8Array(0),da="EndOfContent",X2="OCTET STRING",Y2="BIT STRING";function Dn(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(r){this.valueHexView=new Uint8Array(r)}constructor(...r){var i;super(...r);const s=r[0]||{};this.isHexOnly=(i=s.isHexOnly)!==null&&i!==void 0?i:!1,this.valueHexView=s.valueHex?J.toUint8Array(s.valueHex):Ru}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!or(this,a,i,s))return-1;const c=i+s;return this.valueHexView=a.subarray(i,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),i)}toBER(r=!1){return this.isHexOnly?r?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Ln)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ie.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Li{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}constructor({blockLength:t=0,error:n=It,warnings:r=[],valueBeforeDecode:i=Ru}={}){this.blockLength=t,this.error=n,this.warnings=r,this.valueBeforeDecodeView=J.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ie.ToHex(this.valueBeforeDecodeView)}}}Li.NAME="baseBlock";class $t extends Li{fromBER(t,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}$t.NAME="valueBlock";class Q2 extends Dn(Li){constructor({idBlock:t={}}={}){var n,r,i,s;super(),t?(this.isHexOnly=(n=t.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=t.valueHex?J.toUint8Array(t.valueHex):Ru,this.tagClass=(r=t.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=t.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let n=0;switch(this.tagClass){case 1:n|=0;break;case 2:n|=64;break;case 3:n|=128;break;case 4:n|=192;break;default:return this.error="Unknown tag class",Ln}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=mi(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!t){for(let l=0;l<a-1;l++)c[l+1]=s[l]|128;c[a]=s[a-1]}return c.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=n|31,!t){const i=this.valueHexView;for(let s=0;s<i.length-1;s++)r[s+1]=i[s]|128;r[this.valueHexView.byteLength]=i[i.length-1]}return r.buffer}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const c=s[0]&31;if(c!==31)this.tagNumber=c,this.blockLength=1;else{let l=1,u=this.valueHexView=new Uint8Array(255),d=255;for(;s[l]&128;){if(u[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===d){d+=255;const p=new Uint8Array(d);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(d)}}this.blockLength=l+1,u[l-1]=s[l]&127;const f=new Uint8Array(l);for(let p=0;p<l;p++)f[p]=u[p];u=this.valueHexView=new Uint8Array(l),u.set(f),this.blockLength<=9?this.tagNumber=zo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return n+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Q2.NAME="identificationBlock";class e3 extends Li{constructor({lenBlock:t={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=t.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=t.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=t.length)!==null&&i!==void 0?i:0}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,n+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,n+this.blockLength;const a=s[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const c=n+1,l=i.subarray(c,c+a);return l[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=zo(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(t=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=mi(this.length,8);if(i.byteLength>127)return this.error="Too big length",Ln;if(n=new ArrayBuffer(i.byteLength+1),t)return n;const s=new Uint8Array(i);r=new Uint8Array(n),r[0]=i.byteLength|128;for(let a=0;a<i.byteLength;a++)r[a+1]=s[a];return n}return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}e3.NAME="lengthBlock";const ne={};class ct extends Li{constructor({name:t=It,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=t,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new Q2(i),this.lenBlock=new e3(i),this.valueBlock=s?new s(i):new $t(i)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(t,n){const r=n||new Ou;n||t3(this);const i=this.idBlock.toBER(t);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(t);r.write(a),r.write(s)}return n?Ln:r.final()}toJSON(){const t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():ie.ToHex(this.toBER())}onAsciiEncoding(){const t=this.constructor.NAME,n=ie.ToHex(this.valueBlock.valueBeforeDecodeView);return`${t} : ${n}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;const n=this.toBER(),r=t.toBER();return J7(n,r)}}ct.NAME="BaseBlock";function t3(e){var t;if(e instanceof ne.Constructed)for(const n of e.valueBlock.value)t3(n)&&(e.lenBlock.isIndefiniteForm=!0);return!!(!((t=e.lenBlock)===null||t===void 0)&&t.isIndefiniteForm)}class K0 extends ct{getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}constructor({value:t=It,...n}={},r){super(n,r),t&&this.fromString(t)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}K0.NAME="BaseStringBlock";class n3 extends Dn($t){constructor({isHexOnly:t=!0,...n}={}){super(n),this.isHexOnly=t}}n3.NAME="PrimitiveValueBlock";var r3;class La extends ct{constructor(t={}){super(t,n3),this.idBlock.isConstructed=!1}}r3=La;ne.Primitive=r3;La.NAME="PRIMITIVE";function iC(e,t){if(e instanceof t)return e;const n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function Wo(e,t=0,n=e.length){const r=t;let i=new ct({},$t);const s=new Li;if(!or(s,e,t,n))return i.error=s.error,{offset:-1,result:i};if(!e.subarray(t,t+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(e,t,n);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),c===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(e,t,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=c,n-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let l=ct;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};l=ne.EndOfContent;break;case 1:l=ne.Boolean;break;case 2:l=ne.Integer;break;case 3:l=ne.BitString;break;case 4:l=ne.OctetString;break;case 5:l=ne.Null;break;case 6:l=ne.ObjectIdentifier;break;case 10:l=ne.Enumerated;break;case 12:l=ne.Utf8String;break;case 13:l=ne.RelativeObjectIdentifier;break;case 14:l=ne.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=ne.Sequence;break;case 17:l=ne.Set;break;case 18:l=ne.NumericString;break;case 19:l=ne.PrintableString;break;case 20:l=ne.TeletexString;break;case 21:l=ne.VideotexString;break;case 22:l=ne.IA5String;break;case 23:l=ne.UTCTime;break;case 24:l=ne.GeneralizedTime;break;case 25:l=ne.GraphicString;break;case 26:l=ne.VisibleString;break;case 27:l=ne.GeneralString;break;case 28:l=ne.UniversalString;break;case 29:l=ne.CharacterString;break;case 30:l=ne.BmpString;break;case 31:l=ne.DATE;break;case 32:l=ne.TimeOfDay;break;case 33:l=ne.DateTime;break;case 34:l=ne.Duration;break;default:{const u=i.idBlock.isConstructed?new ne.Constructed:new ne.Primitive;u.idBlock=i.idBlock,u.lenBlock=i.lenBlock,u.warnings=i.warnings,i=u}}break;default:l=i.idBlock.isConstructed?ne.Constructed:ne.Primitive}return i=iC(i,l),c=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(r,r+i.blockLength),{offset:c,result:i}}function mo(e){if(!e.byteLength){const t=new ct({},$t);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Wo(J.toUint8Array(e).slice(),0,e.byteLength)}function oC(e,t){return e?1:t}class $r extends $t{constructor({value:t=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=t,this.isIndefiniteForm=n}fromBER(t,n,r){const i=J.toUint8Array(t);if(!or(this,i,n,r))return-1;if(this.valueBeforeDecodeView=i.subarray(n,n+r),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),n;let s=n;for(;oC(this.isIndefiniteForm,r)>0;){const a=Wo(i,s,r);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(s=a.offset,this.blockLength+=a.result.blockLength,r-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===da)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===da?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,n){const r=n||new Ou;for(let i=0;i<this.value.length;i++)this.value[i].toBER(t,r);return n?Ln:r.final()}toJSON(){const t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)t.value.push(n.toJSON());return t}}$r.NAME="ConstructedValueBlock";var i3;class kt extends ct{constructor(t={}){super(t,$r),this.idBlock.isConstructed=!0}fromBER(t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){const t=[];for(const r of this.valueBlock.value)t.push(r.toString("ascii").split(`
68
68
  `).map(i=>` ${i}`).join(`
69
69
  `));const n=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${n} :
70
70
  ${t.join(`
@@ -83,7 +83,7 @@ ${t}`):e.set("log",t)}const EN=o.z.object({grant_type:o.z.literal("refresh_token
83
83
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function GN(e,t){if(e){if(typeof e=="string")return cb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?cb(e,t):void 0}}function cb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var WN=["MOBILE","PREMIUM_RATE","TOLL_FREE","SHARED_COST","VOIP","PERSONAL_NUMBER","PAGER","UAN","VOICEMAIL"];function D_(e,t,n){if(t=t||{},!(!e.country&&!e.countryCallingCode)){n=new yt(n),n.selectNumberingPlan(e.country,e.countryCallingCode);var r=t.v2?e.nationalNumber:e.phone;if(ir(r,n.nationalNumberPattern())){if(hp(r,"FIXED_LINE",n))return n.type("MOBILE")&&n.type("MOBILE").pattern()===""||!n.type("MOBILE")||hp(r,"MOBILE",n)?"FIXED_LINE_OR_MOBILE":"FIXED_LINE";for(var i=KN(WN),s;!(s=i()).done;){var a=s.value;if(hp(r,a,n))return a}}}}function hp(e,t,n){var r=n.type(t);return!r||!r.pattern()||r.possibleLengths()&&r.possibleLengths().indexOf(e.length)<0?!1:ir(e,r.pattern())}function JN(e,t,n){if(t=t||{},n=new yt(n),n.selectNumberingPlan(e.country,e.countryCallingCode),n.hasTypes())return D_(e,t,n.metadata)!==void 0;var r=t.v2?e.nationalNumber:e.phone;return ir(r,n.nationalNumberPattern())}function ZN(e,t,n){var r=new yt(n),i=r.getCountryCodesForCallingCode(e);return i?i.filter(function(s){return XN(t,s,n)}):[]}function XN(e,t,n){var r=new yt(n);return r.selectNumberingPlan(t),r.numberingPlan.possibleLengths().indexOf(e.length)>=0}var U_=2,YN=17,QN=3,gn="0-90-9٠-٩۰-۹",eT="-‐-―−ー-",tT="//",nT="..",rT="  ­​⁠ ",iT="()()[]\\[\\]",oT="~⁓∼~",su="".concat(eT).concat(tT).concat(nT).concat(rT).concat(iT).concat(oT),B_="++",sT=new RegExp("(["+gn+"])");function aT(e,t,n,r){if(t){var i=new yt(r);i.selectNumberingPlan(t,n);var s=new RegExp(i.IDDPrefix());if(e.search(s)===0){e=e.slice(e.match(s)[0].length);var a=e.match(sT);if(!(a&&a[1]!=null&&a[1].length>0&&a[1]==="0"))return e}}}function cT(e,t){if(e&&t.numberingPlan.nationalPrefixForParsing()){var n=new RegExp("^(?:"+t.numberingPlan.nationalPrefixForParsing()+")"),r=n.exec(e);if(r){var i,s,a=r.length-1,c=a>0&&r[a];if(t.nationalPrefixTransformRule()&&c)i=e.replace(n,t.nationalPrefixTransformRule()),a>1&&(s=r[1]);else{var l=r[0];i=e.slice(l.length),c&&(s=r[1])}var u;if(c){var d=e.indexOf(r[1]),f=e.slice(0,d);f===t.numberingPlan.nationalPrefix()&&(u=t.numberingPlan.nationalPrefix())}else u=r[0];return{nationalNumber:i,nationalPrefix:u,carrierCode:s}}}return{nationalNumber:e}}function lT(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=uT(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
84
84
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function uT(e,t){if(e){if(typeof e=="string")return lb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lb(e,t):void 0}}function lb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function dT(e,t){var n=t.countries,r=t.metadata;r=new yt(r);for(var i=lT(n),s;!(s=i()).done;){var a=s.value;if(r.selectNumberingPlan(a),r.leadingDigits()){if(e&&e.search(r.leadingDigits())===0)return a}else if(D_({phone:e,country:a},void 0,r.metadata))return a}}function Wk(e,t){var n=t.nationalNumber,r=t.metadata,i=r.getCountryCodesForCallingCode(e);if(i)return i.length===1?i[0]:dT(n,{countries:i,metadata:r.metadata})}function Wh(e,t,n){var r=cT(e,n),i=r.carrierCode,s=r.nationalNumber;if(s!==e){if(!pT(e,s,n))return{nationalNumber:e};if(n.numberingPlan.possibleLengths()&&(t||(t=Wk(n.numberingPlan.callingCode(),{nationalNumber:s,metadata:n})),!fT(s,t,n)))return{nationalNumber:e}}return{nationalNumber:s,carrierCode:i}}function pT(e,t,n){return!(ir(e,n.nationalNumberPattern())&&!ir(t,n.nationalNumberPattern()))}function fT(e,t,n){switch(L_(e,t,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function hT(e,t,n,r,i){var s=n?R_(n,i):r;if(e.indexOf(s)===0){i=new yt(i),i.selectNumberingPlan(n,s);var a=e.slice(s.length),c=Wh(a,t,i),l=c.nationalNumber,u=Wh(e,t,i),d=u.nationalNumber;if(!ir(d,i.nationalNumberPattern())&&ir(l,i.nationalNumberPattern())||L_(d,t,i)==="TOO_LONG")return{countryCallingCode:s,number:a}}return{number:e}}function Jk(e,t,n,r,i){if(!e)return{};var s;if(e[0]!=="+"){var a=aT(e,n,r,i);if(a&&a!==e)s=!0,e="+"+a;else{if(n||r){var c=hT(e,t,n,r,i),l=c.countryCallingCode,u=c.number;if(l)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:l,number:u}}return{number:e}}}if(e[1]==="0")return{};i=new yt(i);for(var d=2;d-1<=QN&&d<=e.length;){var f=e.slice(1,d);if(i.hasCallingCode(f))return i.selectNumberingPlan(f),{countryCallingCodeSource:s?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:f,number:e.slice(d)};d++}return{}}function _T(e){return e.replace(new RegExp("[".concat(su,"]+"),"g")," ").trim()}var mT=/(\$\d)/;function gT(e,t,n){var r=n.useInternationalFormat,i=n.withNationalPrefix,s=e.replace(new RegExp(t.pattern()),r?t.internationalFormat():i&&t.nationalPrefixFormattingRule()?t.format().replace(mT,t.nationalPrefixFormattingRule()):t.format());return r?_T(s):s}var yT=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function bT(e,t,n){var r=new yt(n);if(r.selectNumberingPlan(e,t),r.defaultIDDPrefix())return r.defaultIDDPrefix();if(yT.test(r.IDDPrefix()))return r.IDDPrefix()}var vT=";ext=",Gi=function(t){return"([".concat(gn,"]{1,").concat(t,"})")};function Zk(e){var t="20",n="15",r="9",i="6",s="[  \\t,]*",a="[:\\..]?[  \\t,-]*",c="#?",l="(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)",u="(?:[xx##~~]|int|int)",d="[- ]+",f="[  \\t]*",p="(?:,{2}|;)",h=vT+Gi(t),_=s+l+a+Gi(t)+c,g=s+u+a+Gi(r)+c,y=d+Gi(i)+"#",m=f+p+a+Gi(n)+c,w=f+"(?:,)+"+a+Gi(r)+c;return h+"|"+_+"|"+g+"|"+y+"|"+m+"|"+w}var wT="["+gn+"]{"+U_+"}",kT="["+B_+"]{0,1}(?:["+su+"]*["+gn+"]){3,}["+su+gn+"]*",$T=new RegExp("^["+B_+"]{0,1}(?:["+su+"]*["+gn+"]){1,2}$","i"),ST=kT+"(?:"+Zk()+")?",xT=new RegExp("^"+wT+"$|^"+ST+"$","i");function zT(e){return e.length>=U_&&xT.test(e)}function AT(e){return $T.test(e)}function ET(e){var t=e.number,n=e.ext;if(!t)return"";if(t[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(t).concat(n?";ext="+n:"")}var ub={formatExtension:function(t,n,r){return"".concat(t).concat(r.ext()).concat(n)}};function CT(e,t,n,r){if(n?n=NT({},ub,n):n=ub,r=new yt(r),e.country&&e.country!=="001"){if(!r.hasCountry(e.country))throw new Error("Unknown country: ".concat(e.country));r.selectNumberingPlan(e.country)}else if(e.countryCallingCode)r.selectNumberingPlan(e.countryCallingCode);else return e.phone||"";var i=r.countryCallingCode(),s=n.v2?e.nationalNumber:e.phone,a;switch(t){case"NATIONAL":return s?(a=au(s,e.carrierCode,"NATIONAL",r,n),_p(a,e.ext,r,n.formatExtension)):"";case"INTERNATIONAL":return s?(a=au(s,null,"INTERNATIONAL",r,n),a="+".concat(i," ").concat(a),_p(a,e.ext,r,n.formatExtension)):"+".concat(i);case"E.164":return"+".concat(i).concat(s);case"RFC3966":return ET({number:"+".concat(i).concat(s),ext:e.ext});case"IDD":if(!n.fromCountry)return;var c=jT(s,e.carrierCode,i,n.fromCountry,r);return c?_p(c,e.ext,r,n.formatExtension):void 0;default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(t,'"'))}}function au(e,t,n,r,i){var s=IT(r.formats(),e);return s?gT(e,s,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(s.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&i&&i.nationalPrefix===!1)}):e}function IT(e,t){return TT(e,function(n){if(n.leadingDigitsPatterns().length>0){var r=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(t.search(r)!==0)return!1}return ir(t,n.pattern())})}function _p(e,t,n,r){return t?r(e,t,n):e}function jT(e,t,n,r,i){var s=R_(r,i.metadata);if(s===n){var a=au(e,t,"NATIONAL",i);return n==="1"?n+" "+a:a}var c=bT(r,void 0,i.metadata);if(c)return"".concat(c," ").concat(n," ").concat(au(e,null,"INTERNATIONAL",i))}function NT(){for(var e=1,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(;e<n.length;){if(n[e])for(var i in n[e])n[0][i]=n[e][i];e++}return n[0]}function TT(e,t){for(var n=0;n<e.length;){if(t(e[n]))return e[n];n++}}function ka(e){"@babel/helpers - typeof";return ka=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ka(e)}function db(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function pb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?db(Object(n),!0).forEach(function(r){PT(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):db(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function PT(e,t,n){return(t=Xk(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function OT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function RT(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Xk(r.key),r)}}function LT(e,t,n){return t&&RT(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xk(e){var t=DT(e,"string");return ka(t)=="symbol"?t:t+""}function DT(e,t){if(ka(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ka(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var UT=(function(){function e(t,n,r){if(OT(this,e),!t)throw new TypeError("First argument is required");if(typeof t!="string")throw new TypeError("First argument must be a string");if(t[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(bo(n)&&bo(n.countries)){r=n;var i=t;if(!qT.test(i))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var s=Jk(i,void 0,void 0,void 0,r),a=s.countryCallingCode,c=s.number;if(n=c,t=a,!n)throw new Error("Invalid `number` argument passed: too short")}if(!n)throw new TypeError("`nationalNumber` argument is required");if(typeof n!="string")throw new TypeError("`nationalNumber` argument must be a string");Vk(r);var l=MT(t,r),u=l.country,d=l.countryCallingCode;this.country=u,this.countryCallingCode=d,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return r}}return LT(e,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:ZN(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return VN(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return JN(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new yt(this.getMetadata());return n.isNonGeographicCallingCode(this.countryCallingCode)}},{key:"isEqual",value:function(n){return this.number===n.number&&this.ext===n.ext}},{key:"getType",value:function(){return D_(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,r){return CT(this,n,r?pb(pb({},r),{},{v2:!0}):{v2:!0},this.getMetadata())}},{key:"formatNational",value:function(n){return this.format("NATIONAL",n)}},{key:"formatInternational",value:function(n){return this.format("INTERNATIONAL",n)}},{key:"getURI",value:function(n){return this.format("RFC3966",n)}}])})(),BT=function(t){return/^[A-Z]{2}$/.test(t)};function MT(e,t){var n,r,i=new yt(t);return BT(e)?(n=e,i.selectNumberingPlan(n),r=i.countryCallingCode()):r=e,{country:n,countryCallingCode:r}}var qT=/^\+\d+$/;function Jh(e){"@babel/helpers - typeof";return Jh=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Jh(e)}function FT(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function HT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function VT(e,t,n){return t=Sa(t),KT(e,M_()?Reflect.construct(t,n||[],Sa(e).constructor):t.apply(e,n))}function KT(e,t){if(t&&(Jh(t)=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return GT(e)}function GT(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function WT(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&$a(e,t)}function Zh(e){var t=typeof Map=="function"?new Map:void 0;return Zh=function(r){if(r===null||!ZT(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(r))return t.get(r);t.set(r,i)}function i(){return JT(r,arguments,Sa(this).constructor)}return i.prototype=Object.create(r.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),$a(i,r)},Zh(e)}function JT(e,t,n){if(M_())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&$a(i,n.prototype),i}function M_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(M_=function(){return!!e})()}function ZT(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function $a(e,t){return $a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},$a(e,t)}function Sa(e){return Sa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Sa(e)}var Wn=(function(e){function t(n){var r;return HT(this,t),r=VT(this,t,[n]),Object.setPrototypeOf(r,t.prototype),r.name=r.constructor.name,r}return WT(t,e),FT(t)})(Zh(Error)),fb=new RegExp("(?:"+Zk()+")$","i");function XT(e){var t=e.search(fb);if(t<0)return{};for(var n=e.slice(0,t),r=e.match(fb),i=1;i<r.length;){if(r[i])return{number:n,ext:r[i]};i++}}var YT={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9"};function QT(e){return YT[e]}function eP(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=tP(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
85
85
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tP(e,t){if(e){if(typeof e=="string")return hb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?hb(e,t):void 0}}function hb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function _b(e){for(var t="",n=eP(e.split("")),r;!(r=n()).done;){var i=r.value;t+=nP(i,t)||""}return t}function nP(e,t,n){return e==="+"?t?void 0:"+":QT(e)}var Yk="+",rP="[\\-\\.\\(\\)]?",mb="(["+gn+"]|"+rP+")",iP="^\\"+Yk+mb+"*["+gn+"]"+mb+"*$",oP=new RegExp(iP,"g"),Xh=gn,sP="["+Xh+"]+((\\-)*["+Xh+"])*",aP="a-zA-Z",cP="["+aP+"]+((\\-)*["+Xh+"])*",lP="^("+sP+"\\.)*"+cP+"\\.?$",uP=new RegExp(lP,"g"),gb="tel:",Yh=";phone-context=",dP=";isub=";function pP(e){var t=e.indexOf(Yh);if(t<0)return null;var n=t+Yh.length;if(n>=e.length)return"";var r=e.indexOf(";",n);return r>=0?e.substring(n,r):e.substring(n)}function fP(e){return e===null?!0:e.length===0?!1:oP.test(e)||uP.test(e)}function hP(e,t){var n=t.extractFormattedPhoneNumber,r=pP(e);if(!fP(r))throw new Wn("NOT_A_NUMBER");var i;if(r===null)i=n(e)||"";else{i="",r.charAt(0)===Yk&&(i+=r);var s=e.indexOf(gb),a;s>=0?a=s+gb.length:a=0;var c=e.indexOf(Yh);i+=e.substring(a,c)}var l=i.indexOf(dP);if(l>0&&(i=i.substring(0,l)),i!=="")return i}var _P=250,mP=new RegExp("["+B_+gn+"]"),gP=new RegExp("[^"+gn+"#]+$");function yP(e,t,n){if(t=t||{},n=new yt(n),t.defaultCountry&&!n.hasCountry(t.defaultCountry))throw t.v2?new Wn("INVALID_COUNTRY"):new Error("Unknown country: ".concat(t.defaultCountry));var r=vP(e,t.v2,t.extract),i=r.number,s=r.ext,a=r.error;if(!i){if(t.v2)throw a==="TOO_SHORT"?new Wn("TOO_SHORT"):new Wn("NOT_A_NUMBER");return{}}var c=kP(i,t.defaultCountry,t.defaultCallingCode,n),l=c.country,u=c.nationalNumber,d=c.countryCallingCode,f=c.countryCallingCodeSource,p=c.carrierCode;if(!n.hasSelectedNumberingPlan()){if(t.v2)throw new Wn("INVALID_COUNTRY");return{}}if(!u||u.length<U_){if(t.v2)throw new Wn("TOO_SHORT");return{}}if(u.length>YN){if(t.v2)throw new Wn("TOO_LONG");return{}}if(t.v2){var h=new UT(d,u,n.metadata);return l&&(h.country=l),p&&(h.carrierCode=p),s&&(h.ext=s),h.__countryCallingCodeSource=f,h}var _=(t.extended?n.hasSelectedNumberingPlan():l)?ir(u,n.nationalNumberPattern()):!1;return t.extended?{country:l,countryCallingCode:d,carrierCode:p,valid:_,possible:_?!0:!!(t.extended===!0&&n.possibleLengths()&&Gk(u,l,n)),phone:u,ext:s}:_?wP(l,u,s):{}}function bP(e,t,n){if(e){if(e.length>_P){if(n)throw new Wn("TOO_LONG");return}if(t===!1)return e;var r=e.search(mP);if(!(r<0))return e.slice(r).replace(gP,"")}}function vP(e,t,n){var r=hP(e,{extractFormattedPhoneNumber:function(a){return bP(a,n,t)}});if(!r)return{};if(!zT(r))return AT(r)?{error:"TOO_SHORT"}:{};var i=XT(r);return i.ext?i:{number:r}}function wP(e,t,n){var r={country:e,phone:t};return n&&(r.ext=n),r}function kP(e,t,n,r){var i=Jk(_b(e),void 0,t,n,r.metadata),s=i.countryCallingCodeSource,a=i.countryCallingCode,c=i.number,l;if(a)r.selectNumberingPlan(a);else if(c&&(t||n))r.selectNumberingPlan(t,n),t&&(l=t),a=n||R_(t,r.metadata);else return{};if(!c)return{countryCallingCodeSource:s,countryCallingCode:a};var u=Wh(_b(c),l,r),d=u.nationalNumber,f=u.carrierCode,p=Wk(a,{nationalNumber:d,metadata:r});return p&&(l=p,p==="001"||r.selectNumberingPlan(l)),{country:l,countryCallingCode:a,countryCallingCodeSource:s,nationalNumber:d,carrierCode:f}}function xa(e){"@babel/helpers - typeof";return xa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xa(e)}function yb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function bb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yb(Object(n),!0).forEach(function(r){$P(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $P(e,t,n){return(t=SP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function SP(e){var t=xP(e,"string");return xa(t)=="symbol"?t:t+""}function xP(e,t){if(xa(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(xa(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zP(e,t,n){return yP(e,bb(bb({},t),{},{v2:!0}),n)}function za(e){"@babel/helpers - typeof";return za=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},za(e)}function vb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function AP(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?vb(Object(n),!0).forEach(function(r){EP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):vb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function EP(e,t,n){return(t=CP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function CP(e){var t=IP(e,"string");return za(t)=="symbol"?t:t+""}function IP(e,t){if(za(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(za(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function jP(e,t){return OP(e)||PP(e,t)||TP(e,t)||NP()}function NP(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
86
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function TP(e,t){if(e){if(typeof e=="string")return wb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wb(e,t):void 0}}function wb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function PP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function OP(e){if(Array.isArray(e))return e}function RP(e){var t=Array.prototype.slice.call(e),n=jP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=AP({defaultCountry:i},l));else if(bo(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function Aa(e){"@babel/helpers - typeof";return Aa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Aa(e)}function kb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function $b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?kb(Object(n),!0).forEach(function(r){LP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):kb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function LP(e,t,n){return(t=DP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function DP(e){var t=UP(e,"string");return Aa(t)=="symbol"?t:t+""}function UP(e,t){if(Aa(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Aa(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function BP(e,t,n){t&&t.defaultCountry&&!FN(t.defaultCountry,n)&&(t=$b($b({},t),{},{defaultCountry:void 0}));try{return zP(e,t,n)}catch(r){if(!(r instanceof Wn))throw r}}function MP(){var e=RP(arguments),t=e.text,n=e.options,r=e.metadata;return BP(t,n,r)}function qP(){return jN(MP,arguments)}function cs(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=qP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Te}}function q_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function FP(e){const n=q_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function HP(e){const t=q_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function VP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function Sb(e){if(!e)return null;const t=q_(VP(e));return FP(t)?{family:4,normalized:t}:HP(t)?{family:6,normalized:t.toLowerCase()}:null}function xb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function KP(e,t,n=!0){const r=Sb(e),i=Sb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=xb(r.normalized),a=xb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class dn extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=dn.name,this.location=t,this.status=n}}const GP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:ea.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Qk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=cs(n,c);if(!u)throw new X(400,{message:"Invalid username format"});e.set("connection",l);const d=await qe(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new X(400,{message:he("code_invalid"),userSafe:!0});if(p.expires_at<new Date().toISOString())throw new X(400,{message:he("code_expired"),userSafe:!0});if(p.used_at)throw new X(400,{message:he("code_used"),userSafe:!0});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new X(400,{message:"Code not found or expired",userSafe:!0});if(s&&h.ip&&a&&!KP(h.ip,a))throw new dn(`${wt(e.env)}invalid-session?state=${h.id}`);const _=await Nu(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,connectionType:l,authConnection:l,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function rc(e,t){const n=await Qk(e,t);return mt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authConnection:n.connectionType,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const zb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Ab=o.z.union([Hk.extend(zb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...zb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function WP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Ab},"application/json":{schema:Ab}}}},responses:{200:{content:{"application/json":{schema:S0}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=WP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await AN(e,zN.parse(i));break;case an.ClientCredential:s=await xN(e,Hk.parse(i));break;case an.RefreshToken:s=await CN(e,EN.parse(i));break;case an.OTP:s=await Qk(e,GP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&pl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await ia(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new X(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await ia(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await Su(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function ic(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function e4(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await qe(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function t4(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${wt(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await ic(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${wt(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:pe.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Cd(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=cs(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(wt(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await ic(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await e4(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:pe.CODE_LINK_SENT,description:t})}async function Id(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=cs(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await ic(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await e4(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:pe.CODE_LINK_SENT,description:t})}async function jd(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await ic(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${wt(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function ZP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${wt(e.env)}signup?state=${r}&code=${n}`;await ic(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const XP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await qe(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ra(e.env.data,i.tenant.id,a);try{await Oa(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Pn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Te}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await la(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Te}|${Ti()}`,email:t,email_verified:!1,provider:Te,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await jd(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:pe.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await qe(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Te}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await t4(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function Rn(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const YP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:ea.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:ea.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await qe(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Fs).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:Rn(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Fs).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await Id(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Cd(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(st),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await qe(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await rc(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const S=k;"message"in S&&typeof S.message=="string"&&(h=S.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),w=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Fs).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${wt(e.env)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class eo extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function QP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function eO(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function n4(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new X(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Te});if(!a)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new eo(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new eo(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),eO(c).length>=3)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Too many failed login attempts"}),new eo(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await Ko.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),QP(i,t.tenant.id,c),new eo(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await jd(e,a,p),fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Email not verified"}),r&&await WA(e,t.tenant.id,r,"Email not verified"),new eo(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function oc(e,t,n,r,i){const s=await n4(e,t,n,r);return mt(e,{...s,ticketAuth:i,authConnection:e.get("connection")||"Username-Password-Authentication",authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function tO(e,t,n,r){await Nu(e,{client:t,username:n,provider:Te,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=Rn(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=Rn(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Mz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+Bz).toISOString()});await t4(e,n,f.code_id,r)}const nO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await qe(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await rc(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await oc(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function r4(e,t){if(!e||t.length===0)return!1;const n=mp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=mp(r)?.host??null:i=mp("https://"+r)?.host??null,n===i)return!0}return!1}function mp(e){try{return new URL(e)}catch{return null}}function rO(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function iO({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);rO(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return mt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=Rn();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+di*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Id(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/login/email-otp-challenge?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=fo.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function oO(e){if(e==="Username-Password-Authentication")return Te;if(e==="email")return"email";throw new X(403,{message:"Invalid realm"})}async function sO(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new X(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new X(403,{message:"Session not found"});const l=await qe(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=oO(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Te?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Nu(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),mt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authConnection:i,authStrategy:{strategy:f,strategy_type:p}})}async function aO({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===fn.WEB_MESSAGE;async function w(le="Login required"){const Se=new Headers;if(n&&(fe(e,t.tenant.id,{type:pe.FAILED_SILENT_AUTH,description:le}),Ww(t.tenant.id,e.req.header("host")).forEach(Hr=>{Se.append("set-cookie",Hr)})),m)return gf(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),Se);const F=new URL(r);if(d===st.TOKEN||d===st.TOKEN_ID_TOKEN){const Xe=new URLSearchParams;Xe.set("error","login_required"),Xe.set("error_description",le),i&&Xe.set("state",i),F.hash=Xe.toString()}else F.searchParams.set("error","login_required"),F.searchParams.set("error_description",le),i&&F.searchParams.set("state",i);const xt={Location:F.toString()},ue=Se.get("set-cookie");return ue&&(xt["set-cookie"]=ue),new Response(null,{status:302,headers:xt})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,S=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||S)return w();e.set("user_id",n.user_id);const v=await _.data.users.get(t.tenant.id,n.user_id);if(!v)return console.error("User not found",n.user_id),w("User not found");e.set("username",v.email),e.set("connection",v.connection);let x;if(p&&(x=await _.data.organizations.get(t.tenant.id,p),!x))return w("Organization not found");const A=l||t.tenant.audience;let E=u||"",P=[];if(A)try{const le=await ia(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:x?.id,userId:v.user_id});E=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const Se=le?.body?.error_description||le?.message||"Access denied";return w(Se)}throw le}else if(x&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${v.user_id}`,per_page:1e3})).userOrganizations.some(F=>F.organization_id===x.id))return w("User is not a member of the specified organization");const D=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),C=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,R={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:E,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:v,session_id:n.id,auth_time:C,permissions:P,organization:x},B=d===st.CODE?await x2(e,{user:v,client:t,authParams:R.authParams,login_id:D.id}):await Su(e,R),V=n.idle_expires_at?new Date(Date.now()+bu*1e3).toISOString():void 0;await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:D.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:V}),V&&await _.data.loginSessions.update(t.tenant.id,D.id,{expires_at:V}),fe(e,t.tenant.id,{type:pe.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const L=new Headers;if(pl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{L.append("set-cookie",le)}),m)return gf(e,y,JSON.stringify({...B,state:i}),L);const ae=new URL(r);if(d===st.TOKEN||d===st.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(B).forEach(([Se,F])=>{F!==void 0&&le.set(Se,String(F))}),i&&le.set("state",i),ae.hash=le.toString()}else Object.entries(B).forEach(([le,Se])=>{Se!==void 0&&ae.searchParams.set(le,String(Se))}),i&&ae.searchParams.set("state",i);const ve={Location:ae.toString()},Ee=L.get("set-cookie");return Ee&&(ve["set-cookie"]=Ee),new Response(null,{status:302,headers:ve})}const cO=["email","sms","Username-Password-Authentication"],Eb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(fn).optional(),response_type:o.z.nativeEnum(st).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(gu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function lO(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const uO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:Eb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:S0}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const L=lO(n.request);if(L){const Q=Eb.safeParse(L);Q.success&&(r=Q.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:w,login_ticket:k,realm:S,login_hint:v,ui_locales:x,organization:A}={...r,...n};e.set("log","authorize");const E=await qe(t,i);e.set("client_id",E.client_id),Vt(e,E.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const D=e.req.header("origin");if(D&&!r4(D,E.web_origins||[]))throw new I(403,{message:`Origin ${D} not allowed`});if(!p){if(P){const L=new URL(P);return L.searchParams.set("error","invalid_request"),L.searchParams.set("error_description","Missing required parameter: response_type"),l&&L.searchParams.set("state",l),e.redirect(L.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const C={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:v,ui_locales:x,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:w};if(C.redirect_uri){const L=E.callbacks||[];if(e.var.host&&(L.push(`${Pi(e.env)}/*`),L.push(`${wt(e.env)}/*`)),!O_(C.redirect_uri,L,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${C.redirect_uri}`})}let R;const B=Hz(E.tenant.id,e.req.header("cookie"));for(const L of B){const Q=await t.data.sessions.get(E.tenant.id,L);if(Q&&!Q.revoked_at){R=Q;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return aO({ctx:e,session:R||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:E,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(E.connections.length===1&&E.connections[0]&&!cO.includes(E.connections[0].strategy||""))return Qy(e,E,E.connections[0].name,C);if(f&&f!=="email")return Qy(e,E,f,C);if(k){const L=await sO(e,E.tenant.id,k,C,S);return L instanceof Response?L:e.json(L)}const V=await iO({ctx:e,client:E,authParams:C,session:R||void 0,connection:f,login_hint:v});return V instanceof Response?V:e.json(V)}),dO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await qe(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!r4(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=a.callbacks||[];if(e.var.host&&(w.push(`${Pi(e.env)}/*`),w.push(`${wt(e.env)}/*`)),!O_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=pi(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${wt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const w=new URL("/u/account",e.req.url);return w.searchParams.set("state",m.id),e.redirect(w.toString())}return e.redirect(`${wt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function pO(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Ho(r,e.dataAdapter),a=e.dataAdapter.cache||as({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=nc(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks"],cache:a});return r.env.data=tc(r,l),i()}),t.use("/oauth/token",Fk({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ss).use(os).use(zd(t));const n=t.route("/v2/logout",vN).route("/userinfo",$N).route("/.well-known",SN).route("/oauth/token",JP).route("/dbconnections",XP).route("/passwordless",YP).route("/co/authenticate",nO).route("/authorize",uO).route("/account",dO).route("/callback",yN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),T_(n),n}var F_=Symbol("RENDERER"),Qh=Symbol("ERROR_HANDLER"),Fe=Symbol("STASH"),i4=Symbol("INTERNAL"),fO=Symbol("MEMO"),cu=Symbol("PERMALINK"),Cb=e=>(e[i4]=!0,e),o4=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:Cb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Cb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Qh]=s=>{throw e.pop(),s},i},s4=e=>{const t=[e],n=o4(t);return n.values=t,n.Provider=n,Do.push(n),n},Do=[],a4=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new f4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[F_]=o4(t),Do.push(n),n},ls=e=>e.values.at(-1),lu={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},e0={},ei="data-precedence",c4=e=>e.rel==="stylesheet"&&"precedence"in e,l4=(e,t)=>e==="link"?t:lu[e].length>0,sc=e=>Array.isArray(e)?e:[e],Ib=new WeakMap,jb=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Ib.get(s)||{};Ib.set(s,a);const c=a[e]||=[];let l=!1;const u=lu[e],d=l4(e,r!==void 0);if(d){e:for(const[,f]of c)if(!(e==="link"&&!(f.rel==="stylesheet"&&f[ei]!==void 0))){for(const p of u)if((f?.[p]??null)===n?.[p]){l=!0;break e}}}if(l?i[0]=i[0].replaceAll(t,""):d||e==="link"?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let f;if(e==="link"||r!==void 0){const p=[];f=c.map(([h,,_],g)=>{if(_===void 0)return[h,Number.MAX_SAFE_INTEGER,g];let y=p.indexOf(_);return y===-1&&(p.push(_),y=p.length-1),[h,y,g]}).sort((h,_)=>h[1]-_[1]||h[2]-_[2]).map(([h])=>h)}else f=c.map(([p])=>p);f.forEach(p=>{i[0]=i[0].replaceAll(p,"")}),i[0]=i[0].replace(/(?=<\/head>)/,f.join(""))}},ac=(e,t,n)=>Cr(new mn(e,n,sc(t??[])).toString()),cc=(e,t,n,r)=>{if("itemProp"in n)return ac(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ei]=i);const c=new mn(e,a,sc(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],jb(e,l,a,i)])):Cr(c,[jb(e,c,a,i)])},hO=({children:e,...t})=>{const n=H_();if(n){const r=ls(n);if(r==="svg"||r==="head")return new mn("title",t,sc(e??[]))}return cc("title",e,t,!1)},_O=({children:e,...t})=>{const n=H_();return["src","async"].some(r=>!t[r])||n&&ls(n)==="head"?ac("script",e,t):cc("script",e,t,!1)},mO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,cc("style",e,t,!0)):ac("style",e,t),gO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?ac("link",e,t):cc("link",e,t,c4(t)),yO=({children:e,...t})=>{const n=H_();return n&&ls(n)==="head"?ac("meta",e,t):cc("meta",e,t,!1)},u4=(e,{children:t,...n})=>new mn(e,n,sc(t??[])),bO=e=>(typeof e.action=="function"&&(e.action=cu in e.action?e.action[cu]:void 0),u4("form",e)),d4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=cu in t.formAction?t.formAction[cu]:void 0),u4(e,t)),vO=e=>d4("input",e),wO=e=>d4("button",e);const gp=Object.freeze(Object.defineProperty({__proto__:null,button:wO,form:bO,input:vO,link:gO,meta:yO,script:_O,style:mO,title:hO},Symbol.toStringTag,{value:"Module"}));var kO=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),uu=e=>kO.get(e)||e,p4=(e,t)=>{for(const[n,r]of Object.entries(e)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);t(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},Ea=void 0,H_=()=>Ea,$O=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,SO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],xO=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],V_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")yo(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof mn?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):V_(i,t)}}},mn=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?Cj(Cr(e[0],e.callbacks)).toString():e[0]:Ej(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=Ea&&ls(Ea)==="svg"?s=>$O(uu(s)):s=>uu(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";p4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',yo(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,yo(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&xO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,yo(a.toString(),e),e[0]+='"'}if(SO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",V_(r,e),e[0]+=`</${t}>`}},yp=class extends mn{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Do.length===0)e.unshift("",r);else{const i=Do.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof mn&&(s.localContexts=i),s)))}else r instanceof mn?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):yo(r,e)}},f4=class extends mn{toStringToBuffer(e){V_(this.children,e)}},zO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Fc(e,t,n);return i.key=r,i},Nb=!1,Fc=(e,t,n)=>{if(!Nb){for(const r in e0)gp[r][F_]=e0[r];Nb=!0}return typeof e=="function"?new yp(e,t,n):gp[e]?new yp(gp[e],t,n):e==="svg"||e==="head"?(Ea||=a4(""),new mn(e,t,[new yp(Ea,{value:e},n)])):new mn(e,t,n)},Uo=({children:e})=>new f4("",{children:e},Array.isArray(e)?e:e?[e]:[]),AO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return zO(e.tag,{...e.props,...t},...r)};function b(e,t,n){let r;if(!t||!("children"in t))r=Fc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Fc(e,t,i):Fc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new I(400,{message:"Login session not found"});e.set("loginSession",i);const s=await qe(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new I(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new dn(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??na,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ci(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=pi(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&XA(c,n.continuationScope)){if(!c.user_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const bp={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function h4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Vo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Pn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Te}))?.app_metadata?.strategy;if(a&&bp[a])return bp[a];const c=t.connections.map(u=>bp[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const K_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?b("div",{className:"inline-flex h-9 items-center",children:b("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):b(Uo,{})},_4=e=>b("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&b("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",b("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var vp={exports:{}};var Tb;function EO(){return Tb||(Tb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(vp)),vp.exports}var CO=EO();const Be=Kw(CO),IO=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=IO(t);return b("span",{className:Be(`uicon-${e}`,n,r)})},jO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Bo="mmt5mnty",NO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||jO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
86
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function TP(e,t){if(e){if(typeof e=="string")return wb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wb(e,t):void 0}}function wb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function PP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function OP(e){if(Array.isArray(e))return e}function RP(e){var t=Array.prototype.slice.call(e),n=jP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=AP({defaultCountry:i},l));else if(bo(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function Aa(e){"@babel/helpers - typeof";return Aa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Aa(e)}function kb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function $b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?kb(Object(n),!0).forEach(function(r){LP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):kb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function LP(e,t,n){return(t=DP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function DP(e){var t=UP(e,"string");return Aa(t)=="symbol"?t:t+""}function UP(e,t){if(Aa(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Aa(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function BP(e,t,n){t&&t.defaultCountry&&!FN(t.defaultCountry,n)&&(t=$b($b({},t),{},{defaultCountry:void 0}));try{return zP(e,t,n)}catch(r){if(!(r instanceof Wn))throw r}}function MP(){var e=RP(arguments),t=e.text,n=e.options,r=e.metadata;return BP(t,n,r)}function qP(){return jN(MP,arguments)}function cs(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=qP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Te}}function q_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function FP(e){const n=q_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function HP(e){const t=q_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function VP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function Sb(e){if(!e)return null;const t=q_(VP(e));return FP(t)?{family:4,normalized:t}:HP(t)?{family:6,normalized:t.toLowerCase()}:null}function xb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function KP(e,t,n=!0){const r=Sb(e),i=Sb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=xb(r.normalized),a=xb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class dn extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=dn.name,this.location=t,this.status=n}}const GP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:ea.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Qk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=cs(n,c);if(!u)throw new X(400,{message:"Invalid username format"});e.set("connection",l);const d=await qe(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new X(400,{message:he("code_invalid"),userSafe:!0});if(p.expires_at<new Date().toISOString())throw new X(400,{message:he("code_expired"),userSafe:!0});if(p.used_at)throw new X(400,{message:he("code_used"),userSafe:!0});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new X(400,{message:"Code not found or expired",userSafe:!0});if(s&&h.ip&&a&&!KP(h.ip,a))throw new dn(`${wt(e.env)}invalid-session?state=${h.id}`);const _=await Nu(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,connectionType:l,authConnection:l,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function rc(e,t){const n=await Qk(e,t);return mt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authConnection:n.connectionType,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const zb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Ab=o.z.union([Hk.extend(zb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...zb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function WP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Ab},"application/json":{schema:Ab}}}},responses:{200:{content:{"application/json":{schema:S0}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=WP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await AN(e,zN.parse(i));break;case an.ClientCredential:s=await xN(e,Hk.parse(i));break;case an.RefreshToken:s=await CN(e,EN.parse(i));break;case an.OTP:s=await Qk(e,GP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&pl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await ia(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new X(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await ia(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await Su(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function ic(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function e4(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await qe(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function t4(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${wt(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await ic(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${wt(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:pe.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Cd(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=cs(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(wt(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await ic(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await e4(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:pe.CODE_LINK_SENT,description:t})}async function Id(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=cs(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await ic(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await e4(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:pe.CODE_LINK_SENT,description:t})}async function jd(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await ic(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${wt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${wt(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function ZP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${wt(e.env)}signup?state=${r}&code=${n}`;await ic(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const XP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await qe(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ra(e.env.data,i.tenant.id,a);try{await Oa(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Pn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Te}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await la(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Te}|${Ti()}`,email:t,email_verified:!1,provider:Te,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await jd(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:pe.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await qe(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Te}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await t4(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function Rn(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const YP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:ea.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:ea.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await qe(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Fs).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:Rn(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Fs).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await Id(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Cd(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(st),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await qe(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await rc(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const S=k;"message"in S&&typeof S.message=="string"&&(h=S.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),w=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Fs).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${wt(e.env)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class eo extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function QP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function eO(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function n4(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new X(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Te});if(!a)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new eo(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new eo(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),eO(c).length>=3)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Too many failed login attempts"}),new eo(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await Ko.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),QP(i,t.tenant.id,c),new eo(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await jd(e,a,p),fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Email not verified"}),r&&await WA(e,t.tenant.id,r,"Email not verified"),new eo(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function oc(e,t,n,r,i){const s=await n4(e,t,n,r);return mt(e,{...s,ticketAuth:i,authConnection:e.get("connection")||"Username-Password-Authentication",authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function tO(e,t,n,r){await Nu(e,{client:t,username:n,provider:Te,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=Rn(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=Rn(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Mz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+Bz).toISOString()});await t4(e,n,f.code_id,r)}const nO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await qe(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await rc(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await oc(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function r4(e,t){if(!e||t.length===0)return!1;const n=mp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=mp(r)?.host??null:i=mp("https://"+r)?.host??null,n===i)return!0}return!1}function mp(e){try{return new URL(e)}catch{return null}}function rO(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function iO({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);rO(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return mt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=Rn();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+di*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Id(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/login/email-otp-challenge?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=fo.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function oO(e){if(e==="Username-Password-Authentication")return Te;if(e==="email")return"email";throw new X(403,{message:"Invalid realm"})}async function sO(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new X(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new X(403,{message:"Session not found"});const l=await qe(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=oO(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Te?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Nu(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),mt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authConnection:i,authStrategy:{strategy:f,strategy_type:p}})}async function aO({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===fn.WEB_MESSAGE;async function w(le="Login required"){const Se=new Headers;if(n&&(fe(e,t.tenant.id,{type:pe.FAILED_SILENT_AUTH,description:le}),Ww(t.tenant.id,e.req.header("host")).forEach(Hr=>{Se.append("set-cookie",Hr)})),m)return gf(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),Se);const F=new URL(r);if(d===st.TOKEN||d===st.TOKEN_ID_TOKEN){const Xe=new URLSearchParams;Xe.set("error","login_required"),Xe.set("error_description",le),i&&Xe.set("state",i),F.hash=Xe.toString()}else F.searchParams.set("error","login_required"),F.searchParams.set("error_description",le),i&&F.searchParams.set("state",i);const xt={Location:F.toString()},ue=Se.get("set-cookie");return ue&&(xt["set-cookie"]=ue),new Response(null,{status:302,headers:xt})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,S=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||S)return w();e.set("user_id",n.user_id);const v=await _.data.users.get(t.tenant.id,n.user_id);if(!v)return console.error("User not found",n.user_id),w("User not found");e.set("username",v.email),e.set("connection",v.connection);let x;if(p&&(x=await _.data.organizations.get(t.tenant.id,p),!x))return w("Organization not found");const A=l||t.tenant.audience;let E=u||"",P=[];if(A)try{const le=await ia(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:x?.id,userId:v.user_id});E=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const Se=le?.body?.error_description||le?.message||"Access denied";return w(Se)}throw le}else if(x&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${v.user_id}`,per_page:1e3})).userOrganizations.some(F=>F.organization_id===x.id))return w("User is not a member of the specified organization");const D=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),C=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,R={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:E,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:v,session_id:n.id,auth_time:C,permissions:P,organization:x},B=d===st.CODE?await x2(e,{user:v,client:t,authParams:R.authParams,login_id:D.id}):await Su(e,R),V=n.idle_expires_at?new Date(Date.now()+bu*1e3).toISOString():void 0;await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:D.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:V}),V&&await _.data.loginSessions.update(t.tenant.id,D.id,{expires_at:V}),fe(e,t.tenant.id,{type:pe.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const L=new Headers;if(pl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{L.append("set-cookie",le)}),m)return gf(e,y,JSON.stringify({...B,state:i}),L);const ae=new URL(r);if(d===st.TOKEN||d===st.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(B).forEach(([Se,F])=>{F!==void 0&&le.set(Se,String(F))}),i&&le.set("state",i),ae.hash=le.toString()}else Object.entries(B).forEach(([le,Se])=>{Se!==void 0&&ae.searchParams.set(le,String(Se))}),i&&ae.searchParams.set("state",i);const ve={Location:ae.toString()},Ee=L.get("set-cookie");return Ee&&(ve["set-cookie"]=Ee),new Response(null,{status:302,headers:ve})}const cO=["email","sms","Username-Password-Authentication"],Eb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(fn).optional(),response_type:o.z.nativeEnum(st).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(gu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function lO(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const uO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:Eb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:S0}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const L=lO(n.request);if(L){const Q=Eb.safeParse(L);Q.success&&(r=Q.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:w,login_ticket:k,realm:S,login_hint:v,ui_locales:x,organization:A}={...r,...n};e.set("log","authorize");const E=await qe(t,i);e.set("client_id",E.client_id),Vt(e,E.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const D=e.req.header("origin");if(D&&!r4(D,E.web_origins||[]))throw new I(403,{message:`Origin ${D} not allowed`});if(!p){if(P){const L=new URL(P);return L.searchParams.set("error","invalid_request"),L.searchParams.set("error_description","Missing required parameter: response_type"),l&&L.searchParams.set("state",l),e.redirect(L.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const C={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:v,ui_locales:x,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:w};if(C.redirect_uri){const L=E.callbacks||[];if(e.var.host&&(L.push(`${Pi(e.env)}/*`),L.push(`${wt(e.env)}/*`)),!O_(C.redirect_uri,L,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${C.redirect_uri}`})}let R;const B=Hz(E.tenant.id,e.req.header("cookie"));for(const L of B){const Q=await t.data.sessions.get(E.tenant.id,L);if(Q&&!Q.revoked_at){R=Q;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return aO({ctx:e,session:R||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:E,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(E.connections.length===1&&E.connections[0]&&!cO.includes(E.connections[0].strategy||""))return Qy(e,E,E.connections[0].name,C);if(f&&f!=="email")return Qy(e,E,f,C);if(k){const L=await sO(e,E.tenant.id,k,C,S);return L instanceof Response?L:e.json(L)}const V=await iO({ctx:e,client:E,authParams:C,session:R||void 0,connection:f,login_hint:v});return V instanceof Response?V:e.json(V)}),dO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await qe(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!r4(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=a.callbacks||[];if(e.var.host&&(w.push(`${Pi(e.env)}/*`),w.push(`${wt(e.env)}/*`)),!O_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=pi(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${wt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const w=new URL("/u/account",e.req.url);return w.searchParams.set("state",m.id),e.redirect(w.toString())}return e.redirect(`${wt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function pO(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Ho(r,e.dataAdapter),a=e.dataAdapter.cache||as({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=nc(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks"],cache:a});return r.env.data=tc(r,l),i()}),t.use("/oauth/token",Fk({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ss).use(os).use(zd(t));const n=t.route("/v2/logout",vN).route("/userinfo",$N).route("/.well-known",SN).route("/oauth/token",JP).route("/dbconnections",XP).route("/passwordless",YP).route("/co/authenticate",nO).route("/authorize",uO).route("/account",dO).route("/callback",yN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),T_(n),n}var F_=Symbol("RENDERER"),Qh=Symbol("ERROR_HANDLER"),Fe=Symbol("STASH"),i4=Symbol("INTERNAL"),fO=Symbol("MEMO"),cu=Symbol("PERMALINK"),Cb=e=>(e[i4]=!0,e),o4=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:Cb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Cb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Qh]=s=>{throw e.pop(),s},i},s4=e=>{const t=[e],n=o4(t);return n.values=t,n.Provider=n,Do.push(n),n},Do=[],a4=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new f4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[F_]=o4(t),Do.push(n),n},ls=e=>e.values.at(-1),lu={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},e0={},ei="data-precedence",c4=e=>e.rel==="stylesheet"&&"precedence"in e,l4=(e,t)=>e==="link"?t:lu[e].length>0,sc=e=>Array.isArray(e)?e:[e],Ib=new WeakMap,jb=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Ib.get(s)||{};Ib.set(s,a);const c=a[e]||=[];let l=!1;const u=lu[e],d=l4(e,r!==void 0);if(d){e:for(const[,f]of c)if(!(e==="link"&&!(f.rel==="stylesheet"&&f[ei]!==void 0))){for(const p of u)if((f?.[p]??null)===n?.[p]){l=!0;break e}}}if(l?i[0]=i[0].replaceAll(t,""):d||e==="link"?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let f;if(e==="link"||r!==void 0){const p=[];f=c.map(([h,,_],g)=>{if(_===void 0)return[h,Number.MAX_SAFE_INTEGER,g];let y=p.indexOf(_);return y===-1&&(p.push(_),y=p.length-1),[h,y,g]}).sort((h,_)=>h[1]-_[1]||h[2]-_[2]).map(([h])=>h)}else f=c.map(([p])=>p);f.forEach(p=>{i[0]=i[0].replaceAll(p,"")}),i[0]=i[0].replace(/(?=<\/head>)/,f.join(""))}},ac=(e,t,n)=>Cr(new mn(e,n,sc(t??[])).toString()),cc=(e,t,n,r)=>{if("itemProp"in n)return ac(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ei]=i);const c=new mn(e,a,sc(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],jb(e,l,a,i)])):Cr(c,[jb(e,c,a,i)])},hO=({children:e,...t})=>{const n=H_();if(n){const r=ls(n);if(r==="svg"||r==="head")return new mn("title",t,sc(e??[]))}return cc("title",e,t,!1)},_O=({children:e,...t})=>{const n=H_();return["src","async"].some(r=>!t[r])||n&&ls(n)==="head"?ac("script",e,t):cc("script",e,t,!1)},mO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,cc("style",e,t,!0)):ac("style",e,t),gO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?ac("link",e,t):cc("link",e,t,c4(t)),yO=({children:e,...t})=>{const n=H_();return n&&ls(n)==="head"?ac("meta",e,t):cc("meta",e,t,!1)},u4=(e,{children:t,...n})=>new mn(e,n,sc(t??[])),bO=e=>(typeof e.action=="function"&&(e.action=cu in e.action?e.action[cu]:void 0),u4("form",e)),d4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=cu in t.formAction?t.formAction[cu]:void 0),u4(e,t)),vO=e=>d4("input",e),wO=e=>d4("button",e);const gp=Object.freeze(Object.defineProperty({__proto__:null,button:wO,form:bO,input:vO,link:gO,meta:yO,script:_O,style:mO,title:hO},Symbol.toStringTag,{value:"Module"}));var kO=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),uu=e=>kO.get(e)||e,p4=(e,t)=>{for(const[n,r]of Object.entries(e)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);t(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},Ea=void 0,H_=()=>Ea,$O=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,SO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],xO=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],V_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")yo(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof mn?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):V_(i,t)}}},mn=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?Cj(Cr(e[0],e.callbacks)).toString():e[0]:Ej(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=Ea&&ls(Ea)==="svg"?s=>$O(uu(s)):s=>uu(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";p4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',yo(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,yo(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&xO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,yo(a.toString(),e),e[0]+='"'}if(SO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",V_(r,e),e[0]+=`</${t}>`}},yp=class extends mn{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Do.length===0)e.unshift("",r);else{const i=Do.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof mn&&(s.localContexts=i),s)))}else r instanceof mn?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):yo(r,e)}},f4=class extends mn{toStringToBuffer(e){V_(this.children,e)}},zO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Fc(e,t,n);return i.key=r,i},Nb=!1,Fc=(e,t,n)=>{if(!Nb){for(const r in e0)gp[r][F_]=e0[r];Nb=!0}return typeof e=="function"?new yp(e,t,n):gp[e]?new yp(gp[e],t,n):e==="svg"||e==="head"?(Ea||=a4(""),new mn(e,t,[new yp(Ea,{value:e},n)])):new mn(e,t,n)},Uo=({children:e})=>new f4("",{children:e},Array.isArray(e)?e:e?[e]:[]),AO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return zO(e.tag,{...e.props,...t},...r)};function b(e,t,n){let r;if(!t||!("children"in t))r=Fc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Fc(e,t,i):Fc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new I(400,{message:"Login session not found"});e.set("loginSession",i);const s=await qe(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new I(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new dn(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??na,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ci(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=pi(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&XA(c,n.continuationScope)){if(!c.user_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new dn(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const bp={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function h4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Vo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Pn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Te}))?.app_metadata?.strategy;if(a&&bp[a])return bp[a];const c=t.connections.map(u=>bp[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const K_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?b("div",{className:"inline-flex h-9 items-center",children:b("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):b(Uo,{})},_4=e=>b("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&b("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",b("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var vp={exports:{}};var Tb;function EO(){return Tb||(Tb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(vp)),vp.exports}var CO=EO();const Be=Kw(CO),IO=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=IO(t);return b("span",{className:Be(`uicon-${e}`,n,r)})},jO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Bo="mmtdtz05",NO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||jO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
87
87
  body {
88
88
  --primary-color: ${n};
89
89
  --primary-hover: ${r};