authhero 3.5.0 → 3.6.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
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var C=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};const de=e=>typeof e=="string",lo=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},nh=e=>e==null?"":""+e,s3=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},a3=/###/g,rh=e=>e&&e.indexOf("###")>-1?e.replace(a3,"."):e,ih=e=>!e||de(e),Do=(e,t,n)=>{const r=de(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(ih(e))return{};const s=rh(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return ih(e)?{}:{obj:e,k:rh(r[i])}},oh=(e,t,n)=>{const{obj:r,k:i}=Do(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let s=t[t.length-1],a=t.slice(0,t.length-1),c=Do(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Do(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},c3=(e,t,n,r)=>{const{obj:i,k:s}=Do(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Pa=(e,t)=>{const{obj:n,k:r}=Do(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},u3=(e,t,n)=>{const r=Pa(e,n);return r!==void 0?r:Pa(t,n)},R1=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?de(e[r])||e[r]instanceof String||de(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):R1(e[r],t[r],n):e[r]=t[r]);return e},ti=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var l3={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const d3=e=>de(e)?e.replace(/[&<>"'\/]/g,t=>l3[t]):e;class p3{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const f3=[" ",",","?","!",";"],h3=new p3(20),g3=(e,t,n)=>{t=t||"",n=n||"";const r=f3.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=h3.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(e);if(!s){const a=e.indexOf(n);a>0&&!i.test(e.substring(0,a))&&(s=!0)}return s},vd=(e,t,n=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const r=t.split(n);let i=e;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let a,c="";for(let u=s;u<r.length;++u)if(u!==s&&(c+=n),c+=r[u],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&u<r.length-1)continue;s+=u-s+1;break}i=a}return i},Xo=e=>e?.replace("_","-"),m3={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Ra{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||m3,this.options=n,this.debug=n.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,n,r,i){return i&&!this.debug?null:(de(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Ra(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Ra(this.logger,t)}}var pn=new Ra;class Fc{constructor(){this.observers={}}on(t,n){return t.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t,...n){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i.apply(i,[t,...n])})}}class sh extends Fc{constructor(t,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,a=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;t.indexOf(".")>-1?c=t.split("."):(c=[t,n],r&&(Array.isArray(r)?c.push(...r):de(r)&&s?c.push(...r.split(s)):c.push(r)));const u=Pa(this.data,c);return!u&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),u||!a||!de(r)?u:vd(this.data?.[t]?.[n],r,s)}addResource(t,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[t,n];r&&(c=c.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(c=t.split("."),i=n,n=c[1]),this.addNamespaces(n),oh(this.data,c,i),s.silent||this.emit("added",t,n,r,i)}addResources(t,n,r,i={silent:!1}){for(const s in r)(de(r[s])||Array.isArray(r[s]))&&this.addResource(t,n,s,r[s],{silent:!0});i.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[t,n];t.indexOf(".")>-1&&(c=t.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let u=Pa(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?R1(u,r,s):u={...u,...r},oh(this.data,c,u),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var L1={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(s=>{t=this.processors[s]?.process(t,n,r,i)??t}),t}};const D1=Symbol("i18next/PATH_KEY");function _3(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===D1?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function xd(e,t){const{[D1]:n}=e(_3());return n.join(t?.keySeparator??".")}const ah={},ll=e=>!de(e)&&typeof e!="boolean"&&typeof e!="number";class La extends Fc{constructor(t,n={}){super(),s3(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=pn.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,n={interpolation:{}}){const r={...n};if(t==null)return!1;const i=this.resolve(t,r);if(i?.res===void 0)return!1;const s=ll(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!g3(t,r,i);if(a&&!c){const u=t.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:t,namespaces:de(s)?[s]:s};const l=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(l[0])>-1)&&(s=l.shift()),t=l.join(i)}return{key:t,namespaces:de(s)?[s]:s}}translate(t,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),t==null)return"";typeof t=="function"&&(t=xd(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]);const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:u}=this.extractFromKey(t[t.length-1],i),l=u[u.length-1];let d=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const f=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return p?s?{res:`${l}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let g=h?.res;const y=h?.usedKey||c,w=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],x=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,$=!this.i18nFormat||this.i18nFormat.handleAsObject,k=i.count!==void 0&&!de(i.count),v=La.hasDefaultValue(i),z=k?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&k?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",N=k&&!i.ordinal&&i.count===0,R=N&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${z}`]||i[`defaultValue${A}`]||i.defaultValue;let L=g;$&&!g&&v&&(L=R);const E=ll(L),O=Object.prototype.toString.apply(L);if($&&L&&E&&m.indexOf(O)<0&&!(de(x)&&Array.isArray(L))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const q=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,L,{...i,ns:u}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=q,h.usedParams=this.getUsedParamsDetails(i),h):q}if(a){const q=Array.isArray(L),K=q?[]:{},B=q?w:y;for(const oe in L)if(Object.prototype.hasOwnProperty.call(L,oe)){const ae=`${B}${a}${oe}`;v&&!g?K[oe]=this.translate(ae,{...i,defaultValue:ll(R)?R[oe]:void 0,joinArrays:!1,ns:u}):K[oe]=this.translate(ae,{...i,joinArrays:!1,ns:u}),K[oe]===ae&&(K[oe]=L[oe])}g=K}}else if($&&de(x)&&Array.isArray(g))g=g.join(x),g&&(g=this.extendTranslation(g,t,i,r));else{let q=!1,K=!1;!this.isValidLookup(g)&&v&&(q=!0,g=R),this.isValidLookup(g)||(K=!0,g=c);const oe=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&K?void 0:g,ae=v&&R!==g&&this.options.updateMissing;if(K||q||ae){if(this.logger.log(ae?"updateKey":"missingKey",f,l,c,ae?R:g),a){const Ce=this.resolve(c,{...i,keySeparator:!1});Ce&&Ce.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let se=[];const we=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&we&&we[0])for(let Ce=0;Ce<we.length;Ce++)se.push(we[Ce]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(i.lng||this.language):se.push(i.lng||this.language);const Ee=(Ce,Ge,F)=>{const Le=v&&F!==g?F:oe;this.options.missingKeyHandler?this.options.missingKeyHandler(Ce,l,Ge,Le,ae,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Ce,l,Ge,Le,ae,i),this.emit("missingKey",Ce,l,Ge,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&k?se.forEach(Ce=>{const Ge=this.pluralResolver.getSuffixes(Ce,i);N&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ge.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ge.push(`${this.options.pluralSeparator}zero`),Ge.forEach(F=>{Ee([Ce],c+F,i[`defaultValue${F}`]||R)})}):Ee(se,c,R))}g=this.extendTranslation(g,t,i,h,r),K&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${l}${d}${c}`),(K||q)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${d}${c}`:c,q?g:void 0,i))}return s?(h.res=g,h.usedParams=this.getUsedParamsDetails(i),h):g}extendTranslation(t,n,r,i,s){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=de(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let l;if(u){const f=t.match(this.interpolator.nestingRegexp);l=f&&f.length}let d=r.replace&&!de(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,r.lng||this.language||i.usedLng,r),u){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;l<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(t=this.interpolator.nest(t,(...f)=>s?.[0]===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${n[0]}`),null):this.translate(...f,n),r)),r.interpolation&&this.interpolator.reset()}const a=r.postProcess||this.options.postProcess,c=de(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=L1.handle(c,t,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),t}resolve(t,n={}){let r,i,s,a,c;return de(t)&&(t=[t]),t.forEach(u=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(u,n),d=l.key;i=d;let f=l.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!de(n.count),h=p&&!n.ordinal&&n.count===0,g=n.context!==void 0&&(de(n.context)||typeof n.context=="number")&&n.context!=="",y=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(w=>{this.isValidLookup(r)||(c=w,!ah[`${y[0]}-${w}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(ah[`${y[0]}-${w}`]=!0,this.logger.warn(`key "${i}" for languages "${y.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),y.forEach(m=>{if(this.isValidLookup(r))return;a=m;const x=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(x,d,m,w,n);else{let k;p&&(k=this.pluralResolver.getSuffix(m,n.count,n));const v=`${this.options.pluralSeparator}zero`,z=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&k.indexOf(z)===0&&x.push(d+k.replace(z,this.options.pluralSeparator)),x.push(d+k),h&&x.push(d+v)),g){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;x.push(A),p&&(n.ordinal&&k.indexOf(z)===0&&x.push(A+k.replace(z,this.options.pluralSeparator)),x.push(A+k),h&&x.push(A+v))}}let $;for(;$=x.pop();)this.isValidLookup(r)||(s=$,r=this.getResource(m,w,$,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,n,r,i):this.resourceStore.getResource(t,n,r,i)}getUsedParamsDetails(t={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&!de(t.replace);let i=r?t.replace:t;if(r&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}class ch{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=pn.create("languageUtils")}getScriptPartFromCode(t){if(t=Xo(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Xo(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(de(t)&&t.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(t)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(a=>{if(a===s)return a;if(!(a.indexOf("-")<0&&s.indexOf("-")<0)&&(a.indexOf("-")>0&&s.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===s||a.indexOf(s)===0&&s.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),de(t)&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],t),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return de(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(t))):de(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const uh={zero:0,one:1,two:2,few:3,many:4,other:5},lh={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class y3{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=pn.create("pluralResolver"),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Xo(t==="dev"?"en":t),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let a;try{a=new Intl.PluralRules(r,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),lh;if(!t.match(/-|_/))return lh;const u=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(u,n)}return this.pluralRulesCache[s]=a,a}needsPlural(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,n,r={}){return this.getSuffixes(t,r).map(i=>`${n}${i}`)}getSuffixes(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>uh[i]-uh[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,n,r={}){const i=this.getRule(t,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",n,r))}}const dh=(e,t,n,r=".",i=!0)=>{let s=u3(e,t,n);return!s&&i&&de(n)&&(s=vd(e,n,r),s===void 0&&(s=vd(t,n,r))),s},dl=e=>e.replace(/\$/g,"$$$$");class ph{constructor(t={}){this.logger=pn.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(n=>n),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:u,formatSeparator:l,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:g,nestingSuffixEscaped:y,nestingOptionsSeparator:w,maxReplaces:m,alwaysFormat:x}=t.interpolation;this.escape=n!==void 0?n:d3,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ti(s):a||"{{",this.suffix=c?ti(c):u||"}}",this.formatSeparator=l||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?ti(p):h||ti("$t("),this.nestingSuffix=g?ti(g):y||ti(")"),this.nestingOptionsSeparator=w||",",this.maxReplaces=m||1e3,this.alwaysFormat=x!==void 0?x:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,n,r,i){let s,a,c;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=h=>{if(h.indexOf(this.formatSeparator)<0){const m=dh(n,u,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const g=h.split(this.formatSeparator),y=g.shift().trim(),w=g.join(this.formatSeparator).trim();return this.format(dh(n,u,y,this.options.keySeparator,this.options.ignoreJSONStructure),w,r,{...i,...n,interpolationkey:y})};this.resetRegExp();const d=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>dl(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?dl(this.escape(h)):dl(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const g=s[1].trim();if(a=l(g),a===void 0)if(typeof d=="function"){const w=d(t,s,i);a=de(w)?w:""}else if(i&&Object.prototype.hasOwnProperty.call(i,g))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${t}`),a="";else!de(a)&&!this.useRawValueToEscape&&(a=nh(a));const y=h.safeValue(a);if(t=t.replace(s[0],y),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=s[0].length):h.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),t}nest(t,n,r={}){let i,s,a;const c=(u,l)=>{const d=this.nestingOptionsSeparator;if(u.indexOf(d)<0)return u;const f=u.split(new RegExp(`${d}[ ]*{`));let p=`{${f[1]}`;u=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),g=p.match(/"/g);((h?.length??0)%2===0&&!g||g.length%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),l&&(a={...l,...a})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,y),`${u}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,u};for(;i=this.nestingRegexp.exec(t);){let u=[];a={...r},a=a.replace&&!de(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const l=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(l!==-1&&(u=i[1].slice(l).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,l)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!de(s))return s;de(s)||(s=nh(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),u.length&&(s=u.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),t=t.replace(i[0],s),this.regexp.lastIndex=0}return t}}const b3=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);t==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...u]=a.split(":"),l=u.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=l),l==="false"&&(n[d]=!1),l==="true"&&(n[d]=!0),isNaN(l)||(n[d]=parseInt(l,10))}})}return{formatName:t,formatOptions:n}},fh=e=>{const t={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const a=r+JSON.stringify(s);let c=t[a];return c||(c=e(Xo(r),i),t[a]=c),c(n)}},w3=e=>(t,n,r)=>e(Xo(n),r)(t);class v3{constructor(t={}){this.logger=pn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?fh:w3;this.formats={number:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s});return c=>a.format(c)}),currency:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s,style:"currency"});return c=>a.format(c)}),datetime:r((i,s)=>{const a=new Intl.DateTimeFormat(i,{...s});return c=>a.format(c)}),relativetime:r((i,s)=>{const a=new Intl.RelativeTimeFormat(i,{...s});return c=>a.format(c,s.range||"day")}),list:r((i,s)=>{const a=new Intl.ListFormat(i,{...s});return c=>a.format(c)})}}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=fh(n)}format(t,n,r,i={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(c=>c.indexOf(")")>-1)){const c=s.findIndex(u=>u.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,u)=>{const{formatName:l,formatOptions:d}=b3(u);if(this.formats[l]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[l](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${l}`);return c},t)}}const x3=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class $3 extends Fc{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=pn.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(t,n,r,i){const s={},a={},c={},u={};return t.forEach(l=>{let d=!0;n.forEach(f=>{const p=`${l}|${f}`;!r.reload&&this.store.hasResourceBundle(l,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),s[p]===void 0&&(s[p]=!0),u[f]===void 0&&(u[f]=!0)))}),d||(c[l]=!0)}),(Object.keys(s).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(u)}}loaded(t,n,r){const i=t.split("|"),s=i[0],a=i[1];n&&this.emit("failedLoading",s,a,n),!n&&r&&this.store.addResourceBundle(s,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const c={};this.queue.forEach(u=>{c3(u.loaded,[s],a),x3(u,t),n&&u.errors.push(n),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(l=>{c[l]||(c[l]={});const d=u.loaded[l];d.length&&d.forEach(f=>{c[l][f]===void 0&&(c[l][f]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(u=>!u.done)}read(t,n,r,i=0,s=this.retryTimeout,a){if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(l,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(l&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(l,d)},u=this.backend[r].bind(this.backend);if(u.length===2){try{const l=u(t,n);l&&typeof l.then=="function"?l.then(d=>c(null,d)).catch(c):c(null,l)}catch(l){c(l)}return}return u(t,n,c)}prepareLoading(t,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();de(t)&&(t=this.languageUtils.toResolveHierarchy(t)),de(n)&&(n=[n]);const s=this.queueLoad(t,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t,n=""){const r=t.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,c),this.loaded(t,a,c)})}saveMissing(t,n,r,i,s,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const u={...a,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let d;l.length===5?d=l(t,n,r,i,u):d=l(t,n,r,i),d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}else l(t,n,r,i,c,u)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const hh=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),de(e[1])&&(t.defaultValue=e[1]),de(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),gh=e=>(de(e.ns)&&(e.ns=[e.ns]),de(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),de(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),ta=()=>{},k3=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Bo extends Fc{constructor(t={},n){if(super(),this.options=gh(t),this.services={},this.logger=pn,this.modules={external:[]},k3(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(t={},n){this.isInitializing=!0,typeof t=="function"&&(n=t,t={}),t.defaultNS==null&&t.ns&&(de(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=hh();this.options={...r,...this.options,...gh(t)},this.options.interpolation={...r.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=l=>l?typeof l=="function"?new l:l:null;if(!this.options.isClone){this.modules.logger?pn.init(i(this.modules.logger),this.options):pn.init(null,this.options);let l;this.modules.formatter?l=this.modules.formatter:l=v3;const d=new ch(this.options);this.store=new sh(this.options.resources,this.options);const f=this.services;f.logger=pn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new y3(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),l&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(l),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ph(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new $3(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,...g)=>{this.emit(h,...g)}),this.modules.languageDetector&&(f.languageDetector=i(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=i(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new La(this.services,this.options),this.translator.on("*",(h,...g)=>{this.emit(h,...g)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=ta),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.length>0&&l[0]!=="dev"&&(this.options.lng=l[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(l=>{this[l]=(...d)=>this.store[l](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(l=>{this[l]=(...d)=>(this.store[l](...d),this)});const c=lo(),u=()=>{const l=(d,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),n(d,f)};if(this.languages&&!this.isInitialized)return l(null,this.t.bind(this));this.changeLanguage(this.options.lng,l)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),c}loadResources(t,n=ta){let r=n;const i=de(t)?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(l=>{l!=="cimode"&&s.indexOf(l)<0&&s.push(l)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>a(u)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(s,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(t,n,r){const i=lo();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=ta),this.services.backendConnector.reload(t,n,s=>{i.resolve(),r(s)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&L1.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,n){this.isLanguageChangingTo=t;const r=lo();this.emit("languageChanging",t);const i=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},s=(c,u)=>{u?this.isLanguageChangingTo===t&&(i(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,r.resolve((...l)=>this.t(...l)),n&&n(c,(...l)=>this.t(...l))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const u=de(c)?c:c&&c[0],l=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(de(c)?[c]:c);l&&(this.language||i(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector?.cacheUserLanguage?.(l)),this.loadResources(l,d=>{s(d,l)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t),r}getFixedT(t,n,r){const i=(s,a,...c)=>{let u;typeof a!="object"?u=this.options.overloadTranslationOptionHandler([s,a].concat(c)):u={...a},u.lng=u.lng||i.lng,u.lngs=u.lngs||i.lngs,u.ns=u.ns||i.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||r||i.keyPrefix);const l=this.options.keySeparator||".";let d;return u.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=xd(f,{...this.options,...a})),`${u.keyPrefix}${l}${f}`)):(typeof s=="function"&&(s=xd(s,{...this.options,...a})),d=u.keyPrefix?`${u.keyPrefix}${l}${s}`:s),this.t(d,u)};return de(t)?i.lng=t:i.lngs=t,i.ns=n,i.keyPrefix=r,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(c,u)=>{const l=this.services.backendConnector.state[`${c}|${u}`];return l===-1||l===0||l===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!i||a(s,t)))}loadNamespaces(t,n){const r=lo();return this.options.ns?(de(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=lo();de(t)&&(t=[t]);const i=this.options.preload||[],s=t.filter(a=>i.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return s.length?(this.options.preload=i.concat(s),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const i=new Intl.Locale(t);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new ch(hh());return t.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},n){const r=new Bo(t,n);return r.createInstance=Bo.createInstance,r}cloneInstance(t={},n=ta){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Bo(i);if((t.debug!==void 0||t.prefix!==void 0)&&(s.logger=s.logger.clone(t)),["store","services","language"].forEach(c=>{s[c]=this[c]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const c=Object.keys(this.store.data).reduce((u,l)=>(u[l]={...this.store.data[l]},u[l]=Object.keys(u[l]).reduce((d,f)=>(d[f]={...u[l][f]},d),u[l]),u),{});s.store=new sh(c,i),s.services.resourceStore=s.store}return t.interpolation&&(s.services.interpolator=new ph(i)),s.translator=new La(s.services,i),s.translator.on("*",(c,...u)=>{s.emit(c,...u)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const j=Bo.createInstance();j.createInstance;j.dir;j.init;j.loadResources;j.reloadResources;j.use;j.changeLanguage;j.getFixedT;const le=j.t;j.exists;j.setDefaultNamespace;j.hasLoadedNamespace;j.loadNamespaces;j.loadLanguages;var B1=e=>{const n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...e},r=(s=>typeof s=="string"?s==="*"?()=>s:a=>s===a?a:null:typeof s=="function"?s:a=>s.includes(a)?a:null)(n.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(n.allowMethods);return async function(a,c){function u(d,f){a.res.headers.set(d,f)}const l=await r(a.req.header("origin")||"",a);if(l&&u("Access-Control-Allow-Origin",l),n.credentials&&u("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&u("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&u("Vary","Origin"),n.maxAge!=null&&u("Access-Control-Max-Age",n.maxAge.toString());const d=await i(a.req.header("origin")||"",a);d.length&&u("Access-Control-Allow-Methods",d.join(","));let f=n.allowHeaders;if(!f?.length){const p=a.req.header("Access-Control-Request-Headers");p&&(f=p.split(/\s*,\s*/))}return f?.length&&(u("Access-Control-Allow-Headers",f.join(",")),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),n.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};const Vr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),S3=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),z3=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),A3=o.z.enum(["VERIFY_EMAIL"]),U1=o.z.object({require_mx_record:o.z.boolean().optional(),block_aliases:o.z.boolean().optional(),block_free_emails:o.z.boolean().optional(),block_disposable_emails:o.z.boolean().optional(),blocklist:o.z.array(o.z.string()).optional(),allowlist:o.z.array(o.z.string()).optional()}),M1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("AUTH0"),action:o.z.literal("UPDATE_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({connection_id:o.z.string().optional(),user_id:o.z.string(),changes:o.z.record(o.z.string(),o.z.any())})}),q1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("EMAIL"),action:o.z.literal("VERIFY_EMAIL"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({email:o.z.string(),rules:U1.optional()})}),F1=o.z.enum(["change-email","account","custom"]),H1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("REDIRECT"),action:o.z.literal("REDIRECT_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({target:F1.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:o.z.string().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),V1=o.z.union([M1,q1,H1]),Da=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(V1).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),hi=Da.extend({...Vr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),E3=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})}),wt=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),K1=o.z.object({email:o.z.string().optional(),email_verified:o.z.boolean().optional(),name:o.z.string().optional(),username:o.z.string().optional(),given_name:o.z.string().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),family_name:o.z.string().optional()}).catchall(o.z.any()),G1=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:K1.optional()}),Hc=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().optional(),phone_number:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),nickname:o.z.string().optional(),name:o.z.string().optional(),picture:o.z.string().optional(),locale:o.z.string().optional(),linked_to:o.z.string().optional(),profileData:o.z.string().optional(),user_id:o.z.string().optional(),app_metadata:o.z.any().default({}).optional(),user_metadata:o.z.any().default({}).optional()}),Ba=Hc.extend({email_verified:o.z.boolean().default(!1),verify_email:o.z.boolean().optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string().optional(),provider:o.z.string().optional(),connection:o.z.string(),is_social:o.z.boolean().optional()}),gf=o.z.object({...Ba.shape,...Vr.shape,user_id:o.z.string(),provider:o.z.string(),is_social:o.z.boolean(),email:o.z.string().optional(),login_count:o.z.number().default(0),identities:o.z.array(G1).optional()}),ln=gf,C3=Hc.extend({login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any()),I3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let N3=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=I3[n[e]&63];return t};const Ua=o.z.object({client_id:o.z.string().openapi({description:"ID of this client."}),name:o.z.string().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:o.z.string().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:o.z.boolean().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:o.z.string().default(()=>N3()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:o.z.enum(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:o.z.string().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:o.z.boolean().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),callbacks:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs allowed to make requests from JavaScript to Auth0 API (typically used with CORS). By default, all your callback URLs will be allowed. This field allows you to enter other origins if necessary. You can also use wildcards at the subdomain level (e.g., https://*.contoso.com). Query strings and hash information are not taken into account when validating these URLs."}),web_origins:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of allowed origins for use with Cross-Origin Authentication, Device Flow, and web message response mode."}),client_aliases:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of allow clients and API ids that are allowed to make delegation requests. Empty means all all your clients are allowed."}),connections:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of connection IDs enabled for this client. The order determines the display order on the login page."}),allowed_logout_urls:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs that are valid to redirect to after logout from Auth0. Wildcards are allowed for subdomains."}),session_transfer:o.z.record(o.z.any()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of grant types supported for this application. Can include authorization_code, implicit, refresh_token, client_credentials, password, http://auth0.com/oauth/grant-type/password-realm, http://auth0.com/oauth/grant-type/mfa-oob, http://auth0.com/oauth/grant-type/mfa-otp, http://auth0.com/oauth/grant-type/mfa-recovery-code, urn:openid:params:grant-type:ciba, and urn:ietf:params:oauth:grant-type:device_code."}),jwt_configuration:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:o.z.array(o.z.record(o.z.any())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:o.z.record(o.z.any()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:o.z.boolean().default(!1).openapi({description:"Applies only to SSO clients and determines whether Auth0 will handle Single Sign On (true) or whether the Identity Provider will (false)."}),sso_disabled:o.z.boolean().default(!0).openapi({description:"Whether Single Sign On is disabled (true) or enabled (true). Defaults to true."}),cross_origin_authentication:o.z.boolean().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:o.z.string().url().optional().openapi({description:"URL of the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page."}),custom_login_page_on:o.z.boolean().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:o.z.string().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:o.z.record(o.z.any()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:o.z.enum(["none","client_secret_post","client_secret_basic"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. Can be none (public client without a client secret), client_secret_post (client uses HTTP POST parameters), or client_secret_basic (client uses HTTP Basic)."}),client_metadata:o.z.record(o.z.string().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),mobile:o.z.record(o.z.any()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:o.z.string().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:o.z.record(o.z.any()).default({}).optional(),refresh_token:o.z.record(o.z.any()).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:o.z.enum(["deny","allow","require"]).default("deny").optional().openapi({description:"Defines how to proceed during an authentication transaction with regards an organization. Can be deny (default), allow or require."}),organization_require_behavior:o.z.enum(["no_prompt","pre_login_prompt","post_login_prompt"]).default("no_prompt").optional().openapi({description:"Defines how to proceed during an authentication transaction when client.organization_usage: 'require'. Can be no_prompt (default), pre_login_prompt or post_login_prompt. post_login_prompt requires oidc_conformant: true."}),client_authentication_methods:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:o.z.boolean().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:o.z.boolean().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:o.z.record(o.z.any()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:o.z.enum(["none","fapi1_adv_pkj_par","fapi1_adv_mtls_par","fapi2_sp_pkj_mtls","fapi2_sp_mtls_mtls"]).optional().openapi({description:"Defines the compliance level for this client, which may restrict it's capabilities"}),par_request_expiry:o.z.number().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:o.z.record(o.z.any()).default({}).optional()}),yr=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Ua.shape}),Ma=o.z.object({client_id:o.z.string().min(1).openapi({description:"ID of the client."}),audience:o.z.string().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:o.z.array(o.z.string()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:o.z.enum(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:o.z.boolean().optional().openapi({description:"If enabled, any organization can be used with this grant. If disabled (default), the grant must be explicitly assigned to the desired organizations."}),is_system:o.z.boolean().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"The type of application access the client grant allows. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."}),authorization_details_types:o.z.array(o.z.string()).optional().openapi({description:"Types of authorization_details allowed for this client grant. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."})}),br=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Ma.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),j3=o.z.array(br),Kr=o.z.object({x:o.z.number(),y:o.z.number()});var mf=(e=>(e.RICH_TEXT="RICH_TEXT",e.NEXT_BUTTON="NEXT_BUTTON",e.BACK_BUTTON="BACK_BUTTON",e.SUBMIT_BUTTON="SUBMIT_BUTTON",e.DIVIDER="DIVIDER",e.TEXT="TEXT",e.EMAIL="EMAIL",e.PASSWORD="PASSWORD",e.NUMBER="NUMBER",e.PHONE="PHONE",e.DATE="DATE",e.CHECKBOX="CHECKBOX",e.RADIO="RADIO",e.SELECT="SELECT",e.HIDDEN="HIDDEN",e.LEGAL="LEGAL",e))(mf||{}),_f=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(_f||{});const Vc=o.z.object({id:o.z.string(),category:o.z.nativeEnum(_f),type:o.z.nativeEnum(mf)}),W1=Vc.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),J1=Vc.extend({category:o.z.literal("BLOCK"),type:o.z.union([o.z.literal("NEXT_BUTTON"),o.z.literal("BACK_BUTTON"),o.z.literal("SUBMIT_BUTTON")]),config:o.z.object({text:o.z.string()}).passthrough()}),X1=Vc.extend({category:o.z.literal("FIELD"),type:o.z.literal("LEGAL"),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({text:o.z.string()}).passthrough()}),Z1=Vc.extend({category:o.z.literal("FIELD"),type:o.z.union([o.z.literal("TEXT"),o.z.literal("EMAIL"),o.z.literal("PASSWORD"),o.z.literal("NUMBER"),o.z.literal("PHONE"),o.z.literal("DATE"),o.z.literal("CHECKBOX"),o.z.literal("RADIO"),o.z.literal("SELECT"),o.z.literal("HIDDEN")]),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()}).passthrough()}),Y1=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Q1=o.z.union([W1,J1,X1,Z1,Y1]);var ey=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(ey||{});const ty=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Q1),next_node:o.z.string()}).passthrough()}),ny=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),ry=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({action_type:o.z.enum(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:o.z.enum(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:o.z.string().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:o.z.string().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),iy=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Kr}).passthrough(),oy=o.z.union([ty,ny,ry,iy]),sy=o.z.object({next_node:o.z.string(),coordinates:Kr}).passthrough(),ay=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Kr}).passthrough(),cy=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(oy),start:sy,ending:ay,created_at:o.z.string(),updated_at:o.z.string(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).passthrough()}).passthrough(),T3=cy.omit({id:!0,created_at:!0,updated_at:!0});var Tt=(e=>(e.TOKEN="token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(Tt||{}),fn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(fn||{}),Kc=(e=>(e.S256="S256",e.Plain="plain",e))(Kc||{});const Zo=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(Tt).optional(),response_mode:o.z.nativeEnum(fn).optional(),redirect_uri:o.z.string().optional(),audience:o.z.string().optional(),organization:o.z.string().optional(),state:o.z.string().optional(),nonce:o.z.string().optional(),scope:o.z.string().optional(),prompt:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Kc).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),vendor_id:o.z.string().optional()}),$d=o.z.object({colors:o.z.object({primary:o.z.string(),page_background:o.z.object({type:o.z.string().optional(),start:o.z.string().optional(),end:o.z.string().optional(),angle_deg:o.z.number().optional()}).optional()}).optional(),logo_url:o.z.string().optional(),favicon_url:o.z.string().optional(),powered_by_logo_url:o.z.string().optional(),font:o.z.object({url:o.z.string()}).optional()}),bi=o.z.object({kid:o.z.string().optional(),team_id:o.z.string().optional(),realms:o.z.string().optional(),authentication_method:o.z.string().optional(),client_id:o.z.string().optional(),client_secret:o.z.string().optional(),app_secret:o.z.string().optional(),scope:o.z.string().optional(),authorization_endpoint:o.z.string().optional(),token_endpoint:o.z.string().optional(),userinfo_endpoint:o.z.string().optional(),jwks_uri:o.z.string().optional(),discovery_url:o.z.string().optional(),issuer:o.z.string().optional(),provider:o.z.string().optional(),from:o.z.string().optional(),twilio_sid:o.z.string().optional(),twilio_token:o.z.string().optional(),icon_url:o.z.string().optional()}),qa=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:bi.default({}),enabled_clients:o.z.array(o.z.string()).default([]).optional(),response_type:o.z.custom().optional(),response_mode:o.z.custom().optional(),is_domain_connection:o.z.boolean().optional(),show_as_button:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional(),is_system:o.z.boolean().optional()}),Nt=o.z.object({id:o.z.string(),created_at:o.z.string().transform(e=>e===null?"":e),updated_at:o.z.string().transform(e=>e===null?"":e)}).extend(qa.shape),yf=o.z.object({id:o.z.string().optional(),audience:o.z.string(),friendly_name:o.z.string(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sender_email:o.z.string().email(),sender_name:o.z.string(),session_lifetime:o.z.number().optional(),idle_session_lifetime:o.z.number().optional(),ephemeral_session_lifetime:o.z.number().optional(),idle_ephemeral_session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:o.z.array(o.z.string()).optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_changing_enable_sso:o.z.boolean().optional(),allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),change_pwd_flow_v1:o.z.boolean().optional(),custom_domains_provisioning:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),disable_impersonation:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),enable_sso:o.z.boolean().optional(),enforce_client_authentication_on_passwordless_start:o.z.boolean().optional(),genai_trial:o.z.boolean().optional(),improved_signup_bot_detection_in_classic:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional(),no_disclose_enterprise_connections:o.z.boolean().optional(),remove_alg_from_jwks:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),trust_azure_adfs_email_verified_connection_property:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),inherit_global_permissions_in_organizations:o.z.boolean().optional()}).optional(),sandbox_version:o.z.string().optional(),legacy_sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),device_flow:o.z.object({charset:o.z.enum(["base20","digits"]).optional(),mask:o.z.string().max(20).optional()}).optional(),default_token_quota:o.z.object({clients:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional(),organizations:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),oidc_logout:o.z.object({rp_logout_end_session_endpoint_discovery:o.z.boolean().optional()}).optional(),allow_organization_name_in_authentication_api:o.z.boolean().optional(),customize_mfa_in_postlogin_action:o.z.boolean().optional(),acr_values_supported:o.z.array(o.z.string()).optional(),mtls:o.z.object({enable_endpoint_aliases:o.z.boolean().optional()}).optional(),pushed_authorization_requests_supported:o.z.boolean().optional(),authorization_response_iss_parameter_supported:o.z.boolean().optional()}),Fa=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...yf.shape,id:o.z.string()}),O3=o.z.object({...yr.shape,tenant:Fa,connections:o.z.array(Nt)}),uy=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),ly=o.z.object({code_id:o.z.string().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:o.z.string().openapi({description:"The id of the login session that the code is connected to"}),connection_id:o.z.string().optional().openapi({description:"The connection that the code is connected to"}),code_type:uy,code_verifier:o.z.string().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:o.z.string().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:o.z.enum(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:o.z.string().optional().openapi({description:"The redirect URI associated with the code"}),nonce:o.z.string().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:o.z.string().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:o.z.string(),used_at:o.z.string().optional(),user_id:o.z.string().optional()}),P3=o.z.object({...ly.shape,created_at:o.z.string()}),bf=o.z.object({domain:o.z.string(),custom_domain_id:o.z.string().optional(),type:o.z.enum(["auth0_managed_certs","self_managed_certs"]),verification_method:o.z.enum(["txt"]).optional(),tls_policy:o.z.enum(["recommended"]).optional(),custom_client_ip_header:o.z.enum(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:o.z.record(o.z.string().max(255)).optional()}),dy=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),Hn=o.z.object({...bf.shape,custom_domain_id:o.z.string(),primary:o.z.boolean(),status:o.z.enum(["disabled","pending","pending_verification","ready"]),origin_domain_name:o.z.string().optional(),verification:o.z.object({methods:o.z.array(dy)}).optional(),tls_policy:o.z.string().optional()}),R3=Hn.extend({tenant_id:o.z.string()}),wf=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),sr=wf.extend({category:o.z.literal("BLOCK").optional()}),L3=sr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({}).optional()}),D3=sr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),B3=sr.extend({type:o.z.literal("IMAGE"),config:o.z.object({src:o.z.string().optional(),alt:o.z.string().optional(),width:o.z.number().optional(),height:o.z.number().optional()}).optional()}),U3=sr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),M3=sr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),q3=sr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),F3=sr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),H3=sr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),vf=wf.extend({category:o.z.literal("WIDGET").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),V3=vf.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),K3=vf.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),G3=vf.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),dt=wf.extend({category:o.z.literal("FIELD").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),W3=dt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),J3=dt.extend({type:o.z.literal("CARDS"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string(),description:o.z.string().optional(),image:o.z.string().optional()})).optional(),multi_select:o.z.boolean().optional()}).optional()}),X3=dt.extend({type:o.z.literal("CHOICE"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),display:o.z.enum(["radio","checkbox"]).optional()}).optional()}),Z3=dt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional()})}),Y3=dt.extend({type:o.z.literal("DATE"),config:o.z.object({format:o.z.string().optional(),min:o.z.string().optional(),max:o.z.string().optional()}).optional()}),Q3=dt.extend({type:o.z.literal("DROPDOWN"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),placeholder:o.z.string().optional(),searchable:o.z.boolean().optional()}).optional()}),e4=dt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional()}).optional()}),t4=dt.extend({type:o.z.literal("FILE"),config:o.z.object({accept:o.z.string().optional(),max_size:o.z.number().optional(),multiple:o.z.boolean().optional()}).optional()}),n4=dt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),r4=dt.extend({type:o.z.literal("NUMBER"),config:o.z.object({placeholder:o.z.string().optional(),min:o.z.number().optional(),max:o.z.number().optional(),step:o.z.number().optional()}).optional()}),i4=dt.extend({type:o.z.literal("PASSWORD"),config:o.z.object({placeholder:o.z.string().optional(),min_length:o.z.number().optional(),show_toggle:o.z.boolean().optional(),forgot_password_link:o.z.string().optional()}).optional()}),o4=dt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),s4=dt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional()}).optional()}),a4=dt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional()}).optional()}),c4=dt.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional(),max_length:o.z.number().optional()}).optional()}),u4=dt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional()}).optional()}),py=o.z.discriminatedUnion("type",[L3,D3,B3,U3,M3,q3,F3,H3]),fy=o.z.discriminatedUnion("type",[V3,K3,G3]),hy=o.z.discriminatedUnion("type",[W3,J3,X3,Z3,Y3,Q3,e4,t4,n4,r4,i4,o4,s4,a4,c4,u4]),xf=o.z.union([py,fy,hy]),l4=o.z.object({id:o.z.string(),type:o.z.literal("submit"),label:o.z.string(),className:o.z.string().optional(),disabled:o.z.boolean().optional().default(!1),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0),customizations:o.z.record(o.z.string(),o.z.any()).optional()}),Yo=o.z.object({x:o.z.number(),y:o.z.number()}),d4=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Yo,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({flow_id:o.z.string().max(30),next_node:o.z.string().optional()})}),p4=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Yo,alias:o.z.string().min(1).max(150),config:o.z.object({rules:o.z.array(o.z.object({id:o.z.string(),alias:o.z.string().min(1).max(150).optional(),condition:o.z.any(),next_node:o.z.string()})),fallback:o.z.string()})}),f4=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Yo,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(xf),next_node:o.z.string().optional()})}),gy=o.z.discriminatedUnion("type",[d4,p4,f4]),Ha=o.z.object({name:o.z.string().openapi({description:"The name of the form"}),messages:o.z.object({errors:o.z.record(o.z.string(),o.z.any()).optional(),custom:o.z.record(o.z.string(),o.z.any()).optional()}).optional(),languages:o.z.object({primary:o.z.string().optional(),default:o.z.string().optional()}).optional(),translations:o.z.record(o.z.string(),o.z.any()).optional(),nodes:o.z.array(gy).optional(),start:o.z.object({hidden_fields:o.z.array(o.z.object({key:o.z.string(),value:o.z.string()})).optional(),next_node:o.z.string().optional(),coordinates:Yo.optional()}).optional(),ending:o.z.object({redirection:o.z.object({delay:o.z.number().optional(),target:o.z.string().optional()}).optional(),after_submit:o.z.object({flow_id:o.z.string().optional()}).optional(),coordinates:Yo.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),gi=o.z.object({...Vr.shape,...Ha.shape,id:o.z.string()}),my=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),_y=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),h4=o.z.object({action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(xf),messages:o.z.array(my).optional(),links:o.z.array(_y).optional()});function g4(e){return e.category==="BLOCK"}function m4(e){return e.category==="WIDGET"}function _4(e){return e.category==="FIELD"}const yy=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),by=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Gc={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},y4=o.z.object({...Gc,trigger_id:yy,url:o.z.string()}),b4=o.z.object({...Gc,trigger_id:by,form_id:o.z.string()}),ba=o.z.union([y4,b4]),w4=o.z.object({...Gc,trigger_id:yy,...Vr.shape,hook_id:o.z.string(),url:o.z.string()}),v4=o.z.object({...Gc,trigger_id:by,...Vr.shape,hook_id:o.z.string(),form_id:o.z.string()}),mi=o.z.union([w4,v4]),wy=o.z.object({name:o.z.string().optional()}),vy=o.z.object({email:o.z.string().optional()}),$f=o.z.object({organization_id:o.z.string().max(50),inviter:wy,invitee:vy,invitation_url:o.z.string().url(),client_id:o.z.string(),connection_id:o.z.string().optional(),app_metadata:o.z.record(o.z.any()).default({}).optional(),user_metadata:o.z.record(o.z.any()).default({}).optional(),ttl_sec:o.z.number().int().max(2592e3).default(604800).optional(),roles:o.z.array(o.z.string()).default([]).optional(),send_invitation_email:o.z.boolean().default(!0).optional()}),Uo=o.z.object({id:o.z.string(),organization_id:o.z.string().max(50),created_at:o.z.string().datetime(),expires_at:o.z.string().datetime(),ticket_id:o.z.string().optional()}).extend($f.shape),kf=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),e:o.z.string(),kid:o.z.string(),kty:o.z.enum(["RSA","EC","oct"]),n:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional(),use:o.z.enum(["sig","enc"]).optional()}),xy=o.z.object({keys:o.z.array(kf)}),kd=o.z.object({issuer:o.z.string(),authorization_endpoint:o.z.string(),token_endpoint:o.z.string(),device_authorization_endpoint:o.z.string(),userinfo_endpoint:o.z.string(),mfa_challenge_endpoint:o.z.string(),jwks_uri:o.z.string(),registration_endpoint:o.z.string(),revocation_endpoint:o.z.string(),scopes_supported:o.z.array(o.z.string()),response_types_supported:o.z.array(o.z.string()),code_challenge_methods_supported:o.z.array(o.z.string()),response_modes_supported:o.z.array(o.z.string()),subject_types_supported:o.z.array(o.z.string()),id_token_signing_alg_values_supported:o.z.array(o.z.string()),token_endpoint_auth_methods_supported:o.z.array(o.z.string()),claims_supported:o.z.array(o.z.string()),request_uri_parameter_supported:o.z.boolean(),request_parameter_supported:o.z.boolean(),token_endpoint_auth_signing_alg_values_supported:o.z.array(o.z.string())}),$y=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Zo,expires_at:o.z.string(),deleted_at:o.z.string().optional(),ip:o.z.string().optional(),useragent:o.z.string().optional(),session_id:o.z.string().optional(),authorization_url:o.z.string().optional(),login_completed:o.z.boolean().optional().default(!1)}).openapi({description:"This represents a login sesion"}),x4=o.z.object({...$y.shape,id:o.z.string().openapi({description:"This is is used as the state in the universal login"}),created_at:o.z.string(),updated_at:o.z.string()}),he={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",MFA_REQUIRED:"mfar",MANAGEMENT_API_READ_OPERATION:"mgmt_api_read",FAILED_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_failed",SUCCESSFUL_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_succeeded",FAILED_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_failed",SUCCESSFUL_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_succeeded",ORGANIZATION_MEMBER_ADDED:"organization_member_added",PASSKEY_CHALLENGE_FAILED:"passkey_challenge_failed",PASSKEY_CHALLENGE_STARTED:"passkey_challenge_started",PRE_LOGIN_ASSESSMENT:"pla",BREACHED_PASSWORD:"pwd_leak",BREACHED_PASSWORD_ON_RESET:"reset_pwd_leak",SUCCESS_RESOURCE_CLEANUP:"resource_cleanup",RICH_CONSENTS_ACCESS_ERROR:"rich_consents_access_error",SUCCESS_LOGIN:"s",SUCCESS_API_OPERATION:"sapi",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},$4=o.z.string().refine(e=>Object.values(he).includes(e),{message:"Invalid log type"}),ky=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),Sy=o.z.object({country_code:o.z.string().length(2),city_name:o.z.string(),latitude:o.z.string(),longitude:o.z.string(),time_zone:o.z.string(),continent_code:o.z.string()}),zy=o.z.object({type:$4,date:o.z.string(),description:o.z.string().optional(),ip:o.z.string().optional(),user_agent:o.z.string().optional(),details:o.z.any().optional(),isMobile:o.z.boolean(),user_id:o.z.string().optional(),user_name:o.z.string().optional(),connection:o.z.string().optional(),connection_id:o.z.string().optional(),client_id:o.z.string().optional(),client_name:o.z.string().optional(),audience:o.z.string().optional(),scope:o.z.string().optional(),strategy:o.z.string().optional(),strategy_type:o.z.string().optional(),hostname:o.z.string().optional(),auth0_client:ky.optional(),log_id:o.z.string().optional(),location_info:Sy.optional()}),Va=o.z.object({...zy.shape,log_id:o.z.string()}),Ay=o.z.object({id:o.z.string().optional(),user_id:o.z.string(),password:o.z.string(),algorithm:o.z.enum(["bcrypt","argon2id"]).default("argon2id"),is_current:o.z.boolean().default(!0)}),k4=Ay.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),Ey=o.z.object({initial_user_agent:o.z.string().describe("First user agent of the device from which this user logged in"),initial_ip:o.z.string().describe("First IP address associated with this session"),initial_asn:o.z.string().describe("First autonomous system number associated with this session"),last_user_agent:o.z.string().describe("Last user agent of the device from which this user logged in"),last_ip:o.z.string().describe("Last IP address from which this user logged in"),last_asn:o.z.string().describe("Last autonomous system number from which this user logged in")}),Cy=o.z.object({id:o.z.string(),revoked_at:o.z.string().optional(),used_at:o.z.string().optional(),user_id:o.z.string().describe("The user ID associated with the session"),expires_at:o.z.string().optional(),login_session_id:o.z.string(),idle_expires_at:o.z.string().optional(),device:Ey.describe("Metadata related to the device used in the session"),clients:o.z.array(o.z.string()).describe("List of client details for the session")}),Wc=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...Cy.shape}),Sd=o.z.object({kid:o.z.string().openapi({description:"The key id of the signing key"}),cert:o.z.string().openapi({description:"The public certificate of the signing key"}),fingerprint:o.z.string().openapi({description:"The cert fingerprint"}),thumbprint:o.z.string().openapi({description:"The cert thumbprint"}),pkcs7:o.z.string().optional().openapi({description:"The private key in pkcs7 format"}),current:o.z.boolean().optional().openapi({description:"True if the key is the current key"}),next:o.z.boolean().optional().openapi({description:"True if the key is the next key"}),previous:o.z.boolean().optional().openapi({description:"True if the key is the previous key"}),current_since:o.z.string().optional().openapi({description:"The date and time when the key became the current key"}),current_until:o.z.string().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:o.z.boolean().optional().openapi({description:"True if the key is revoked"}),revoked_at:o.z.string().optional().openapi({description:"The date and time when the key was revoked"}),connection:o.z.string().optional().openapi({description:"The connection identifier associated with the key"}),type:o.z.enum(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});var Wt=(e=>(e.RefreshToken="refresh_token",e.AuthorizationCode="authorization_code",e.ClientCredential="client_credentials",e.Passwordless="passwordless",e.Password="password",e.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",e))(Wt||{});const Sf=o.z.object({access_token:o.z.string(),id_token:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),refresh_token:o.z.string().optional(),token_type:o.z.string(),expires_in:o.z.number()});o.z.object({code:o.z.string(),state:o.z.string().optional()});const Iy=o.z.object({button_border_radius:o.z.number(),button_border_weight:o.z.number(),buttons_style:o.z.enum(["pill","rounded","sharp"]),input_border_radius:o.z.number(),input_border_weight:o.z.number(),inputs_style:o.z.enum(["pill","rounded","sharp"]),show_widget_shadow:o.z.boolean(),widget_border_weight:o.z.number(),widget_corner_radius:o.z.number()}),Ny=o.z.object({base_focus_color:o.z.string(),base_hover_color:o.z.string(),body_text:o.z.string(),captcha_widget_theme:o.z.enum(["auto","dark","light"]),error:o.z.string(),header:o.z.string(),icons:o.z.string(),input_background:o.z.string(),input_border:o.z.string(),input_filled_text:o.z.string(),input_labels_placeholders:o.z.string(),links_focused_components:o.z.string(),primary_button:o.z.string(),primary_button_label:o.z.string(),secondary_button_border:o.z.string(),secondary_button_label:o.z.string(),success:o.z.string(),widget_background:o.z.string(),widget_border:o.z.string()}),gr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),jy=o.z.object({body_text:gr,buttons_text:gr,font_url:o.z.string(),input_labels:gr,links:gr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:gr,title:gr}),Ty=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),Oy=o.z.object({header_text_alignment:o.z.enum(["center","left","right"]),logo_height:o.z.number(),logo_position:o.z.enum(["center","left","none","right"]),logo_url:o.z.string(),social_buttons_layout:o.z.enum(["bottom","top"])}),Py=o.z.object({borders:Iy,colors:Ny,displayName:o.z.string(),fonts:jy,page_background:Ty,widget:Oy}),wa=Py.extend({themeId:o.z.string()}),va=o.z.object({universal_login_experience:o.z.enum(["new","classic"]).default("new"),identifier_first:o.z.boolean().default(!0),password_first:o.z.boolean().default(!1),webauthn_platform_first_factor:o.z.boolean()}),xa=o.z.object({name:o.z.string(),enabled:o.z.boolean().optional().default(!0),default_from_address:o.z.string().optional(),credentials:o.z.union([o.z.object({accessKeyId:o.z.string(),secretAccessKey:o.z.string(),region:o.z.string()}),o.z.object({smtp_host:o.z.array(o.z.string()),smtp_port:o.z.number(),smtp_user:o.z.string(),smtp_pass:o.z.string()}),o.z.object({api_key:o.z.string(),domain:o.z.string().optional()}),o.z.object({connectionString:o.z.string()}),o.z.object({tenantId:o.z.string(),clientId:o.z.string(),clientSecret:o.z.string()})]),settings:o.z.object({}).optional()}),zf=o.z.object({id:o.z.string(),session_id:o.z.string(),user_id:o.z.string(),client_id:o.z.string(),expires_at:o.z.string().optional(),idle_expires_at:o.z.string().optional(),last_exchanged_at:o.z.string().optional(),device:Ey,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),S4=o.z.object({created_at:o.z.string(),...zf.shape}),z4=o.z.object({to:o.z.string(),message:o.z.string()}),A4=o.z.object({name:o.z.string(),options:o.z.object({})}),Ry=o.z.object({value:o.z.string(),description:o.z.string().optional()}),Ly=o.z.object({token_dialect:o.z.enum(["access_token","access_token_authz"]).optional(),enforce_policies:o.z.boolean().optional(),allow_skipping_userinfo:o.z.boolean().optional(),skip_userinfo:o.z.boolean().optional(),persist_client_authorization:o.z.boolean().optional(),enable_introspection_endpoint:o.z.boolean().optional(),mtls:o.z.object({bound_access_tokens:o.z.boolean().optional()}).optional()}),Ka=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(Ry).optional(),signing_alg:o.z.string().optional(),signing_secret:o.z.string().optional(),token_lifetime:o.z.number().optional(),token_lifetime_for_web:o.z.number().optional(),skip_consent_for_verifiable_first_party_clients:o.z.boolean().optional(),allow_offline_access:o.z.boolean().optional(),verificationKey:o.z.string().optional(),options:Ly.optional(),is_system:o.z.boolean().optional()}),wr=o.z.object({...Ka.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),E4=o.z.array(wr),Dy=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),By=o.z.object({...Dy.shape,created_at:o.z.string()}),Uy=o.z.array(By),My=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string(),organization_id:o.z.string().optional()}),qy=o.z.object({...My.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),C4=o.z.array(qy),Fy=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),resource_server_name:o.z.string(),permission_name:o.z.string(),description:o.z.string().nullable().optional(),created_at:o.z.string().optional(),organization_id:o.z.string().optional()}),Hy=o.z.array(Fy),Vy=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),Ky=o.z.object({...Vy.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),I4=o.z.array(Ky),Ga=o.z.object({id:o.z.string().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:o.z.string().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:o.z.string().max(255).optional().openapi({description:"The description of the role"}),is_system:o.z.boolean().optional()}),vr=Ga.extend({id:o.z.string().openapi({description:"The unique identifier of the role"}),created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Wa=o.z.array(vr),Gy=o.z.object({logo_url:o.z.string().optional().openapi({description:"URL of the organization's logo"}),colors:o.z.object({primary:o.z.string().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:o.z.string().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),Wy=o.z.object({connection_id:o.z.string().openapi({description:"ID of the connection"}),assign_membership_on_login:o.z.boolean().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:o.z.boolean().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:o.z.boolean().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),Jy=o.z.object({client_credentials:o.z.object({enforce:o.z.boolean().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),Ja=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).openapi({description:"The name of the organization"}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Gy,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Wy).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Jy}),Vn=o.z.object({...Ja.shape,...Vr.shape,id:o.z.string()}),Xy=o.z.object({user_id:o.z.string().openapi({description:"ID of the user"}),organization_id:o.z.string().openapi({description:"ID of the organization"})}),N4=o.z.object({...Xy.shape,...Vr.shape,id:o.z.string()}),j4=o.z.object({idle_session_lifetime:o.z.number().optional(),session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:o.z.boolean().optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional()}).optional(),friendly_name:o.z.string().optional(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional()}),Zy=o.z.object({date:o.z.string().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:o.z.number().openapi({description:"Number of logins on this date",example:150}),signups:o.z.number().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:o.z.number().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:o.z.string().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:o.z.string().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})}),T4=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234});function O4(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function P4(e){const{primary:t,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=e,i={get(s,a){if(typeof a=="symbol")return s[a];const c=s[a];return typeof c!="function"?c:r.includes(a)?async(...u)=>{const l=await c.apply(s,u),d=[];for(const f of n){const p=f.adapter[a];if(typeof p!="function")continue;const h=(async()=>{try{await p.apply(f.adapter,u)}catch(g){try{f.onError?f.onError(g,a,u):console.error(`Passthrough adapter: secondary write failed for ${a}:`,g)}catch(y){console.error(`Passthrough adapter: onError handler threw for ${a}:`,y)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),l}:c.bind(s)}};return new Proxy(t,i)}function R4(e){return e}const mh={themeId:"default",borders:{button_border_radius:8,button_border_weight:1,buttons_style:"pill",input_border_radius:8,input_border_weight:1,inputs_style:"pill",show_widget_shadow:!0,widget_border_weight:1,widget_corner_radius:16},colors:{base_focus_color:"#7D68F4",base_hover_color:"#A091F2",body_text:"#000000",captcha_widget_theme:"auto",error:"#FC5A5A",header:"#000000",icons:"#666666",input_background:"#FFFFFF",input_border:"#BFBCD7",input_filled_text:"#000000",input_labels_placeholders:"#88869F",links_focused_components:"#7D68F4",primary_button:"#7D68F4",primary_button_label:"#FFFFFF",secondary_button_border:"#BFBCD7",secondary_button_label:"#000000",success:"#36BF76",widget_background:"#FFFFFF",widget_border:"#BFBCD7"},displayName:"Default Theme",fonts:{body_text:{bold:!1,size:16},buttons_text:{bold:!1,size:16},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:14},links:{bold:!1,size:16},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:18},title:{bold:!0,size:24}},page_background:{background_color:"#F8F9FB",background_image_url:"https://assets.sesamy.com/images/login-bg.jpg",page_layout:"center"},widget:{header_text_alignment:"center",logo_height:36,logo_position:"center",logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",social_buttons_layout:"bottom"}};function zd(e,t){const n=structuredClone(e);function r(i,s){for(const a in s)s[a]!==void 0&&typeof s[a]=="object"&&!Array.isArray(s[a])&&typeof i[a]=="object"&&i[a]!==null?r(i[a],s[a]):i[a]=s[a];return i}return r(n,t)}const L4=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/default",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:themes","auth:read"]}],responses:{200:{content:{"application/json":{schema:wa}},description:"Default theme settings"}}}),async e=>{const t=await e.env.data.themes.get(e.var.tenant_id,"default");return t?e.json(t):e.json(mh)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:wa.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:themes","auth:write"]}],responses:{200:{content:{"application/json":{schema:wa}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default");if(n){const r=zd(n,t);await e.env.data.themes.update(e.var.tenant_id,"default",r);const i=await e.env.data.themes.get(e.var.tenant_id,"default");return e.json(i)}else{const r=zd(mh,t),i=await e.env.data.themes.create(e.var.tenant_id,r);return e.json(i)}}),D4={colors:{primary:"#7D68F4",page_background:{type:"solid",start:"#F8F9FB",end:"#F8F9FB",angle_deg:0}},logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",favicon_url:"https://assets.sesamy.com/images/favicon.ico",font:{url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2"}},B4=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:$d}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json(D4)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object($d.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.branding.set(e.var.tenant_id,t),e.text("OK")}).route("/themes",L4),Yy={},U4=Object.freeze(Object.defineProperty({__proto__:null,default:Yy},Symbol.toStringTag,{value:"Module"}));var Ad=null;function M4(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return Yy.randomBytes(e)}catch{}if(!Ad)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return Ad(e)}function q4(e){Ad=e}function Af(e,t){if(e=e||Ef,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(Xa(M4(Qo),Qo)),n.join("")}function Qy(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=Ef;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){Jt(function(){try{i(null,Af(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 eb(e,t){if(typeof t>"u"&&(t=Ef),typeof t=="number"&&(t=Af(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return Ed(e,t)}function tb(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?Qy(t,function(a,c){Ed(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?Ed(e,t,s,r):Jt(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,u){if(c){a(c);return}s(u)})})}function nb(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 F4(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:nb(eb(e,t.substring(0,t.length-31)),t)}function H4(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){Jt(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){Jt(s.bind(this,null,!1));return}tb(e,t.substring(0,29),function(a,c){a?s(a):s(null,nb(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,u){if(c){a(c);return}s(u)})})}function V4(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function K4(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 G4(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return rb(e)>72}var Jt=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function rb(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 W4(e){for(var t=0,n,r,i=new Array(rb(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 ni="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),Mn=[-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 Xa(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(ni[i>>2&63]),i=(i&3)<<4,n>=t){r.push(ni[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(ni[i&63]),i=(s&15)<<2,n>=t){r.push(ni[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(ni[i&63]),r.push(ni[s&63])}return r.join("")}function ib(e,t){var n=0,r=e.length,i=0,s=[],a,c,u,l,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<Mn.length?Mn[f]:-1,f=e.charCodeAt(n++),c=f<Mn.length?Mn[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++),u=f<Mn.length?Mn[f]:-1,u==-1)||(d=(c&15)<<4>>>0,d|=(u&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),l=f<Mn.length?Mn[f]:-1,d=(u&3)<<6>>>0,d|=l,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var Qo=16,Ef=10,J4=16,X4=100,_h=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],yh=[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],ob=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function es(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[J4+1],e[t+1]=s,e}function ci(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 bh(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,u=0;u<s;u++)c=ci(e,r),r=c.offp,t[u]=t[u]^c.key;for(u=0;u<s;u+=2)i=es(i,0,t,n),t[u]=i[0],t[u+1]=i[1];for(u=0;u<a;u+=2)i=es(i,0,t,n),n[u]=i[0],n[u+1]=i[1]}function Z4(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,u,l=0;l<a;l++)u=ci(t,i),i=u.offp,n[l]=n[l]^u.key;for(i=0,l=0;l<a;l+=2)u=ci(e,i),i=u.offp,s[0]^=u.key,u=ci(e,i),i=u.offp,s[1]^=u.key,s=es(s,0,n,r),n[l]=s[0],n[l+1]=s[1];for(l=0;l<c;l+=2)u=ci(e,i),i=u.offp,s[0]^=u.key,u=ci(e,i),i=u.offp,s[1]^=u.key,s=es(s,0,n,r),r[l]=s[0],r[l+1]=s[1]}function wh(e,t,n,r,i){var s=ob.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){Jt(r.bind(this,c));return}else throw c;if(t.length!==Qo)if(c=Error("Illegal salt length: "+t.length+" != "+Qo),r){Jt(r.bind(this,c));return}else throw c;n=1<<n>>>0;var u,l,d=0,f;typeof Int32Array=="function"?(u=new Int32Array(_h),l=new Int32Array(yh)):(u=_h.slice(),l=yh.slice()),Z4(t,e,u,l);function p(){if(i&&i(d/n),d<n)for(var g=Date.now();d<n&&(d=d+1,bh(e,u,l),bh(t,u,l),!(Date.now()-g>X4)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)es(s,f<<1,u,l);var y=[];for(d=0;d<a;d++)y.push((s[d]>>24&255)>>>0),y.push((s[d]>>16&255)>>>0),y.push((s[d]>>8&255)>>>0),y.push((s[d]&255)>>>0);if(r){r(null,y);return}else return y}r&&Jt(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function Ed(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){Jt(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){Jt(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){Jt(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){Jt(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,u=parseInt(t.substring(a+1,a+2),10),l=c+u,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=W4(e),p=ib(d,Qo);function h(g){var y=[];return y.push("$2"),s>="a"&&y.push(s),y.push("$"),l<10&&y.push("0"),y.push(l.toString()),y.push("$"),y.push(Xa(p,p.length)),y.push(Xa(g,ob.length*4-1)),y.join("")}if(typeof n>"u")return h(wh(f,p,l));wh(f,p,l,function(g,y){g?n(g,null):n(null,h(y))},r)}function Y4(e,t){return Xa(e,t)}function Q4(e,t){return ib(e,t)}const Yn={setRandomFallback:q4,genSaltSync:Af,genSalt:Qy,hashSync:eb,hash:tb,compareSync:F4,compare:H4,getRounds:V4,getSalt:K4,truncates:G4,encodeBase64:Y4,decodeBase64:Q4},e6="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let t6=e=>crypto.getRandomValues(new Uint8Array(e)),n6=(e,t,n)=>{let r=(2<<Math.log2(e.length-1))-1,i=-~(1.6*r*t/e.length);return(s=t)=>{let a="";for(;;){let c=n(i),u=i|0;for(;u--;)if(a+=e[c[u]&r]||"",a.length>=s)return a}}},sb=(e,t=21)=>n6(e,t|0,t6),Ne=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=e6[n[e]&63];return t};const r6=24;function $s(){return sb("0123456789abcdef",r6)()}function na(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}function i6(e){return async(t,n)=>{if(!n.email||!n.email_verified)return e.users.create(t,n);const r=await Ss({userAdapter:e.users,tenant_id:t,email:n.email});if(!r)return e.users.create(t,n);await e.users.create(t,{...n,linked_to:r.user_id});const i=await e.users.get(t,r.user_id);if(!i)throw new Error("Failed to fetch primary user after linking");return i}}var o6={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},ab=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(o6))if(s6(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},s6=e=>navigator.userAgent.startsWith(e);function cb(e,t){if(ab()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function a6(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function _e(e,t,n){const r={};if(e.req.raw?.headers){const s=a6(e.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(e.env.data.geo)try{s=await e.env.data.geo.getGeoInfo(r)||void 0}catch(c){console.warn("Failed to get geo information:",c)}const a={type:n.type,description:n.description||"",ip:e.var.ip,user_agent:e.var.useragent||"",auth0_client:e.var.auth0_client,date:new Date().toISOString(),details:{request:{method:e.req.method,path:e.req.path,qs:e.req.queries(),body:n.body||e.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:e.var.client_id,client_name:"",user_id:n.userId||e.var.user_id||"",hostname:e.req.header("host")||"",user_name:e.var.username||"",connection_id:"",connection:n.connection||e.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await e.env.data.logs.create(t,a)};n.waitForCompletion?await i():cb(e,i())}class Za{constructor(t,n){this.value=t,this.unit=n}value;unit;milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(t){return new Za(Math.round(this.milliseconds()*t),"ms")}}class c6{hash;constructor(t){this.hash=t}async verify(t,n,r){const i=await crypto.subtle.importKey("spki",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(t,n){const r=await crypto.subtle.importKey("pkcs8",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(t){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:t??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function ub(e){return await crypto.subtle.digest("SHA-256",e)}const vh="0123456789abcdef";function Cd(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=vh[i];const s=t[r]&15;n+=vh[s]}return n}class lb{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const c=(8-r.length%8)%8;for(let u=0;u<c;u++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const u=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);u.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const l=(u[0]<<3)+(u[1]>>2);if(s.push(l),c<6){const d=((u[1]&3)<<6)+(u[2]<<1)+(u[3]>>4);s.push(d)}if(c<4){const d=((u[3]&255)<<4)+(u[4]>>1);s.push(d)}if(c<3){const d=((u[4]&1)<<7)+(u[5]<<2)+(u[6]>>3);s.push(d)}if(c<1){const d=((u[6]&7)<<5)+u[7];s.push(d)}}return Uint8Array.from(s)}}new lb("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new lb("0123456789ABCDEFGHIJKLMNOPQRSTUV");class db{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const c=(4-r.length%4)%4;for(let u=0;u<c;u++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,u=0;for(let l=0;l<4;l++){const d=t[a*4+l];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);u+=f<<6*(3-l)}s.push(u>>16&255),c<2&&s.push(u>>8&255),c<1&&s.push(u&255)}return Uint8Array.from(s)}}const u6=new db("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),kr=new db("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function xh(e,t,n,r){const i={alg:e,typ:"JWT",...r?.headers},s={...n};r?.audiences!==void 0&&(s.aud=r.audiences),r?.subject!==void 0&&(s.sub=r.subject),r?.issuer!==void 0&&(s.iss=r.issuer),r?.jwtId!==void 0&&(s.jti=r.jwtId),r?.expiresIn!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),r?.notBefore!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const a=new TextEncoder,c=kr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),u=kr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),l=a.encode([c,u].join(".")),d=await d6(e).sign(t,l),f=kr.encode(new Uint8Array(d),{includePadding:!1});return[c,u,f].join(".")}function l6(e){const t=e.split(".");return t.length!==3?null:t}function ks(e){const t=l6(e);if(!t)return null;const n=new TextDecoder,r=kr.decode(t[0],{strict:!1}),i=kr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!p6(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const a=JSON.parse(n.decode(i));if(typeof a!="object"||a===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in a){if(typeof a.exp!="number")return null;c.expiresAt=new Date(a.exp*1e3)}if("iss"in a){if(typeof a.iss!="string")return null;c.issuer=a.iss}if("sub"in a){if(typeof a.sub!="string")return null;c.subject=a.sub}if("aud"in a)if(Array.isArray(a.aud)){for(const u of a.aud)if(typeof u!="string")return null;c.audiences=a.aud}else{if(typeof a.aud!="string")return null;c.audiences=[a.aud]}if("nbf"in a){if(typeof a.nbf!="number")return null;c.notBefore=new Date(a.nbf*1e3)}if("iat"in a){if(typeof a.iat!="number")return null;c.issuedAt=new Date(a.iat*1e3)}if("jti"in a){if(typeof a.jti!="string")return null;c.jwtId=a.jti}return{value:e,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:t,...c}}function d6(e){return new c6(f6[e])}function p6(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const f6={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function h6(){const e=new Uint8Array(32);return crypto.getRandomValues(e),kr.encode(e,{includePadding:!1})}function g6(e){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(e);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{e=e.replace(/./g,"\0")}}async function m6(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await ub(n);return kr.encode(new Uint8Array(r),{includePadding:!1})}const ra=300,Jc=720*60*60,Er=1440*60,_6="auth-token",Mo=1800*1e3,Id=10080*60*1e3,y6=300,b6=300,w6=1800*1e3,v6=1800*1e3,x6=1440*60*1e3;function pb(e,t,n){const r=[];return r.push([encodeURIComponent(e),encodeURIComponent(t)]),n?.domain!==void 0&&r.push(["Domain",n.domain]),n?.expires!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n?.httpOnly&&r.push(["HttpOnly"]),n?.maxAge!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),n?.path!==void 0&&r.push(["Path",n.path]),n?.sameSite==="lax"&&r.push(["SameSite","Lax"]),n?.sameSite==="none"&&r.push(["SameSite","None"]),n?.sameSite==="strict"&&r.push(["SameSite","Strict"]),n?.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function $6(e){const t=new Map,n=e.split("; ");for(const r of n){const i=r.split("="),s=i[0],a=i[1]??"";s&&t.set(decodeURIComponent(s),decodeURIComponent(a))}return t}function Cf(e){return`${e}-${_6}`}function fb(e){if(!e)return;const[t]=e.split(":");if(!t||t==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return;const n=t.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${t}`}function Ai(e,t){return t?$6(t).get(Cf(e)):void 0}function hb(e,t){return pb(Cf(e),"",{path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?fb(t):void 0})}function Ya(e,t,n){return pb(Cf(e),t,{path:"/",httpOnly:!0,secure:!0,maxAge:Jc,sameSite:"none",domain:n?fb(n):void 0})}class X extends C{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}var k6=Object.defineProperty,S6=(e,t,n)=>t in e?k6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wi=(e,t,n)=>S6(e,typeof t!="symbol"?t+"":t,n);const st=o.z.object({"#text":o.z.string()}),z6=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":z6,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(e=>e.toLowerCase()==="true").optional(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string().datetime(),"@_Destination":o.z.string().url(),"@_AssertionConsumerServiceURL":o.z.string().url().optional(),"@_ProtocolBinding":o.z.string().optional(),"@_Version":o.z.string()})});o.z.array(o.z.object({":@":o.z.object({"@_xmlns":o.z.string(),"@_entityID":o.z.string()}),EntityDescriptor:o.z.array(o.z.object({":@":o.z.object({"@_protocolSupportEnumeration":o.z.string()}),IDPSSODescriptor:o.z.array(o.z.union([o.z.object({KeyDescriptor:o.z.array(o.z.object({KeyInfo:o.z.array(o.z.object({X509Data:o.z.array(o.z.object({X509Certificate:o.z.array(st)}))})),":@":o.z.object({"@_xmlns":o.z.string()})})),":@":o.z.object({"@_use":o.z.string()})}),o.z.object({SingleLogoutService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({NameIDFormat:o.z.array(st)}),o.z.object({SingleSignOnService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({Attribute:o.z.array(o.z.object({})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string(),"@_xmlns":o.z.string()})})]))}))}));const A6=o.z.object({"saml:Attribute":o.z.array(o.z.object({"saml:AttributeValue":o.z.array(o.z.object({"#text":o.z.string()})),":@":o.z.object({"@_xmlns:xs":o.z.string().optional(),"@_xmlns:xsi":o.z.string(),"@_xsi:type":o.z.string()}).optional()})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string().optional()})}),E6=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),$h=o.z.object({"ds:Signature":o.z.array(o.z.union([o.z.object({"ds:SignedInfo":o.z.array(o.z.union([o.z.object({"ds:CanonicalizationMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:SignatureMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:Reference":o.z.array(o.z.union([o.z.object({"ds:Transforms":o.z.array(E6)}),o.z.object({"ds:DigestMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:DigestValue":o.z.array(st)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(st)}),o.z.object({"ds:KeyInfo":o.z.array(o.z.union([o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(st)}),o.z.object({"ds:Exponent":o.z.array(st)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(st)}))}),o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(st)}),o.z.object({"ds:Exponent":o.z.array(st)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(st)}))})]))})])),":@":o.z.object({"@_xmlns:ds":o.z.string().optional()}).optional()});o.z.array(o.z.object({"samlp:Response":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(st)}),$h,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(st),":@":o.z.object({"@_Value":o.z.string()})}))}),o.z.object({"saml:Assertion":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(st)}),$h,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(st),":@":o.z.object({"@_Format":o.z.string()})}),o.z.object({"saml:SubjectConfirmation":o.z.array(o.z.object({"saml:SubjectConfirmationData":o.z.array(o.z.any()),":@":o.z.object({"@_InResponseTo":o.z.string(),"@_NotOnOrAfter":o.z.string(),"@_Recipient":o.z.string()})})),":@":o.z.object({"@_Method":o.z.string()})})]))}),o.z.object({"saml:Conditions":o.z.array(o.z.object({"saml:AudienceRestriction":o.z.array(o.z.object({"saml:Audience":o.z.array(st)}))})),":@":o.z.object({"@_NotBefore":o.z.string(),"@_NotOnOrAfter":o.z.string()})}),o.z.object({"saml:AuthnStatement":o.z.array(o.z.object({"saml:AuthnContext":o.z.array(o.z.object({"saml:AuthnContextClassRef":o.z.array(st)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(A6)})])),":@":o.z.object({"@_xmlns":o.z.string(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})})])),":@":o.z.object({"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string(),"@_Destination":o.z.string(),"@_ID":o.z.string(),"@_InResponseTo":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})}));var C6={};(function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+t+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,u){const l=[];let d=u.exec(c);for(;d;){const f=[];f.startIndex=u.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);l.push(f),d=u.exec(c)}return l},a=function(c){const u=i.exec(c);return!(u===null||typeof u>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,u,l){if(u){const d=Object.keys(u),f=d.length;for(let p=0;p<f;p++)l==="strict"?c[d[p]]=[u[d[p]]]:c[d[p]]=u[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(C6);function I6(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(const n of e)if(typeof n=="string"&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var N6=I6;const j6=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var C=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};const de=e=>typeof e=="string",lo=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},nh=e=>e==null?"":""+e,s3=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},a3=/###/g,rh=e=>e&&e.indexOf("###")>-1?e.replace(a3,"."):e,ih=e=>!e||de(e),Do=(e,t,n)=>{const r=de(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(ih(e))return{};const s=rh(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return ih(e)?{}:{obj:e,k:rh(r[i])}},oh=(e,t,n)=>{const{obj:r,k:i}=Do(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let s=t[t.length-1],a=t.slice(0,t.length-1),c=Do(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Do(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},c3=(e,t,n,r)=>{const{obj:i,k:s}=Do(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Pa=(e,t)=>{const{obj:n,k:r}=Do(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},u3=(e,t,n)=>{const r=Pa(e,n);return r!==void 0?r:Pa(t,n)},R1=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?de(e[r])||e[r]instanceof String||de(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):R1(e[r],t[r],n):e[r]=t[r]);return e},ti=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var l3={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const d3=e=>de(e)?e.replace(/[&<>"'\/]/g,t=>l3[t]):e;class p3{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const f3=[" ",",","?","!",";"],h3=new p3(20),g3=(e,t,n)=>{t=t||"",n=n||"";const r=f3.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=h3.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(e);if(!s){const a=e.indexOf(n);a>0&&!i.test(e.substring(0,a))&&(s=!0)}return s},vd=(e,t,n=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const r=t.split(n);let i=e;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let a,c="";for(let u=s;u<r.length;++u)if(u!==s&&(c+=n),c+=r[u],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&u<r.length-1)continue;s+=u-s+1;break}i=a}return i},Xo=e=>e?.replace("_","-"),m3={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Ra{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||m3,this.options=n,this.debug=n.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,n,r,i){return i&&!this.debug?null:(de(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Ra(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Ra(this.logger,t)}}var pn=new Ra;class Fc{constructor(){this.observers={}}on(t,n){return t.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t,...n){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i.apply(i,[t,...n])})}}class sh extends Fc{constructor(t,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,a=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;t.indexOf(".")>-1?c=t.split("."):(c=[t,n],r&&(Array.isArray(r)?c.push(...r):de(r)&&s?c.push(...r.split(s)):c.push(r)));const u=Pa(this.data,c);return!u&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),u||!a||!de(r)?u:vd(this.data?.[t]?.[n],r,s)}addResource(t,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[t,n];r&&(c=c.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(c=t.split("."),i=n,n=c[1]),this.addNamespaces(n),oh(this.data,c,i),s.silent||this.emit("added",t,n,r,i)}addResources(t,n,r,i={silent:!1}){for(const s in r)(de(r[s])||Array.isArray(r[s]))&&this.addResource(t,n,s,r[s],{silent:!0});i.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[t,n];t.indexOf(".")>-1&&(c=t.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let u=Pa(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?R1(u,r,s):u={...u,...r},oh(this.data,c,u),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var L1={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(s=>{t=this.processors[s]?.process(t,n,r,i)??t}),t}};const D1=Symbol("i18next/PATH_KEY");function _3(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===D1?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function xd(e,t){const{[D1]:n}=e(_3());return n.join(t?.keySeparator??".")}const ah={},ll=e=>!de(e)&&typeof e!="boolean"&&typeof e!="number";class La extends Fc{constructor(t,n={}){super(),s3(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=pn.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,n={interpolation:{}}){const r={...n};if(t==null)return!1;const i=this.resolve(t,r);if(i?.res===void 0)return!1;const s=ll(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!g3(t,r,i);if(a&&!c){const u=t.match(this.interpolator.nestingRegexp);if(u&&u.length>0)return{key:t,namespaces:de(s)?[s]:s};const l=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(l[0])>-1)&&(s=l.shift()),t=l.join(i)}return{key:t,namespaces:de(s)?[s]:s}}translate(t,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),t==null)return"";typeof t=="function"&&(t=xd(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]);const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:u}=this.extractFromKey(t[t.length-1],i),l=u[u.length-1];let d=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const f=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return p?s?{res:`${l}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let g=h?.res;const y=h?.usedKey||c,w=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],x=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,$=!this.i18nFormat||this.i18nFormat.handleAsObject,k=i.count!==void 0&&!de(i.count),v=La.hasDefaultValue(i),z=k?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&k?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",N=k&&!i.ordinal&&i.count===0,R=N&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${z}`]||i[`defaultValue${A}`]||i.defaultValue;let L=g;$&&!g&&v&&(L=R);const E=ll(L),O=Object.prototype.toString.apply(L);if($&&L&&E&&m.indexOf(O)<0&&!(de(x)&&Array.isArray(L))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const q=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,L,{...i,ns:u}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=q,h.usedParams=this.getUsedParamsDetails(i),h):q}if(a){const q=Array.isArray(L),K=q?[]:{},B=q?w:y;for(const oe in L)if(Object.prototype.hasOwnProperty.call(L,oe)){const ae=`${B}${a}${oe}`;v&&!g?K[oe]=this.translate(ae,{...i,defaultValue:ll(R)?R[oe]:void 0,joinArrays:!1,ns:u}):K[oe]=this.translate(ae,{...i,joinArrays:!1,ns:u}),K[oe]===ae&&(K[oe]=L[oe])}g=K}}else if($&&de(x)&&Array.isArray(g))g=g.join(x),g&&(g=this.extendTranslation(g,t,i,r));else{let q=!1,K=!1;!this.isValidLookup(g)&&v&&(q=!0,g=R),this.isValidLookup(g)||(K=!0,g=c);const oe=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&K?void 0:g,ae=v&&R!==g&&this.options.updateMissing;if(K||q||ae){if(this.logger.log(ae?"updateKey":"missingKey",f,l,c,ae?R:g),a){const Ce=this.resolve(c,{...i,keySeparator:!1});Ce&&Ce.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let se=[];const we=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&we&&we[0])for(let Ce=0;Ce<we.length;Ce++)se.push(we[Ce]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(i.lng||this.language):se.push(i.lng||this.language);const Ee=(Ce,Ge,F)=>{const Le=v&&F!==g?F:oe;this.options.missingKeyHandler?this.options.missingKeyHandler(Ce,l,Ge,Le,ae,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Ce,l,Ge,Le,ae,i),this.emit("missingKey",Ce,l,Ge,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&k?se.forEach(Ce=>{const Ge=this.pluralResolver.getSuffixes(Ce,i);N&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ge.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ge.push(`${this.options.pluralSeparator}zero`),Ge.forEach(F=>{Ee([Ce],c+F,i[`defaultValue${F}`]||R)})}):Ee(se,c,R))}g=this.extendTranslation(g,t,i,h,r),K&&g===c&&this.options.appendNamespaceToMissingKey&&(g=`${l}${d}${c}`),(K||q)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${d}${c}`:c,q?g:void 0,i))}return s?(h.res=g,h.usedParams=this.getUsedParamsDetails(i),h):g}extendTranslation(t,n,r,i,s){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=de(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let l;if(u){const f=t.match(this.interpolator.nestingRegexp);l=f&&f.length}let d=r.replace&&!de(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,r.lng||this.language||i.usedLng,r),u){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;l<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(t=this.interpolator.nest(t,(...f)=>s?.[0]===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${n[0]}`),null):this.translate(...f,n),r)),r.interpolation&&this.interpolator.reset()}const a=r.postProcess||this.options.postProcess,c=de(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=L1.handle(c,t,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),t}resolve(t,n={}){let r,i,s,a,c;return de(t)&&(t=[t]),t.forEach(u=>{if(this.isValidLookup(r))return;const l=this.extractFromKey(u,n),d=l.key;i=d;let f=l.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!de(n.count),h=p&&!n.ordinal&&n.count===0,g=n.context!==void 0&&(de(n.context)||typeof n.context=="number")&&n.context!=="",y=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(w=>{this.isValidLookup(r)||(c=w,!ah[`${y[0]}-${w}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(ah[`${y[0]}-${w}`]=!0,this.logger.warn(`key "${i}" for languages "${y.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),y.forEach(m=>{if(this.isValidLookup(r))return;a=m;const x=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(x,d,m,w,n);else{let k;p&&(k=this.pluralResolver.getSuffix(m,n.count,n));const v=`${this.options.pluralSeparator}zero`,z=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&k.indexOf(z)===0&&x.push(d+k.replace(z,this.options.pluralSeparator)),x.push(d+k),h&&x.push(d+v)),g){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;x.push(A),p&&(n.ordinal&&k.indexOf(z)===0&&x.push(A+k.replace(z,this.options.pluralSeparator)),x.push(A+k),h&&x.push(A+v))}}let $;for(;$=x.pop();)this.isValidLookup(r)||(s=$,r=this.getResource(m,w,$,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,n,r,i):this.resourceStore.getResource(t,n,r,i)}getUsedParamsDetails(t={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&!de(t.replace);let i=r?t.replace:t;if(r&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}class ch{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=pn.create("languageUtils")}getScriptPartFromCode(t){if(t=Xo(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Xo(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(de(t)&&t.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(t)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(a=>{if(a===s)return a;if(!(a.indexOf("-")<0&&s.indexOf("-")<0)&&(a.indexOf("-")>0&&s.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===s||a.indexOf(s)===0&&s.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),de(t)&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],t),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return de(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(t))):de(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const uh={zero:0,one:1,two:2,few:3,many:4,other:5},lh={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class y3{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=pn.create("pluralResolver"),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Xo(t==="dev"?"en":t),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let a;try{a=new Intl.PluralRules(r,{type:i})}catch{if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),lh;if(!t.match(/-|_/))return lh;const u=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(u,n)}return this.pluralRulesCache[s]=a,a}needsPlural(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,n,r={}){return this.getSuffixes(t,r).map(i=>`${n}${i}`)}getSuffixes(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>uh[i]-uh[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,n,r={}){const i=this.getRule(t,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",n,r))}}const dh=(e,t,n,r=".",i=!0)=>{let s=u3(e,t,n);return!s&&i&&de(n)&&(s=vd(e,n,r),s===void 0&&(s=vd(t,n,r))),s},dl=e=>e.replace(/\$/g,"$$$$");class ph{constructor(t={}){this.logger=pn.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(n=>n),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:u,formatSeparator:l,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:g,nestingSuffixEscaped:y,nestingOptionsSeparator:w,maxReplaces:m,alwaysFormat:x}=t.interpolation;this.escape=n!==void 0?n:d3,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?ti(s):a||"{{",this.suffix=c?ti(c):u||"}}",this.formatSeparator=l||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?ti(p):h||ti("$t("),this.nestingSuffix=g?ti(g):y||ti(")"),this.nestingOptionsSeparator=w||",",this.maxReplaces=m||1e3,this.alwaysFormat=x!==void 0?x:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,n,r,i){let s,a,c;const u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=h=>{if(h.indexOf(this.formatSeparator)<0){const m=dh(n,u,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const g=h.split(this.formatSeparator),y=g.shift().trim(),w=g.join(this.formatSeparator).trim();return this.format(dh(n,u,y,this.options.keySeparator,this.options.ignoreJSONStructure),w,r,{...i,...n,interpolationkey:y})};this.resetRegExp();const d=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>dl(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?dl(this.escape(h)):dl(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const g=s[1].trim();if(a=l(g),a===void 0)if(typeof d=="function"){const w=d(t,s,i);a=de(w)?w:""}else if(i&&Object.prototype.hasOwnProperty.call(i,g))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${t}`),a="";else!de(a)&&!this.useRawValueToEscape&&(a=nh(a));const y=h.safeValue(a);if(t=t.replace(s[0],y),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=s[0].length):h.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),t}nest(t,n,r={}){let i,s,a;const c=(u,l)=>{const d=this.nestingOptionsSeparator;if(u.indexOf(d)<0)return u;const f=u.split(new RegExp(`${d}[ ]*{`));let p=`{${f[1]}`;u=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),g=p.match(/"/g);((h?.length??0)%2===0&&!g||g.length%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),l&&(a={...l,...a})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${u}`,y),`${u}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,u};for(;i=this.nestingRegexp.exec(t);){let u=[];a={...r},a=a.replace&&!de(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const l=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(l!==-1&&(u=i[1].slice(l).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,l)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!de(s))return s;de(s)||(s=nh(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),u.length&&(s=u.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),t=t.replace(i[0],s),this.regexp.lastIndex=0}return t}}const b3=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);t==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...u]=a.split(":"),l=u.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=l),l==="false"&&(n[d]=!1),l==="true"&&(n[d]=!0),isNaN(l)||(n[d]=parseInt(l,10))}})}return{formatName:t,formatOptions:n}},fh=e=>{const t={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const a=r+JSON.stringify(s);let c=t[a];return c||(c=e(Xo(r),i),t[a]=c),c(n)}},w3=e=>(t,n,r)=>e(Xo(n),r)(t);class v3{constructor(t={}){this.logger=pn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?fh:w3;this.formats={number:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s});return c=>a.format(c)}),currency:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s,style:"currency"});return c=>a.format(c)}),datetime:r((i,s)=>{const a=new Intl.DateTimeFormat(i,{...s});return c=>a.format(c)}),relativetime:r((i,s)=>{const a=new Intl.RelativeTimeFormat(i,{...s});return c=>a.format(c,s.range||"day")}),list:r((i,s)=>{const a=new Intl.ListFormat(i,{...s});return c=>a.format(c)})}}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=fh(n)}format(t,n,r,i={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(c=>c.indexOf(")")>-1)){const c=s.findIndex(u=>u.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,u)=>{const{formatName:l,formatOptions:d}=b3(u);if(this.formats[l]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[l](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${l}`);return c},t)}}const x3=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class $3 extends Fc{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=pn.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(t,n,r,i){const s={},a={},c={},u={};return t.forEach(l=>{let d=!0;n.forEach(f=>{const p=`${l}|${f}`;!r.reload&&this.store.hasResourceBundle(l,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),s[p]===void 0&&(s[p]=!0),u[f]===void 0&&(u[f]=!0)))}),d||(c[l]=!0)}),(Object.keys(s).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(u)}}loaded(t,n,r){const i=t.split("|"),s=i[0],a=i[1];n&&this.emit("failedLoading",s,a,n),!n&&r&&this.store.addResourceBundle(s,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const c={};this.queue.forEach(u=>{c3(u.loaded,[s],a),x3(u,t),n&&u.errors.push(n),u.pendingCount===0&&!u.done&&(Object.keys(u.loaded).forEach(l=>{c[l]||(c[l]={});const d=u.loaded[l];d.length&&d.forEach(f=>{c[l][f]===void 0&&(c[l][f]=!0)})}),u.done=!0,u.errors.length?u.callback(u.errors):u.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(u=>!u.done)}read(t,n,r,i=0,s=this.retryTimeout,a){if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(l,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(l&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(l,d)},u=this.backend[r].bind(this.backend);if(u.length===2){try{const l=u(t,n);l&&typeof l.then=="function"?l.then(d=>c(null,d)).catch(c):c(null,l)}catch(l){c(l)}return}return u(t,n,c)}prepareLoading(t,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();de(t)&&(t=this.languageUtils.toResolveHierarchy(t)),de(n)&&(n=[n]);const s=this.queueLoad(t,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t,n=""){const r=t.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,c),this.loaded(t,a,c)})}saveMissing(t,n,r,i,s,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const u={...a,isUpdate:s},l=this.backend.create.bind(this.backend);if(l.length<6)try{let d;l.length===5?d=l(t,n,r,i,u):d=l(t,n,r,i),d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}else l(t,n,r,i,c,u)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const hh=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),de(e[1])&&(t.defaultValue=e[1]),de(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),gh=e=>(de(e.ns)&&(e.ns=[e.ns]),de(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),de(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),ta=()=>{},k3=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Bo extends Fc{constructor(t={},n){if(super(),this.options=gh(t),this.services={},this.logger=pn,this.modules={external:[]},k3(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(t={},n){this.isInitializing=!0,typeof t=="function"&&(n=t,t={}),t.defaultNS==null&&t.ns&&(de(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=hh();this.options={...r,...this.options,...gh(t)},this.options.interpolation={...r.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=l=>l?typeof l=="function"?new l:l:null;if(!this.options.isClone){this.modules.logger?pn.init(i(this.modules.logger),this.options):pn.init(null,this.options);let l;this.modules.formatter?l=this.modules.formatter:l=v3;const d=new ch(this.options);this.store=new sh(this.options.resources,this.options);const f=this.services;f.logger=pn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new y3(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),l&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(l),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ph(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new $3(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,...g)=>{this.emit(h,...g)}),this.modules.languageDetector&&(f.languageDetector=i(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=i(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new La(this.services,this.options),this.translator.on("*",(h,...g)=>{this.emit(h,...g)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=ta),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const l=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);l.length>0&&l[0]!=="dev"&&(this.options.lng=l[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(l=>{this[l]=(...d)=>this.store[l](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(l=>{this[l]=(...d)=>(this.store[l](...d),this)});const c=lo(),u=()=>{const l=(d,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),n(d,f)};if(this.languages&&!this.isInitialized)return l(null,this.t.bind(this));this.changeLanguage(this.options.lng,l)};return this.options.resources||!this.options.initAsync?u():setTimeout(u,0),c}loadResources(t,n=ta){let r=n;const i=de(t)?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(l=>{l!=="cimode"&&s.indexOf(l)<0&&s.push(l)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>a(u)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(s,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(t,n,r){const i=lo();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=ta),this.services.backendConnector.reload(t,n,s=>{i.resolve(),r(s)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&L1.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,n){this.isLanguageChangingTo=t;const r=lo();this.emit("languageChanging",t);const i=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},s=(c,u)=>{u?this.isLanguageChangingTo===t&&(i(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,r.resolve((...l)=>this.t(...l)),n&&n(c,(...l)=>this.t(...l))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const u=de(c)?c:c&&c[0],l=this.store.hasLanguageSomeTranslations(u)?u:this.services.languageUtils.getBestMatchFromCodes(de(c)?[c]:c);l&&(this.language||i(l),this.translator.language||this.translator.changeLanguage(l),this.services.languageDetector?.cacheUserLanguage?.(l)),this.loadResources(l,d=>{s(d,l)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t),r}getFixedT(t,n,r){const i=(s,a,...c)=>{let u;typeof a!="object"?u=this.options.overloadTranslationOptionHandler([s,a].concat(c)):u={...a},u.lng=u.lng||i.lng,u.lngs=u.lngs||i.lngs,u.ns=u.ns||i.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||r||i.keyPrefix);const l=this.options.keySeparator||".";let d;return u.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=xd(f,{...this.options,...a})),`${u.keyPrefix}${l}${f}`)):(typeof s=="function"&&(s=xd(s,{...this.options,...a})),d=u.keyPrefix?`${u.keyPrefix}${l}${s}`:s),this.t(d,u)};return de(t)?i.lng=t:i.lngs=t,i.ns=n,i.keyPrefix=r,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(c,u)=>{const l=this.services.backendConnector.state[`${c}|${u}`];return l===-1||l===0||l===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!i||a(s,t)))}loadNamespaces(t,n){const r=lo();return this.options.ns?(de(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=lo();de(t)&&(t=[t]);const i=this.options.preload||[],s=t.filter(a=>i.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return s.length?(this.options.preload=i.concat(s),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const i=new Intl.Locale(t);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new ch(hh());return t.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},n){const r=new Bo(t,n);return r.createInstance=Bo.createInstance,r}cloneInstance(t={},n=ta){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Bo(i);if((t.debug!==void 0||t.prefix!==void 0)&&(s.logger=s.logger.clone(t)),["store","services","language"].forEach(c=>{s[c]=this[c]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const c=Object.keys(this.store.data).reduce((u,l)=>(u[l]={...this.store.data[l]},u[l]=Object.keys(u[l]).reduce((d,f)=>(d[f]={...u[l][f]},d),u[l]),u),{});s.store=new sh(c,i),s.services.resourceStore=s.store}return t.interpolation&&(s.services.interpolator=new ph(i)),s.translator=new La(s.services,i),s.translator.on("*",(c,...u)=>{s.emit(c,...u)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const j=Bo.createInstance();j.createInstance;j.dir;j.init;j.loadResources;j.reloadResources;j.use;j.changeLanguage;j.getFixedT;const le=j.t;j.exists;j.setDefaultNamespace;j.hasLoadedNamespace;j.loadNamespaces;j.loadLanguages;var B1=e=>{const n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...e},r=(s=>typeof s=="string"?s==="*"?()=>s:a=>s===a?a:null:typeof s=="function"?s:a=>s.includes(a)?a:null)(n.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(n.allowMethods);return async function(a,c){function u(d,f){a.res.headers.set(d,f)}const l=await r(a.req.header("origin")||"",a);if(l&&u("Access-Control-Allow-Origin",l),n.credentials&&u("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&u("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&u("Vary","Origin"),n.maxAge!=null&&u("Access-Control-Max-Age",n.maxAge.toString());const d=await i(a.req.header("origin")||"",a);d.length&&u("Access-Control-Allow-Methods",d.join(","));let f=n.allowHeaders;if(!f?.length){const p=a.req.header("Access-Control-Request-Headers");p&&(f=p.split(/\s*,\s*/))}return f?.length&&(u("Access-Control-Allow-Headers",f.join(",")),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),n.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};const Vr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),S3=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),z3=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),A3=o.z.enum(["VERIFY_EMAIL"]),U1=o.z.object({require_mx_record:o.z.boolean().optional(),block_aliases:o.z.boolean().optional(),block_free_emails:o.z.boolean().optional(),block_disposable_emails:o.z.boolean().optional(),blocklist:o.z.array(o.z.string()).optional(),allowlist:o.z.array(o.z.string()).optional()}),M1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("AUTH0"),action:o.z.literal("UPDATE_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({connection_id:o.z.string().optional(),user_id:o.z.string(),changes:o.z.record(o.z.string(),o.z.any())})}),q1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("EMAIL"),action:o.z.literal("VERIFY_EMAIL"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({email:o.z.string(),rules:U1.optional()})}),F1=o.z.enum(["change-email","account","custom"]),H1=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("REDIRECT"),action:o.z.literal("REDIRECT_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({target:F1.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:o.z.string().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),V1=o.z.union([M1,q1,H1]),Da=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(V1).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),hi=Da.extend({...Vr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),E3=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})}),wt=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),K1=o.z.object({email:o.z.string().optional(),email_verified:o.z.boolean().optional(),name:o.z.string().optional(),username:o.z.string().optional(),given_name:o.z.string().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),family_name:o.z.string().optional()}).catchall(o.z.any()),G1=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:K1.optional()}),Hc=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().optional(),phone_number:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),nickname:o.z.string().optional(),name:o.z.string().optional(),picture:o.z.string().optional(),locale:o.z.string().optional(),linked_to:o.z.string().optional(),profileData:o.z.string().optional(),user_id:o.z.string().optional(),app_metadata:o.z.any().default({}).optional(),user_metadata:o.z.any().default({}).optional()}),Ba=Hc.extend({email_verified:o.z.boolean().default(!1),verify_email:o.z.boolean().optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string().optional(),provider:o.z.string().optional(),connection:o.z.string(),is_social:o.z.boolean().optional()}),gf=o.z.object({...Ba.shape,...Vr.shape,user_id:o.z.string(),provider:o.z.string(),is_social:o.z.boolean(),email:o.z.string().optional(),login_count:o.z.number().default(0),identities:o.z.array(G1).optional()}),ln=gf,C3=Hc.extend({login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any()),I3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let N3=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=I3[n[e]&63];return t};const Ua=o.z.object({client_id:o.z.string().openapi({description:"ID of this client."}),name:o.z.string().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:o.z.string().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:o.z.boolean().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:o.z.string().default(()=>N3()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:o.z.enum(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:o.z.string().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:o.z.boolean().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),callbacks:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs allowed to make requests from JavaScript to Auth0 API (typically used with CORS). By default, all your callback URLs will be allowed. This field allows you to enter other origins if necessary. You can also use wildcards at the subdomain level (e.g., https://*.contoso.com). Query strings and hash information are not taken into account when validating these URLs."}),web_origins:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of allowed origins for use with Cross-Origin Authentication, Device Flow, and web message response mode."}),client_aliases:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of allow clients and API ids that are allowed to make delegation requests. Empty means all all your clients are allowed."}),connections:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of connection IDs enabled for this client. The order determines the display order on the login page."}),allowed_logout_urls:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs that are valid to redirect to after logout from Auth0. Wildcards are allowed for subdomains."}),session_transfer:o.z.record(o.z.any()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of grant types supported for this application. Can include authorization_code, implicit, refresh_token, client_credentials, password, http://auth0.com/oauth/grant-type/password-realm, http://auth0.com/oauth/grant-type/mfa-oob, http://auth0.com/oauth/grant-type/mfa-otp, http://auth0.com/oauth/grant-type/mfa-recovery-code, urn:openid:params:grant-type:ciba, and urn:ietf:params:oauth:grant-type:device_code."}),jwt_configuration:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:o.z.array(o.z.record(o.z.any())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:o.z.record(o.z.any()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:o.z.boolean().default(!1).openapi({description:"Applies only to SSO clients and determines whether Auth0 will handle Single Sign On (true) or whether the Identity Provider will (false)."}),sso_disabled:o.z.boolean().default(!0).openapi({description:"Whether Single Sign On is disabled (true) or enabled (true). Defaults to true."}),cross_origin_authentication:o.z.boolean().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:o.z.string().url().optional().openapi({description:"URL of the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page."}),custom_login_page_on:o.z.boolean().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:o.z.string().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:o.z.record(o.z.any()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:o.z.enum(["none","client_secret_post","client_secret_basic"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. Can be none (public client without a client secret), client_secret_post (client uses HTTP POST parameters), or client_secret_basic (client uses HTTP Basic)."}),client_metadata:o.z.record(o.z.string().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),mobile:o.z.record(o.z.any()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:o.z.string().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:o.z.record(o.z.any()).default({}).optional(),refresh_token:o.z.record(o.z.any()).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:o.z.enum(["deny","allow","require"]).default("deny").optional().openapi({description:"Defines how to proceed during an authentication transaction with regards an organization. Can be deny (default), allow or require."}),organization_require_behavior:o.z.enum(["no_prompt","pre_login_prompt","post_login_prompt"]).default("no_prompt").optional().openapi({description:"Defines how to proceed during an authentication transaction when client.organization_usage: 'require'. Can be no_prompt (default), pre_login_prompt or post_login_prompt. post_login_prompt requires oidc_conformant: true."}),client_authentication_methods:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:o.z.boolean().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:o.z.boolean().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:o.z.record(o.z.any()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:o.z.enum(["none","fapi1_adv_pkj_par","fapi1_adv_mtls_par","fapi2_sp_pkj_mtls","fapi2_sp_mtls_mtls"]).optional().openapi({description:"Defines the compliance level for this client, which may restrict it's capabilities"}),par_request_expiry:o.z.number().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:o.z.record(o.z.any()).default({}).optional()}),yr=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Ua.shape}),Ma=o.z.object({client_id:o.z.string().min(1).openapi({description:"ID of the client."}),audience:o.z.string().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:o.z.array(o.z.string()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:o.z.enum(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:o.z.boolean().optional().openapi({description:"If enabled, any organization can be used with this grant. If disabled (default), the grant must be explicitly assigned to the desired organizations."}),is_system:o.z.boolean().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"The type of application access the client grant allows. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."}),authorization_details_types:o.z.array(o.z.string()).optional().openapi({description:"Types of authorization_details allowed for this client grant. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."})}),br=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Ma.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),j3=o.z.array(br),Kr=o.z.object({x:o.z.number(),y:o.z.number()});var mf=(e=>(e.RICH_TEXT="RICH_TEXT",e.NEXT_BUTTON="NEXT_BUTTON",e.BACK_BUTTON="BACK_BUTTON",e.SUBMIT_BUTTON="SUBMIT_BUTTON",e.DIVIDER="DIVIDER",e.TEXT="TEXT",e.EMAIL="EMAIL",e.PASSWORD="PASSWORD",e.NUMBER="NUMBER",e.PHONE="PHONE",e.DATE="DATE",e.CHECKBOX="CHECKBOX",e.RADIO="RADIO",e.SELECT="SELECT",e.HIDDEN="HIDDEN",e.LEGAL="LEGAL",e))(mf||{}),_f=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(_f||{});const Vc=o.z.object({id:o.z.string(),category:o.z.nativeEnum(_f),type:o.z.nativeEnum(mf)}),W1=Vc.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),J1=Vc.extend({category:o.z.literal("BLOCK"),type:o.z.union([o.z.literal("NEXT_BUTTON"),o.z.literal("BACK_BUTTON"),o.z.literal("SUBMIT_BUTTON")]),config:o.z.object({text:o.z.string()}).passthrough()}),X1=Vc.extend({category:o.z.literal("FIELD"),type:o.z.literal("LEGAL"),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({text:o.z.string()}).passthrough()}),Z1=Vc.extend({category:o.z.literal("FIELD"),type:o.z.union([o.z.literal("TEXT"),o.z.literal("EMAIL"),o.z.literal("PASSWORD"),o.z.literal("NUMBER"),o.z.literal("PHONE"),o.z.literal("DATE"),o.z.literal("CHECKBOX"),o.z.literal("RADIO"),o.z.literal("SELECT"),o.z.literal("HIDDEN")]),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()}).passthrough()}),Y1=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Q1=o.z.union([W1,J1,X1,Z1,Y1]);var ey=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(ey||{});const ty=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Q1),next_node:o.z.string()}).passthrough()}),ny=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),ry=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Kr,alias:o.z.string().optional(),config:o.z.object({action_type:o.z.enum(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:o.z.enum(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:o.z.string().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:o.z.string().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),iy=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Kr}).passthrough(),oy=o.z.union([ty,ny,ry,iy]),sy=o.z.object({next_node:o.z.string(),coordinates:Kr}).passthrough(),ay=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Kr}).passthrough(),cy=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(oy),start:sy,ending:ay,created_at:o.z.string(),updated_at:o.z.string(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).passthrough()}).passthrough(),T3=cy.omit({id:!0,created_at:!0,updated_at:!0});var Tt=(e=>(e.TOKEN="token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(Tt||{}),fn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(fn||{}),Kc=(e=>(e.S256="S256",e.Plain="plain",e))(Kc||{});const Zo=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(Tt).optional(),response_mode:o.z.nativeEnum(fn).optional(),redirect_uri:o.z.string().optional(),audience:o.z.string().optional(),organization:o.z.string().optional(),state:o.z.string().optional(),nonce:o.z.string().optional(),scope:o.z.string().optional(),prompt:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Kc).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),vendor_id:o.z.string().optional()}),$d=o.z.object({colors:o.z.object({primary:o.z.string(),page_background:o.z.object({type:o.z.string().optional(),start:o.z.string().optional(),end:o.z.string().optional(),angle_deg:o.z.number().optional()}).optional()}).optional(),logo_url:o.z.string().optional(),favicon_url:o.z.string().optional(),powered_by_logo_url:o.z.string().optional(),font:o.z.object({url:o.z.string()}).optional()}),bi=o.z.object({kid:o.z.string().optional(),team_id:o.z.string().optional(),realms:o.z.string().optional(),authentication_method:o.z.string().optional(),client_id:o.z.string().optional(),client_secret:o.z.string().optional(),app_secret:o.z.string().optional(),scope:o.z.string().optional(),authorization_endpoint:o.z.string().optional(),token_endpoint:o.z.string().optional(),userinfo_endpoint:o.z.string().optional(),jwks_uri:o.z.string().optional(),discovery_url:o.z.string().optional(),issuer:o.z.string().optional(),provider:o.z.string().optional(),from:o.z.string().optional(),twilio_sid:o.z.string().optional(),twilio_token:o.z.string().optional(),icon_url:o.z.string().optional()}),qa=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:bi.default({}),enabled_clients:o.z.array(o.z.string()).default([]).optional(),response_type:o.z.custom().optional(),response_mode:o.z.custom().optional(),is_domain_connection:o.z.boolean().optional(),show_as_button:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional(),is_system:o.z.boolean().optional()}),Nt=o.z.object({id:o.z.string(),created_at:o.z.string().transform(e=>e===null?"":e),updated_at:o.z.string().transform(e=>e===null?"":e)}).extend(qa.shape),yf=o.z.object({id:o.z.string().optional(),audience:o.z.string(),friendly_name:o.z.string(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sender_email:o.z.string().email(),sender_name:o.z.string(),session_lifetime:o.z.number().optional(),idle_session_lifetime:o.z.number().optional(),ephemeral_session_lifetime:o.z.number().optional(),idle_ephemeral_session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:o.z.array(o.z.string()).optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_changing_enable_sso:o.z.boolean().optional(),allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),change_pwd_flow_v1:o.z.boolean().optional(),custom_domains_provisioning:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),disable_impersonation:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),enable_sso:o.z.boolean().optional(),enforce_client_authentication_on_passwordless_start:o.z.boolean().optional(),genai_trial:o.z.boolean().optional(),improved_signup_bot_detection_in_classic:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional(),no_disclose_enterprise_connections:o.z.boolean().optional(),remove_alg_from_jwks:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),trust_azure_adfs_email_verified_connection_property:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),inherit_global_permissions_in_organizations:o.z.boolean().optional()}).optional(),sandbox_version:o.z.string().optional(),legacy_sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),device_flow:o.z.object({charset:o.z.enum(["base20","digits"]).optional(),mask:o.z.string().max(20).optional()}).optional(),default_token_quota:o.z.object({clients:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional(),organizations:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),oidc_logout:o.z.object({rp_logout_end_session_endpoint_discovery:o.z.boolean().optional()}).optional(),allow_organization_name_in_authentication_api:o.z.boolean().optional(),customize_mfa_in_postlogin_action:o.z.boolean().optional(),acr_values_supported:o.z.array(o.z.string()).optional(),mtls:o.z.object({enable_endpoint_aliases:o.z.boolean().optional()}).optional(),pushed_authorization_requests_supported:o.z.boolean().optional(),authorization_response_iss_parameter_supported:o.z.boolean().optional()}),Fa=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...yf.shape,id:o.z.string()}),O3=o.z.object({...yr.shape,tenant:Fa,connections:o.z.array(Nt)}),uy=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),ly=o.z.object({code_id:o.z.string().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:o.z.string().openapi({description:"The id of the login session that the code is connected to"}),connection_id:o.z.string().optional().openapi({description:"The connection that the code is connected to"}),code_type:uy,code_verifier:o.z.string().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:o.z.string().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:o.z.enum(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:o.z.string().optional().openapi({description:"The redirect URI associated with the code"}),nonce:o.z.string().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:o.z.string().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:o.z.string(),used_at:o.z.string().optional(),user_id:o.z.string().optional()}),P3=o.z.object({...ly.shape,created_at:o.z.string()}),bf=o.z.object({domain:o.z.string(),custom_domain_id:o.z.string().optional(),type:o.z.enum(["auth0_managed_certs","self_managed_certs"]),verification_method:o.z.enum(["txt"]).optional(),tls_policy:o.z.enum(["recommended"]).optional(),custom_client_ip_header:o.z.enum(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:o.z.record(o.z.string().max(255)).optional()}),dy=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),Hn=o.z.object({...bf.shape,custom_domain_id:o.z.string(),primary:o.z.boolean(),status:o.z.enum(["disabled","pending","pending_verification","ready"]),origin_domain_name:o.z.string().optional(),verification:o.z.object({methods:o.z.array(dy)}).optional(),tls_policy:o.z.string().optional()}),R3=Hn.extend({tenant_id:o.z.string()}),wf=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),sr=wf.extend({category:o.z.literal("BLOCK").optional()}),L3=sr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({}).optional()}),D3=sr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),B3=sr.extend({type:o.z.literal("IMAGE"),config:o.z.object({src:o.z.string().optional(),alt:o.z.string().optional(),width:o.z.number().optional(),height:o.z.number().optional()}).optional()}),U3=sr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),M3=sr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),q3=sr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),F3=sr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),H3=sr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),vf=wf.extend({category:o.z.literal("WIDGET").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),V3=vf.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),K3=vf.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),G3=vf.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),dt=wf.extend({category:o.z.literal("FIELD").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),W3=dt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),J3=dt.extend({type:o.z.literal("CARDS"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string(),description:o.z.string().optional(),image:o.z.string().optional()})).optional(),multi_select:o.z.boolean().optional()}).optional()}),X3=dt.extend({type:o.z.literal("CHOICE"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),display:o.z.enum(["radio","checkbox"]).optional()}).optional()}),Z3=dt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional()})}),Y3=dt.extend({type:o.z.literal("DATE"),config:o.z.object({format:o.z.string().optional(),min:o.z.string().optional(),max:o.z.string().optional()}).optional()}),Q3=dt.extend({type:o.z.literal("DROPDOWN"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),placeholder:o.z.string().optional(),searchable:o.z.boolean().optional()}).optional()}),e4=dt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional()}).optional()}),t4=dt.extend({type:o.z.literal("FILE"),config:o.z.object({accept:o.z.string().optional(),max_size:o.z.number().optional(),multiple:o.z.boolean().optional()}).optional()}),n4=dt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),r4=dt.extend({type:o.z.literal("NUMBER"),config:o.z.object({placeholder:o.z.string().optional(),min:o.z.number().optional(),max:o.z.number().optional(),step:o.z.number().optional()}).optional()}),i4=dt.extend({type:o.z.literal("PASSWORD"),config:o.z.object({placeholder:o.z.string().optional(),min_length:o.z.number().optional(),show_toggle:o.z.boolean().optional(),forgot_password_link:o.z.string().optional()}).optional()}),o4=dt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),s4=dt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional()}).optional()}),a4=dt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional()}).optional()}),c4=dt.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional(),max_length:o.z.number().optional()}).optional()}),u4=dt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional()}).optional()}),py=o.z.discriminatedUnion("type",[L3,D3,B3,U3,M3,q3,F3,H3]),fy=o.z.discriminatedUnion("type",[V3,K3,G3]),hy=o.z.discriminatedUnion("type",[W3,J3,X3,Z3,Y3,Q3,e4,t4,n4,r4,i4,o4,s4,a4,c4,u4]),xf=o.z.union([py,fy,hy]),l4=o.z.object({id:o.z.string(),type:o.z.literal("submit"),label:o.z.string(),className:o.z.string().optional(),disabled:o.z.boolean().optional().default(!1),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0),customizations:o.z.record(o.z.string(),o.z.any()).optional()}),Yo=o.z.object({x:o.z.number(),y:o.z.number()}),d4=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Yo,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({flow_id:o.z.string().max(30),next_node:o.z.string().optional()})}),p4=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Yo,alias:o.z.string().min(1).max(150),config:o.z.object({rules:o.z.array(o.z.object({id:o.z.string(),alias:o.z.string().min(1).max(150).optional(),condition:o.z.any(),next_node:o.z.string()})),fallback:o.z.string()})}),f4=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Yo,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(xf),next_node:o.z.string().optional()})}),gy=o.z.discriminatedUnion("type",[d4,p4,f4]),Ha=o.z.object({name:o.z.string().openapi({description:"The name of the form"}),messages:o.z.object({errors:o.z.record(o.z.string(),o.z.any()).optional(),custom:o.z.record(o.z.string(),o.z.any()).optional()}).optional(),languages:o.z.object({primary:o.z.string().optional(),default:o.z.string().optional()}).optional(),translations:o.z.record(o.z.string(),o.z.any()).optional(),nodes:o.z.array(gy).optional(),start:o.z.object({hidden_fields:o.z.array(o.z.object({key:o.z.string(),value:o.z.string()})).optional(),next_node:o.z.string().optional(),coordinates:Yo.optional()}).optional(),ending:o.z.object({redirection:o.z.object({delay:o.z.number().optional(),target:o.z.string().optional()}).optional(),after_submit:o.z.object({flow_id:o.z.string().optional()}).optional(),coordinates:Yo.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),gi=o.z.object({...Vr.shape,...Ha.shape,id:o.z.string()}),my=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),_y=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),h4=o.z.object({action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(xf),messages:o.z.array(my).optional(),links:o.z.array(_y).optional()});function g4(e){return e.category==="BLOCK"}function m4(e){return e.category==="WIDGET"}function _4(e){return e.category==="FIELD"}const yy=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),by=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Gc={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},y4=o.z.object({...Gc,trigger_id:yy,url:o.z.string()}),b4=o.z.object({...Gc,trigger_id:by,form_id:o.z.string()}),ba=o.z.union([y4,b4]),w4=o.z.object({...Gc,trigger_id:yy,...Vr.shape,hook_id:o.z.string(),url:o.z.string()}),v4=o.z.object({...Gc,trigger_id:by,...Vr.shape,hook_id:o.z.string(),form_id:o.z.string()}),mi=o.z.union([w4,v4]),wy=o.z.object({name:o.z.string().optional()}),vy=o.z.object({email:o.z.string().optional()}),$f=o.z.object({organization_id:o.z.string().max(50),inviter:wy,invitee:vy,invitation_url:o.z.string().url(),client_id:o.z.string(),connection_id:o.z.string().optional(),app_metadata:o.z.record(o.z.any()).default({}).optional(),user_metadata:o.z.record(o.z.any()).default({}).optional(),ttl_sec:o.z.number().int().max(2592e3).default(604800).optional(),roles:o.z.array(o.z.string()).default([]).optional(),send_invitation_email:o.z.boolean().default(!0).optional()}),Uo=o.z.object({id:o.z.string(),organization_id:o.z.string().max(50),created_at:o.z.string().datetime(),expires_at:o.z.string().datetime(),ticket_id:o.z.string().optional()}).extend($f.shape),kf=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),e:o.z.string(),kid:o.z.string(),kty:o.z.enum(["RSA","EC","oct"]),n:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional(),use:o.z.enum(["sig","enc"]).optional()}),xy=o.z.object({keys:o.z.array(kf)}),kd=o.z.object({issuer:o.z.string(),authorization_endpoint:o.z.string(),token_endpoint:o.z.string(),device_authorization_endpoint:o.z.string(),userinfo_endpoint:o.z.string(),mfa_challenge_endpoint:o.z.string(),jwks_uri:o.z.string(),registration_endpoint:o.z.string(),revocation_endpoint:o.z.string(),scopes_supported:o.z.array(o.z.string()),response_types_supported:o.z.array(o.z.string()),code_challenge_methods_supported:o.z.array(o.z.string()),response_modes_supported:o.z.array(o.z.string()),subject_types_supported:o.z.array(o.z.string()),id_token_signing_alg_values_supported:o.z.array(o.z.string()),token_endpoint_auth_methods_supported:o.z.array(o.z.string()),claims_supported:o.z.array(o.z.string()),request_uri_parameter_supported:o.z.boolean(),request_parameter_supported:o.z.boolean(),token_endpoint_auth_signing_alg_values_supported:o.z.array(o.z.string())}),$y=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Zo,expires_at:o.z.string(),deleted_at:o.z.string().optional(),ip:o.z.string().optional(),useragent:o.z.string().optional(),session_id:o.z.string().optional(),authorization_url:o.z.string().optional(),login_completed:o.z.boolean().optional().default(!1)}).openapi({description:"This represents a login sesion"}),x4=o.z.object({...$y.shape,id:o.z.string().openapi({description:"This is is used as the state in the universal login"}),created_at:o.z.string(),updated_at:o.z.string()}),he={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",MFA_REQUIRED:"mfar",MANAGEMENT_API_READ_OPERATION:"mgmt_api_read",FAILED_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_failed",SUCCESSFUL_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_succeeded",FAILED_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_failed",SUCCESSFUL_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_succeeded",ORGANIZATION_MEMBER_ADDED:"organization_member_added",PASSKEY_CHALLENGE_FAILED:"passkey_challenge_failed",PASSKEY_CHALLENGE_STARTED:"passkey_challenge_started",PRE_LOGIN_ASSESSMENT:"pla",BREACHED_PASSWORD:"pwd_leak",BREACHED_PASSWORD_ON_RESET:"reset_pwd_leak",SUCCESS_RESOURCE_CLEANUP:"resource_cleanup",RICH_CONSENTS_ACCESS_ERROR:"rich_consents_access_error",SUCCESS_LOGIN:"s",SUCCESS_API_OPERATION:"sapi",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},$4=o.z.string().refine(e=>Object.values(he).includes(e),{message:"Invalid log type"}),ky=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),Sy=o.z.object({country_code:o.z.string().length(2),city_name:o.z.string(),latitude:o.z.string(),longitude:o.z.string(),time_zone:o.z.string(),continent_code:o.z.string()}),zy=o.z.object({type:$4,date:o.z.string(),description:o.z.string().optional(),ip:o.z.string().optional(),user_agent:o.z.string().optional(),details:o.z.any().optional(),isMobile:o.z.boolean(),user_id:o.z.string().optional(),user_name:o.z.string().optional(),connection:o.z.string().optional(),connection_id:o.z.string().optional(),client_id:o.z.string().optional(),client_name:o.z.string().optional(),audience:o.z.string().optional(),scope:o.z.string().optional(),strategy:o.z.string().optional(),strategy_type:o.z.string().optional(),hostname:o.z.string().optional(),auth0_client:ky.optional(),log_id:o.z.string().optional(),location_info:Sy.optional()}),Va=o.z.object({...zy.shape,log_id:o.z.string()}),Ay=o.z.object({id:o.z.string().optional(),user_id:o.z.string(),password:o.z.string(),algorithm:o.z.enum(["bcrypt","argon2id"]).default("argon2id"),is_current:o.z.boolean().default(!0)}),k4=Ay.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),Ey=o.z.object({initial_user_agent:o.z.string().describe("First user agent of the device from which this user logged in"),initial_ip:o.z.string().describe("First IP address associated with this session"),initial_asn:o.z.string().describe("First autonomous system number associated with this session"),last_user_agent:o.z.string().describe("Last user agent of the device from which this user logged in"),last_ip:o.z.string().describe("Last IP address from which this user logged in"),last_asn:o.z.string().describe("Last autonomous system number from which this user logged in")}),Cy=o.z.object({id:o.z.string(),revoked_at:o.z.string().optional(),used_at:o.z.string().optional(),user_id:o.z.string().describe("The user ID associated with the session"),expires_at:o.z.string().optional(),login_session_id:o.z.string(),idle_expires_at:o.z.string().optional(),device:Ey.describe("Metadata related to the device used in the session"),clients:o.z.array(o.z.string()).describe("List of client details for the session")}),Wc=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...Cy.shape}),Sd=o.z.object({kid:o.z.string().openapi({description:"The key id of the signing key"}),cert:o.z.string().openapi({description:"The public certificate of the signing key"}),fingerprint:o.z.string().openapi({description:"The cert fingerprint"}),thumbprint:o.z.string().openapi({description:"The cert thumbprint"}),pkcs7:o.z.string().optional().openapi({description:"The private key in pkcs7 format"}),current:o.z.boolean().optional().openapi({description:"True if the key is the current key"}),next:o.z.boolean().optional().openapi({description:"True if the key is the next key"}),previous:o.z.boolean().optional().openapi({description:"True if the key is the previous key"}),current_since:o.z.string().optional().openapi({description:"The date and time when the key became the current key"}),current_until:o.z.string().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:o.z.boolean().optional().openapi({description:"True if the key is revoked"}),revoked_at:o.z.string().optional().openapi({description:"The date and time when the key was revoked"}),connection:o.z.string().optional().openapi({description:"The connection identifier associated with the key"}),type:o.z.enum(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});var Wt=(e=>(e.RefreshToken="refresh_token",e.AuthorizationCode="authorization_code",e.ClientCredential="client_credentials",e.Passwordless="passwordless",e.Password="password",e.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",e))(Wt||{});const Sf=o.z.object({access_token:o.z.string(),id_token:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),refresh_token:o.z.string().optional(),token_type:o.z.string(),expires_in:o.z.number()});o.z.object({code:o.z.string(),state:o.z.string().optional()});const Iy=o.z.object({button_border_radius:o.z.number(),button_border_weight:o.z.number(),buttons_style:o.z.enum(["pill","rounded","sharp"]),input_border_radius:o.z.number(),input_border_weight:o.z.number(),inputs_style:o.z.enum(["pill","rounded","sharp"]),show_widget_shadow:o.z.boolean(),widget_border_weight:o.z.number(),widget_corner_radius:o.z.number()}),Ny=o.z.object({base_focus_color:o.z.string(),base_hover_color:o.z.string(),body_text:o.z.string(),captcha_widget_theme:o.z.enum(["auto","dark","light"]),error:o.z.string(),header:o.z.string(),icons:o.z.string(),input_background:o.z.string(),input_border:o.z.string(),input_filled_text:o.z.string(),input_labels_placeholders:o.z.string(),links_focused_components:o.z.string(),primary_button:o.z.string(),primary_button_label:o.z.string(),secondary_button_border:o.z.string(),secondary_button_label:o.z.string(),success:o.z.string(),widget_background:o.z.string(),widget_border:o.z.string()}),gr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),jy=o.z.object({body_text:gr,buttons_text:gr,font_url:o.z.string(),input_labels:gr,links:gr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:gr,title:gr}),Ty=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),Oy=o.z.object({header_text_alignment:o.z.enum(["center","left","right"]),logo_height:o.z.number(),logo_position:o.z.enum(["center","left","none","right"]),logo_url:o.z.string(),social_buttons_layout:o.z.enum(["bottom","top"])}),Py=o.z.object({borders:Iy,colors:Ny,displayName:o.z.string(),fonts:jy,page_background:Ty,widget:Oy}),wa=Py.extend({themeId:o.z.string()}),va=o.z.object({universal_login_experience:o.z.enum(["new","classic"]).default("new"),identifier_first:o.z.boolean().default(!0),password_first:o.z.boolean().default(!1),webauthn_platform_first_factor:o.z.boolean()}),xa=o.z.object({name:o.z.string(),enabled:o.z.boolean().optional().default(!0),default_from_address:o.z.string().optional(),credentials:o.z.union([o.z.object({accessKeyId:o.z.string(),secretAccessKey:o.z.string(),region:o.z.string()}),o.z.object({smtp_host:o.z.array(o.z.string()),smtp_port:o.z.number(),smtp_user:o.z.string(),smtp_pass:o.z.string()}),o.z.object({api_key:o.z.string(),domain:o.z.string().optional()}),o.z.object({connectionString:o.z.string()}),o.z.object({tenantId:o.z.string(),clientId:o.z.string(),clientSecret:o.z.string()})]),settings:o.z.object({}).optional()}),zf=o.z.object({id:o.z.string(),session_id:o.z.string(),user_id:o.z.string(),client_id:o.z.string(),expires_at:o.z.string().optional(),idle_expires_at:o.z.string().optional(),last_exchanged_at:o.z.string().optional(),device:Ey,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),S4=o.z.object({created_at:o.z.string(),...zf.shape}),z4=o.z.object({to:o.z.string(),message:o.z.string()}),A4=o.z.object({name:o.z.string(),options:o.z.object({})}),Ry=o.z.object({value:o.z.string(),description:o.z.string().optional()}),Ly=o.z.object({token_dialect:o.z.enum(["access_token","access_token_authz"]).optional(),enforce_policies:o.z.boolean().optional(),allow_skipping_userinfo:o.z.boolean().optional(),skip_userinfo:o.z.boolean().optional(),persist_client_authorization:o.z.boolean().optional(),enable_introspection_endpoint:o.z.boolean().optional(),mtls:o.z.object({bound_access_tokens:o.z.boolean().optional()}).optional()}),Ka=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(Ry).optional(),signing_alg:o.z.string().optional(),signing_secret:o.z.string().optional(),token_lifetime:o.z.number().optional(),token_lifetime_for_web:o.z.number().optional(),skip_consent_for_verifiable_first_party_clients:o.z.boolean().optional(),allow_offline_access:o.z.boolean().optional(),verificationKey:o.z.string().optional(),options:Ly.optional(),is_system:o.z.boolean().optional()}),wr=o.z.object({...Ka.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),E4=o.z.array(wr),Dy=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),By=o.z.object({...Dy.shape,created_at:o.z.string()}),Uy=o.z.array(By),My=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string(),organization_id:o.z.string().optional()}),qy=o.z.object({...My.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),C4=o.z.array(qy),Fy=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),resource_server_name:o.z.string(),permission_name:o.z.string(),description:o.z.string().nullable().optional(),created_at:o.z.string().optional(),organization_id:o.z.string().optional()}),Hy=o.z.array(Fy),Vy=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),Ky=o.z.object({...Vy.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),I4=o.z.array(Ky),Ga=o.z.object({id:o.z.string().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:o.z.string().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:o.z.string().max(255).optional().openapi({description:"The description of the role"}),is_system:o.z.boolean().optional()}),vr=Ga.extend({id:o.z.string().openapi({description:"The unique identifier of the role"}),created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Wa=o.z.array(vr),Gy=o.z.object({logo_url:o.z.string().optional().openapi({description:"URL of the organization's logo"}),colors:o.z.object({primary:o.z.string().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:o.z.string().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),Wy=o.z.object({connection_id:o.z.string().openapi({description:"ID of the connection"}),assign_membership_on_login:o.z.boolean().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:o.z.boolean().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:o.z.boolean().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),Jy=o.z.object({client_credentials:o.z.object({enforce:o.z.boolean().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),Ja=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Gy,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Wy).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Jy}),Vn=o.z.object({...Ja.shape,...Vr.shape,id:o.z.string(),name:o.z.string().min(1).openapi({description:"The name of the organization"})}),Xy=o.z.object({user_id:o.z.string().openapi({description:"ID of the user"}),organization_id:o.z.string().openapi({description:"ID of the organization"})}),N4=o.z.object({...Xy.shape,...Vr.shape,id:o.z.string()}),j4=o.z.object({idle_session_lifetime:o.z.number().optional(),session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:o.z.boolean().optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional()}).optional(),friendly_name:o.z.string().optional(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional()}),Zy=o.z.object({date:o.z.string().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:o.z.number().openapi({description:"Number of logins on this date",example:150}),signups:o.z.number().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:o.z.number().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:o.z.string().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:o.z.string().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})}),T4=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234});function O4(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function P4(e){const{primary:t,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=e,i={get(s,a){if(typeof a=="symbol")return s[a];const c=s[a];return typeof c!="function"?c:r.includes(a)?async(...u)=>{const l=await c.apply(s,u),d=[];for(const f of n){const p=f.adapter[a];if(typeof p!="function")continue;const h=(async()=>{try{await p.apply(f.adapter,u)}catch(g){try{f.onError?f.onError(g,a,u):console.error(`Passthrough adapter: secondary write failed for ${a}:`,g)}catch(y){console.error(`Passthrough adapter: onError handler threw for ${a}:`,y)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),l}:c.bind(s)}};return new Proxy(t,i)}function R4(e){return e}const mh={themeId:"default",borders:{button_border_radius:8,button_border_weight:1,buttons_style:"pill",input_border_radius:8,input_border_weight:1,inputs_style:"pill",show_widget_shadow:!0,widget_border_weight:1,widget_corner_radius:16},colors:{base_focus_color:"#7D68F4",base_hover_color:"#A091F2",body_text:"#000000",captcha_widget_theme:"auto",error:"#FC5A5A",header:"#000000",icons:"#666666",input_background:"#FFFFFF",input_border:"#BFBCD7",input_filled_text:"#000000",input_labels_placeholders:"#88869F",links_focused_components:"#7D68F4",primary_button:"#7D68F4",primary_button_label:"#FFFFFF",secondary_button_border:"#BFBCD7",secondary_button_label:"#000000",success:"#36BF76",widget_background:"#FFFFFF",widget_border:"#BFBCD7"},displayName:"Default Theme",fonts:{body_text:{bold:!1,size:16},buttons_text:{bold:!1,size:16},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:14},links:{bold:!1,size:16},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:18},title:{bold:!0,size:24}},page_background:{background_color:"#F8F9FB",background_image_url:"https://assets.sesamy.com/images/login-bg.jpg",page_layout:"center"},widget:{header_text_alignment:"center",logo_height:36,logo_position:"center",logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",social_buttons_layout:"bottom"}};function zd(e,t){const n=structuredClone(e);function r(i,s){for(const a in s)s[a]!==void 0&&typeof s[a]=="object"&&!Array.isArray(s[a])&&typeof i[a]=="object"&&i[a]!==null?r(i[a],s[a]):i[a]=s[a];return i}return r(n,t)}const L4=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/default",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:themes","auth:read"]}],responses:{200:{content:{"application/json":{schema:wa}},description:"Default theme settings"}}}),async e=>{const t=await e.env.data.themes.get(e.var.tenant_id,"default");return t?e.json(t):e.json(mh)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:wa.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:themes","auth:write"]}],responses:{200:{content:{"application/json":{schema:wa}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default");if(n){const r=zd(n,t);await e.env.data.themes.update(e.var.tenant_id,"default",r);const i=await e.env.data.themes.get(e.var.tenant_id,"default");return e.json(i)}else{const r=zd(mh,t),i=await e.env.data.themes.create(e.var.tenant_id,r);return e.json(i)}}),D4={colors:{primary:"#7D68F4",page_background:{type:"solid",start:"#F8F9FB",end:"#F8F9FB",angle_deg:0}},logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",favicon_url:"https://assets.sesamy.com/images/favicon.ico",font:{url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2"}},B4=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:$d}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json(D4)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object($d.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.branding.set(e.var.tenant_id,t),e.text("OK")}).route("/themes",L4),Yy={},U4=Object.freeze(Object.defineProperty({__proto__:null,default:Yy},Symbol.toStringTag,{value:"Module"}));var Ad=null;function M4(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return Yy.randomBytes(e)}catch{}if(!Ad)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return Ad(e)}function q4(e){Ad=e}function Af(e,t){if(e=e||Ef,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(Xa(M4(Qo),Qo)),n.join("")}function Qy(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=Ef;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){Jt(function(){try{i(null,Af(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 eb(e,t){if(typeof t>"u"&&(t=Ef),typeof t=="number"&&(t=Af(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return Ed(e,t)}function tb(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?Qy(t,function(a,c){Ed(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?Ed(e,t,s,r):Jt(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,u){if(c){a(c);return}s(u)})})}function nb(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 F4(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:nb(eb(e,t.substring(0,t.length-31)),t)}function H4(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){Jt(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){Jt(s.bind(this,null,!1));return}tb(e,t.substring(0,29),function(a,c){a?s(a):s(null,nb(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,u){if(c){a(c);return}s(u)})})}function V4(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function K4(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 G4(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return rb(e)>72}var Jt=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function rb(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 W4(e){for(var t=0,n,r,i=new Array(rb(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 ni="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),Mn=[-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 Xa(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(ni[i>>2&63]),i=(i&3)<<4,n>=t){r.push(ni[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(ni[i&63]),i=(s&15)<<2,n>=t){r.push(ni[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(ni[i&63]),r.push(ni[s&63])}return r.join("")}function ib(e,t){var n=0,r=e.length,i=0,s=[],a,c,u,l,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<Mn.length?Mn[f]:-1,f=e.charCodeAt(n++),c=f<Mn.length?Mn[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++),u=f<Mn.length?Mn[f]:-1,u==-1)||(d=(c&15)<<4>>>0,d|=(u&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),l=f<Mn.length?Mn[f]:-1,d=(u&3)<<6>>>0,d|=l,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var Qo=16,Ef=10,J4=16,X4=100,_h=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],yh=[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],ob=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function es(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[J4+1],e[t+1]=s,e}function ci(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 bh(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,u=0;u<s;u++)c=ci(e,r),r=c.offp,t[u]=t[u]^c.key;for(u=0;u<s;u+=2)i=es(i,0,t,n),t[u]=i[0],t[u+1]=i[1];for(u=0;u<a;u+=2)i=es(i,0,t,n),n[u]=i[0],n[u+1]=i[1]}function Z4(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,u,l=0;l<a;l++)u=ci(t,i),i=u.offp,n[l]=n[l]^u.key;for(i=0,l=0;l<a;l+=2)u=ci(e,i),i=u.offp,s[0]^=u.key,u=ci(e,i),i=u.offp,s[1]^=u.key,s=es(s,0,n,r),n[l]=s[0],n[l+1]=s[1];for(l=0;l<c;l+=2)u=ci(e,i),i=u.offp,s[0]^=u.key,u=ci(e,i),i=u.offp,s[1]^=u.key,s=es(s,0,n,r),r[l]=s[0],r[l+1]=s[1]}function wh(e,t,n,r,i){var s=ob.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){Jt(r.bind(this,c));return}else throw c;if(t.length!==Qo)if(c=Error("Illegal salt length: "+t.length+" != "+Qo),r){Jt(r.bind(this,c));return}else throw c;n=1<<n>>>0;var u,l,d=0,f;typeof Int32Array=="function"?(u=new Int32Array(_h),l=new Int32Array(yh)):(u=_h.slice(),l=yh.slice()),Z4(t,e,u,l);function p(){if(i&&i(d/n),d<n)for(var g=Date.now();d<n&&(d=d+1,bh(e,u,l),bh(t,u,l),!(Date.now()-g>X4)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)es(s,f<<1,u,l);var y=[];for(d=0;d<a;d++)y.push((s[d]>>24&255)>>>0),y.push((s[d]>>16&255)>>>0),y.push((s[d]>>8&255)>>>0),y.push((s[d]&255)>>>0);if(r){r(null,y);return}else return y}r&&Jt(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function Ed(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){Jt(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){Jt(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){Jt(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){Jt(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,u=parseInt(t.substring(a+1,a+2),10),l=c+u,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=W4(e),p=ib(d,Qo);function h(g){var y=[];return y.push("$2"),s>="a"&&y.push(s),y.push("$"),l<10&&y.push("0"),y.push(l.toString()),y.push("$"),y.push(Xa(p,p.length)),y.push(Xa(g,ob.length*4-1)),y.join("")}if(typeof n>"u")return h(wh(f,p,l));wh(f,p,l,function(g,y){g?n(g,null):n(null,h(y))},r)}function Y4(e,t){return Xa(e,t)}function Q4(e,t){return ib(e,t)}const Yn={setRandomFallback:q4,genSaltSync:Af,genSalt:Qy,hashSync:eb,hash:tb,compareSync:F4,compare:H4,getRounds:V4,getSalt:K4,truncates:G4,encodeBase64:Y4,decodeBase64:Q4},e6="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let t6=e=>crypto.getRandomValues(new Uint8Array(e)),n6=(e,t,n)=>{let r=(2<<Math.log2(e.length-1))-1,i=-~(1.6*r*t/e.length);return(s=t)=>{let a="";for(;;){let c=n(i),u=i|0;for(;u--;)if(a+=e[c[u]&r]||"",a.length>=s)return a}}},sb=(e,t=21)=>n6(e,t|0,t6),Ne=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=e6[n[e]&63];return t};const r6=24;function $s(){return sb("0123456789abcdef",r6)()}function na(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}function i6(e){return async(t,n)=>{if(!n.email||!n.email_verified)return e.users.create(t,n);const r=await Ss({userAdapter:e.users,tenant_id:t,email:n.email});if(!r)return e.users.create(t,n);await e.users.create(t,{...n,linked_to:r.user_id});const i=await e.users.get(t,r.user_id);if(!i)throw new Error("Failed to fetch primary user after linking");return i}}var o6={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},ab=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(o6))if(s6(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},s6=e=>navigator.userAgent.startsWith(e);function cb(e,t){if(ab()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function a6(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function _e(e,t,n){const r={};if(e.req.raw?.headers){const s=a6(e.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(e.env.data.geo)try{s=await e.env.data.geo.getGeoInfo(r)||void 0}catch(c){console.warn("Failed to get geo information:",c)}const a={type:n.type,description:n.description||"",ip:e.var.ip,user_agent:e.var.useragent||"",auth0_client:e.var.auth0_client,date:new Date().toISOString(),details:{request:{method:e.req.method,path:e.req.path,qs:e.req.queries(),body:n.body||e.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:e.var.client_id,client_name:"",user_id:n.userId||e.var.user_id||"",hostname:e.req.header("host")||"",user_name:e.var.username||"",connection_id:"",connection:n.connection||e.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await e.env.data.logs.create(t,a)};n.waitForCompletion?await i():cb(e,i())}class Za{constructor(t,n){this.value=t,this.unit=n}value;unit;milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(t){return new Za(Math.round(this.milliseconds()*t),"ms")}}class c6{hash;constructor(t){this.hash=t}async verify(t,n,r){const i=await crypto.subtle.importKey("spki",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(t,n){const r=await crypto.subtle.importKey("pkcs8",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(t){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:t??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function ub(e){return await crypto.subtle.digest("SHA-256",e)}const vh="0123456789abcdef";function Cd(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=vh[i];const s=t[r]&15;n+=vh[s]}return n}class lb{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const c=(8-r.length%8)%8;for(let u=0;u<c;u++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const u=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);u.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const l=(u[0]<<3)+(u[1]>>2);if(s.push(l),c<6){const d=((u[1]&3)<<6)+(u[2]<<1)+(u[3]>>4);s.push(d)}if(c<4){const d=((u[3]&255)<<4)+(u[4]>>1);s.push(d)}if(c<3){const d=((u[4]&1)<<7)+(u[5]<<2)+(u[6]>>3);s.push(d)}if(c<1){const d=((u[6]&7)<<5)+u[7];s.push(d)}}return Uint8Array.from(s)}}new lb("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new lb("0123456789ABCDEFGHIJKLMNOPQRSTUV");class db{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const c=(4-r.length%4)%4;for(let u=0;u<c;u++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,u=0;for(let l=0;l<4;l++){const d=t[a*4+l];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);u+=f<<6*(3-l)}s.push(u>>16&255),c<2&&s.push(u>>8&255),c<1&&s.push(u&255)}return Uint8Array.from(s)}}const u6=new db("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),kr=new db("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function xh(e,t,n,r){const i={alg:e,typ:"JWT",...r?.headers},s={...n};r?.audiences!==void 0&&(s.aud=r.audiences),r?.subject!==void 0&&(s.sub=r.subject),r?.issuer!==void 0&&(s.iss=r.issuer),r?.jwtId!==void 0&&(s.jti=r.jwtId),r?.expiresIn!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),r?.notBefore!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const a=new TextEncoder,c=kr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),u=kr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),l=a.encode([c,u].join(".")),d=await d6(e).sign(t,l),f=kr.encode(new Uint8Array(d),{includePadding:!1});return[c,u,f].join(".")}function l6(e){const t=e.split(".");return t.length!==3?null:t}function ks(e){const t=l6(e);if(!t)return null;const n=new TextDecoder,r=kr.decode(t[0],{strict:!1}),i=kr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!p6(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const a=JSON.parse(n.decode(i));if(typeof a!="object"||a===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in a){if(typeof a.exp!="number")return null;c.expiresAt=new Date(a.exp*1e3)}if("iss"in a){if(typeof a.iss!="string")return null;c.issuer=a.iss}if("sub"in a){if(typeof a.sub!="string")return null;c.subject=a.sub}if("aud"in a)if(Array.isArray(a.aud)){for(const u of a.aud)if(typeof u!="string")return null;c.audiences=a.aud}else{if(typeof a.aud!="string")return null;c.audiences=[a.aud]}if("nbf"in a){if(typeof a.nbf!="number")return null;c.notBefore=new Date(a.nbf*1e3)}if("iat"in a){if(typeof a.iat!="number")return null;c.issuedAt=new Date(a.iat*1e3)}if("jti"in a){if(typeof a.jti!="string")return null;c.jwtId=a.jti}return{value:e,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:t,...c}}function d6(e){return new c6(f6[e])}function p6(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const f6={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function h6(){const e=new Uint8Array(32);return crypto.getRandomValues(e),kr.encode(e,{includePadding:!1})}function g6(e){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(e);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{e=e.replace(/./g,"\0")}}async function m6(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await ub(n);return kr.encode(new Uint8Array(r),{includePadding:!1})}const ra=300,Jc=720*60*60,Er=1440*60,_6="auth-token",Mo=1800*1e3,Id=10080*60*1e3,y6=300,b6=300,w6=1800*1e3,v6=1800*1e3,x6=1440*60*1e3;function pb(e,t,n){const r=[];return r.push([encodeURIComponent(e),encodeURIComponent(t)]),n?.domain!==void 0&&r.push(["Domain",n.domain]),n?.expires!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n?.httpOnly&&r.push(["HttpOnly"]),n?.maxAge!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),n?.path!==void 0&&r.push(["Path",n.path]),n?.sameSite==="lax"&&r.push(["SameSite","Lax"]),n?.sameSite==="none"&&r.push(["SameSite","None"]),n?.sameSite==="strict"&&r.push(["SameSite","Strict"]),n?.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function $6(e){const t=new Map,n=e.split("; ");for(const r of n){const i=r.split("="),s=i[0],a=i[1]??"";s&&t.set(decodeURIComponent(s),decodeURIComponent(a))}return t}function Cf(e){return`${e}-${_6}`}function fb(e){if(!e)return;const[t]=e.split(":");if(!t||t==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return;const n=t.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${t}`}function Ai(e,t){return t?$6(t).get(Cf(e)):void 0}function hb(e,t){return pb(Cf(e),"",{path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?fb(t):void 0})}function Ya(e,t,n){return pb(Cf(e),t,{path:"/",httpOnly:!0,secure:!0,maxAge:Jc,sameSite:"none",domain:n?fb(n):void 0})}class X extends C{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}var k6=Object.defineProperty,S6=(e,t,n)=>t in e?k6(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wi=(e,t,n)=>S6(e,typeof t!="symbol"?t+"":t,n);const st=o.z.object({"#text":o.z.string()}),z6=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":z6,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(e=>e.toLowerCase()==="true").optional(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string().datetime(),"@_Destination":o.z.string().url(),"@_AssertionConsumerServiceURL":o.z.string().url().optional(),"@_ProtocolBinding":o.z.string().optional(),"@_Version":o.z.string()})});o.z.array(o.z.object({":@":o.z.object({"@_xmlns":o.z.string(),"@_entityID":o.z.string()}),EntityDescriptor:o.z.array(o.z.object({":@":o.z.object({"@_protocolSupportEnumeration":o.z.string()}),IDPSSODescriptor:o.z.array(o.z.union([o.z.object({KeyDescriptor:o.z.array(o.z.object({KeyInfo:o.z.array(o.z.object({X509Data:o.z.array(o.z.object({X509Certificate:o.z.array(st)}))})),":@":o.z.object({"@_xmlns":o.z.string()})})),":@":o.z.object({"@_use":o.z.string()})}),o.z.object({SingleLogoutService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({NameIDFormat:o.z.array(st)}),o.z.object({SingleSignOnService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({Attribute:o.z.array(o.z.object({})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string(),"@_xmlns":o.z.string()})})]))}))}));const A6=o.z.object({"saml:Attribute":o.z.array(o.z.object({"saml:AttributeValue":o.z.array(o.z.object({"#text":o.z.string()})),":@":o.z.object({"@_xmlns:xs":o.z.string().optional(),"@_xmlns:xsi":o.z.string(),"@_xsi:type":o.z.string()}).optional()})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string().optional()})}),E6=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),$h=o.z.object({"ds:Signature":o.z.array(o.z.union([o.z.object({"ds:SignedInfo":o.z.array(o.z.union([o.z.object({"ds:CanonicalizationMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:SignatureMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:Reference":o.z.array(o.z.union([o.z.object({"ds:Transforms":o.z.array(E6)}),o.z.object({"ds:DigestMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:DigestValue":o.z.array(st)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(st)}),o.z.object({"ds:KeyInfo":o.z.array(o.z.union([o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(st)}),o.z.object({"ds:Exponent":o.z.array(st)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(st)}))}),o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(st)}),o.z.object({"ds:Exponent":o.z.array(st)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(st)}))})]))})])),":@":o.z.object({"@_xmlns:ds":o.z.string().optional()}).optional()});o.z.array(o.z.object({"samlp:Response":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(st)}),$h,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(st),":@":o.z.object({"@_Value":o.z.string()})}))}),o.z.object({"saml:Assertion":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(st)}),$h,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(st),":@":o.z.object({"@_Format":o.z.string()})}),o.z.object({"saml:SubjectConfirmation":o.z.array(o.z.object({"saml:SubjectConfirmationData":o.z.array(o.z.any()),":@":o.z.object({"@_InResponseTo":o.z.string(),"@_NotOnOrAfter":o.z.string(),"@_Recipient":o.z.string()})})),":@":o.z.object({"@_Method":o.z.string()})})]))}),o.z.object({"saml:Conditions":o.z.array(o.z.object({"saml:AudienceRestriction":o.z.array(o.z.object({"saml:Audience":o.z.array(st)}))})),":@":o.z.object({"@_NotBefore":o.z.string(),"@_NotOnOrAfter":o.z.string()})}),o.z.object({"saml:AuthnStatement":o.z.array(o.z.object({"saml:AuthnContext":o.z.array(o.z.object({"saml:AuthnContextClassRef":o.z.array(st)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(A6)})])),":@":o.z.object({"@_xmlns":o.z.string(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})})])),":@":o.z.object({"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string(),"@_Destination":o.z.string(),"@_ID":o.z.string(),"@_InResponseTo":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})}));var C6={};(function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+t+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,u){const l=[];let d=u.exec(c);for(;d;){const f=[];f.startIndex=u.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);l.push(f),d=u.exec(c)}return l},a=function(c){const u=i.exec(c);return!(u===null||typeof u>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,u,l){if(u){const d=Object.keys(u),f=d.length;for(let p=0;p<f;p++)l==="strict"?c[d[p]]=[u[d[p]]]:c[d[p]]=u[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(C6);function I6(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(const n of e)if(typeof n=="string"&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var N6=I6;const j6=`
2
2
  `;function T6(e,t){let n="";return t.format&&t.indentBy.length>0&&(n=j6),gb(e,t,"",n)}function gb(e,t,n,r){let i="",s=!1;for(let a=0;a<e.length;a++){const c=e[a],u=O6(c);if(u===void 0)continue;let l="";if(n.length===0?l=u:l=`${n}.${u}`,u===t.textNodeName){let g=c[u];P6(l,t)||(g=t.tagValueProcessor(u,g),g=mb(g,t)),s&&(i+=r),i+=g,s=!1;continue}else if(u===t.cdataPropName){s&&(i+=r),i+=`<![CDATA[${c[u][0][t.textNodeName]}]]>`,s=!1;continue}else if(u===t.commentPropName){i+=r+`<!--${c[u][0][t.textNodeName]}-->`,s=!0;continue}else if(u[0]==="?"){const g=kh(c[":@"],t),y=u==="?xml"?"":r;let w=c[u][0][t.textNodeName];w=w.length!==0?" "+w:"",i+=y+`<${u}${w}${g}?>`,s=!0;continue}let d=r;d!==""&&(d+=t.indentBy);const f=kh(c[":@"],t),p=r+`<${u}${f}`,h=gb(c[u],t,l,d);t.unpairedTags.indexOf(u)!==-1?t.suppressUnpairedNode?i+=p+">":i+=p+"/>":(!h||h.length===0)&&t.suppressEmptyNode?i+=p+"/>":h&&h.endsWith(">")?i+=p+`>${h}${r}</${u}>`:(i+=p+">",h&&r!==""&&(h.includes("/>")||h.includes("</"))?i+=r+t.indentBy+h+r:i+=h,i+=`</${u}>`),s=!0}return i}function O6(e){const t=Object.keys(e);for(let n=0;n<t.length;n++){const r=t[n];if(e.hasOwnProperty(r)&&r!==":@")return r}}function kh(e,t){let n="";if(e&&!t.ignoreAttributes)for(let r in e){if(!e.hasOwnProperty(r))continue;let i=t.attributeValueProcessor(r,e[r]);i=mb(i,t),i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function P6(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let n=e.substr(e.lastIndexOf(".")+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]==="*."+n)return!0;return!1}function mb(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){const r=t.entities[n];e=e.replace(r.regex,r.val)}return e}var R6=T6;const L6=R6,D6=N6,B6={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ar(e){this.options=Object.assign({},B6,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=D6(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=q6),this.processTextOrObjNode=U6,this.options.format?(this.indentate=M6,this.tagEndChar=`>
3
3
  `,this.newLine=`
4
4
  `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}ar.prototype.build=function(e){return this.options.preserveOrder?L6(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)};ar.prototype.j2x=function(e,t,n){let r="",i="";const s=n.join(".");for(let a in e)if(Object.prototype.hasOwnProperty.call(e,a))if(typeof e[a]>"u")this.isAttribute(a)&&(i+="");else if(e[a]===null)this.isAttribute(a)||a===this.options.cdataPropName?i+="":a[0]==="?"?i+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(e[a]instanceof Date)i+=this.buildTextValNode(e[a],a,"",t);else if(typeof e[a]!="object"){const c=this.isAttribute(a);if(c&&!this.ignoreAttributesFn(c,s))r+=this.buildAttrPairStr(c,""+e[a]);else if(!c)if(a===this.options.textNodeName){let u=this.options.tagValueProcessor(a,""+e[a]);i+=this.replaceEntitiesValue(u)}else i+=this.buildTextValNode(e[a],a,"",t)}else if(Array.isArray(e[a])){const c=e[a].length;let u="",l="";for(let d=0;d<c;d++){const f=e[a][d];if(!(typeof f>"u"))if(f===null)a[0]==="?"?i+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(typeof f=="object")if(this.options.oneListGroup){const p=this.j2x(f,t+1,n.concat(a));u+=p.val,this.options.attributesGroupName&&f.hasOwnProperty(this.options.attributesGroupName)&&(l+=p.attrStr)}else u+=this.processTextOrObjNode(f,a,t,n);else if(this.options.oneListGroup){let p=this.options.tagValueProcessor(a,f);p=this.replaceEntitiesValue(p),u+=p}else u+=this.buildTextValNode(f,a,"",t)}this.options.oneListGroup&&(u=this.buildObjectNode(u,a,l,t)),i+=u}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const c=Object.keys(e[a]),u=c.length;for(let l=0;l<u;l++)r+=this.buildAttrPairStr(c[l],""+e[a][c[l]])}else i+=this.processTextOrObjNode(e[a],a,t,n);return{attrStr:r,val:i}};ar.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+e:" "+e+'="'+t+'"'};function U6(e,t,n,r){const i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}ar.prototype.buildObjectNode=function(e,t,n,r){if(e==="")return t[0]==="?"?this.indentate(r)+"<"+t+n+"?"+this.tagEndChar:this.indentate(r)+"<"+t+n+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,s="";return t[0]==="?"&&(s="?",i=""),(n||n==="")&&e.indexOf("<")===-1?this.indentate(r)+"<"+t+n+s+">"+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&s.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+"<"+t+n+s+this.tagEndChar+e+this.indentate(r)+i}};ar.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};ar.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]==="?")return this.indentate(r)+"<"+t+n+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===""?this.indentate(r)+"<"+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+"<"+t+n+">"+i+"</"+t+this.tagEndChar}};ar.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function M6(e){return this.options.indentBy.repeat(e)}function q6(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var F6=ar;const H6=F6;var V6={XMLBuilder:H6};let _b=class{constructor(t,n){if(wi(this,"alphabet"),wi(this,"padding"),wi(this,"decodeMap",new Map),t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let a=0;a<t.length;a++)for(i=i<<8|t[a],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const a=(8-r.length%8)%8;for(let c=0;c<a;c++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const u=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);u.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const l=(u[0]<<3)+(u[1]>>2);if(s.push(l),c<6){const d=((u[1]&3)<<6)+(u[2]<<1)+(u[3]>>4);s.push(d)}if(c<4){const d=((u[3]&255)<<4)+(u[4]>>1);s.push(d)}if(c<3){const d=((u[4]&1)<<7)+(u[5]<<2)+(u[6]>>3);s.push(d)}if(c<1){const d=((u[6]&7)<<5)+u[7];s.push(d)}}return Uint8Array.from(s)}};new _b("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new _b("0123456789ABCDEFGHIJKLMNOPQRSTUV");let yb=class{constructor(t,n){if(wi(this,"alphabet"),wi(this,"padding"),wi(this,"decodeMap",new Map),t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let a=0;a<t.length;a++)for(i=i<<8|t[a],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const a=(4-r.length%4)%4;for(let c=0;c<a;c++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,u=0;for(let l=0;l<4;l++){const d=t[a*4+l];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);u+=f<<6*(3-l)}s.push(u>>16&255),c<2&&s.push(u>>8&255),c<1&&s.push(u&255)}return Uint8Array.from(s)}};new yb("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");new yb("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");const K6="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Sh=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=K6[n[e]&63];return t};async function G6(e,t){const n=e.notBefore||new Date().toISOString(),r=e.notAfter||new Date(new Date(n).getTime()+600*1e3).toISOString(),i=e.issueInstant||n,s=e.sessionNotOnOrAfter||r,a=e.responseId||`_${Sh()}`,c=e.assertionId||`_${Sh()}`,u=[{"samlp:Response":[{"saml:Issuer":[{"#text":e.issuer}]},{"samlp:Status":[{"samlp:StatusCode":[],":@":{"@_Value":"urn:oasis:names:tc:SAML:2.0:status:Success"}}]},{"saml:Assertion":[{"saml:Issuer":[{"#text":e.issuer}]},{"saml:Subject":[{"saml:NameID":[{"#text":e.email}],":@":{"@_Format":"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"}},{"saml:SubjectConfirmation":[{"saml:SubjectConfirmationData":[],":@":{"@_InResponseTo":e.inResponseTo,"@_NotOnOrAfter":r,"@_Recipient":e.destination}}],":@":{"@_Method":"urn:oasis:names:tc:SAML:2.0:cm:bearer"}}]},{"saml:Conditions":[{"saml:AudienceRestriction":[{"saml:Audience":[{"#text":e.audience}]}]}],":@":{"@_NotBefore":n,"@_NotOnOrAfter":r}},{"saml:AuthnStatement":[{"saml:AuthnContext":[{"saml:AuthnContextClassRef":[{"#text":"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"}]}]}],":@":{"@_AuthnInstant":i,"@_SessionIndex":e.sessionIndex,"@_SessionNotOnOrAfter":s}},{"saml:AttributeStatement":[{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.userId}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_FriendlyName":"persistent","@_Name":"id","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.email}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"email","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"default-roles-master"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"offline_access"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"view-profile"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"uma_authorization"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account-links"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}}]}],":@":{"@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion","@_ID":c,"@_IssueInstant":i,"@_Version":"2.0"}}],":@":{"@_xmlns:samlp":"urn:oasis:names:tc:SAML:2.0:protocol","@_xmlns:saml":"urn:oasis:names:tc:SAML:2.0:assertion","@_Destination":e.destination,"@_ID":a,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let l=new V6.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(u);return e.signature&&t&&(l=await t.signSAML(l,e.signature.privateKeyPem,e.signature.cert)),e.encode===!1?l:btoa(l)}let bb=class{constructor(t){this.signUrl=t}async signSAML(t,n,r){const i=await fetch(this.signUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xmlContent:t,privateKey:n,publicCert:r})});if(!i.ok)throw new Error(`Failed to sign SAML via HTTP: ${i.status} ${i.statusText}`);return await i.text()}};function W6(e,t,n){const r=n?`<input type="hidden" name="RelayState" value="${n}" />`:"",i=`
@@ -62,7 +62,7 @@
62
62
  <\/script>
63
63
  </body>
64
64
 
65
- </html>`;return e.html(s,{headers:i})}const jd=["openid","profile","email","address","phone"];async function X6(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(l=>{l.resource_server_identifier===r&&i.push(l.permission_name)});return[...new Set(i)]}async function Z6(e,t){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=t,a=s.filter($=>jd.includes($)),u=(await e.env.data.resourceServers.list(n)).resource_servers.filter($=>$.identifier===i);if(u.length===0)return{scopes:a,permissions:[]};const l=u[0];if(!l)return{scopes:a,permissions:[]};const d=l.options?.enforce_policies===!0,f=l.options?.token_dialect||"access_token",h=(await e.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find($=>$.audience===i);if(!h)return{scopes:a,permissions:[]};const g=h.scope||[],y=(l.scopes||[]).map($=>$.value);if(!d){let $;return s.length===0?$=g.filter(v=>y.includes(v)):$=s.filter(v=>y.includes(v)&&g.includes(v)),{scopes:[...new Set([...a,...$])],permissions:[]}}const w=g.filter($=>y.includes($));if(f==="access_token_authz")return{scopes:a,permissions:w};let m;return s.length===0?m=g.filter($=>y.includes($)):m=s.filter($=>y.includes($)&&g.includes($)),{scopes:[...new Set([...a,...m])],permissions:w}}async function Qa(e,t){if(t.grantType===Wt.ClientCredential)return await Z6(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 O=await e.env.data.userRoles.list(n,r,void 0,"");for(const q of O)if((await e.env.data.rolePermissions.list(n,q.id,{per_page:1e3})).some(oe=>oe.permission_name==="admin:organizations"&&oe.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(K=>K.organization_id===a))throw new X(403,{error:"access_denied",error_description:"User is not a member of the specified organization"})}const u=s.filter(E=>jd.includes(E)),d=(await e.env.data.resourceServers.list(n)).resource_servers.filter(E=>E.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(E=>E.value),h=f.options?.enforce_policies===!0,g=f.options?.token_dialect||"access_token";if(!h)return{scopes:s,permissions:[]};const y=await e.env.data.userPermissions.list(n,r,void 0,a),w=await e.env.data.userRoles.list(n,r,void 0,""),m=a?await e.env.data.userRoles.list(n,r,void 0,a):[],x=[...w,...m],$=a?await X6(e,n,r,i):[],k=[];for(const E of x)(await e.env.data.rolePermissions.list(n,E.id,{per_page:1e3})).forEach(q=>{q.resource_server_identifier===i&&k.push(q.permission_name)});const v=new Set;y.forEach(E=>{E.resource_server_identifier===i&&v.add(E.permission_name)}),k.forEach(E=>{v.add(E)}),$.forEach(E=>{v.add(E)});const z=Array.from(v),A=z.filter(E=>p.includes(E)),N=s.filter(E=>!p.includes(E)&&!jd.includes(E));if(g==="access_token_authz")return{scopes:[...new Set([...u,...N])],permissions:A};const R=s.filter(E=>p.includes(E)&&z.includes(E));return{scopes:[...new Set([...u,...R,...N])],permissions:A}}const zh=["sub","iss","aud","exp","nbf","iat","jti"];async function Xc(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:u}=t,{signingKeys:l}=await e.env.data.keys.list({q:"type:jwt_signing"}),d=l.filter(k=>!k.revoked_at||new Date(k.revoked_at)>new Date),f=d[d.length-1];if(!f?.pkcs7)throw new X(500,{message:"No signing key available"});const p=g6(f.pkcs7),h=e.var.custom_domain?`https://${e.var.custom_domain}/`:e.env.ISSUER,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:h,tenant_id:e.var.tenant_id,sid:s,act:u?{sub:u.user_id}:void 0,org_id:a?a.id:void 0,org_name:a&&i.tenant.allow_organization_name_in_authentication_api?a.name:void 0,permissions:c},w=r&&n.scope?.split(" ").includes("openid")?{aud:n.client_id,sub:r.user_id,iss:h,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified,act:u?{sub:u.user_id}:void 0,org_id:a?.id,org_name:a?.name}:void 0;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:""},{accessToken:{setCustomClaim:(k,v)=>{if(zh.includes(k))throw new Error(`Cannot overwrite reserved claim '${k}'`);y[k]=v}},idToken:{setCustomClaim:(k,v)=>{if(zh.includes(k))throw new Error(`Cannot overwrite reserved claim '${k}'`);w&&(w[k]=v)}},access:{deny:k=>{throw new X(400,{message:`Access denied: ${k}`})}},token:{createServiceToken:async k=>{const{createServiceToken:v}=await Promise.resolve().then(()=>Q6);return(await v(e,e.var.tenant_id,k.scope,k.expiresInSeconds)).access_token}}});const m={expiresIn:u?new Za(1,"h"):new Za(1,"d"),headers:{kid:f.kid}},x=await xh("RS256",p,y,m),$=w?await xh("RS256",p,w,m):void 0;return{access_token:x,refresh_token:t.refresh_token,id_token:$,token_type:"Bearer",expires_in:u?3600:86400}}async function wb(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Ne(),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+y6*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 vb(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Ne(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+Jc*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 xb(e,{user:t,client:n,loginSession:r}){const i=await e.env.data.sessions.create(n.tenant.id,{id:Ne(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+Jc*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]});return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id}),i}async function nn(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||Tt.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 $b(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=h6(),g=Ne(12),y=await e.env.data.codes.create(r.tenant.id,{code_id:Ne(),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+w6).toISOString(),code_verifier:[g,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:y.code_id,co_verifier:h,co_id:g})}let u=t.refreshToken,l=t.sessionId;if(!l&&t.loginSession?.session_id){l=t.loginSession.session_id;const h=await e.env.data.sessions.get(r.tenant.id,l);h&&!h.clients.includes(r.client_id)&&await e.env.data.sessions.update(r.tenant.id,l,{clients:[...h.clients,r.client_id]})}else if(!l){if(!t.loginSession)throw new X(500,{message:"Login session not found for creating a new session."});l=(await xb(e,{user:s,client:r,loginSession:t.loginSession})).id}if(!u&&n.scope?.split(" ").includes("offline_access")&&![Tt.TOKEN,Tt.CODE].includes(a)&&!t.impersonatingUser&&(u=(await vb(e,{user:s,client:r,session_id:l,scope:n.scope,audience:n.audience})).id),c===fn.SAML_POST){if(!l)throw new C(500,{message:"Session ID not available for SAML response"});return J6(e,t.client,t.authParams,s,l)}const d=await Y6(e,{authParams:n,user:s,client:r,session_id:l,refresh_token:u,authStrategy:t.authStrategy,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;if(l){const w=Ya(r.tenant.id,l,e.var.host||"");w&&h.set("set-cookie",w)}else console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const g=new URL(n.redirect_uri),y=`${g.protocol}//${g.host}`;return Nd(e,y,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;if(l){const h=Ya(r.tenant.id,l,e.var.custom_domain||e.req.header("host")||"");h&&f.set("set-cookie",h)}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 Y6(e,t){let{user:n}=t;const r=t.responseType||Tt.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(l=>l.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 c;if(t.grantType===Wt.ClientCredential||!n&&!t.user)c=await Qa(e,{grantType:Wt.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"});c=await Qa(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=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof C)throw c}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 c=await $b(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(c instanceof Response)return c;n=c}if(r===Tt.CODE){if(!n||!t.loginSession)throw new X(500,{message:"User and loginSession is required for code flow"});return await wb(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id})}else return Xc(e,{...t,user:n,authParams:a,permissions:s})}const Ah="auth-service";async function Zc(e,t,n,r){const i=await e.env.data.tenants.get(t);if(!i)throw new Error(`Tenant not found: ${t}`);const s={client_id:Ah,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,sso:!1,sso_disabled:!1,cross_origin_authentication:!1,custom_login_page_on:!1,require_pushed_authorization_requests:!1,require_proof_of_possession:!1,client_metadata:{disable_sign_ups:"false",email_validation:"disabled"},disable_sign_ups:!1,email_validation:"disabled",connections:[]},a=await Xc(e,{client:s,authParams:{client_id:Ah,response_type:Tt.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}const Q6=Object.freeze(Object.defineProperty({__proto__:null,createServiceToken:Zc},Symbol.toStringTag,{value:"Module"}));async function Yc(e,t,n){const r=await Zc(e,n.tenant_id,"webhook");for await(const i of t.filter(s=>"url"in s))(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok||_e(e,n.tenant_id,{type:he.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`})}function e5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t);return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function t5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await Yc(e,r,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function n5(e,t){const{hooks:n}=await e.env.data.hooks.list(t,{q:"trigger_id:validate-registration-username",page:0,per_page:1,include_totals:!1});return n.find(r=>"url"in r&&r.enabled)||null}function r5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function i5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}function Eh(e){return typeof e.form_id=="string"}function Ch(e,t){const n=e.match(/^\{\{context\.user\.(\w+)\}\}$/);if(n){const r=n[1],i=t.user[r];return typeof i=="string"?i:""}return e}function o5(e,t){const n=e.operator?.toLowerCase(),r=e.field?Ch(e.field,t):"",i=e.value||"";switch(n){case"ends_with":return r.endsWith(i);case"starts_with":return r.startsWith(i);case"contains":return 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&&Ch(`{{context.user.${a}}}`,t).endsWith(c))return!0}}return!1}}function If(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 C(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 C(400,{message:`Unknown redirect target: ${e}`})}}async function Nf(e,t,n,r,i=10){let s=t,a=0;for(;a<i;){if(s==="$ending")return{type:"end"};const c=e.find(u=>u.id===s);if(!c)return null;if(c.type==="STEP")return{type:"step",nodeId:c.id};if(c.type==="ACTION"){const u=c;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url};s=u.config.next_node,a++;continue}if(c.type==="ROUTER"){const u=c;let l=null;for(const d of u.config.rules)if(o5(d.condition,n)){l=d.next_node;break}if(l||(l=u.config.fallback),!l)return null;s=l,a++;continue}if(c.type==="FLOW"){const u=c;if(r&&u.config.flow_id){const l=await r(u.config.flow_id);if(l&&l.actions&&l.actions.length>0){for(const d of l.actions)if(d.type==="REDIRECT"&&d.action==="REDIRECT_USER"){const f=d.params?.target;if(f)return{type:"redirect",target:f,customUrl:d.params?.custom_url}}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end"}}return null}return null}async function s5(e,t,n,r){const i=e.env.data,s=e.var.tenant_id||e.req.header("tenant-id");if(!s)throw new C(400,{message:"Missing tenant_id in context"});const a=await i.forms.get(s,t);if(!a)throw new C(404,{message:"Form not found for post-user-login hook"});let c=a.start?.next_node;if(!c&&a.nodes&&a.nodes.length>0&&(c=a.nodes.find(d=>d.type==="STEP")?.id),!c)throw new C(400,{message:"No start node found in form"});if(r&&a.nodes){const l=async f=>{const p=await i.flows.get(s,f);return p?{actions:p.actions?.map(h=>({type:h.type,action:h.action,params:"params"in h&&h.params&&typeof h.params=="object"&&"target"in h.params?{target:h.params.target,custom_url:"custom_url"in h.params?h.params.custom_url:void 0}:void 0}))}:null},d=await Nf(a.nodes,c,{user:r},l);if(!d||d.type==="end")return new Response(null,{status:302,headers:{location:`/u/login/identifier?state=${encodeURIComponent(n.id)}`}});if(d.type==="redirect"){const f=If(d.target,d.customUrl,n.id);return new Response(null,{status:302,headers:{location:f}})}c=d.nodeId}let u=`/u/forms/${a.id}/nodes/${c}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:u}})}function Ih(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function a5(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new C(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(d=>d.permission_name===i))return r;let c=`/u/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:c}})}function Cr(e,t){return{createServiceToken:async n=>(await Zc(e,t,n.scope,n.expiresInSeconds)).access_token}}function Nh(e){return typeof e.url=="string"}function c5(e,t){return async(n,r)=>{if(e.var.client_id){const a=await t.legacyClients.get(e.var.client_id);if(!a)throw new X(400,{message:"Client not found"});r.email&&await l5(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}},token:Cr(e,n)})}catch{_e(e,n,{type:he.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await i6(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:Cr(e,n)})}catch{_e(e,n,{type:he.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await e5(e)(n,s),s}}function u5(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,u)=>{i[c]=u}},cancel:()=>{throw new X(400,{message:"User update cancelled by pre-update hook"})},token:Cr(e,n)})}catch{throw 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:u}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),l=u.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);l.length>0&&await t.users.update(n,r,{linked_to:l[0].user_id})}}return i.email&&_e(e,n,{type:he.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function jf(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 Ss({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"Public signup is disabled for this client"}}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,u;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:l=>{c=!0,u=l},token:Cr(e,t.tenant.id)}),c)return{allowed:!1,reason:u}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await n5(e,t.tenant.id);if(s&&"url"in s)try{const a=await Zc(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 u=await c.json();if(u.allowed===!1)return{allowed:!1,reason:u.reason||"Signup not allowed by webhook"}}catch{_e(e,t.tenant.id,{type:he.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function l5(e,t,n,r){const i=await jf(e,t,n,r);if(!i.allowed)throw _e(e,t.tenant.id,{type:he.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new X(400,{message:i.reason||"Signups are disabled for this client"});await t5(e)(t.tenant.id,r)}function d5(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:Cr(e,n)})}catch(c){throw c instanceof C?c:(_e(e,n,{type:he.FAILED_HOOK,description:`Pre user deletion hook failed: ${c instanceof Error?c.message:String(c)}`}),new X(400,{message:"Pre user deletion hook failed"}))}try{await r5(e)(n,i)}catch(c){throw _e(e,n,{type:he.FAILED_HOOK,description:`Pre user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`}),new X(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.remove(n,r);if(a){_e(e,n,{type:he.SUCCESS_USER_DELETION,description:`user_id: ${r}`,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await i5(e)(n,i)}catch(c){_e(e,n,{type:he.FAILED_HOOK,description:`Post user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`})}}if(a&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:Cr(e,n)})}catch(c){_e(e,n,{type:he.FAILED_HOOK,description:`Post user deletion hook failed: ${c instanceof Error?c.message:String(c)}`})}return a}}function Hi(e,t){const n=t;return{...t,users:{...t.users,create:c5(e,n),update:u5(e,n),remove:d5(e,n)}}}async function p5(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 u;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(u={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 l=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:l||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:u,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 $b(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(_e(e,n,{type:he.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 d=null;const f=await p5(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(f,{prompt:{render:p=>{}},redirect:{sendUserTo:(p,h)=>{const g=new URL(p,e.req.url);g.searchParams.set("state",i.id),h?.query&&Object.entries(h.query).forEach(([y,w])=>{g.searchParams.set(y,w)}),d=g.toString()},encodeToken:p=>JSON.stringify({payload:p.payload,exp:Date.now()+(p.expiresInSeconds||900)*1e3}),validateToken:p=>null},token:Cr(e,n)}),d)return new Response(null,{status:302,headers:{location:d}})}const{hooks:u}=await t.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const d=u.find(p=>p.enabled&&Eh(p));if(d&&Eh(d))return s5(e,d.form_id,i,r);const f=u.find(p=>p.enabled&&Ih(p));if(f&&Ih(f))return a5(e,f.page_id,i,r,f.permission_required)}const l=u.filter(d=>d.enabled&&Nh(d));for(const d of l)if(Nh(d))try{await fetch(d.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{_e(e,n,{type:he.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${d.url}`})}return r}function f5(e){return Hi(e,e.env.data)}async function Tf(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Vi({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=r==="sms"?`phone_number:${n}`:`email:${n}`,{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 email and provider"),s[0]||null}async function Ss({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 Qn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Vi({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Qc(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:u={},ip:l=""}=t;let d=await Qn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||$s()}`,email:i!=="sms"?n:void 0,phone_number:i==="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:l,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(u)};d=await f5(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const Qe=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 ct(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}var h5={Stringify:1},er=(e,t)=>{const n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},g5=/[&<>'"]/,m5=async(e,t)=>{let n="";t||=[];const r=await Promise.all(e);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&t.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&t.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];vi(s,c),n=c[0]}}return er(n,t)},vi=(e,t)=>{const n=e.search(g5);if(n===-1){t[0]+=e;return}let r,i,s=0;for(i=n;i<e.length;i++){switch(e.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}t[0]+=e.substring(s,i)+r,s=i+1}t[0]+=e.substring(s,i)},_5=e=>{const t=e.callbacks;if(!t?.length)return e;const n=[e],r={};return t.forEach(i=>i({phase:h5.Stringify,buffer:n,context:r})),n[0]},Of=Symbol("RENDERER"),Td=Symbol("ERROR_HANDLER"),Be=Symbol("STASH"),kb=Symbol("INTERNAL"),y5=Symbol("MEMO"),ec=Symbol("PERMALINK"),jh=e=>(e[kb]=!0,e),Sb=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:jh(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:jh(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Td]=s=>{throw e.pop(),s},i},zb=e=>{const t=[e],n=Sb(t);return n.values=t,n.Provider=n,Ei.push(n),n},Ei=[],Ab=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new Nb("",{},r.children):r.children).toString():""}finally{t.pop()}return i instanceof Promise?i.then(s=>er(s,s.callbacks)):er(i)});return n.values=t,n.Provider=n,n[Of]=Sb(t),Ei.push(n),n},Ki=e=>e.values.at(-1),$a={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Od={},ka="data-precedence",zs=e=>Array.isArray(e)?e:[e],Th=new WeakMap,Oh=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Th.get(s)||{};Th.set(s,a);const c=a[e]||=[];let u=!1;const l=$a[e];if(l.length>0){e:for(const[,d]of c)for(const f of l)if((d?.[f]??null)===n?.[f]){u=!0;break e}}if(u?i[0]=i[0].replaceAll(t,""):l.length>0?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let d;if(r===void 0)d=c.map(([f])=>f);else{const f=[];d=c.map(([p,,h])=>{let g=f.indexOf(h);return g===-1&&(f.push(h),g=f.length-1),[p,g]}).sort((p,h)=>p[1]-h[1]).map(([p])=>p)}d.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,d.join(""))}},As=(e,t,n)=>er(new Qt(e,n,zs(t??[])).toString()),Es=(e,t,n,r)=>{if("itemProp"in n)return As(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ka]=i);const c=new Qt(e,a,zs(t||[])).toString();return c instanceof Promise?c.then(u=>er(c,[...u.callbacks||[],Oh(e,u,a,i)])):er(c,[Oh(e,c,a,i)])},b5=({children:e,...t})=>{const n=Pf();if(n){const r=Ki(n);if(r==="svg"||r==="head")return new Qt("title",t,zs(e??[]))}return Es("title",e,t,!1)},w5=({children:e,...t})=>{const n=Pf();return["src","async"].some(r=>!t[r])||n&&Ki(n)==="head"?As("script",e,t):Es("script",e,t,!1)},v5=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,Es("style",e,t,!0)):As("style",e,t),x5=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?As("link",e,t):Es("link",e,t,"precedence"in t),$5=({children:e,...t})=>{const n=Pf();return n&&Ki(n)==="head"?As("meta",e,t):Es("meta",e,t,!1)},Eb=(e,{children:t,...n})=>new Qt(e,n,zs(t??[])),k5=e=>(typeof e.action=="function"&&(e.action=ec in e.action?e.action[ec]:void 0),Eb("form",e)),Cb=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=ec in t.formAction?t.formAction[ec]:void 0),Eb(e,t)),S5=e=>Cb("input",e),z5=e=>Cb("button",e);const pl=Object.freeze(Object.defineProperty({__proto__:null,button:z5,form:k5,input:S5,link:x5,meta:$5,script:w5,style:v5,title:b5},Symbol.toStringTag,{value:"Module"}));var A5=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),tc=e=>A5.get(e)||e,Ib=(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)}},ts=void 0,Pf=()=>ts,E5=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,C5=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],I5=["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"],Rf=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")vi(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof Qt?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):Rf(i,t)}}},Qt=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?_5(er(e[0],e.callbacks)).toString():e[0]:m5(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=ts&&Ki(ts)==="svg"?s=>E5(tc(s)):s=>tc(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";Ib(a,(u,l)=>{l!=null&&(c+=`${c?";":""}${u}:${l}`)}),e[0]+=' style="',vi(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,vi(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&I5.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=[er(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}="`,vi(a.toString(),e),e[0]+='"'}if(C5.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",Rf(r,e),e[0]+=`</${t}>`}},fl=class extends Qt{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(Ei.length===0)e.unshift("",r);else{const i=Ei.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof Qt&&(s.localContexts=i),s)))}else r instanceof Qt?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):vi(r,e)}},Nb=class extends Qt{toStringToBuffer(e){Rf(this.children,e)}},N5=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Sa(e,t,n);return i.key=r,i},Ph=!1,Sa=(e,t,n)=>{if(!Ph){for(const r in Od)pl[r][Of]=Od[r];Ph=!0}return typeof e=="function"?new fl(e,t,n):pl[e]?new fl(pl[e],t,n):e==="svg"||e==="head"?(ts||=Ab(""),new Qt(e,t,[new fl(ts,{value:e},n)])):new Qt(e,t,n)},ns=({children:e})=>new Nb("",{children:e},Array.isArray(e)?e:e?[e]:[]),j5=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return N5(e.tag,{...e.props,...t},...r)};function _(e,t,n){let r;if(!t||!("children"in t))r=Sa(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Sa(e,t,i):Sa(e,t,[i])}return r.key=n,r}var Rh;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(Rh||(Rh={}));var Lh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Lh||(Lh={}));function T5(e){return jb(e,O5,rs.Include)}function Lf(e){return jb(e,P5,rs.None)}function jb(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===rs.Include&&(r+="=")}return r}const O5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",P5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var rs;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(rs||(rs={}));var Dh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Dh||(Dh={}));class R5{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 Bh=new R5;function an(e,t){return(e<<32-t|e>>>t)>>>0}function L5(e){const t=new D5;return t.update(e),t.digest()}class D5{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),Bh.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)Bh.putUint32(t,this.H[n],n*4);return t}process(){for(let l=0;l<16;l++)this.w[l]=(this.blocks[l*4]<<24|this.blocks[l*4+1]<<16|this.blocks[l*4+2]<<8|this.blocks[l*4+3])>>>0;for(let l=16;l<64;l++){const d=(an(this.w[l-2],17)^an(this.w[l-2],19)^this.w[l-2]>>>10)>>>0,f=(an(this.w[l-15],7)^an(this.w[l-15],18)^this.w[l-15]>>>3)>>>0;this.w[l]=d+this.w[l-7]+f+this.w[l-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],u=this.H[7];for(let l=0;l<64;l++){const d=(an(s,6)^an(s,11)^an(s,25))>>>0,f=(s&a^~s&c)>>>0,p=u+d+f+B5[l]+this.w[l]|0,h=(an(t,2)^an(t,13)^an(t,22))>>>0,g=(t&n^t&r^n&r)>>>0,y=h+g|0;u=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+y|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]=u+this.H[7]|0}}const B5=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 Tb{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 Ob(e){const t=L5(new TextEncoder().encode(e));return Lf(t)}function eu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Lf(e)}function Pb(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Lf(e)}function U5(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 Uh(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 Mh(e,...t){let n=Uh(e,"/");for(const r of t)n=Uh(n,"/")+"/"+U5(r,"/");return n}function Cn(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 Sr(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return T5(n)}async function Ci(e){let t;try{t=await fetch(e)}catch(n){throw new Bf(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);let r;try{r=Df(n)}catch{throw new Jn(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);return new Tb(n)}throw t.body!==null&&await t.body.cancel(),new xi(t.status)}async function M5(e){let t;try{t=await fetch(e)}catch(n){throw new Bf(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new Jn(t.status,null)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);let r;try{r=Df(n)}catch{throw new Jn(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 xi(t.status)}function Df(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 q5(t,n,r,i)}class Bf extends Error{constructor(t){super("Failed to send request",{cause:t})}}class q5 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 xi extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class Jn extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Gr{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===Ir.S256){const c=Ob(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===Ir.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=Cn(t,i);if(this.clientPassword!==null){const c=Sr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ci(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=Cn(t,i);if(this.clientPassword!==null){const c=Sr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ci(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Cn(t,r);if(this.clientPassword!==null){const s=Sr(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await M5(i)}}var Ir;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(Ir||(Ir={}));var qh;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(qh||(qh={}));var Fh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Fh||(Fh={}));function qo(e){return F5(e,H5,nc.None)}function F5(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===nc.Include&&(r+="=")}return r}const H5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var nc;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(nc||(nc={}));var Hh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Hh||(Hh={}));function V5(e,t,n){const r=qo(new TextEncoder().encode(e)),i=qo(new TextEncoder().encode(t)),s=qo(n);return r+"."+i+"."+s}function K5(e,t){const n=qo(new TextEncoder().encode(e)),r=qo(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const G5="https://appleid.apple.com/auth/authorize",W5="https://appleid.apple.com/auth/token";class Rb{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(G5);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=Cn(W5,n);return await Ci(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,K5(r,i)));return V5(r,i,s)}}const J5="https://www.facebook.com/v16.0/dialog/oauth",X5="https://graph.facebook.com/v16.0/oauth/access_token";class Lb{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(J5);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=Cn(X5,n);return await Ci(r)}}const Z5="https://github.com/login/oauth/authorize",Vh="https://github.com/login/oauth/access_token";class Db{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(Z5);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=Cn(Vh,n),i=Sr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await Kh(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Cn(Vh,n),i=Sr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await Kh(r)}}async function Kh(e){let t;try{t=await fetch(e)}catch(i){throw new Bf(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new xi(t.status);let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Df(n)}catch{throw new Jn(t.status,n)}throw i}return new Tb(n)}const Y5="https://accounts.google.com/o/oauth2/v2/auth",Gh="https://oauth2.googleapis.com/token",Q5="https://oauth2.googleapis.com/revoke";let Bb=class{client;constructor(t,n,r){this.client=new Gr(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(Y5,t,Ir.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(Gh,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(Gh,t,[])}async revokeToken(t){await this.client.revokeToken(Q5,t)}};class Ub{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=Mh("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=Mh("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=Ob(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=Cn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=Sr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Ci(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=Cn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=Sr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Ci(i)}}const Gi=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();Gi.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function tu(e){return e.ISSUER}function nt(e){return e.UNIVERSAL_LOGIN_URL||`${e.ISSUER}u/`}function Te(e){return e.OAUTH_API_URL||e.ISSUER}const e8="Apple",t8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M45 0H0V45H45V0Z",fill:"white"}),_("path",{d:"M23.5344 10.3846C25.5313 10.3846 28.0344 9.01144 29.525 7.18055C30.875 5.5213 31.8594 3.20407 31.8594 0.886839C31.8594 0.572154 31.8313 0.25747 31.775 0C29.5531 0.0858233 26.8813 1.51621 25.2781 3.43293C24.0125 4.89193 22.8594 7.18055 22.8594 9.52638C22.8594 9.86968 22.9156 10.213 22.9438 10.3274C23.0844 10.356 23.3094 10.3846 23.5344 10.3846ZM16.5031 45C19.2313 45 20.4406 43.1405 23.8438 43.1405C27.3031 43.1405 28.0625 44.9428 31.1 44.9428C34.0813 44.9428 36.0781 42.1392 37.9625 39.3929C40.0719 36.246 40.9438 33.1564 41 33.0134C40.8031 32.9561 35.0938 30.5817 35.0938 23.9161C35.0938 18.1373 39.5938 15.534 39.8469 15.3338C36.8656 10.9854 32.3375 10.8709 31.1 10.8709C27.7531 10.8709 25.025 12.9307 23.3094 12.9307C21.4531 12.9307 19.0063 10.9854 16.1094 10.9854C10.5969 10.9854 5 15.6198 5 24.3738C5 29.8093 7.08125 35.5594 9.64063 39.2784C11.8344 42.4253 13.7469 45 16.5031 45Z",fill:"black"})]});function Mb(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 n8(e,t){const{options:n,keyArray:r}=Mb(t),i=`${Te(e.env)}callback`,s=new Rb(n.client_id,n.team_id,n.kid,r,i),a=Ne(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(l=>["email","name"].includes(l))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function r8(e,t,n){const{options:r,keyArray:i}=Mb(t),a=await new Rb(r.client_id,r.team_id,r.kid,i,`${Te(e.env)}callback`).validateAuthorizationCode(n),c=ks(a.idToken());if(!c)throw new Error("Invalid ID token");const u=Gi.parse(c.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture,locale:u.locale}}const i8=Object.freeze(Object.defineProperty({__proto__:null,displayName:e8,getRedirect:n8,logo:t8,validateAuthorizationCodeAndGetUser:r8},Symbol.toStringTag,{value:"Module"})),o8="Facebook",s8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M45 22.5C45 10.0736 34.9264 0 22.5 0C10.0736 0 0 10.0736 0 22.5C0 33.7031 8.23242 42.9785 19.0039 44.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039 11.8945 22.3828 8.75977 27.5391 8.75977C29.9658 8.75977 32.5049 9.19922 32.5049 9.19922V14.7656H29.7012C26.9414 14.7656 26.0156 16.4824 26.0156 18.2432V22.5H32.2412L31.2012 28.9746H26.0156V44.6953C36.7871 42.9785 45 33.7031 45 22.5Z",fill:"#1877F2"}),_("path",{d:"M31.2012 28.9746L32.2412 22.5H26.0156V18.2432C26.0156 16.4824 26.9414 14.7656 29.7012 14.7656H32.5049V9.19922C32.5049 9.19922 29.9658 8.75977 27.5391 8.75977C22.3828 8.75977 19.0039 11.8945 19.0039 17.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562 44.8984 21.3203 45 22.5 45C23.6797 45 24.8438 44.8984 26.0156 44.6953V28.9746H31.2012Z",fill:"white"})]});async function a8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Te(e.env)}callback`,i=new Lb(n.client_id,n.client_secret,r),s=Ne();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function c8(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 Lb(r.client_id,r.client_secret,`${Te(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 u8=Object.freeze(Object.defineProperty({__proto__:null,displayName:o8,getRedirect:a8,logo:s8,validateAuthorizationCodeAndGetUser:c8},Symbol.toStringTag,{value:"Module"})),l8="Google",d8=!0,p8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M44.1035 23.0123C44.1054 21.4791 43.9758 19.9486 43.716 18.4375H22.498V27.1028H34.6507C34.4021 28.4868 33.8757 29.8061 33.1034 30.9812C32.3311 32.1562 31.3289 33.1628 30.1571 33.9401V39.5649H37.41C41.6567 35.6494 44.1035 29.859 44.1035 23.0123Z",fill:"#4285F4"}),_("path",{d:"M22.4982 44.9997C28.5698 44.9997 33.6821 43.0061 37.4101 39.5687L30.1573 33.9439C28.1386 35.3126 25.5387 36.0938 22.4982 36.0938C16.6296 36.0938 11.6485 32.1377 9.86736 26.8066H2.39575V32.6033C4.26839 36.3297 7.13989 39.4622 10.6896 41.6512C14.2394 43.8402 18.3277 44.9995 22.4982 44.9997Z",fill:"#34A853"}),_("path",{d:"M9.86737 26.8073C8.92572 24.0138 8.92572 20.9886 9.86737 18.1951V12.3984H2.39576C0.820432 15.5332 0 18.9929 0 22.5012C0 26.0095 0.820432 29.4692 2.39576 32.604L9.86737 26.8073Z",fill:"#FBBC04"}),_("path",{d:"M22.4982 8.90741C25.7068 8.85499 28.8071 10.0673 31.1291 12.2823L37.5507 5.86064C33.4788 2.03602 28.0843 -0.0637686 22.4982 0.00147616C18.3277 0.00166623 14.2394 1.16098 10.6896 3.34999C7.13989 5.539 4.26839 8.67155 2.39575 12.3979L9.86736 18.1946C11.6485 12.8635 16.6296 8.90741 22.4982 8.90741Z",fill:"#EA4335"})]});async function f8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Te(e.env)}callback`,i=new Bb(n.client_id,n.client_secret,r),s=Ne(),a=eu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function h8(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 Bb(i.client_id,i.client_secret,`${Te(e.env)}callback`).validateAuthorizationCode(n,r),c=ks(a.idToken());if(!c)throw new Error("Invalid ID token");const u=Gi.parse(c.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture,locale:u.locale}}const g8=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:d8,displayName:l8,getRedirect:f8,logo:p8,validateAuthorizationCodeAndGetUser:h8},Symbol.toStringTag,{value:"Module"})),m8="Vipps",_8=({className:e=""})=>_("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",width:"45",height:"45",className:e,children:[_("path",{fill:"#FF5B24",d:"M3.5,8h41c1.9,0,3.5,1.6,3.5,3.5v25c0,1.9-1.6,3.5-3.5,3.5h-41C1.6,40,0,38.4,0,36.5v-25C0,9.6,1.6,8,3.5,8z"}),_("path",{fillRule:"evenodd",clipRule:"evenodd",fill:"#FFFFFF",d:`M27.9,20.3c1.4,0,2.6-1,2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4,0-2.6,1-2.6,2.5C25.3,19.2,26.5,20.3,27.9,20.3z
65
+ </html>`;return e.html(s,{headers:i})}const jd=["openid","profile","email","address","phone"];async function X6(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(l=>{l.resource_server_identifier===r&&i.push(l.permission_name)});return[...new Set(i)]}async function Z6(e,t){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=t,a=s.filter($=>jd.includes($)),u=(await e.env.data.resourceServers.list(n)).resource_servers.filter($=>$.identifier===i);if(u.length===0)return{scopes:a,permissions:[]};const l=u[0];if(!l)return{scopes:a,permissions:[]};const d=l.options?.enforce_policies===!0,f=l.options?.token_dialect||"access_token",h=(await e.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find($=>$.audience===i);if(!h)return{scopes:a,permissions:[]};const g=h.scope||[],y=(l.scopes||[]).map($=>$.value);if(!d){let $;return s.length===0?$=g.filter(v=>y.includes(v)):$=s.filter(v=>y.includes(v)&&g.includes(v)),{scopes:[...new Set([...a,...$])],permissions:[]}}const w=g.filter($=>y.includes($));if(f==="access_token_authz")return{scopes:a,permissions:w};let m;return s.length===0?m=g.filter($=>y.includes($)):m=s.filter($=>y.includes($)&&g.includes($)),{scopes:[...new Set([...a,...m])],permissions:w}}async function Qa(e,t){if(t.grantType===Wt.ClientCredential)return await Z6(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 O=await e.env.data.userRoles.list(n,r,void 0,"");for(const q of O)if((await e.env.data.rolePermissions.list(n,q.id,{per_page:1e3})).some(oe=>oe.permission_name==="admin:organizations"&&oe.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(K=>K.organization_id===a))throw new X(403,{error:"access_denied",error_description:"User is not a member of the specified organization"})}const u=s.filter(E=>jd.includes(E)),d=(await e.env.data.resourceServers.list(n)).resource_servers.filter(E=>E.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(E=>E.value),h=f.options?.enforce_policies===!0,g=f.options?.token_dialect||"access_token";if(!h)return{scopes:s,permissions:[]};const y=await e.env.data.userPermissions.list(n,r,void 0,a),w=await e.env.data.userRoles.list(n,r,void 0,""),m=a?await e.env.data.userRoles.list(n,r,void 0,a):[],x=[...w,...m],$=a?await X6(e,n,r,i):[],k=[];for(const E of x)(await e.env.data.rolePermissions.list(n,E.id,{per_page:1e3})).forEach(q=>{q.resource_server_identifier===i&&k.push(q.permission_name)});const v=new Set;y.forEach(E=>{E.resource_server_identifier===i&&v.add(E.permission_name)}),k.forEach(E=>{v.add(E)}),$.forEach(E=>{v.add(E)});const z=Array.from(v),A=z.filter(E=>p.includes(E)),N=s.filter(E=>!p.includes(E)&&!jd.includes(E));if(g==="access_token_authz")return{scopes:[...new Set([...u,...N])],permissions:A};const R=s.filter(E=>p.includes(E)&&z.includes(E));return{scopes:[...new Set([...u,...R,...N])],permissions:A}}const zh=["sub","iss","aud","exp","nbf","iat","jti"];async function Xc(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:u}=t,{signingKeys:l}=await e.env.data.keys.list({q:"type:jwt_signing"}),d=l.filter(k=>!k.revoked_at||new Date(k.revoked_at)>new Date),f=d[d.length-1];if(!f?.pkcs7)throw new X(500,{message:"No signing key available"});const p=g6(f.pkcs7),h=e.var.custom_domain?`https://${e.var.custom_domain}/`:e.env.ISSUER,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:h,tenant_id:e.var.tenant_id,sid:s,act:u?{sub:u.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},w=r&&n.scope?.split(" ").includes("openid")?{aud:n.client_id,sub:r.user_id,iss:h,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified,act:u?{sub:u.user_id}:void 0,org_id:a?.id,org_name:a?.name.toLowerCase()}:void 0;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:""},{accessToken:{setCustomClaim:(k,v)=>{if(zh.includes(k))throw new Error(`Cannot overwrite reserved claim '${k}'`);y[k]=v}},idToken:{setCustomClaim:(k,v)=>{if(zh.includes(k))throw new Error(`Cannot overwrite reserved claim '${k}'`);w&&(w[k]=v)}},access:{deny:k=>{throw new X(400,{message:`Access denied: ${k}`})}},token:{createServiceToken:async k=>{const{createServiceToken:v}=await Promise.resolve().then(()=>Q6);return(await v(e,e.var.tenant_id,k.scope,k.expiresInSeconds)).access_token}}});const m={expiresIn:u?new Za(1,"h"):new Za(1,"d"),headers:{kid:f.kid}},x=await xh("RS256",p,y,m),$=w?await xh("RS256",p,w,m):void 0;return{access_token:x,refresh_token:t.refresh_token,id_token:$,token_type:"Bearer",expires_in:u?3600:86400}}async function wb(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Ne(),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+y6*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 vb(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Ne(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+Jc*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 xb(e,{user:t,client:n,loginSession:r}){const i=await e.env.data.sessions.create(n.tenant.id,{id:Ne(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+Jc*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]});return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id}),i}async function nn(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||Tt.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 $b(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=h6(),g=Ne(12),y=await e.env.data.codes.create(r.tenant.id,{code_id:Ne(),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+w6).toISOString(),code_verifier:[g,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:y.code_id,co_verifier:h,co_id:g})}let u=t.refreshToken,l=t.sessionId;if(!l&&t.loginSession?.session_id){l=t.loginSession.session_id;const h=await e.env.data.sessions.get(r.tenant.id,l);h&&!h.clients.includes(r.client_id)&&await e.env.data.sessions.update(r.tenant.id,l,{clients:[...h.clients,r.client_id]})}else if(!l){if(!t.loginSession)throw new X(500,{message:"Login session not found for creating a new session."});l=(await xb(e,{user:s,client:r,loginSession:t.loginSession})).id}if(!u&&n.scope?.split(" ").includes("offline_access")&&![Tt.TOKEN,Tt.CODE].includes(a)&&!t.impersonatingUser&&(u=(await vb(e,{user:s,client:r,session_id:l,scope:n.scope,audience:n.audience})).id),c===fn.SAML_POST){if(!l)throw new C(500,{message:"Session ID not available for SAML response"});return J6(e,t.client,t.authParams,s,l)}const d=await Y6(e,{authParams:n,user:s,client:r,session_id:l,refresh_token:u,authStrategy:t.authStrategy,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;if(l){const w=Ya(r.tenant.id,l,e.var.host||"");w&&h.set("set-cookie",w)}else console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const g=new URL(n.redirect_uri),y=`${g.protocol}//${g.host}`;return Nd(e,y,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;if(l){const h=Ya(r.tenant.id,l,e.var.custom_domain||e.req.header("host")||"");h&&f.set("set-cookie",h)}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 Y6(e,t){let{user:n}=t;const r=t.responseType||Tt.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(l=>l.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 c;if(t.grantType===Wt.ClientCredential||!n&&!t.user)c=await Qa(e,{grantType:Wt.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"});c=await Qa(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=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof C)throw c}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 c=await $b(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(c instanceof Response)return c;n=c}if(r===Tt.CODE){if(!n||!t.loginSession)throw new X(500,{message:"User and loginSession is required for code flow"});return await wb(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id})}else return Xc(e,{...t,user:n,authParams:a,permissions:s})}const Ah="auth-service";async function Zc(e,t,n,r){const i=await e.env.data.tenants.get(t);if(!i)throw new Error(`Tenant not found: ${t}`);const s={client_id:Ah,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,sso:!1,sso_disabled:!1,cross_origin_authentication:!1,custom_login_page_on:!1,require_pushed_authorization_requests:!1,require_proof_of_possession:!1,client_metadata:{disable_sign_ups:"false",email_validation:"disabled"},disable_sign_ups:!1,email_validation:"disabled",connections:[]},a=await Xc(e,{client:s,authParams:{client_id:Ah,response_type:Tt.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}const Q6=Object.freeze(Object.defineProperty({__proto__:null,createServiceToken:Zc},Symbol.toStringTag,{value:"Module"}));async function Yc(e,t,n){const r=await Zc(e,n.tenant_id,"webhook");for await(const i of t.filter(s=>"url"in s))(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok||_e(e,n.tenant_id,{type:he.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`})}function e5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t);return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function t5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await Yc(e,r,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function n5(e,t){const{hooks:n}=await e.env.data.hooks.list(t,{q:"trigger_id:validate-registration-username",page:0,per_page:1,include_totals:!1});return n.find(r=>"url"in r&&r.enabled)||null}function r5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function i5(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await Yc(e,r,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}function Eh(e){return typeof e.form_id=="string"}function Ch(e,t){const n=e.match(/^\{\{context\.user\.(\w+)\}\}$/);if(n){const r=n[1],i=t.user[r];return typeof i=="string"?i:""}return e}function o5(e,t){const n=e.operator?.toLowerCase(),r=e.field?Ch(e.field,t):"",i=e.value||"";switch(n){case"ends_with":return r.endsWith(i);case"starts_with":return r.startsWith(i);case"contains":return 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&&Ch(`{{context.user.${a}}}`,t).endsWith(c))return!0}}return!1}}function If(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 C(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 C(400,{message:`Unknown redirect target: ${e}`})}}async function Nf(e,t,n,r,i=10){let s=t,a=0;for(;a<i;){if(s==="$ending")return{type:"end"};const c=e.find(u=>u.id===s);if(!c)return null;if(c.type==="STEP")return{type:"step",nodeId:c.id};if(c.type==="ACTION"){const u=c;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url};s=u.config.next_node,a++;continue}if(c.type==="ROUTER"){const u=c;let l=null;for(const d of u.config.rules)if(o5(d.condition,n)){l=d.next_node;break}if(l||(l=u.config.fallback),!l)return null;s=l,a++;continue}if(c.type==="FLOW"){const u=c;if(r&&u.config.flow_id){const l=await r(u.config.flow_id);if(l&&l.actions&&l.actions.length>0){for(const d of l.actions)if(d.type==="REDIRECT"&&d.action==="REDIRECT_USER"){const f=d.params?.target;if(f)return{type:"redirect",target:f,customUrl:d.params?.custom_url}}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end"}}return null}return null}async function s5(e,t,n,r){const i=e.env.data,s=e.var.tenant_id||e.req.header("tenant-id");if(!s)throw new C(400,{message:"Missing tenant_id in context"});const a=await i.forms.get(s,t);if(!a)throw new C(404,{message:"Form not found for post-user-login hook"});let c=a.start?.next_node;if(!c&&a.nodes&&a.nodes.length>0&&(c=a.nodes.find(d=>d.type==="STEP")?.id),!c)throw new C(400,{message:"No start node found in form"});if(r&&a.nodes){const l=async f=>{const p=await i.flows.get(s,f);return p?{actions:p.actions?.map(h=>({type:h.type,action:h.action,params:"params"in h&&h.params&&typeof h.params=="object"&&"target"in h.params?{target:h.params.target,custom_url:"custom_url"in h.params?h.params.custom_url:void 0}:void 0}))}:null},d=await Nf(a.nodes,c,{user:r},l);if(!d||d.type==="end")return new Response(null,{status:302,headers:{location:`/u/login/identifier?state=${encodeURIComponent(n.id)}`}});if(d.type==="redirect"){const f=If(d.target,d.customUrl,n.id);return new Response(null,{status:302,headers:{location:f}})}c=d.nodeId}let u=`/u/forms/${a.id}/nodes/${c}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:u}})}function Ih(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function a5(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new C(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(d=>d.permission_name===i))return r;let c=`/u/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:c}})}function Cr(e,t){return{createServiceToken:async n=>(await Zc(e,t,n.scope,n.expiresInSeconds)).access_token}}function Nh(e){return typeof e.url=="string"}function c5(e,t){return async(n,r)=>{if(e.var.client_id){const a=await t.legacyClients.get(e.var.client_id);if(!a)throw new X(400,{message:"Client not found"});r.email&&await l5(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}},token:Cr(e,n)})}catch{_e(e,n,{type:he.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await i6(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:Cr(e,n)})}catch{_e(e,n,{type:he.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await e5(e)(n,s),s}}function u5(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,u)=>{i[c]=u}},cancel:()=>{throw new X(400,{message:"User update cancelled by pre-update hook"})},token:Cr(e,n)})}catch{throw 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:u}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),l=u.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);l.length>0&&await t.users.update(n,r,{linked_to:l[0].user_id})}}return i.email&&_e(e,n,{type:he.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function jf(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 Ss({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"Public signup is disabled for this client"}}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,u;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:l=>{c=!0,u=l},token:Cr(e,t.tenant.id)}),c)return{allowed:!1,reason:u}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await n5(e,t.tenant.id);if(s&&"url"in s)try{const a=await Zc(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 u=await c.json();if(u.allowed===!1)return{allowed:!1,reason:u.reason||"Signup not allowed by webhook"}}catch{_e(e,t.tenant.id,{type:he.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function l5(e,t,n,r){const i=await jf(e,t,n,r);if(!i.allowed)throw _e(e,t.tenant.id,{type:he.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new X(400,{message:i.reason||"Signups are disabled for this client"});await t5(e)(t.tenant.id,r)}function d5(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:Cr(e,n)})}catch(c){throw c instanceof C?c:(_e(e,n,{type:he.FAILED_HOOK,description:`Pre user deletion hook failed: ${c instanceof Error?c.message:String(c)}`}),new X(400,{message:"Pre user deletion hook failed"}))}try{await r5(e)(n,i)}catch(c){throw _e(e,n,{type:he.FAILED_HOOK,description:`Pre user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`}),new X(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.remove(n,r);if(a){_e(e,n,{type:he.SUCCESS_USER_DELETION,description:`user_id: ${r}`,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await i5(e)(n,i)}catch(c){_e(e,n,{type:he.FAILED_HOOK,description:`Post user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`})}}if(a&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:Cr(e,n)})}catch(c){_e(e,n,{type:he.FAILED_HOOK,description:`Post user deletion hook failed: ${c instanceof Error?c.message:String(c)}`})}return a}}function Hi(e,t){const n=t;return{...t,users:{...t.users,create:c5(e,n),update:u5(e,n),remove:d5(e,n)}}}async function p5(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 u;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(u={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 l=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:l||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:u,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 $b(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(_e(e,n,{type:he.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 d=null;const f=await p5(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(f,{prompt:{render:p=>{}},redirect:{sendUserTo:(p,h)=>{const g=new URL(p,e.req.url);g.searchParams.set("state",i.id),h?.query&&Object.entries(h.query).forEach(([y,w])=>{g.searchParams.set(y,w)}),d=g.toString()},encodeToken:p=>JSON.stringify({payload:p.payload,exp:Date.now()+(p.expiresInSeconds||900)*1e3}),validateToken:p=>null},token:Cr(e,n)}),d)return new Response(null,{status:302,headers:{location:d}})}const{hooks:u}=await t.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const d=u.find(p=>p.enabled&&Eh(p));if(d&&Eh(d))return s5(e,d.form_id,i,r);const f=u.find(p=>p.enabled&&Ih(p));if(f&&Ih(f))return a5(e,f.page_id,i,r,f.permission_required)}const l=u.filter(d=>d.enabled&&Nh(d));for(const d of l)if(Nh(d))try{await fetch(d.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{_e(e,n,{type:he.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${d.url}`})}return r}function f5(e){return Hi(e,e.env.data)}async function Tf(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Vi({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=r==="sms"?`phone_number:${n}`:`email:${n}`,{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 email and provider"),s[0]||null}async function Ss({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 Qn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Vi({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Qc(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:u={},ip:l=""}=t;let d=await Qn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||$s()}`,email:i!=="sms"?n:void 0,phone_number:i==="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:l,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(u)};d=await f5(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const Qe=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 ct(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}var h5={Stringify:1},er=(e,t)=>{const n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},g5=/[&<>'"]/,m5=async(e,t)=>{let n="";t||=[];const r=await Promise.all(e);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&t.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&t.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];vi(s,c),n=c[0]}}return er(n,t)},vi=(e,t)=>{const n=e.search(g5);if(n===-1){t[0]+=e;return}let r,i,s=0;for(i=n;i<e.length;i++){switch(e.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}t[0]+=e.substring(s,i)+r,s=i+1}t[0]+=e.substring(s,i)},_5=e=>{const t=e.callbacks;if(!t?.length)return e;const n=[e],r={};return t.forEach(i=>i({phase:h5.Stringify,buffer:n,context:r})),n[0]},Of=Symbol("RENDERER"),Td=Symbol("ERROR_HANDLER"),Be=Symbol("STASH"),kb=Symbol("INTERNAL"),y5=Symbol("MEMO"),ec=Symbol("PERMALINK"),jh=e=>(e[kb]=!0,e),Sb=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:jh(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:jh(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Td]=s=>{throw e.pop(),s},i},zb=e=>{const t=[e],n=Sb(t);return n.values=t,n.Provider=n,Ei.push(n),n},Ei=[],Ab=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new Nb("",{},r.children):r.children).toString():""}finally{t.pop()}return i instanceof Promise?i.then(s=>er(s,s.callbacks)):er(i)});return n.values=t,n.Provider=n,n[Of]=Sb(t),Ei.push(n),n},Ki=e=>e.values.at(-1),$a={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Od={},ka="data-precedence",zs=e=>Array.isArray(e)?e:[e],Th=new WeakMap,Oh=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Th.get(s)||{};Th.set(s,a);const c=a[e]||=[];let u=!1;const l=$a[e];if(l.length>0){e:for(const[,d]of c)for(const f of l)if((d?.[f]??null)===n?.[f]){u=!0;break e}}if(u?i[0]=i[0].replaceAll(t,""):l.length>0?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let d;if(r===void 0)d=c.map(([f])=>f);else{const f=[];d=c.map(([p,,h])=>{let g=f.indexOf(h);return g===-1&&(f.push(h),g=f.length-1),[p,g]}).sort((p,h)=>p[1]-h[1]).map(([p])=>p)}d.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,d.join(""))}},As=(e,t,n)=>er(new Qt(e,n,zs(t??[])).toString()),Es=(e,t,n,r)=>{if("itemProp"in n)return As(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ka]=i);const c=new Qt(e,a,zs(t||[])).toString();return c instanceof Promise?c.then(u=>er(c,[...u.callbacks||[],Oh(e,u,a,i)])):er(c,[Oh(e,c,a,i)])},b5=({children:e,...t})=>{const n=Pf();if(n){const r=Ki(n);if(r==="svg"||r==="head")return new Qt("title",t,zs(e??[]))}return Es("title",e,t,!1)},w5=({children:e,...t})=>{const n=Pf();return["src","async"].some(r=>!t[r])||n&&Ki(n)==="head"?As("script",e,t):Es("script",e,t,!1)},v5=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,Es("style",e,t,!0)):As("style",e,t),x5=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?As("link",e,t):Es("link",e,t,"precedence"in t),$5=({children:e,...t})=>{const n=Pf();return n&&Ki(n)==="head"?As("meta",e,t):Es("meta",e,t,!1)},Eb=(e,{children:t,...n})=>new Qt(e,n,zs(t??[])),k5=e=>(typeof e.action=="function"&&(e.action=ec in e.action?e.action[ec]:void 0),Eb("form",e)),Cb=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=ec in t.formAction?t.formAction[ec]:void 0),Eb(e,t)),S5=e=>Cb("input",e),z5=e=>Cb("button",e);const pl=Object.freeze(Object.defineProperty({__proto__:null,button:z5,form:k5,input:S5,link:x5,meta:$5,script:w5,style:v5,title:b5},Symbol.toStringTag,{value:"Module"}));var A5=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),tc=e=>A5.get(e)||e,Ib=(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)}},ts=void 0,Pf=()=>ts,E5=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,C5=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],I5=["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"],Rf=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")vi(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof Qt?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):Rf(i,t)}}},Qt=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?_5(er(e[0],e.callbacks)).toString():e[0]:m5(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=ts&&Ki(ts)==="svg"?s=>E5(tc(s)):s=>tc(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";Ib(a,(u,l)=>{l!=null&&(c+=`${c?";":""}${u}:${l}`)}),e[0]+=' style="',vi(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,vi(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&I5.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=[er(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}="`,vi(a.toString(),e),e[0]+='"'}if(C5.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",Rf(r,e),e[0]+=`</${t}>`}},fl=class extends Qt{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(Ei.length===0)e.unshift("",r);else{const i=Ei.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof Qt&&(s.localContexts=i),s)))}else r instanceof Qt?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):vi(r,e)}},Nb=class extends Qt{toStringToBuffer(e){Rf(this.children,e)}},N5=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Sa(e,t,n);return i.key=r,i},Ph=!1,Sa=(e,t,n)=>{if(!Ph){for(const r in Od)pl[r][Of]=Od[r];Ph=!0}return typeof e=="function"?new fl(e,t,n):pl[e]?new fl(pl[e],t,n):e==="svg"||e==="head"?(ts||=Ab(""),new Qt(e,t,[new fl(ts,{value:e},n)])):new Qt(e,t,n)},ns=({children:e})=>new Nb("",{children:e},Array.isArray(e)?e:e?[e]:[]),j5=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return N5(e.tag,{...e.props,...t},...r)};function _(e,t,n){let r;if(!t||!("children"in t))r=Sa(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Sa(e,t,i):Sa(e,t,[i])}return r.key=n,r}var Rh;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(Rh||(Rh={}));var Lh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Lh||(Lh={}));function T5(e){return jb(e,O5,rs.Include)}function Lf(e){return jb(e,P5,rs.None)}function jb(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===rs.Include&&(r+="=")}return r}const O5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",P5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var rs;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(rs||(rs={}));var Dh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Dh||(Dh={}));class R5{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 Bh=new R5;function an(e,t){return(e<<32-t|e>>>t)>>>0}function L5(e){const t=new D5;return t.update(e),t.digest()}class D5{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),Bh.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)Bh.putUint32(t,this.H[n],n*4);return t}process(){for(let l=0;l<16;l++)this.w[l]=(this.blocks[l*4]<<24|this.blocks[l*4+1]<<16|this.blocks[l*4+2]<<8|this.blocks[l*4+3])>>>0;for(let l=16;l<64;l++){const d=(an(this.w[l-2],17)^an(this.w[l-2],19)^this.w[l-2]>>>10)>>>0,f=(an(this.w[l-15],7)^an(this.w[l-15],18)^this.w[l-15]>>>3)>>>0;this.w[l]=d+this.w[l-7]+f+this.w[l-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],u=this.H[7];for(let l=0;l<64;l++){const d=(an(s,6)^an(s,11)^an(s,25))>>>0,f=(s&a^~s&c)>>>0,p=u+d+f+B5[l]+this.w[l]|0,h=(an(t,2)^an(t,13)^an(t,22))>>>0,g=(t&n^t&r^n&r)>>>0,y=h+g|0;u=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+y|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]=u+this.H[7]|0}}const B5=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 Tb{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 Ob(e){const t=L5(new TextEncoder().encode(e));return Lf(t)}function eu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Lf(e)}function Pb(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Lf(e)}function U5(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 Uh(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 Mh(e,...t){let n=Uh(e,"/");for(const r of t)n=Uh(n,"/")+"/"+U5(r,"/");return n}function Cn(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 Sr(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return T5(n)}async function Ci(e){let t;try{t=await fetch(e)}catch(n){throw new Bf(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);let r;try{r=Df(n)}catch{throw new Jn(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);return new Tb(n)}throw t.body!==null&&await t.body.cancel(),new xi(t.status)}async function M5(e){let t;try{t=await fetch(e)}catch(n){throw new Bf(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new Jn(t.status,null)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);let r;try{r=Df(n)}catch{throw new Jn(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 xi(t.status)}function Df(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 q5(t,n,r,i)}class Bf extends Error{constructor(t){super("Failed to send request",{cause:t})}}class q5 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 xi extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class Jn extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Gr{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===Ir.S256){const c=Ob(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===Ir.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=Cn(t,i);if(this.clientPassword!==null){const c=Sr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ci(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=Cn(t,i);if(this.clientPassword!==null){const c=Sr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ci(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Cn(t,r);if(this.clientPassword!==null){const s=Sr(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await M5(i)}}var Ir;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(Ir||(Ir={}));var qh;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(qh||(qh={}));var Fh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Fh||(Fh={}));function qo(e){return F5(e,H5,nc.None)}function F5(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===nc.Include&&(r+="=")}return r}const H5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var nc;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(nc||(nc={}));var Hh;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(Hh||(Hh={}));function V5(e,t,n){const r=qo(new TextEncoder().encode(e)),i=qo(new TextEncoder().encode(t)),s=qo(n);return r+"."+i+"."+s}function K5(e,t){const n=qo(new TextEncoder().encode(e)),r=qo(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const G5="https://appleid.apple.com/auth/authorize",W5="https://appleid.apple.com/auth/token";class Rb{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(G5);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=Cn(W5,n);return await Ci(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,K5(r,i)));return V5(r,i,s)}}const J5="https://www.facebook.com/v16.0/dialog/oauth",X5="https://graph.facebook.com/v16.0/oauth/access_token";class Lb{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(J5);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=Cn(X5,n);return await Ci(r)}}const Z5="https://github.com/login/oauth/authorize",Vh="https://github.com/login/oauth/access_token";class Db{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(Z5);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=Cn(Vh,n),i=Sr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await Kh(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Cn(Vh,n),i=Sr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await Kh(r)}}async function Kh(e){let t;try{t=await fetch(e)}catch(i){throw new Bf(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new xi(t.status);let n;try{n=await t.json()}catch{throw new xi(t.status)}if(typeof n!="object"||n===null)throw new Jn(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Df(n)}catch{throw new Jn(t.status,n)}throw i}return new Tb(n)}const Y5="https://accounts.google.com/o/oauth2/v2/auth",Gh="https://oauth2.googleapis.com/token",Q5="https://oauth2.googleapis.com/revoke";let Bb=class{client;constructor(t,n,r){this.client=new Gr(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(Y5,t,Ir.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(Gh,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(Gh,t,[])}async revokeToken(t){await this.client.revokeToken(Q5,t)}};class Ub{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=Mh("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=Mh("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=Ob(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=Cn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=Sr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Ci(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=Cn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=Sr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Ci(i)}}const Gi=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();Gi.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function tu(e){return e.ISSUER}function nt(e){return e.UNIVERSAL_LOGIN_URL||`${e.ISSUER}u/`}function Te(e){return e.OAUTH_API_URL||e.ISSUER}const e8="Apple",t8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M45 0H0V45H45V0Z",fill:"white"}),_("path",{d:"M23.5344 10.3846C25.5313 10.3846 28.0344 9.01144 29.525 7.18055C30.875 5.5213 31.8594 3.20407 31.8594 0.886839C31.8594 0.572154 31.8313 0.25747 31.775 0C29.5531 0.0858233 26.8813 1.51621 25.2781 3.43293C24.0125 4.89193 22.8594 7.18055 22.8594 9.52638C22.8594 9.86968 22.9156 10.213 22.9438 10.3274C23.0844 10.356 23.3094 10.3846 23.5344 10.3846ZM16.5031 45C19.2313 45 20.4406 43.1405 23.8438 43.1405C27.3031 43.1405 28.0625 44.9428 31.1 44.9428C34.0813 44.9428 36.0781 42.1392 37.9625 39.3929C40.0719 36.246 40.9438 33.1564 41 33.0134C40.8031 32.9561 35.0938 30.5817 35.0938 23.9161C35.0938 18.1373 39.5938 15.534 39.8469 15.3338C36.8656 10.9854 32.3375 10.8709 31.1 10.8709C27.7531 10.8709 25.025 12.9307 23.3094 12.9307C21.4531 12.9307 19.0063 10.9854 16.1094 10.9854C10.5969 10.9854 5 15.6198 5 24.3738C5 29.8093 7.08125 35.5594 9.64063 39.2784C11.8344 42.4253 13.7469 45 16.5031 45Z",fill:"black"})]});function Mb(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 n8(e,t){const{options:n,keyArray:r}=Mb(t),i=`${Te(e.env)}callback`,s=new Rb(n.client_id,n.team_id,n.kid,r,i),a=Ne(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(l=>["email","name"].includes(l))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function r8(e,t,n){const{options:r,keyArray:i}=Mb(t),a=await new Rb(r.client_id,r.team_id,r.kid,i,`${Te(e.env)}callback`).validateAuthorizationCode(n),c=ks(a.idToken());if(!c)throw new Error("Invalid ID token");const u=Gi.parse(c.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture,locale:u.locale}}const i8=Object.freeze(Object.defineProperty({__proto__:null,displayName:e8,getRedirect:n8,logo:t8,validateAuthorizationCodeAndGetUser:r8},Symbol.toStringTag,{value:"Module"})),o8="Facebook",s8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M45 22.5C45 10.0736 34.9264 0 22.5 0C10.0736 0 0 10.0736 0 22.5C0 33.7031 8.23242 42.9785 19.0039 44.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039 11.8945 22.3828 8.75977 27.5391 8.75977C29.9658 8.75977 32.5049 9.19922 32.5049 9.19922V14.7656H29.7012C26.9414 14.7656 26.0156 16.4824 26.0156 18.2432V22.5H32.2412L31.2012 28.9746H26.0156V44.6953C36.7871 42.9785 45 33.7031 45 22.5Z",fill:"#1877F2"}),_("path",{d:"M31.2012 28.9746L32.2412 22.5H26.0156V18.2432C26.0156 16.4824 26.9414 14.7656 29.7012 14.7656H32.5049V9.19922C32.5049 9.19922 29.9658 8.75977 27.5391 8.75977C22.3828 8.75977 19.0039 11.8945 19.0039 17.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562 44.8984 21.3203 45 22.5 45C23.6797 45 24.8438 44.8984 26.0156 44.6953V28.9746H31.2012Z",fill:"white"})]});async function a8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Te(e.env)}callback`,i=new Lb(n.client_id,n.client_secret,r),s=Ne();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function c8(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 Lb(r.client_id,r.client_secret,`${Te(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 u8=Object.freeze(Object.defineProperty({__proto__:null,displayName:o8,getRedirect:a8,logo:s8,validateAuthorizationCodeAndGetUser:c8},Symbol.toStringTag,{value:"Module"})),l8="Google",d8=!0,p8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M44.1035 23.0123C44.1054 21.4791 43.9758 19.9486 43.716 18.4375H22.498V27.1028H34.6507C34.4021 28.4868 33.8757 29.8061 33.1034 30.9812C32.3311 32.1562 31.3289 33.1628 30.1571 33.9401V39.5649H37.41C41.6567 35.6494 44.1035 29.859 44.1035 23.0123Z",fill:"#4285F4"}),_("path",{d:"M22.4982 44.9997C28.5698 44.9997 33.6821 43.0061 37.4101 39.5687L30.1573 33.9439C28.1386 35.3126 25.5387 36.0938 22.4982 36.0938C16.6296 36.0938 11.6485 32.1377 9.86736 26.8066H2.39575V32.6033C4.26839 36.3297 7.13989 39.4622 10.6896 41.6512C14.2394 43.8402 18.3277 44.9995 22.4982 44.9997Z",fill:"#34A853"}),_("path",{d:"M9.86737 26.8073C8.92572 24.0138 8.92572 20.9886 9.86737 18.1951V12.3984H2.39576C0.820432 15.5332 0 18.9929 0 22.5012C0 26.0095 0.820432 29.4692 2.39576 32.604L9.86737 26.8073Z",fill:"#FBBC04"}),_("path",{d:"M22.4982 8.90741C25.7068 8.85499 28.8071 10.0673 31.1291 12.2823L37.5507 5.86064C33.4788 2.03602 28.0843 -0.0637686 22.4982 0.00147616C18.3277 0.00166623 14.2394 1.16098 10.6896 3.34999C7.13989 5.539 4.26839 8.67155 2.39575 12.3979L9.86736 18.1946C11.6485 12.8635 16.6296 8.90741 22.4982 8.90741Z",fill:"#EA4335"})]});async function f8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Te(e.env)}callback`,i=new Bb(n.client_id,n.client_secret,r),s=Ne(),a=eu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function h8(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 Bb(i.client_id,i.client_secret,`${Te(e.env)}callback`).validateAuthorizationCode(n,r),c=ks(a.idToken());if(!c)throw new Error("Invalid ID token");const u=Gi.parse(c.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture,locale:u.locale}}const g8=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:d8,displayName:l8,getRedirect:f8,logo:p8,validateAuthorizationCodeAndGetUser:h8},Symbol.toStringTag,{value:"Module"})),m8="Vipps",_8=({className:e=""})=>_("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",width:"45",height:"45",className:e,children:[_("path",{fill:"#FF5B24",d:"M3.5,8h41c1.9,0,3.5,1.6,3.5,3.5v25c0,1.9-1.6,3.5-3.5,3.5h-41C1.6,40,0,38.4,0,36.5v-25C0,9.6,1.6,8,3.5,8z"}),_("path",{fillRule:"evenodd",clipRule:"evenodd",fill:"#FFFFFF",d:`M27.9,20.3c1.4,0,2.6-1,2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4,0-2.6,1-2.6,2.5C25.3,19.2,26.5,20.3,27.9,20.3z
66
66
  M31.2,24.4c-1.7,2.2-3.5,3.8-6.7,3.8h0c-3.2,0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8,0.6-1,1.8-0.3,2.9
67
67
  c2.7,4.1,6.5,6.6,10.9,6.6c4,0,7.2-2,9.6-5.2c0.9-1.2,0.9-2.5,0-3.1C33.3,22.9,32.1,23.2,31.2,24.4z`})]});async function y8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Gr(n.client_id,n.client_secret,`${Te(e.env)}callback`),i=Ne(),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 b8(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 Gr(r.client_id,r.client_secret,`${Te(e.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=ks(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Gi.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const u=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!u.ok)throw new X(400,{message:"Failed to get user from vipps"});return await u.json()}const w8=Object.freeze(Object.defineProperty({__proto__:null,displayName:m8,getRedirect:y8,logo:_8,validateAuthorizationCodeAndGetUser:b8},Symbol.toStringTag,{value:"Module"})),v8="GitHub",x8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:_("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.5 0C10.074 0 0 10.335 0 23.077C0 33.266 6.444 41.895 15.39 44.955C16.515 45.165 16.935 44.46 16.935 43.857C16.935 43.32 16.92 41.865 16.905 39.99C10.65 41.355 9.33 36.99 9.33 36.99C8.31 34.32 6.825 33.615 6.825 33.615C4.77 32.205 6.975 32.235 6.975 32.235C9.24 32.385 10.425 34.59 10.425 34.59C12.45 38.13 15.75 37.125 17.01 36.555C17.22 35.07 17.82 34.065 18.48 33.51C13.455 32.94 8.19 30.93 8.19 22.035C8.19 19.5 9.075 17.43 10.47 15.81C10.23 15.24 9.435 12.87 10.695 9.66C10.695 9.66 12.585 9.045 16.875 12.06C18.675 11.565 20.595 11.31 22.5 11.31C24.405 11.31 26.325 11.565 28.125 12.06C32.415 9.045 34.305 9.66 34.305 9.66C35.565 12.87 34.77 15.24 34.53 15.81C35.925 17.43 36.81 19.5 36.81 22.035C36.81 30.96 31.53 32.925 26.49 33.48C27.33 34.2 28.095 35.625 28.095 37.815C28.095 40.95 28.065 43.47 28.065 43.857C28.065 44.46 28.485 45.18 29.625 44.955C38.571 41.88 45 33.252 45 23.077C45 10.335 34.926 0 22.5 0Z",fill:"currentColor"})});async function $8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${Te(e.env)}callback`,i=new Db(n.client_id,n.client_secret,r),s=Ne();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function k8(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 Db(r.client_id,r.client_secret,`${Te(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(),u=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});let l=c.email;if(u.ok){const d=await u.json(),f=d.find(p=>p.primary&&p.verified)||d.find(p=>p.verified);f&&(l=f.email)}return e.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:l,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const S8=Object.freeze(Object.defineProperty({__proto__:null,displayName:v8,getRedirect:$8,logo:x8,validateAuthorizationCodeAndGetUser:k8},Symbol.toStringTag,{value:"Module"})),z8="Microsoft",A8=({className:e=""})=>_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{fill:"#F25022",d:"M0 0H21.43V21.43H0V0Z"}),_("path",{fill:"#7FBA00",d:"M23.57 0H45V21.43H23.57V0Z"}),_("path",{fill:"#00A4EF",d:"M0 23.57H21.43V45H0V23.57Z"}),_("path",{fill:"#FFB900",d:"M23.57 23.57H45V45H23.57V23.57Z"})]});async function E8(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${Te(e.env)}callback`,i=n.realms||"common",s=new Ub(i,n.client_id,n.client_secret,r),a=Ne(),c=eu();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function C8(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 Ub(s,i.client_id,i.client_secret,`${Te(e.env)}callback`).validateAuthorizationCode(n,r),u=ks(c.idToken());if(!u)throw new Error("Invalid ID token");const l=Gi.parse(u.payload);return e.set("log",`Microsoft user: ${JSON.stringify(l)}`),{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture}}const I8=Object.freeze(Object.defineProperty({__proto__:null,displayName:z8,getRedirect:E8,logo:A8,validateAuthorizationCodeAndGetUser:C8},Symbol.toStringTag,{value:"Module"})),N8="OpenID Connect",j8=({className:e="",iconUrl:t})=>t?_("img",{src:t,alt:"OIDC Provider",className:e}):_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:[_("path",{d:"M22.5 0C10.074 0 0 10.074 0 22.5S10.074 45 22.5 45 45 34.926 45 22.5 34.926 0 22.5 0zm0 40.5c-9.941 0-18-8.059-18-18s8.059-18 18-18 18 8.059 18 18-8.059 18-18 18z",fill:"currentColor"}),_("path",{d:"M22.5 9c-7.456 0-13.5 6.044-13.5 13.5S15.044 36 22.5 36 36 29.956 36 22.5 29.956 9 22.5 9zm0 22.5c-4.971 0-9-4.029-9-9s4.029-9 9-9 9 4.029 9 9-4.029 9-9 9z",fill:"currentColor"})]});async function T8(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${Te(e.env)}callback`,i=new Gr(n.client_id,n.client_secret||null,r),s=Pb(),a=eu(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,Ir.S256,a,c).href,code:s,codeVerifier:a}}async function O8(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Te(e.env)}callback`,c=await new Gr(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const l=ks(c.idToken());if(l?.payload){const d=Gi.passthrough().parse(l.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 l=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!l.ok)throw new Error("Failed to fetch user info");const d=await l.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 P8=Object.freeze(Object.defineProperty({__proto__:null,displayName:N8,getRedirect:T8,logo:j8,validateAuthorizationCodeAndGetUser:O8},Symbol.toStringTag,{value:"Module"})),R8="OAuth 2.0",L8=({className:e="",iconUrl:t})=>t?_("img",{src:t,alt:"OAuth Provider",className:e}):_("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:e,children:_("path",{d:"M31.5 18h-1.5v-4.5c0-4.136-3.364-7.5-7.5-7.5s-7.5 3.364-7.5 7.5v4.5h-1.5c-1.657 0-3 1.343-3 3v15c0 1.657 1.343 3 3 3h18c1.657 0 3-1.343 3-3v-15c0-1.657-1.343-3-3-3zm-12-4.5c0-2.481 2.019-4.5 4.5-4.5s4.5 2.019 4.5 4.5v4.5h-9v-4.5zm12 22.5h-18v-15h18v15zm-9-6c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3z",fill:"currentColor"})});async function D8(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${Te(e.env)}callback`,i=new Gr(n.client_id,n.client_secret||null,r),s=Pb(),a=eu(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,Ir.S256,a,c).href,code:s,codeVerifier:a}}async function B8(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Te(e.env)}callback`,c=await new Gr(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 u=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!u.ok)throw new Error("Failed to fetch user info");const l=await u.json(),d=l.sub||l.id||l.user_id;if(!d)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:d,email:l.email,given_name:l.given_name||l.first_name,family_name:l.family_name||l.last_name,name:l.name||`${l.given_name||l.first_name||""} ${l.family_name||l.last_name||""}`.trim()}}const U8=Object.freeze(Object.defineProperty({__proto__:null,displayName:R8,getRedirect:D8,logo:L8,validateAuthorizationCodeAndGetUser:B8},Symbol.toStringTag,{value:"Module"})),Uf={apple:i8,facebook:u8,"google-oauth2":g8,vipps:w8,github:S8,microsoft:I8,oidc:P8,oauth2:U8};function qb(e,t){const n=e.env.STRATEGIES||{},i={...Uf,...n}[t];if(!i)throw new Error(`Strategy ${t} not found`);return i}const M8=new Set(["oidc","samlp","waad","adfs","oauth2"]);function q8(e){return M8.has(e.strategy)?e.name:e.strategy}const Wh=wt.extend({users:o.z.array(ln)}),F8=wt.extend({sessions:o.z.array(Wc)}),H8=wt.extend({organizations:o.z.array(Vn)}),V8=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:Qe,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(ln),Wh])}},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 l=s.split("=")[1],f=(await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,q:`email:${l}`})).users.filter(g=>g.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 C(500,{message:"Primary account not found"});return e.json([ln.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:ct(i),q:a.join(" ")}),u=c.users.filter(l=>!l.linked_to);return r?e.json(Wh.parse({users:u,length:c.length,start:c.start,limit:c.limit})):e.json(o.z.array(ln).parse(u))}).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:ln}},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 C(404);if(n.linked_to)throw new C(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 C(404);return await _e(e,e.var.tenant_id,{type:he.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({...Ba.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["create:users","auth:write"]}],responses:{201:{content:{"application/json":{schema:ln}},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:u,password:l}=t,d=await e.env.data.connections.get(e.var.tenant_id,u),f=d?q8(d):c||u,p=t.user_id,h=p?na(p):$s(),g=`${f}|${h}`;try{const y={email:n,user_id:g,name:i||n||r,phone_number:r,provider:f,connection:u,linked_to:s??void 0,email_verified:a||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString()},w=await e.env.data.users.create(e.var.tenant_id,y);if(l){const x={user_id:g,password:await Yn.hash(l,10),algorithm:"bcrypt",is_current:!0};await e.env.data.passwords.create(e.var.tenant_id,x)}e.set("user_id",w.user_id),await _e(e,e.var.tenant_id,{type:he.SUCCESS_API_OPERATION,description:"User created"});const m=w.identities?w:{...w,identities:[{connection:w.connection,provider:w.provider,user_id:na(w.user_id),isSocial:w.is_social}]};return e.json(ln.parse(m),{status:201})}catch(y){throw y.message==="User already exists"?new C(409,{message:"User already exists"}):y}}).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({...Ba.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,u=await t.users.get(e.var.tenant_id,r);if(!u)throw new C(404);if(u.linked_to)throw new C(404,{message:"User is linked to another user"});let l=r,d=u;if(a)if(u.connection===a)l=r,d=u;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(g=>g.connection===a);if(!h)throw new C(404,{message:`No identity found with connection: ${a}`});l=h.user_id,d=h}if(c.email&&c.email!==d.email){const p=await Tf(e.env.data.users,e.var.tenant_id,c.email);if(p.length&&p.some(h=>h.user_id!==l))throw new C(409,{message:"Another user with the same email address already exists."})}if(await e.env.data.users.update(e.var.tenant_id,l,c),s){let p;if(a)if(a==="Username-Password-Authentication")p={provider:d.provider,user_id:na(l)};else throw new C(400,{message:`Cannot set password for connection: ${a}`});else if(p=u.identities?.find(y=>y.connection==="Username-Password-Authentication"),!p)throw new C(400,{message:"User does not have a password identity"});const h=`${p.provider}|${p.user_id}`,g=await t.passwords.get(e.var.tenant_id,h);g&&await t.passwords.update(e.var.tenant_id,{id:g.id,user_id:h,password:g.password,algorithm:g.algorithm,is_current:!1}),await t.passwords.create(e.var.tenant_id,{user_id:h,password:await Yn.hash(s,10),algorithm:"bcrypt",is_current:!0})}const f=await e.env.data.users.get(e.var.tenant_id,r);if(!f)throw new C(500);return await _e(e,e.var.tenant_id,{type:he.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(o.z.object({connection:o.z.string(),provider:o.z.string(),user_id:o.z.string(),isSocial:o.z.boolean()}))}},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 C(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(c=>({connection:c.connection,provider:c.provider,user_id:na(c.user_id),isSocial:c.is_social}));return e.json(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(ln)}},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 C(404);return e.json([ln.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:Qe,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(Wc),F8])}},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:Qe},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:Hy}},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 C(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:ct(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 C(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 C(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 C(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 C(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:Wa}},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 C(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 C(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 C(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 C(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 C(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:Qe,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([H8,o.z.array(Vn)])}},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 C(404,{message:"User not found"});const c=await e.env.data.userOrganizations.listUserOrganizations(e.var.tenant_id,t,{page:n,per_page:r,sort:ct(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 C(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 C(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 Jh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Fb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function K8(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var Xh={};var Zh;function G8(){if(Zh)return Xh;Zh=1;var e;return(function(t){(function(n){var r=typeof globalThis=="object"?globalThis:typeof Jh=="object"?Jh:typeof self=="object"?self:typeof this=="object"?this:u(),i=s(t);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(l,d){return function(f,p){Object.defineProperty(l,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 u(){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",u=typeof Object.create=="function",l={__proto__:[]}instanceof Array,d=!u&&!l,f={create:u?function(){return ul(Object.create(null))}:l?function(){return ul({__proto__:null})}:function(){return ul({})},has:d?function(T,P){return i.call(T,P)}:function(T,P){return P in T},get:d?function(T,P){return i.call(T,P)?T[P]:void 0}:function(T,P){return T[P]}},p=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ea(),g=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:cl(),y=typeof WeakMap=="function"?WeakMap:r3(),w=s?Symbol.for("@reflect-metadata:registry"):void 0,m=vn(),x=Ut(m);function $(T,P,U,J){if(F(U)){if(!Z(T))throw new TypeError;if(!pe(P))throw new TypeError;return q(T,P)}else{if(!Z(T))throw new TypeError;if(!ue(P))throw new TypeError;if(!ue(J)&&!F(J)&&!Le(J))throw new TypeError;return Le(J)&&(J=void 0),U=D(U),K(T,P,U,J)}}n("decorate",$);function k(T,P){function U(J,ce){if(!ue(J))throw new TypeError;if(!F(ce)&&!We(ce))throw new TypeError;we(T,P,J,ce)}return U}n("metadata",k);function v(T,P,U,J){if(!ue(U))throw new TypeError;return F(J)||(J=D(J)),we(T,P,U,J)}n("defineMetadata",v);function z(T,P,U){if(!ue(P))throw new TypeError;return F(U)||(U=D(U)),B(T,P,U)}n("hasMetadata",z);function A(T,P,U){if(!ue(P))throw new TypeError;return F(U)||(U=D(U)),oe(T,P,U)}n("hasOwnMetadata",A);function N(T,P,U){if(!ue(P))throw new TypeError;return F(U)||(U=D(U)),ae(T,P,U)}n("getMetadata",N);function R(T,P,U){if(!ue(P))throw new TypeError;return F(U)||(U=D(U)),se(T,P,U)}n("getOwnMetadata",R);function L(T,P){if(!ue(T))throw new TypeError;return F(P)||(P=D(P)),Ee(T,P)}n("getMetadataKeys",L);function E(T,P){if(!ue(T))throw new TypeError;return F(P)||(P=D(P)),Ce(T,P)}n("getOwnMetadataKeys",E);function O(T,P,U){if(!ue(P))throw new TypeError;if(F(U)||(U=D(U)),!ue(P))throw new TypeError;F(U)||(U=D(U));var J=dr(P,U,!1);return F(J)?!1:J.OrdinaryDeleteMetadata(T,P,U)}n("deleteMetadata",O);function q(T,P){for(var U=T.length-1;U>=0;--U){var J=T[U],ce=J(P);if(!F(ce)&&!Le(ce)){if(!pe(ce))throw new TypeError;P=ce}}return P}function K(T,P,U,J){for(var ce=T.length-1;ce>=0;--ce){var qe=T[ce],Xe=qe(P,U,J);if(!F(Xe)&&!Le(Xe)){if(!ue(Xe))throw new TypeError;J=Xe}}return J}function B(T,P,U){var J=oe(T,P,U);if(J)return!0;var ce=$e(P);return Le(ce)?!1:B(T,ce,U)}function oe(T,P,U){var J=dr(P,U,!1);return F(J)?!1:Yr(J.OrdinaryHasOwnMetadata(T,P,U))}function ae(T,P,U){var J=oe(T,P,U);if(J)return se(T,P,U);var ce=$e(P);if(!Le(ce))return ae(T,ce,U)}function se(T,P,U){var J=dr(P,U,!1);if(!F(J))return J.OrdinaryGetOwnMetadata(T,P,U)}function we(T,P,U,J){var ce=dr(U,J,!0);ce.OrdinaryDefineOwnMetadata(T,P,U,J)}function Ee(T,P){var U=Ce(T,P),J=$e(T);if(J===null)return U;var ce=Ee(J,P);if(ce.length<=0)return U;if(U.length<=0)return ce;for(var qe=new g,Xe=[],ye=0,Y=U;ye<Y.length;ye++){var te=Y[ye],re=qe.has(te);re||(qe.add(te),Xe.push(te))}for(var ie=0,be=ce;ie<be.length;ie++){var te=be[ie],re=qe.has(te);re||(qe.add(te),Xe.push(te))}return Xe}function Ce(T,P){var U=dr(T,P,!1);return U?U.OrdinaryOwnMetadataKeys(T,P):[]}function Ge(T){if(T===null)return 1;switch(typeof T){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return T===null?1:6;default:return 6}}function F(T){return T===void 0}function Le(T){return T===null}function Bt(T){return typeof T=="symbol"}function ue(T){return typeof T=="object"?T!==null:typeof T=="function"}function $t(T,P){switch(Ge(T)){case 0:return T;case 1:return T;case 2:return T;case 3:return T;case 4:return T;case 5:return T}var U="string",J=sl(T,a);if(J!==void 0){var ce=J.call(T,U);if(ue(ce))throw new TypeError;return ce}return uo(T)}function uo(T,P){var U,J,ce;{var qe=T.toString;if(V(qe)){var J=qe.call(T);if(!ue(J))return J}var U=T.valueOf;if(V(U)){var J=U.call(T);if(!ue(J))return J}}throw new TypeError}function Yr(T){return!!T}function Qr(T){return""+T}function D(T){var P=$t(T);return Bt(P)?P:Qr(P)}function Z(T){return Array.isArray?Array.isArray(T):T instanceof Object?T instanceof Array:Object.prototype.toString.call(T)==="[object Array]"}function V(T){return typeof T=="function"}function pe(T){return typeof T=="function"}function We(T){switch(Ge(T)){case 3:return!0;case 4:return!0;default:return!1}}function Je(T,P){return T===P||T!==T&&P!==P}function sl(T,P){var U=T[P];if(U!=null){if(!V(U))throw new TypeError;return U}}function al(T){var P=sl(T,c);if(!V(P))throw new TypeError;var U=P.call(T);if(!ue(U))throw new TypeError;return U}function Se(T){return T.value}function xe(T){var P=T.next();return P.done?!1:P}function ei(T){var P=T.return;P&&P.call(T)}function $e(T){var P=Object.getPrototypeOf(T);if(typeof T!="function"||T===p||P!==p)return P;var U=T.prototype,J=U&&Object.getPrototypeOf(U);if(J==null||J===Object.prototype)return P;var ce=J.constructor;return typeof ce!="function"||ce===T?P:ce}function ze(){var T;!F(w)&&typeof r.Reflect<"u"&&!(w in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(T=kt(r.Reflect));var P,U,J,ce=new y,qe={registerProvider:Xe,getProvider:Y,setProvider:re};return qe;function Xe(ie){if(!Object.isExtensible(qe))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case T===ie:break;case F(P):P=ie;break;case P===ie:break;case F(U):U=ie;break;case U===ie:break;default:J===void 0&&(J=new g),J.add(ie);break}}function ye(ie,be){if(!F(P)){if(P.isProviderFor(ie,be))return P;if(!F(U)){if(U.isProviderFor(ie,be))return P;if(!F(J))for(var je=al(J);;){var Fe=xe(je);if(!Fe)return;var Mt=Se(Fe);if(Mt.isProviderFor(ie,be))return ei(je),Mt}}}if(!F(T)&&T.isProviderFor(ie,be))return T}function Y(ie,be){var je=ce.get(ie),Fe;return F(je)||(Fe=je.get(be)),F(Fe)&&(Fe=ye(ie,be),F(Fe)||(F(je)&&(je=new h,ce.set(ie,je)),je.set(be,Fe))),Fe}function te(ie){if(F(ie))throw new TypeError;return P===ie||U===ie||!F(J)&&J.has(ie)}function re(ie,be,je){if(!te(je))throw new Error("Metadata provider not registered.");var Fe=Y(ie,be);if(Fe!==je){if(!F(Fe))return!1;var Mt=ce.get(ie);F(Mt)&&(Mt=new h,ce.set(ie,Mt)),Mt.set(be,je)}return!0}}function vn(){var T;return!F(w)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&(T=r.Reflect[w]),F(T)&&(T=ze()),!F(w)&&ue(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,w,{enumerable:!1,configurable:!1,writable:!1,value:T}),T}function Ut(T){var P=new y,U={isProviderFor:function(te,re){var ie=P.get(te);return F(ie)?!1:ie.has(re)},OrdinaryDefineOwnMetadata:Xe,OrdinaryHasOwnMetadata:ce,OrdinaryGetOwnMetadata:qe,OrdinaryOwnMetadataKeys:ye,OrdinaryDeleteMetadata:Y};return m.registerProvider(U),U;function J(te,re,ie){var be=P.get(te),je=!1;if(F(be)){if(!ie)return;be=new h,P.set(te,be),je=!0}var Fe=be.get(re);if(F(Fe)){if(!ie)return;if(Fe=new h,be.set(re,Fe),!T.setProvider(te,re,U))throw be.delete(re),je&&P.delete(te),new Error("Wrong provider for target.")}return Fe}function ce(te,re,ie){var be=J(re,ie,!1);return F(be)?!1:Yr(be.has(te))}function qe(te,re,ie){var be=J(re,ie,!1);if(!F(be))return be.get(te)}function Xe(te,re,ie,be){var je=J(ie,be,!0);je.set(te,re)}function ye(te,re){var ie=[],be=J(te,re,!1);if(F(be))return ie;for(var je=be.keys(),Fe=al(je),Mt=0;;){var th=xe(Fe);if(!th)return ie.length=Mt,ie;var i3=Se(th);try{ie[Mt]=i3}catch(o3){try{ei(Fe)}finally{throw o3}}Mt++}}function Y(te,re,ie){var be=J(re,ie,!1);if(F(be)||!be.delete(te))return!1;if(be.size===0){var je=P.get(re);F(je)||(je.delete(ie),je.size===0&&P.delete(je))}return!0}}function kt(T){var P=T.defineMetadata,U=T.hasOwnMetadata,J=T.getOwnMetadata,ce=T.getOwnMetadataKeys,qe=T.deleteMetadata,Xe=new y,ye={isProviderFor:function(Y,te){var re=Xe.get(Y);return!F(re)&&re.has(te)?!0:ce(Y,te).length?(F(re)&&(re=new g,Xe.set(Y,re)),re.add(te),!0):!1},OrdinaryDefineOwnMetadata:P,OrdinaryHasOwnMetadata:U,OrdinaryGetOwnMetadata:J,OrdinaryOwnMetadataKeys:ce,OrdinaryDeleteMetadata:qe};return ye}function dr(T,P,U){var J=m.getProvider(T,P);if(!F(J))return J;if(U){if(m.setProvider(T,P,x))return x;throw new Error("Illegal state.")}}function ea(){var T={},P=[],U=(function(){function ye(Y,te,re){this._index=0,this._keys=Y,this._values=te,this._selector=re}return ye.prototype["@@iterator"]=function(){return this},ye.prototype[c]=function(){return this},ye.prototype.next=function(){var Y=this._index;if(Y>=0&&Y<this._keys.length){var te=this._selector(this._keys[Y],this._values[Y]);return Y+1>=this._keys.length?(this._index=-1,this._keys=P,this._values=P):this._index++,{value:te,done:!1}}return{value:void 0,done:!0}},ye.prototype.throw=function(Y){throw this._index>=0&&(this._index=-1,this._keys=P,this._values=P),Y},ye.prototype.return=function(Y){return this._index>=0&&(this._index=-1,this._keys=P,this._values=P),{value:Y,done:!0}},ye})(),J=(function(){function ye(){this._keys=[],this._values=[],this._cacheKey=T,this._cacheIndex=-2}return Object.defineProperty(ye.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ye.prototype.has=function(Y){return this._find(Y,!1)>=0},ye.prototype.get=function(Y){var te=this._find(Y,!1);return te>=0?this._values[te]:void 0},ye.prototype.set=function(Y,te){var re=this._find(Y,!0);return this._values[re]=te,this},ye.prototype.delete=function(Y){var te=this._find(Y,!1);if(te>=0){for(var re=this._keys.length,ie=te+1;ie<re;ie++)this._keys[ie-1]=this._keys[ie],this._values[ie-1]=this._values[ie];return this._keys.length--,this._values.length--,Je(Y,this._cacheKey)&&(this._cacheKey=T,this._cacheIndex=-2),!0}return!1},ye.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=T,this._cacheIndex=-2},ye.prototype.keys=function(){return new U(this._keys,this._values,ce)},ye.prototype.values=function(){return new U(this._keys,this._values,qe)},ye.prototype.entries=function(){return new U(this._keys,this._values,Xe)},ye.prototype["@@iterator"]=function(){return this.entries()},ye.prototype[c]=function(){return this.entries()},ye.prototype._find=function(Y,te){if(!Je(this._cacheKey,Y)){this._cacheIndex=-1;for(var re=0;re<this._keys.length;re++)if(Je(this._keys[re],Y)){this._cacheIndex=re;break}}return this._cacheIndex<0&&te&&(this._cacheIndex=this._keys.length,this._keys.push(Y),this._values.push(void 0)),this._cacheIndex},ye})();return J;function ce(ye,Y){return ye}function qe(ye,Y){return Y}function Xe(ye,Y){return[ye,Y]}}function cl(){var T=(function(){function P(){this._map=new h}return Object.defineProperty(P.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),P.prototype.has=function(U){return this._map.has(U)},P.prototype.add=function(U){return this._map.set(U,U),this},P.prototype.delete=function(U){return this._map.delete(U)},P.prototype.clear=function(){this._map.clear()},P.prototype.keys=function(){return this._map.keys()},P.prototype.values=function(){return this._map.keys()},P.prototype.entries=function(){return this._map.entries()},P.prototype["@@iterator"]=function(){return this.keys()},P.prototype[c]=function(){return this.keys()},P})();return T}function r3(){var T=16,P=f.create(),U=J();return(function(){function Y(){this._key=J()}return Y.prototype.has=function(te){var re=ce(te,!1);return re!==void 0?f.has(re,this._key):!1},Y.prototype.get=function(te){var re=ce(te,!1);return re!==void 0?f.get(re,this._key):void 0},Y.prototype.set=function(te,re){var ie=ce(te,!0);return ie[this._key]=re,this},Y.prototype.delete=function(te){var re=ce(te,!1);return re!==void 0?delete re[this._key]:!1},Y.prototype.clear=function(){this._key=J()},Y})();function J(){var Y;do Y="@@WeakMap@@"+ye();while(f.has(P,Y));return P[Y]=!0,Y}function ce(Y,te){if(!i.call(Y,U)){if(!te)return;Object.defineProperty(Y,U,{value:f.create()})}return Y[U]}function qe(Y,te){for(var re=0;re<te;++re)Y[re]=Math.random()*255|0;return Y}function Xe(Y){if(typeof Uint8Array=="function"){var te=new Uint8Array(Y);return typeof crypto<"u"?crypto.getRandomValues(te):typeof msCrypto<"u"?msCrypto.getRandomValues(te):qe(te,Y),te}return qe(new Array(Y),Y)}function ye(){var Y=Xe(T);Y[6]=Y[6]&79|64,Y[8]=Y[8]&191|128;for(var te="",re=0;re<T;++re){var ie=Y[re];(re===4||re===6||re===8)&&(te+="-"),ie<16&&(te+="0"),te+=ie.toString(16).toLowerCase()}return te}}function ul(T){return T.__=void 0,delete T.__,T}})})(e||(e={})),Xh}G8();const W8="[object ArrayBuffer]";class W{static isArrayBuffer(t){return Object.prototype.toString.call(t)===W8}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=W.toUint8Array(t),i=W.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 hl="string",J8=/^[0-9a-f\s]+$/i,X8=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Z8=/^[a-zA-Z0-9-_]+$/;class Yh{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=W.toUint8Array(t);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class cn{static toString(t,n=!1){const r=W.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 ne{static isHex(t){return typeof t===hl&&J8.test(t)}static isBase64(t){return typeof t===hl&&X8.test(t)}static isBase64Url(t){return typeof t===hl&&Z8.test(t)}static ToString(t,n="utf8"){const r=W.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 cn.toString(r,!0);case"utf16":case"utf16be":return cn.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 cn.fromString(t,!0);case"utf16":case"utf16be":return cn.fromString(t);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(t){const n=W.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(!ne.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(!ne.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=ne.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(t);case"utf8":return Yh.fromString(t);case"utf16":case"utf16be":return cn.fromString(t);case"utf16le":case"usc2":return cn.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=ne.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(t);case"utf8":return Yh.toString(t);case"utf16":case"utf16be":return cn.toString(t);case"utf16le":case"usc2":return cn.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=W.toUint8Array(t);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(t){const n=W.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(!ne.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 cn.toString(t,n)}static FromUtf16String(t,n=!1){return cn.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,"")||""}}ne.DEFAULT_UTF8_ENCODING="utf8";function Y8(...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 Hb(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 Ii(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 Nr(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 u;if(r<0)u=new ArrayBuffer(c),s=c;else{if(r<c)return new ArrayBuffer(0);u=new ArrayBuffer(r),s=r}const l=new Uint8Array(u);for(let d=c-1;d>=0;d--){const f=Math.pow(2,d*t);l[s-d-1]=Math.floor(i/f),i-=l[s-d-1]*f}return u}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Pd(...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 Vb(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=e[0]===255&&e[1]&128,u=e[0]===0&&(e[1]&128)===0;(c||u)&&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=Ii(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,Ii(s,8)-r}function Q8(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=Nr(a,8,r),u=new Uint8Array(c);return u[0]|=128,c}let i=Nr(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 u=0;u<a.byteLength;u++)s[u+1]=c[u];s[0]=0}return i}n*=Math.pow(2,8)}return new ArrayBuffer(0)}function ex(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 St(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 rc(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Mf(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 Ln(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 nu{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Mf(this.items)}}const po=[new Uint8Array([1])],Qh="0123456789",gl="name",eg="valueHexView",tx="isHexOnly",nx="idBlock",rx="tagClass",ix="tagNumber",ox="isConstructed",sx="fromBER",ax="toBER",cx="local",yt="",_n=new ArrayBuffer(0),ru=new Uint8Array(0),is="EndOfContent",Kb="OCTET STRING",Gb="BIT STRING";function yn(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?W.toUint8Array(s.valueHex):ru}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!Ln(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",_n)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ne.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Wr{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=yt,warnings:r=[],valueBeforeDecode:i=ru}={}){this.blockLength=t,this.error=n,this.warnings=r,this.valueBeforeDecodeView=W.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ne.ToHex(this.valueBeforeDecodeView)}}}Wr.NAME="baseBlock";class gt extends Wr{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'")}}gt.NAME="valueBlock";class Wb extends yn(Wr){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?W.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",_n}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=Nr(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!t){for(let u=0;u<a-1;u++)c[u+1]=s[u]|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=W.toUint8Array(t);if(!Ln(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 u=1,l=this.valueHexView=new Uint8Array(255),d=255;for(;s[u]&128;){if(l[u-1]=s[u]&127,u++,u>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(u===d){d+=255;const p=new Uint8Array(d);for(let h=0;h<l.length;h++)p[h]=l[h];l=this.valueHexView=new Uint8Array(d)}}this.blockLength=u+1,l[u-1]=s[u]&127;const f=new Uint8Array(u);for(let p=0;p<u;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(u),l.set(f),this.blockLength<=9?this.tagNumber=Ii(l,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}}}Wb.NAME="identificationBlock";class Jb extends Wr{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=W.toUint8Array(t);if(!Ln(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,u=i.subarray(c,c+a);return u[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ii(u,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=Nr(this.length,8);if(i.byteLength>127)return this.error="Too big length",_n;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}}}Jb.NAME="lengthBlock";const ee={};class rt extends Wr{constructor({name:t=yt,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=t,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new Wb(i),this.lenBlock=new Jb(i),this.valueBlock=s?new s(i):new gt(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 nu;n||Xb(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?_n: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():ne.ToHex(this.toBER())}onAsciiEncoding(){const t=this.constructor.NAME,n=ne.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 ex(n,r)}}rt.NAME="BaseBlock";function Xb(e){var t;if(e instanceof ee.Constructed)for(const n of e.valueBlock.value)Xb(n)&&(e.lenBlock.isIndefiniteForm=!0);return!!(!((t=e.lenBlock)===null||t===void 0)&&t.isIndefiniteForm)}class qf extends rt{getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}constructor({value:t=yt,...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}'`}}qf.NAME="BaseStringBlock";class Zb extends yn(gt){constructor({isHexOnly:t=!0,...n}={}){super(n),this.isHexOnly=t}}Zb.NAME="PrimitiveValueBlock";var Yb;class Cs extends rt{constructor(t={}){super(t,Zb),this.idBlock.isConstructed=!1}}Yb=Cs;ee.Primitive=Yb;Cs.NAME="PRIMITIVE";function ux(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 Wi(e,t=0,n=e.length){const r=t;let i=new rt({},gt);const s=new Wr;if(!Ln(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 u=rt;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};u=ee.EndOfContent;break;case 1:u=ee.Boolean;break;case 2:u=ee.Integer;break;case 3:u=ee.BitString;break;case 4:u=ee.OctetString;break;case 5:u=ee.Null;break;case 6:u=ee.ObjectIdentifier;break;case 10:u=ee.Enumerated;break;case 12:u=ee.Utf8String;break;case 13:u=ee.RelativeObjectIdentifier;break;case 14:u=ee.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:u=ee.Sequence;break;case 17:u=ee.Set;break;case 18:u=ee.NumericString;break;case 19:u=ee.PrintableString;break;case 20:u=ee.TeletexString;break;case 21:u=ee.VideotexString;break;case 22:u=ee.IA5String;break;case 23:u=ee.UTCTime;break;case 24:u=ee.GeneralizedTime;break;case 25:u=ee.GraphicString;break;case 26:u=ee.VisibleString;break;case 27:u=ee.GeneralString;break;case 28:u=ee.UniversalString;break;case 29:u=ee.CharacterString;break;case 30:u=ee.BmpString;break;case 31:u=ee.DATE;break;case 32:u=ee.TimeOfDay;break;case 33:u=ee.DateTime;break;case 34:u=ee.Duration;break;default:{const l=i.idBlock.isConstructed?new ee.Constructed:new ee.Primitive;l.idBlock=i.idBlock,l.lenBlock=i.lenBlock,l.warnings=i.warnings,i=l}}break;default:u=i.idBlock.isConstructed?ee.Constructed:ee.Primitive}return i=ux(i,u),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 $i(e){if(!e.byteLength){const t=new rt({},gt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Wi(W.toUint8Array(e).slice(),0,e.byteLength)}function lx(e,t){return e?1:t}class Xn extends gt{constructor({value:t=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=t,this.isIndefiniteForm=n}fromBER(t,n,r){const i=W.toUint8Array(t);if(!Ln(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(;lx(this.isIndefiniteForm,r)>0;){const a=Wi(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===is)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===is?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,n){const r=n||new nu;for(let i=0;i<this.value.length;i++)this.value[i].toBER(t,r);return n?_n:r.final()}toJSON(){const t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)t.value.push(n.toJSON());return t}}Xn.NAME="ConstructedValueBlock";var Qb;class ht extends rt{constructor(t={}){super(t,Xn),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(`