authhero 4.54.0 → 4.55.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/assets/u/widget/index.esm.js +1 -1
- package/dist/authhero.cjs +3 -3
- package/dist/authhero.d.ts +182 -67
- package/dist/authhero.mjs +30 -7
- package/dist/stats.html +1 -1
- package/package.json +4 -4
package/dist/authhero.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var dS=Object.create;var lm=Object.defineProperty;var pS=Object.getOwnPropertyDescriptor;var fS=Object.getOwnPropertyNames;var hS=Object.getPrototypeOf,_S=Object.prototype.hasOwnProperty;var mS=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fS(t))!_S.call(e,i)&&i!==n&&lm(e,i,{get:()=>t[i],enumerable:!(r=pS(t,i))||r.enumerable});return e};var gS=(e,t,n)=>(n=e!=null?dS(hS(e)):{},mS(t||!e||!e.__esModule?lm(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var I=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 _e=e=>typeof e=="string",ss=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},um=e=>e==null?"":""+e,yS=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},bS=/###/g,dm=e=>e&&e.indexOf("###")>-1?e.replace(bS,"."):e,pm=e=>!e||_e(e),Ps=(e,t,n)=>{const r=_e(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(pm(e))return{};const s=dm(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return pm(e)?{}:{obj:e,k:dm(r[i])}},fm=(e,t,n)=>{const{obj:r,k:i}=Ps(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=Ps(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Ps(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},vS=(e,t,n,r)=>{const{obj:i,k:s}=Ps(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Vc=(e,t)=>{const{obj:n,k:r}=Ps(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},wS=(e,t,n)=>{const r=Vc(e,n);return r!==void 0?r:Vc(t,n)},fv=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?_e(e[r])||e[r]instanceof String||_e(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):fv(e[r],t[r],n):e[r]=t[r]);return e},Kr=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var kS={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const $S=e=>_e(e)?e.replace(/[&<>"'\/]/g,t=>kS[t]):e;class SS{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 xS=[" ",",","?","!",";"],zS=new SS(20),AS=(e,t,n)=>{t=t||"",n=n||"";const r=xS.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=zS.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},af=(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 l=s;l<r.length;++l)if(l!==s&&(c+=n),c+=r[l],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<r.length-1)continue;s+=l-s+1;break}i=a}return i},Zs=e=>e?.replace(/_/g,"-"),ES={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 Kc{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||ES,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:(_e(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Kc(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Kc(this.logger,t)}}var zn=new Kc;class uu{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 hm extends uu{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):_e(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Vc(this.data,c);return!l&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!_e(r)?l:af(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),fm(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)(_e(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 l=Vc(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?fv(l,r,s):l={...l,...r},fm(this.data,c,l),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 hv={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 _v=Symbol("i18next/PATH_KEY");function CS(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===_v?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function Os(e,t){const{[_v]:n}=e(CS()),r=t?.keySeparator??".",i=t?.nsSeparator??":";if(n.length>1&&i){const s=t?.ns;if((s?Array.isArray(s)?s:[s]:[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const _m={},Md=e=>!_e(e)&&typeof e!="boolean"&&typeof e!="number";class Gc extends uu{constructor(t,n={}){super(),yS(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=zn.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=Md(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&&!AS(t,r,i);if(a&&!c){const l=t.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:t,namespaces:_e(s)?[s]:s};const u=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(u[0])>-1)&&(s=u.shift()),t=u.join(i)}return{key:t,namespaces:_e(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=Os(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(B=>typeof B=="function"?Os(B,{...this.options,...i}):String(B));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(t[t.length-1],i),u=l[l.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:`${u}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let _=h?.res;const g=h?.usedKey||c,y=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],w=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,S=i.count!==void 0&&!_e(i.count),b=Gc.hasDefaultValue(i),x=S?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&S?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",E=S&&!i.ordinal&&i.count===0,P=E&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${x}`]||i[`defaultValue${A}`]||i.defaultValue;let R=_;k&&!_&&b&&(R=P);const C=Md(R),L=Object.prototype.toString.apply(R);if(k&&R&&C&&m.indexOf(L)<0&&!(_e(w)&&Array.isArray(R))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const B=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,R,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=B,h.usedParams=this.getUsedParamsDetails(i),h):B}if(a){const B=Array.isArray(R),V=B?[]:{},D=B?y:g;for(const ne in R)if(Object.prototype.hasOwnProperty.call(R,ne)){const ce=`${D}${a}${ne}`;b&&!_?V[ne]=this.translate(ce,{...i,defaultValue:Md(P)?P[ne]:void 0,joinArrays:!1,ns:l}):V[ne]=this.translate(ce,{...i,joinArrays:!1,ns:l}),V[ne]===ce&&(V[ne]=R[ne])}_=V}}else if(k&&_e(w)&&Array.isArray(_))_=_.join(w),_&&(_=this.extendTranslation(_,t,i,r));else{let B=!1,V=!1;!this.isValidLookup(_)&&b&&(B=!0,_=P),this.isValidLookup(_)||(V=!0,_=c);const ne=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&V?void 0:_,ce=b&&P!==_&&this.options.updateMissing;if(V||B||ce){if(this.logger.log(ce?"updateKey":"missingKey",f,u,c,ce?P:_),a){const le=this.resolve(c,{...i,keySeparator:!1});le&&le.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 ae=[];const ve=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ve&&ve[0])for(let le=0;le<ve.length;le++)ae.push(ve[le]);else this.options.saveMissingTo==="all"?ae=this.languageUtils.toResolveHierarchy(i.lng||this.language):ae.push(i.lng||this.language);const Ee=(le,Se,F)=>{const Pe=b&&F!==_?F:ne;this.options.missingKeyHandler?this.options.missingKeyHandler(le,u,Se,Pe,ce,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(le,u,Se,Pe,ce,i),this.emit("missingKey",le,u,Se,_)};this.options.saveMissing&&(this.options.saveMissingPlurals&&S?ae.forEach(le=>{const Se=this.pluralResolver.getSuffixes(le,i);E&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Se.indexOf(`${this.options.pluralSeparator}zero`)<0&&Se.push(`${this.options.pluralSeparator}zero`),Se.forEach(F=>{Ee([le],c+F,i[`defaultValue${F}`]||P)})}):Ee(ae,c,P))}_=this.extendTranslation(_,t,i,h,r),V&&_===c&&this.options.appendNamespaceToMissingKey&&(_=`${u}${d}${c}`),(V||B)&&this.options.parseMissingKeyHandler&&(_=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${c}`:c,B?_:void 0,i))}return s?(h.res=_,h.usedParams=this.getUsedParamsDetails(i),h):_}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 l=_e(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(l){const f=t.match(this.interpolator.nestingRegexp);u=f&&f.length}let d=r.replace&&!_e(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),l){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;u<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=_e(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=hv.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 _e(t)&&(t=[t]),Array.isArray(t)&&(t=t.map(l=>typeof l=="function"?Os(l,{...this.options,...n}):l)),t.forEach(l=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(l,n),d=u.key;i=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!_e(n.count),h=p&&!n.ordinal&&n.count===0,_=n.context!==void 0&&(_e(n.context)||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(y=>{this.isValidLookup(r)||(c=y,!_m[`${g[0]}-${y}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(_m[`${g[0]}-${y}`]=!0,this.logger.warn(`key "${i}" for languages "${g.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!!!")),g.forEach(m=>{if(this.isValidLookup(r))return;a=m;const w=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,d,m,y,n);else{let S;p&&(S=this.pluralResolver.getSuffix(m,n.count,n));const b=`${this.options.pluralSeparator}zero`,x=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&S.indexOf(x)===0&&w.push(d+S.replace(x,this.options.pluralSeparator)),w.push(d+S),h&&w.push(d+b)),_){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;w.push(A),p&&(n.ordinal&&S.indexOf(x)===0&&w.push(A+S.replace(x,this.options.pluralSeparator)),w.push(A+S),h&&w.push(A+b))}}let k;for(;k=w.pop();)this.isValidLookup(r)||(s=k,r=this.getResource(m,y,k,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&&!_e(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 mm{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=zn.create("languageUtils")}getScriptPartFromCode(t){if(t=Zs(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=Zs(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(_e(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)),_e(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 _e(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))):_e(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const gm={zero:0,one:1,two:2,few:3,many:4,other:5},ym={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class IS{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=zn.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Zs(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(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),ym;if(!t.match(/-|_/))return ym;const l=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(l,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)=>gm[i]-gm[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 bm=(e,t,n,r=".",i=!0)=>{let s=wS(e,t,n);return!s&&i&&_e(n)&&(s=af(e,n,r),s===void 0&&(s=af(t,n,r))),s},qd=e=>e.replace(/\$/g,"$$$$");class vm{constructor(t={}){this.logger=zn.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:l,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:_,nestingSuffixEscaped:g,nestingOptionsSeparator:y,maxReplaces:m,alwaysFormat:w}=t.interpolation;this.escape=n!==void 0?n:$S,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Kr(s):a||"{{",this.suffix=c?Kr(c):l||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?Kr(p):h||Kr("$t("),this.nestingSuffix=_?Kr(_):g||Kr(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=m||1e3,this.alwaysFormat=w!==void 0?w:!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 l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const m=bm(n,l,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const _=h.split(this.formatSeparator),g=_.shift().trim(),y=_.join(this.formatSeparator).trim();return this.format(bm(n,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),y,r,{...i,...n,interpolationkey:g})};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=>qd(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?qd(this.escape(h)):qd(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const _=s[1].trim();if(a=u(_),a===void 0)if(typeof d=="function"){const y=d(t,s,i);a=_e(y)?y:""}else if(i&&Object.prototype.hasOwnProperty.call(i,_))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${_} for interpolating ${t}`),a="";else!_e(a)&&!this.useRawValueToEscape&&(a=um(a));const g=h.safeValue(a);if(t=t.replace(s[0],g),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=(l,u)=>{const d=this.nestingOptionsSeparator;if(l.indexOf(d)<0)return l;const f=l.split(new RegExp(`${Kr(d)}[ ]*{`));let p=`{${f[1]}`;l=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),_=p.match(/"/g);((h?.length??0)%2===0&&!_||(_?.length??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(t);){let l=[];a={...r},a=a.replace&&!_e(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(l=i[1].slice(u).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!_e(s))return s;_e(s)||(s=um(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),l.length&&(s=l.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 jS=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,...l]=a.split(":"),u=l.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},wm=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(Zs(r),i),t[a]=c),c(n)}},NS=e=>(t,n,r)=>e(Zs(n),r)(t);class TS{constructor(t={}){this.logger=zn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?wm:NS;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()]=wm(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(l=>l.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,l)=>{const{formatName:u,formatOptions:d}=jS(l);if(this.formats[u]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[u](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return c},t)}}const PS=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class OS extends uu{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=zn.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={},l={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,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),l[f]===void 0&&(l[f]=!0)))}),d||(c[u]=!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(l)}}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(l=>{vS(l.loaded,[s],a),PS(l,t),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{c[u]||(c[u]={});const d=l.loaded[u];d.length&&d.forEach(f=>{c[u][f]===void 0&&(c[u][f]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.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=(u,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(u&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(u,d)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const u=l(t,n);u&&typeof u.then=="function"?u.then(d=>c(null,d)).catch(c):c(null,u)}catch(u){c(u)}return}return l(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();_e(t)&&(t=this.languageUtils.toResolveHierarchy(t)),_e(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 l={...a,isUpdate:s},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,i,l):d=u(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 u(t,n,r,i,c,l)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const Fd=()=>({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]),_e(e[1])&&(t.defaultValue=e[1]),_e(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}),km=e=>(_e(e.ns)&&(e.ns=[e.ns]),_e(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),_e(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),lc=()=>{},RS=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})},mv="__i18next_supportNoticeShown",LS=()=>typeof globalThis<"u"&&!!globalThis[mv],DS=()=>{typeof globalThis<"u"&&(globalThis[mv]=!0)},US=e=>!!(e?.modules?.backend?.name?.indexOf("Locize")>0||e?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||e?.options?.backend?.backends&&e.options.backend.backends.some(t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(t=>t?.projectId));class Rs extends uu{constructor(t={},n){if(super(),this.options=km(t),this.services={},this.logger=zn,this.modules={external:[]},RS(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&&(_e(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=Fd();this.options={...r,...this.options,...km(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),this.options.showSupportNotice!==!1&&!US(this)&&!LS()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),DS());const i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?zn.init(i(this.modules.logger),this.options):zn.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=TS;const d=new mm(this.options);this.store=new hm(this.options.resources,this.options);const f=this.services;f.logger=zn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new IS(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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(u),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new vm(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new OS(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,..._)=>{this.emit(h,..._)}),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 Gc(this.services,this.options),this.translator.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=lc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const c=ss(),l=()=>{const u=(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 u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(t,n=lc){let r=n;const i=_e(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(u=>{u!=="cimode"&&s.indexOf(u)<0&&s.push(u)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),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=ss();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=lc),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"&&hv.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=ss();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,l)=>{l?this.isLanguageChangingTo===t&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,r.resolve((...u)=>this.t(...u)),n&&n(c,(...u)=>this.t(...u))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const l=_e(c)?c:c&&c[0],u=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(_e(c)?[c]:c);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{s(d,u)})};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 l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([s,a].concat(c)):l={...a},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||i.keyPrefix);const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=Os(f,{...this.options,...a})),`${l.keyPrefix}${u}${f}`)):(typeof s=="function"&&(s=Os(s,{...this.options,...a})),d=l.keyPrefix?`${l.keyPrefix}${u}${s}`:s),this.t(d,l)};return _e(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,l)=>{const u=this.services.backendConnector.state[`${c}|${l}`];return u===-1||u===0||u===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=ss();return this.options.ns?(_e(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=ss();_e(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 mm(Fd());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 Rs(t,n);return r.createInstance=Rs.createInstance,r}cloneInstance(t={},n=lc){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Rs(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((l,u)=>(l[u]={...this.store.data[u]},l[u]=Object.keys(l[u]).reduce((d,f)=>(d[f]={...l[u][f]},d),l[u]),l),{});s.store=new hm(c,i),s.services.resourceStore=s.store}if(t.interpolation){const l={...Fd().interpolation,...this.options.interpolation,...t.interpolation},u={...i,interpolation:l};s.services.interpolator=new vm(u)}return s.translator=new Gc(s.services,i),s.translator.on("*",(c,...l)=>{s.emit(c,...l)}),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 T=Rs.createInstance();T.createInstance;T.dir;T.init;T.loadResources;T.reloadResources;T.use;T.changeLanguage;T.getFixedT;const he=T.t;T.exists;T.setDefaultNamespace;T.hasLoadedNamespace;T.loadNamespaces;T.loadLanguages;const jr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),BS=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),MS=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),qS=o.z.enum(["VERIFY_EMAIL"]),gv=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()}),yv=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())})}),bv=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:gv.optional()})}),vv=o.z.enum(["change-email","account","custom"]),wv=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:vv.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'"})})}),kv=o.z.union([yv,bv,wv]),Wc=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(kv).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),to=Wc.extend({...jr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),FS=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"})}),jt=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),$v=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()),Jc=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),username:o.z.string().optional(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:$v.optional()}),Sv=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),du=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().refine(e=>!e.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().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(),middle_name:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),address:Sv}),Zc=du.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(),password:o.z.object({hash:o.z.string(),algorithm:o.z.string()}).optional()}),dh=o.z.object({...Zc.omit({password:!0}).shape,...jr.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(Jc).optional()}),Sn=dh,HS=du.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()),VS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let KS=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=VS[n[e]&63];return t};const Xc=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(()=>KS()).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)."}),auth0_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client follows Auth0-compatible behavior (true) or strict OIDC behavior (false). When true, profile/email claims are included in the ID token when scopes are requested. When false, these claims are only available from the userinfo endpoint (strict OIDC 5.4 compliance)."}),callbacks: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()}),ti=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Xc.shape}),Yc=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."})}),ni=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Yc.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),GS=o.z.array(ni),Ii=o.z.object({x:o.z.number(),y:o.z.number()});var ph=(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))(ph||{}),fh=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(fh||{});const pu=o.z.object({id:o.z.string(),category:o.z.nativeEnum(fh),type:o.z.nativeEnum(ph)}),xv=pu.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),zv=pu.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()}),Av=pu.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()}),Ev=pu.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()}),Cv=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Iv=o.z.union([xv,zv,Av,Ev,Cv]);var jv=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(jv||{});const Nv=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ii,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Iv),next_node:o.z.string()}).passthrough()}),Tv=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ii,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Pv=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Ii,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()}),Ov=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Ii}).passthrough(),Rv=o.z.union([Nv,Tv,Pv,Ov]),Lv=o.z.object({next_node:o.z.string(),coordinates:Ii}).passthrough(),Dv=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Ii}).passthrough(),Uv=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(Rv),start:Lv,ending:Dv,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(),WS=Uv.omit({id:!0,created_at:!0,updated_at:!0});var at=(e=>(e.TOKEN="token",e.ID_TOKEN="id_token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(at||{}),pn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(pn||{}),fu=(e=>(e.S256="S256",e.Plain="plain",e))(fu||{});const Xs=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(at).optional(),response_mode:o.z.nativeEnum(pn).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(fu).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),max_age:o.z.number().optional(),acr_values:o.z.string().optional(),vendor_id:o.z.string().optional()}),Ec=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()}),Bv=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),Mv=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:Bv,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()}),JS=o.z.object({...Mv.shape,created_at:o.z.string()}),qv=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(),passwordPolicy:o.z.enum(["none","low","fair","good","excellent"]).optional(),password_complexity_options:o.z.object({min_length:o.z.number().optional()}).optional(),password_history:o.z.object({enable:o.z.boolean().optional(),size:o.z.number().optional()}).optional(),password_no_personal_info:o.z.object({enable:o.z.boolean().optional()}).optional(),password_dictionary:o.z.object({enable:o.z.boolean().optional(),dictionary:o.z.array(o.z.string()).optional()}).optional(),disable_signup:o.z.boolean().optional(),brute_force_protection:o.z.boolean().optional(),import_mode:o.z.boolean().optional(),attributes:o.z.object({email:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional(),verification:o.z.object({active:o.z.boolean().optional()}).optional()}).optional(),validation:o.z.object({allowed:o.z.boolean().optional()}).optional(),unique:o.z.boolean().optional(),profile_required:o.z.boolean().optional(),verification_method:o.z.enum(["link","code"]).optional()}).optional(),username:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional(),validation:o.z.object({max_length:o.z.number().optional(),min_length:o.z.number().optional(),allowed_types:o.z.object({email:o.z.boolean().optional(),phone_number:o.z.boolean().optional()}).optional()}).optional(),profile_required:o.z.boolean().optional()}).optional(),phone_number:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:o.z.object({password:o.z.object({enabled:o.z.boolean().optional()}).optional(),passkey:o.z.object({enabled:o.z.boolean().optional()}).optional()}).optional(),passkey_options:o.z.object({challenge_ui:o.z.enum(["both","autofill","button"]).optional(),local_enrollment_enabled:o.z.boolean().optional(),progressive_enrollment_enabled:o.z.boolean().optional()}).optional(),requires_username:o.z.boolean().optional(),validation:o.z.object({username:o.z.object({min:o.z.number().optional(),max:o.z.number().optional()}).optional()}).optional()}),Qc=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:qv.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()}),_r=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(Qc.shape),hh=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()}),Fv=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),fr=o.z.object({...hh.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(Fv)}).optional(),tls_policy:o.z.string().optional()}),ZS=fr.extend({tenant_id:o.z.string()}),_h=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),Nr=_h.extend({category:o.z.literal("BLOCK").optional()}),XS=Nr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({text:o.z.string().optional()}).optional()}),YS=Nr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),QS=Nr.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()}),ex=Nr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),tx=Nr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),nx=Nr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),rx=Nr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),ix=Nr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),mh=_h.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()}),ox=mh.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),sx=mh.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),ax=mh.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),bt=_h.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()}),cx=bt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),lx=bt.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()}),ux=bt.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(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),dx=bt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional(),schema:o.z.record(o.z.any()).optional(),code:o.z.string().optional()})}),px=bt.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(),default_value:o.z.string().optional()}).optional()}),fx=bt.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(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),hx=bt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),_x=bt.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()}),mx=bt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),gx=bt.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(),default_value:o.z.string().optional()}).optional()}),yx=bt.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(),default_value:o.z.string().optional()}).optional()}),bx=bt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),vx=bt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional(),provider_details:o.z.array(o.z.object({name:o.z.string(),strategy:o.z.string().optional(),display_name:o.z.string().optional(),icon_url:o.z.string().optional()})).optional()}).optional()}),wx=bt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),kx=bt.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(),default_value:o.z.string().optional()}).optional()}),$x=bt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),Hv=o.z.discriminatedUnion("type",[XS,YS,QS,ex,tx,nx,rx,ix]),Vv=o.z.discriminatedUnion("type",[ox,sx,ax]),Kv=o.z.discriminatedUnion("type",[cx,lx,ux,dx,px,fx,hx,_x,mx,gx,yx,bx,vx,wx,kx,$x]),gh=o.z.union([Hv,Vv,Kv]),yh=new Set(["BOOLEAN","CARDS","CHOICE","DATE","DROPDOWN","EMAIL","LEGAL","NUMBER","PASSWORD","TEL","TEXT","URL"]),Sx=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()}),Ys=o.z.object({x:o.z.number(),y:o.z.number()}),xx=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ys,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()})}),zx=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Ys,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()})}),Ax=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ys,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(gh),next_node:o.z.string().optional()})}),Gv=o.z.discriminatedUnion("type",[xx,zx,Ax]),el=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(Gv).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:Ys.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:Ys.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),no=o.z.object({...jr.shape,...el.shape,id:o.z.string()}),Wv=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),Jv=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),Ex=o.z.object({name:o.z.string().optional(),action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(gh),messages:o.z.array(Wv).optional(),links:o.z.array(Jv).optional(),footer:o.z.string().optional()});function Cx(e){return e.category==="BLOCK"}function Ix(e){return e.category==="WIDGET"}function jx(e){return e.category==="FIELD"}const Zv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Xv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Yv=o.z.enum(["post-user-login","credentials-exchange"]),bh=o.z.enum(["ensure-username","set-preferred-username"]),Nx={"ensure-username":{name:"Ensure Username",description:"Automatically assigns a username to users who sign in without one. Creates a linked username account for social/email users.",trigger_id:"post-user-login"},"set-preferred-username":{name:"Set Preferred Username",description:"Sets the preferred_username claim on tokens based on the username from the primary or linked user.",trigger_id:"credentials-exchange"}},Uo={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},Tx=o.z.object({...Uo,trigger_id:Zv,url:o.z.string()}),Px=o.z.object({...Uo,trigger_id:Xv,form_id:o.z.string()}),Ox=o.z.object({...Uo,trigger_id:Yv,template_id:bh}),cf=o.z.union([Tx,Px,Ox]),Rx=o.z.object({...Uo,trigger_id:Zv,...jr.shape,hook_id:o.z.string(),url:o.z.string()}),Lx=o.z.object({...Uo,trigger_id:Xv,...jr.shape,hook_id:o.z.string(),form_id:o.z.string()}),Dx=o.z.object({...Uo,trigger_id:Yv,...jr.shape,hook_id:o.z.string(),template_id:bh}),ro=o.z.union([Rx,Lx,Dx]),Qv=o.z.object({name:o.z.string().optional()}),ew=o.z.object({email:o.z.string().optional()}),vh=o.z.object({organization_id:o.z.string().max(50),inviter:Qv,invitee:ew,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()}),Ls=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(vh.shape),wh=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()}),tw=o.z.object({keys:o.z.array(wh)}),lf=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())});var We=(e=>(e.PENDING="pending",e.AUTHENTICATED="authenticated",e.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",e.AWAITING_HOOK="awaiting_hook",e.AWAITING_CONTINUATION="awaiting_continuation",e.COMPLETED="completed",e.FAILED="failed",e.EXPIRED="expired",e))(We||{});const nw=o.z.nativeEnum(We),rw=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Xs,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(),state:nw.optional().default("pending"),state_data:o.z.string().optional(),failure_reason:o.z.string().optional(),user_id:o.z.string().optional()}).openapi({description:"This represents a login sesion"}),Ux=o.z.object({...rw.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()}),pe={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_IMPERSONATION:"fimp",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",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",SUCCESS_IMPERSONATION:"simp",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"},Bx=o.z.string().refine(e=>Object.values(pe).includes(e),{message:"Invalid log type"}),iw=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),ow=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()}),sw=o.z.object({type:Bx,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:iw.optional(),log_id:o.z.string().optional(),location_info:ow.optional()}),tl=o.z.object({...sw.shape,log_id:o.z.string()}),aw=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)}),Mx=aw.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),cw=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")}),lw=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:cw.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")}),hu=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...lw.shape}),uf=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"})}),kh=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(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),nl=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...kh.shape,id:o.z.string()});var an=(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))(an||{});const $h=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 uw=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()}),dw=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()}),Xr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),pw=o.z.object({body_text:Xr,buttons_text:Xr,font_url:o.z.string(),input_labels:Xr,links:Xr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Xr,title:Xr}),fw=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),hw=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"])}),_w=o.z.object({borders:uw,colors:dw,displayName:o.z.string(),fonts:pw,page_background:fw,widget:hw}),Cc=_w.extend({themeId:o.z.string()}),Ds=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()}),Ic=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()}),Sh=o.z.object({id:o.z.string(),login_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:cw,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),qx=o.z.object({created_at:o.z.string(),...Sh.shape}),Fx=o.z.object({to:o.z.string(),message:o.z.string()}),Hx=o.z.object({name:o.z.string(),options:o.z.object({})}),mw=o.z.object({value:o.z.string(),description:o.z.string().optional()}),gw=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()}),rl=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(mw).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:gw.optional(),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional()}),ri=o.z.object({...rl.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Vx=o.z.array(ri),yw=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),bw=o.z.object({...yw.shape,created_at:o.z.string()}),vw=o.z.array(bw),ww=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()}),kw=o.z.object({...ww.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),Kx=o.z.array(kw),$w=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()}),Sw=o.z.array($w),xw=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),zw=o.z.object({...xw.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),Gx=o.z.array(zw),il=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(),metadata:o.z.record(o.z.any()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),ii=il.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()}),ol=o.z.array(ii),Aw=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(),Ew=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"})}),Cw=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(),sl=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:Aw,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Ew).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Cw}),mr=o.z.object({...sl.shape,...jr.shape,id:o.z.string(),name:o.z.string().min(1).openapi({description:"The name of the organization"})}),Iw=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"})}),Wx=o.z.object({...Iw.shape,...jr.shape,id:o.z.string()}),Jx=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(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),jw=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"})}),Zx=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234}),io=o.z.enum(["login","login-id","login-password","signup","signup-id","signup-password","reset-password","consent","mfa","mfa-push","mfa-otp","mfa-voice","mfa-phone","mfa-webauthn","mfa-sms","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form"]),oo=o.z.record(o.z.string(),o.z.string()).openapi({type:"object",additionalProperties:{type:"string"}}),Xx=o.z.object({prompt:io,language:o.z.string(),custom_text:oo});function Yx(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function Qx(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(...l)=>{const u=await c.apply(s,l),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,l)}catch(_){try{f.onError?f.onError(_,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,_)}catch(g){console.error(`Passthrough adapter: onError handler threw for ${a}:`,g)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),u}:c.bind(s)}};return new Proxy(t,i)}function ez(e){return e}function ji(e){var t,n,r,i,s,a,c,l,u,d,f,p;const h=e?.options;if(!h)return{usernameIdentifierActive:!1,emailIdentifierActive:!0,usernameMinLength:1,usernameMaxLength:15};const _=h.attributes;if(_){const g=((n=(t=_.username)==null?void 0:t.identifier)==null?void 0:n.active)===!0,y=((i=(r=_.email)==null?void 0:r.identifier)==null?void 0:i.active)!==!1,m=((a=(s=_.username)==null?void 0:s.validation)==null?void 0:a.min_length)??1,w=((l=(c=_.username)==null?void 0:c.validation)==null?void 0:l.max_length)??15;return{usernameIdentifierActive:g,emailIdentifierActive:y,usernameMinLength:m,usernameMaxLength:w}}return{usernameIdentifierActive:h.requires_username===!0,emailIdentifierActive:!0,usernameMinLength:((d=(u=h.validation)==null?void 0:u.username)==null?void 0:d.min)??1,usernameMaxLength:((p=(f=h.validation)==null?void 0:f.username)==null?void 0:p.max)??15}}const df={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:100},buttons_text:{bold:!0,size:100},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:100},links:{bold:!0,size:100},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:100},title:{bold:!0,size:150}},page_background:{background_color:"#F8F9FB",background_image_url:"",page_layout:"center"},widget:{logo_url:"",header_text_alignment:"center",logo_height:36,logo_position:"center",social_buttons_layout:"bottom"}};function Nw(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 tz=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:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Cc}},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(df)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:Cc.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Cc}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default"),i=Nw(n||df,t);return n?await e.env.data.themes.update(e.var.tenant_id,"default",i):await e.env.data.themes.create(e.var.tenant_id,i,"default"),e.json({...i,themeId:"default"})}),$m={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"}},Sm=o.z.object({body:o.z.string()}),nz=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:Ec}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json($m)}).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(Ec.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Ec}},description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");await e.env.data.branding.set(e.var.tenant_id,t);const n=await e.env.data.branding.get(e.var.tenant_id);return e.json(n||$m)}).openapi(o.createRoute({tags:["branding"],method:"get",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sm}},description:"Universal login template"},404:{description:"Template not found"}}}),async e=>{const t=await e.env.data.universalLoginTemplates.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Template not found"});return e.json(t)}).openapi(o.createRoute({tags:["branding"],method:"put",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:Sm}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{204:{description:"Template updated successfully"},400:{description:"Invalid template"}}}),async e=>{const t=e.req.valid("json");if(!t.body.includes("{%- auth0:head -%}"))throw new I(400,{message:"Template must contain {%- auth0:head -%} tag"});if(!t.body.includes("{%- auth0:widget -%}"))throw new I(400,{message:"Template must contain {%- auth0:widget -%} tag"});return await e.env.data.universalLoginTemplates.set(e.var.tenant_id,t),e.body(null,204)}).openapi(o.createRoute({tags:["branding"],method:"delete",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:branding","auth:write"]}],responses:{204:{description:"Template deleted successfully"}}}),async e=>(await e.env.data.universalLoginTemplates.delete(e.var.tenant_id),e.body(null,204))).route("/themes",tz),rz="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let iz=e=>crypto.getRandomValues(new Uint8Array(e)),oz=(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),l=i|0;for(;l--;)if(a+=e[c[l]&r]||"",a.length>=s)return a}}},Tw=(e,t=21)=>oz(e,t|0,iz),Oe=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=rz[n[e]&63];return t};const sz=24;function Ni(){return Tw("0123456789abcdef",sz)()}function pf(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}class W extends I{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}function az(e){return async(t,n)=>{const r=n.email?.toLowerCase();if(!n.linked_to&&r&&n.email_verified){const s=await Mo({userAdapter:e.users,tenant_id:t,email:r});s&&(n.linked_to=s.user_id)}if(n.linked_to&&!await e.users.get(t,n.linked_to))throw new W(400,{error:"invalid_request",error_description:"Primary user does not exist"});const i=await e.users.create(t,n);if(n.linked_to){const s=await e.users.get(t,n.linked_to);if(!s)throw new W(500,{error:"server_error",error_description:"Failed to fetch primary user after linking"});return s}return i}}var cz={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Pw=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(cz))if(lz(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},lz=e=>navigator.userAgent.startsWith(e);function Ow(e,t){if(Pw()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function uz(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function fe(e,t,n){const r={};if(e.req.raw?.headers){const s=uz(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:n.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():Ow(e,i())}class al{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 al(Math.round(this.milliseconds()*t),"ms")}}class dz{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 Rw(e){return await crypto.subtle.digest("SHA-256",e)}const xm="0123456789abcdef";function ff(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=xm[i];const s=t[r]&15;n+=xm[s]}return n}class Lw{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 l=0;l<c;l++)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 l=[];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}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}}new Lw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Lw("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Dw{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 l=0;l<c;l++)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,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];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}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const pz=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),wr=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function zm(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=wr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=wr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),u=a.encode([c,l].join(".")),d=await hz(e).sign(t,u),f=wr.encode(new Uint8Array(d),{includePadding:!1});return[c,l,f].join(".")}function fz(e){const t=e.split(".");return t.length!==3?null:t}function Ca(e){const t=fz(e);if(!t)return null;const n=new TextDecoder,r=wr.decode(t[0],{strict:!1}),i=wr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!_z(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 l of a.aud)if(typeof l!="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 hz(e){return new dz(mz[e])}function _z(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const mz={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function jc(e){const t=new Error(e);return t.source="ulid",t}const xh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Us=xh.length,Am=Math.pow(2,48)-1,gz=10,yz=16;function bz(e){let t=Math.floor(e()*Us);return t===Us&&(t=Us-1),xh.charAt(t)}function vz(e,t){if(isNaN(e))throw new Error(e+" must be a number");if(e>Am)throw jc("cannot encode time greater than "+Am);if(e<0)throw jc("time must be positive");if(Number.isInteger(Number(e))===!1)throw jc("time must be an integer");let n,r="";for(;t>0;t--)n=e%Us,r=xh.charAt(n)+r,e=(e-n)/Us;return r}function wz(e,t){let n="";for(;e>0;e--)n=bz(t)+n;return n}function kz(e=!1,t){t||(t=typeof window<"u"?window:null);const n=t&&(t.crypto||t.msCrypto);if(n)return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};try{const r=require("crypto");return()=>r.randomBytes(1).readUInt8()/255}catch{}if(e){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw jc("secure crypto unusable, insecure Math.random not allowed")}function $z(e){return e||(e=kz()),function(n){return isNaN(n)&&(n=Date.now()),vz(n,gz)+wz(yz,e)}}const Uw=$z();function Sz(){const e=new Uint8Array(32);return crypto.getRandomValues(e),wr.encode(e,{includePadding:!1})}function xz(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 zz(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await Rw(n);return wr.encode(new Uint8Array(r),{includePadding:!1})}const Te="auth2",uc=300,_u=720*60*60,di=1440*60,Az="auth-token",Bs=1800*1e3,hf=10080*60*1e3,Ez=300,Cz=300,Iz=1800*1e3,jz=1800*1e3,Nz=1440*60*1e3;var Em=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Tz(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 Yt={},Cm;function Pz(){if(Cm)return Yt;Cm=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.parseCookie=c,Yt.parse=c,Yt.stringifyCookie=l,Yt.stringifySetCookie=u,Yt.serialize=u,Yt.parseSetCookie=d,Yt.stringifySetCookie=u,Yt.serialize=u;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,t=/^[\u0021-\u003A\u003C-\u007E]*$/,n=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,r=/^[\u0020-\u003A\u003D-\u007E]*$/,i=/^-?\d+$/,s=Object.prototype.toString,a=(()=>{const y=function(){};return y.prototype=Object.create(null),y})();function c(y,m){const w=new a,k=y.length;if(k<2)return w;const S=m?.decode||_;let b=0;do{const x=p(y,b,k);if(x===-1)break;const A=f(y,b,k);if(x>A){b=y.lastIndexOf(";",x-1)+1;continue}const E=h(y,b,x);w[E]===void 0&&(w[E]=S(h(y,x+1,A))),b=A+1}while(b<k);return w}function l(y,m){const w=m?.encode||encodeURIComponent,k=[];for(const S of Object.keys(y)){const b=y[S];if(b===void 0)continue;if(!e.test(S))throw new TypeError(`cookie name is invalid: ${S}`);const x=w(b);if(!t.test(x))throw new TypeError(`cookie val is invalid: ${b}`);k.push(`${S}=${x}`)}return k.join("; ")}function u(y,m,w){const k=typeof y=="object"?y:{...w,name:y,value:String(m)},b=(typeof m=="object"?m:w)?.encode||encodeURIComponent;if(!e.test(k.name))throw new TypeError(`argument name is invalid: ${k.name}`);const x=k.value?b(k.value):"";if(!t.test(x))throw new TypeError(`argument val is invalid: ${k.value}`);let A=k.name+"="+x;if(k.maxAge!==void 0){if(!Number.isInteger(k.maxAge))throw new TypeError(`option maxAge is invalid: ${k.maxAge}`);A+="; Max-Age="+k.maxAge}if(k.domain){if(!n.test(k.domain))throw new TypeError(`option domain is invalid: ${k.domain}`);A+="; Domain="+k.domain}if(k.path){if(!r.test(k.path))throw new TypeError(`option path is invalid: ${k.path}`);A+="; Path="+k.path}if(k.expires){if(!g(k.expires)||!Number.isFinite(k.expires.valueOf()))throw new TypeError(`option expires is invalid: ${k.expires}`);A+="; Expires="+k.expires.toUTCString()}if(k.httpOnly&&(A+="; HttpOnly"),k.secure&&(A+="; Secure"),k.partitioned&&(A+="; Partitioned"),k.priority)switch(typeof k.priority=="string"?k.priority.toLowerCase():void 0){case"low":A+="; Priority=Low";break;case"medium":A+="; Priority=Medium";break;case"high":A+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${k.priority}`)}if(k.sameSite)switch(typeof k.sameSite=="string"?k.sameSite.toLowerCase():k.sameSite){case!0:case"strict":A+="; SameSite=Strict";break;case"lax":A+="; SameSite=Lax";break;case"none":A+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${k.sameSite}`)}return A}function d(y,m){const w=m?.decode||_,k=y.length,S=f(y,0,k),b=p(y,0,S),x=b===-1?{name:"",value:w(h(y,0,S))}:{name:h(y,0,b),value:w(h(y,b+1,S))};let A=S+1;for(;A<k;){const E=f(y,A,k),P=p(y,A,E),R=P===-1?h(y,A,E):h(y,A,P),C=P===-1?void 0:h(y,P+1,E);switch(R.toLowerCase()){case"httponly":x.httpOnly=!0;break;case"secure":x.secure=!0;break;case"partitioned":x.partitioned=!0;break;case"domain":x.domain=C;break;case"path":x.path=C;break;case"max-age":C&&i.test(C)&&(x.maxAge=Number(C));break;case"expires":if(!C)break;const L=new Date(C);Number.isFinite(L.valueOf())&&(x.expires=L);break;case"priority":if(!C)break;const B=C.toLowerCase();(B==="low"||B==="medium"||B==="high")&&(x.priority=B);break;case"samesite":if(!C)break;const V=C.toLowerCase();(V==="lax"||V==="strict"||V==="none")&&(x.sameSite=V);break}A=E+1}return x}function f(y,m,w){const k=y.indexOf(";",m);return k===-1?w:k}function p(y,m,w){const k=y.indexOf("=",m);return k<w?k:-1}function h(y,m,w){let k=m,S=w;do{const b=y.charCodeAt(k);if(b!==32&&b!==9)break}while(++k<S);for(;S>k;){const b=y.charCodeAt(S-1);if(b!==32&&b!==9)break;S--}return y.slice(k,S)}function _(y){if(y.indexOf("%")===-1)return y;try{return decodeURIComponent(y)}catch{return y}}function g(y){return s.call(y)==="[object Date]"}return Yt}var Qs=Pz();function mu(e){return`${e}-${Az}`}function Mw(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 Oz(e,t){if(!t)return[];const n=mu(e),r=[],i=t.split(";");for(const s of i){const[a,...c]=s.trim().split("=");a===n&&c.length>0&&r.push(c.join("="))}return r}function pi(e,t){return t?Qs.parse(t)[mu(e)]:void 0}function qw(e,t){const n=mu(e),r={path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?Mw(t):void 0};return[Qs.serialize(n,"",r),Qs.serialize(n,"",{...r,partitioned:!0})]}function cl(e,t,n){const r=mu(e),i={path:"/",httpOnly:!0,secure:!0,sameSite:"none",domain:n?Mw(n):void 0};return[Qs.serialize(r,"",{...i,maxAge:0}),Qs.serialize(r,t,{...i,maxAge:_u,partitioned:!0})]}var Rz=Object.defineProperty,Lz=(e,t,n)=>t in e?Rz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lo=(e,t,n)=>Lz(e,typeof t!="symbol"?t+"":t,n);const pt=o.z.object({"#text":o.z.string()}),Dz=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":Dz,"@_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(pt)}))})),":@":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(pt)}),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 Uz=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()})}),Bz=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),Im=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(Bz)}),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(pt)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(pt)}),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(pt)}),o.z.object({"ds:Exponent":o.z.array(pt)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(pt)}))}),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(pt)}),o.z.object({"ds:Exponent":o.z.array(pt)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(pt)}))})]))})])),":@":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(pt)}),Im,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(pt),":@":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(pt)}),Im,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(pt),":@":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(pt)}))})),":@":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(pt)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(Uz)})])),":@":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 Mz={};(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,l){const u=[];let d=l.exec(c);for(;d;){const f=[];f.startIndex=l.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);u.push(f),d=l.exec(c)}return u},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,l,u){if(l){const d=Object.keys(l),f=d.length;for(let p=0;p<f;p++)u==="strict"?c[d[p]]=[l[d[p]]]:c[d[p]]=l[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(Mz);function qz(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 Fz=qz;const Hz=`
|
|
1
|
+
"use strict";var dS=Object.create;var lm=Object.defineProperty;var pS=Object.getOwnPropertyDescriptor;var fS=Object.getOwnPropertyNames;var hS=Object.getPrototypeOf,_S=Object.prototype.hasOwnProperty;var mS=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fS(t))!_S.call(e,i)&&i!==n&&lm(e,i,{get:()=>t[i],enumerable:!(r=pS(t,i))||r.enumerable});return e};var gS=(e,t,n)=>(n=e!=null?dS(hS(e)):{},mS(t||!e||!e.__esModule?lm(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var I=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 _e=e=>typeof e=="string",ss=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},um=e=>e==null?"":""+e,yS=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},bS=/###/g,dm=e=>e&&e.indexOf("###")>-1?e.replace(bS,"."):e,pm=e=>!e||_e(e),Ps=(e,t,n)=>{const r=_e(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(pm(e))return{};const s=dm(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return pm(e)?{}:{obj:e,k:dm(r[i])}},fm=(e,t,n)=>{const{obj:r,k:i}=Ps(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=Ps(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Ps(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},vS=(e,t,n,r)=>{const{obj:i,k:s}=Ps(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Vc=(e,t)=>{const{obj:n,k:r}=Ps(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},wS=(e,t,n)=>{const r=Vc(e,n);return r!==void 0?r:Vc(t,n)},fv=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?_e(e[r])||e[r]instanceof String||_e(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):fv(e[r],t[r],n):e[r]=t[r]);return e},Kr=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var kS={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const $S=e=>_e(e)?e.replace(/[&<>"'\/]/g,t=>kS[t]):e;class SS{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 xS=[" ",",","?","!",";"],zS=new SS(20),AS=(e,t,n)=>{t=t||"",n=n||"";const r=xS.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=zS.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},af=(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 l=s;l<r.length;++l)if(l!==s&&(c+=n),c+=r[l],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<r.length-1)continue;s+=l-s+1;break}i=a}return i},Zs=e=>e?.replace(/_/g,"-"),ES={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 Kc{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||ES,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:(_e(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Kc(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Kc(this.logger,t)}}var zn=new Kc;class uu{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 hm extends uu{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):_e(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Vc(this.data,c);return!l&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!_e(r)?l:af(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),fm(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)(_e(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 l=Vc(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?fv(l,r,s):l={...l,...r},fm(this.data,c,l),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 hv={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 _v=Symbol("i18next/PATH_KEY");function CS(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===_v?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function Os(e,t){const{[_v]:n}=e(CS()),r=t?.keySeparator??".",i=t?.nsSeparator??":";if(n.length>1&&i){const s=t?.ns;if((s?Array.isArray(s)?s:[s]:[]).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const _m={},Md=e=>!_e(e)&&typeof e!="boolean"&&typeof e!="number";class Gc extends uu{constructor(t,n={}){super(),yS(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=zn.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=Md(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&&!AS(t,r,i);if(a&&!c){const l=t.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:t,namespaces:_e(s)?[s]:s};const u=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(u[0])>-1)&&(s=u.shift()),t=u.join(i)}return{key:t,namespaces:_e(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=Os(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(B=>typeof B=="function"?Os(B,{...this.options,...i}):String(B));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(t[t.length-1],i),u=l[l.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:`${u}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let _=h?.res;const g=h?.usedKey||c,y=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],w=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,S=i.count!==void 0&&!_e(i.count),b=Gc.hasDefaultValue(i),x=S?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&S?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",E=S&&!i.ordinal&&i.count===0,P=E&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${x}`]||i[`defaultValue${A}`]||i.defaultValue;let R=_;k&&!_&&b&&(R=P);const C=Md(R),L=Object.prototype.toString.apply(R);if(k&&R&&C&&m.indexOf(L)<0&&!(_e(w)&&Array.isArray(R))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const B=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,R,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=B,h.usedParams=this.getUsedParamsDetails(i),h):B}if(a){const B=Array.isArray(R),V=B?[]:{},D=B?y:g;for(const ne in R)if(Object.prototype.hasOwnProperty.call(R,ne)){const ce=`${D}${a}${ne}`;b&&!_?V[ne]=this.translate(ce,{...i,defaultValue:Md(P)?P[ne]:void 0,joinArrays:!1,ns:l}):V[ne]=this.translate(ce,{...i,joinArrays:!1,ns:l}),V[ne]===ce&&(V[ne]=R[ne])}_=V}}else if(k&&_e(w)&&Array.isArray(_))_=_.join(w),_&&(_=this.extendTranslation(_,t,i,r));else{let B=!1,V=!1;!this.isValidLookup(_)&&b&&(B=!0,_=P),this.isValidLookup(_)||(V=!0,_=c);const ne=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&V?void 0:_,ce=b&&P!==_&&this.options.updateMissing;if(V||B||ce){if(this.logger.log(ce?"updateKey":"missingKey",f,u,c,ce?P:_),a){const le=this.resolve(c,{...i,keySeparator:!1});le&&le.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 ae=[];const ve=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ve&&ve[0])for(let le=0;le<ve.length;le++)ae.push(ve[le]);else this.options.saveMissingTo==="all"?ae=this.languageUtils.toResolveHierarchy(i.lng||this.language):ae.push(i.lng||this.language);const Ee=(le,Se,F)=>{const Pe=b&&F!==_?F:ne;this.options.missingKeyHandler?this.options.missingKeyHandler(le,u,Se,Pe,ce,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(le,u,Se,Pe,ce,i),this.emit("missingKey",le,u,Se,_)};this.options.saveMissing&&(this.options.saveMissingPlurals&&S?ae.forEach(le=>{const Se=this.pluralResolver.getSuffixes(le,i);E&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Se.indexOf(`${this.options.pluralSeparator}zero`)<0&&Se.push(`${this.options.pluralSeparator}zero`),Se.forEach(F=>{Ee([le],c+F,i[`defaultValue${F}`]||P)})}):Ee(ae,c,P))}_=this.extendTranslation(_,t,i,h,r),V&&_===c&&this.options.appendNamespaceToMissingKey&&(_=`${u}${d}${c}`),(V||B)&&this.options.parseMissingKeyHandler&&(_=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${c}`:c,B?_:void 0,i))}return s?(h.res=_,h.usedParams=this.getUsedParamsDetails(i),h):_}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 l=_e(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(l){const f=t.match(this.interpolator.nestingRegexp);u=f&&f.length}let d=r.replace&&!_e(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),l){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;u<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=_e(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=hv.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 _e(t)&&(t=[t]),Array.isArray(t)&&(t=t.map(l=>typeof l=="function"?Os(l,{...this.options,...n}):l)),t.forEach(l=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(l,n),d=u.key;i=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!_e(n.count),h=p&&!n.ordinal&&n.count===0,_=n.context!==void 0&&(_e(n.context)||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(y=>{this.isValidLookup(r)||(c=y,!_m[`${g[0]}-${y}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(_m[`${g[0]}-${y}`]=!0,this.logger.warn(`key "${i}" for languages "${g.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!!!")),g.forEach(m=>{if(this.isValidLookup(r))return;a=m;const w=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(w,d,m,y,n);else{let S;p&&(S=this.pluralResolver.getSuffix(m,n.count,n));const b=`${this.options.pluralSeparator}zero`,x=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&S.indexOf(x)===0&&w.push(d+S.replace(x,this.options.pluralSeparator)),w.push(d+S),h&&w.push(d+b)),_){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;w.push(A),p&&(n.ordinal&&S.indexOf(x)===0&&w.push(A+S.replace(x,this.options.pluralSeparator)),w.push(A+S),h&&w.push(A+b))}}let k;for(;k=w.pop();)this.isValidLookup(r)||(s=k,r=this.getResource(m,y,k,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&&!_e(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 mm{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=zn.create("languageUtils")}getScriptPartFromCode(t){if(t=Zs(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=Zs(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(_e(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)),_e(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 _e(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))):_e(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const gm={zero:0,one:1,two:2,few:3,many:4,other:5},ym={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class IS{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=zn.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Zs(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(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),ym;if(!t.match(/-|_/))return ym;const l=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(l,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)=>gm[i]-gm[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 bm=(e,t,n,r=".",i=!0)=>{let s=wS(e,t,n);return!s&&i&&_e(n)&&(s=af(e,n,r),s===void 0&&(s=af(t,n,r))),s},qd=e=>e.replace(/\$/g,"$$$$");class vm{constructor(t={}){this.logger=zn.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:l,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:_,nestingSuffixEscaped:g,nestingOptionsSeparator:y,maxReplaces:m,alwaysFormat:w}=t.interpolation;this.escape=n!==void 0?n:$S,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Kr(s):a||"{{",this.suffix=c?Kr(c):l||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?Kr(p):h||Kr("$t("),this.nestingSuffix=_?Kr(_):g||Kr(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=m||1e3,this.alwaysFormat=w!==void 0?w:!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 l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const m=bm(n,l,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const _=h.split(this.formatSeparator),g=_.shift().trim(),y=_.join(this.formatSeparator).trim();return this.format(bm(n,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),y,r,{...i,...n,interpolationkey:g})};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=>qd(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?qd(this.escape(h)):qd(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const _=s[1].trim();if(a=u(_),a===void 0)if(typeof d=="function"){const y=d(t,s,i);a=_e(y)?y:""}else if(i&&Object.prototype.hasOwnProperty.call(i,_))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${_} for interpolating ${t}`),a="";else!_e(a)&&!this.useRawValueToEscape&&(a=um(a));const g=h.safeValue(a);if(t=t.replace(s[0],g),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=(l,u)=>{const d=this.nestingOptionsSeparator;if(l.indexOf(d)<0)return l;const f=l.split(new RegExp(`${Kr(d)}[ ]*{`));let p=`{${f[1]}`;l=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),_=p.match(/"/g);((h?.length??0)%2===0&&!_||(_?.length??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(t);){let l=[];a={...r},a=a.replace&&!_e(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(l=i[1].slice(u).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!_e(s))return s;_e(s)||(s=um(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),l.length&&(s=l.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 jS=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,...l]=a.split(":"),u=l.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},wm=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(Zs(r),i),t[a]=c),c(n)}},NS=e=>(t,n,r)=>e(Zs(n),r)(t);class TS{constructor(t={}){this.logger=zn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?wm:NS;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()]=wm(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(l=>l.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,l)=>{const{formatName:u,formatOptions:d}=jS(l);if(this.formats[u]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[u](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return c},t)}}const PS=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class OS extends uu{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=zn.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={},l={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,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),l[f]===void 0&&(l[f]=!0)))}),d||(c[u]=!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(l)}}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(l=>{vS(l.loaded,[s],a),PS(l,t),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{c[u]||(c[u]={});const d=l.loaded[u];d.length&&d.forEach(f=>{c[u][f]===void 0&&(c[u][f]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.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=(u,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(u&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(u,d)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const u=l(t,n);u&&typeof u.then=="function"?u.then(d=>c(null,d)).catch(c):c(null,u)}catch(u){c(u)}return}return l(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();_e(t)&&(t=this.languageUtils.toResolveHierarchy(t)),_e(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 l={...a,isUpdate:s},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,i,l):d=u(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 u(t,n,r,i,c,l)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const Fd=()=>({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]),_e(e[1])&&(t.defaultValue=e[1]),_e(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}),km=e=>(_e(e.ns)&&(e.ns=[e.ns]),_e(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),_e(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),lc=()=>{},RS=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})},mv="__i18next_supportNoticeShown",LS=()=>typeof globalThis<"u"&&!!globalThis[mv],DS=()=>{typeof globalThis<"u"&&(globalThis[mv]=!0)},US=e=>!!(e?.modules?.backend?.name?.indexOf("Locize")>0||e?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||e?.options?.backend?.backends&&e.options.backend.backends.some(t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(t=>t?.projectId));class Rs extends uu{constructor(t={},n){if(super(),this.options=km(t),this.services={},this.logger=zn,this.modules={external:[]},RS(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&&(_e(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=Fd();this.options={...r,...this.options,...km(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),this.options.showSupportNotice!==!1&&!US(this)&&!LS()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),DS());const i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?zn.init(i(this.modules.logger),this.options):zn.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=TS;const d=new mm(this.options);this.store=new hm(this.options.resources,this.options);const f=this.services;f.logger=zn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new IS(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"),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(u),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new vm(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new OS(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,..._)=>{this.emit(h,..._)}),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 Gc(this.services,this.options),this.translator.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=lc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[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(u=>{this[u]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const c=ss(),l=()=>{const u=(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 u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(t,n=lc){let r=n;const i=_e(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(u=>{u!=="cimode"&&s.indexOf(u)<0&&s.push(u)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),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=ss();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=lc),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"&&hv.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=ss();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,l)=>{l?this.isLanguageChangingTo===t&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,r.resolve((...u)=>this.t(...u)),n&&n(c,(...u)=>this.t(...u))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const l=_e(c)?c:c&&c[0],u=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(_e(c)?[c]:c);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{s(d,u)})};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 l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([s,a].concat(c)):l={...a},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||i.keyPrefix);const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=Os(f,{...this.options,...a})),`${l.keyPrefix}${u}${f}`)):(typeof s=="function"&&(s=Os(s,{...this.options,...a})),d=l.keyPrefix?`${l.keyPrefix}${u}${s}`:s),this.t(d,l)};return _e(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,l)=>{const u=this.services.backendConnector.state[`${c}|${l}`];return u===-1||u===0||u===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=ss();return this.options.ns?(_e(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=ss();_e(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 mm(Fd());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 Rs(t,n);return r.createInstance=Rs.createInstance,r}cloneInstance(t={},n=lc){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Rs(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((l,u)=>(l[u]={...this.store.data[u]},l[u]=Object.keys(l[u]).reduce((d,f)=>(d[f]={...l[u][f]},d),l[u]),l),{});s.store=new hm(c,i),s.services.resourceStore=s.store}if(t.interpolation){const l={...Fd().interpolation,...this.options.interpolation,...t.interpolation},u={...i,interpolation:l};s.services.interpolator=new vm(u)}return s.translator=new Gc(s.services,i),s.translator.on("*",(c,...l)=>{s.emit(c,...l)}),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 T=Rs.createInstance();T.createInstance;T.dir;T.init;T.loadResources;T.reloadResources;T.use;T.changeLanguage;T.getFixedT;const he=T.t;T.exists;T.setDefaultNamespace;T.hasLoadedNamespace;T.loadNamespaces;T.loadLanguages;const jr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),BS=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),MS=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),qS=o.z.enum(["VERIFY_EMAIL"]),gv=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()}),yv=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())})}),bv=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:gv.optional()})}),vv=o.z.enum(["change-email","account","custom"]),wv=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:vv.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'"})})}),kv=o.z.union([yv,bv,wv]),Wc=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(kv).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),to=Wc.extend({...jr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),FS=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"})}),jt=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),$v=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()),Jc=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),username:o.z.string().optional(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:$v.optional()}),Sv=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),du=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().refine(e=>!e.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().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(),middle_name:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),address:Sv}),Zc=du.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(),password:o.z.object({hash:o.z.string(),algorithm:o.z.string()}).optional()}),dh=o.z.object({...Zc.omit({password:!0}).shape,...jr.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(Jc).optional()}),Sn=dh,HS=du.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()),VS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let KS=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=VS[n[e]&63];return t};const Xc=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(()=>KS()).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)."}),auth0_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client follows Auth0-compatible behavior (true) or strict OIDC behavior (false). When true, profile/email claims are included in the ID token when scopes are requested. When false, these claims are only available from the userinfo endpoint (strict OIDC 5.4 compliance)."}),callbacks: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()}),ti=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Xc.shape}),Yc=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."})}),ni=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Yc.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),GS=o.z.array(ni),Ii=o.z.object({x:o.z.number(),y:o.z.number()});var ph=(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))(ph||{}),fh=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(fh||{});const pu=o.z.object({id:o.z.string(),category:o.z.nativeEnum(fh),type:o.z.nativeEnum(ph)}),xv=pu.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),zv=pu.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()}),Av=pu.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()}),Ev=pu.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()}),Cv=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Iv=o.z.union([xv,zv,Av,Ev,Cv]);var jv=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(jv||{});const Nv=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ii,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Iv),next_node:o.z.string()}).passthrough()}),Tv=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ii,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Pv=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Ii,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()}),Ov=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Ii}).passthrough(),Rv=o.z.union([Nv,Tv,Pv,Ov]),Lv=o.z.object({next_node:o.z.string(),coordinates:Ii}).passthrough(),Dv=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Ii}).passthrough(),Uv=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(Rv),start:Lv,ending:Dv,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(),WS=Uv.omit({id:!0,created_at:!0,updated_at:!0});var at=(e=>(e.TOKEN="token",e.ID_TOKEN="id_token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(at||{}),pn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(pn||{}),fu=(e=>(e.S256="S256",e.Plain="plain",e))(fu||{});const Xs=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(at).optional(),response_mode:o.z.nativeEnum(pn).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(fu).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),max_age:o.z.number().optional(),acr_values:o.z.string().optional(),vendor_id:o.z.string().optional()}),Ec=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()}),Bv=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),Mv=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:Bv,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()}),JS=o.z.object({...Mv.shape,created_at:o.z.string()}),qv=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(),passwordPolicy:o.z.enum(["none","low","fair","good","excellent"]).optional(),password_complexity_options:o.z.object({min_length:o.z.number().optional()}).optional(),password_history:o.z.object({enable:o.z.boolean().optional(),size:o.z.number().optional()}).optional(),password_no_personal_info:o.z.object({enable:o.z.boolean().optional()}).optional(),password_dictionary:o.z.object({enable:o.z.boolean().optional(),dictionary:o.z.array(o.z.string()).optional()}).optional(),disable_signup:o.z.boolean().optional(),brute_force_protection:o.z.boolean().optional(),import_mode:o.z.boolean().optional(),attributes:o.z.object({email:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional(),verification:o.z.object({active:o.z.boolean().optional()}).optional()}).optional(),validation:o.z.object({allowed:o.z.boolean().optional()}).optional(),unique:o.z.boolean().optional(),profile_required:o.z.boolean().optional(),verification_method:o.z.enum(["link","code"]).optional()}).optional(),username:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional(),validation:o.z.object({max_length:o.z.number().optional(),min_length:o.z.number().optional(),allowed_types:o.z.object({email:o.z.boolean().optional(),phone_number:o.z.boolean().optional()}).optional()}).optional(),profile_required:o.z.boolean().optional()}).optional(),phone_number:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:o.z.object({password:o.z.object({enabled:o.z.boolean().optional()}).optional(),passkey:o.z.object({enabled:o.z.boolean().optional()}).optional()}).optional(),passkey_options:o.z.object({challenge_ui:o.z.enum(["both","autofill","button"]).optional(),local_enrollment_enabled:o.z.boolean().optional(),progressive_enrollment_enabled:o.z.boolean().optional()}).optional(),requires_username:o.z.boolean().optional(),validation:o.z.object({username:o.z.object({min:o.z.number().optional(),max:o.z.number().optional()}).optional()}).optional()}),Qc=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:qv.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()}),_r=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(Qc.shape),hh=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()}),Fv=o.z.discriminatedUnion("name",[o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),o.z.object({name:o.z.literal("http"),http_body:o.z.string(),http_url:o.z.string()})]),fr=o.z.object({...hh.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(Fv)}).optional(),tls_policy:o.z.string().optional()}),ZS=fr.extend({tenant_id:o.z.string()}),_h=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),Nr=_h.extend({category:o.z.literal("BLOCK").optional()}),XS=Nr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({text:o.z.string().optional()}).optional()}),YS=Nr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),QS=Nr.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()}),ex=Nr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),tx=Nr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),nx=Nr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),rx=Nr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),ix=Nr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),mh=_h.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()}),ox=mh.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),sx=mh.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),ax=mh.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),bt=_h.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()}),cx=bt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),lx=bt.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()}),ux=bt.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(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),dx=bt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional(),schema:o.z.record(o.z.any()).optional(),code:o.z.string().optional()})}),px=bt.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(),default_value:o.z.string().optional()}).optional()}),fx=bt.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(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),hx=bt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),_x=bt.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()}),mx=bt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),gx=bt.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(),default_value:o.z.string().optional()}).optional()}),yx=bt.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(),default_value:o.z.string().optional()}).optional()}),bx=bt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),vx=bt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional(),provider_details:o.z.array(o.z.object({name:o.z.string(),strategy:o.z.string().optional(),display_name:o.z.string().optional(),icon_url:o.z.string().optional()})).optional()}).optional()}),wx=bt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),kx=bt.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(),default_value:o.z.string().optional()}).optional()}),$x=bt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),Hv=o.z.discriminatedUnion("type",[XS,YS,QS,ex,tx,nx,rx,ix]),Vv=o.z.discriminatedUnion("type",[ox,sx,ax]),Kv=o.z.discriminatedUnion("type",[cx,lx,ux,dx,px,fx,hx,_x,mx,gx,yx,bx,vx,wx,kx,$x]),gh=o.z.union([Hv,Vv,Kv]),yh=new Set(["BOOLEAN","CARDS","CHOICE","DATE","DROPDOWN","EMAIL","LEGAL","NUMBER","PASSWORD","TEL","TEXT","URL"]),Sx=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()}),Ys=o.z.object({x:o.z.number(),y:o.z.number()}),xx=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ys,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()})}),zx=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Ys,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()})}),Ax=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ys,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(gh),next_node:o.z.string().optional()})}),Gv=o.z.discriminatedUnion("type",[xx,zx,Ax]),el=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(Gv).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:Ys.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:Ys.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),no=o.z.object({...jr.shape,...el.shape,id:o.z.string()}),Wv=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),Jv=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),Ex=o.z.object({name:o.z.string().optional(),action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(gh),messages:o.z.array(Wv).optional(),links:o.z.array(Jv).optional(),footer:o.z.string().optional()});function Cx(e){return e.category==="BLOCK"}function Ix(e){return e.category==="WIDGET"}function jx(e){return e.category==="FIELD"}const Zv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Xv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Yv=o.z.enum(["post-user-login","credentials-exchange"]),bh=o.z.enum(["ensure-username","set-preferred-username"]),Nx={"ensure-username":{name:"Ensure Username",description:"Automatically assigns a username to users who sign in without one. Creates a linked username account for social/email users.",trigger_id:"post-user-login"},"set-preferred-username":{name:"Set Preferred Username",description:"Sets the preferred_username claim on tokens based on the username from the primary or linked user.",trigger_id:"credentials-exchange"}},Uo={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},Tx=o.z.object({...Uo,trigger_id:Zv,url:o.z.string()}),Px=o.z.object({...Uo,trigger_id:Xv,form_id:o.z.string()}),Ox=o.z.object({...Uo,trigger_id:Yv,template_id:bh}),cf=o.z.union([Tx,Px,Ox]),Rx=o.z.object({...Uo,trigger_id:Zv,...jr.shape,hook_id:o.z.string(),url:o.z.string()}),Lx=o.z.object({...Uo,trigger_id:Xv,...jr.shape,hook_id:o.z.string(),form_id:o.z.string()}),Dx=o.z.object({...Uo,trigger_id:Yv,...jr.shape,hook_id:o.z.string(),template_id:bh}),ro=o.z.union([Rx,Lx,Dx]),Qv=o.z.object({name:o.z.string().optional()}),ew=o.z.object({email:o.z.string().optional()}),vh=o.z.object({organization_id:o.z.string().max(50),inviter:Qv,invitee:ew,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()}),Ls=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(vh.shape),wh=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()}),tw=o.z.object({keys:o.z.array(wh)}),lf=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())});var We=(e=>(e.PENDING="pending",e.AUTHENTICATED="authenticated",e.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",e.AWAITING_HOOK="awaiting_hook",e.AWAITING_CONTINUATION="awaiting_continuation",e.COMPLETED="completed",e.FAILED="failed",e.EXPIRED="expired",e))(We||{});const nw=o.z.nativeEnum(We),rw=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Xs,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(),state:nw.optional().default("pending"),state_data:o.z.string().optional(),failure_reason:o.z.string().optional(),user_id:o.z.string().optional()}).openapi({description:"This represents a login sesion"}),Ux=o.z.object({...rw.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()}),pe={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_IMPERSONATION:"fimp",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",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",SUCCESS_IMPERSONATION:"simp",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"},Bx=o.z.string().refine(e=>Object.values(pe).includes(e),{message:"Invalid log type"}),iw=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),ow=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()}),sw=o.z.object({type:Bx,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:iw.optional(),log_id:o.z.string().optional(),location_info:ow.optional()}),tl=o.z.object({...sw.shape,log_id:o.z.string()}),aw=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)}),Mx=aw.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),cw=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")}),lw=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:cw.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")}),hu=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...lw.shape}),uf=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"})}),kh=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(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),nl=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...kh.shape,id:o.z.string()});var an=(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))(an||{});const $h=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 uw=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()}),dw=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()}),Xr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),pw=o.z.object({body_text:Xr,buttons_text:Xr,font_url:o.z.string(),input_labels:Xr,links:Xr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Xr,title:Xr}),fw=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),hw=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"])}),_w=o.z.object({borders:uw,colors:dw,displayName:o.z.string(),fonts:pw,page_background:fw,widget:hw}),Cc=_w.extend({themeId:o.z.string()}),Ds=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()}),Ic=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()}),Sh=o.z.object({id:o.z.string(),login_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:cw,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),qx=o.z.object({created_at:o.z.string(),...Sh.shape}),Fx=o.z.object({to:o.z.string(),message:o.z.string()}),Hx=o.z.object({name:o.z.string(),options:o.z.object({})}),mw=o.z.object({value:o.z.string(),description:o.z.string().optional()}),gw=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()}),rl=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(mw).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:gw.optional(),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional()}),ri=o.z.object({...rl.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Vx=o.z.array(ri),yw=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),bw=o.z.object({...yw.shape,created_at:o.z.string()}),vw=o.z.array(bw),ww=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()}),kw=o.z.object({...ww.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),Kx=o.z.array(kw),$w=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()}),Sw=o.z.array($w),xw=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),zw=o.z.object({...xw.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),Gx=o.z.array(zw),il=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(),metadata:o.z.record(o.z.any()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),ii=il.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()}),ol=o.z.array(ii),Aw=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(),Ew=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"})}),Cw=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(),sl=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:Aw,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Ew).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Cw}),mr=o.z.object({...sl.shape,...jr.shape,id:o.z.string(),name:o.z.string().min(1).openapi({description:"The name of the organization"})}),Iw=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"})}),Wx=o.z.object({...Iw.shape,...jr.shape,id:o.z.string()}),Jx=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(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),jw=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"})}),Zx=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234}),io=o.z.enum(["login","login-id","login-password","signup","signup-id","signup-password","reset-password","consent","mfa","mfa-push","mfa-otp","mfa-voice","mfa-phone","mfa-webauthn","mfa-sms","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form"]),oo=o.z.record(o.z.string(),o.z.string()).openapi({type:"object",additionalProperties:{type:"string"}}),Xx=o.z.object({prompt:io,language:o.z.string(),custom_text:oo});function Yx(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function Qx(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(...l)=>{const u=await c.apply(s,l),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,l)}catch(_){try{f.onError?f.onError(_,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,_)}catch(g){console.error(`Passthrough adapter: onError handler threw for ${a}:`,g)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),u}:c.bind(s)}};return new Proxy(t,i)}function ez(e){return e}function ji(e){var t,n,r,i,s,a,c,l,u,d,f,p;const h=e?.options;if(!h)return{usernameIdentifierActive:!1,emailIdentifierActive:!0,usernameMinLength:1,usernameMaxLength:15};const _=h.attributes;if(_){const g=((n=(t=_.username)==null?void 0:t.identifier)==null?void 0:n.active)===!0,y=((i=(r=_.email)==null?void 0:r.identifier)==null?void 0:i.active)!==!1,m=((a=(s=_.username)==null?void 0:s.validation)==null?void 0:a.min_length)??1,w=((l=(c=_.username)==null?void 0:c.validation)==null?void 0:l.max_length)??15;return{usernameIdentifierActive:g,emailIdentifierActive:y,usernameMinLength:m,usernameMaxLength:w}}return{usernameIdentifierActive:h.requires_username===!0,emailIdentifierActive:!0,usernameMinLength:((d=(u=h.validation)==null?void 0:u.username)==null?void 0:d.min)??1,usernameMaxLength:((p=(f=h.validation)==null?void 0:f.username)==null?void 0:p.max)??15}}const df={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:100},buttons_text:{bold:!0,size:100},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:100},links:{bold:!0,size:100},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:100},title:{bold:!0,size:150}},page_background:{background_color:"#F8F9FB",background_image_url:"",page_layout:"center"},widget:{logo_url:"",header_text_alignment:"center",logo_height:36,logo_position:"center",social_buttons_layout:"bottom"}};function Nw(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 tz=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:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Cc}},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(df)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:Cc.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Cc}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default"),i=Nw(n||df,t);return n?await e.env.data.themes.update(e.var.tenant_id,"default",i):await e.env.data.themes.create(e.var.tenant_id,i,"default"),e.json({...i,themeId:"default"})}),$m={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"}},Sm=o.z.object({body:o.z.string()}),nz=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:Ec}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json($m)}).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(Ec.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Ec}},description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");await e.env.data.branding.set(e.var.tenant_id,t);const n=await e.env.data.branding.get(e.var.tenant_id);return e.json(n||$m)}).openapi(o.createRoute({tags:["branding"],method:"get",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sm}},description:"Universal login template"},404:{description:"Template not found"}}}),async e=>{const t=await e.env.data.universalLoginTemplates.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Template not found"});return e.json(t)}).openapi(o.createRoute({tags:["branding"],method:"put",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:Sm}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{204:{description:"Template updated successfully"},400:{description:"Invalid template"}}}),async e=>{const t=e.req.valid("json");if(!t.body.includes("{%- auth0:head -%}"))throw new I(400,{message:"Template must contain {%- auth0:head -%} tag"});if(!t.body.includes("{%- auth0:widget -%}"))throw new I(400,{message:"Template must contain {%- auth0:widget -%} tag"});return await e.env.data.universalLoginTemplates.set(e.var.tenant_id,t),e.body(null,204)}).openapi(o.createRoute({tags:["branding"],method:"delete",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:branding","auth:write"]}],responses:{204:{description:"Template deleted successfully"}}}),async e=>(await e.env.data.universalLoginTemplates.delete(e.var.tenant_id),e.body(null,204))).route("/themes",tz),rz="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let iz=e=>crypto.getRandomValues(new Uint8Array(e)),oz=(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),l=i|0;for(;l--;)if(a+=e[c[l]&r]||"",a.length>=s)return a}}},Tw=(e,t=21)=>oz(e,t|0,iz),Oe=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=rz[n[e]&63];return t};const sz=24;function Ni(){return Tw("0123456789abcdef",sz)()}function pf(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}class W extends I{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}function az(e){return async(t,n)=>{const r=n.email?.toLowerCase();if(!n.linked_to&&r&&n.email_verified){const s=await Mo({userAdapter:e.users,tenant_id:t,email:r});s&&(n.linked_to=s.user_id)}if(n.linked_to&&!await e.users.get(t,n.linked_to))throw new W(400,{error:"invalid_request",error_description:"Primary user does not exist"});const i=await e.users.create(t,n);if(n.linked_to){const s=await e.users.get(t,n.linked_to);if(!s)throw new W(500,{error:"server_error",error_description:"Failed to fetch primary user after linking"});return s}return i}}var cz={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Pw=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(cz))if(lz(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},lz=e=>navigator.userAgent.startsWith(e);function Ow(e,t){if(Pw()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function uz(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function fe(e,t,n){const r={};if(e.req.raw?.headers){const s=uz(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:n.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():Ow(e,i())}class al{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 al(Math.round(this.milliseconds()*t),"ms")}}class dz{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 Rw(e){return await crypto.subtle.digest("SHA-256",e)}const xm="0123456789abcdef";function ff(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=xm[i];const s=t[r]&15;n+=xm[s]}return n}class Lw{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 l=0;l<c;l++)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 l=[];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}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}}new Lw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Lw("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Dw{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 l=0;l<c;l++)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,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];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}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const pz=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),wr=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function zm(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=wr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=wr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),u=a.encode([c,l].join(".")),d=await hz(e).sign(t,u),f=wr.encode(new Uint8Array(d),{includePadding:!1});return[c,l,f].join(".")}function fz(e){const t=e.split(".");return t.length!==3?null:t}function Ca(e){const t=fz(e);if(!t)return null;const n=new TextDecoder,r=wr.decode(t[0],{strict:!1}),i=wr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!_z(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 l of a.aud)if(typeof l!="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 hz(e){return new dz(mz[e])}function _z(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const mz={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function jc(e){const t=new Error(e);return t.source="ulid",t}const xh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Us=xh.length,Am=Math.pow(2,48)-1,gz=10,yz=16;function bz(e){let t=Math.floor(e()*Us);return t===Us&&(t=Us-1),xh.charAt(t)}function vz(e,t){if(isNaN(e))throw new Error(e+" must be a number");if(e>Am)throw jc("cannot encode time greater than "+Am);if(e<0)throw jc("time must be positive");if(Number.isInteger(Number(e))===!1)throw jc("time must be an integer");let n,r="";for(;t>0;t--)n=e%Us,r=xh.charAt(n)+r,e=(e-n)/Us;return r}function wz(e,t){let n="";for(;e>0;e--)n=bz(t)+n;return n}function kz(e=!1,t){t||(t=typeof window<"u"?window:null);const n=t&&(t.crypto||t.msCrypto);if(n)return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};try{const r=require("crypto");return()=>r.randomBytes(1).readUInt8()/255}catch{}if(e){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw jc("secure crypto unusable, insecure Math.random not allowed")}function $z(e){return e||(e=kz()),function(n){return isNaN(n)&&(n=Date.now()),vz(n,gz)+wz(yz,e)}}const Uw=$z();function Sz(){const e=new Uint8Array(32);return crypto.getRandomValues(e),wr.encode(e,{includePadding:!1})}function xz(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 zz(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await Rw(n);return wr.encode(new Uint8Array(r),{includePadding:!1})}const Te="auth2",uc=300,_u=720*60*60,di=1440*60,Az="auth-token",Bs=1800*1e3,hf=10080*60*1e3,Ez=300,Cz=300,Iz=1800*1e3,jz=1800*1e3,Nz=1440*60*1e3;var Em=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Tz(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 Yt={},Cm;function Pz(){if(Cm)return Yt;Cm=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.parseCookie=c,Yt.parse=c,Yt.stringifyCookie=l,Yt.stringifySetCookie=u,Yt.serialize=u,Yt.parseSetCookie=d,Yt.stringifySetCookie=u,Yt.serialize=u;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,t=/^[\u0021-\u003A\u003C-\u007E]*$/,n=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,r=/^[\u0020-\u003A\u003D-\u007E]*$/,i=/^-?\d+$/,s=Object.prototype.toString,a=(()=>{const y=function(){};return y.prototype=Object.create(null),y})();function c(y,m){const w=new a,k=y.length;if(k<2)return w;const S=m?.decode||_;let b=0;do{const x=p(y,b,k);if(x===-1)break;const A=f(y,b,k);if(x>A){b=y.lastIndexOf(";",x-1)+1;continue}const E=h(y,b,x);w[E]===void 0&&(w[E]=S(h(y,x+1,A))),b=A+1}while(b<k);return w}function l(y,m){const w=m?.encode||encodeURIComponent,k=[];for(const S of Object.keys(y)){const b=y[S];if(b===void 0)continue;if(!e.test(S))throw new TypeError(`cookie name is invalid: ${S}`);const x=w(b);if(!t.test(x))throw new TypeError(`cookie val is invalid: ${b}`);k.push(`${S}=${x}`)}return k.join("; ")}function u(y,m,w){const k=typeof y=="object"?y:{...w,name:y,value:String(m)},b=(typeof m=="object"?m:w)?.encode||encodeURIComponent;if(!e.test(k.name))throw new TypeError(`argument name is invalid: ${k.name}`);const x=k.value?b(k.value):"";if(!t.test(x))throw new TypeError(`argument val is invalid: ${k.value}`);let A=k.name+"="+x;if(k.maxAge!==void 0){if(!Number.isInteger(k.maxAge))throw new TypeError(`option maxAge is invalid: ${k.maxAge}`);A+="; Max-Age="+k.maxAge}if(k.domain){if(!n.test(k.domain))throw new TypeError(`option domain is invalid: ${k.domain}`);A+="; Domain="+k.domain}if(k.path){if(!r.test(k.path))throw new TypeError(`option path is invalid: ${k.path}`);A+="; Path="+k.path}if(k.expires){if(!g(k.expires)||!Number.isFinite(k.expires.valueOf()))throw new TypeError(`option expires is invalid: ${k.expires}`);A+="; Expires="+k.expires.toUTCString()}if(k.httpOnly&&(A+="; HttpOnly"),k.secure&&(A+="; Secure"),k.partitioned&&(A+="; Partitioned"),k.priority)switch(typeof k.priority=="string"?k.priority.toLowerCase():void 0){case"low":A+="; Priority=Low";break;case"medium":A+="; Priority=Medium";break;case"high":A+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${k.priority}`)}if(k.sameSite)switch(typeof k.sameSite=="string"?k.sameSite.toLowerCase():k.sameSite){case!0:case"strict":A+="; SameSite=Strict";break;case"lax":A+="; SameSite=Lax";break;case"none":A+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${k.sameSite}`)}return A}function d(y,m){const w=m?.decode||_,k=y.length,S=f(y,0,k),b=p(y,0,S),x=b===-1?{name:"",value:w(h(y,0,S))}:{name:h(y,0,b),value:w(h(y,b+1,S))};let A=S+1;for(;A<k;){const E=f(y,A,k),P=p(y,A,E),R=P===-1?h(y,A,E):h(y,A,P),C=P===-1?void 0:h(y,P+1,E);switch(R.toLowerCase()){case"httponly":x.httpOnly=!0;break;case"secure":x.secure=!0;break;case"partitioned":x.partitioned=!0;break;case"domain":x.domain=C;break;case"path":x.path=C;break;case"max-age":C&&i.test(C)&&(x.maxAge=Number(C));break;case"expires":if(!C)break;const L=new Date(C);Number.isFinite(L.valueOf())&&(x.expires=L);break;case"priority":if(!C)break;const B=C.toLowerCase();(B==="low"||B==="medium"||B==="high")&&(x.priority=B);break;case"samesite":if(!C)break;const V=C.toLowerCase();(V==="lax"||V==="strict"||V==="none")&&(x.sameSite=V);break}A=E+1}return x}function f(y,m,w){const k=y.indexOf(";",m);return k===-1?w:k}function p(y,m,w){const k=y.indexOf("=",m);return k<w?k:-1}function h(y,m,w){let k=m,S=w;do{const b=y.charCodeAt(k);if(b!==32&&b!==9)break}while(++k<S);for(;S>k;){const b=y.charCodeAt(S-1);if(b!==32&&b!==9)break;S--}return y.slice(k,S)}function _(y){if(y.indexOf("%")===-1)return y;try{return decodeURIComponent(y)}catch{return y}}function g(y){return s.call(y)==="[object Date]"}return Yt}var Qs=Pz();function mu(e){return`${e}-${Az}`}function Mw(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 Oz(e,t){if(!t)return[];const n=mu(e),r=[],i=t.split(";");for(const s of i){const[a,...c]=s.trim().split("=");a===n&&c.length>0&&r.push(c.join("="))}return r}function pi(e,t){return t?Qs.parse(t)[mu(e)]:void 0}function qw(e,t){const n=mu(e),r={path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?Mw(t):void 0};return[Qs.serialize(n,"",r),Qs.serialize(n,"",{...r,partitioned:!0})]}function cl(e,t,n){const r=mu(e),i={path:"/",httpOnly:!0,secure:!0,sameSite:"none",domain:n?Mw(n):void 0};return[Qs.serialize(r,"",{...i,maxAge:0}),Qs.serialize(r,t,{...i,maxAge:_u,partitioned:!0})]}var Rz=Object.defineProperty,Lz=(e,t,n)=>t in e?Rz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,lo=(e,t,n)=>Lz(e,typeof t!="symbol"?t+"":t,n);const pt=o.z.object({"#text":o.z.string()}),Dz=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":Dz,"@_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(pt)}))})),":@":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(pt)}),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 Uz=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()})}),Bz=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),Im=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(Bz)}),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(pt)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(pt)}),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(pt)}),o.z.object({"ds:Exponent":o.z.array(pt)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(pt)}))}),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(pt)}),o.z.object({"ds:Exponent":o.z.array(pt)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(pt)}))})]))})])),":@":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(pt)}),Im,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(pt),":@":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(pt)}),Im,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(pt),":@":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(pt)}))})),":@":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(pt)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(Uz)})])),":@":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 Mz={};(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,l){const u=[];let d=l.exec(c);for(;d;){const f=[];f.startIndex=l.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);u.push(f),d=l.exec(c)}return u},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,l,u){if(l){const d=Object.keys(l),f=d.length;for(let p=0;p<f;p++)u==="strict"?c[d[p]]=[l[d[p]]]:c[d[p]]=l[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(Mz);function qz(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 Fz=qz;const Hz=`
|
|
2
2
|
`;function Vz(e,t){let n="";return t.format&&t.indentBy.length>0&&(n=Hz),Fw(e,t,"",n)}function Fw(e,t,n,r){let i="",s=!1;if(!Array.isArray(e)){if(e!=null){let a=e.toString();return a=_f(a,t),a}return""}for(let a=0;a<e.length;a++){const c=e[a],l=Kz(c);if(l===void 0)continue;let u="";if(n.length===0?u=l:u=`${n}.${l}`,l===t.textNodeName){let _=c[l];Gz(u,t)||(_=t.tagValueProcessor(l,_),_=_f(_,t)),s&&(i+=r),i+=_,s=!1;continue}else if(l===t.cdataPropName){s&&(i+=r),i+=`<![CDATA[${c[l][0][t.textNodeName]}]]>`,s=!1;continue}else if(l===t.commentPropName){i+=r+`<!--${c[l][0][t.textNodeName]}-->`,s=!0;continue}else if(l[0]==="?"){const _=jm(c[":@"],t),g=l==="?xml"?"":r;let y=c[l][0][t.textNodeName];y=y.length!==0?" "+y:"",i+=g+`<${l}${y}${_}?>`,s=!0;continue}let d=r;d!==""&&(d+=t.indentBy);const f=jm(c[":@"],t),p=r+`<${l}${f}`,h=Fw(c[l],t,u,d);t.unpairedTags.indexOf(l)!==-1?t.suppressUnpairedNode?i+=p+">":i+=p+"/>":(!h||h.length===0)&&t.suppressEmptyNode?i+=p+"/>":h&&h.endsWith(">")?i+=p+`>${h}${r}</${l}>`:(i+=p+">",h&&r!==""&&(h.includes("/>")||h.includes("</"))?i+=r+t.indentBy+h+r:i+=h,i+=`</${l}>`),s=!0}return i}function Kz(e){const t=Object.keys(e);for(let n=0;n<t.length;n++){const r=t[n];if(Object.prototype.hasOwnProperty.call(e,r)&&r!==":@")return r}}function jm(e,t){let n="";if(e&&!t.ignoreAttributes)for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t.attributeValueProcessor(r,e[r]);i=_f(i,t),i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function Gz(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 _f(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 Wz=Vz;const Jz=Wz,Zz=Fz,Xz={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Tr(e){this.options=Object.assign({},Xz,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Zz(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=e9),this.processTextOrObjNode=Yz,this.options.format?(this.indentate=Qz,this.tagEndChar=`>
|
|
3
3
|
`,this.newLine=`
|
|
4
4
|
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}Tr.prototype.build=function(e){return this.options.preserveOrder?Jz(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)};Tr.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 l=this.options.tagValueProcessor(a,""+e[a]);i+=this.replaceEntitiesValue(l)}else i+=this.buildTextValNode(e[a],a,"",t)}else if(Array.isArray(e[a])){const c=e[a].length;let l="",u="";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));l+=p.val,this.options.attributesGroupName&&f.hasOwnProperty(this.options.attributesGroupName)&&(u+=p.attrStr)}else l+=this.processTextOrObjNode(f,a,t,n);else if(this.options.oneListGroup){let p=this.options.tagValueProcessor(a,f);p=this.replaceEntitiesValue(p),l+=p}else l+=this.buildTextValNode(f,a,"",t)}this.options.oneListGroup&&(l=this.buildObjectNode(l,a,u,t)),i+=l}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const c=Object.keys(e[a]),l=c.length;for(let u=0;u<l;u++)r+=this.buildAttrPairStr(c[u],""+e[a][c[u]])}else i+=this.processTextOrObjNode(e[a],a,t,n);return{attrStr:r,val:i}};Tr.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 Yz(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)}Tr.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}};Tr.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};Tr.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}};Tr.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 Qz(e){return this.options.indentBy.repeat(e)}function e9(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var t9=Tr;const n9=t9;var r9={XMLBuilder:n9};let Hw=class{constructor(t,n){if(lo(this,"alphabet"),lo(this,"padding"),lo(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 l=[];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}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}};new Hw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Hw("0123456789ABCDEFGHIJKLMNOPQRSTUV");let Vw=class{constructor(t,n){if(lo(this,"alphabet"),lo(this,"padding"),lo(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,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];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}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}};new Vw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");new Vw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");const i9="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Nm=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=i9[n[e]&63];return t};async function o9(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||`_${Nm()}`,c=e.assertionId||`_${Nm()}`,l=[{"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 u=new r9.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(l);return e.signature&&t&&(u=await t.signSAML(u,e.signature.privateKeyPem,e.signature.cert)),e.encode===!1?u:btoa(u)}let Kw=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 s9(e,t,n){const r=n?`<input type="hidden" name="RelayState" value="${n}" />`:"",i=`
|
|
@@ -78,12 +78,12 @@ ${t.join(`
|
|
|
78
78
|
`,i=0;for(;i<n.length;)i+64<=n.length?r+=n.substr(i,64)+`\r
|
|
79
79
|
`:r+=n.substr(i)+`\r
|
|
80
80
|
`,i+=64;return r+=`-----END ${e} KEY-----\r
|
|
81
|
-
`,r}async function NI(e){const t=await e.publicKey.export(),n=await crypto.subtle.exportKey("jwk",t),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return ff(await Rw(s))}const TI=1e3*60*60*24,PI=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:keys","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(uf)}},description:"List of keys"}}}),async e=>{const{signingKeys:t}=await e.env.data.keys.list({q:"type:jwt_signing"}),n=t.filter(r=>"cert"in r).map(r=>r);return e.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["read:keys","auth:read"]}],responses:{200:{content:{"application/json":{schema:uf}},description:"The requested key"}}}),async e=>{const{kid:t}=e.req.valid("param"),{signingKeys:n}=await e.env.data.keys.list({q:"type:jwt_signing"}),r=n.find(i=>i.kid===t);if(!r)throw new I(404,{message:"Key not found"});return e.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:keys","auth:write"]}],responses:{201:{description:"Status"}}}),async e=>{const{signingKeys:t}=await e.env.data.keys.list({q:"type:jwt_signing"});for await(const r of t)await e.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+TI).toISOString()});const n=await Yl({name:`CN=${e.env.ORGANIZATION_NAME}`});return await e.env.data.keys.create({...n,type:"jwt_signing"}),e.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["update:keys","auth:write"]}],responses:{201:{description:"Status"}}}),async e=>{const{kid:t}=e.req.valid("param");if(!await e.env.data.keys.update(t,{revoked_at:new Date().toISOString()}))throw new I(404,{message:"Key not found"});const r=await Yl({name:`CN=${e.env.ORGANIZATION_NAME}`});return await e.env.data.keys.create({...r,type:"jwt_signing"}),e.text("OK")}),OI=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(dh)}},description:"List of users"}}}),async e=>{const{email:t}=e.req.valid("query"),r=(await Dh(e.env.data.users,e.var.tenant_id,t)).filter(i=>!i.linked_to);return e.json(r)}),RI=jt.extend({clients:o.z.array(ti)}),qy=o.z.object({enabled_connections:o.z.array(o.z.object({connection_id:o.z.string(),connection:_r.optional()}))}),LI=o.z.array(o.z.string()),DI=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([RI,o.z.array(ti)])}},description:"List of clients"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i,sort:s,q:a}=e.req.valid("query"),l=(await e.env.data.clients.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a})).clients;return i?e.json({clients:l,start:0,limit:10,length:l.length}):e.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:ti}},description:"A client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clients.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:clients","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.clients.remove(t,n))throw new I(404,{message:"Client not found"});return e.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Xc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:clients","auth:write"]}],responses:{200:{content:{"application/json":{schema:ti}},description:"The updated client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),i=e.req.valid("json");await e.env.data.clients.update(t,n,i);const s=await e.env.data.clients.get(t,n);if(!s)throw new I(404,{message:"Client not found"});return e.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Xc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:clients","auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(ti.shape)}},description:"A client"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r={...n,client_secret:n.client_secret||Oe()},i=await e.env.data.clients.create(t,r);return e.json(i,{status:201})}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}/connections",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:qy}},description:"List of connections enabled for this client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clients.get(t,n);if(!r)throw new I(404,{message:"Client not found"});const i=r.connections&&r.connections.length>0;let s;if(i)s=await Promise.all(r.connections.map(async a=>{const c=await e.env.data.connections.get(t,a);return{connection_id:a,connection:c||void 0}}));else{const{connections:a}=await e.env.data.connections.list(t,{});s=a.filter(c=>c.id).map(c=>({connection_id:c.id,connection:c}))}return e.json({enabled_connections:s})}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}/connections",request:{body:{content:{"application/json":{schema:LI}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:clients","auth:write"]}],responses:{200:{content:{"application/json":{schema:qy}},description:"Updated list of connections for this client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.clients.get(t,n))throw new I(404,{message:"Client not found"});const s=[];for(const c of r)await e.env.data.connections.get(t,c)&&s.push(c);await e.env.data.clients.update(t,n,{connections:s});const a=await Promise.all(s.map(async c=>{const l=await e.env.data.connections.get(t,c);return{connection_id:c,connection:l||void 0}}));return e.json({enabled_connections:a})}),UI=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants","settings"],method:"get",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:tenants","auth:read"]}],responses:{200:{content:{"application/json":{schema:nl}},description:"Current tenant settings"}}}),async e=>{const t=await e.env.data.tenants.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Tenant not found"});return e.json(t)}).openapi(o.createRoute({tags:["tenants","settings"],method:"patch",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(kh.shape).partial()}}}},security:[{Bearer:["update:tenants","auth:write"]}],responses:{200:{content:{"application/json":{schema:nl}},description:"Updated tenant settings"}}}),async e=>{const t=e.req.valid("json"),{id:n,...r}=t,i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(404,{message:"Tenant not found"});const s=Nw(i,r);await e.env.data.tenants.update(e.var.tenant_id,s);const a=await e.env.data.tenants.get(e.var.tenant_id);if(!a)throw new I(500,{message:"Failed to retrieve updated tenant"});return e.json(a)}),BI=jt.extend({logs:o.z.array(tl)}),MI=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:logs","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(tl),BI])}},description:"List of log rows"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.logs.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["read:logs","auth:read"]}],responses:{200:{content:{"application/json":{schema:tl}},description:"A log entry"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.logs.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}),qI=17,FI={organization:"org_",connection:"con_",action:"act_",hook:"h_",rule:"rul_",resource_server:"api_",guardian_factor:"gfa_",invite:"inv_",flow:"af_"};function kd(e){const r=Tw("0123456789abcdefghijklmnopqrstuvwxyz",qI)();return`${FI[e]}${r}`}function HI(){return kd("organization")}function VI(){return kd("connection")}function KI(){return kd("hook")}function GI(){return kd("invite")}const WI=jt.extend({hooks:o.z.array(ro)}),JI=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:hooks","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ro),WI])}},description:"List of hooks"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.hooks.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:cf}}}},security:[{Bearer:["create:hooks","auth:write"]}],responses:{201:{content:{"application/json":{schema:ro}},description:"The created hook"}}}),async e=>{const t=e.req.valid("json"),n={...t,hook_id:t.hook_id||KI()},r=await e.env.data.hooks.create(e.var.tenant_id,n);return e.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.union(cf.options.map(e=>e.omit({hook_id:!0}).partial()))}}}},security:[{Bearer:["update:hooks","auth:write"]}],responses:{200:{content:{"application/json":{schema:ro}},description:"The updated hook"},404:{description:"Hook not found"}}}),async e=>{const{hook_id:t}=e.req.valid("param"),n=e.req.valid("json");await e.env.data.hooks.update(e.var.tenant_id,t,n);const r=await e.env.data.hooks.get(e.var.tenant_id,t);if(!r)throw new I(404,{message:"Hook not found"});return e.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["read:hooks","auth:read"]}],responses:{200:{content:{"application/json":{schema:ro}},description:"A hook"},404:{description:"Hook not found"}}}),async e=>{const{hook_id:t}=e.req.valid("param"),n=await e.env.data.hooks.get(e.var.tenant_id,t);if(!n)throw new I(404,{message:"Hook not found"});return e.json(n)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["delete:hooks","auth:write"]}],responses:{200:{description:"A hook"}}}),async e=>{const{hook_id:t}=e.req.valid("param");if(!await e.env.data.hooks.remove(e.var.tenant_id,t))throw new I(404,{message:"Hook not found"});return e.text("OK")});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});du.extend({email:o.z.string(),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());const ZI=jt.extend({connections:o.z.array(_r)}),XI=o.z.object({enabled_clients:o.z.array(o.z.object({client_id:o.z.string(),name:o.z.string()}))}),YI=o.z.array(o.z.object({client_id:o.z.string(),status:o.z.boolean()})),QI=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(_r),ZI])}},description:"List of connectionss"}}}),async e=>{const{page:t,per_page:n,include_totals:r=!1,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.connections.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:_r}},description:"A connection"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.connections.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:connections","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!await e.env.data.connections.remove(n,t))throw new I(404,{message:"Connection not found"});return e.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Qc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:connections","auth:write"]}],responses:{200:{content:{"application/json":{schema:_r}},description:"The updated connection"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json"),r=e.var.tenant_id;if(!await e.env.data.connections.update(r,t,n))throw new I(404,{message:"Connection not found"});const s=await e.env.data.connections.get(r,t);if(!s)throw new I(404,{message:"Connection not found"});return e.json(s)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Qc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:connections","auth:write"]}],responses:{201:{content:{"application/json":{schema:_r}},description:"A connection"}}}),async e=>{const t=e.req.valid("json"),n=e.var.tenant_id,r=t.id||VI(),i=await e.env.data.connections.create(n,{...t,id:r});return e.json(i,{status:201})}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}/clients",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:XI}},description:"List of clients enabled for this connection"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.connections.get(e.var.tenant_id,t))throw new I(404,{message:"Connection not found"});const{clients:r}=await e.env.data.clients.list(e.var.tenant_id,{per_page:1e3}),i=r.filter(s=>s.connections?.includes(t)).map(s=>({client_id:s.client_id,name:s.name}));return e.json({enabled_clients:i})}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}/clients",request:{body:{content:{"application/json":{schema:YI}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:connections","auth:write"]}],responses:{200:{description:"Clients updated successfully"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json");if(!await e.env.data.connections.get(e.var.tenant_id,t))throw new I(404,{message:"Connection not found"});for(const i of n){const s=await e.env.data.clients.get(e.var.tenant_id,i.client_id);if(!s)continue;const a=s.connections||[];i.status?a.includes(t)||await e.env.data.clients.update(e.var.tenant_id,i.client_id,{connections:[...a,t]}):a.includes(t)&&await e.env.data.clients.update(e.var.tenant_id,i.client_id,{connections:a.filter(c=>c!==t)})}return e.text("OK")}),ej=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ds}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.promptSettings.get(e.var.tenant_id);return t?e.json(t):e.json(Ds.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ds.shape).partial()}}}},security:[{Bearer:["update:prompts","auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.promptSettings.get(e.var.tenant_id);return Object.assign(n,t),await e.env.data.promptSettings.set(e.var.tenant_id,n),e.json(n)}).openapi(o.createRoute({tags:["prompts"],method:"get",path:"/custom-text",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(o.z.object({prompt:io,language:o.z.string()}))}},description:"List of custom text entries"}}}),async e=>{const t=await e.env.data.customText.list(e.var.tenant_id);return e.json(t)}).openapi(o.createRoute({tags:["prompts"],method:"get",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:oo}},description:"Custom text for the prompt and language"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param"),r=await e.env.data.customText.get(e.var.tenant_id,t,n);return e.json(r||{})}).openapi(o.createRoute({tags:["prompts"],method:"put",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()}),body:{content:{"application/json":{schema:oo}}}},security:[{Bearer:["update:prompts","auth:write"]}],responses:{200:{content:{"application/json":{schema:oo}},description:"Updated custom text"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param"),r=oo.parse(await e.req.json());return await e.env.data.customText.set(e.var.tenant_id,t,n,r),e.json(r)}).openapi(o.createRoute({tags:["prompts"],method:"delete",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()})},security:[{Bearer:["delete:prompts","auth:write"]}],responses:{204:{description:"Custom text deleted"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param");return await e.env.data.customText.delete(e.var.tenant_id,t,n),e.body(null,204)});let Fy=!1;function N_(e){e.use(async(t,n)=>(Fy||(e.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${t.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Fy=!0),await n()))}var tj=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(const i of["domain","path"])if(n[i]&&/[;\r\n]/.test(n[i]))throw new Error(`${i} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},op=(e,t,n)=>(t=encodeURIComponent(t),tj(e,t,n)),nj=(e,t,n)=>{let r;return n?.prefix==="secure"?r=op("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?r=op("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):r=op(e,t,{path:"/",...n}),r},Hy=(e,t,n,r)=>{const i=nj(t,n,r);e.header("Set-Cookie",i,{append:!0})},Ck=e=>Ik(e.replace(/_|-/g,t=>({_:"/","-":"+"})[t]??t)),Ik=e=>{const t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length)),r=t.length/2;for(let i=0,s=t.length-1;i<=r;i++,s--)n[i]=t.charCodeAt(i),n[s]=t.charCodeAt(s);return n},Ws=(e=>(e.HS256="HS256",e.HS384="HS384",e.HS512="HS512",e.RS256="RS256",e.RS384="RS384",e.RS512="RS512",e.PS256="PS256",e.PS384="PS384",e.PS512="PS512",e.ES256="ES256",e.ES384="ES384",e.ES512="ES512",e.EdDSA="EdDSA",e))(Ws||{}),rj=class extends Error{constructor(e){super(`${e} is not an implemented algorithm`),this.name="JwtAlgorithmNotImplemented"}},Vy=class extends Error{constructor(){super('JWT verification requires "alg" option to be specified'),this.name="JwtAlgorithmRequired"}},ij=class extends Error{constructor(e,t){super(`JWT algorithm mismatch: expected "${e}", got "${t}"`),this.name="JwtAlgorithmMismatch"}},H0=class extends Error{constructor(e){super(`invalid JWT token: ${e}`),this.name="JwtTokenInvalid"}},oj=class extends Error{constructor(e){super(`token (${e}) is being used before it's valid`),this.name="JwtTokenNotBefore"}},sj=class extends Error{constructor(e){super(`token (${e}) expired`),this.name="JwtTokenExpired"}},aj=class extends Error{constructor(e,t){super(`Invalid "iat" claim, must be a valid number lower than "${e}" (iat: "${t}")`),this.name="JwtTokenIssuedAt"}},sp=class extends Error{constructor(e,t){super(`expected issuer "${e}", got ${t?`"${t}"`:"none"} `),this.name="JwtTokenIssuer"}},cj=class extends Error{constructor(e){super(`jwt header is invalid: ${JSON.stringify(e)}`),this.name="JwtHeaderInvalid"}},lj=class extends Error{constructor(e){super(`token(${e}) signature mismatched`),this.name="JwtTokenSignatureMismatched"}},uj=class extends Error{constructor(e){super(`required "aud" in jwt payload: ${JSON.stringify(e)}`),this.name="JwtPayloadRequiresAud"}},dj=class extends Error{constructor(e,t){super(`expected audience "${Array.isArray(e)?e.join(", "):e}", got "${t}"`),this.name="JwtTokenAudience"}},Ql=(e=>(e.Encrypt="encrypt",e.Decrypt="decrypt",e.Sign="sign",e.Verify="verify",e.DeriveKey="deriveKey",e.DeriveBits="deriveBits",e.WrapKey="wrapKey",e.UnwrapKey="unwrapKey",e))(Ql||{}),jk=new TextEncoder,pj=new TextDecoder;async function fj(e,t,n,r){const i=_j(t),s=await hj(e,i);return await crypto.subtle.verify(i,s,n,r)}function Ky(e){return Ik(e.replace(/-+(BEGIN|END).*/g,"").replace(/\s/g,""))}async function hj(e,t){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if(mj(e)){if(e.type==="public"||e.type==="secret")return e;e=await Gy(e)}if(typeof e=="string"&&e.includes("PRIVATE")){const r=await crypto.subtle.importKey("pkcs8",Ky(e),t,!0,[Ql.Sign]);e=await Gy(r)}const n=[Ql.Verify];return typeof e=="object"?await crypto.subtle.importKey("jwk",e,t,!1,n):e.includes("PUBLIC")?await crypto.subtle.importKey("spki",Ky(e),t,!1,n):await crypto.subtle.importKey("raw",jk.encode(e),t,!1,n)}async function Gy(e){if(e.type!=="private")throw new Error(`unexpected key type: ${e.type}`);if(!e.extractable)throw new Error("unexpected private key is unextractable");const t=await crypto.subtle.exportKey("jwk",e),{kty:n}=t,{alg:r,e:i,n:s}=t,{crv:a,x:c,y:l}=t;return{kty:n,alg:r,e:i,n:s,crv:a,x:c,y:l,key_ops:[Ql.Verify]}}function _j(e){switch(e){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"RS384":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"PS256":return{name:"RSA-PSS",hash:{name:"SHA-256"},saltLength:32};case"PS384":return{name:"RSA-PSS",hash:{name:"SHA-384"},saltLength:48};case"PS512":return{name:"RSA-PSS",hash:{name:"SHA-512"},saltLength:64};case"ES256":return{name:"ECDSA",hash:{name:"SHA-256"},namedCurve:"P-256"};case"ES384":return{name:"ECDSA",hash:{name:"SHA-384"},namedCurve:"P-384"};case"ES512":return{name:"ECDSA",hash:{name:"SHA-512"},namedCurve:"P-521"};case"EdDSA":return{name:"Ed25519",namedCurve:"Ed25519"};default:throw new rj(e)}}function mj(e){return Pw()==="node"&&crypto.webcrypto?e instanceof crypto.webcrypto.CryptoKey:e instanceof CryptoKey}var Wy=e=>JSON.parse(pj.decode(Ck(e)));function gj(e){if(typeof e=="object"&&e!==null){const t=e;return"alg"in t&&Object.values(Ws).includes(t.alg)&&(!("typ"in t)||t.typ==="JWT")}return!1}var yj=async(e,t,n)=>{if(!n)throw new Vy;const{alg:r,iss:i,nbf:s=!0,exp:a=!0,iat:c=!0,aud:l}=typeof n=="string"?{alg:n}:n;if(!r)throw new Vy;const u=e.split(".");if(u.length!==3)throw new H0(e);const{header:d,payload:f}=Nk(e);if(!gj(d))throw new cj(d);if(d.alg!==r)throw new ij(r,d.alg);const p=Math.floor(Date.now()/1e3);if(s&&f.nbf&&f.nbf>p)throw new oj(e);if(a&&f.exp&&f.exp<=p)throw new sj(e);if(c&&f.iat&&p<f.iat)throw new aj(p,f.iat);if(i){if(!f.iss)throw new sp(i,null);if(typeof i=="string"&&f.iss!==i)throw new sp(i,f.iss);if(i instanceof RegExp&&!i.test(f.iss))throw new sp(i,f.iss)}if(l){if(!f.aud)throw new uj(f);if(!(Array.isArray(f.aud)?f.aud:[f.aud]).some(m=>l instanceof RegExp?l.test(m):typeof l=="string"?m===l:Array.isArray(l)&&l.includes(m)))throw new dj(l,f.aud)}const h=e.substring(0,e.lastIndexOf("."));if(!await fj(t,r,Ck(u[2]),jk.encode(h)))throw new lj(e);return f};Ws.HS256,Ws.HS384,Ws.HS512;var Nk=e=>{const t=e.split(".");if(t.length!==3)throw new H0(e);try{const n=Wy(t[0]),r=Wy(t[1]);return{header:n,payload:r}}catch{throw new H0(e)}},Tk={verify:yj,decode:Nk},bj={Stringify:1},Cr=(e,t)=>{const n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},vj=/[&<>'"]/,wj=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];ho(s,c),n=c[0]}}return Cr(n,t)},ho=(e,t)=>{const n=e.search(vj);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=""";break;case 39:r="'";break;case 38:r="&";break;case 60:r="<";break;case 62:r=">";break;default:continue}t[0]+=e.substring(s,i)+r,s=i+1}t[0]+=e.substring(s,i)},kj=e=>{const t=e.callbacks;if(!t?.length)return e;const n=[e],r={};return t.forEach(i=>i({phase:bj.Stringify,buffer:n,context:r})),n[0]},$j=Tk.verify,Sj=Tk.decode;async function Lc(e){const{signingKeys:t}=await e.keys.list({q:"type:jwt_signing"});return await Promise.all(t.map(async r=>{const s=await new wd(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return wh.parse({...a,kid:r.kid})}))}const xj=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kty:o.z.enum(["RSA","EC","oct"]),use:o.z.enum(["sig","enc"]).optional(),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional()});async function zj(e){if(e.JWKS_URL&&e.JWKS_SERVICE)try{const t=await e.JWKS_SERVICE.fetch(e.JWKS_URL);if(!t.ok)return console.warn(`JWKS fetch failed with status ${t.status}, falling back to database`),await Lc(e.data);const n=await t.json();return o.z.object({keys:o.z.array(xj)}).parse(n).keys}catch(t){return console.warn(`JWKS fetch error: ${t instanceof Error?t.message:"Unknown error"}, falling back to database`),await Lc(e.data)}return await Lc(e.data)}async function V0(e,t){try{const{header:n}=Sj(t),i=(await zj(e.env)).find(c=>c.kid===n.kid);if(!i)throw new W(401,{message:"No matching kid found"});const s=await crypto.subtle.importKey("jwk",i,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return await $j(t,s,"RS256")}catch(n){throw n instanceof I?n:new W(403,{message:"Invalid JWT signature"})}}const Aj="urn:authhero:management";function Ej(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function $d(e){return async(t,n)=>{const r=t.req.matchedRoutes.find(l=>l.method.toUpperCase()===t.req.method&&l.path!=="/*");if(!r)return await n();const i=Ej(r.path),s="/api/v2",a=i.startsWith(s)?i.slice(s.length)||"/":i,c=e.openAPIRegistry.definitions.find(l=>"route"in l&&l.route.path===a&&l.route.method.toUpperCase()===t.req.method.toUpperCase());if(c&&"route"in c){const l=c.route.security?.[0]?.Bearer;if(l===void 0)return await n();const u=t.req.header("authorization")||"",[d,f]=u.split(" ");if(d?.toLowerCase()!=="bearer"||!f)throw new W(401,{message:"Missing bearer token"});try{const p=await V0(t,f);t.set("user_id",p.sub),t.set("user",p),p.org_name&&t.set("org_name",p.org_name),p.org_id&&t.set("organization_id",p.org_id),!t.var.tenant_id&&p.tenant_id&&t.set("tenant_id",p.tenant_id);const h=Array.isArray(p.permissions)?p.permissions:[],_=typeof p.scope=="string"?p.scope.split(" "):Array.isArray(p.scope)?p.scope:[];if(l.length&&!(l.some(g=>h.includes(g))||l.some(g=>_.includes(g))))throw new W(403,{message:"Unauthorized"})}catch(p){throw p instanceof I?p:new W(403,{message:"Invalid token"})}}return await n()}}const Cj=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:emails","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ic}},description:"Email provider"}}}),async e=>{const t=await e.env.data.emailProviders.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Email provider not found"});return e.json(t)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ic.shape)}}}},security:[{Bearer:["create:emails","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.emailProviders.create(e.var.tenant_id,t),e.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ic.shape).partial()}}}},security:[{Bearer:["update:emails","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.emailProviders.update(e.var.tenant_id,t),e.text("OK")}),Ij=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:sessions","auth:read"]}],responses:{200:{content:{"application/json":{schema:hu}},description:"A session"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.sessions.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:sessions","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.sessions.remove(e.var.tenant_id,t))throw new I(404,{message:"Session not found"});return e.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:sessions","auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.sessions.update(e.var.tenant_id,t,{revoked_at:new Date().toDateString()}))throw new I(404,{message:"Session not found"});return e.text("Session deletion request accepted.",{status:202})}),jj=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:refresh_tokens","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sh}},description:"A session"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.refreshTokens.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:refresh_tokens","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.refreshTokens.remove(e.var.tenant_id,t))throw new I(404,{message:"Session not found"});return e.text("OK")}),Nj=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:custom_domains","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(fr)}},description:"List of custom domains"}}}),async e=>{const t=await e.env.data.customDomains.list(e.var.tenant_id);return e.json(t)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:custom_domains","auth:read"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"A customDomain"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.customDomains.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:custom_domains","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.customDomains.remove(e.var.tenant_id,t))throw new I(404,{message:"Custom domain not found"});return e.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(fr.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:custom_domains","auth:write"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"The updated custom domain"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json");if(!await e.env.data.customDomains.update(e.var.tenant_id,t,n))throw new I(404);const i=await e.env.data.customDomains.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json(i)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(hh.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:custom_domains","auth:write"]}],responses:{201:{content:{"application/json":{schema:fr}},description:"The created custom domain"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.customDomains.create(e.var.tenant_id,t);return e.json(n,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:custom_domains","auth:write"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"The custom domain"}}}),async()=>{throw new I(501,{message:"Not implemented"})});function Ya(e,t){const n={};for(const[r,i]of Object.entries(t)){if(i==null)continue;const s={};for(const[a,c]of Object.entries(i))typeof c=="function"?s[a]=async(...l)=>{const u=performance.now();try{const d=await c(...l),p=performance.now()-u,h=e.res.headers.get("Server-Timing")||"",_=h?`${h}, ${r}-${a};dur=${p.toFixed(2)}`:`${r}-${a};dur=${p.toFixed(2)}`;return e.res.headers.set("Server-Timing",_),d}catch(d){const p=performance.now()-u,h=e.res.headers.get("Server-Timing")||"",_=h?`${h}, ${r}-${a}-error;dur=${p.toFixed(2)}`:`${r}-${a}-error;dur=${p.toFixed(2)}`;throw e.res.headers.set("Server-Timing",_),d}}:s[a]=c;n[r]=s}return n}async function ts(e,t){const n=e.var.user;if(n?.tenant_id)return e.set("tenant_id",n.tenant_id),await t();const r=e.req.header("tenant-id");if(r)return e.set("tenant_id",r),await t();const i=e.req.header("x-forwarded-host");if(i){const a=await e.env.data.customDomains.getByDomain(i);if(a)return e.set("tenant_id",a.tenant_id),e.set("custom_domain",i),e.set("host",i),await t()}const s=e.req.header("host");if(s){e.set("host",s);const a=await e.env.data.customDomains.getByDomain(s);if(a)return e.set("tenant_id",a.tenant_id),e.set("custom_domain",s),await t();const c=s.split(".");if(c.length>1&&typeof c[0]=="string"){const l=c[0];await e.env.data.tenants.get(l)&&e.set("tenant_id",l)}}else e.set("host",new URL($u(e.env)).host);if(!e.var.tenant_id){const{tenants:a}=await e.env.data.tenants.list({per_page:2});a.length===1&&a[0]&&e.set("tenant_id",a[0].id)}return await t()}const Tj=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()});function Pj(e){if(e)try{let t=e;try{t=atob(e)}catch{}try{const n=JSON.parse(t);return Tj.parse(n)}catch{}}catch{return}}const ns=async(e,t)=>{const n=e.req.query("auth0Client")?.slice(0,255),i=(e.req.header("x-forwarded-host")&&e.req.header("x-forwarded-for")?e.req.header("x-forwarded-for")?.split(",")[0]?.trim():e.req.header("cf-connecting-ip")||e.req.header("x-real-ip"))?.slice(0,45),s=e.req.header("user-agent")?.slice(0,512),a=e.req.header("cf-ipcountry")?.slice(0,2),c=n?Pj(n):void 0;c&&e.set("auth0_client",c),i&&e.set("ip",i),s&&e.set("useragent",s),a&&e.set("countryCode",a),await t()};function ap(e,t,n,r){try{const i=`${e}:${t}:${JSON.stringify(n)}`;return r?`${r}:${i}`:i}catch{const s=`${e}:${t}:${Date.now()}-${Math.random()}`;return r?`${r}:${s}`:s}}function Qa(e,t){const{cache:n,defaultTtl:r,customTtls:i={},excludeMethods:s=[],cacheEntities:a=[],keyPrefix:c}=t,l=new Set(s),u=a.length===0,d=new Set(a),f={};for(const[p,h]of Object.entries(e)){if(h==null)continue;const _=u||d.has(p),g={};for(const[y,m]of Object.entries(h))if(typeof m=="function"){if(!_){g[y]=m;continue}const w=`${p}:${y}`;if(l.has(w)){g[y]=m;continue}const k=i[w]??r,S=["create","update","remove","delete","set","used"].includes(y);g[y]=async(...b)=>{if(S){const P=await m.apply(h,b);try{if(b.length>=2&&["update","remove","delete"].includes(y)){const C=ap(p,"get",[b[0],b[1]],c);await n.delete(C);const L=ap(p,"list",[b[0],{}],c);await n.delete(L)}const R=c?`${c}:${p}:`:`${p}:`;await n.deleteByPrefix(R)}catch{}return P}const x=ap(p,y,b,c),A=await n.get(x);if(A!==null)if(A&&typeof A=="object"&&"isCachedNull"in A){const P=A;return P.isCachedNull?null:P.value}else return A;const E=await m.apply(h,b);if(k>=0)if(E!==null)await n.set(x,E,k);else{const P={value:null,isCachedNull:!0};await n.set(x,P,k)}return E}}else g[y]=m;f[p]=g}return f}function gc(e){if(!e)return;const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:{beforeCreate:eu(t.map(n=>n.beforeCreate),(n,r)=>[n,r],(n,r)=>[n[0],r]),afterCreate:co(t.map(n=>n.afterCreate)),beforeUpdate:eu(t.map(n=>n.beforeUpdate),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterUpdate:co(t.map(n=>n.afterUpdate)),beforeDelete:co(t.map(n=>n.beforeDelete)),afterDelete:co(t.map(n=>n.afterDelete))}}function eu(e,t,n){const r=e.filter(i=>i!==void 0);if(r.length!==0)return r.length===1?r[0]:async(...i)=>{let s=t(...i),a=s[s.length-1];for(const c of r)a=await c(...s),s=n(s,a);return a}}function co(e){const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:async(...n)=>{for(const r of t)await r(...n)}}function Oj(e){if(!e)return;const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:{beforeAssign:eu(t.map(n=>n.beforeAssign),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterAssign:co(t.map(n=>n.afterAssign)),beforeRemove:eu(t.map(n=>n.beforeRemove),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterRemove:co(t.map(n=>n.afterRemove))}}function cp(e,t,n){return t?{...e,create:async(r,i)=>{let s=i;t.beforeCreate&&(s=await t.beforeCreate(n,i));const a=await e.create(r,s);return t.afterCreate&&await t.afterCreate(n,a),a},update:async(r,i,s)=>{let a=s;t.beforeUpdate&&(a=await t.beforeUpdate(n,i,s));const c=await e.update(r,i,a);if(t.afterUpdate){let l;typeof c=="boolean"?l=await e.get(r,i):l=c,l&&await t.afterUpdate(n,i,l)}return c},remove:async(r,i)=>{t.beforeDelete&&await t.beforeDelete(n,i);const s=await e.remove(r,i);return t.afterDelete&&s&&await t.afterDelete(n,i),s}}:e}function Rj(e,t,n){return t?{...e,assign:async(r,i,s)=>{let a=s;t.beforeAssign&&(a=await t.beforeAssign(n,i,s));const c=await e.assign(r,i,a);return t.afterAssign&&c&&await t.afterAssign(n,i,a),c},remove:async(r,i,s)=>{let a=s;t.beforeRemove&&(a=await t.beforeRemove(n,i,s));const c=await e.remove(r,i,a);return t.afterRemove&&c&&await t.afterRemove(n,i,a),c}}:e}function Lj(e,t,n){return t?{...e,create:async r=>{let i=r;t.beforeCreate&&(i=await t.beforeCreate(n,r));const s=await e.create(i);return t.afterCreate&&await t.afterCreate(n,s),s},update:async(r,i)=>{let s=i;if(t.beforeUpdate&&(s=await t.beforeUpdate(n,r,i)),await e.update(r,s),t.afterUpdate){const a=await e.get(r);a&&await t.afterUpdate(n,r,a)}},remove:async r=>{t.beforeDelete&&await t.beforeDelete(n,r);const i=await e.remove(r);return t.afterDelete&&i&&await t.afterDelete(n,r),i}}:e}function Pk(e,t){const{tenantId:n,entityHooks:r}=t;if(!r)return e;const i={connections:gc(r.connections),roles:gc(r.roles),resourceServers:gc(r.resourceServers),rolePermissions:Oj(r.rolePermissions),tenants:gc(r.tenants)},s={tenantId:n,adapters:e};return{...e,connections:cp(e.connections,i.connections,s),roles:cp(e.roles,i.roles,s),resourceServers:cp(e.resourceServers,i.resourceServers,s),rolePermissions:Rj(e.rolePermissions,i.rolePermissions,s),tenants:Lj(e.tenants,i.tenants,s)}}class Dj{constructor(t={}){this.config=t;const n=t.cleanupIntervalMs;n&&n>0&&(this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},n))}cache=new Map;accessOrder=new Map;accessCounter=0;cleanupTimer;async get(t){const n=this.cache.get(t);return n?n.expiresAt&&n.expiresAt<new Date?(this.cache.delete(t),this.accessOrder.delete(t),null):(this.accessOrder.set(t,++this.accessCounter),n.value):null}async set(t,n,r){let i;const s=r??this.config.defaultTtlSeconds,a=s!==void 0,c=a?Math.max(0,s):0;a&&(i=new Date(Date.now()+(c>0?c*1e3:-1))),this.config.maxEntries&&this.cache.size>=this.config.maxEntries&&!this.cache.has(t)&&this.evictLeastRecentlyUsed();const l={value:n,expiresAt:i};this.cache.set(t,l),this.accessOrder.set(t,++this.accessCounter)}async delete(t){const n=this.cache.has(t);return this.cache.delete(t),this.accessOrder.delete(t),n}async deleteByPrefix(t){let n=0;for(const r of this.cache.keys())r.startsWith(t)&&(this.cache.delete(r),this.accessOrder.delete(r),n++);return n}async clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}getStats(){return{size:this.cache.size,maxEntries:this.config.maxEntries,defaultTtlSeconds:this.config.defaultTtlSeconds}}cleanupExpired(){const t=new Date,n=[];for(const[r,i]of this.cache.entries())i.expiresAt&&i.expiresAt<t&&n.push(r);for(const r of n)this.cache.delete(r),this.accessOrder.delete(r)}evictLeastRecentlyUsed(){let t=null,n=1/0;for(const[r,i]of this.accessOrder.entries())i<n&&(n=i,t=r);t&&(this.cache.delete(t),this.accessOrder.delete(t))}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}}function rs(e={}){return new Dj(e)}const Uj=jt.extend({forms:o.z.array(no)}),Bj=new o.OpenAPIHono().openapi(o.createRoute({tags:["forms"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:forms","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(no),Uj])}},description:"List of forms"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.forms.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.forms)}).openapi(o.createRoute({tags:["forms"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:forms","auth:read"]}],responses:{200:{content:{"application/json":{schema:no}},description:"A form"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.forms.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["forms"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:forms","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.forms.remove(t,n))throw new I(404,{message:"Form not found"});return e.text("OK")}).openapi(o.createRoute({tags:["forms"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(el.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:forms","auth:write"]}],responses:{200:{content:{"application/json":{schema:no}},description:"The updated form"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.forms.update(t,n,r))throw new I(404,{message:"Form not found"});const s=await e.env.data.forms.get(t,n);if(!s)throw new I(404,{message:"Form not found"});return e.json(s)}).openapi(o.createRoute({tags:["forms"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(el.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:forms","auth:write"]}],responses:{201:{content:{"application/json":{schema:no}},description:"A form"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.forms.create(t,n);return e.json(r,{status:201})}),Mj=jt.extend({flows:o.z.array(to)}),qj=new o.OpenAPIHono().openapi(o.createRoute({tags:["flows"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:flows","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(to),Mj])}},description:"List of flows"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.flows.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.flows)}).openapi(o.createRoute({tags:["flows"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:flows","auth:read"]}],responses:{200:{content:{"application/json":{schema:to}},description:"A flow"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.flows.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["flows"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:flows","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.flows.remove(t,n))throw new I(404,{message:"Flow not found"});return e.text("OK")}).openapi(o.createRoute({tags:["flows"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Wc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:flows","auth:write"]}],responses:{200:{content:{"application/json":{schema:to}},description:"The updated flow"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json"),i=await e.env.data.flows.update(t,n,r);if(!i)throw new I(404,{message:"Flow not found"});return e.json(i)}).openapi(o.createRoute({tags:["flows"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Wc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:flows","auth:write"]}],responses:{201:{content:{"application/json":{schema:to}},description:"The created flow"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.flows.create(t,n);return e.json(r,{status:201})}),Fj=jt.extend({roles:o.z.array(ii)}),Hj=new o.OpenAPIHono().openapi(o.createRoute({tags:["roles"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ii),Fj])}},description:"List of roles"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=e.var.tenant_id;if(!a)throw new I(400,{message:"tenant-id header is required"});const c=await e.env.data.roles.list(a,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(c):e.json(c.roles)}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:ii}},description:"A role"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});const r=await e.env.data.roles.get(n,t);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:il}}}},security:[{Bearer:["create:roles","auth:write"]}],responses:{201:{content:{"application/json":{schema:ii}},description:"Role created"}}}),async e=>{const t=e.req.valid("json"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});const r=await e.env.data.roles.create(n,t);return e.json(r,{status:201})}).openapi(o.createRoute({tags:["roles"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:il.partial()}}}},security:[{Bearer:["update:roles","auth:write"]}],responses:{200:{content:{"application/json":{schema:ii}},description:"Updated role"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.update(r,t,n))throw new I(404);const s=await e.env.data.roles.get(r,t);return e.json(s)}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:roles","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.remove(n,t))throw new I(404);return e.text("OK")}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:vw}},description:"Role permissions"}}}),async e=>{const{id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query"),a=e.var.tenant_id;if(!a)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(a,t))throw new I(404,{message:"Role not found"});const l=await e.env.data.rolePermissions.list(a,t,{page:n,per_page:r,include_totals:!1,sort:ht(i),q:s});return e.json(l)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/{id}/permissions",request:{params:o.z.object({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:roles","auth:write"]}],responses:{201:{description:"Permissions assigned to role"}}}),async e=>{const{id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(r,t))throw new I(404,{message:"Role not found"});const s=n.map(c=>({role_id:t,resource_server_identifier:c.resource_server_identifier,permission_name:c.permission_name}));if(!await e.env.data.rolePermissions.assign(r,t,s))throw new I(500,{message:"Failed to assign permissions to role"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}/permissions",request:{params:o.z.object({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:roles","auth:write"]}],responses:{200:{description:"Permissions removed from role"}}}),async e=>{const{id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(r,t))throw new I(404,{message:"Role not found"});if(!await e.env.data.rolePermissions.remove(r,t,n))throw new I(500,{message:"Failed to remove permissions from role"});return e.json({message:"Permissions removed successfully"})}),Vj=jt.extend({resource_servers:o.z.array(ri)}),Kj=new o.OpenAPIHono().openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:resource_servers","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ri),Vj])}},description:"List of resource servers"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.resourceServers.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.resource_servers)}).openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:resource_servers","auth:read"]}],responses:{200:{content:{"application/json":{schema:ri}},description:"A resource server"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.resourceServers.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["resource-servers"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:resource_servers","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.resourceServers.get(t,n);if(!r)throw new I(404,{message:"Resource server not found"});if(r.is_system)throw new I(403,{message:"System entities cannot be deleted"});return await e.env.data.resourceServers.remove(t,n),e.text("OK")}).openapi(o.createRoute({tags:["resource-servers"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(rl.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:resource_servers","auth:write"]}],responses:{200:{content:{"application/json":{schema:ri}},description:"The updated resource server"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json"),i=await e.env.data.resourceServers.get(t,n);if(!i)throw new I(404,{message:"Resource server not found"});if(i.is_system)throw new I(403,{message:"System entities cannot be modified"});await e.env.data.resourceServers.update(t,n,r);const s=await e.env.data.resourceServers.get(t,n);if(!s)throw new I(404,{message:"Resource server not found"});return e.json(s)}).openapi(o.createRoute({tags:["resource-servers"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(rl.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:resource_servers","auth:write"]}],responses:{201:{content:{"application/json":{schema:ri}},description:"A resource server"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.resourceServers.create(t,n);return e.json(r,{status:201})}),Gj=o.z.object({per_page:o.z.string().min(1).optional().default("50").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),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."}),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().min(1).optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),audience:o.z.string().optional().openapi({description:"Optional filter on audience."}),client_id:o.z.string().optional().openapi({description:"Optional filter on client_id."}),allow_any_organization:o.z.string().optional().transform(e=>e==="true"?!0:e==="false"?!1:void 0).openapi({description:"Optional filter on allow_any_organization."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"EA 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."})}),Wj=jt.extend({client_grants:o.z.array(ni)}),Jj=new o.OpenAPIHono().openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/",request:{query:Gj,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:client_grants","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ni),Wj])}},description:"List of client grants"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,from:s,take:a,audience:c,client_id:l,allow_any_organization:u,subject_type:d}=e.req.valid("query"),f=[];l&&f.push(`client_id:"${l}"`),c&&f.push(`audience:"${c}"`),u!==void 0&&f.push(`allow_any_organization:${u}`),d&&f.push(`subject_type:"${d}"`),s&&f.push(`id:>${s}`);const p=f.length>0?f.join(" AND "):void 0,h=a??r,_=await e.env.data.clientGrants.list(t,{page:n,per_page:h,include_totals:i,q:p});return i?e.json(_):e.json(_.client_grants)}).openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:client_grants","auth:read"]}],responses:{200:{content:{"application/json":{schema:ni}},description:"A client grant"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clientGrants.get(t,n);if(!r)throw new I(404,{message:"Client grant not found"});return e.json(r)}).openapi(o.createRoute({tags:["client-grants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:client_grants","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.clientGrants.remove(t,n))throw new I(404,{message:"Client grant not found"});return e.text("OK")}).openapi(o.createRoute({tags:["client-grants"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Yc.shape).partial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:client_grants","auth:write"]}],responses:{200:{content:{"application/json":{schema:ni}},description:"The updated client grant"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.clientGrants.get(t,n))throw new I(404,{message:"Client grant not found"});if(!await e.env.data.clientGrants.update(t,n,r))throw new I(500,{message:"Failed to update client grant"});const a=await e.env.data.clientGrants.get(t,n);if(!a)throw new I(404,{message:"Client grant not found"});return e.json(a)}).openapi(o.createRoute({tags:["client-grants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Yc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:client_grants","auth:write"]}],responses:{201:{content:{"application/json":{schema:ni}},description:"A client grant"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.clientGrants.create(t,n);return e.json(r,{status:201})}),Zj=o.z.object({page:o.z.string().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().optional().default("50").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:"When true, return results inside an object that also contains the start and limit. When false (default), a direct array of results is returned."}),fields:o.z.string().optional().openapi({description:"Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields."}),include_fields:o.z.string().optional().default("true").transform(e=>e==="true").openapi({description:"Whether specified fields are to be included (true) or excluded (false). Defaults to true."}),sort:o.z.string().optional().default("created_at:-1").openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. Defaults to created_at:-1."})}),Xj=o.z.object({invitations:o.z.array(Ls),start:o.z.number(),limit:o.z.number(),length:o.z.number()}),Yj=vh.omit({organization_id:!0,invitation_url:!0}),Qj=jt.extend({organizations:o.z.array(mr)}),T_=o.z.object({user_id:o.z.string().openapi({description:"ID of this user"}),email:o.z.string().email().optional().openapi({description:"Email address of this user",format:"email"}),roles:o.z.array(o.z.object({})).default([]).openapi({description:"Array of roles assigned to this user in the organization"})}),eN=o.z.object({start:o.z.number().openapi({description:"Start index of the current page"}),limit:o.z.number().openapi({description:"Number of items per page"}),total:o.z.number().openapi({description:"Total number of members"}),members:o.z.array(T_).openapi({description:"Array of organization members"})}),tN=o.z.object({next:o.z.string().optional().openapi({description:"Checkpoint ID to be used to retrieve the next set of results"}),members:o.z.array(T_).openapi({description:"Array of organization members"})}),nN=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to add to the organization"})}),rN=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to remove from the organization"})}),iN=new o.OpenAPIHono().openapi(o.createRoute({tags:["organizations"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Qj,o.z.array(mr)])}},description:"List of organizations"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i,sort:s,q:a,from:c,take:l}=e.req.valid("query"),u=await e.env.data.organizations.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a,from:c,take:l});return i?e.json(u):e.json(u.organizations)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:mr}},description:"An organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.organizations.get(t,n);if(!r)throw new I(404,{message:"Organization not found"});return e.json(r)}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:organizations","auth:write"]}],responses:{200:{description:"Organization deleted successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.organizations.remove(t,n))throw new I(404,{message:"Organization not found"});return e.text("OK")}).openapi(o.createRoute({tags:["organizations"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:sl.partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{content:{"application/json":{schema:mr}},description:"The updated organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.organizations.update(t,n,r))throw new I(404,{message:"Organization not found"});const s=await e.env.data.organizations.get(t,n);if(!s)throw new I(404,{message:"Organization not found"});return e.json(s)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:sl}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:organizations","auth:write"]}],responses:{201:{content:{"application/json":{schema:mr}},description:"The created organization"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r={...n,id:n.id||HI()},i=await e.env.data.organizations.create(t,r);return e.json(i,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(T_),eN,tN])}},description:"List of organization members"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,include_totals:s,sort:a}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const l=await e.env.data.userOrganizations.list(t,{page:r,per_page:i,include_totals:s,sort:ht(a),q:`organization_id:${n}`}),u=[];for(const d of l.userOrganizations){const f=await e.env.data.users.get(t,d.user_id);f&&u.push({user_id:f.user_id,email:f.email||void 0,roles:[]})}return s?e.json({start:l.start,limit:l.limit,total:l.length,members:u}):e.json(u)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:nN}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{204:{description:"Members added successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{members:r}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});for(const s of r)(await e.env.data.userOrganizations.list(t,{q:`user_id:${s}`,per_page:1})).userOrganizations.some(l=>l.organization_id===n)||await e.env.data.userOrganizations.create(t,{user_id:s,organization_id:n});return new Response(null,{status:204})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:rN}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{description:"Members removed successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{members:r}=e.req.valid("json");for(const i of r){const a=(await e.env.data.userOrganizations.list(t,{q:`user_id:${i}`,per_page:100})).userOrganizations.find(c=>c.organization_id===n);a&&await e.env.data.userOrganizations.remove(t,a.id)}return e.json({message:"Members removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:ol}},description:"User roles in organization"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});const a=await e.env.data.userRoles.list(t,r,void 0,n);return e.json(a)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string()).openapi({description:"List of role IDs to associate with the user"})})}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{201:{description:"Roles assigned successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param"),{roles:i}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});for(const c of i){if(!await e.env.data.roles.get(t,c))throw new I(400,{message:`Role ${c} not found`});if(!await e.env.data.userRoles.create(t,r,c,n))throw new I(500,{message:`Failed to assign role ${c} to user`})}return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string()).openapi({description:"List of role IDs to remove from the user"})})}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{description:"Roles removed successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param"),{roles:i}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});for(const c of i)if(!await e.env.data.userRoles.remove(t,r,c,n))throw new I(500,{message:`Failed to remove role ${c} from user`});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/roles",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:ol}},description:"List of roles available in organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,sort:s,q:a}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const l=await e.env.data.roles.list(t,{page:r,per_page:i,sort:ht(s),q:a});return e.json(l.roles)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),query:Zj,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ls),Xj])}},description:"List of organization invitations"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,include_totals:s,fields:a,include_fields:c,sort:l}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});let f=(await e.env.data.invites.list(t,{page:r,per_page:i})).invites.filter(p=>p.organization_id===n);if(l){const p=ht(l);if(p){const{sort_by:h,sort_order:_}=p;f.sort((g,y)=>{const m=g[h],w=y[h];if(m===void 0||w===void 0||m===w)return 0;const k=m<w?-1:1;return _==="asc"?k:-k})}}if(a){const p=a.split(",").map(h=>h.trim());f=f.map(h=>{const _={};for(const g of Object.keys(h))(c?p.includes(g):!p.includes(g))&&(_[g]=h[g]);return _})}return s?e.json({invitations:f,start:r*i,limit:i,length:f.length}):e.json(f)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ls}},description:"An invitation"},404:{description:"Invitation not found"}}}),async e=>{const t=e.var.tenant_id,{id:n,invitation_id:r}=e.req.valid("param"),i=await e.env.data.invites.get(t,r);if(!i||i.organization_id!==n)throw new I(404,{message:"Invitation not found"});return e.json(i)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),body:{content:{"application/json":{schema:Yj}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{201:{content:{"application/json":{schema:Ls}},description:"The created invitation"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const a=`https://invite.placeholder/${GI()}`,c={...r,organization_id:n,invitation_url:a},l=await e.env.data.invites.create(t,c);return e.json(l,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{204:{description:"Invitation deleted successfully"},404:{description:"Invitation not found"}}}),async e=>{const t=e.var.tenant_id,{id:n,invitation_id:r}=e.req.valid("param"),i=await e.env.data.invites.get(t,r);if(!i||i.organization_id!==n)throw new I(404,{message:"Invitation not found"});if(!await e.env.data.invites.remove(t,r))throw new I(404,{message:"Invitation not found"});return e.body(null,{status:204})}),oN=new o.OpenAPIHono().openapi(o.createRoute({tags:["stats"],method:"get",path:"/daily",request:{query:o.z.object({from:o.z.string().optional().openapi({description:"Optional first day of the date range (inclusive) in YYYYMMDD format",example:"20251120"}),to:o.z.string().optional().openapi({description:"Optional last day of the date range (inclusive) in YYYYMMDD format",example:"20251219"})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:stats","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(jw)}},description:"Daily statistics including logins, signups, and leaked passwords"}}}),async e=>{const{from:t,to:n}=e.req.valid("query");if(!e.env.data.stats)throw new I(501,{message:"Stats adapter not configured"});const r=await e.env.data.stats.getDaily(e.var.tenant_id,{from:t,to:n});return e.json(r)}).openapi(o.createRoute({tags:["stats"],method:"get",path:"/active-users",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:stats","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234})}},description:"Number of active users in the last 30 days"}}}),async e=>{if(!e.env.data.stats)throw new I(501,{message:"Stats adapter not configured"});const t=await e.env.data.stats.getActiveUsers(e.var.tenant_id);return e.json(t)}),Dc=["sms","otp","email","push-notification","webauthn-roaming","webauthn-platform","recovery-code","duo"];function lp(e){return e.replace(/-/g,"_")}const K0=o.z.object({name:o.z.enum(Dc),enabled:o.z.boolean(),trial_expired:o.z.boolean().optional()}),sN=o.z.array(K0),aN=o.z.object({enabled:o.z.boolean()}),up=o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"])}),dp=o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}),cN=o.z.object({message_type:o.z.enum(["sms","voice"])}),lN=new o.OpenAPIHono().openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:sN}},description:"List of MFA factors"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.factors,r=Dc.map(i=>{const s=lp(i);return{name:i,enabled:!!n?.[s],trial_expired:!1}});return e.json(r)}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/sms/selected-provider",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:up}},description:"Selected SMS provider"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.sms_provider?.provider||"twilio";return e.json({provider:n})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/sms/selected-provider",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:up}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:up}},description:"Updated SMS provider selection"}}}),async e=>{const{provider:t}=e.req.valid("json"),n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new I(404,{message:"Tenant not found"});return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...n.mfa,sms_provider:{provider:t}}}),e.json({provider:t})}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/sms/providers/twilio",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:dp}},description:"Twilio provider configuration"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.twilio||{};return e.json({sid:n.sid,auth_token:n.auth_token?"********":void 0,from:n.from,messaging_service_sid:n.messaging_service_sid})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/sms/providers/twilio",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:dp}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:dp}},description:"Updated Twilio configuration"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new I(404,{message:"Tenant not found"});const r=n.mfa?.twilio||{},i={...r,...t,auth_token:t.auth_token&&t.auth_token!=="********"?t.auth_token:r.auth_token};return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...n.mfa,twilio:i}}),e.json({sid:i.sid,auth_token:i.auth_token?"********":void 0,from:i.from,messaging_service_sid:i.messaging_service_sid})}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/phone/message-types",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(cN)}},description:"Available message types"}}}),async e=>{const t=[{message_type:"sms"}];return e.json(t)}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/{factor_name}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({factor_name:o.z.enum(Dc)})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:K0}},description:"MFA factor details"}}}),async e=>{const{factor_name:t}=e.req.valid("param"),r=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.factors,i=lp(t);return e.json({name:t,enabled:!!r?.[i],trial_expired:!1})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/{factor_name}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({factor_name:o.z.enum(Dc)}),body:{content:{"application/json":{schema:aN}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:K0}},description:"Updated MFA factor"}}}),async e=>{const{factor_name:t}=e.req.valid("param"),{enabled:n}=e.req.valid("json"),r=lp(t),i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(404,{message:"Tenant not found"});const s=i.mfa?.factors;return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...i.mfa,factors:{sms:s?.sms??!1,otp:s?.otp??!1,email:s?.email??!1,push_notification:s?.push_notification??!1,webauthn_roaming:s?.webauthn_roaming??!1,webauthn_platform:s?.webauthn_platform??!1,recovery_code:s?.recovery_code??!1,duo:s?.duo??!1,[r]:n}}}),e.json({name:t,enabled:n,trial_expired:!1})});function uN(e){const t=new o.OpenAPIHono,n=e.managementDataAdapter??e.dataAdapter;t.use(async(i,s)=>{const a=i.req.header("origin"),c=l=>{i.res.headers.set("Access-Control-Allow-Origin",l),i.res.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),i.res.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),i.res.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),i.res.headers.set("Access-Control-Max-Age","600"),i.res.headers.set("Access-Control-Allow-Credentials","true")};if(i.req.method==="OPTIONS"){const l=new Response(null,{status:204});if(a){if(e.allowedOrigins?.includes(a))return l.headers.set("Access-Control-Allow-Origin",a),l.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),l.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),l.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),l.headers.set("Access-Control-Max-Age","600"),l.headers.set("Access-Control-Allow-Credentials","true"),l;const u=i.req.header("tenant-id");if(u&&(await n.clients.list(u,{})).clients.flatMap(p=>p.web_origins||[]).includes(a))return l.headers.set("Access-Control-Allow-Origin",a),l.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),l.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),l.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),l.headers.set("Access-Control-Max-Age","600"),l.headers.set("Access-Control-Allow-Credentials","true"),l}return l}if(await s(),a){if(e.allowedOrigins?.includes(a)){c(a);return}const l=i.var.tenant_id||i.req.header("tenant-id");l&&(await n.clients.list(l,{})).clients.flatMap(f=>f.web_origins||[]).includes(a)&&c(a)}}),N_(t),t.use(async(i,s)=>{const a=Bo(i,n),c=rs({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),l=Qa(a,{defaultTtl:0,cacheEntities:["tenants","connections","clients","branding","themes","promptSettings","customText","forms","hooks"],cache:c});return i.env.data=Ya(i,l),i.env.entityHooks=e.entityHooks,s()}),t.use(ns).use(ts).use($d(t)).use(async(i,s)=>(e.entityHooks&&i.var.tenant_id&&(i.env.data=Pk(i.env.data,{tenantId:i.var.tenant_id,entityHooks:e.entityHooks})),s()));const r=t.route("/branding",nz).route("/custom-domains",Nj).route("/email/providers",Cj).route("/users",P7).route("/keys",PI).route("/users-by-email",OI).route("/clients",DI).route("/client-grants",Jj).route("/tenants",UI).route("/logs",MI).route("/hooks",JI).route("/connections",QI).route("/prompts",ej).route("/sessions",Ij).route("/refresh_tokens",jj).route("/forms",Bj).route("/flows",qj).route("/roles",Hj).route("/resource-servers",Kj).route("/organizations",iN).route("/stats",oN).route("/guardian",lN);if(e.managementApiExtensions)for(const i of e.managementApiExtensions)r.route(i.path,i.router);return r.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management API"},servers:[{url:"/api/v2",description:"API V2"}],security:[{oauth2:["openid","email","profile"]}]}),r}var Ok=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 l(d,f){a.res.headers.set(d,f)}const u=await r(a.req.header("origin")||"",a);if(u&&l("Access-Control-Allow-Origin",u),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());const d=await i(a.req.header("origin")||"",a);d.length&&l("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&&(l("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})}};function rr(e){if(e)return`${e.name}/${e.version}${e.env?.node?` (env: node/${e.env.node})`:""}`}function Vt(e,t){const n=e.var.tenant_id;if(!n){e.set("tenant_id",t);return}if(n!==t)throw new I(403,{message:"Tenant mismatch"})}async function Jy(e,t,n,r){if(!r.state)throw new W(400,{message:"State not found"});const i=t.connections.find(l=>l.name===n);if(!i)throw e.set("client_id",t.client_id),await fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Connection not found"}),new W(403,{message:"Connection Not Found"});let s=await e.env.data.loginSessions.get(t.tenant.id,r.state);if(!s){const l=e.get("ip"),u=e.get("useragent"),d=e.get("auth0_client");s=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),ip:l,useragent:u,auth0Client:rr(d)})}const c=await U2(e,i.strategy).getRedirect(e,i);return await e.env.data.codes.create(t.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+Cz*1e3).toISOString()}),new Response(null,{status:302,headers:{location:c.redirectUrl}})}async function Zy(e,{code:t,state:n}){const{env:r}=e,i=await r.data.codes.get(e.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new W(403,{message:"State not found"});const s=await r.data.loginSessions.get(e.var.tenant_id||"",i.login_id);if(!s)throw new W(403,{message:"Session not found"});if(s.authorization_url){const _=new URL(s.authorization_url).hostname,g=e.var.host||"";if(_!==g&&_){const y=new URL(`https://${_}/callback`);return y.searchParams.set("state",n),y.searchParams.set("code",t),new Response("Redirecting",{status:307,headers:{location:y.toString()}})}}const a=await He(r,s.authParams.client_id);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c=a.connections.find(_=>_.id===i.connection_id);if(!c)throw await fe(e,a.tenant.id,{type:pe.FAILED_LOGIN,description:"Connection not found"}),new W(403,{message:"Connection not found"});if(e.set("connection",c.name),!s.authParams.redirect_uri)throw await fe(e,a.tenant.id,{type:pe.FAILED_LOGIN,description:"Redirect URI not defined"}),new W(403,{message:"Redirect URI not defined"});const u=await U2(e,c.strategy).validateAuthorizationCodeAndGetUser(e,c,t,i.code_verifier),{sub:d,...f}=u;e.set("user_id",d);const p=u.email?.toLocaleLowerCase()||`${c.name}.${d}@${new URL(e.env.ISSUER).hostname}`;e.set("username",p);const h=await Cu(e,{client:a,username:p,provider:c.strategy,connection:c.name,userId:d,profileData:f,isSocial:!0,ip:e.var.ip});return yt(e,{client:a,authParams:s.authParams,loginSession:s,user:h,authStrategy:{strategy:c.strategy,strategy_type:"social"}})}async function yc(e,t,n,r,i,s){const a=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(!a)throw new I(400,{message:"State not found"});const c=await e.env.data.loginSessions.get(e.var.tenant_id,a.login_id);if(!c)throw new I(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new I(400,{message:"Redirect uri not found"});fe(e,e.var.tenant_id,{type:pe.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});const u=new URL(l);return LA(u,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),e.redirect(`${mt(e.env)}login/identifier?state=${c.id}&error=${encodeURIComponent(n)}${r?`&error_description=${encodeURIComponent(r)}`:""}`)}const dN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{state:t,code:n,error:r,error_description:i,error_code:s,error_reason:a}=e.req.valid("query");if(r)return yc(e,t,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});try{const c=await Zy(e,{code:n,state:t});if(!(c instanceof Response))throw new I(500,{message:"Internal server error"});return c}catch(c){if(c instanceof W&&c.status===400){const l=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(l&&await e.env.data.loginSessions.get(e.var.tenant_id,l.login_id)){let d="access_denied";try{d=JSON.parse(c.message).message||d}catch{d=c.message||d}return yc(e,t,"access_denied",d)}}throw c}}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{state:t,code:n,error:r,error_description:i,error_code:s,error_reason:a}=e.req.valid("form");if(r)return yc(e,t,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});try{const c=await Zy(e,{code:n,state:t});if(!(c instanceof Response))throw new I(500,{message:"Internal server error"});return c}catch(c){if(c instanceof W&&c.status===400){const l=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(l&&await e.env.data.loginSessions.get(e.var.tenant_id,l.login_id)){let d="access_denied";try{d=JSON.parse(c.message).message||d}catch{d=c.message||d}return yc(e,t,"access_denied",d)}}throw c}});function P_(e,t=[],n={}){try{const r=new URL(e);return t.some(i=>{try{return pN(r,new URL(i),n)}catch{return!1}})}catch{return!1}}function pN(e,t,n={}){if(e.protocol!==t.protocol)return!1;if(n.allowPathWildcards&&t.pathname.includes("*")){const r=t.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(e.pathname))return!1}else if(e.pathname!==t.pathname)return!1;if(n.allowSubDomainWildcards&&t.hostname.startsWith("*.")&&t.hostname.split(".").length>2&&["http:","https:"].includes(t.protocol)){const r=t.hostname.split(".").slice(1).join(".");return e.hostname===r||e.hostname.endsWith("."+r)}return e.hostname===t.hostname}const fN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async e=>{const{client_id:t,returnTo:n}=e.req.valid("query");let r;try{r=await He(e.env,t)}catch{return e.text("OK")}let i;try{i=await He(e.env,"DEFAULT_CLIENT")}catch{}e.set("client_id",t),Vt(e,r.tenant.id);const s=n||e.req.header("referer");if(!s)return e.text("OK");if(!P_(s,[...r.allowed_logout_urls||[],...i?.allowed_logout_urls||[]],{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:"Invalid redirect uri"});const a=e.req.header("cookie");if(a){const u=pi(r.tenant.id,a);if(u){const d=await e.env.data.sessions.get(r.tenant.id,u);if(d){const f=await e.env.data.users.get(r.tenant.id,d.user_id);if(f&&(e.set("user_id",f.user_id),e.set("connection",f.connection)),d.login_session_id){const p=await e.env.data.refreshTokens.list(r.tenant.id,{q:`login_id=${d.login_session_id}`,page:0,per_page:100,include_totals:!1});await Promise.all(p.refresh_tokens.map(h=>e.env.data.refreshTokens.remove(r.tenant.id,h.id)))}await e.env.data.sessions.update(r.tenant.id,u,{revoked_at:new Date().toISOString()})}}}fe(e,r.tenant.id,{type:pe.SUCCESS_LOGOUT,description:"User successfully logged out"});const c=new Headers;return qw(r.tenant.id,e.var.custom_domain||e.req.header("host")).forEach(u=>{c.append("set-cookie",u)}),c.set("location",s),new Response("Redirecting",{status:302,headers:c})}),hN=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),Xy=o.z.object({sub:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_number_verified:o.z.boolean().optional(),name:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),middle_name:o.z.string().optional(),nickname:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),picture:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),locale:o.z.string().optional(),updated_at:o.z.number().optional(),address:hN});function Yy(e,t){const n={sub:e.user_id};if(t.includes("email")&&(e.email&&(n.email=e.email),e.email_verified!==void 0&&(n.email_verified=e.email_verified)),t.includes("profile")){e.name&&(n.name=e.name),e.family_name&&(n.family_name=e.family_name),e.given_name&&(n.given_name=e.given_name),e.middle_name&&(n.middle_name=e.middle_name),e.nickname&&(n.nickname=e.nickname);const r=e.preferred_username||e.username;r&&(n.preferred_username=r),e.profile&&(n.profile=e.profile),e.picture&&(n.picture=e.picture),e.website&&(n.website=e.website),e.gender&&(n.gender=e.gender),e.birthdate&&(n.birthdate=e.birthdate),e.zoneinfo&&(n.zoneinfo=e.zoneinfo),e.locale&&(n.locale=e.locale),e.updated_at&&(n.updated_at=Math.floor(new Date(e.updated_at).getTime()/1e3))}return t.includes("address")&&e.address&&(n.address=e.address),t.includes("phone")&&(e.phone_number&&(n.phone_number=e.phone_number),e.phone_verified!==void 0&&(n.phone_number_verified=e.phone_verified)),n}const _N=o.z.object({access_token:o.z.string().optional()}),mN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Xy}},description:"Userinfo"}}}),async e=>{if(!e.var.user)throw new I(404,{message:"User not found"});const t=e.var.user.tenant_id||e.var.tenant_id;if(!t)throw new I(400,{message:"Unable to determine tenant"});const n=await e.env.data.users.get(t,e.var.user.sub);if(!n)throw new I(404,{message:"User not found"});const i=e.var.user?.scope?.split(" ")||[],s=Yy(n,i),a=e.env.hooks?.onFetchUserInfo;if(a){const c={};return await a({ctx:e,user:n,tenant_id:t,scopes:i},{setCustomClaim:(l,u)=>{c[l]=u}}),e.json({...s,...c})}return e.json(s)}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:_N}}}},responses:{200:{content:{"application/json":{schema:Xy}},description:"Userinfo"}}}),async e=>{let t=null;if(e.var.user&&(t=e.var.user),!t){const c=e.req.header("authorization")||"",[l,u]=c.split(" ");if(l?.toLowerCase()==="bearer"&&u){if(t=await V0(e,u),!(t?.scope?.split(" ")||[]).includes("openid"))throw new W(403,{message:"openid scope required"});e.set("user",t)}}if(!t)try{const c=await e.req.parseBody(),l=typeof c.access_token=="string"?c.access_token:void 0;if(l){if(t=await V0(e,l),!(t?.scope?.split(" ")||[]).includes("openid"))throw new W(403,{message:"openid scope required"});e.set("user",t)}}catch(c){if(c instanceof I||c instanceof W)throw c}if(!t)throw new I(401,{message:"No access token provided"});const n=t.tenant_id||e.var.tenant_id;if(!n)throw new I(400,{message:"Unable to determine tenant"});const r=await e.env.data.users.get(n,t.sub);if(!r)throw new I(404,{message:"User not found"});const i=t?.scope?.split(" ")||[],s=Yy(r,i),a=e.env.hooks?.onFetchUserInfo;if(a){const c={};return await a({ctx:e,user:r,tenant_id:n,scopes:i},{setCustomClaim:(l,u)=>{c[l]=u}}),e.json({...s,...c})}return e.json(s)}),gN=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:tw}},description:"List of tenants"}}}),async e=>{const t=await Lc(e.env.data);return e.json({keys:t},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${uc}, stale-while-revalidate=${uc*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:lf}},description:"List of tenants"}}}),async e=>{const t=lf.parse({issuer:$u(e.env),authorization_endpoint:`${Le(e.env)}authorize`,token_endpoint:`${Le(e.env)}oauth/token`,device_authorization_endpoint:`${Le(e.env)}oauth/device/code`,userinfo_endpoint:`${Le(e.env)}userinfo`,mfa_challenge_endpoint:`${Le(e.env)}mfa/challenge`,jwks_uri:`${Le(e.env)}.well-known/jwks.json`,registration_endpoint:`${Le(e.env)}oidc/register`,revocation_endpoint:`${Le(e.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return e.json(t,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${uc}, stale-while-revalidate=${uc*2}, stale-if-error=86400`}})});function Js(e,t){if(!e||!t||e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}const Rk=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional(),organization:o.z.string().optional()});async function yN(e,t){const n=await He(e.env,t.client_id,e.var.tenant_id);if(n.client_secret&&!Js(n.client_secret,t.client_secret))throw new W(403,{message:"Invalid client credentials"});let r;if(t.organization){const s=await e.env.data.organizations.get(n.tenant.id,t.organization);if(!s)throw new W(400,{error:"invalid_request",error_description:`Organization '${t.organization}' not found`});r={id:s.id,name:s.name}}const i={client_id:n.client_id,scope:t.scope,audience:t.audience||n.tenant.default_audience,organization:t.organization};return{client:n,authParams:i,organization:r}}const bN=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.z.string().optional(),organization:o.z.string().optional()}).refine(e=>"client_secret"in e&&!("code_verifier"in e)||!("client_secret"in e)&&"code_verifier"in e,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function vN(e,t){const n=await He(e.env,t.client_id,e.var.tenant_id),r=await e.env.data.codes.get(n.tenant.id,t.code,"authorization_code");if(!r||!r.user_id)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials"}),new W(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Code expired",userId:r.user_id}),new W(403,{message:"Code expired"});if(r.used_at)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid authorization code",userId:r.user_id}),new W(400,{error:"invalid_grant",error_description:"Invalid authorization code"});const i=await e.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new W(403,{message:"Invalid login"});if(t.organization&&i.authParams.organization&&t.organization!==i.authParams.organization)throw new W(400,{error:"invalid_request",error_description:"Organization parameter does not match login session organization"});if("client_secret"in t){let u;try{u=await He(e.env,"DEFAULT_CLIENT")}catch{}if(!Js(n.client_secret,t.client_secret)&&!Js(u?.client_secret,t.client_secret))throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new W(403,{message:"Invalid client credentials"})}else if(r.code_challenge&&r.code_challenge_method&&t.code_verifier){const u=await zz(t.code_verifier,r.code_challenge_method);if(!Js(u,r.code_challenge))throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new W(403,{message:"Invalid client credentials"})}if(r.redirect_uri&&r.redirect_uri!==t.redirect_uri)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid redirect uri",userId:r.user_id}),new W(403,{message:"Invalid redirect uri"});const s=await e.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new W(403,{message:"User not found"});await e.env.data.codes.used(n.tenant.id,t.code);let a;i.session_id&&i.authParams.scope?.split(" ").includes("offline_access")&&(a=await b2(e,{user:s,client:n,login_id:i.id,scope:i.authParams.scope,audience:i.authParams.audience}));let c;if(i.authParams.organization){const u=await e.env.data.organizations.get(n.tenant.id,i.authParams.organization);u?c={id:u.id,name:u.name}:c={id:i.authParams.organization,name:"Unknown"}}let l;if(i.authParams.max_age!==void 0&&i.session_id){const u=await e.env.data.sessions.get(n.tenant.id,i.session_id);u?.authenticated_at&&(l=Math.floor(new Date(u.authenticated_at).getTime()/1e3))}return{user:s,client:n,loginSession:i,session_id:i.session_id,refresh_token:a?.id,organization:c,auth_time:l,authParams:{...i.authParams,state:r.state,nonce:r.nonce,response_mode:pn.WEB_MESSAGE,client_id:n.client_id,scope:i.authParams.scope,audience:i.authParams.audience}}}function Qy(e,t){const n=e.var.log;n?e.set("log",`${n}
|
|
81
|
+
`,r}async function NI(e){const t=await e.publicKey.export(),n=await crypto.subtle.exportKey("jwk",t),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return ff(await Rw(s))}const TI=1e3*60*60*24,PI=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:keys","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(uf)}},description:"List of keys"}}}),async e=>{const{signingKeys:t}=await e.env.data.keys.list({q:"type:jwt_signing"}),n=t.filter(r=>"cert"in r).map(r=>r);return e.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["read:keys","auth:read"]}],responses:{200:{content:{"application/json":{schema:uf}},description:"The requested key"}}}),async e=>{const{kid:t}=e.req.valid("param"),{signingKeys:n}=await e.env.data.keys.list({q:"type:jwt_signing"}),r=n.find(i=>i.kid===t);if(!r)throw new I(404,{message:"Key not found"});return e.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:keys","auth:write"]}],responses:{201:{description:"Status"}}}),async e=>{const{signingKeys:t}=await e.env.data.keys.list({q:"type:jwt_signing"});for await(const r of t)await e.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+TI).toISOString()});const n=await Yl({name:`CN=${e.env.ORGANIZATION_NAME}`});return await e.env.data.keys.create({...n,type:"jwt_signing"}),e.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["update:keys","auth:write"]}],responses:{201:{description:"Status"}}}),async e=>{const{kid:t}=e.req.valid("param");if(!await e.env.data.keys.update(t,{revoked_at:new Date().toISOString()}))throw new I(404,{message:"Key not found"});const r=await Yl({name:`CN=${e.env.ORGANIZATION_NAME}`});return await e.env.data.keys.create({...r,type:"jwt_signing"}),e.text("OK")}),OI=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(dh)}},description:"List of users"}}}),async e=>{const{email:t}=e.req.valid("query"),r=(await Dh(e.env.data.users,e.var.tenant_id,t)).filter(i=>!i.linked_to);return e.json(r)}),RI=jt.extend({clients:o.z.array(ti)}),qy=o.z.object({enabled_connections:o.z.array(o.z.object({connection_id:o.z.string(),connection:_r.optional()}))}),LI=o.z.array(o.z.string()),DI=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([RI,o.z.array(ti)])}},description:"List of clients"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i,sort:s,q:a}=e.req.valid("query"),l=(await e.env.data.clients.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a})).clients;return i?e.json({clients:l,start:0,limit:10,length:l.length}):e.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:ti}},description:"A client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clients.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:clients","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.clients.remove(t,n))throw new I(404,{message:"Client not found"});return e.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Xc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:clients","auth:write"]}],responses:{200:{content:{"application/json":{schema:ti}},description:"The updated client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),i=e.req.valid("json");await e.env.data.clients.update(t,n,i);const s=await e.env.data.clients.get(t,n);if(!s)throw new I(404,{message:"Client not found"});return e.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Xc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:clients","auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(ti.shape)}},description:"A client"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r={...n,client_secret:n.client_secret||Oe()},i=await e.env.data.clients.create(t,r);return e.json(i,{status:201})}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}/connections",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:clients","auth:read"]}],responses:{200:{content:{"application/json":{schema:qy}},description:"List of connections enabled for this client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clients.get(t,n);if(!r)throw new I(404,{message:"Client not found"});const i=r.connections&&r.connections.length>0;let s;if(i)s=await Promise.all(r.connections.map(async a=>{const c=await e.env.data.connections.get(t,a);return{connection_id:a,connection:c||void 0}}));else{const{connections:a}=await e.env.data.connections.list(t,{});s=a.filter(c=>c.id).map(c=>({connection_id:c.id,connection:c}))}return e.json({enabled_connections:s})}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}/connections",request:{body:{content:{"application/json":{schema:LI}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:clients","auth:write"]}],responses:{200:{content:{"application/json":{schema:qy}},description:"Updated list of connections for this client"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.clients.get(t,n))throw new I(404,{message:"Client not found"});const s=[];for(const c of r)await e.env.data.connections.get(t,c)&&s.push(c);await e.env.data.clients.update(t,n,{connections:s});const a=await Promise.all(s.map(async c=>{const l=await e.env.data.connections.get(t,c);return{connection_id:c,connection:l||void 0}}));return e.json({enabled_connections:a})}),UI=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants","settings"],method:"get",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:tenants","auth:read"]}],responses:{200:{content:{"application/json":{schema:nl}},description:"Current tenant settings"}}}),async e=>{const t=await e.env.data.tenants.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Tenant not found"});return e.json(t)}).openapi(o.createRoute({tags:["tenants","settings"],method:"patch",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(kh.shape).partial()}}}},security:[{Bearer:["update:tenants","auth:write"]}],responses:{200:{content:{"application/json":{schema:nl}},description:"Updated tenant settings"}}}),async e=>{const t=e.req.valid("json"),{id:n,...r}=t,i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(404,{message:"Tenant not found"});const s=Nw(i,r);await e.env.data.tenants.update(e.var.tenant_id,s);const a=await e.env.data.tenants.get(e.var.tenant_id);if(!a)throw new I(500,{message:"Failed to retrieve updated tenant"});return e.json(a)}),BI=jt.extend({logs:o.z.array(tl)}),MI=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:logs","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(tl),BI])}},description:"List of log rows"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.logs.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["read:logs","auth:read"]}],responses:{200:{content:{"application/json":{schema:tl}},description:"A log entry"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.logs.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}),qI=17,FI={organization:"org_",connection:"con_",action:"act_",hook:"h_",rule:"rul_",resource_server:"api_",guardian_factor:"gfa_",invite:"inv_",flow:"af_"};function kd(e){const r=Tw("0123456789abcdefghijklmnopqrstuvwxyz",qI)();return`${FI[e]}${r}`}function HI(){return kd("organization")}function VI(){return kd("connection")}function KI(){return kd("hook")}function GI(){return kd("invite")}const WI=jt.extend({hooks:o.z.array(ro)}),JI=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:hooks","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ro),WI])}},description:"List of hooks"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.hooks.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:cf}}}},security:[{Bearer:["create:hooks","auth:write"]}],responses:{201:{content:{"application/json":{schema:ro}},description:"The created hook"}}}),async e=>{const t=e.req.valid("json"),n={...t,hook_id:t.hook_id||KI()},r=await e.env.data.hooks.create(e.var.tenant_id,n);return e.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.union(cf.options.map(e=>e.omit({hook_id:!0}).partial()))}}}},security:[{Bearer:["update:hooks","auth:write"]}],responses:{200:{content:{"application/json":{schema:ro}},description:"The updated hook"},404:{description:"Hook not found"}}}),async e=>{const{hook_id:t}=e.req.valid("param"),n=e.req.valid("json");await e.env.data.hooks.update(e.var.tenant_id,t,n);const r=await e.env.data.hooks.get(e.var.tenant_id,t);if(!r)throw new I(404,{message:"Hook not found"});return e.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["read:hooks","auth:read"]}],responses:{200:{content:{"application/json":{schema:ro}},description:"A hook"},404:{description:"Hook not found"}}}),async e=>{const{hook_id:t}=e.req.valid("param"),n=await e.env.data.hooks.get(e.var.tenant_id,t);if(!n)throw new I(404,{message:"Hook not found"});return e.json(n)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["delete:hooks","auth:write"]}],responses:{200:{description:"A hook"}}}),async e=>{const{hook_id:t}=e.req.valid("param");if(!await e.env.data.hooks.remove(e.var.tenant_id,t))throw new I(404,{message:"Hook not found"});return e.text("OK")});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});du.extend({email:o.z.string(),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());const ZI=jt.extend({connections:o.z.array(_r)}),XI=o.z.object({enabled_clients:o.z.array(o.z.object({client_id:o.z.string(),name:o.z.string()}))}),YI=o.z.array(o.z.object({client_id:o.z.string(),status:o.z.boolean()})),QI=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(_r),ZI])}},description:"List of connectionss"}}}),async e=>{const{page:t,per_page:n,include_totals:r=!1,sort:i,q:s}=e.req.valid("query"),a=await e.env.data.connections.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(a):e.json(a.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:_r}},description:"A connection"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.connections.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:connections","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!await e.env.data.connections.remove(n,t))throw new I(404,{message:"Connection not found"});return e.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Qc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:connections","auth:write"]}],responses:{200:{content:{"application/json":{schema:_r}},description:"The updated connection"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json"),r=e.var.tenant_id;if(!await e.env.data.connections.update(r,t,n))throw new I(404,{message:"Connection not found"});const s=await e.env.data.connections.get(r,t);if(!s)throw new I(404,{message:"Connection not found"});return e.json(s)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Qc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:connections","auth:write"]}],responses:{201:{content:{"application/json":{schema:_r}},description:"A connection"}}}),async e=>{const t=e.req.valid("json"),n=e.var.tenant_id,r=t.id||VI(),i=await e.env.data.connections.create(n,{...t,id:r});return e.json(i,{status:201})}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}/clients",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:connections","auth:read"]}],responses:{200:{content:{"application/json":{schema:XI}},description:"List of clients enabled for this connection"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.connections.get(e.var.tenant_id,t))throw new I(404,{message:"Connection not found"});const{clients:r}=await e.env.data.clients.list(e.var.tenant_id,{per_page:1e3}),i=r.filter(s=>s.connections?.includes(t)).map(s=>({client_id:s.client_id,name:s.name}));return e.json({enabled_clients:i})}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}/clients",request:{body:{content:{"application/json":{schema:YI}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:connections","auth:write"]}],responses:{200:{description:"Clients updated successfully"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json");if(!await e.env.data.connections.get(e.var.tenant_id,t))throw new I(404,{message:"Connection not found"});for(const i of n){const s=await e.env.data.clients.get(e.var.tenant_id,i.client_id);if(!s)continue;const a=s.connections||[];i.status?a.includes(t)||await e.env.data.clients.update(e.var.tenant_id,i.client_id,{connections:[...a,t]}):a.includes(t)&&await e.env.data.clients.update(e.var.tenant_id,i.client_id,{connections:a.filter(c=>c!==t)})}return e.text("OK")}),ej=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ds}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.promptSettings.get(e.var.tenant_id);return t?e.json(t):e.json(Ds.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ds.shape).partial()}}}},security:[{Bearer:["update:prompts","auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.promptSettings.get(e.var.tenant_id);return Object.assign(n,t),await e.env.data.promptSettings.set(e.var.tenant_id,n),e.json(n)}).openapi(o.createRoute({tags:["prompts"],method:"get",path:"/custom-text",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(o.z.object({prompt:io,language:o.z.string()}))}},description:"List of custom text entries"}}}),async e=>{const t=await e.env.data.customText.list(e.var.tenant_id);return e.json(t)}).openapi(o.createRoute({tags:["prompts"],method:"get",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()})},security:[{Bearer:["read:prompts","auth:read"]}],responses:{200:{content:{"application/json":{schema:oo}},description:"Custom text for the prompt and language"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param"),r=await e.env.data.customText.get(e.var.tenant_id,t,n);return e.json(r||{})}).openapi(o.createRoute({tags:["prompts"],method:"put",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()}),body:{content:{"application/json":{schema:oo}}}},security:[{Bearer:["update:prompts","auth:write"]}],responses:{200:{content:{"application/json":{schema:oo}},description:"Updated custom text"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param"),r=oo.parse(await e.req.json());return await e.env.data.customText.set(e.var.tenant_id,t,n,r),e.json(r)}).openapi(o.createRoute({tags:["prompts"],method:"delete",path:"/{prompt}/custom-text/{language}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({prompt:io,language:o.z.string()})},security:[{Bearer:["delete:prompts","auth:write"]}],responses:{204:{description:"Custom text deleted"}}}),async e=>{const{prompt:t,language:n}=e.req.valid("param");return await e.env.data.customText.delete(e.var.tenant_id,t,n),e.body(null,204)});let Fy=!1;function N_(e){e.use(async(t,n)=>(Fy||(e.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${t.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Fy=!0),await n()))}var tj=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(const i of["domain","path"])if(n[i]&&/[;\r\n]/.test(n[i]))throw new Error(`${i} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},op=(e,t,n)=>(t=encodeURIComponent(t),tj(e,t,n)),nj=(e,t,n)=>{let r;return n?.prefix==="secure"?r=op("__Secure-"+e,t,{path:"/",...n,secure:!0}):n?.prefix==="host"?r=op("__Host-"+e,t,{...n,path:"/",secure:!0,domain:void 0}):r=op(e,t,{path:"/",...n}),r},Hy=(e,t,n,r)=>{const i=nj(t,n,r);e.header("Set-Cookie",i,{append:!0})},Ck=e=>Ik(e.replace(/_|-/g,t=>({_:"/","-":"+"})[t]??t)),Ik=e=>{const t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length)),r=t.length/2;for(let i=0,s=t.length-1;i<=r;i++,s--)n[i]=t.charCodeAt(i),n[s]=t.charCodeAt(s);return n},Ws=(e=>(e.HS256="HS256",e.HS384="HS384",e.HS512="HS512",e.RS256="RS256",e.RS384="RS384",e.RS512="RS512",e.PS256="PS256",e.PS384="PS384",e.PS512="PS512",e.ES256="ES256",e.ES384="ES384",e.ES512="ES512",e.EdDSA="EdDSA",e))(Ws||{}),rj=class extends Error{constructor(e){super(`${e} is not an implemented algorithm`),this.name="JwtAlgorithmNotImplemented"}},Vy=class extends Error{constructor(){super('JWT verification requires "alg" option to be specified'),this.name="JwtAlgorithmRequired"}},ij=class extends Error{constructor(e,t){super(`JWT algorithm mismatch: expected "${e}", got "${t}"`),this.name="JwtAlgorithmMismatch"}},H0=class extends Error{constructor(e){super(`invalid JWT token: ${e}`),this.name="JwtTokenInvalid"}},oj=class extends Error{constructor(e){super(`token (${e}) is being used before it's valid`),this.name="JwtTokenNotBefore"}},sj=class extends Error{constructor(e){super(`token (${e}) expired`),this.name="JwtTokenExpired"}},aj=class extends Error{constructor(e,t){super(`Invalid "iat" claim, must be a valid number lower than "${e}" (iat: "${t}")`),this.name="JwtTokenIssuedAt"}},sp=class extends Error{constructor(e,t){super(`expected issuer "${e}", got ${t?`"${t}"`:"none"} `),this.name="JwtTokenIssuer"}},cj=class extends Error{constructor(e){super(`jwt header is invalid: ${JSON.stringify(e)}`),this.name="JwtHeaderInvalid"}},lj=class extends Error{constructor(e){super(`token(${e}) signature mismatched`),this.name="JwtTokenSignatureMismatched"}},uj=class extends Error{constructor(e){super(`required "aud" in jwt payload: ${JSON.stringify(e)}`),this.name="JwtPayloadRequiresAud"}},dj=class extends Error{constructor(e,t){super(`expected audience "${Array.isArray(e)?e.join(", "):e}", got "${t}"`),this.name="JwtTokenAudience"}},Ql=(e=>(e.Encrypt="encrypt",e.Decrypt="decrypt",e.Sign="sign",e.Verify="verify",e.DeriveKey="deriveKey",e.DeriveBits="deriveBits",e.WrapKey="wrapKey",e.UnwrapKey="unwrapKey",e))(Ql||{}),jk=new TextEncoder,pj=new TextDecoder;async function fj(e,t,n,r){const i=_j(t),s=await hj(e,i);return await crypto.subtle.verify(i,s,n,r)}function Ky(e){return Ik(e.replace(/-+(BEGIN|END).*/g,"").replace(/\s/g,""))}async function hj(e,t){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if(mj(e)){if(e.type==="public"||e.type==="secret")return e;e=await Gy(e)}if(typeof e=="string"&&e.includes("PRIVATE")){const r=await crypto.subtle.importKey("pkcs8",Ky(e),t,!0,[Ql.Sign]);e=await Gy(r)}const n=[Ql.Verify];return typeof e=="object"?await crypto.subtle.importKey("jwk",e,t,!1,n):e.includes("PUBLIC")?await crypto.subtle.importKey("spki",Ky(e),t,!1,n):await crypto.subtle.importKey("raw",jk.encode(e),t,!1,n)}async function Gy(e){if(e.type!=="private")throw new Error(`unexpected key type: ${e.type}`);if(!e.extractable)throw new Error("unexpected private key is unextractable");const t=await crypto.subtle.exportKey("jwk",e),{kty:n}=t,{alg:r,e:i,n:s}=t,{crv:a,x:c,y:l}=t;return{kty:n,alg:r,e:i,n:s,crv:a,x:c,y:l,key_ops:[Ql.Verify]}}function _j(e){switch(e){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"RS384":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"PS256":return{name:"RSA-PSS",hash:{name:"SHA-256"},saltLength:32};case"PS384":return{name:"RSA-PSS",hash:{name:"SHA-384"},saltLength:48};case"PS512":return{name:"RSA-PSS",hash:{name:"SHA-512"},saltLength:64};case"ES256":return{name:"ECDSA",hash:{name:"SHA-256"},namedCurve:"P-256"};case"ES384":return{name:"ECDSA",hash:{name:"SHA-384"},namedCurve:"P-384"};case"ES512":return{name:"ECDSA",hash:{name:"SHA-512"},namedCurve:"P-521"};case"EdDSA":return{name:"Ed25519",namedCurve:"Ed25519"};default:throw new rj(e)}}function mj(e){return Pw()==="node"&&crypto.webcrypto?e instanceof crypto.webcrypto.CryptoKey:e instanceof CryptoKey}var Wy=e=>JSON.parse(pj.decode(Ck(e)));function gj(e){if(typeof e=="object"&&e!==null){const t=e;return"alg"in t&&Object.values(Ws).includes(t.alg)&&(!("typ"in t)||t.typ==="JWT")}return!1}var yj=async(e,t,n)=>{if(!n)throw new Vy;const{alg:r,iss:i,nbf:s=!0,exp:a=!0,iat:c=!0,aud:l}=typeof n=="string"?{alg:n}:n;if(!r)throw new Vy;const u=e.split(".");if(u.length!==3)throw new H0(e);const{header:d,payload:f}=Nk(e);if(!gj(d))throw new cj(d);if(d.alg!==r)throw new ij(r,d.alg);const p=Math.floor(Date.now()/1e3);if(s&&f.nbf&&f.nbf>p)throw new oj(e);if(a&&f.exp&&f.exp<=p)throw new sj(e);if(c&&f.iat&&p<f.iat)throw new aj(p,f.iat);if(i){if(!f.iss)throw new sp(i,null);if(typeof i=="string"&&f.iss!==i)throw new sp(i,f.iss);if(i instanceof RegExp&&!i.test(f.iss))throw new sp(i,f.iss)}if(l){if(!f.aud)throw new uj(f);if(!(Array.isArray(f.aud)?f.aud:[f.aud]).some(m=>l instanceof RegExp?l.test(m):typeof l=="string"?m===l:Array.isArray(l)&&l.includes(m)))throw new dj(l,f.aud)}const h=e.substring(0,e.lastIndexOf("."));if(!await fj(t,r,Ck(u[2]),jk.encode(h)))throw new lj(e);return f};Ws.HS256,Ws.HS384,Ws.HS512;var Nk=e=>{const t=e.split(".");if(t.length!==3)throw new H0(e);try{const n=Wy(t[0]),r=Wy(t[1]);return{header:n,payload:r}}catch{throw new H0(e)}},Tk={verify:yj,decode:Nk},bj={Stringify:1},Cr=(e,t)=>{const n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},vj=/[&<>'"]/,wj=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];ho(s,c),n=c[0]}}return Cr(n,t)},ho=(e,t)=>{const n=e.search(vj);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=""";break;case 39:r="'";break;case 38:r="&";break;case 60:r="<";break;case 62:r=">";break;default:continue}t[0]+=e.substring(s,i)+r,s=i+1}t[0]+=e.substring(s,i)},kj=e=>{const t=e.callbacks;if(!t?.length)return e;const n=[e],r={};return t.forEach(i=>i({phase:bj.Stringify,buffer:n,context:r})),n[0]},$j=Tk.verify,Sj=Tk.decode;async function Lc(e){const{signingKeys:t}=await e.keys.list({q:"type:jwt_signing"});return await Promise.all(t.map(async r=>{const s=await new wd(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return wh.parse({...a,kid:r.kid})}))}const xj=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kty:o.z.enum(["RSA","EC","oct"]),use:o.z.enum(["sig","enc"]).optional(),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional()});async function zj(e){if(e.JWKS_URL&&e.JWKS_SERVICE)try{const t=await e.JWKS_SERVICE.fetch(e.JWKS_URL);if(!t.ok)return console.warn(`JWKS fetch failed with status ${t.status}, falling back to database`),await Lc(e.data);const n=await t.json();return o.z.object({keys:o.z.array(xj)}).parse(n).keys}catch(t){return console.warn(`JWKS fetch error: ${t instanceof Error?t.message:"Unknown error"}, falling back to database`),await Lc(e.data)}return await Lc(e.data)}async function V0(e,t){try{const{header:n}=Sj(t),i=(await zj(e.env)).find(c=>c.kid===n.kid);if(!i)throw new W(401,{message:"No matching kid found"});const s=await crypto.subtle.importKey("jwk",i,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return await $j(t,s,"RS256")}catch(n){throw n instanceof I?n:new W(403,{message:"Invalid JWT signature"})}}const Aj="urn:authhero:management";function Ej(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function $d(e){return async(t,n)=>{const r=t.req.matchedRoutes.find(l=>l.method.toUpperCase()===t.req.method&&l.path!=="/*");if(!r)return await n();const i=Ej(r.path),s="/api/v2",a=i.startsWith(s)?i.slice(s.length)||"/":i,c=e.openAPIRegistry.definitions.find(l=>"route"in l&&l.route.path===a&&l.route.method.toUpperCase()===t.req.method.toUpperCase());if(c&&"route"in c){const l=c.route.security?.[0]?.Bearer;if(l===void 0)return await n();const u=t.req.header("authorization")||"",[d,f]=u.split(" ");if(d?.toLowerCase()!=="bearer"||!f)throw new W(401,{message:"Missing bearer token"});try{const p=await V0(t,f);t.set("user_id",p.sub),t.set("user",p),p.org_name&&t.set("org_name",p.org_name),p.org_id&&t.set("organization_id",p.org_id),!t.var.tenant_id&&p.tenant_id&&t.set("tenant_id",p.tenant_id);const h=Array.isArray(p.permissions)?p.permissions:[],_=typeof p.scope=="string"?p.scope.split(" "):Array.isArray(p.scope)?p.scope:[];if(l.length&&!(l.some(g=>h.includes(g))||l.some(g=>_.includes(g))))throw new W(403,{message:"Unauthorized"})}catch(p){throw p instanceof I?p:new W(403,{message:"Invalid token"})}}return await n()}}const Cj=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:emails","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ic}},description:"Email provider"}}}),async e=>{const t=await e.env.data.emailProviders.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Email provider not found"});return e.json(t)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ic.shape)}}}},security:[{Bearer:["create:emails","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.emailProviders.create(e.var.tenant_id,t),e.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(Ic.shape).partial()}}}},security:[{Bearer:["update:emails","auth:write"]}],responses:{200:{description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");return await e.env.data.emailProviders.update(e.var.tenant_id,t),e.text("OK")}),Ij=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:sessions","auth:read"]}],responses:{200:{content:{"application/json":{schema:hu}},description:"A session"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.sessions.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:sessions","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.sessions.remove(e.var.tenant_id,t))throw new I(404,{message:"Session not found"});return e.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:sessions","auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.sessions.update(e.var.tenant_id,t,{revoked_at:new Date().toDateString()}))throw new I(404,{message:"Session not found"});return e.text("Session deletion request accepted.",{status:202})}),jj=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:refresh_tokens","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sh}},description:"A session"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.refreshTokens.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:refresh_tokens","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.refreshTokens.remove(e.var.tenant_id,t))throw new I(404,{message:"Session not found"});return e.text("OK")}),Nj=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:custom_domains","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(fr)}},description:"List of custom domains"}}}),async e=>{const t=await e.env.data.customDomains.list(e.var.tenant_id);return e.json(t)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:custom_domains","auth:read"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"A customDomain"}}}),async e=>{const{id:t}=e.req.valid("param"),n=await e.env.data.customDomains.get(e.var.tenant_id,t);if(!n)throw new I(404);return e.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:custom_domains","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param");if(!await e.env.data.customDomains.remove(e.var.tenant_id,t))throw new I(404,{message:"Custom domain not found"});return e.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(fr.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:custom_domains","auth:write"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"The updated custom domain"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json");if(!await e.env.data.customDomains.update(e.var.tenant_id,t,n))throw new I(404);const i=await e.env.data.customDomains.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json(i)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(hh.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:custom_domains","auth:write"]}],responses:{201:{content:{"application/json":{schema:fr}},description:"The created custom domain"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.customDomains.create(e.var.tenant_id,t);return e.json(n,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:custom_domains","auth:write"]}],responses:{200:{content:{"application/json":{schema:fr}},description:"The custom domain"}}}),async()=>{throw new I(501,{message:"Not implemented"})});function Ya(e,t){const n={};for(const[r,i]of Object.entries(t)){if(i==null)continue;const s={};for(const[a,c]of Object.entries(i))typeof c=="function"?s[a]=async(...l)=>{const u=performance.now();try{const d=await c(...l),p=performance.now()-u,h=e.res.headers.get("Server-Timing")||"",_=h?`${h}, ${r}-${a};dur=${p.toFixed(2)}`:`${r}-${a};dur=${p.toFixed(2)}`;return e.res.headers.set("Server-Timing",_),d}catch(d){const p=performance.now()-u,h=e.res.headers.get("Server-Timing")||"",_=h?`${h}, ${r}-${a}-error;dur=${p.toFixed(2)}`:`${r}-${a}-error;dur=${p.toFixed(2)}`;throw e.res.headers.set("Server-Timing",_),d}}:s[a]=c;n[r]=s}return n}async function ts(e,t){const n=e.var.user;if(n?.tenant_id)return e.set("tenant_id",n.tenant_id),await t();const r=e.req.header("tenant-id");if(r)return e.set("tenant_id",r),await t();const i=e.req.header("x-forwarded-host");if(i){const a=await e.env.data.customDomains.getByDomain(i);if(a)return e.set("tenant_id",a.tenant_id),e.set("custom_domain",i),e.set("host",i),await t()}const s=e.req.header("host");if(s){e.set("host",s);const a=await e.env.data.customDomains.getByDomain(s);if(a)return e.set("tenant_id",a.tenant_id),e.set("custom_domain",s),await t();const c=s.split(".");if(c.length>1&&typeof c[0]=="string"){const l=c[0];await e.env.data.tenants.get(l)&&e.set("tenant_id",l)}}else e.set("host",new URL($u(e.env)).host);if(!e.var.tenant_id){const{tenants:a}=await e.env.data.tenants.list({per_page:2});a.length===1&&a[0]&&e.set("tenant_id",a[0].id)}return await t()}const Tj=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()});function Pj(e){if(e)try{let t=e;try{t=atob(e)}catch{}try{const n=JSON.parse(t);return Tj.parse(n)}catch{}}catch{return}}const ns=async(e,t)=>{const n=e.req.query("auth0Client")?.slice(0,255),i=(e.req.header("x-forwarded-host")&&e.req.header("x-forwarded-for")?e.req.header("x-forwarded-for")?.split(",")[0]?.trim():e.req.header("cf-connecting-ip")||e.req.header("x-real-ip"))?.slice(0,45),s=e.req.header("user-agent")?.slice(0,512),a=e.req.header("cf-ipcountry")?.slice(0,2),c=n?Pj(n):void 0;c&&e.set("auth0_client",c),i&&e.set("ip",i),s&&e.set("useragent",s),a&&e.set("countryCode",a),await t()};function ap(e,t,n,r){try{const i=`${e}:${t}:${JSON.stringify(n)}`;return r?`${r}:${i}`:i}catch{const s=`${e}:${t}:${Date.now()}-${Math.random()}`;return r?`${r}:${s}`:s}}function Qa(e,t){const{cache:n,defaultTtl:r,customTtls:i={},excludeMethods:s=[],cacheEntities:a=[],keyPrefix:c}=t,l=new Set(s),u=a.length===0,d=new Set(a),f={};for(const[p,h]of Object.entries(e)){if(h==null)continue;const _=u||d.has(p),g={};for(const[y,m]of Object.entries(h))if(typeof m=="function"){if(!_){g[y]=m;continue}const w=`${p}:${y}`;if(l.has(w)){g[y]=m;continue}const k=i[w]??r,S=["create","update","remove","delete","set","used"].includes(y);g[y]=async(...b)=>{if(S){const P=await m.apply(h,b);try{if(b.length>=2&&["update","remove","delete"].includes(y)){const C=ap(p,"get",[b[0],b[1]],c);await n.delete(C);const L=ap(p,"list",[b[0],{}],c);await n.delete(L)}const R=c?`${c}:${p}:`:`${p}:`;await n.deleteByPrefix(R)}catch{}return P}const x=ap(p,y,b,c),A=await n.get(x);if(A!==null)if(A&&typeof A=="object"&&"isCachedNull"in A){const P=A;return P.isCachedNull?null:P.value}else return A;const E=await m.apply(h,b);if(k>=0)if(E!==null)await n.set(x,E,k);else{const P={value:null,isCachedNull:!0};await n.set(x,P,k)}return E}}else g[y]=m;f[p]=g}return f}function gc(e){if(!e)return;const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:{beforeCreate:eu(t.map(n=>n.beforeCreate),(n,r)=>[n,r],(n,r)=>[n[0],r]),afterCreate:co(t.map(n=>n.afterCreate)),beforeUpdate:eu(t.map(n=>n.beforeUpdate),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterUpdate:co(t.map(n=>n.afterUpdate)),beforeDelete:co(t.map(n=>n.beforeDelete)),afterDelete:co(t.map(n=>n.afterDelete))}}function eu(e,t,n){const r=e.filter(i=>i!==void 0);if(r.length!==0)return r.length===1?r[0]:async(...i)=>{let s=t(...i),a=s[s.length-1];for(const c of r)a=await c(...s),s=n(s,a);return a}}function co(e){const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:async(...n)=>{for(const r of t)await r(...n)}}function Oj(e){if(!e)return;const t=e.filter(n=>n!==void 0);if(t.length!==0)return t.length===1?t[0]:{beforeAssign:eu(t.map(n=>n.beforeAssign),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterAssign:co(t.map(n=>n.afterAssign)),beforeRemove:eu(t.map(n=>n.beforeRemove),(n,r,i)=>[n,r,i],(n,r)=>[n[0],n[1],r]),afterRemove:co(t.map(n=>n.afterRemove))}}function cp(e,t,n){return t?{...e,create:async(r,i)=>{let s=i;t.beforeCreate&&(s=await t.beforeCreate(n,i));const a=await e.create(r,s);return t.afterCreate&&await t.afterCreate(n,a),a},update:async(r,i,s)=>{let a=s;t.beforeUpdate&&(a=await t.beforeUpdate(n,i,s));const c=await e.update(r,i,a);if(t.afterUpdate){let l;typeof c=="boolean"?l=await e.get(r,i):l=c,l&&await t.afterUpdate(n,i,l)}return c},remove:async(r,i)=>{t.beforeDelete&&await t.beforeDelete(n,i);const s=await e.remove(r,i);return t.afterDelete&&s&&await t.afterDelete(n,i),s}}:e}function Rj(e,t,n){return t?{...e,assign:async(r,i,s)=>{let a=s;t.beforeAssign&&(a=await t.beforeAssign(n,i,s));const c=await e.assign(r,i,a);return t.afterAssign&&c&&await t.afterAssign(n,i,a),c},remove:async(r,i,s)=>{let a=s;t.beforeRemove&&(a=await t.beforeRemove(n,i,s));const c=await e.remove(r,i,a);return t.afterRemove&&c&&await t.afterRemove(n,i,a),c}}:e}function Lj(e,t,n){return t?{...e,create:async r=>{let i=r;t.beforeCreate&&(i=await t.beforeCreate(n,r));const s=await e.create(i);return t.afterCreate&&await t.afterCreate(n,s),s},update:async(r,i)=>{let s=i;if(t.beforeUpdate&&(s=await t.beforeUpdate(n,r,i)),await e.update(r,s),t.afterUpdate){const a=await e.get(r);a&&await t.afterUpdate(n,r,a)}},remove:async r=>{t.beforeDelete&&await t.beforeDelete(n,r);const i=await e.remove(r);return t.afterDelete&&i&&await t.afterDelete(n,r),i}}:e}function Pk(e,t){const{tenantId:n,entityHooks:r}=t;if(!r)return e;const i={connections:gc(r.connections),roles:gc(r.roles),resourceServers:gc(r.resourceServers),rolePermissions:Oj(r.rolePermissions),tenants:gc(r.tenants)},s={tenantId:n,adapters:e};return{...e,connections:cp(e.connections,i.connections,s),roles:cp(e.roles,i.roles,s),resourceServers:cp(e.resourceServers,i.resourceServers,s),rolePermissions:Rj(e.rolePermissions,i.rolePermissions,s),tenants:Lj(e.tenants,i.tenants,s)}}class Dj{constructor(t={}){this.config=t;const n=t.cleanupIntervalMs;n&&n>0&&(this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},n))}cache=new Map;accessOrder=new Map;accessCounter=0;cleanupTimer;async get(t){const n=this.cache.get(t);return n?n.expiresAt&&n.expiresAt<new Date?(this.cache.delete(t),this.accessOrder.delete(t),null):(this.accessOrder.set(t,++this.accessCounter),n.value):null}async set(t,n,r){let i;const s=r??this.config.defaultTtlSeconds,a=s!==void 0,c=a?Math.max(0,s):0;a&&(i=new Date(Date.now()+(c>0?c*1e3:-1))),this.config.maxEntries&&this.cache.size>=this.config.maxEntries&&!this.cache.has(t)&&this.evictLeastRecentlyUsed();const l={value:n,expiresAt:i};this.cache.set(t,l),this.accessOrder.set(t,++this.accessCounter)}async delete(t){const n=this.cache.has(t);return this.cache.delete(t),this.accessOrder.delete(t),n}async deleteByPrefix(t){let n=0;for(const r of this.cache.keys())r.startsWith(t)&&(this.cache.delete(r),this.accessOrder.delete(r),n++);return n}async clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}getStats(){return{size:this.cache.size,maxEntries:this.config.maxEntries,defaultTtlSeconds:this.config.defaultTtlSeconds}}cleanupExpired(){const t=new Date,n=[];for(const[r,i]of this.cache.entries())i.expiresAt&&i.expiresAt<t&&n.push(r);for(const r of n)this.cache.delete(r),this.accessOrder.delete(r)}evictLeastRecentlyUsed(){let t=null,n=1/0;for(const[r,i]of this.accessOrder.entries())i<n&&(n=i,t=r);t&&(this.cache.delete(t),this.accessOrder.delete(t))}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}}function rs(e={}){return new Dj(e)}const Uj=jt.extend({forms:o.z.array(no)}),Bj=new o.OpenAPIHono().openapi(o.createRoute({tags:["forms"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:forms","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(no),Uj])}},description:"List of forms"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.forms.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.forms)}).openapi(o.createRoute({tags:["forms"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:forms","auth:read"]}],responses:{200:{content:{"application/json":{schema:no}},description:"A form"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.forms.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["forms"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:forms","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.forms.remove(t,n))throw new I(404,{message:"Form not found"});return e.text("OK")}).openapi(o.createRoute({tags:["forms"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(el.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:forms","auth:write"]}],responses:{200:{content:{"application/json":{schema:no}},description:"The updated form"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.forms.update(t,n,r))throw new I(404,{message:"Form not found"});const s=await e.env.data.forms.get(t,n);if(!s)throw new I(404,{message:"Form not found"});return e.json(s)}).openapi(o.createRoute({tags:["forms"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(el.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:forms","auth:write"]}],responses:{201:{content:{"application/json":{schema:no}},description:"A form"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.forms.create(t,n);return e.json(r,{status:201})}),Mj=jt.extend({flows:o.z.array(to)}),qj=new o.OpenAPIHono().openapi(o.createRoute({tags:["flows"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:flows","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(to),Mj])}},description:"List of flows"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.flows.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.flows)}).openapi(o.createRoute({tags:["flows"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:flows","auth:read"]}],responses:{200:{content:{"application/json":{schema:to}},description:"A flow"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.flows.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["flows"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:flows","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.flows.remove(t,n))throw new I(404,{message:"Flow not found"});return e.text("OK")}).openapi(o.createRoute({tags:["flows"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Wc.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:flows","auth:write"]}],responses:{200:{content:{"application/json":{schema:to}},description:"The updated flow"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json"),i=await e.env.data.flows.update(t,n,r);if(!i)throw new I(404,{message:"Flow not found"});return e.json(i)}).openapi(o.createRoute({tags:["flows"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Wc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:flows","auth:write"]}],responses:{201:{content:{"application/json":{schema:to}},description:"The created flow"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.flows.create(t,n);return e.json(r,{status:201})}),Fj=jt.extend({roles:o.z.array(ii)}),Hj=new o.OpenAPIHono().openapi(o.createRoute({tags:["roles"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ii),Fj])}},description:"List of roles"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query"),a=e.var.tenant_id;if(!a)throw new I(400,{message:"tenant-id header is required"});const c=await e.env.data.roles.list(a,{page:t,per_page:n,include_totals:r,sort:ht(i),q:s});return r?e.json(c):e.json(c.roles)}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:ii}},description:"A role"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});const r=await e.env.data.roles.get(n,t);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:il}}}},security:[{Bearer:["create:roles","auth:write"]}],responses:{201:{content:{"application/json":{schema:ii}},description:"Role created"}}}),async e=>{const t=e.req.valid("json"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});const r=await e.env.data.roles.create(n,t);return e.json(r,{status:201})}).openapi(o.createRoute({tags:["roles"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:il.partial()}}}},security:[{Bearer:["update:roles","auth:write"]}],responses:{200:{content:{"application/json":{schema:ii}},description:"Updated role"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.update(r,t,n))throw new I(404);const s=await e.env.data.roles.get(r,t);return e.json(s)}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:roles","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{id:t}=e.req.valid("param"),n=e.var.tenant_id;if(!n)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.remove(n,t))throw new I(404);return e.text("OK")}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:roles","auth:read"]}],responses:{200:{content:{"application/json":{schema:vw}},description:"Role permissions"}}}),async e=>{const{id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query"),a=e.var.tenant_id;if(!a)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(a,t))throw new I(404,{message:"Role not found"});const l=await e.env.data.rolePermissions.list(a,t,{page:n,per_page:r,include_totals:!1,sort:ht(i),q:s});return e.json(l)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/{id}/permissions",request:{params:o.z.object({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:roles","auth:write"]}],responses:{201:{description:"Permissions assigned to role"}}}),async e=>{const{id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(r,t))throw new I(404,{message:"Role not found"});const s=n.map(c=>({role_id:t,resource_server_identifier:c.resource_server_identifier,permission_name:c.permission_name}));if(!await e.env.data.rolePermissions.assign(r,t,s))throw new I(500,{message:"Failed to assign permissions to role"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}/permissions",request:{params:o.z.object({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:roles","auth:write"]}],responses:{200:{description:"Permissions removed from role"}}}),async e=>{const{id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json"),r=e.var.tenant_id;if(!r)throw new I(400,{message:"tenant-id header is required"});if(!await e.env.data.roles.get(r,t))throw new I(404,{message:"Role not found"});if(!await e.env.data.rolePermissions.remove(r,t,n))throw new I(500,{message:"Failed to remove permissions from role"});return e.json({message:"Permissions removed successfully"})}),Vj=jt.extend({resource_servers:o.z.array(ri)}),Kj=new o.OpenAPIHono().openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:resource_servers","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ri),Vj])}},description:"List of resource servers"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=e.req.valid("query"),c=await e.env.data.resourceServers.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a});return i?e.json(c):e.json(c.resource_servers)}).openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:resource_servers","auth:read"]}],responses:{200:{content:{"application/json":{schema:ri}},description:"A resource server"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.resourceServers.get(t,n);if(!r)throw new I(404);return e.json(r)}).openapi(o.createRoute({tags:["resource-servers"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:resource_servers","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.resourceServers.get(t,n);if(!r)throw new I(404,{message:"Resource server not found"});if(r.is_system)throw new I(403,{message:"System entities cannot be deleted"});return await e.env.data.resourceServers.remove(t,n),e.text("OK")}).openapi(o.createRoute({tags:["resource-servers"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(rl.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:resource_servers","auth:write"]}],responses:{200:{content:{"application/json":{schema:ri}},description:"The updated resource server"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json"),i=await e.env.data.resourceServers.get(t,n);if(!i)throw new I(404,{message:"Resource server not found"});if(i.is_system)throw new I(403,{message:"System entities cannot be modified"});await e.env.data.resourceServers.update(t,n,r);const s=await e.env.data.resourceServers.get(t,n);if(!s)throw new I(404,{message:"Resource server not found"});return e.json(s)}).openapi(o.createRoute({tags:["resource-servers"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(rl.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:resource_servers","auth:write"]}],responses:{201:{content:{"application/json":{schema:ri}},description:"A resource server"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.resourceServers.create(t,n);return e.json(r,{status:201})}),Gj=o.z.object({per_page:o.z.string().min(1).optional().default("50").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),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."}),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().min(1).optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),audience:o.z.string().optional().openapi({description:"Optional filter on audience."}),client_id:o.z.string().optional().openapi({description:"Optional filter on client_id."}),allow_any_organization:o.z.string().optional().transform(e=>e==="true"?!0:e==="false"?!1:void 0).openapi({description:"Optional filter on allow_any_organization."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"EA 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."})}),Wj=jt.extend({client_grants:o.z.array(ni)}),Jj=new o.OpenAPIHono().openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/",request:{query:Gj,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:client_grants","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ni),Wj])}},description:"List of client grants"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i=!1,from:s,take:a,audience:c,client_id:l,allow_any_organization:u,subject_type:d}=e.req.valid("query"),f=[];l&&f.push(`client_id:"${l}"`),c&&f.push(`audience:"${c}"`),u!==void 0&&f.push(`allow_any_organization:${u}`),d&&f.push(`subject_type:"${d}"`),s&&f.push(`id:>${s}`);const p=f.length>0?f.join(" AND "):void 0,h=a??r,_=await e.env.data.clientGrants.list(t,{page:n,per_page:h,include_totals:i,q:p});return i?e.json(_):e.json(_.client_grants)}).openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:client_grants","auth:read"]}],responses:{200:{content:{"application/json":{schema:ni}},description:"A client grant"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.clientGrants.get(t,n);if(!r)throw new I(404,{message:"Client grant not found"});return e.json(r)}).openapi(o.createRoute({tags:["client-grants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:client_grants","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.clientGrants.remove(t,n))throw new I(404,{message:"Client grant not found"});return e.text("OK")}).openapi(o.createRoute({tags:["client-grants"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Yc.shape).partial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:client_grants","auth:write"]}],responses:{200:{content:{"application/json":{schema:ni}},description:"The updated client grant"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.clientGrants.get(t,n))throw new I(404,{message:"Client grant not found"});if(!await e.env.data.clientGrants.update(t,n,r))throw new I(500,{message:"Failed to update client grant"});const a=await e.env.data.clientGrants.get(t,n);if(!a)throw new I(404,{message:"Client grant not found"});return e.json(a)}).openapi(o.createRoute({tags:["client-grants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Yc.shape)}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:client_grants","auth:write"]}],responses:{201:{content:{"application/json":{schema:ni}},description:"A client grant"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r=await e.env.data.clientGrants.create(t,n);return e.json(r,{status:201})}),Zj=o.z.object({page:o.z.string().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().optional().default("50").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:"When true, return results inside an object that also contains the start and limit. When false (default), a direct array of results is returned."}),fields:o.z.string().optional().openapi({description:"Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields."}),include_fields:o.z.string().optional().default("true").transform(e=>e==="true").openapi({description:"Whether specified fields are to be included (true) or excluded (false). Defaults to true."}),sort:o.z.string().optional().default("created_at:-1").openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. Defaults to created_at:-1."})}),Xj=o.z.object({invitations:o.z.array(Ls),start:o.z.number(),limit:o.z.number(),length:o.z.number()}),Yj=vh.omit({organization_id:!0,invitation_url:!0}),Qj=jt.extend({organizations:o.z.array(mr)}),T_=o.z.object({user_id:o.z.string().openapi({description:"ID of this user"}),email:o.z.string().email().optional().openapi({description:"Email address of this user",format:"email"}),roles:o.z.array(o.z.object({})).default([]).openapi({description:"Array of roles assigned to this user in the organization"})}),eN=o.z.object({start:o.z.number().openapi({description:"Start index of the current page"}),limit:o.z.number().openapi({description:"Number of items per page"}),total:o.z.number().openapi({description:"Total number of members"}),members:o.z.array(T_).openapi({description:"Array of organization members"})}),tN=o.z.object({next:o.z.string().optional().openapi({description:"Checkpoint ID to be used to retrieve the next set of results"}),members:o.z.array(T_).openapi({description:"Array of organization members"})}),nN=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to add to the organization"})}),rN=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to remove from the organization"})}),iN=new o.OpenAPIHono().openapi(o.createRoute({tags:["organizations"],method:"get",path:"/",request:{query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Qj,o.z.array(mr)])}},description:"List of organizations"}}}),async e=>{const t=e.var.tenant_id,{page:n,per_page:r,include_totals:i,sort:s,q:a,from:c,take:l}=e.req.valid("query"),u=await e.env.data.organizations.list(t,{page:n,per_page:r,include_totals:i,sort:ht(s),q:a,from:c,take:l});return i?e.json(u):e.json(u.organizations)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:mr}},description:"An organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=await e.env.data.organizations.get(t,n);if(!r)throw new I(404,{message:"Organization not found"});return e.json(r)}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:organizations","auth:write"]}],responses:{200:{description:"Organization deleted successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param");if(!await e.env.data.organizations.remove(t,n))throw new I(404,{message:"Organization not found"});return e.text("OK")}).openapi(o.createRoute({tags:["organizations"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:sl.partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{content:{"application/json":{schema:mr}},description:"The updated organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.organizations.update(t,n,r))throw new I(404,{message:"Organization not found"});const s=await e.env.data.organizations.get(t,n);if(!s)throw new I(404,{message:"Organization not found"});return e.json(s)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:sl}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["create:organizations","auth:write"]}],responses:{201:{content:{"application/json":{schema:mr}},description:"The created organization"}}}),async e=>{const t=e.var.tenant_id,n=e.req.valid("json"),r={...n,id:n.id||HI()},i=await e.env.data.organizations.create(t,r);return e.json(i,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),query:ot,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(T_),eN,tN])}},description:"List of organization members"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,include_totals:s,sort:a}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const l=await e.env.data.userOrganizations.list(t,{page:r,per_page:i,include_totals:s,sort:ht(a),q:`organization_id:${n}`}),u=[];for(const d of l.userOrganizations){const f=await e.env.data.users.get(t,d.user_id);f&&u.push({user_id:f.user_id,email:f.email||void 0,roles:[]})}return s?e.json({start:l.start,limit:l.limit,total:l.length,members:u}):e.json(u)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:nN}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{204:{description:"Members added successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{members:r}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});for(const s of r)(await e.env.data.userOrganizations.list(t,{q:`user_id:${s}`,per_page:1})).userOrganizations.some(l=>l.organization_id===n)||await e.env.data.userOrganizations.create(t,{user_id:s,organization_id:n});return new Response(null,{status:204})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:rN}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{description:"Members removed successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{members:r}=e.req.valid("json");for(const i of r){const a=(await e.env.data.userOrganizations.list(t,{q:`user_id:${i}`,per_page:100})).userOrganizations.find(c=>c.organization_id===n);a&&await e.env.data.userOrganizations.remove(t,a.id)}return e.json({message:"Members removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:ol}},description:"User roles in organization"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});const a=await e.env.data.userRoles.list(t,r,void 0,n);return e.json(a)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string()).openapi({description:"List of role IDs to associate with the user"})})}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{201:{description:"Roles assigned successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param"),{roles:i}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});for(const c of i){if(!await e.env.data.roles.get(t,c))throw new I(400,{message:`Role ${c} not found`});if(!await e.env.data.userRoles.create(t,r,c,n))throw new I(500,{message:`Failed to assign role ${c} to user`})}return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string()).openapi({description:"List of role IDs to remove from the user"})})}}}},security:[{Bearer:["update:organizations","auth:write"]}],responses:{200:{description:"Roles removed successfully"}}}),async e=>{const t=e.var.tenant_id,{id:n,user_id:r}=e.req.valid("param"),{roles:i}=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});if(!await e.env.data.users.get(t,r))throw new I(404,{message:"User not found"});for(const c of i)if(!await e.env.data.userRoles.remove(t,r,c,n))throw new I(500,{message:`Failed to remove role ${c} from user`});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/roles",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:ot},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:ol}},description:"List of roles available in organization"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,sort:s,q:a}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const l=await e.env.data.roles.list(t,{page:r,per_page:i,sort:ht(s),q:a});return e.json(l.roles)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),query:Zj,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ls),Xj])}},description:"List of organization invitations"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),{page:r,per_page:i,include_totals:s,fields:a,include_fields:c,sort:l}=e.req.valid("query");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});let f=(await e.env.data.invites.list(t,{page:r,per_page:i})).invites.filter(p=>p.organization_id===n);if(l){const p=ht(l);if(p){const{sort_by:h,sort_order:_}=p;f.sort((g,y)=>{const m=g[h],w=y[h];if(m===void 0||w===void 0||m===w)return 0;const k=m<w?-1:1;return _==="asc"?k:-k})}}if(a){const p=a.split(",").map(h=>h.trim());f=f.map(h=>{const _={};for(const g of Object.keys(h))(c?p.includes(g):!p.includes(g))&&(_[g]=h[g]);return _})}return s?e.json({invitations:f,start:r*i,limit:i,length:f.length}):e.json(f)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:organizations","auth:read"]}],responses:{200:{content:{"application/json":{schema:Ls}},description:"An invitation"},404:{description:"Invitation not found"}}}),async e=>{const t=e.var.tenant_id,{id:n,invitation_id:r}=e.req.valid("param"),i=await e.env.data.invites.get(t,r);if(!i||i.organization_id!==n)throw new I(404,{message:"Invitation not found"});return e.json(i)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),body:{content:{"application/json":{schema:Yj}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{201:{content:{"application/json":{schema:Ls}},description:"The created invitation"}}}),async e=>{const t=e.var.tenant_id,{id:n}=e.req.valid("param"),r=e.req.valid("json");if(!await e.env.data.organizations.get(t,n))throw new I(404,{message:"Organization not found"});const a=`https://invite.placeholder/${GI()}`,c={...r,organization_id:n,invitation_url:a},l=await e.env.data.invites.create(t,c);return e.json(l,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:organizations","auth:write"]}],responses:{204:{description:"Invitation deleted successfully"},404:{description:"Invitation not found"}}}),async e=>{const t=e.var.tenant_id,{id:n,invitation_id:r}=e.req.valid("param"),i=await e.env.data.invites.get(t,r);if(!i||i.organization_id!==n)throw new I(404,{message:"Invitation not found"});if(!await e.env.data.invites.remove(t,r))throw new I(404,{message:"Invitation not found"});return e.body(null,{status:204})}),oN=new o.OpenAPIHono().openapi(o.createRoute({tags:["stats"],method:"get",path:"/daily",request:{query:o.z.object({from:o.z.string().optional().openapi({description:"Optional first day of the date range (inclusive) in YYYYMMDD format",example:"20251120"}),to:o.z.string().optional().openapi({description:"Optional last day of the date range (inclusive) in YYYYMMDD format",example:"20251219"})}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:stats","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(jw)}},description:"Daily statistics including logins, signups, and leaked passwords"}}}),async e=>{const{from:t,to:n}=e.req.valid("query");if(!e.env.data.stats)throw new I(501,{message:"Stats adapter not configured"});const r=await e.env.data.stats.getDaily(e.var.tenant_id,{from:t,to:n});return e.json(r)}).openapi(o.createRoute({tags:["stats"],method:"get",path:"/active-users",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:stats","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234})}},description:"Number of active users in the last 30 days"}}}),async e=>{if(!e.env.data.stats)throw new I(501,{message:"Stats adapter not configured"});const t=await e.env.data.stats.getActiveUsers(e.var.tenant_id);return e.json(t)}),Dc=["sms","otp","email","push-notification","webauthn-roaming","webauthn-platform","recovery-code","duo"];function lp(e){return e.replace(/-/g,"_")}const K0=o.z.object({name:o.z.enum(Dc),enabled:o.z.boolean(),trial_expired:o.z.boolean().optional()}),sN=o.z.array(K0),aN=o.z.object({enabled:o.z.boolean()}),up=o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"])}),dp=o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}),cN=o.z.object({message_type:o.z.enum(["sms","voice"])}),lN=new o.OpenAPIHono().openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:sN}},description:"List of MFA factors"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.factors,r=Dc.map(i=>{const s=lp(i);return{name:i,enabled:!!n?.[s],trial_expired:!1}});return e.json(r)}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/sms/selected-provider",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:up}},description:"Selected SMS provider"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.sms_provider?.provider||"twilio";return e.json({provider:n})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/sms/selected-provider",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:up}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:up}},description:"Updated SMS provider selection"}}}),async e=>{const{provider:t}=e.req.valid("json"),n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new I(404,{message:"Tenant not found"});return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...n.mfa,sms_provider:{provider:t}}}),e.json({provider:t})}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/sms/providers/twilio",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:dp}},description:"Twilio provider configuration"}}}),async e=>{const n=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.twilio||{};return e.json({sid:n.sid,auth_token:n.auth_token?"********":void 0,from:n.from,messaging_service_sid:n.messaging_service_sid})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/sms/providers/twilio",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:dp}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:dp}},description:"Updated Twilio configuration"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new I(404,{message:"Tenant not found"});const r=n.mfa?.twilio||{},i={...r,...t,auth_token:t.auth_token&&t.auth_token!=="********"?t.auth_token:r.auth_token};return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...n.mfa,twilio:i}}),e.json({sid:i.sid,auth_token:i.auth_token?"********":void 0,from:i.from,messaging_service_sid:i.messaging_service_sid})}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/phone/message-types",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(cN)}},description:"Available message types"}}}),async e=>{const t=[{message_type:"sms"}];return e.json(t)}).openapi(o.createRoute({tags:["guardian"],method:"get",path:"/factors/{factor_name}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({factor_name:o.z.enum(Dc)})},security:[{Bearer:["read:guardian_factors","auth:read"]}],responses:{200:{content:{"application/json":{schema:K0}},description:"MFA factor details"}}}),async e=>{const{factor_name:t}=e.req.valid("param"),r=(await e.env.data.tenants.get(e.var.tenant_id))?.mfa?.factors,i=lp(t);return e.json({name:t,enabled:!!r?.[i],trial_expired:!1})}).openapi(o.createRoute({tags:["guardian"],method:"put",path:"/factors/{factor_name}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({factor_name:o.z.enum(Dc)}),body:{content:{"application/json":{schema:aN}}}},security:[{Bearer:["update:guardian_factors","auth:write"]}],responses:{200:{content:{"application/json":{schema:K0}},description:"Updated MFA factor"}}}),async e=>{const{factor_name:t}=e.req.valid("param"),{enabled:n}=e.req.valid("json"),r=lp(t),i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(404,{message:"Tenant not found"});const s=i.mfa?.factors;return await e.env.data.tenants.update(e.var.tenant_id,{mfa:{...i.mfa,factors:{sms:s?.sms??!1,otp:s?.otp??!1,email:s?.email??!1,push_notification:s?.push_notification??!1,webauthn_roaming:s?.webauthn_roaming??!1,webauthn_platform:s?.webauthn_platform??!1,recovery_code:s?.recovery_code??!1,duo:s?.duo??!1,[r]:n}}}),e.json({name:t,enabled:n,trial_expired:!1})});function uN(e){const t=new o.OpenAPIHono,n=e.managementDataAdapter??e.dataAdapter;t.use(async(i,s)=>{const a=i.req.header("origin"),c=l=>{i.res.headers.set("Access-Control-Allow-Origin",l),i.res.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),i.res.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),i.res.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),i.res.headers.set("Access-Control-Max-Age","600"),i.res.headers.set("Access-Control-Allow-Credentials","true")};if(i.req.method==="OPTIONS"){const l=new Response(null,{status:204});if(a){if(e.allowedOrigins?.includes(a))return l.headers.set("Access-Control-Allow-Origin",a),l.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),l.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),l.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),l.headers.set("Access-Control-Max-Age","600"),l.headers.set("Access-Control-Allow-Credentials","true"),l;const u=i.req.header("tenant-id");if(u&&(await n.clients.list(u,{})).clients.flatMap(p=>p.web_origins||[]).includes(a))return l.headers.set("Access-Control-Allow-Origin",a),l.headers.set("Access-Control-Allow-Headers","Tenant-Id, Content-Type, Content-Range, Auth0-Client, Authorization, Range, Upgrade-Insecure-Requests"),l.headers.set("Access-Control-Allow-Methods","POST, PUT, GET, DELETE, PATCH, OPTIONS"),l.headers.set("Access-Control-Expose-Headers","Content-Length, Content-Range"),l.headers.set("Access-Control-Max-Age","600"),l.headers.set("Access-Control-Allow-Credentials","true"),l}return l}if(await s(),a){if(e.allowedOrigins?.includes(a)){c(a);return}const l=i.var.tenant_id||i.req.header("tenant-id");l&&(await n.clients.list(l,{})).clients.flatMap(f=>f.web_origins||[]).includes(a)&&c(a)}}),N_(t),t.use(async(i,s)=>{const a=Bo(i,n),c=rs({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),l=Qa(a,{defaultTtl:0,cacheEntities:["tenants","connections","clients","branding","themes","promptSettings","customText","forms","hooks"],cache:c});return i.env.data=Ya(i,l),i.env.entityHooks=e.entityHooks,s()}),t.use(ns).use(ts).use($d(t)).use(async(i,s)=>(e.entityHooks&&i.var.tenant_id&&(i.env.data=Pk(i.env.data,{tenantId:i.var.tenant_id,entityHooks:e.entityHooks})),s()));const r=t.route("/branding",nz).route("/custom-domains",Nj).route("/email/providers",Cj).route("/users",P7).route("/keys",PI).route("/users-by-email",OI).route("/clients",DI).route("/client-grants",Jj).route("/tenants",UI).route("/logs",MI).route("/hooks",JI).route("/connections",QI).route("/prompts",ej).route("/sessions",Ij).route("/refresh_tokens",jj).route("/forms",Bj).route("/flows",qj).route("/roles",Hj).route("/resource-servers",Kj).route("/organizations",iN).route("/stats",oN).route("/guardian",lN);if(e.managementApiExtensions)for(const i of e.managementApiExtensions)r.route(i.path,i.router);return r.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management API"},servers:[{url:"/api/v2",description:"API V2"}],security:[{oauth2:["openid","email","profile"]}]}),r}var Ok=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 l(d,f){a.res.headers.set(d,f)}const u=await r(a.req.header("origin")||"",a);if(u&&l("Access-Control-Allow-Origin",u),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());const d=await i(a.req.header("origin")||"",a);d.length&&l("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&&(l("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})}};function rr(e){if(e)return`${e.name}/${e.version}${e.env?.node?` (env: node/${e.env.node})`:""}`}function Vt(e,t){const n=e.var.tenant_id;if(!n){e.set("tenant_id",t);return}if(n!==t)throw new I(403,{message:"Tenant mismatch"})}async function Jy(e,t,n,r){if(!r.state)throw new W(400,{message:"State not found"});const i=t.connections.find(l=>l.name===n);if(!i)throw e.set("client_id",t.client_id),await fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Connection not found"}),new W(403,{message:"Connection Not Found"});let s=await e.env.data.loginSessions.get(t.tenant.id,r.state);if(!s){const l=e.get("ip"),u=e.get("useragent"),d=e.get("auth0_client");s=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),ip:l,useragent:u,auth0Client:rr(d)})}const c=await U2(e,i.strategy).getRedirect(e,i);return await e.env.data.codes.create(t.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+Cz*1e3).toISOString()}),new Response(null,{status:302,headers:{location:c.redirectUrl}})}async function Zy(e,{code:t,state:n}){const{env:r}=e,i=await r.data.codes.get(e.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new W(403,{message:"State not found"});const s=await r.data.loginSessions.get(e.var.tenant_id||"",i.login_id);if(!s)throw new W(403,{message:"Session not found"});if(s.authorization_url){const _=new URL(s.authorization_url).hostname,g=e.var.host||"";if(_!==g&&_){const y=new URL(`https://${_}/callback`);return y.searchParams.set("state",n),y.searchParams.set("code",t),new Response("Redirecting",{status:307,headers:{location:y.toString()}})}}const a=await He(r,s.authParams.client_id);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c=a.connections.find(_=>_.id===i.connection_id);if(!c)throw await fe(e,a.tenant.id,{type:pe.FAILED_LOGIN,description:"Connection not found"}),new W(403,{message:"Connection not found"});if(e.set("connection",c.name),!s.authParams.redirect_uri)throw await fe(e,a.tenant.id,{type:pe.FAILED_LOGIN,description:"Redirect URI not defined"}),new W(403,{message:"Redirect URI not defined"});const u=await U2(e,c.strategy).validateAuthorizationCodeAndGetUser(e,c,t,i.code_verifier),{sub:d,...f}=u;e.set("user_id",d);const p=u.email?.toLocaleLowerCase()||`${c.name}.${d}@${new URL(e.env.ISSUER).hostname}`;e.set("username",p);const h=await Cu(e,{client:a,username:p,provider:c.strategy,connection:c.name,userId:d,profileData:f,isSocial:!0,ip:e.var.ip});return yt(e,{client:a,authParams:s.authParams,loginSession:s,user:h,authStrategy:{strategy:c.strategy,strategy_type:"social"}})}async function yc(e,t,n,r,i,s){const a=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(!a)throw new I(400,{message:"State not found"});const c=await e.env.data.loginSessions.get(e.var.tenant_id,a.login_id);if(!c)throw new I(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new I(400,{message:"Redirect uri not found"});fe(e,e.var.tenant_id,{type:pe.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});const u=new URL(l);return LA(u,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),e.redirect(`${mt(e.env)}login/identifier?state=${c.id}&error=${encodeURIComponent(n)}${r?`&error_description=${encodeURIComponent(r)}`:""}`)}const dN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{state:t,code:n,error:r,error_description:i,error_code:s,error_reason:a}=e.req.valid("query");if(r)return yc(e,t,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});try{const c=await Zy(e,{code:n,state:t});if(!(c instanceof Response))throw new I(500,{message:"Internal server error"});return c}catch(c){if(c instanceof W&&c.status===400){const l=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(l&&await e.env.data.loginSessions.get(e.var.tenant_id,l.login_id)){let d="access_denied";try{d=JSON.parse(c.message).message||d}catch{d=c.message||d}return yc(e,t,"access_denied",d)}}throw c}}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{state:t,code:n,error:r,error_description:i,error_code:s,error_reason:a}=e.req.valid("form");if(r)return yc(e,t,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});try{const c=await Zy(e,{code:n,state:t});if(!(c instanceof Response))throw new I(500,{message:"Internal server error"});return c}catch(c){if(c instanceof W&&c.status===400){const l=await e.env.data.codes.get(e.var.tenant_id||"",t,"oauth2_state");if(l&&await e.env.data.loginSessions.get(e.var.tenant_id,l.login_id)){let d="access_denied";try{d=JSON.parse(c.message).message||d}catch{d=c.message||d}return yc(e,t,"access_denied",d)}}throw c}});function P_(e,t=[],n={}){try{const r=new URL(e);return t.some(i=>{try{return pN(r,new URL(i),n)}catch{return!1}})}catch{return!1}}function pN(e,t,n={}){if(e.protocol!==t.protocol)return!1;if(n.allowPathWildcards&&t.pathname.includes("*")){const r=t.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(e.pathname))return!1}else if(e.pathname!==t.pathname)return!1;if(n.allowSubDomainWildcards&&t.hostname.startsWith("*.")&&t.hostname.split(".").length>2&&["http:","https:"].includes(t.protocol)){const r=t.hostname.split(".").slice(1).join(".");return e.hostname===r||e.hostname.endsWith("."+r)}return e.hostname===t.hostname}const fN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async e=>{const{client_id:t,returnTo:n}=e.req.valid("query");let r;try{r=await He(e.env,t)}catch{return e.text("OK")}let i;try{i=await He(e.env,"DEFAULT_CLIENT")}catch{}e.set("client_id",t),Vt(e,r.tenant.id);const s=n||e.req.header("referer");if(!s)return e.text("OK");if(!P_(s,[...r.allowed_logout_urls||[],...i?.allowed_logout_urls||[]],{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:"Invalid redirect uri"});const a=e.req.header("cookie");if(a){const u=pi(r.tenant.id,a);if(u){const d=await e.env.data.sessions.get(r.tenant.id,u);if(d){const f=await e.env.data.users.get(r.tenant.id,d.user_id);if(f&&(e.set("user_id",f.user_id),e.set("connection",f.connection)),d.login_session_id){const p=await e.env.data.refreshTokens.list(r.tenant.id,{q:`login_id=${d.login_session_id}`,page:0,per_page:100,include_totals:!1});await Promise.all(p.refresh_tokens.map(h=>e.env.data.refreshTokens.remove(r.tenant.id,h.id)))}await e.env.data.sessions.update(r.tenant.id,u,{revoked_at:new Date().toISOString()})}}}fe(e,r.tenant.id,{type:pe.SUCCESS_LOGOUT,description:"User successfully logged out"});const c=new Headers;return qw(r.tenant.id,e.var.custom_domain||e.req.header("host")).forEach(u=>{c.append("set-cookie",u)}),c.set("location",s),new Response("Redirecting",{status:302,headers:c})}),hN=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),Xy=o.z.object({sub:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_number_verified:o.z.boolean().optional(),name:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),middle_name:o.z.string().optional(),nickname:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),picture:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),locale:o.z.string().optional(),updated_at:o.z.number().optional(),address:hN});function Yy(e,t){const n={sub:e.user_id};if(t.includes("email")&&(e.email&&(n.email=e.email),e.email_verified!==void 0&&(n.email_verified=e.email_verified)),t.includes("profile")){e.name&&(n.name=e.name),e.family_name&&(n.family_name=e.family_name),e.given_name&&(n.given_name=e.given_name),e.middle_name&&(n.middle_name=e.middle_name),e.nickname&&(n.nickname=e.nickname);const r=e.preferred_username||e.username;r&&(n.preferred_username=r),e.profile&&(n.profile=e.profile),e.picture&&(n.picture=e.picture),e.website&&(n.website=e.website),e.gender&&(n.gender=e.gender),e.birthdate&&(n.birthdate=e.birthdate),e.zoneinfo&&(n.zoneinfo=e.zoneinfo),e.locale&&(n.locale=e.locale),e.updated_at&&(n.updated_at=Math.floor(new Date(e.updated_at).getTime()/1e3))}return t.includes("address")&&e.address&&(n.address=e.address),t.includes("phone")&&(e.phone_number&&(n.phone_number=e.phone_number),e.phone_verified!==void 0&&(n.phone_number_verified=e.phone_verified)),n}const _N=o.z.object({access_token:o.z.string().optional()}),mN=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Xy}},description:"Userinfo"}}}),async e=>{if(!e.var.user)throw new I(404,{message:"User not found"});const t=e.var.user.tenant_id||e.var.tenant_id;if(!t)throw new I(400,{message:"Unable to determine tenant"});const n=await e.env.data.users.get(t,e.var.user.sub);if(!n)throw new I(404,{message:"User not found"});const i=e.var.user?.scope?.split(" ")||[],s=Yy(n,i),a=e.env.hooks?.onFetchUserInfo;if(a){const c={};return await a({ctx:e,user:n,tenant_id:t,scopes:i},{setCustomClaim:(l,u)=>{c[l]=u}}),e.json({...s,...c})}return e.json(s)}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:_N}}}},responses:{200:{content:{"application/json":{schema:Xy}},description:"Userinfo"}}}),async e=>{let t=null;if(e.var.user&&(t=e.var.user),!t){const c=e.req.header("authorization")||"",[l,u]=c.split(" ");if(l?.toLowerCase()==="bearer"&&u){if(t=await V0(e,u),!(t?.scope?.split(" ")||[]).includes("openid"))throw new W(403,{message:"openid scope required"});e.set("user",t)}}if(!t)try{const c=await e.req.parseBody(),l=typeof c.access_token=="string"?c.access_token:void 0;if(l){if(t=await V0(e,l),!(t?.scope?.split(" ")||[]).includes("openid"))throw new W(403,{message:"openid scope required"});e.set("user",t)}}catch(c){if(c instanceof I||c instanceof W)throw c}if(!t)throw new I(401,{message:"No access token provided"});const n=t.tenant_id||e.var.tenant_id;if(!n)throw new I(400,{message:"Unable to determine tenant"});const r=await e.env.data.users.get(n,t.sub);if(!r)throw new I(404,{message:"User not found"});const i=t?.scope?.split(" ")||[],s=Yy(r,i),a=e.env.hooks?.onFetchUserInfo;if(a){const c={};return await a({ctx:e,user:r,tenant_id:n,scopes:i},{setCustomClaim:(l,u)=>{c[l]=u}}),e.json({...s,...c})}return e.json(s)}),gN=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:tw}},description:"List of tenants"}}}),async e=>{const t=await Lc(e.env.data);return e.json({keys:t},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${uc}, stale-while-revalidate=${uc*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:lf}},description:"List of tenants"}}}),async e=>{const t=lf.parse({issuer:$u(e.env),authorization_endpoint:`${Le(e.env)}authorize`,token_endpoint:`${Le(e.env)}oauth/token`,device_authorization_endpoint:`${Le(e.env)}oauth/device/code`,userinfo_endpoint:`${Le(e.env)}userinfo`,mfa_challenge_endpoint:`${Le(e.env)}mfa/challenge`,jwks_uri:`${Le(e.env)}.well-known/jwks.json`,registration_endpoint:`${Le(e.env)}oidc/register`,revocation_endpoint:`${Le(e.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return e.json(t,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${uc}, stale-while-revalidate=${uc*2}, stale-if-error=86400`}})}).get("/*",async e=>{const t=e.var.custom_domain||e.req.header("x-forwarded-host");if(!t)return e.text("Not Found",404);const n=await e.env.data.customDomains.getByDomain(t);if(!n)return e.text("Not Found",404);const r=await e.env.data.customDomains.get(n.tenant_id,n.custom_domain_id);if(!r?.verification?.methods)return e.text("Not Found",404);const i=new URL(e.req.url).pathname,s=r.verification.methods.find(a=>a.name==="http"&&new URL(a.http_url).pathname===i);return!s||s.name!=="http"?e.text("Not Found",404):e.text(s.http_body,200,{"content-type":"text/plain"})});function Js(e,t){if(!e||!t||e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}const Rk=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional(),organization:o.z.string().optional()});async function yN(e,t){const n=await He(e.env,t.client_id,e.var.tenant_id);if(n.client_secret&&!Js(n.client_secret,t.client_secret))throw new W(403,{message:"Invalid client credentials"});let r;if(t.organization){const s=await e.env.data.organizations.get(n.tenant.id,t.organization);if(!s)throw new W(400,{error:"invalid_request",error_description:`Organization '${t.organization}' not found`});r={id:s.id,name:s.name}}const i={client_id:n.client_id,scope:t.scope,audience:t.audience||n.tenant.default_audience,organization:t.organization};return{client:n,authParams:i,organization:r}}const bN=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.z.string().optional(),organization:o.z.string().optional()}).refine(e=>"client_secret"in e&&!("code_verifier"in e)||!("client_secret"in e)&&"code_verifier"in e,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function vN(e,t){const n=await He(e.env,t.client_id,e.var.tenant_id),r=await e.env.data.codes.get(n.tenant.id,t.code,"authorization_code");if(!r||!r.user_id)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials"}),new W(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Code expired",userId:r.user_id}),new W(403,{message:"Code expired"});if(r.used_at)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid authorization code",userId:r.user_id}),new W(400,{error:"invalid_grant",error_description:"Invalid authorization code"});const i=await e.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new W(403,{message:"Invalid login"});if(t.organization&&i.authParams.organization&&t.organization!==i.authParams.organization)throw new W(400,{error:"invalid_request",error_description:"Organization parameter does not match login session organization"});if("client_secret"in t){let u;try{u=await He(e.env,"DEFAULT_CLIENT")}catch{}if(!Js(n.client_secret,t.client_secret)&&!Js(u?.client_secret,t.client_secret))throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new W(403,{message:"Invalid client credentials"})}else if(r.code_challenge&&r.code_challenge_method&&t.code_verifier){const u=await zz(t.code_verifier,r.code_challenge_method);if(!Js(u,r.code_challenge))throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new W(403,{message:"Invalid client credentials"})}if(r.redirect_uri&&r.redirect_uri!==t.redirect_uri)throw fe(e,n.tenant.id,{type:pe.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid redirect uri",userId:r.user_id}),new W(403,{message:"Invalid redirect uri"});const s=await e.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new W(403,{message:"User not found"});await e.env.data.codes.used(n.tenant.id,t.code);let a;i.session_id&&i.authParams.scope?.split(" ").includes("offline_access")&&(a=await b2(e,{user:s,client:n,login_id:i.id,scope:i.authParams.scope,audience:i.authParams.audience}));let c;if(i.authParams.organization){const u=await e.env.data.organizations.get(n.tenant.id,i.authParams.organization);u?c={id:u.id,name:u.name}:c={id:i.authParams.organization,name:"Unknown"}}let l;if(i.authParams.max_age!==void 0&&i.session_id){const u=await e.env.data.sessions.get(n.tenant.id,i.session_id);u?.authenticated_at&&(l=Math.floor(new Date(u.authenticated_at).getTime()/1e3))}return{user:s,client:n,loginSession:i,session_id:i.session_id,refresh_token:a?.id,organization:c,auth_time:l,authParams:{...i.authParams,state:r.state,nonce:r.nonce,response_mode:pn.WEB_MESSAGE,client_id:n.client_id,scope:i.authParams.scope,audience:i.authParams.audience}}}function Qy(e,t){const n=e.var.log;n?e.set("log",`${n}
|
|
82
82
|
${t}`):e.set("log",t)}const wN=o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),redirect_uri:o.z.string().optional(),refresh_token:o.z.string(),client_secret:o.z.string().optional()});async function kN(e,t){const n=await He(e.env,t.client_id,e.var.tenant_id);if(t.client_secret&&n.client_secret&&!Js(n.client_secret,t.client_secret))throw new W(403,{error:"invalid_client",error_description:"Client authentication failed"});const r=await e.env.data.refreshTokens.get(n.tenant.id,t.refresh_token);if(r){if(r.expires_at&&new Date(r.expires_at)<new Date||r.idle_expires_at&&new Date(r.idle_expires_at)<new Date)throw Qy(e,`Refresh token has expired: ${t.refresh_token}`),new W(400,{error:"invalid_grant",error_description:"Refresh token has expired"})}else throw Qy(e,`Invalid refresh token: ${t.refresh_token}`),new W(400,{error:"invalid_grant",error_description:"Invalid refresh token"});const i=await e.env.data.users.get(n.tenant.id,r.user_id);if(!i)throw new W(403,{message:"User not found"});e.set("user_id",i.user_id);const s=r.resource_servers[0];let a;if(r.login_id&&(a=(await e.env.data.loginSessions.get(n.tenant.id,r.login_id))?.session_id),r.idle_expires_at){const c=new Date(Date.now()+2592e6);await e.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:c.toISOString(),last_exchanged_at:new Date().toISOString(),device:{...r.device,last_ip:e.req.header["x-real-ip"]||"",last_user_agent:e.req.header["user-agent"]||""}}),r.login_id&&await e.env.data.loginSessions.update(n.tenant.id,r.login_id,{expires_at:c.toISOString()})}return{user:i,client:n,refresh_token:r.id,session_id:a,login_id:r.login_id,authParams:{client_id:n.client_id,audience:s?.audience,scope:s?.scopes,response_mode:pn.WEB_MESSAGE}}}const $N={version:4,country_calling_codes:{1:["US","AG","AI","AS","BB","BM","BS","CA","DM","DO","GD","GU","JM","KN","KY","LC","MP","MS","PR","SX","TC","TT","VC","VG","VI"],7:["RU","KZ"],20:["EG"],27:["ZA"],30:["GR"],31:["NL"],32:["BE"],33:["FR"],34:["ES"],36:["HU"],39:["IT","VA"],40:["RO"],41:["CH"],43:["AT"],44:["GB","GG","IM","JE"],45:["DK"],46:["SE"],47:["NO","SJ"],48:["PL"],49:["DE"],51:["PE"],52:["MX"],53:["CU"],54:["AR"],55:["BR"],56:["CL"],57:["CO"],58:["VE"],60:["MY"],61:["AU","CC","CX"],62:["ID"],63:["PH"],64:["NZ"],65:["SG"],66:["TH"],81:["JP"],82:["KR"],84:["VN"],86:["CN"],90:["TR"],91:["IN"],92:["PK"],93:["AF"],94:["LK"],95:["MM"],98:["IR"],211:["SS"],212:["MA","EH"],213:["DZ"],216:["TN"],218:["LY"],220:["GM"],221:["SN"],222:["MR"],223:["ML"],224:["GN"],225:["CI"],226:["BF"],227:["NE"],228:["TG"],229:["BJ"],230:["MU"],231:["LR"],232:["SL"],233:["GH"],234:["NG"],235:["TD"],236:["CF"],237:["CM"],238:["CV"],239:["ST"],240:["GQ"],241:["GA"],242:["CG"],243:["CD"],244:["AO"],245:["GW"],246:["IO"],247:["AC"],248:["SC"],249:["SD"],250:["RW"],251:["ET"],252:["SO"],253:["DJ"],254:["KE"],255:["TZ"],256:["UG"],257:["BI"],258:["MZ"],260:["ZM"],261:["MG"],262:["RE","YT"],263:["ZW"],264:["NA"],265:["MW"],266:["LS"],267:["BW"],268:["SZ"],269:["KM"],290:["SH","TA"],291:["ER"],297:["AW"],298:["FO"],299:["GL"],350:["GI"],351:["PT"],352:["LU"],353:["IE"],354:["IS"],355:["AL"],356:["MT"],357:["CY"],358:["FI","AX"],359:["BG"],370:["LT"],371:["LV"],372:["EE"],373:["MD"],374:["AM"],375:["BY"],376:["AD"],377:["MC"],378:["SM"],380:["UA"],381:["RS"],382:["ME"],383:["XK"],385:["HR"],386:["SI"],387:["BA"],389:["MK"],420:["CZ"],421:["SK"],423:["LI"],500:["FK"],501:["BZ"],502:["GT"],503:["SV"],504:["HN"],505:["NI"],506:["CR"],507:["PA"],508:["PM"],509:["HT"],590:["GP","BL","MF"],591:["BO"],592:["GY"],593:["EC"],594:["GF"],595:["PY"],596:["MQ"],597:["SR"],598:["UY"],599:["CW","BQ"],670:["TL"],672:["NF"],673:["BN"],674:["NR"],675:["PG"],676:["TO"],677:["SB"],678:["VU"],679:["FJ"],680:["PW"],681:["WF"],682:["CK"],683:["NU"],685:["WS"],686:["KI"],687:["NC"],688:["TV"],689:["PF"],690:["TK"],691:["FM"],692:["MH"],850:["KP"],852:["HK"],853:["MO"],855:["KH"],856:["LA"],880:["BD"],886:["TW"],960:["MV"],961:["LB"],962:["JO"],963:["SY"],964:["IQ"],965:["KW"],966:["SA"],967:["YE"],968:["OM"],970:["PS"],971:["AE"],972:["IL"],973:["BH"],974:["QA"],975:["BT"],976:["MN"],977:["NP"],992:["TJ"],993:["TM"],994:["AZ"],995:["GE"],996:["KG"],998:["UZ"]},countries:{AC:["247","00","(?:[01589]\\d|[46])\\d{4}",[5,6]],AD:["376","00","(?:1|6\\d)\\d{7}|[135-9]\\d{5}",[6,8,9],[["(\\d{3})(\\d{3})","$1 $2",["[135-9]"]],["(\\d{4})(\\d{4})","$1 $2",["1"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]]],AE:["971","00","(?:[4-7]\\d|9[0-689])\\d{7}|800\\d{2,9}|[2-4679]\\d{7}",[5,6,7,8,9,10,11,12],[["(\\d{3})(\\d{2,9})","$1 $2",["60|8"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[236]|[479][2-8]"],"0$1"],["(\\d{3})(\\d)(\\d{5})","$1 $2 $3",["[479]"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"]],"0"],AF:["93","00","[2-7]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"]],"0"],AG:["1","011","(?:268|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([457]\\d{6})$|1","268$1",0,"268"],AI:["1","011","(?:264|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2457]\\d{6})$|1","264$1",0,"264"],AL:["355","00","(?:700\\d\\d|900)\\d{3}|8\\d{5,7}|(?:[2-5]|6\\d)\\d{7}",[6,7,8,9],[["(\\d{3})(\\d{3,4})","$1 $2",["80|9"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["4[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2358][2-5]|4"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["[23578]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["6"],"0$1"]],"0"],AM:["374","00","(?:[1-489]\\d|55|60|77)\\d{6}",[8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[89]0"],"0 $1"],["(\\d{3})(\\d{5})","$1 $2",["2|3[12]"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["1|47"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[3-9]"],"0$1"]],"0"],AO:["244","00","[29]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[29]"]]]],AR:["54","00","(?:11|[89]\\d\\d)\\d{8}|[2368]\\d{9}",[10,11],[["(\\d{4})(\\d{2})(\\d{4})","$1 $2-$3",["2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9])","2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8]))|2(?:2[24-9]|3[1-59]|47)","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5[56][46]|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|58|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|54(?:4|5[13-7]|6[89])|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:454|85[56])[46]|3(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["1"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[68]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2-$3",["[23]"],"0$1",1],["(\\d)(\\d{4})(\\d{2})(\\d{4})","$2 15-$3-$4",["9(?:2[2-469]|3[3-578])","9(?:2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9]))","9(?:2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8])))|92(?:2[24-9]|3[1-59]|47)","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5(?:[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|5(?:4(?:4|5[13-7]|6[89])|[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",0,"$1 $2 $3-$4"],["(\\d)(\\d{2})(\\d{4})(\\d{4})","$2 15-$3-$4",["91"],"0$1",0,"$1 $2 $3-$4"],["(\\d{3})(\\d{3})(\\d{5})","$1-$2-$3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{4})","$2 15-$3-$4",["9"],"0$1",0,"$1 $2 $3-$4"]],"0",0,"0?(?:(11|2(?:2(?:02?|[13]|2[13-79]|4[1-6]|5[2457]|6[124-8]|7[1-4]|8[13-6]|9[1267])|3(?:02?|1[467]|2[03-6]|3[13-8]|[49][2-6]|5[2-8]|[67])|4(?:7[3-578]|9)|6(?:[0136]|2[24-6]|4[6-8]?|5[15-8])|80|9(?:0[1-3]|[19]|2\\d|3[1-6]|4[02568]?|5[2-4]|6[2-46]|72?|8[23]?))|3(?:3(?:2[79]|6|8[2578])|4(?:0[0-24-9]|[12]|3[5-8]?|4[24-7]|5[4-68]?|6[02-9]|7[126]|8[2379]?|9[1-36-8])|5(?:1|2[1245]|3[237]?|4[1-46-9]|6[2-4]|7[1-6]|8[2-5]?)|6[24]|7(?:[069]|1[1568]|2[15]|3[145]|4[13]|5[14-8]|7[2-57]|8[126])|8(?:[01]|2[15-7]|3[2578]?|4[13-6]|5[4-8]?|6[1-357-9]|7[36-8]?|8[5-8]?|9[124])))15)?","9$1"],AS:["1","011","(?:[58]\\d\\d|684|900)\\d{7}",[10],0,"1",0,"([267]\\d{6})$|1","684$1",0,"684"],AT:["43","00","1\\d{3,12}|2\\d{6,12}|43(?:(?:0\\d|5[02-9])\\d{3,9}|2\\d{4,5}|[3467]\\d{4}|8\\d{4,6}|9\\d{4,7})|5\\d{4,12}|8\\d{7,12}|9\\d{8,12}|(?:[367]\\d|4[0-24-9])\\d{4,11}",[4,5,6,7,8,9,10,11,12,13],[["(\\d)(\\d{3,12})","$1 $2",["1(?:11|[2-9])"],"0$1"],["(\\d{3})(\\d{2})","$1 $2",["517"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["5[079]"],"0$1"],["(\\d{3})(\\d{3,10})","$1 $2",["(?:31|4)6|51|6(?:48|5[0-3579]|[6-9])|7(?:20|32|8)|[89]","(?:31|4)6|51|6(?:485|5[0-3579]|[6-9])|7(?:20|32|8)|[89]"],"0$1"],["(\\d{4})(\\d{3,9})","$1 $2",["[2-467]|5[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["5"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,7})","$1 $2 $3",["5"],"0$1"]],"0"],AU:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{7}(?:\\d(?:\\d{2})?)?|8[0-24-9]\\d{7})|[2-478]\\d{8}|1\\d{4,7}",[5,6,7,8,9,10,12],[["(\\d{2})(\\d{3,4})","$1 $2",["16"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,4})","$1 $2 $3",["16"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["14|4"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[2378]"],"(0$1)"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:30|[89])"]]],"0",0,"(183[12])|0",0,0,0,[["(?:(?:241|349)0\\d\\d|8(?:51(?:0(?:0[03-9]|[12479]\\d|3[2-9]|5[0-8]|6[1-9]|8[0-7])|1(?:[0235689]\\d|1[0-69]|4[0-589]|7[0-47-9])|2(?:0[0-79]|[18][13579]|2[14-9]|3[0-46-9]|[4-6]\\d|7[89]|9[0-4])|[34]\\d\\d)|91(?:(?:[0-58]\\d|6[0135-9])\\d|7(?:0[0-24-9]|[1-9]\\d)|9(?:[0-46-9]\\d|5[0-79]))))\\d{3}|(?:2(?:[0-26-9]\\d|3[0-8]|4[02-9]|5[0135-9])|3(?:[0-3589]\\d|4[0-578]|6[1-9]|7[0-35-9])|7(?:[013-57-9]\\d|2[0-8])|8(?:55|6[0-8]|[78]\\d|9[02-9]))\\d{6}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,["163\\d{2,6}",[5,6,7,8,9]],["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],AW:["297","00","(?:[25-79]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[25-9]"]]]],AX:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","2\\d{4,9}|35\\d{4,5}|(?:60\\d\\d|800)\\d{4,6}|7\\d{5,11}|(?:[14]\\d|3[0-46-9]|50)\\d{4,8}",[5,6,7,8,9,10,11,12],0,"0",0,0,0,0,"18",0,"00"],AZ:["994","00","365\\d{6}|(?:[124579]\\d|60|88)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[28]|2|365|46","1[28]|2|365[45]|46","1[28]|2|365(?:4|5[02])|46"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[13-9]"],"0$1"]],"0"],BA:["387","00","6\\d{8}|(?:[35689]\\d|49|70)\\d{6}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["6[1-3]|[7-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2-$3",["[3-5]|6[56]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["6"],"0$1"]],"0"],BB:["1","011","(?:246|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","246$1",0,"246"],BD:["880","00","[1-469]\\d{9}|8[0-79]\\d{7,8}|[2-79]\\d{8}|[2-9]\\d{7}|[3-9]\\d{6}|[57-9]\\d{5}",[6,7,8,9,10],[["(\\d{2})(\\d{4,6})","$1-$2",["31[5-8]|[459]1"],"0$1"],["(\\d{3})(\\d{3,7})","$1-$2",["3(?:[67]|8[013-9])|4(?:6[168]|7|[89][18])|5(?:6[128]|9)|6(?:[15]|28|4[14])|7[2-589]|8(?:0[014-9]|[12])|9[358]|(?:3[2-5]|4[235]|5[2-578]|6[0389]|76|8[3-7]|9[24])1|(?:44|66)[01346-9]"],"0$1"],["(\\d{4})(\\d{3,6})","$1-$2",["[13-9]|2[23]"],"0$1"],["(\\d)(\\d{7,8})","$1-$2",["2"],"0$1"]],"0"],BE:["32","00","4\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:80|9)0"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[239]|4[23]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[15-8]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4"],"0$1"]],"0"],BF:["226","00","(?:[025-7]\\d|44)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[024-7]"]]]],BG:["359","00","00800\\d{7}|[2-7]\\d{6,7}|[89]\\d{6,8}|2\\d{5}",[6,7,8,9,12],[["(\\d)(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["43[1-6]|70[1-9]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:70|8)0"],"0$1"],["(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3",["43[1-7]|7"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[48]|9[08]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"]],"0"],BH:["973","00","[136-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[13679]|8[02-4679]"]]]],BI:["257","00","(?:[267]\\d|31)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2367]"]]]],BJ:["229","00","(?:01\\d|8)\\d{7}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["0"]]]],BL:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:2[7-9]|3[3-7]|5[12]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],BM:["1","011","(?:441|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","441$1",0,"441"],BN:["673","00","[2-578]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-578]"]]]],BO:["591","00(?:1\\d)?","8001\\d{5}|(?:[2-467]\\d|50)\\d{6}",[8,9],[["(\\d)(\\d{7})","$1 $2",["[235]|4[46]"]],["(\\d{8})","$1",["[67]"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["8"]]],"0",0,"0(1\\d)?"],BQ:["599","00","(?:[34]1|7\\d)\\d{5}",[7],0,0,0,0,0,0,"[347]"],BR:["55","00(?:1[245]|2[1-35]|31|4[13]|[56]5|99)","[1-467]\\d{9,10}|55[0-46-9]\\d{8}|[34]\\d{7}|55\\d{7,8}|(?:5[0-46-9]|[89]\\d)\\d{7,9}",[8,9,10,11],[["(\\d{4})(\\d{4})","$1-$2",["300|4(?:0[02]|37|86)","300|4(?:0(?:0|20)|370|864)"]],["(\\d{3})(\\d{2,3})(\\d{4})","$1 $2 $3",["(?:[358]|90)0"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-57]"],"($1)"],["(\\d{2})(\\d{5})(\\d{4})","$1 $2-$3",["[16][1-9]|[2-57-9]"],"($1)"]],"0",0,"(?:0|90)(?:(1[245]|2[1-35]|31|4[13]|[56]5|99)(\\d{10,11}))?","$2"],BS:["1","011","(?:242|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([3-8]\\d{6})$|1","242$1",0,"242"],BT:["975","00","[178]\\d{7}|[2-8]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[2-6]|7[246]|8[2-4]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[67]|[78]"]]]],BW:["267","00","(?:0800|(?:[37]|800)\\d)\\d{6}|(?:[2-6]\\d|90)\\d{5}",[7,8,10],[["(\\d{2})(\\d{5})","$1 $2",["90"]],["(\\d{3})(\\d{4})","$1 $2",["[24-6]|3[15-9]"]],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37]"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["8"]]]],BY:["375","810","(?:[12]\\d|33|44|902)\\d{7}|8(?:0[0-79]\\d{5,7}|[1-7]\\d{9})|8(?:1[0-489]|[5-79]\\d)\\d{7}|8[1-79]\\d{6,7}|8[0-79]\\d{5}|8\\d{5}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3})","$1 $2",["800"],"8 $1"],["(\\d{3})(\\d{2})(\\d{2,4})","$1 $2 $3",["800"],"8 $1"],["(\\d{4})(\\d{2})(\\d{3})","$1 $2-$3",["1(?:5[169]|6[3-5]|7[179])|2(?:1[35]|2[34]|3[3-5])","1(?:5[169]|6(?:3[1-3]|4|5[125])|7(?:1[3-9]|7[0-24-6]|9[2-7]))|2(?:1[35]|2[34]|3[3-5])"],"8 0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["1(?:[56]|7[467])|2[1-3]"],"8 0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-4]"],"8 0$1"],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["[89]"],"8 $1"]],"8",0,"0|80?",0,0,0,0,"8~10"],BZ:["501","00","(?:0800\\d|[2-8])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1-$2",["[2-8]"]],["(\\d)(\\d{3})(\\d{4})(\\d{3})","$1-$2-$3-$4",["0"]]]],CA:["1","011","[2-9]\\d{9}|3\\d{6}",[7,10],0,"1",0,0,0,0,0,[["(?:2(?:04|[23]6|[48]9|5[07]|63)|3(?:06|43|54|6[578]|82)|4(?:03|1[68]|[26]8|3[178]|50|74)|5(?:06|1[49]|48|79|8[147])|6(?:04|[18]3|39|47|72)|7(?:0[59]|42|53|78|8[02])|8(?:[06]7|19|25|7[39])|9(?:0[25]|42))[2-9]\\d{6}",[10]],["",[10]],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",[10]],["900[2-9]\\d{6}",[10]],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|(?:5(?:2[125-9]|3[23]|44|66|77|88)|6(?:22|33))[2-9]\\d{6}",[10]],0,["310\\d{4}",[7]],0,["600[2-9]\\d{6}",[10]]]],CC:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:02|31|60|89)|1(?:18|76)|223)|91(?:0(?:1[0-2]|29)|1(?:[28]2|50|79)|2(?:10|64)|3(?:[06]8|22)|4[29]8|62\\d|70[23]|959))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CD:["243","00","(?:(?:[189]|5\\d)\\d|2)\\d{7}|[1-68]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["[1-6]"],"0$1"],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["5"],"0$1"]],"0"],CF:["236","00","8776\\d{4}|(?:[27]\\d|61)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[26-8]"]]]],CG:["242","00","222\\d{6}|(?:0\\d|80)\\d{7}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[02]"]]]],CH:["41","00","8\\d{11}|[2-9]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8[047]|90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]|81"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["8"],"0$1"]],"0"],CI:["225","00","[02]\\d{9}",[10],[["(\\d{2})(\\d{2})(\\d)(\\d{5})","$1 $2 $3 $4",["2"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3 $4",["0"]]]],CK:["682","00","[2-578]\\d{4}",[5],[["(\\d{2})(\\d{3})","$1 $2",["[2-578]"]]]],CL:["56","(?:0|1(?:1[0-69]|2[02-5]|5[13-58]|69|7[0167]|8[018]))0","12300\\d{6}|6\\d{9,10}|[2-9]\\d{8}",[9,10,11],[["(\\d{5})(\\d{4})","$1 $2",["219","2196"],"($1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["60|809"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["44"]],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2[1-36]"],"($1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["9(?:10|[2-9])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["3[2-5]|[47]|5[1-3578]|6[13-57]|8(?:0[1-8]|[1-9])"],"($1)"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["60|8"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{3})(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3 $4",["60"]]]],CM:["237","00","[26]\\d{8}|88\\d{6,7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["88"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[26]|88"]]]],CN:["86","00|1(?:[12]\\d|79)\\d\\d00","(?:(?:1[03-689]|2\\d)\\d\\d|6)\\d{8}|1\\d{10}|[126]\\d{6}(?:\\d(?:\\d{2})?)?|86\\d{5,6}|(?:[3-579]\\d|8[0-57-9])\\d{5,9}",[7,8,9,10,11,12],[["(\\d{2})(\\d{5,6})","$1 $2",["(?:10|2[0-57-9])[19]|3(?:[157]|35|49|9[1-68])|4(?:1[124-9]|2[179]|6[47-9]|7|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:07|1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3|4[13]|5[1-5]|7[0-79]|9[0-35-9])|(?:4[35]|59|85)[1-9]","(?:10|2[0-57-9])(?:1[02]|9[56])|8078|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))1","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|80781|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))12","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|807812|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123"],"0$1"],["(\\d{3})(\\d{5,6})","$1 $2",["3(?:[157]|35|49|9[1-68])|4(?:[17]|2[179]|6[47-9]|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]|4[13]|5[1-5])|(?:4[35]|59|85)[1-9]","(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))[19]","85[23](?:10|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:10|9[56])","85[23](?:100|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:100|9[56])"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["(?:4|80)0"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|2(?:[02-57-9]|1[1-9])","10|2(?:[02-57-9]|1[1-9])","10[0-79]|2(?:[02-57-9]|1[1-79])|(?:10|21)8(?:0[1-9]|[1-9])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["3(?:[3-59]|7[02-68])|4(?:[26-8]|3[3-9]|5[2-9])|5(?:3[03-9]|[468]|7[028]|9[2-46-9])|6|7(?:[0-247]|3[04-9]|5[0-4689]|6[2368])|8(?:[1-358]|9[1-7])|9(?:[013479]|5[1-5])|(?:[34]1|55|79|87)[02-9]"],"0$1",1],["(\\d{3})(\\d{7,8})","$1 $2",["9"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["80"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[3-578]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["1[3-9]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3 $4",["[12]"],"0$1",1]],"0",0,"(1(?:[12]\\d|79)\\d\\d)|0",0,0,0,0,"00"],CO:["57","00(?:4(?:[14]4|56)|[579])","(?:46|60\\d\\d)\\d{6}|(?:1\\d|[39])\\d{9}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["46"]],["(\\d{3})(\\d{7})","$1 $2",["6|90"],"($1)"],["(\\d{3})(\\d{7})","$1 $2",["3[0-357]|9[14]"]],["(\\d)(\\d{3})(\\d{7})","$1-$2-$3",["1"],"0$1",0,"$1 $2 $3"]],"0",0,"0([3579]|4(?:[14]4|56))?"],CR:["506","00","(?:8\\d|90)\\d{8}|(?:[24-8]\\d{3}|3005)\\d{4}",[8,10],[["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[3-9]"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[89]"]]],0,0,"(19(?:0[0-2468]|1[09]|20|66|77|99))"],CU:["53","119","(?:[2-7]|8\\d\\d)\\d{7}|[2-47]\\d{6}|[34]\\d{5}",[6,7,8,10],[["(\\d{2})(\\d{4,6})","$1 $2",["2[1-4]|[34]"],"(0$1)"],["(\\d)(\\d{6,7})","$1 $2",["7"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["[56]"],"0$1"],["(\\d{3})(\\d{7})","$1 $2",["8"],"0$1"]],"0"],CV:["238","0","(?:[2-59]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2-589]"]]]],CW:["599","00","(?:[34]1|60|(?:7|9\\d)\\d)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[3467]"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["9[4-8]"]]],0,0,0,0,0,"[69]"],CX:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:01|30|59|88)|1(?:17|46|75)|2(?:22|35))|91(?:00[6-9]|1(?:[28]1|49|78)|2(?:09|63)|3(?:12|26|75)|4(?:56|97)|64\\d|7(?:0[01]|1[0-2])|958))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CY:["357","00","(?:[279]\\d|[58]0)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[257-9]"]]]],CZ:["420","00","(?:[2-578]\\d|60)\\d{7}|9\\d{8,11}",[9,10,11,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]|9[015-7]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3 $4",["96"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]]],DE:["49","00","[2579]\\d{5,14}|49(?:[34]0|69|8\\d)\\d\\d?|49(?:37|49|60|7[089]|9\\d)\\d{1,3}|49(?:2[024-9]|3[2-689]|7[1-7])\\d{1,8}|(?:1|[368]\\d|4[0-8])\\d{3,13}|49(?:[015]\\d|2[13]|31|[46][1-8])\\d{1,9}",[4,5,6,7,8,9,10,11,12,13,14,15],[["(\\d{2})(\\d{3,13})","$1 $2",["3[02]|40|[68]9"],"0$1"],["(\\d{3})(\\d{3,12})","$1 $2",["2(?:0[1-389]|1[124]|2[18]|3[14])|3(?:[35-9][15]|4[015])|906|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1","2(?:0[1-389]|12[0-8])|3(?:[35-9][15]|4[015])|906|2(?:[13][14]|2[18])|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1"],"0$1"],["(\\d{4})(\\d{2,11})","$1 $2",["[24-6]|3(?:[3569][02-46-9]|4[2-4679]|7[2-467]|8[2-46-8])|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]","[24-6]|3(?:3(?:0[1-467]|2[127-9]|3[124578]|7[1257-9]|8[1256]|9[145])|4(?:2[135]|4[13578]|9[1346])|5(?:0[14]|2[1-3589]|6[1-4]|7[13468]|8[13568])|6(?:2[1-489]|3[124-6]|6[13]|7[12579]|8[1-356]|9[135])|7(?:2[1-7]|4[145]|6[1-5]|7[1-4])|8(?:21|3[1468]|6|7[1467]|8[136])|9(?:0[12479]|2[1358]|4[134679]|6[1-9]|7[136]|8[147]|9[1468]))|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]|3[68]4[1347]|3(?:47|60)[1356]|3(?:3[46]|46|5[49])[1246]|3[4579]3[1357]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["138"],"0$1"],["(\\d{5})(\\d{2,10})","$1 $2",["3"],"0$1"],["(\\d{3})(\\d{5,11})","$1 $2",["181"],"0$1"],["(\\d{3})(\\d)(\\d{4,10})","$1 $2 $3",["1(?:3|80)|9"],"0$1"],["(\\d{3})(\\d{7,8})","$1 $2",["1[67]"],"0$1"],["(\\d{3})(\\d{7,12})","$1 $2",["8"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["185","1850","18500"],"0$1"],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["18[68]"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["15[1279]"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["15[03568]","15(?:[0568]|3[13])"],"0$1"],["(\\d{3})(\\d{8})","$1 $2",["18"],"0$1"],["(\\d{3})(\\d{2})(\\d{7,8})","$1 $2 $3",["1(?:6[023]|7)"],"0$1"],["(\\d{4})(\\d{2})(\\d{7})","$1 $2 $3",["15[279]"],"0$1"],["(\\d{3})(\\d{2})(\\d{8})","$1 $2 $3",["15"],"0$1"]],"0"],DJ:["253","00","(?:2\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[27]"]]]],DK:["45","00","[2-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-9]"]]]],DM:["1","011","(?:[58]\\d\\d|767|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","767$1",0,"767"],DO:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,0,0,0,"8001|8[024]9"],DZ:["213","00","(?:[1-4]|[5-79]\\d|80)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["9"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-8]"],"0$1"]],"0"],EC:["593","00","1\\d{9,10}|(?:[2-7]|9\\d)\\d{7}",[8,9,10,11],[["(\\d)(\\d{3})(\\d{4})","$1 $2-$3",["[2-7]"],"(0$1)",0,"$1-$2-$3"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{3})(\\d{3,4})","$1 $2 $3",["1"]]],"0"],EE:["372","00","8\\d{9}|[4578]\\d{7}|(?:[3-8]\\d|90)\\d{5}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[369]|4[3-8]|5(?:[0-2]|5[0-478]|6[45])|7[1-9]|88","[369]|4[3-8]|5(?:[02]|1(?:[0-8]|95)|5[0-478]|6(?:4[0-4]|5[1-589]))|7[1-9]|88"]],["(\\d{4})(\\d{3,4})","$1 $2",["[45]|8(?:00|[1-49])","[45]|8(?:00[1-9]|[1-49])"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],EG:["20","00","[189]\\d{8,9}|[24-6]\\d{8}|[135]\\d{7}",[8,9,10],[["(\\d)(\\d{7,8})","$1 $2",["[23]"],"0$1"],["(\\d{2})(\\d{6,7})","$1 $2",["1[35]|[4-6]|8[2468]|9[235-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{8})","$1 $2",["1"],"0$1"]],"0"],EH:["212","00","[5-8]\\d{8}",[9],0,"0",0,0,0,0,0,[["528[89]\\d{5}"],["(?:6(?:[0-79]\\d|8[0-247-9])|7(?:[016-8]\\d|2[0-8]|5[0-5]))\\d{6}"],["80[0-7]\\d{6}"],["89\\d{7}"],0,0,0,0,["(?:592(?:4[0-2]|93)|80[89]\\d\\d)\\d{4}"]]],ER:["291","00","[178]\\d{6}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[178]"],"0$1"]],"0"],ES:["34","00","[5-9]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]00"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-9]"]]]],ET:["251","00","(?:11|[2-579]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-579]"],"0$1"]],"0"],FI:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","[1-35689]\\d{4}|7\\d{10,11}|(?:[124-7]\\d|3[0-46-9])\\d{8}|[1-9]\\d{5,8}",[5,6,7,8,9,10,11,12],[["(\\d{5})","$1",["20[2-59]"],"0$1"],["(\\d{3})(\\d{3,7})","$1 $2",["(?:[1-3]0|[68])0|70[07-9]"],"0$1"],["(\\d{2})(\\d{4,8})","$1 $2",["[14]|2[09]|50|7[135]"],"0$1"],["(\\d{2})(\\d{6,10})","$1 $2",["7"],"0$1"],["(\\d)(\\d{4,9})","$1 $2",["(?:19|[2568])[1-8]|3(?:0[1-9]|[1-9])|9"],"0$1"]],"0",0,0,0,0,"1[03-79]|[2-9]",0,"00"],FJ:["679","0(?:0|52)","45\\d{5}|(?:0800\\d|[235-9])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1 $2",["[235-9]|45"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]]],0,0,0,0,0,0,0,"00"],FK:["500","00","[2-7]\\d{4}",[5]],FM:["691","00","(?:[39]\\d\\d|820)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[389]"]]]],FO:["298","00","[2-9]\\d{5}",[6],[["(\\d{6})","$1",["[2-9]"]]],0,0,"(10(?:01|[12]0|88))"],FR:["33","00","[1-9]\\d{8}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0 $1"],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[1-79]"],"0$1"]],"0"],GA:["241","00","(?:[067]\\d|11)\\d{6}|[2-7]\\d{6}",[7,8],[["(\\d)(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-7]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["11|[67]"],"0$1"]],0,0,"0(11\\d{6}|60\\d{6}|61\\d{6}|6[256]\\d{6}|7[467]\\d{6})","$1"],GB:["44","00","[1-357-9]\\d{9}|[18]\\d{8}|8\\d{6}",[7,9,10],[["(\\d{3})(\\d{4})","$1 $2",["800","8001","80011","800111","8001111"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["845","8454","84546","845464"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["800"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["1(?:38|5[23]|69|76|94)","1(?:(?:38|69)7|5(?:24|39)|768|946)","1(?:3873|5(?:242|39[4-6])|(?:697|768)[347]|9467)"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["1(?:[2-69][02-9]|[78])"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[25]|7(?:0|6[02-9])","[25]|7(?:0|6(?:[03-9]|2[356]))"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[1389]"],"0$1"]],"0",0,"0|180020",0,0,0,[["(?:1(?:1(?:3(?:[0-58]\\d\\d|73[0-5])|4(?:(?:[0-5]\\d|70)\\d|69[7-9])|(?:(?:5[0-26-9]|[78][0-49])\\d|6(?:[0-4]\\d|5[01]))\\d)|(?:2(?:(?:0[024-9]|2[3-9]|3[3-79]|4[1-689]|[58][02-9]|6[0-47-9]|7[013-9]|9\\d)\\d|1(?:[0-7]\\d|8[0-3]))|(?:3(?:0\\d|1[0-8]|[25][02-9]|3[02-579]|[468][0-46-9]|7[1-35-79]|9[2-578])|4(?:0[03-9]|[137]\\d|[28][02-57-9]|4[02-69]|5[0-8]|[69][0-79])|5(?:0[1-35-9]|[16]\\d|2[024-9]|3[015689]|4[02-9]|5[03-9]|7[0-35-9]|8[0-468]|9[0-57-9])|6(?:0[034689]|1\\d|2[0-35689]|[38][013-9]|4[1-467]|5[0-69]|6[13-9]|7[0-8]|9[0-24578])|7(?:0[0246-9]|2\\d|3[0236-8]|4[03-9]|5[0-46-9]|6[013-9]|7[0-35-9]|8[024-9]|9[02-9])|8(?:0[35-9]|2[1-57-9]|3[02-578]|4[0-578]|5[124-9]|6[2-69]|7\\d|8[02-9]|9[02569])|9(?:0[02-589]|[18]\\d|2[02-689]|3[1-57-9]|4[2-9]|5[0-579]|6[2-47-9]|7[0-24578]|9[2-57]))\\d)\\d)|2(?:0[013478]|3[0189]|4[017]|8[0-46-9]|9[0-2])\\d{3})\\d{4}|1(?:2(?:0(?:46[1-4]|87[2-9])|545[1-79]|76(?:2\\d|3[1-8]|6[1-6])|9(?:7(?:2[0-4]|3[2-5])|8(?:2[2-8]|7[0-47-9]|8[3-5])))|3(?:6(?:38[2-5]|47[23])|8(?:47[04-9]|64[0157-9]))|4(?:044[1-7]|20(?:2[23]|8\\d)|6(?:0(?:30|5[2-57]|6[1-8]|7[2-8])|140)|8(?:052|87[1-3]))|5(?:2(?:4(?:3[2-79]|6\\d)|76\\d)|6(?:26[06-9]|686))|6(?:06(?:4\\d|7[4-79])|295[5-7]|35[34]\\d|47(?:24|61)|59(?:5[08]|6[67]|74)|9(?:55[0-4]|77[23]))|7(?:26(?:6[13-9]|7[0-7])|(?:442|688)\\d|50(?:2[0-3]|[3-68]2|76))|8(?:27[56]\\d|37(?:5[2-5]|8[239])|843[2-58])|9(?:0(?:0(?:6[1-8]|85)|52\\d)|3583|4(?:66[1-8]|9(?:2[01]|81))|63(?:23|3[1-4])|9561))\\d{3}",[9,10]],["7(?:457[0-57-9]|700[01]|911[028])\\d{5}|7(?:[1-3]\\d\\d|4(?:[0-46-9]\\d|5[0-689])|5(?:0[0-8]|[13-9]\\d|2[0-35-9])|7(?:0[1-9]|[1-7]\\d|8[02-9]|9[0-689])|8(?:[014-9]\\d|[23][0-8])|9(?:[024-9]\\d|1[02-9]|3[0-689]))\\d{6}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[2-49]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]],0," x"],GD:["1","011","(?:473|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","473$1",0,"473"],GE:["995","00","(?:[3-57]\\d\\d|800)\\d{6}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["32"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[57]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[348]"],"0$1"]],"0"],GF:["594","00","(?:[56]94\\d|7093)\\d{5}|(?:80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]|9[47]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[89]"],"0$1"]],"0"],GG:["44","00","(?:1481|[357-9]\\d{3})\\d{6}|8\\d{6}(?:\\d{2})?",[7,9,10],0,"0",0,"([25-9]\\d{5})$|0|180020","1481$1",0,0,[["1481[25-9]\\d{5}",[10]],["7(?:(?:781|839)\\d|911[17])\\d{5}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[0-3]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]]],GH:["233","00","(?:[235]\\d{3}|800)\\d{5}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[235]"],"0$1"]],"0"],GI:["350","00","(?:[25]\\d|60)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["2"]]]],GL:["299","00","(?:19|[2-689]\\d|70)\\d{4}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["19|[2-9]"]]]],GM:["220","00","[2-9]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],GN:["224","00","722\\d{6}|(?:3|6\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["3"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[67]"]]]],GP:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0",0,0,0,0,0,[["590(?:0[1-68]|[14][0-24-9]|2[0-68]|3[1-9]|5[3-579]|[68][0-689]|7[08]|9\\d)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],GQ:["240","00","222\\d{6}|(?:3\\d|55|[89]0)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235]"]],["(\\d{3})(\\d{6})","$1 $2",["[89]"]]]],GR:["30","00","5005000\\d{3}|8\\d{9,11}|(?:[269]\\d|70)\\d{8}",[10,11,12],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["21|7"]],["(\\d{4})(\\d{6})","$1 $2",["2(?:2|3[2-57-9]|4[2-469]|5[2-59]|6[2-9]|7[2-69]|8[2-49])|5"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2689]"]],["(\\d{3})(\\d{3,4})(\\d{5})","$1 $2 $3",["8"]]]],GT:["502","00","80\\d{6}|(?:1\\d{3}|[2-7])\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1 $2",["[2-8]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],GU:["1","011","(?:[58]\\d\\d|671|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","671$1",0,"671"],GW:["245","00","[49]\\d{8}|4\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["40"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"]]]],GY:["592","001","(?:[2-8]\\d{3}|9008)\\d{3}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],HK:["852","00(?:30|5[09]|[126-9]?)","8[0-46-9]\\d{6,7}|9\\d{4,7}|(?:[2-7]|9\\d{3})\\d{7}",[5,6,7,8,9,11],[["(\\d{3})(\\d{2,5})","$1 $2",["900","9003"]],["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[1-4]|9(?:0[1-9]|[1-8])"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{3})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]],0,0,0,0,0,0,0,"00"],HN:["504","00","8\\d{10}|[237-9]\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1-$2",["[237-9]"]]]],HR:["385","00","[2-69]\\d{8}|80\\d{5,7}|[1-79]\\d{7}|6\\d{6}",[7,8,9],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["6[01]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{4})(\\d{3})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6|7[245]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-57]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"]],"0"],HT:["509","00","[2-589]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[2-589]"]]]],HU:["36","00","[235-7]\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27][2-9]|3[2-7]|4[24-9]|5[2-79]|6|8[2-57-9]|9[2-69]"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"06 $1"]],"06"],ID:["62","00[89]","00[1-9]\\d{9,14}|(?:[1-36]|8\\d{5})\\d{6}|00\\d{9}|[1-9]\\d{8,10}|[2-9]\\d{7}",[7,8,9,10,11,12,13,14,15,16,17],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["15"]],["(\\d{2})(\\d{5,9})","$1 $2",["2[124]|[36]1"],"(0$1)"],["(\\d{3})(\\d{5,7})","$1 $2",["800"],"0$1"],["(\\d{3})(\\d{5,8})","$1 $2",["[2-79]"],"(0$1)"],["(\\d{3})(\\d{3,4})(\\d{3})","$1-$2-$3",["8[1-35-9]"],"0$1"],["(\\d{3})(\\d{6,8})","$1 $2",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["804"],"0$1"],["(\\d{3})(\\d)(\\d{3})(\\d{3})","$1 $2 $3 $4",["80"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1-$2-$3",["8"],"0$1"]],"0"],IE:["353","00","(?:1\\d|[2569])\\d{6,8}|4\\d{6,9}|7\\d{8}|8\\d{8,9}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["2[24-9]|47|58|6[237-9]|9[35-9]"],"(0$1)"],["(\\d{3})(\\d{5})","$1 $2",["[45]0"],"(0$1)"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["1"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2569]|4[1-69]|7[14]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["81"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[78]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["4"],"(0$1)"],["(\\d{2})(\\d)(\\d{3})(\\d{4})","$1 $2 $3 $4",["8"],"0$1"]],"0"],IL:["972","0(?:0|1[2-9])","1\\d{6}(?:\\d{3,5})?|[57]\\d{8}|[1-489]\\d{7}",[7,8,9,10,11,12],[["(\\d{4})(\\d{3})","$1-$2",["125"]],["(\\d{4})(\\d{2})(\\d{2})","$1-$2-$3",["121"]],["(\\d)(\\d{3})(\\d{4})","$1-$2-$3",["[2-489]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1-$2-$3",["12"]],["(\\d{4})(\\d{6})","$1-$2",["159"]],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3-$4",["1[7-9]"]],["(\\d{3})(\\d{1,2})(\\d{3})(\\d{4})","$1-$2 $3-$4",["15"]]],"0"],IM:["44","00","1624\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([25-8]\\d{5})$|0|180020","1624$1",0,"74576|(?:16|7[56])24"],IN:["91","00","(?:000800|[2-9]\\d\\d)\\d{7}|1\\d{7,12}",[8,9,10,11,12,13],[["(\\d{8})","$1",["5(?:0|2[23]|3[03]|[67]1|88)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|888)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|8888)"],0,1],["(\\d{4})(\\d{4,5})","$1 $2",["180","1800"],0,1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["140"],0,1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["11|2[02]|33|4[04]|79[1-7]|80[2-46]","11|2[02]|33|4[04]|79(?:[1-6]|7[19])|80(?:[2-4]|6[0-589])","11|2[02]|33|4[04]|79(?:[124-6]|3(?:[02-9]|1[0-24-9])|7(?:1|9[1-6]))|80(?:[2-4]|6[0-589])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1(?:2[0-249]|3[0-25]|4[145]|[68]|7[1257])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|5[12]|[78]1)|6(?:12|[2-4]1|5[17]|6[13]|80)|7(?:12|3[134]|4[47]|61|88)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91)|(?:43|59|75)[15]|(?:1[59]|29|67|72)[14]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|674|7(?:(?:2[14]|3[34]|5[15])[2-6]|61[346]|88[0-8])|8(?:70[2-6]|84[235-7]|91[3-7])|(?:1(?:29|60|8[06])|261|552|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))[2-7]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12(?:[2-6]|7[0-8])|74[2-7])|7(?:(?:2[14]|5[15])[2-6]|3171|61[346]|88(?:[2-7]|82))|8(?:70[2-6]|84(?:[2356]|7[19])|91(?:[3-6]|7[19]))|73[134][2-6]|(?:74[47]|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[2-6]|7[19])|(?:1(?:29|60|8[06])|261|552|6(?:[2-4]1|5[17]|6[13]|7(?:1|4[0189])|80)|7(?:12|88[01]))[2-7]"],"0$1",1],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2[2457-9]|3[2-5]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1[013-9]|28|3[129]|4[1-35689]|5[29]|6[02-5]|70)|807","1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2(?:[2457]|84|95)|3(?:[2-4]|55)|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1(?:[013-8]|9[6-9])|28[6-8]|3(?:17|2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4|5[0-367])|70[13-7])|807[19]","1(?:[2-479]|5(?:[0236-9]|5[013-9]))|[2-5]|6(?:2(?:84|95)|355|8(?:28[235-7]|3))|73179|807(?:1|9[1-3])|(?:1552|6(?:(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689])\\d|8(?:[14-6]\\d|2[0-79]))|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]))[2-7]"],"0$1",1],["(\\d{5})(\\d{5})","$1 $2",["16|[6-9]"],"0$1",1],["(\\d{4})(\\d{2,4})(\\d{4})","$1 $2 $3",["18[06]","18[06]0"],0,1],["(\\d{4})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["18"],0,1]],"0"],IO:["246","00","3\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["3"]]]],IQ:["964","00","(?:1|7\\d\\d)\\d{7}|[2-6]\\d{7,8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-6]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"]],"0"],IR:["98","00","[1-9]\\d{9}|(?:[1-8]\\d\\d|9)\\d{3,4}",[4,5,6,7,10],[["(\\d{4,5})","$1",["96"],"0$1"],["(\\d{2})(\\d{4,5})","$1 $2",["(?:1[137]|2[13-68]|3[1458]|4[145]|5[1468]|6[16]|7[1467]|8[13467])[12689]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[1-8]"],"0$1"]],"0"],IS:["354","00|1(?:0(?:01|[12]0)|100)","(?:38\\d|[4-9])\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["[4-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["3"]]],0,0,0,0,0,0,0,"00"],IT:["39","00","0\\d{5,11}|1\\d{8,10}|3(?:[0-8]\\d{7,10}|9\\d{7,8})|(?:43|55|70)\\d{8}|8\\d{5}(?:\\d{2,4})?",[6,7,8,9,10,11,12],[["(\\d{2})(\\d{4,6})","$1 $2",["0[26]"]],["(\\d{3})(\\d{3,6})","$1 $2",["0[13-57-9][0159]|8(?:03|4[17]|9[2-5])","0[13-57-9][0159]|8(?:03|4[17]|9(?:2|3[04]|[45][0-4]))"]],["(\\d{4})(\\d{2,6})","$1 $2",["0(?:[13-579][2-46-8]|8[236-8])"]],["(\\d{4})(\\d{4})","$1 $2",["894"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[26]|5"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["1(?:44|[679])|[378]|43"]],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[13-57-9][0159]|14"]],["(\\d{2})(\\d{4})(\\d{5})","$1 $2 $3",["0[26]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[03]"]]],0,0,0,0,0,0,[["0(?:669[0-79]\\d{1,6}|831\\d{2,8})|0(?:1(?:[0159]\\d|[27][1-5]|31|4[1-4]|6[1356]|8[2-57])|2\\d\\d|3(?:[0159]\\d|2[1-4]|3[12]|[48][1-6]|6[2-59]|7[1-7])|4(?:[0159]\\d|[23][1-9]|4[245]|6[1-5]|7[1-4]|81)|5(?:[0159]\\d|2[1-5]|3[2-6]|4[1-79]|6[4-6]|7[1-578]|8[3-8])|6(?:[0-57-9]\\d|6[0-8])|7(?:[0159]\\d|2[12]|3[1-7]|4[2-46]|6[13569]|7[13-6]|8[1-59])|8(?:[0159]\\d|2[3-578]|3[2356]|[6-8][1-5])|9(?:[0159]\\d|[238][1-5]|4[12]|6[1-8]|7[1-6]))\\d{2,7}"],["3[2-9]\\d{7,8}|(?:31|43)\\d{8}",[9,10]],["80(?:0\\d{3}|3)\\d{3}",[6,9]],["(?:0878\\d{3}|89(?:2\\d|3[04]|4(?:[0-4]|[5-9]\\d\\d)|5[0-4]))\\d\\d|(?:1(?:44|6[346])|89(?:38|5[5-9]|9))\\d{6}",[6,8,9,10]],["1(?:78\\d|99)\\d{6}",[9,10]],["3[2-8]\\d{9,10}",[11,12]],0,0,["55\\d{8}",[10]],["84(?:[08]\\d{3}|[17])\\d{3}",[6,9]]]],JE:["44","00","1534\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([0-24-8]\\d{5})$|0|180020","1534$1",0,0,[["1534[0-24-8]\\d{5}"],["7(?:(?:(?:50|82)9|937)\\d|7(?:00[378]|97\\d))\\d{5}"],["80(?:07(?:35|81)|8901)\\d{4}"],["(?:8(?:4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|90(?:066[59]|1810|71(?:07|55)))\\d{4}"],["701511\\d{4}"],0,["(?:3(?:0(?:07(?:35|81)|8901)|3\\d{4}|4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|55\\d{4})\\d{4}"],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}"],["56\\d{8}"]]],JM:["1","011","(?:[58]\\d\\d|658|900)\\d{7}",[10],0,"1",0,0,0,0,"658|876"],JO:["962","00","(?:(?:[2689]|7\\d)\\d|32|427|53)\\d{6}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2356]|87"],"(0$1)"],["(\\d{3})(\\d{5,6})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["70"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[47]"],"0$1"]],"0"],JP:["81","010","00[1-9]\\d{6,14}|[25-9]\\d{9}|(?:00|[1-9]\\d\\d)\\d{6}",[8,9,10,11,12,13,14,15,16,17],[["(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3",["(?:12|57|99)0"],"0$1"],["(\\d{4})(\\d)(\\d{4})","$1-$2-$3",["1(?:26|3[79]|4[56]|5[4-68]|6[3-5])|499|5(?:76|97)|746|8(?:3[89]|47|51)|9(?:80|9[16])","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:76|97)9|7468|8(?:3(?:8[7-9]|96)|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:769|979[2-69])|7468|8(?:3(?:8[7-9]|96[2457-9])|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["60"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2-$3",["3|4(?:2[09]|7[01])|6[1-9]","3|4(?:2(?:0|9[02-69])|7(?:0[019]|1))|6[1-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["1(?:1|5[45]|77|88|9[69])|2(?:2[1-37]|3[0-269]|4[59]|5|6[24]|7[1-358]|8[1369]|9[0-38])|4(?:[28][1-9]|3[0-57]|[45]|6[248]|7[2-579]|9[29])|5(?:2|3[0459]|4[0-369]|5[29]|8[02389]|9[0-389])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9[2-6])|8(?:2[124589]|3[26-9]|49|51|6|7[0-468]|8[68]|9[019])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9[1-489])","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2(?:[127]|3[014-9])|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9[19])|62|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|8[1-9]|9[29])|5(?:2|3(?:[045]|9[0-8])|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0-2469])|3(?:[29]|60)|49|51|6(?:[0-24]|36|5[0-3589]|7[23]|9[01459])|7[0-468]|8[68])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9(?:[1289]|3[34]|4[0178]))|(?:264|837)[016-9]|2(?:57|93)[015-9]|(?:25[0468]|422|838)[01]|(?:47[59]|59[89]|8(?:6[68]|9))[019]","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2[127]|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9(?:17|99))|6(?:2|4[016-9])|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|9[29])|5(?:2|3(?:[045]|9(?:[0-58]|6[4-9]|7[0-35689]))|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0169])|3(?:[29]|60|7(?:[017-9]|6[6-8]))|49|51|6(?:[0-24]|36[2-57-9]|5(?:[0-389]|5[23])|6(?:[01]|9[178])|7(?:2[2-468]|3[78])|9[0145])|7[0-468]|8[68])|9(?:4[15]|5[138]|7[156]|8[189]|9(?:[1289]|3(?:31|4[357])|4[0178]))|(?:8294|96)[1-3]|2(?:57|93)[015-9]|(?:223|8699)[014-9]|(?:25[0468]|422|838)[01]|(?:48|8292|9[23])[1-9]|(?:47[59]|59[89]|8(?:68|9))[019]"],"0$1"],["(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3",["[14]|[289][2-9]|5[3-9]|7[2-4679]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["800"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[25-9]"],"0$1"]],"0",0,"(000[2569]\\d{4,6})$|(?:(?:003768)0?)|0","$1"],KE:["254","000","(?:[17]\\d\\d|900)\\d{6}|(?:2|80)0\\d{6,7}|[4-6]\\d{6,8}",[7,8,9,10],[["(\\d{2})(\\d{5,7})","$1 $2",["[24-6]"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[17]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0"],KG:["996","00","8\\d{9}|[235-9]\\d{8}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["3(?:1[346]|[24-79])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-79]|88"],"0$1"],["(\\d{3})(\\d{3})(\\d)(\\d{2,3})","$1 $2 $3 $4",["8"],"0$1"]],"0"],KH:["855","00[14-9]","1\\d{9}|[1-9]\\d{7,8}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],KI:["686","00","(?:[37]\\d|6[0-79])\\d{6}|(?:[2-48]\\d|50)\\d{3}",[5,8],0,"0"],KM:["269","00","[3478]\\d{6}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[3478]"]]]],KN:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","869$1",0,"869"],KP:["850","00|99","85\\d{6}|(?:19\\d|[2-7])\\d{7}",[8,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"]],"0"],KR:["82","00(?:[125689]|3(?:[46]5|91)|7(?:00|27|3|55|6[126]))","00[1-9]\\d{8,11}|(?:[12]|5\\d{3})\\d{7}|[13-6]\\d{9}|(?:[1-6]\\d|80)\\d{7}|[3-6]\\d{4,5}|(?:00|7)0\\d{8}",[5,6,8,9,10,11,12,13,14],[["(\\d{2})(\\d{3,4})","$1-$2",["(?:3[1-3]|[46][1-4]|5[1-5])1"],"0$1"],["(\\d{4})(\\d{4})","$1-$2",["1"]],["(\\d)(\\d{3,4})(\\d{4})","$1-$2-$3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[36]0|8"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1-$2-$3",["[1346]|5[1-5]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{2})(\\d{5})(\\d{4})","$1-$2-$3",["5"],"0$1"]],"0",0,"0(8(?:[1-46-8]|5\\d\\d))?"],KW:["965","00","18\\d{5}|(?:[2569]\\d|41)\\d{6}",[7,8],[["(\\d{4})(\\d{3,4})","$1 $2",["[169]|2(?:[235]|4[1-35-9])|52"]],["(\\d{3})(\\d{5})","$1 $2",["[245]"]]]],KY:["1","011","(?:345|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","345$1",0,"345"],KZ:["7","810","8\\d{13}|[78]\\d{9}",[10,14],0,"8",0,0,0,0,"7",0,"8~10"],LA:["856","00","[23]\\d{9}|3\\d{8}|(?:[235-8]\\d|41)\\d{6}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2[13]|3[14]|[4-8]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["3"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[23]"],"0$1"]],"0"],LB:["961","00","[27-9]\\d{7}|[13-9]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[13-69]|7(?:[2-57]|62|8[0-6]|9[04-9])|8[02-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27-9]"]]],"0"],LC:["1","011","(?:[58]\\d\\d|758|900)\\d{7}",[10],0,"1",0,"([2-8]\\d{6})$|1","758$1",0,"758"],LI:["423","00","[68]\\d{8}|(?:[2378]\\d|90)\\d{5}",[7,9],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2379]|8(?:0[09]|7)","[2379]|8(?:0(?:02|9)|7)"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["69"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]],"0",0,"(1001)|0"],LK:["94","00","[1-9]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[1-689]"],"0$1"]],"0"],LR:["231","00","(?:[2457]\\d|33|88)\\d{7}|(?:2\\d|[4-6])\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["4[67]|[56]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-578]"],"0$1"]],"0"],LS:["266","00","(?:[256]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2568]"]]]],LT:["370","00","(?:[3469]\\d|52|[78]0)\\d{6}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["52[0-7]"],"(0-$1)",1],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[7-9]"],"0 $1",1],["(\\d{2})(\\d{6})","$1 $2",["37|4(?:[15]|6[1-8])"],"(0-$1)",1],["(\\d{3})(\\d{5})","$1 $2",["[3-6]"],"(0-$1)",1]],"0",0,"[08]"],LU:["352","00","35[013-9]\\d{4,8}|6\\d{8}|35\\d{2,4}|(?:[2457-9]\\d|3[0-46-9])\\d{2,9}",[4,5,6,7,8,9,10,11],[["(\\d{2})(\\d{3})","$1 $2",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["20[2-689]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4",["20"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,5})","$1 $2 $3 $4",["[3-57]|8[13-9]|9(?:0[89]|[2-579])|(?:2|80)[2-9]"]],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["80[01]|90[015]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["20"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4 $5",["20"]]],0,0,"(15(?:0[06]|1[12]|[35]5|4[04]|6[26]|77|88|99)\\d)"],LV:["371","00","(?:[268]\\d|78|90)\\d{6}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2679]|8[01]"]]]],LY:["218","00","[2-9]\\d{8}",[9],[["(\\d{2})(\\d{7})","$1-$2",["[2-9]"],"0$1"]],"0"],MA:["212","00","[5-8]\\d{8}",[9],[["(\\d{4})(\\d{5})","$1-$2",["892"],"0$1"],["(\\d{2})(\\d{7})","$1-$2",["8(?:0[0-7]|9)"],"0$1"],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[5-8]"],"0$1"]],"0",0,0,0,0,"[5-8]"],MC:["377","00","(?:[3489]|[67]\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["4"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[389]"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[67]"],"0$1"]],"0"],MD:["373","00","(?:[235-7]\\d|[89]0)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["22|3"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[25-7]"],"0$1"]],"0"],ME:["382","00","(?:20|[3-79]\\d)\\d{6}|80\\d{6,7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"0$1"]],"0"],MF:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:0[079]|[14]3|[27][79]|3[03-7]|5[0-268]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],MG:["261","00","[23]\\d{8}",[9],[["(\\d{2})(\\d{2})(\\d{3})(\\d{2})","$1 $2 $3 $4",["[23]"],"0$1"]],"0",0,"([24-9]\\d{6})$|0","20$1"],MH:["692","011","329\\d{4}|(?:[256]\\d|45)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1-$2",["[2-6]"]]],"1"],MK:["389","00","[2-578]\\d{7}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2|34[47]|4(?:[37]7|5[47]|64)"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[347]"],"0$1"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["[58]"],"0$1"]],"0"],ML:["223","00","[24-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24-9]"]]]],MM:["95","00","1\\d{5,7}|95\\d{6}|(?:[4-7]|9[0-46-9])\\d{6,8}|(?:2|8\\d)\\d{5,8}",[6,7,8,9,10],[["(\\d)(\\d{2})(\\d{3})","$1 $2 $3",["16|2"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["4(?:[2-46]|5[3-5])|5|6(?:[1-689]|7[235-7])|7(?:[0-4]|5[2-7])|8[1-5]|(?:60|86)[23]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[12]|452|678|86","[12]|452|6788|86"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[4-7]|8[1-35]"],"0$1"],["(\\d)(\\d{3})(\\d{4,6})","$1 $2 $3",["9(?:2[0-4]|[35-9]|4[137-9])"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["92"],"0$1"],["(\\d)(\\d{5})(\\d{4})","$1 $2 $3",["9"],"0$1"]],"0"],MN:["976","001","[12]\\d{7,9}|[5-9]\\d{7}",[8,9,10],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[12]1"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[5-9]"]],["(\\d{3})(\\d{5,6})","$1 $2",["[12]2[1-3]"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["[12](?:27|3[2-8]|4[2-68]|5[1-4689])","[12](?:27|3[2-8]|4[2-68]|5[1-4689])[0-3]"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["[12]"],"0$1"]],"0"],MO:["853","00","0800\\d{3}|(?:28|[68]\\d)\\d{6}",[7,8],[["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{4})(\\d{4})","$1 $2",["[268]"]]]],MP:["1","011","[58]\\d{9}|(?:67|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","670$1",0,"670"],MQ:["596","00","(?:596\\d|7091)\\d{5}|(?:69|[89]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]|8(?:0[6-9]|[36])"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],MR:["222","00","(?:[2-4]\\d\\d|800)\\d{5}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-48]"]]]],MS:["1","011","(?:[58]\\d\\d|664|900)\\d{7}",[10],0,"1",0,"([34]\\d{6})$|1","664$1",0,"664"],MT:["356","00","3550\\d{4}|(?:[2579]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2357-9]"]]]],MU:["230","0(?:0|[24-7]0|3[03])","(?:[57]|8\\d\\d)\\d{7}|[2-468]\\d{6}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[2-46]|8[013]"]],["(\\d{4})(\\d{4})","$1 $2",["[57]"]],["(\\d{5})(\\d{5})","$1 $2",["8"]]],0,0,0,0,0,0,0,"020"],MV:["960","0(?:0|19)","(?:800|9[0-57-9]\\d)\\d{7}|[34679]\\d{6}",[7,10],[["(\\d{3})(\\d{4})","$1-$2",["[34679]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"]]],0,0,0,0,0,0,0,"00"],MW:["265","00","(?:[1289]\\d|31|77)\\d{7}|1\\d{6}",[7,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["1[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[137-9]"],"0$1"]],"0"],MX:["52","0[09]","[2-9]\\d{9}",[10],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["33|5[56]|81"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2-9]"]]],0,0,0,0,0,0,0,"00"],MY:["60","00","1\\d{8,9}|(?:3\\d|[4-9])\\d{7}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1-$2 $3",["[4-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1-$2 $3",["1(?:[02469]|[378][1-9]|53)|8","1(?:[02469]|[37][1-9]|53|8(?:[1-46-9]|5[7-9]))|8"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2 $3",["3"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3-$4",["1(?:[367]|80)"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2 $3",["15"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2 $3",["1"],"0$1"]],"0"],MZ:["258","00","(?:2|8\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2|8[2-79]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],NA:["264","00","[68]\\d{7,8}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["87"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],NC:["687","00","(?:050|[2-57-9]\\d\\d)\\d{3}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1.$2.$3",["[02-57-9]"]]]],NE:["227","00","[027-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["08"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[089]|2[013]|7[0467]"]]]],NF:["672","00","[13]\\d{5}",[6],[["(\\d{2})(\\d{4})","$1 $2",["1[0-3]"]],["(\\d)(\\d{5})","$1 $2",["[13]"]]],0,0,"([0-258]\\d{4})$","3$1"],NG:["234","009","(?:20|9\\d)\\d{8}|[78]\\d{9,13}",[10,11,12,13,14],[["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[7-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["20[129]"],"0$1"],["(\\d{4})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[78]"],"0$1"],["(\\d{3})(\\d{5})(\\d{5,6})","$1 $2 $3",["[78]"],"0$1"]],"0"],NI:["505","00","(?:1800|[25-8]\\d{3})\\d{4}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[125-8]"]]]],NL:["31","00","(?:[124-7]\\d\\d|3(?:[02-9]\\d|1[0-8]))\\d{6}|8\\d{6,9}|9\\d{6,10}|1\\d{4,5}",[5,6,7,8,9,10,11],[["(\\d{3})(\\d{4,7})","$1 $2",["[89]0"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["66"],"0$1"],["(\\d)(\\d{8})","$1 $2",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["1[16-8]|2[259]|3[124]|4[17-9]|5[124679]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-578]|91"],"0$1"],["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3",["9"],"0$1"]],"0"],NO:["47","00","(?:0|[2-9]\\d{3})\\d{4}",[5,8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]"]]],0,0,0,0,0,"[02-689]|7[0-8]"],NP:["977","00","(?:1\\d|9)\\d{9}|[1-9]\\d{7}",[8,10,11],[["(\\d)(\\d{7})","$1-$2",["1[2-6]"],"0$1"],["(\\d{2})(\\d{6})","$1-$2",["1[01]|[2-8]|9(?:[1-59]|[67][2-6])"],"0$1"],["(\\d{3})(\\d{7})","$1-$2",["9"]]],"0"],NR:["674","00","(?:222|444|(?:55|8\\d)\\d|666|777|999)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[24-9]"]]]],NU:["683","00","(?:[4-7]|888\\d)\\d{3}",[4,7],[["(\\d{3})(\\d{4})","$1 $2",["8"]]]],NZ:["64","0(?:0|161)","[1289]\\d{9}|50\\d{5}(?:\\d{2,3})?|[27-9]\\d{7,8}|(?:[34]\\d|6[0-35-9])\\d{6}|8\\d{4,6}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,8})","$1 $2",["8[1-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["50[036-8]|8|90","50(?:[0367]|88)|8|90"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["24|[346]|7[2-57-9]|9[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:10|74)|[589]"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["1|2[028]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,5})","$1 $2 $3",["2(?:[169]|7[0-35-9])|7"],"0$1"]],"0",0,0,0,0,0,0,"00"],OM:["968","00","(?:1505|[279]\\d{3}|500)\\d{4}|800\\d{5,6}",[7,8,9],[["(\\d{3})(\\d{4,6})","$1 $2",["[58]"]],["(\\d{2})(\\d{6})","$1 $2",["2"]],["(\\d{4})(\\d{4})","$1 $2",["[179]"]]]],PA:["507","00","(?:00800|8\\d{3})\\d{6}|[68]\\d{7}|[1-57-9]\\d{6}",[7,8,10,11],[["(\\d{3})(\\d{4})","$1-$2",["[1-57-9]"]],["(\\d{4})(\\d{4})","$1-$2",["[68]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]]],PE:["51","00|19(?:1[124]|77|90)00","(?:[14-8]|9\\d)\\d{7}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["80"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["1"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[4-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"]]],"0",0,0,0,0,0,0,"00"," Anexo "],PF:["689","00","4\\d{5}(?:\\d{2})?|8\\d{7,8}",[6,8,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["44"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4|8[7-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],PG:["675","00|140[1-3]","(?:180|[78]\\d{3})\\d{4}|(?:[2-589]\\d|64)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["18|[2-69]|85"]],["(\\d{4})(\\d{4})","$1 $2",["[78]"]]],0,0,0,0,0,0,0,"00"],PH:["63","00","(?:[2-7]|9\\d)\\d{8}|2\\d{5}|(?:1800|8)\\d{7,9}",[6,8,9,10,11,12,13],[["(\\d)(\\d{5})","$1 $2",["2"],"(0$1)"],["(\\d{4})(\\d{4,6})","$1 $2",["3(?:23|39|46)|4(?:2[3-6]|[35]9|4[26]|76)|544|88[245]|(?:52|64|86)2","3(?:230|397|461)|4(?:2(?:35|[46]4|51)|396|4(?:22|63)|59[347]|76[15])|5(?:221|446)|642[23]|8(?:622|8(?:[24]2|5[13]))"],"(0$1)"],["(\\d{5})(\\d{4})","$1 $2",["346|4(?:27|9[35])|883","3469|4(?:279|9(?:30|56))|8834"],"(0$1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|8[2-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{4})(\\d{1,2})(\\d{3})(\\d{4})","$1 $2 $3 $4",["1"]]],"0"],PK:["92","00","122\\d{6}|[24-8]\\d{10,11}|9(?:[013-9]\\d{8,10}|2(?:[01]\\d\\d|2(?:[06-8]\\d|1[01]))\\d{7})|(?:[2-8]\\d{3}|92(?:[0-7]\\d|8[1-9]))\\d{6}|[24-9]\\d{8}|[89]\\d{7}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,7})","$1 $2 $3",["[89]0"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["1"]],["(\\d{3})(\\d{6,7})","$1 $2",["2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:2[2-8]|3[27-9]|4[2-6]|6[3569]|9[25-8])","9(?:2[3-8]|98)|(?:2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:22|3[27-9]|4[2-6]|6[3569]|9[25-7]))[2-9]"],"(0$1)"],["(\\d{2})(\\d{7,8})","$1 $2",["(?:2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91)[2-9]"],"(0$1)"],["(\\d{5})(\\d{5})","$1 $2",["58"],"(0$1)"],["(\\d{3})(\\d{7})","$1 $2",["3"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[24-9]"],"(0$1)"]],"0"],PL:["48","00","(?:6|8\\d\\d)\\d{7}|[1-9]\\d{6}(?:\\d{2})?|[26]\\d{5}",[6,7,8,9,10],[["(\\d{5})","$1",["19"]],["(\\d{3})(\\d{3})","$1 $2",["11|20|64"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])1","(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])19"]],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["64"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["21|39|45|5[0137]|6[0469]|7[02389]|8(?:0[14]|8)"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[2-8]|[2-7]|8[1-79]|9[145]"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["8"]]]],PM:["508","00","[45]\\d{5}|(?:708|8\\d\\d)\\d{6}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[45]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],PR:["1","011","(?:[589]\\d\\d|787)\\d{7}",[10],0,"1",0,0,0,0,"787|939"],PS:["970","00","[2489]2\\d{6}|(?:1\\d|5)\\d{8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2489]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["5"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],PT:["351","00","1693\\d{5}|(?:[26-9]\\d|30)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["2[12]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["16|[236-9]"]]]],PW:["680","01[12]","(?:[24-8]\\d\\d|345|900)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],PY:["595","00","[36-8]\\d{5,8}|4\\d{6,8}|59\\d{6}|9\\d{5,10}|(?:2\\d|5[0-8])\\d{6,7}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3,6})","$1 $2",["[2-9]0"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["3[289]|4[246-8]|61|7[1-3]|8[1-36]"],"(0$1)"],["(\\d{3})(\\d{4,5})","$1 $2",["2[279]|3[13-5]|4[359]|5|6(?:[34]|7[1-46-8])|7[46-8]|85"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2[14-68]|3[26-9]|4[1246-8]|6(?:1|75)|7[1-35]|8[1-36]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["87"]],["(\\d{3})(\\d{6})","$1 $2",["9(?:[5-79]|8[1-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["9"]]],"0"],QA:["974","00","800\\d{4}|(?:2|800)\\d{6}|(?:0080|[3-7])\\d{7}",[7,8,9,11],[["(\\d{3})(\\d{4})","$1 $2",["2[136]|8"]],["(\\d{4})(\\d{4})","$1 $2",["[3-7]"]]]],RE:["262","00","709\\d{6}|(?:26|[689]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[26-9]"],"0$1"]],"0",0,0,0,0,0,[["26(?:2\\d\\d|3(?:0\\d|1[0-6]))\\d{4}"],["(?:69(?:2\\d\\d|3(?:[06][0-6]|1[0-3]|2[0-2]|3[0-39]|4\\d|5[0-5]|7[0-37]|8[0-8]|9[0-479]))|7092[0-3])\\d{4}"],["80\\d{7}"],["89[1-37-9]\\d{6}"],0,0,0,0,["9(?:399[0-3]|479[0-6]|76(?:2[278]|3[0-37]))\\d{4}"],["8(?:1[019]|2[0156]|84|90)\\d{6}"]]],RO:["40","00","(?:[236-8]\\d|90)\\d{7}|[23]\\d{5}",[6,9],[["(\\d{3})(\\d{3})","$1 $2",["2[3-6]","2[3-6]\\d9"],"0$1"],["(\\d{2})(\\d{4})","$1 $2",["219|31"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[23]1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[236-9]"],"0$1"]],"0",0,0,0,0,0,0,0," int "],RS:["381","00","38[02-9]\\d{6,9}|6\\d{7,9}|90\\d{4,8}|38\\d{5,6}|(?:7\\d\\d|800)\\d{3,9}|(?:[12]\\d|3[0-79])\\d{5,10}",[6,7,8,9,10,11,12],[["(\\d{3})(\\d{3,9})","$1 $2",["(?:2[389]|39)0|[7-9]"],"0$1"],["(\\d{2})(\\d{5,10})","$1 $2",["[1-36]"],"0$1"]],"0"],RU:["7","810","8\\d{13}|[347-9]\\d{9}",[10,14],[["(\\d{4})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-8]|2[1-9])","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:1[23]|[2-9]2))","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:13[03-69]|62[013-9]))|72[1-57-9]2"],"8 ($1)",1],["(\\d{5})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-68]|2[1-9])","7(?:1(?:[06][3-6]|[18]|2[35]|[3-5][3-5])|2(?:[13][3-5]|[24-689]|7[457]))","7(?:1(?:0(?:[356]|4[023])|[18]|2(?:3[013-9]|5)|3[45]|43[013-79]|5(?:3[1-8]|4[1-7]|5)|6(?:3[0-35-9]|[4-6]))|2(?:1(?:3[178]|[45])|[24-689]|3[35]|7[457]))|7(?:14|23)4[0-8]|71(?:33|45)[1-79]"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[349]|8(?:[02-7]|1[1-8])"],"8 ($1)",1],["(\\d{4})(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3 $4",["8"],"8 ($1)"]],"8",0,0,0,0,"[3489]",0,"8~10"],RW:["250","00","(?:06|[27]\\d\\d|[89]00)\\d{6}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[7-9]"],"0$1"]],"0"],SA:["966","00","(?:[15]\\d|800|92)\\d{7}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["9"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]],"0"],SB:["677","0[01]","[6-9]\\d{6}|[1-6]\\d{4}",[5,7],[["(\\d{2})(\\d{5})","$1 $2",["6[89]|7|8[4-9]|9(?:[1-8]|9[0-8])"]]]],SC:["248","010|0[0-2]","(?:[2489]\\d|64)\\d{5}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[246]|9[57]"]]],0,0,0,0,0,0,0,"00"],SD:["249","00","[19]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[19]"],"0$1"]],"0"],SE:["46","00","(?:[26]\\d\\d|9)\\d{9}|[1-9]\\d{8}|[1-689]\\d{7}|[1-4689]\\d{6}|2\\d{5}",[6,7,8,9,10,12],[["(\\d{2})(\\d{2,3})(\\d{2})","$1-$2 $3",["20"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{4})","$1-$2",["9(?:00|39|44|9)"],"0$1",0,"$1 $2"],["(\\d{2})(\\d{3})(\\d{2})","$1-$2 $3",["[12][136]|3[356]|4[0246]|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3"],["(\\d)(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2,3})(\\d{2})","$1-$2 $3",["1[2457]|2(?:[247-9]|5[0138])|3[0247-9]|4[1357-9]|5[0-35-9]|6(?:[125689]|4[02-57]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{2,3})(\\d{3})","$1-$2 $3",["9(?:00|39|44)"],"0$1",0,"$1 $2 $3"],["(\\d{2})(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["1[13689]|2[0136]|3[1356]|4[0246]|54|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3 $4"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["10|7"],"0$1",0,"$1 $2 $3 $4"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1-$2 $3 $4",["[13-5]|2(?:[247-9]|5[0138])|6(?:[124-689]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{3})","$1-$2 $3 $4",["9"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4 $5",["[26]"],"0$1",0,"$1 $2 $3 $4 $5"]],"0"],SG:["65","0[0-3]\\d","(?:(?:1\\d|8)\\d\\d|7000)\\d{7}|[3689]\\d{7}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["[369]|8(?:0[1-9]|[1-9])"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]],["(\\d{4})(\\d{4})(\\d{3})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],SH:["290","00","(?:[256]\\d|8)\\d{3}",[4,5],0,0,0,0,0,0,"[256]"],SI:["386","00|10(?:22|66|88|99)","[1-7]\\d{7}|8\\d{4,7}|90\\d{4,6}",[5,6,7,8],[["(\\d{2})(\\d{3,6})","$1 $2",["8[09]|9"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["59|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37][01]|4[0139]|51|6"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-57]"],"(0$1)"]],"0",0,0,0,0,0,0,"00"],SJ:["47","00","0\\d{4}|(?:[489]\\d|79)\\d{6}",[5,8],0,0,0,0,0,0,"79"],SK:["421","00","[2-689]\\d{8}|[2-59]\\d{6}|[2-5]\\d{5}",[6,7,9],[["(\\d)(\\d{2})(\\d{3,4})","$1 $2 $3",["21"],"0$1"],["(\\d{2})(\\d{2})(\\d{2,3})","$1 $2 $3",["[3-5][1-8]1","[3-5][1-8]1[67]"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1/$2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[689]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1/$2 $3 $4",["[3-5]"],"0$1"]],"0"],SL:["232","00","(?:[237-9]\\d|66)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[236-9]"],"(0$1)"]],"0"],SM:["378","00","(?:0549|[5-7]\\d)\\d{6}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]"]],["(\\d{4})(\\d{6})","$1 $2",["0"]]],0,0,"([89]\\d{5})$","0549$1"],SN:["221","00","(?:[378]\\d|93)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[379]"]]]],SO:["252","00","[346-9]\\d{8}|[12679]\\d{7}|[1-5]\\d{6}|[1348]\\d{5}",[6,7,8,9],[["(\\d{2})(\\d{4})","$1 $2",["8[125]"]],["(\\d{6})","$1",["[134]"]],["(\\d)(\\d{6})","$1 $2",["[15]|2[0-79]|3[0-46-8]|4[0-7]"]],["(\\d)(\\d{7})","$1 $2",["(?:2|90)4|[67]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[348]|64|79|90"]],["(\\d{2})(\\d{5,7})","$1 $2",["1|28|6[0-35-9]|7[67]|9[2-9]"]]],"0"],SR:["597","00","(?:[2-5]|[6-8]\\d|90)\\d{5}",[6,7],[["(\\d{2})(\\d{2})(\\d{2})","$1-$2-$3",["56"]],["(\\d{3})(\\d{3})","$1-$2",["[2-5]"]],["(\\d{3})(\\d{4})","$1-$2",["[6-9]"]]]],SS:["211","00","[19]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[19]"],"0$1"]],"0"],ST:["239","00","(?:22|9\\d)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[29]"]]]],SV:["503","00","[25-7]\\d{7}|(?:80\\d|900)\\d{4}(?:\\d{4})?",[7,8,11],[["(\\d{3})(\\d{4})","$1 $2",["[89]"]],["(\\d{4})(\\d{4})","$1 $2",["[25-7]"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[89]"]]]],SX:["1","011","7215\\d{6}|(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"(5\\d{6})$|1","721$1",0,"721"],SY:["963","00","[1-359]\\d{8}|[1-5]\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-4]|5[1-3]"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[59]"],"0$1",1]],"0"],SZ:["268","00","0800\\d{4}|(?:[237]\\d|900)\\d{6}",[8,9],[["(\\d{4})(\\d{4})","$1 $2",["[0237]"]],["(\\d{5})(\\d{4})","$1 $2",["9"]]]],TA:["290","00","8\\d{3}",[4],0,0,0,0,0,0,"8"],TC:["1","011","(?:[58]\\d\\d|649|900)\\d{7}",[10],0,"1",0,"([2-479]\\d{6})$|1","649$1",0,"649"],TD:["235","00|16","(?:22|30|[689]\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[236-9]"]]],0,0,0,0,0,0,0,"00"],TG:["228","00","[279]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[279]"]]]],TH:["66","00[1-9]","(?:001800|[2-57]|[689]\\d)\\d{7}|1\\d{7,9}",[8,9,10,13],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[13-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],TJ:["992","810","(?:[0-57-9]\\d|66)\\d{7}",[9],[["(\\d{6})(\\d)(\\d{2})","$1 $2 $3",["331","3317"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["44[02-479]|[34]7"]],["(\\d{4})(\\d)(\\d{4})","$1 $2 $3",["3(?:[1245]|3[12])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["\\d"]]],0,0,0,0,0,0,0,"8~10"],TK:["690","00","[2-47]\\d{3,6}",[4,5,6,7]],TL:["670","00","7\\d{7}|(?:[2-47]\\d|[89]0)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[2-489]|70"]],["(\\d{4})(\\d{4})","$1 $2",["7"]]]],TM:["993","810","(?:[1-6]\\d|71)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["12"],"(8 $1)"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-5]"],"(8 $1)"],["(\\d{2})(\\d{6})","$1 $2",["[67]"],"8 $1"]],"8",0,0,0,0,0,0,"8~10"],TN:["216","00","[2-57-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-57-9]"]]]],TO:["676","00","(?:0800|(?:[5-8]\\d\\d|999)\\d)\\d{3}|[2-8]\\d{4}",[5,7],[["(\\d{2})(\\d{3})","$1-$2",["[2-4]|50|6[09]|7[0-24-69]|8[05]"]],["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[5-9]"]]]],TR:["90","00","4\\d{6}|8\\d{11,12}|(?:[2-58]\\d\\d|900)\\d{7}",[7,10,12,13],[["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["512|8[01589]|90"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["5(?:[0-579]|61)","5(?:[0-579]|61[06])","5(?:[0-579]|61[06]1)"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24][1-8]|3[1-9]"],"(0$1)",1],["(\\d{3})(\\d{3})(\\d{6,7})","$1 $2 $3",["80"],"0$1",1]],"0"],TT:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-46-8]\\d{6})$|1","868$1",0,"868"],TV:["688","00","(?:2|7\\d\\d|90)\\d{4}",[5,6,7],[["(\\d{2})(\\d{3})","$1 $2",["2"]],["(\\d{2})(\\d{4})","$1 $2",["90"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],TW:["886","0(?:0[25-79]|19)","[2-689]\\d{8}|7\\d{9,10}|[2-8]\\d{7}|2\\d{6}",[7,8,9,10,11],[["(\\d{2})(\\d)(\\d{4})","$1 $2 $3",["202"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[258]0"],"0$1"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["[23568]|4(?:0[02-48]|[1-47-9])|7[1-9]","[23568]|4(?:0[2-48]|[1-47-9])|(?:400|7)[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,5})","$1 $2 $3",["7"],"0$1"]],"0",0,0,0,0,0,0,0,"#"],TZ:["255","00[056]","(?:[25-8]\\d|41|90)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[24]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["5"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[67]"],"0$1"]],"0"],UA:["380","00","[89]\\d{9}|[3-9]\\d{8}",[9,10],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6[12][29]|(?:3[1-8]|4[136-8]|5[12457]|6[49])2|(?:56|65)[24]","6[12][29]|(?:35|4[1378]|5[12457]|6[49])2|(?:56|65)[24]|(?:3[1-46-8]|46)2[013-9]"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6[0135689]|7[4-6])|6(?:[12][3-7]|[459])","3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6(?:[015689]|3[02389])|7[4-6])|6(?:[12][3-7]|[459])"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|89|9[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0",0,0,0,0,0,0,"0~0"],UG:["256","00[057]","800\\d{6}|(?:[29]0|[347]\\d)\\d{7}",[9],[["(\\d{4})(\\d{5})","$1 $2",["202","2024"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[27-9]|4(?:6[45]|[7-9])"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[34]"],"0$1"]],"0"],US:["1","011","[2-9]\\d{9}|3\\d{6}",[10],[["(\\d{3})(\\d{4})","$1-$2",["310"],0,1],["(\\d{3})(\\d{3})(\\d{4})","($1) $2-$3",["[2-9]"],0,1,"$1-$2-$3"]],"1",0,0,0,0,0,[["(?:274[27]|(?:472|983)[2-47-9])\\d{6}|(?:2(?:0[1-35-9]|1[02-9]|2[03-57-9]|3[1459]|4[08]|5[1-46]|6[0279]|7[0269]|8[13])|3(?:0[1-57-9]|1[02-9]|2[013-79]|3[0-24679]|4[167]|5[0-3]|6[01349]|8[056])|4(?:0[124-9]|1[02-579]|2[3-5]|3[0245]|4[023578]|58|6[349]|7[0589]|8[04])|5(?:0[1-57-9]|1[0235-8]|20|3[0149]|4[01]|5[179]|6[1-47]|7[0-5]|8[0256])|6(?:0[1-35-9]|1[024-9]|2[03689]|3[016]|4[0156]|5[01679]|6[0-279]|78|8[0-269])|7(?:0[1-46-8]|1[2-9]|2[04-8]|3[0-247]|4[0378]|5[47]|6[02359]|7[0-59]|8[156])|8(?:0[1-68]|1[02-8]|2[0168]|3[0-2589]|4[03578]|5[046-9]|6[02-5]|7[028])|9(?:0[1346-9]|1[02-9]|2[0589]|3[0146-8]|4[01357-9]|5[12469]|7[0-3589]|8[04-69]))[2-9]\\d{6}"],[""],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}"],["900[2-9]\\d{6}"],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|3[23]|44|66|77|88)[2-9]\\d{6}"]]],UY:["598","0(?:0|1[3-9]\\d)","0004\\d{2,9}|[1249]\\d{7}|2\\d{3,4}|(?:[49]\\d|80)\\d{5}",[4,5,6,7,8,9,10,11,12,13],[["(\\d{4,5})","$1",["21"]],["(\\d{3})(\\d{3,4})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[49]0|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[124]"]],["(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3 $4",["0"]]],"0",0,0,0,0,0,0,"00"," int. "],UZ:["998","00","(?:20|33|[5-9]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[235-9]"]]]],VA:["39","00","0\\d{5,10}|3[0-8]\\d{7,10}|55\\d{8}|8\\d{5}(?:\\d{2,4})?|(?:1\\d|39)\\d{7,8}",[6,7,8,9,10,11,12],0,0,0,0,0,0,"06698"],VC:["1","011","(?:[58]\\d\\d|784|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","784$1",0,"784"],VE:["58","00","[68]00\\d{7}|(?:[24]\\d|[59]0)\\d{8}",[10],[["(\\d{3})(\\d{7})","$1-$2",["[24-689]"],"0$1"]],"0"],VG:["1","011","(?:284|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-578]\\d{6})$|1","284$1",0,"284"],VI:["1","011","[58]\\d{9}|(?:34|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","340$1",0,"340"],VN:["84","00","[12]\\d{9}|[135-9]\\d{8}|[16]\\d{7}|[16-8]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["80"],"0$1",1],["(\\d{4})(\\d{4,6})","$1 $2",["1"],0,1],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["6"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[357-9]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["2[48]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["2"],"0$1",1]],"0"],VU:["678","00","[57-9]\\d{6}|(?:[238]\\d|48)\\d{3}",[5,7],[["(\\d{3})(\\d{4})","$1 $2",["[57-9]"]]]],WF:["681","00","(?:40|72|8\\d{4})\\d{4}|[89]\\d{5}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[47-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],WS:["685","0","(?:[2-6]|8\\d{5})\\d{4}|[78]\\d{6}|[68]\\d{5}",[5,6,7,10],[["(\\d{5})","$1",["[2-5]|6[1-9]"]],["(\\d{3})(\\d{3,7})","$1 $2",["[68]"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],XK:["383","00","2\\d{7,8}|3\\d{7,11}|(?:4\\d\\d|[89]00)\\d{5}",[8,9,10,11,12],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2|39"],"0$1"],["(\\d{2})(\\d{7,10})","$1 $2",["3"],"0$1"]],"0"],YE:["967","00","(?:1|7\\d)\\d{7}|[1-7]\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-6]|7(?:[24-6]|8[0-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"],"0$1"]],"0"],YT:["262","00","7093\\d{5}|(?:80|9\\d)\\d{7}|(?:26|63)9\\d{6}",[9],0,"0",0,0,0,0,0,[["269(?:0[0-467]|15|5[0-4]|6\\d|[78]0)\\d{4}"],["(?:639(?:0[0-79]|1[019]|[267]\\d|3[09]|40|5[05-9]|9[04-79])|7093[5-7])\\d{4}"],["80\\d{7}"],0,0,0,0,0,["9(?:(?:39|47)8[01]|769\\d)\\d{4}"]]],ZA:["27","00","[1-79]\\d{8}|8\\d{4,9}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,4})","$1 $2",["8[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["8[1-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["860"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],ZM:["260","00","800\\d{6}|(?:21|[579]\\d|63)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[28]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[579]"],"0$1"]],"0"],ZW:["263","00","2(?:[0-57-9]\\d{6,8}|6[0-24-9]\\d{6,7})|[38]\\d{9}|[35-8]\\d{8}|[3-6]\\d{7}|[1-689]\\d{6}|[1-3569]\\d{5}|[1356]\\d{4}",[5,6,7,8,9,10],[["(\\d{3})(\\d{3,5})","$1 $2",["2(?:0[45]|2[278]|[49]8)|3(?:[09]8|17)|6(?:[29]8|37|75)|[23][78]|(?:33|5[15]|6[68])[78]"],"0$1"],["(\\d)(\\d{3})(\\d{2,4})","$1 $2 $3",["[49]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["80"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["24|8[13-59]|(?:2[05-79]|39|5[45]|6[15-8])2","2(?:02[014]|4|[56]20|[79]2)|392|5(?:42|525)|6(?:[16-8]21|52[013])|8[13-59]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:1[39]|2[0157]|[378]|[56][14])|3(?:12|29)","2(?:1[39]|2[0157]|[378]|[56][14])|3(?:123|29)"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["1|2(?:0[0-36-9]|12|29|[56])|3(?:1[0-689]|[24-6])|5(?:[0236-9]|1[2-4])|6(?:[013-59]|7[0-46-9])|(?:33|55|6[68])[0-69]|(?:29|3[09]|62)[0-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["29[013-9]|39|54"],"0$1"],["(\\d{4})(\\d{3,5})","$1 $2",["(?:25|54)8","258|5483"],"0$1"]],"0"]},nonGeographic:{800:["800",0,"(?:00|[1-9]\\d)\\d{6}",[8],[["(\\d{4})(\\d{4})","$1 $2",["\\d"]]],0,0,0,0,0,0,[0,0,["(?:00|[1-9]\\d)\\d{6}"]]],808:["808",0,"[1-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[1-9]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,0,["[1-9]\\d{7}"]]],870:["870",0,"7\\d{11}|[235-7]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-7]"]]],0,0,0,0,0,0,[0,["(?:[356]|774[45])\\d{8}|7[6-8]\\d{7}"],0,0,0,0,0,0,["2\\d{8}",[9]]]],878:["878",0,"10\\d{10}",[12],[["(\\d{2})(\\d{5})(\\d{5})","$1 $2 $3",["1"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["10\\d{10}"]]],881:["881",0,"6\\d{9}|[0-36-9]\\d{8}",[9,10],[["(\\d)(\\d{3})(\\d{5})","$1 $2 $3",["[0-37-9]"]],["(\\d)(\\d{3})(\\d{5,6})","$1 $2 $3",["6"]]],0,0,0,0,0,0,[0,["6\\d{9}|[0-36-9]\\d{8}"]]],882:["882",0,"[13]\\d{6}(?:\\d{2,5})?|[19]\\d{7}|(?:[25]\\d\\d|4)\\d{7}(?:\\d{2})?",[7,8,9,10,11,12],[["(\\d{2})(\\d{5})","$1 $2",["16|342"]],["(\\d{2})(\\d{6})","$1 $2",["49"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["1[36]|9"]],["(\\d{2})(\\d{4})(\\d{3})","$1 $2 $3",["3[23]"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["16"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|23|3(?:[15]|4[57])|4|5[12]"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["34"]],["(\\d{2})(\\d{4,5})(\\d{5})","$1 $2 $3",["[1-35]"]]],0,0,0,0,0,0,[0,["342\\d{4}|(?:337|49)\\d{6}|(?:3(?:2|47|7\\d{3})|5(?:0\\d{3}|2[0-2]))\\d{7}",[7,8,9,10,12]],0,0,0,["348[57]\\d{7}",[11]],0,0,["1(?:3(?:0[0347]|[13][0139]|2[035]|4[013568]|6[0459]|7[06]|8[15-8]|9[0689])\\d{4}|6\\d{5,10})|(?:345\\d|9[89])\\d{6}|(?:10|2(?:3|85\\d)|3(?:[15]|[69]\\d\\d)|4[15-8]|51)\\d{8}"]]],883:["883",0,"(?:[1-4]\\d|51)\\d{6,10}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,8})","$1 $2 $3",["[14]|2[24-689]|3[02-689]|51[24-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["510"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["21"]],["(\\d{4})(\\d{4})(\\d{4})","$1 $2 $3",["51[13]"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[235]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["(?:2(?:00\\d\\d|10)|(?:370[1-9]|51\\d0)\\d)\\d{7}|51(?:00\\d{5}|[24-9]0\\d{4,7})|(?:1[0-79]|2[24-689]|3[02-689]|4[0-4])0\\d{5,9}"]]],888:["888",0,"\\d{11}",[11],[["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3"]],0,0,0,0,0,0,[0,0,0,0,0,0,["\\d{11}"]]],979:["979",0,"[1359]\\d{8}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[1359]"]]],0,0,0,0,0,0,[0,0,0,["[1359]\\d{8}"]]]}};function SN(e,t){var n=Array.prototype.slice.call(t);return n.push($N),e.apply(this,n)}function eb(e,t){e=e.split("-"),t=t.split("-");for(var n=e[0].split("."),r=t[0].split("."),i=0;i<3;i++){var s=Number(n[i]),a=Number(r[i]);if(s>a)return 1;if(a>s)return-1;if(!isNaN(s)&&isNaN(a))return 1;if(isNaN(s)&&!isNaN(a))return-1}return e[1]&&t[1]?e[1]>t[1]?1:e[1]<t[1]?-1:0:!e[1]&&t[1]?1:e[1]&&!t[1]?-1:0}var xN={}.constructor;function _o(e){return e!=null&&e.constructor===xN}function To(e){"@babel/helpers - typeof";return To=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},To(e)}function Sd(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function zN(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,AN(r.key),r)}}function xd(e,t,n){return t&&zN(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function AN(e){var t=EN(e,"string");return To(t)=="symbol"?t:t+""}function EN(e,t){if(To(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(To(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var CN="1.2.0",IN="1.7.35",tb=" ext. ",jN=/^\d+$/,vt=(function(){function e(t){Sd(this,e),Lk(t),this.metadata=t,Dk.call(this,t)}return xd(e,[{key:"getCountries",value:function(){return Object.keys(this.metadata.countries).filter(function(n){return n!=="001"})}},{key:"getCountryMetadata",value:function(n){return this.metadata.countries[n]}},{key:"nonGeographic",value:function(){if(!(this.v1||this.v2||this.v3))return this.metadata.nonGeographic||this.metadata.nonGeographical}},{key:"hasCountry",value:function(n){return this.getCountryMetadata(n)!==void 0}},{key:"hasCallingCode",value:function(n){if(this.getCountryCodesForCallingCode(n))return!0;if(this.nonGeographic()){if(this.nonGeographic()[n])return!0}else{var r=this.countryCallingCodes()[n];if(r&&r.length===1&&r[0]==="001")return!0}}},{key:"isNonGeographicCallingCode",value:function(n){return this.nonGeographic()?!!this.nonGeographic()[n]:!this.getCountryCodesForCallingCode(n)}},{key:"country",value:function(n){return this.selectNumberingPlan(n)}},{key:"selectNumberingPlan",value:function(n,r){if(n&&jN.test(n)&&(r=n,n=null),n&&n!=="001"){if(!this.hasCountry(n))throw new Error("Unknown country: ".concat(n));this.numberingPlan=new nb(this.getCountryMetadata(n),this)}else if(r){if(!this.hasCallingCode(r))throw new Error("Unknown calling code: ".concat(r));this.numberingPlan=new nb(this.getNumberingPlanMetadata(r),this)}else this.numberingPlan=void 0;return this}},{key:"getCountryCodesForCallingCode",value:function(n){var r=this.countryCallingCodes()[n];if(r)return r.length===1&&r[0].length===3?void 0:r}},{key:"getCountryCodeForCallingCode",value:function(n){var r=this.getCountryCodesForCallingCode(n);if(r)return r[0]}},{key:"getNumberingPlanMetadata",value:function(n){var r=this.getCountryCodeForCallingCode(n);if(r)return this.getCountryMetadata(r);if(this.nonGeographic()){var i=this.nonGeographic()[n];if(i)return i}else{var s=this.countryCallingCodes()[n];if(s&&s.length===1&&s[0]==="001")return this.metadata.countries["001"]}}},{key:"countryCallingCode",value:function(){return this.numberingPlan.callingCode()}},{key:"IDDPrefix",value:function(){return this.numberingPlan.IDDPrefix()}},{key:"defaultIDDPrefix",value:function(){return this.numberingPlan.defaultIDDPrefix()}},{key:"nationalNumberPattern",value:function(){return this.numberingPlan.nationalNumberPattern()}},{key:"possibleLengths",value:function(){return this.numberingPlan.possibleLengths()}},{key:"formats",value:function(){return this.numberingPlan.formats()}},{key:"nationalPrefixForParsing",value:function(){return this.numberingPlan.nationalPrefixForParsing()}},{key:"nationalPrefixTransformRule",value:function(){return this.numberingPlan.nationalPrefixTransformRule()}},{key:"leadingDigits",value:function(){return this.numberingPlan.leadingDigits()}},{key:"hasTypes",value:function(){return this.numberingPlan.hasTypes()}},{key:"type",value:function(n){return this.numberingPlan.type(n)}},{key:"ext",value:function(){return this.numberingPlan.ext()}},{key:"countryCallingCodes",value:function(){return this.v1?this.metadata.country_phone_code_to_countries:this.metadata.country_calling_codes}},{key:"chooseCountryByCountryCallingCode",value:function(n){return this.selectNumberingPlan(n)}},{key:"hasSelectedNumberingPlan",value:function(){return this.numberingPlan!==void 0}}])})(),nb=(function(){function e(t,n){Sd(this,e),this.globalMetadataObject=n,this.metadata=t,Dk.call(this,n.metadata)}return xd(e,[{key:"callingCode",value:function(){return this.metadata[0]}},{key:"getDefaultCountryMetadataForRegion",value:function(){return this.globalMetadataObject.getNumberingPlanMetadata(this.callingCode())}},{key:"IDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[1]}},{key:"defaultIDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[12]}},{key:"nationalNumberPattern",value:function(){return this.v1||this.v2?this.metadata[1]:this.metadata[2]}},{key:"possibleLengths",value:function(){if(!this.v1)return this.metadata[this.v2?2:3]}},{key:"_getFormats",value:function(n){return n[this.v1?2:this.v2?3:4]}},{key:"formats",value:function(){var n=this,r=this._getFormats(this.metadata)||this._getFormats(this.getDefaultCountryMetadataForRegion())||[];return r.map(function(i){return new NN(i,n)})}},{key:"nationalPrefix",value:function(){return this.metadata[this.v1?3:this.v2?4:5]}},{key:"_getNationalPrefixFormattingRule",value:function(n){return n[this.v1?4:this.v2?5:6]}},{key:"nationalPrefixFormattingRule",value:function(){return this._getNationalPrefixFormattingRule(this.metadata)||this._getNationalPrefixFormattingRule(this.getDefaultCountryMetadataForRegion())}},{key:"_nationalPrefixForParsing",value:function(){return this.metadata[this.v1?5:this.v2?6:7]}},{key:"nationalPrefixForParsing",value:function(){return this._nationalPrefixForParsing()||this.nationalPrefix()}},{key:"nationalPrefixTransformRule",value:function(){return this.metadata[this.v1?6:this.v2?7:8]}},{key:"_getNationalPrefixIsOptionalWhenFormatting",value:function(){return!!this.metadata[this.v1?7:this.v2?8:9]}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return this._getNationalPrefixIsOptionalWhenFormatting(this.metadata)||this._getNationalPrefixIsOptionalWhenFormatting(this.getDefaultCountryMetadataForRegion())}},{key:"leadingDigits",value:function(){return this.metadata[this.v1?8:this.v2?9:10]}},{key:"types",value:function(){return this.metadata[this.v1?9:this.v2?10:11]}},{key:"hasTypes",value:function(){return this.types()&&this.types().length===0?!1:!!this.types()}},{key:"type",value:function(n){if(this.hasTypes()&&rb(this.types(),n))return new PN(rb(this.types(),n),this)}},{key:"ext",value:function(){return this.v1||this.v2?tb:this.metadata[13]||tb}}])})(),NN=(function(){function e(t,n){Sd(this,e),this._format=t,this.metadata=n}return xd(e,[{key:"pattern",value:function(){return this._format[0]}},{key:"format",value:function(){return this._format[1]}},{key:"leadingDigitsPatterns",value:function(){return this._format[2]||[]}},{key:"nationalPrefixFormattingRule",value:function(){return this._format[3]||this.metadata.nationalPrefixFormattingRule()}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return!!this._format[4]||this.metadata.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"nationalPrefixIsMandatoryWhenFormattingInNationalFormat",value:function(){return this.usesNationalPrefix()&&!this.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"usesNationalPrefix",value:function(){return!!(this.nationalPrefixFormattingRule()&&!TN.test(this.nationalPrefixFormattingRule()))}},{key:"internationalFormat",value:function(){return this._format[5]||this.format()}}])})(),TN=/^\(?\$1\)?$/,PN=(function(){function e(t,n){Sd(this,e),this.type=t,this.metadata=n}return xd(e,[{key:"pattern",value:function(){return this.metadata.v1?this.type:this.type[0]}},{key:"possibleLengths",value:function(){if(!this.metadata.v1)return this.type[1]||this.metadata.possibleLengths()}}])})();function rb(e,t){switch(t){case"FIXED_LINE":return e[0];case"MOBILE":return e[1];case"TOLL_FREE":return e[2];case"PREMIUM_RATE":return e[3];case"PERSONAL_NUMBER":return e[4];case"VOICEMAIL":return e[5];case"UAN":return e[6];case"PAGER":return e[7];case"VOIP":return e[8];case"SHARED_COST":return e[9]}}function Lk(e){if(!e)throw new Error("[libphonenumber-js] `metadata` argument not passed. Check your arguments.");if(!_o(e)||!_o(e.countries))throw new Error("[libphonenumber-js] `metadata` argument was passed but it's not a valid metadata. Must be an object having `.countries` child object property. Got ".concat(_o(e)?"an object of shape: { "+Object.keys(e).join(", ")+" }":"a "+ON(e)+": "+e,"."))}var ON=function(t){return To(t)};function O_(e,t){if(t=new vt(t),t.hasCountry(e))return t.selectNumberingPlan(e).countryCallingCode();throw new Error("Unknown country: ".concat(e))}function RN(e,t){return t.countries.hasOwnProperty(e)}function Dk(e){var t=e.version;typeof t=="number"?(this.v1=t===1,this.v2=t===2,this.v3=t===3,this.v4=t===4):t?eb(t,CN)===-1?this.v2=!0:eb(t,IN)===-1?this.v3=!0:this.v4=!0:this.v1=!0}function R_(e,t,n){return LN(e,t,void 0,n)}function LN(e,t,n,r){t&&(r=new vt(r.metadata),r.selectNumberingPlan(t));var i=r.type(n),s=i&&i.possibleLengths()||r.possibleLengths();if(!s)return"IS_POSSIBLE";var a=e.length,c=s[0];return c===a?"IS_POSSIBLE":c>a?"TOO_SHORT":s[s.length-1]<a?"TOO_LONG":s.indexOf(a,1)>=0?"IS_POSSIBLE":"INVALID_LENGTH"}function DN(e,t,n){if(t===void 0&&(t={}),n=new vt(n),t.v2){if(!e.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(e.countryCallingCode)}else{if(!e.phone)return!1;if(e.country){if(!n.hasCountry(e.country))throw new Error("Unknown country: ".concat(e.country));n.selectNumberingPlan(e.country)}else{if(!e.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(e.countryCallingCode)}}if(n.possibleLengths())return Uk(e.phone||e.nationalNumber,e.country,n);if(e.countryCallingCode&&n.isNonGeographicCallingCode(e.countryCallingCode))return!0;throw new Error('Missing "possibleLengths" in metadata. Perhaps the metadata has been generated before v1.0.18.')}function Uk(e,t,n){return R_(e,t,n)==="IS_POSSIBLE"}function ir(e,t){return e=e||"",new RegExp("^(?:"+t+")$").test(e)}function UN(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=BN(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
83
83
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function BN(e,t){if(e){if(typeof e=="string")return ib(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ib(e,t):void 0}}function ib(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var MN=["MOBILE","PREMIUM_RATE","TOLL_FREE","SHARED_COST","VOIP","PERSONAL_NUMBER","PAGER","UAN","VOICEMAIL"];function L_(e,t,n){if(t=t||{},!(!e.country&&!e.countryCallingCode)){n=new vt(n),n.selectNumberingPlan(e.country,e.countryCallingCode);var r=t.v2?e.nationalNumber:e.phone;if(ir(r,n.nationalNumberPattern())){if(pp(r,"FIXED_LINE",n))return n.type("MOBILE")&&n.type("MOBILE").pattern()===""||!n.type("MOBILE")||pp(r,"MOBILE",n)?"FIXED_LINE_OR_MOBILE":"FIXED_LINE";for(var i=UN(MN),s;!(s=i()).done;){var a=s.value;if(pp(r,a,n))return a}}}}function pp(e,t,n){var r=n.type(t);return!r||!r.pattern()||r.possibleLengths()&&r.possibleLengths().indexOf(e.length)<0?!1:ir(e,r.pattern())}function qN(e,t,n){if(t=t||{},n=new vt(n),n.selectNumberingPlan(e.country,e.countryCallingCode),n.hasTypes())return L_(e,t,n.metadata)!==void 0;var r=t.v2?e.nationalNumber:e.phone;return ir(r,n.nationalNumberPattern())}function FN(e,t,n){var r=new vt(n),i=r.getCountryCodesForCallingCode(e);return i?i.filter(function(s){return HN(t,s,n)}):[]}function HN(e,t,n){var r=new vt(n);return r.selectNumberingPlan(t),r.numberingPlan.possibleLengths().indexOf(e.length)>=0}var D_=2,VN=17,KN=3,mn="0-90-9٠-٩۰-۹",GN="-‐-―−ー-",WN="//",JN="..",ZN=" ",XN="()()[]\\[\\]",YN="~⁓∼~",tu="".concat(GN).concat(WN).concat(JN).concat(ZN).concat(XN).concat(YN),U_="++",QN=new RegExp("(["+mn+"])");function eT(e,t,n,r){if(t){var i=new vt(r);i.selectNumberingPlan(t,n);var s=new RegExp(i.IDDPrefix());if(e.search(s)===0){e=e.slice(e.match(s)[0].length);var a=e.match(QN);if(!(a&&a[1]!=null&&a[1].length>0&&a[1]==="0"))return e}}}function tT(e,t){if(e&&t.numberingPlan.nationalPrefixForParsing()){var n=new RegExp("^(?:"+t.numberingPlan.nationalPrefixForParsing()+")"),r=n.exec(e);if(r){var i,s,a=r.length-1,c=a>0&&r[a];if(t.nationalPrefixTransformRule()&&c)i=e.replace(n,t.nationalPrefixTransformRule()),a>1&&(s=r[1]);else{var l=r[0];i=e.slice(l.length),c&&(s=r[1])}var u;if(c){var d=e.indexOf(r[1]),f=e.slice(0,d);f===t.numberingPlan.nationalPrefix()&&(u=t.numberingPlan.nationalPrefix())}else u=r[0];return{nationalNumber:i,nationalPrefix:u,carrierCode:s}}}return{nationalNumber:e}}function nT(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=rT(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
84
84
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rT(e,t){if(e){if(typeof e=="string")return ob(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ob(e,t):void 0}}function ob(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function iT(e,t){var n=t.countries,r=t.metadata;r=new vt(r);for(var i=nT(n),s;!(s=i()).done;){var a=s.value;if(r.selectNumberingPlan(a),r.leadingDigits()){if(e&&e.search(r.leadingDigits())===0)return a}else if(L_({phone:e,country:a},void 0,r.metadata))return a}}function Bk(e,t){var n=t.nationalNumber,r=t.metadata,i=r.getCountryCodesForCallingCode(e);if(i)return i.length===1?i[0]:iT(n,{countries:i,metadata:r.metadata})}function G0(e,t,n){var r=tT(e,n),i=r.carrierCode,s=r.nationalNumber;if(s!==e){if(!oT(e,s,n))return{nationalNumber:e};if(n.numberingPlan.possibleLengths()&&(t||(t=Bk(n.numberingPlan.callingCode(),{nationalNumber:s,metadata:n})),!sT(s,t,n)))return{nationalNumber:e}}return{nationalNumber:s,carrierCode:i}}function oT(e,t,n){return!(ir(e,n.nationalNumberPattern())&&!ir(t,n.nationalNumberPattern()))}function sT(e,t,n){switch(R_(e,t,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function aT(e,t,n,r,i){var s=n?O_(n,i):r;if(e.indexOf(s)===0){i=new vt(i),i.selectNumberingPlan(n,s);var a=e.slice(s.length),c=G0(a,t,i),l=c.nationalNumber,u=G0(e,t,i),d=u.nationalNumber;if(!ir(d,i.nationalNumberPattern())&&ir(l,i.nationalNumberPattern())||R_(d,t,i)==="TOO_LONG")return{countryCallingCode:s,number:a}}return{number:e}}function Mk(e,t,n,r,i){if(!e)return{};var s;if(e[0]!=="+"){var a=eT(e,n,r,i);if(a&&a!==e)s=!0,e="+"+a;else{if(n||r){var c=aT(e,t,n,r,i),l=c.countryCallingCode,u=c.number;if(l)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:l,number:u}}return{number:e}}}if(e[1]==="0")return{};i=new vt(i);for(var d=2;d-1<=KN&&d<=e.length;){var f=e.slice(1,d);if(i.hasCallingCode(f))return i.selectNumberingPlan(f),{countryCallingCodeSource:s?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:f,number:e.slice(d)};d++}return{}}function cT(e){return e.replace(new RegExp("[".concat(tu,"]+"),"g")," ").trim()}var lT=/(\$\d)/;function uT(e,t,n){var r=n.useInternationalFormat,i=n.withNationalPrefix,s=e.replace(new RegExp(t.pattern()),r?t.internationalFormat():i&&t.nationalPrefixFormattingRule()?t.format().replace(lT,t.nationalPrefixFormattingRule()):t.format());return r?cT(s):s}var dT=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function pT(e,t,n){var r=new vt(n);if(r.selectNumberingPlan(e,t),r.defaultIDDPrefix())return r.defaultIDDPrefix();if(dT.test(r.IDDPrefix()))return r.IDDPrefix()}var fT=";ext=",Vi=function(t){return"([".concat(mn,"]{1,").concat(t,"})")};function qk(e){var t="20",n="15",r="9",i="6",s="[ \\t,]*",a="[:\\..]?[ \\t,-]*",c="#?",l="(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)",u="(?:[xx##~~]|int|int)",d="[- ]+",f="[ \\t]*",p="(?:,{2}|;)",h=fT+Vi(t),_=s+l+a+Vi(t)+c,g=s+u+a+Vi(r)+c,y=d+Vi(i)+"#",m=f+p+a+Vi(n)+c,w=f+"(?:,)+"+a+Vi(r)+c;return h+"|"+_+"|"+g+"|"+y+"|"+m+"|"+w}var hT="["+mn+"]{"+D_+"}",_T="["+U_+"]{0,1}(?:["+tu+"]*["+mn+"]){3,}["+tu+mn+"]*",mT=new RegExp("^["+U_+"]{0,1}(?:["+tu+"]*["+mn+"]){1,2}$","i"),gT=_T+"(?:"+qk()+")?",yT=new RegExp("^"+hT+"$|^"+gT+"$","i");function bT(e){return e.length>=D_&&yT.test(e)}function vT(e){return mT.test(e)}function wT(e){var t=e.number,n=e.ext;if(!t)return"";if(t[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(t).concat(n?";ext="+n:"")}var sb={formatExtension:function(t,n,r){return"".concat(t).concat(r.ext()).concat(n)}};function kT(e,t,n,r){if(n?n=xT({},sb,n):n=sb,r=new vt(r),e.country&&e.country!=="001"){if(!r.hasCountry(e.country))throw new Error("Unknown country: ".concat(e.country));r.selectNumberingPlan(e.country)}else if(e.countryCallingCode)r.selectNumberingPlan(e.countryCallingCode);else return e.phone||"";var i=r.countryCallingCode(),s=n.v2?e.nationalNumber:e.phone,a;switch(t){case"NATIONAL":return s?(a=nu(s,e.carrierCode,"NATIONAL",r,n),fp(a,e.ext,r,n.formatExtension)):"";case"INTERNATIONAL":return s?(a=nu(s,null,"INTERNATIONAL",r,n),a="+".concat(i," ").concat(a),fp(a,e.ext,r,n.formatExtension)):"+".concat(i);case"E.164":return"+".concat(i).concat(s);case"RFC3966":return wT({number:"+".concat(i).concat(s),ext:e.ext});case"IDD":if(!n.fromCountry)return;var c=ST(s,e.carrierCode,i,n.fromCountry,r);return c?fp(c,e.ext,r,n.formatExtension):void 0;default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(t,'"'))}}function nu(e,t,n,r,i){var s=$T(r.formats(),e);return s?uT(e,s,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(s.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&i&&i.nationalPrefix===!1)}):e}function $T(e,t){return zT(e,function(n){if(n.leadingDigitsPatterns().length>0){var r=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(t.search(r)!==0)return!1}return ir(t,n.pattern())})}function fp(e,t,n,r){return t?r(e,t,n):e}function ST(e,t,n,r,i){var s=O_(r,i.metadata);if(s===n){var a=nu(e,t,"NATIONAL",i);return n==="1"?n+" "+a:a}var c=pT(r,void 0,i.metadata);if(c)return"".concat(c," ").concat(n," ").concat(nu(e,null,"INTERNATIONAL",i))}function xT(){for(var e=1,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(;e<n.length;){if(n[e])for(var i in n[e])n[0][i]=n[e][i];e++}return n[0]}function zT(e,t){for(var n=0;n<e.length;){if(t(e[n]))return e[n];n++}}function ya(e){"@babel/helpers - typeof";return ya=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ya(e)}function ab(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function cb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ab(Object(n),!0).forEach(function(r){AT(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ab(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function AT(e,t,n){return(t=Fk(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ET(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function CT(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Fk(r.key),r)}}function IT(e,t,n){return t&&CT(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Fk(e){var t=jT(e,"string");return ya(t)=="symbol"?t:t+""}function jT(e,t){if(ya(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ya(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var NT=(function(){function e(t,n,r){if(ET(this,e),!t)throw new TypeError("First argument is required");if(typeof t!="string")throw new TypeError("First argument must be a string");if(t[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(_o(n)&&_o(n.countries)){r=n;var i=t;if(!OT.test(i))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var s=Mk(i,void 0,void 0,void 0,r),a=s.countryCallingCode,c=s.number;if(n=c,t=a,!n)throw new Error("Invalid `number` argument passed: too short")}if(!n)throw new TypeError("`nationalNumber` argument is required");if(typeof n!="string")throw new TypeError("`nationalNumber` argument must be a string");Lk(r);var l=PT(t,r),u=l.country,d=l.countryCallingCode;this.country=u,this.countryCallingCode=d,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return r}}return IT(e,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:FN(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return DN(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return qN(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new vt(this.getMetadata());return n.isNonGeographicCallingCode(this.countryCallingCode)}},{key:"isEqual",value:function(n){return this.number===n.number&&this.ext===n.ext}},{key:"getType",value:function(){return L_(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,r){return kT(this,n,r?cb(cb({},r),{},{v2:!0}):{v2:!0},this.getMetadata())}},{key:"formatNational",value:function(n){return this.format("NATIONAL",n)}},{key:"formatInternational",value:function(n){return this.format("INTERNATIONAL",n)}},{key:"getURI",value:function(n){return this.format("RFC3966",n)}}])})(),TT=function(t){return/^[A-Z]{2}$/.test(t)};function PT(e,t){var n,r,i=new vt(t);return TT(e)?(n=e,i.selectNumberingPlan(n),r=i.countryCallingCode()):r=e,{country:n,countryCallingCode:r}}var OT=/^\+\d+$/;function W0(e){"@babel/helpers - typeof";return W0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},W0(e)}function RT(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function LT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function DT(e,t,n){return t=va(t),UT(e,B_()?Reflect.construct(t,n||[],va(e).constructor):t.apply(e,n))}function UT(e,t){if(t&&(W0(t)=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return BT(e)}function BT(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function MT(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ba(e,t)}function J0(e){var t=typeof Map=="function"?new Map:void 0;return J0=function(r){if(r===null||!FT(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(r))return t.get(r);t.set(r,i)}function i(){return qT(r,arguments,va(this).constructor)}return i.prototype=Object.create(r.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),ba(i,r)},J0(e)}function qT(e,t,n){if(B_())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&ba(i,n.prototype),i}function B_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(B_=function(){return!!e})()}function FT(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function ba(e,t){return ba=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},ba(e,t)}function va(e){return va=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},va(e)}var Gn=(function(e){function t(n){var r;return LT(this,t),r=DT(this,t,[n]),Object.setPrototypeOf(r,t.prototype),r.name=r.constructor.name,r}return MT(t,e),RT(t)})(J0(Error)),lb=new RegExp("(?:"+qk()+")$","i");function HT(e){var t=e.search(lb);if(t<0)return{};for(var n=e.slice(0,t),r=e.match(lb),i=1;i<r.length;){if(r[i])return{number:n,ext:r[i]};i++}}var VT={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9"};function KT(e){return VT[e]}function GT(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=WT(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
85
85
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function WT(e,t){if(e){if(typeof e=="string")return ub(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ub(e,t):void 0}}function ub(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function db(e){for(var t="",n=GT(e.split("")),r;!(r=n()).done;){var i=r.value;t+=JT(i,t)||""}return t}function JT(e,t,n){return e==="+"?t?void 0:"+":KT(e)}var Hk="+",ZT="[\\-\\.\\(\\)]?",pb="(["+mn+"]|"+ZT+")",XT="^\\"+Hk+pb+"*["+mn+"]"+pb+"*$",YT=new RegExp(XT,"g"),Z0=mn,QT="["+Z0+"]+((\\-)*["+Z0+"])*",eP="a-zA-Z",tP="["+eP+"]+((\\-)*["+Z0+"])*",nP="^("+QT+"\\.)*"+tP+"\\.?$",rP=new RegExp(nP,"g"),fb="tel:",X0=";phone-context=",iP=";isub=";function oP(e){var t=e.indexOf(X0);if(t<0)return null;var n=t+X0.length;if(n>=e.length)return"";var r=e.indexOf(";",n);return r>=0?e.substring(n,r):e.substring(n)}function sP(e){return e===null?!0:e.length===0?!1:YT.test(e)||rP.test(e)}function aP(e,t){var n=t.extractFormattedPhoneNumber,r=oP(e);if(!sP(r))throw new Gn("NOT_A_NUMBER");var i;if(r===null)i=n(e)||"";else{i="",r.charAt(0)===Hk&&(i+=r);var s=e.indexOf(fb),a;s>=0?a=s+fb.length:a=0;var c=e.indexOf(X0);i+=e.substring(a,c)}var l=i.indexOf(iP);if(l>0&&(i=i.substring(0,l)),i!=="")return i}var cP=250,lP=new RegExp("["+U_+mn+"]"),uP=new RegExp("[^"+mn+"#]+$");function dP(e,t,n){if(t=t||{},n=new vt(n),t.defaultCountry&&!n.hasCountry(t.defaultCountry))throw t.v2?new Gn("INVALID_COUNTRY"):new Error("Unknown country: ".concat(t.defaultCountry));var r=fP(e,t.v2,t.extract),i=r.number,s=r.ext,a=r.error;if(!i){if(t.v2)throw a==="TOO_SHORT"?new Gn("TOO_SHORT"):new Gn("NOT_A_NUMBER");return{}}var c=_P(i,t.defaultCountry,t.defaultCallingCode,n),l=c.country,u=c.nationalNumber,d=c.countryCallingCode,f=c.countryCallingCodeSource,p=c.carrierCode;if(!n.hasSelectedNumberingPlan()){if(t.v2)throw new Gn("INVALID_COUNTRY");return{}}if(!u||u.length<D_){if(t.v2)throw new Gn("TOO_SHORT");return{}}if(u.length>VN){if(t.v2)throw new Gn("TOO_LONG");return{}}if(t.v2){var h=new NT(d,u,n.metadata);return l&&(h.country=l),p&&(h.carrierCode=p),s&&(h.ext=s),h.__countryCallingCodeSource=f,h}var _=(t.extended?n.hasSelectedNumberingPlan():l)?ir(u,n.nationalNumberPattern()):!1;return t.extended?{country:l,countryCallingCode:d,carrierCode:p,valid:_,possible:_?!0:!!(t.extended===!0&&n.possibleLengths()&&Uk(u,l,n)),phone:u,ext:s}:_?hP(l,u,s):{}}function pP(e,t,n){if(e){if(e.length>cP){if(n)throw new Gn("TOO_LONG");return}if(t===!1)return e;var r=e.search(lP);if(!(r<0))return e.slice(r).replace(uP,"")}}function fP(e,t,n){var r=aP(e,{extractFormattedPhoneNumber:function(a){return pP(a,n,t)}});if(!r)return{};if(!bT(r))return vT(r)?{error:"TOO_SHORT"}:{};var i=HT(r);return i.ext?i:{number:r}}function hP(e,t,n){var r={country:e,phone:t};return n&&(r.ext=n),r}function _P(e,t,n,r){var i=Mk(db(e),void 0,t,n,r.metadata),s=i.countryCallingCodeSource,a=i.countryCallingCode,c=i.number,l;if(a)r.selectNumberingPlan(a);else if(c&&(t||n))r.selectNumberingPlan(t,n),t&&(l=t),a=n||O_(t,r.metadata);else return{};if(!c)return{countryCallingCodeSource:s,countryCallingCode:a};var u=G0(db(c),l,r),d=u.nationalNumber,f=u.carrierCode,p=Bk(a,{nationalNumber:d,metadata:r});return p&&(l=p,p==="001"||r.selectNumberingPlan(l)),{country:l,countryCallingCode:a,countryCallingCodeSource:s,nationalNumber:d,carrierCode:f}}function wa(e){"@babel/helpers - typeof";return wa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wa(e)}function hb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function _b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?hb(Object(n),!0).forEach(function(r){mP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):hb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function mP(e,t,n){return(t=gP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function gP(e){var t=yP(e,"string");return wa(t)=="symbol"?t:t+""}function yP(e,t){if(wa(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(wa(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function bP(e,t,n){return dP(e,_b(_b({},t),{},{v2:!0}),n)}function ka(e){"@babel/helpers - typeof";return ka=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ka(e)}function mb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function vP(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?mb(Object(n),!0).forEach(function(r){wP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function wP(e,t,n){return(t=kP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kP(e){var t=$P(e,"string");return ka(t)=="symbol"?t:t+""}function $P(e,t){if(ka(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ka(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function SP(e,t){return EP(e)||AP(e,t)||zP(e,t)||xP()}function xP(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
86
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zP(e,t){if(e){if(typeof e=="string")return gb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gb(e,t):void 0}}function gb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function AP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function EP(e){if(Array.isArray(e))return e}function CP(e){var t=Array.prototype.slice.call(e),n=SP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=vP({defaultCountry:i},l));else if(_o(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function $a(e){"@babel/helpers - typeof";return $a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$a(e)}function yb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function bb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yb(Object(n),!0).forEach(function(r){IP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function IP(e,t,n){return(t=jP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jP(e){var t=NP(e,"string");return $a(t)=="symbol"?t:t+""}function NP(e,t){if($a(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if($a(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function TP(e,t,n){t&&t.defaultCountry&&!RN(t.defaultCountry,n)&&(t=bb(bb({},t),{},{defaultCountry:void 0}));try{return bP(e,t,n)}catch(r){if(!(r instanceof Gn))throw r}}function PP(){var e=CP(arguments),t=e.text,n=e.options,r=e.metadata;return TP(t,n,r)}function OP(){return SN(PP,arguments)}function is(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=OP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Te}}function M_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function RP(e){const n=M_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function LP(e){const t=M_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function DP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function vb(e){if(!e)return null;const t=M_(DP(e));return RP(t)?{family:4,normalized:t}:LP(t)?{family:6,normalized:t.toLowerCase()}:null}function wb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function UP(e,t,n=!0){const r=vb(e),i=vb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=wb(r.normalized),a=wb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class qt extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=qt.name,this.location=t,this.status=n}}const BP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:Xs.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Vk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=is(n,c);if(!u)throw new W(400,{message:"Invalid username format"});const d=await He(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new W(400,{message:he("code_invalid")});if(p.expires_at<new Date().toISOString())throw new W(400,{message:he("code_expired")});if(p.used_at)throw new W(400,{message:he("code_used")});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new W(400,{message:"Code not found or expired"});if(s&&h.ip&&a&&!UP(h.ip,a))throw new qt(`${mt(e.env)}invalid-session?state=${h.id}`);const _=await Cu(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function zd(e,t){const n=await Vk(e,t);return yt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const kb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),$b=o.z.union([Rk.extend(kb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...kb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function MP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const qP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:$b},"application/json":{schema:$b}}}},responses:{200:{content:{"application/json":{schema:$h}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=MP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await vN(e,bN.parse(i));break;case an.ClientCredential:s=await yN(e,Rk.parse(i));break;case an.RefreshToken:s=await kN(e,wN.parse(i));break;case an.OTP:s=await Vk(e,BP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&cl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await ea(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await ea(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await vu(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function ec(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function Kk(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await He(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function Gk(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${mt(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await ec(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${mt(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:pe.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Ad(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=is(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(mt(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await ec(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await Kk(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:pe.CODE_LINK_SENT,description:t})}async function Ed(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=is(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await ec(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await Kk(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:pe.CODE_LINK_SENT,description:t})}async function Cd(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await ec(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${mt(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function FP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${mt(e.env)}signup?state=${r}&code=${n}`;await ec(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const HP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await He(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ta(e.env.data,i.tenant.id,a);try{await Na(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Xn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Te}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await oa(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Te}|${Ni()}`,email:t,email_verified:!1,provider:Te,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await Cd(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:pe.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await He(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Te}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await Gk(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function In(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const VP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Xs.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Xs.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await He(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Bs).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:In(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Bs).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await Ed(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Ad(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(at),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await He(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await zd(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const S=k;"message"in S&&typeof S.message=="string"&&(h=S.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),w=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Bs).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${mt(e.env)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class Yi extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function KP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function GP(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function Wk(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new W(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Te});if(!a)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Yi(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new Yi(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),GP(c).length>=3)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Too many failed login attempts"}),new Yi(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await qo.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),KP(i,t.tenant.id,c),new Yi(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await Cd(e,a,p),fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Email not verified"}),r&&await BA(e,t.tenant.id,r,"Email not verified"),new Yi(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function tc(e,t,n,r,i){const s=await Wk(e,t,n,r);return yt(e,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function WP(e,t,n,r){await Cu(e,{client:t,username:n,provider:Te,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Nz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+jz).toISOString()});await Gk(e,n,f.code_id,r)}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await He(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await zd(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await tc(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function Jk(e,t){if(!e||t.length===0)return!1;const n=hp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=hp(r)?.host??null:i=hp("https://"+r)?.host??null,n===i)return!0}return!1}function hp(e){try{return new URL(e)}catch{return null}}function ZP(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function XP({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);ZP(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return yt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=In();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+di*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Ed(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/enter-code?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=Ds.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function YP(e){if(e==="Username-Password-Authentication")return Te;if(e==="email")return"email";throw new W(403,{message:"Invalid realm"})}async function QP(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new W(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new W(403,{message:"Session not found"});const l=await He(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=YP(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Te?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Cu(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),yt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authStrategy:{strategy:f,strategy_type:p}})}async function eO({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===pn.WEB_MESSAGE;async function w(le="Login required"){const Se=new Headers;if(n&&(fe(e,t.tenant.id,{type:pe.FAILED_SILENT_AUTH,description:le}),qw(t.tenant.id,e.req.header("host")).forEach(Hr=>{Se.append("set-cookie",Hr)})),m)return mf(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),Se);const F=new URL(r);if(d===at.TOKEN||d===at.TOKEN_ID_TOKEN){const Xe=new URLSearchParams;Xe.set("error","login_required"),Xe.set("error_description",le),i&&Xe.set("state",i),F.hash=Xe.toString()}else F.searchParams.set("error","login_required"),F.searchParams.set("error_description",le),i&&F.searchParams.set("state",i);const St={Location:F.toString()},ue=Se.get("set-cookie");return ue&&(St["set-cookie"]=ue),new Response(null,{status:302,headers:St})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,S=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||S)return w();e.set("user_id",n.user_id);const b=await _.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),w("User not found");e.set("username",b.email),e.set("connection",b.connection);let x;if(p&&(x=await _.data.organizations.get(t.tenant.id,p),!x))return w("Organization not found");const A=l||t.tenant.audience;let E=u||"",P=[];if(A)try{const le=await ea(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:x?.id,userId:b.user_id});E=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const Se=le?.body?.error_description||le?.message||"Access denied";return w(Se)}throw le}else if(x&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${b.user_id}`,per_page:1e3})).userOrganizations.some(F=>F.organization_id===x.id))return w("User is not a member of the specified organization");const R=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),C=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,L={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:E,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:b,session_id:n.id,auth_time:C,permissions:P,organization:x},B=d===at.CODE?await y2(e,{user:b,client:t,authParams:L.authParams,login_id:R.id}):await vu(e,L),V=n.idle_expires_at?new Date(Date.now()+_u*1e3).toISOString():void 0;await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:R.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:V}),V&&await _.data.loginSessions.update(t.tenant.id,R.id,{expires_at:V}),fe(e,t.tenant.id,{type:pe.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const D=new Headers;if(cl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{D.append("set-cookie",le)}),m)return mf(e,y,JSON.stringify({...B,state:i}),D);const ce=new URL(r);if(d===at.TOKEN||d===at.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(B).forEach(([Se,F])=>{F!==void 0&&le.set(Se,String(F))}),i&&le.set("state",i),ce.hash=le.toString()}else Object.entries(B).forEach(([le,Se])=>{Se!==void 0&&ce.searchParams.set(le,String(Se))}),i&&ce.searchParams.set("state",i);const ve={Location:ce.toString()},Ee=D.get("set-cookie");return Ee&&(ve["set-cookie"]=Ee),new Response(null,{status:302,headers:ve})}const tO=["email","sms","Username-Password-Authentication"],Sb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(pn).optional(),response_type:o.z.nativeEnum(at).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(fu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function nO(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const rO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:Sb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:$h}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const D=nO(n.request);if(D){const ne=Sb.safeParse(D);ne.success&&(r=ne.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:w,login_ticket:k,realm:S,login_hint:b,ui_locales:x,organization:A}={...r,...n};e.set("log","authorize");const E=await He(t,i);e.set("client_id",E.client_id),Vt(e,E.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const R=e.req.header("origin");if(R&&!Jk(R,E.web_origins||[]))throw new I(403,{message:`Origin ${R} not allowed`});if(!p){if(P){const D=new URL(P);return D.searchParams.set("error","invalid_request"),D.searchParams.set("error_description","Missing required parameter: response_type"),l&&D.searchParams.set("state",l),e.redirect(D.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const C={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:b,ui_locales:x,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:w};if(C.redirect_uri){const D=E.callbacks||[];if(e.var.host&&(D.push(`${$u(e.env)}/*`),D.push(`${mt(e.env)}/*`)),!P_(C.redirect_uri,D,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${C.redirect_uri}`})}let L;const B=Oz(E.tenant.id,e.req.header("cookie"));for(const D of B){const ne=await t.data.sessions.get(E.tenant.id,D);if(ne&&!ne.revoked_at){L=ne;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return eO({ctx:e,session:L||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:E,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(E.connections.length===1&&E.connections[0]&&!tO.includes(E.connections[0].strategy||""))return Jy(e,E,E.connections[0].name,C);if(f&&f!=="email")return Jy(e,E,f,C);if(k){const D=await QP(e,E.tenant.id,k,C,S);return D instanceof Response?D:e.json(D)}const V=await XP({ctx:e,client:E,authParams:C,session:L||void 0,connection:f,login_hint:b});return V instanceof Response?V:e.json(V)}),iO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await He(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!Jk(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=a.callbacks||[];if(e.var.host&&(w.push(`${$u(e.env)}/*`),w.push(`${mt(e.env)}/*`)),!P_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=pi(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${mt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const w=new URL("/u/account",e.req.url);return w.searchParams.set("state",m.id),e.redirect(w.toString())}return e.redirect(`${mt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function oO(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Bo(r,e.dataAdapter),a=e.dataAdapter.cache||rs({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Qa(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks"],cache:a});return r.env.data=Ya(r,l),i()}),t.use("/oauth/token",Ok({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ns).use(ts).use($d(t));const n=t.route("/v2/logout",fN).route("/userinfo",mN).route("/.well-known",gN).route("/oauth/token",qP).route("/dbconnections",HP).route("/passwordless",VP).route("/co/authenticate",JP).route("/authorize",rO).route("/account",iO).route("/callback",dN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),N_(n),n}var q_=Symbol("RENDERER"),Y0=Symbol("ERROR_HANDLER"),qe=Symbol("STASH"),Zk=Symbol("INTERNAL"),sO=Symbol("MEMO"),ru=Symbol("PERMALINK"),xb=e=>(e[Zk]=!0,e),Xk=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:xb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:xb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Y0]=s=>{throw e.pop(),s},i},Yk=e=>{const t=[e],n=Xk(t);return n.values=t,n.Provider=n,Po.push(n),n},Po=[],Qk=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new o4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[q_]=Xk(t),Po.push(n),n},os=e=>e.values.at(-1),iu={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Q0={},ei="data-precedence",e4=e=>e.rel==="stylesheet"&&"precedence"in e,t4=(e,t)=>e==="link"?t:iu[e].length>0,nc=e=>Array.isArray(e)?e:[e],zb=new WeakMap,Ab=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=zb.get(s)||{};zb.set(s,a);const c=a[e]||=[];let l=!1;const u=iu[e],d=t4(e,r!==void 0);if(d){e:for(const[,f]of c)if(!(e==="link"&&!(f.rel==="stylesheet"&&f[ei]!==void 0))){for(const p of u)if((f?.[p]??null)===n?.[p]){l=!0;break e}}}if(l?i[0]=i[0].replaceAll(t,""):d||e==="link"?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let f;if(e==="link"||r!==void 0){const p=[];f=c.map(([h,,_],g)=>{if(_===void 0)return[h,Number.MAX_SAFE_INTEGER,g];let y=p.indexOf(_);return y===-1&&(p.push(_),y=p.length-1),[h,y,g]}).sort((h,_)=>h[1]-_[1]||h[2]-_[2]).map(([h])=>h)}else f=c.map(([p])=>p);f.forEach(p=>{i[0]=i[0].replaceAll(p,"")}),i[0]=i[0].replace(/(?=<\/head>)/,f.join(""))}},rc=(e,t,n)=>Cr(new _n(e,n,nc(t??[])).toString()),ic=(e,t,n,r)=>{if("itemProp"in n)return rc(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ei]=i);const c=new _n(e,a,nc(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],Ab(e,l,a,i)])):Cr(c,[Ab(e,c,a,i)])},aO=({children:e,...t})=>{const n=F_();if(n){const r=os(n);if(r==="svg"||r==="head")return new _n("title",t,nc(e??[]))}return ic("title",e,t,!1)},cO=({children:e,...t})=>{const n=F_();return["src","async"].some(r=>!t[r])||n&&os(n)==="head"?rc("script",e,t):ic("script",e,t,!1)},lO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,ic("style",e,t,!0)):rc("style",e,t),uO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?rc("link",e,t):ic("link",e,t,e4(t)),dO=({children:e,...t})=>{const n=F_();return n&&os(n)==="head"?rc("meta",e,t):ic("meta",e,t,!1)},n4=(e,{children:t,...n})=>new _n(e,n,nc(t??[])),pO=e=>(typeof e.action=="function"&&(e.action=ru in e.action?e.action[ru]:void 0),n4("form",e)),r4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=ru in t.formAction?t.formAction[ru]:void 0),n4(e,t)),fO=e=>r4("input",e),hO=e=>r4("button",e);const _p=Object.freeze(Object.defineProperty({__proto__:null,button:hO,form:pO,input:fO,link:uO,meta:dO,script:cO,style:lO,title:aO},Symbol.toStringTag,{value:"Module"}));var _O=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),ou=e=>_O.get(e)||e,i4=(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)}},Sa=void 0,F_=()=>Sa,mO=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,gO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],yO=["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"],H_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")ho(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof _n?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):H_(i,t)}}},_n=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?kj(Cr(e[0],e.callbacks)).toString():e[0]:wj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=Sa&&os(Sa)==="svg"?s=>mO(ou(s)):s=>ou(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";i4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',ho(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,ho(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&yO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,ho(a.toString(),e),e[0]+='"'}if(gO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",H_(r,e),e[0]+=`</${t}>`}},mp=class extends _n{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(Po.length===0)e.unshift("",r);else{const i=Po.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof _n&&(s.localContexts=i),s)))}else r instanceof _n?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):ho(r,e)}},o4=class extends _n{toStringToBuffer(e){H_(this.children,e)}},bO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Uc(e,t,n);return i.key=r,i},Eb=!1,Uc=(e,t,n)=>{if(!Eb){for(const r in Q0)_p[r][q_]=Q0[r];Eb=!0}return typeof e=="function"?new mp(e,t,n):_p[e]?new mp(_p[e],t,n):e==="svg"||e==="head"?(Sa||=Qk(""),new _n(e,t,[new mp(Sa,{value:e},n)])):new _n(e,t,n)},Oo=({children:e})=>new o4("",{children:e},Array.isArray(e)?e:e?[e]:[]),vO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return bO(e.tag,{...e.props,...t},...r)};function v(e,t,n){let r;if(!t||!("children"in t))r=Uc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Uc(e,t,i):Uc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new W(400,{message:"Login session not found"});e.set("loginSession",i);const s=await He(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new W(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new qt(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??df,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ci(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=pi(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&FA(c,n.continuationScope)){if(!c.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const gp={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function s4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Mo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Xn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Te}))?.app_metadata?.strategy;if(a&&gp[a])return gp[a];const c=t.connections.map(u=>gp[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const V_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?v("div",{className:"inline-flex h-9 items-center",children:v("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):v(Oo,{})},a4=e=>v("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&v("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",v("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var yp={exports:{}};var Cb;function wO(){return Cb||(Cb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(yp)),yp.exports}var kO=wO();const Be=Bw(kO),$O=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=$O(t);return v("span",{className:Be(`uicon-${e}`,n,r)})},SO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Ro="mmno1m1n",xO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||SO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
|
|
86
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zP(e,t){if(e){if(typeof e=="string")return gb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gb(e,t):void 0}}function gb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function AP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function EP(e){if(Array.isArray(e))return e}function CP(e){var t=Array.prototype.slice.call(e),n=SP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=vP({defaultCountry:i},l));else if(_o(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function $a(e){"@babel/helpers - typeof";return $a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$a(e)}function yb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function bb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yb(Object(n),!0).forEach(function(r){IP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function IP(e,t,n){return(t=jP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jP(e){var t=NP(e,"string");return $a(t)=="symbol"?t:t+""}function NP(e,t){if($a(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if($a(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function TP(e,t,n){t&&t.defaultCountry&&!RN(t.defaultCountry,n)&&(t=bb(bb({},t),{},{defaultCountry:void 0}));try{return bP(e,t,n)}catch(r){if(!(r instanceof Gn))throw r}}function PP(){var e=CP(arguments),t=e.text,n=e.options,r=e.metadata;return TP(t,n,r)}function OP(){return SN(PP,arguments)}function is(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=OP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Te}}function M_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function RP(e){const n=M_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function LP(e){const t=M_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function DP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function vb(e){if(!e)return null;const t=M_(DP(e));return RP(t)?{family:4,normalized:t}:LP(t)?{family:6,normalized:t.toLowerCase()}:null}function wb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function UP(e,t,n=!0){const r=vb(e),i=vb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=wb(r.normalized),a=wb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class qt extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=qt.name,this.location=t,this.status=n}}const BP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:Xs.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Vk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=is(n,c);if(!u)throw new W(400,{message:"Invalid username format"});const d=await He(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new W(400,{message:he("code_invalid")});if(p.expires_at<new Date().toISOString())throw new W(400,{message:he("code_expired")});if(p.used_at)throw new W(400,{message:he("code_used")});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new W(400,{message:"Code not found or expired"});if(s&&h.ip&&a&&!UP(h.ip,a))throw new qt(`${mt(e.env)}invalid-session?state=${h.id}`);const _=await Cu(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function zd(e,t){const n=await Vk(e,t);return yt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const kb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),$b=o.z.union([Rk.extend(kb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...kb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function MP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const qP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:$b},"application/json":{schema:$b}}}},responses:{200:{content:{"application/json":{schema:$h}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=MP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await vN(e,bN.parse(i));break;case an.ClientCredential:s=await yN(e,Rk.parse(i));break;case an.RefreshToken:s=await kN(e,wN.parse(i));break;case an.OTP:s=await Vk(e,BP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&cl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await ea(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await ea(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await vu(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function ec(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function Kk(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await He(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function Gk(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${mt(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await ec(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${mt(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:pe.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Ad(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=is(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(mt(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await ec(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await Kk(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:pe.CODE_LINK_SENT,description:t})}async function Ed(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=is(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await ec(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await Kk(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:pe.CODE_LINK_SENT,description:t})}async function Cd(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await ec(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${mt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${mt(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function FP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${mt(e.env)}signup?state=${r}&code=${n}`;await ec(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const HP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await He(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ta(e.env.data,i.tenant.id,a);try{await Na(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Xn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Te}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await oa(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Te}|${Ni()}`,email:t,email_verified:!1,provider:Te,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await Cd(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:pe.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await He(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Te}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await Gk(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function In(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const VP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Xs.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Xs.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await He(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Bs).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:In(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Bs).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await Ed(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Ad(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(at),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await He(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await zd(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const S=k;"message"in S&&typeof S.message=="string"&&(h=S.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),w=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Bs).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${mt(e.env)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class Yi extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function KP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function GP(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function Wk(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new W(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Te});if(!a)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Yi(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new Yi(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),GP(c).length>=3)throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Too many failed login attempts"}),new Yi(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await qo.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:pe.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),KP(i,t.tenant.id,c),new Yi(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await Cd(e,a,p),fe(e,t.tenant.id,{type:pe.FAILED_LOGIN,description:"Email not verified"}),r&&await BA(e,t.tenant.id,r,"Email not verified"),new Yi(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function tc(e,t,n,r,i){const s=await Wk(e,t,n,r);return yt(e,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function WP(e,t,n,r){await Cu(e,{client:t,username:n,provider:Te,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Nz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+jz).toISOString()});await Gk(e,n,f.code_id,r)}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await He(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await zd(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await tc(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function Jk(e,t){if(!e||t.length===0)return!1;const n=hp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=hp(r)?.host??null:i=hp("https://"+r)?.host??null,n===i)return!0}return!1}function hp(e){try{return new URL(e)}catch{return null}}function ZP(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function XP({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);ZP(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return yt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=In();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+di*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Ed(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/enter-code?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=Ds.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function YP(e){if(e==="Username-Password-Authentication")return Te;if(e==="email")return"email";throw new W(403,{message:"Invalid realm"})}async function QP(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new W(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new W(403,{message:"Session not found"});const l=await He(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=YP(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Te?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Cu(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),yt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authStrategy:{strategy:f,strategy_type:p}})}async function eO({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===pn.WEB_MESSAGE;async function w(le="Login required"){const Se=new Headers;if(n&&(fe(e,t.tenant.id,{type:pe.FAILED_SILENT_AUTH,description:le}),qw(t.tenant.id,e.req.header("host")).forEach(Hr=>{Se.append("set-cookie",Hr)})),m)return mf(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),Se);const F=new URL(r);if(d===at.TOKEN||d===at.TOKEN_ID_TOKEN){const Xe=new URLSearchParams;Xe.set("error","login_required"),Xe.set("error_description",le),i&&Xe.set("state",i),F.hash=Xe.toString()}else F.searchParams.set("error","login_required"),F.searchParams.set("error_description",le),i&&F.searchParams.set("state",i);const St={Location:F.toString()},ue=Se.get("set-cookie");return ue&&(St["set-cookie"]=ue),new Response(null,{status:302,headers:St})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,S=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||S)return w();e.set("user_id",n.user_id);const b=await _.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),w("User not found");e.set("username",b.email),e.set("connection",b.connection);let x;if(p&&(x=await _.data.organizations.get(t.tenant.id,p),!x))return w("Organization not found");const A=l||t.tenant.audience;let E=u||"",P=[];if(A)try{const le=await ea(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:x?.id,userId:b.user_id});E=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const Se=le?.body?.error_description||le?.message||"Access denied";return w(Se)}throw le}else if(x&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${b.user_id}`,per_page:1e3})).userOrganizations.some(F=>F.organization_id===x.id))return w("User is not a member of the specified organization");const R=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),C=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,L={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:E,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:b,session_id:n.id,auth_time:C,permissions:P,organization:x},B=d===at.CODE?await y2(e,{user:b,client:t,authParams:L.authParams,login_id:R.id}):await vu(e,L),V=n.idle_expires_at?new Date(Date.now()+_u*1e3).toISOString():void 0;await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:R.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:V}),V&&await _.data.loginSessions.update(t.tenant.id,R.id,{expires_at:V}),fe(e,t.tenant.id,{type:pe.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const D=new Headers;if(cl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{D.append("set-cookie",le)}),m)return mf(e,y,JSON.stringify({...B,state:i}),D);const ce=new URL(r);if(d===at.TOKEN||d===at.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(B).forEach(([Se,F])=>{F!==void 0&&le.set(Se,String(F))}),i&&le.set("state",i),ce.hash=le.toString()}else Object.entries(B).forEach(([le,Se])=>{Se!==void 0&&ce.searchParams.set(le,String(Se))}),i&&ce.searchParams.set("state",i);const ve={Location:ce.toString()},Ee=D.get("set-cookie");return Ee&&(ve["set-cookie"]=Ee),new Response(null,{status:302,headers:ve})}const tO=["email","sms","Username-Password-Authentication"],Sb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(pn).optional(),response_type:o.z.nativeEnum(at).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(fu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function nO(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const rO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:Sb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:$h}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const D=nO(n.request);if(D){const ne=Sb.safeParse(D);ne.success&&(r=ne.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:w,login_ticket:k,realm:S,login_hint:b,ui_locales:x,organization:A}={...r,...n};e.set("log","authorize");const E=await He(t,i);e.set("client_id",E.client_id),Vt(e,E.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const R=e.req.header("origin");if(R&&!Jk(R,E.web_origins||[]))throw new I(403,{message:`Origin ${R} not allowed`});if(!p){if(P){const D=new URL(P);return D.searchParams.set("error","invalid_request"),D.searchParams.set("error_description","Missing required parameter: response_type"),l&&D.searchParams.set("state",l),e.redirect(D.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const C={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:b,ui_locales:x,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:w};if(C.redirect_uri){const D=E.callbacks||[];if(e.var.host&&(D.push(`${$u(e.env)}/*`),D.push(`${mt(e.env)}/*`)),!P_(C.redirect_uri,D,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${C.redirect_uri}`})}let L;const B=Oz(E.tenant.id,e.req.header("cookie"));for(const D of B){const ne=await t.data.sessions.get(E.tenant.id,D);if(ne&&!ne.revoked_at){L=ne;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return eO({ctx:e,session:L||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:E,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(E.connections.length===1&&E.connections[0]&&!tO.includes(E.connections[0].strategy||""))return Jy(e,E,E.connections[0].name,C);if(f&&f!=="email")return Jy(e,E,f,C);if(k){const D=await QP(e,E.tenant.id,k,C,S);return D instanceof Response?D:e.json(D)}const V=await XP({ctx:e,client:E,authParams:C,session:L||void 0,connection:f,login_hint:b});return V instanceof Response?V:e.json(V)}),iO=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await He(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!Jk(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=a.callbacks||[];if(e.var.host&&(w.push(`${$u(e.env)}/*`),w.push(`${mt(e.env)}/*`)),!P_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=pi(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+di*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${mt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const w=new URL("/u/account",e.req.url);return w.searchParams.set("state",m.id),e.redirect(w.toString())}return e.redirect(`${mt(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function oO(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Bo(r,e.dataAdapter),a=e.dataAdapter.cache||rs({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Qa(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks"],cache:a});return r.env.data=Ya(r,l),i()}),t.use("/oauth/token",Ok({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ns).use(ts).use($d(t));const n=t.route("/v2/logout",fN).route("/userinfo",mN).route("/.well-known",gN).route("/oauth/token",qP).route("/dbconnections",HP).route("/passwordless",VP).route("/co/authenticate",JP).route("/authorize",rO).route("/account",iO).route("/callback",dN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),N_(n),n}var q_=Symbol("RENDERER"),Y0=Symbol("ERROR_HANDLER"),qe=Symbol("STASH"),Zk=Symbol("INTERNAL"),sO=Symbol("MEMO"),ru=Symbol("PERMALINK"),xb=e=>(e[Zk]=!0,e),Xk=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:xb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:xb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Y0]=s=>{throw e.pop(),s},i},Yk=e=>{const t=[e],n=Xk(t);return n.values=t,n.Provider=n,Po.push(n),n},Po=[],Qk=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new o4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[q_]=Xk(t),Po.push(n),n},os=e=>e.values.at(-1),iu={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Q0={},ei="data-precedence",e4=e=>e.rel==="stylesheet"&&"precedence"in e,t4=(e,t)=>e==="link"?t:iu[e].length>0,nc=e=>Array.isArray(e)?e:[e],zb=new WeakMap,Ab=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=zb.get(s)||{};zb.set(s,a);const c=a[e]||=[];let l=!1;const u=iu[e],d=t4(e,r!==void 0);if(d){e:for(const[,f]of c)if(!(e==="link"&&!(f.rel==="stylesheet"&&f[ei]!==void 0))){for(const p of u)if((f?.[p]??null)===n?.[p]){l=!0;break e}}}if(l?i[0]=i[0].replaceAll(t,""):d||e==="link"?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let f;if(e==="link"||r!==void 0){const p=[];f=c.map(([h,,_],g)=>{if(_===void 0)return[h,Number.MAX_SAFE_INTEGER,g];let y=p.indexOf(_);return y===-1&&(p.push(_),y=p.length-1),[h,y,g]}).sort((h,_)=>h[1]-_[1]||h[2]-_[2]).map(([h])=>h)}else f=c.map(([p])=>p);f.forEach(p=>{i[0]=i[0].replaceAll(p,"")}),i[0]=i[0].replace(/(?=<\/head>)/,f.join(""))}},rc=(e,t,n)=>Cr(new _n(e,n,nc(t??[])).toString()),ic=(e,t,n,r)=>{if("itemProp"in n)return rc(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[ei]=i);const c=new _n(e,a,nc(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],Ab(e,l,a,i)])):Cr(c,[Ab(e,c,a,i)])},aO=({children:e,...t})=>{const n=F_();if(n){const r=os(n);if(r==="svg"||r==="head")return new _n("title",t,nc(e??[]))}return ic("title",e,t,!1)},cO=({children:e,...t})=>{const n=F_();return["src","async"].some(r=>!t[r])||n&&os(n)==="head"?rc("script",e,t):ic("script",e,t,!1)},lO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,ic("style",e,t,!0)):rc("style",e,t),uO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?rc("link",e,t):ic("link",e,t,e4(t)),dO=({children:e,...t})=>{const n=F_();return n&&os(n)==="head"?rc("meta",e,t):ic("meta",e,t,!1)},n4=(e,{children:t,...n})=>new _n(e,n,nc(t??[])),pO=e=>(typeof e.action=="function"&&(e.action=ru in e.action?e.action[ru]:void 0),n4("form",e)),r4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=ru in t.formAction?t.formAction[ru]:void 0),n4(e,t)),fO=e=>r4("input",e),hO=e=>r4("button",e);const _p=Object.freeze(Object.defineProperty({__proto__:null,button:hO,form:pO,input:fO,link:uO,meta:dO,script:cO,style:lO,title:aO},Symbol.toStringTag,{value:"Module"}));var _O=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),ou=e=>_O.get(e)||e,i4=(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)}},Sa=void 0,F_=()=>Sa,mO=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,gO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],yO=["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"],H_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")ho(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof _n?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):H_(i,t)}}},_n=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?kj(Cr(e[0],e.callbacks)).toString():e[0]:wj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=Sa&&os(Sa)==="svg"?s=>mO(ou(s)):s=>ou(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";i4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',ho(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,ho(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&yO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,ho(a.toString(),e),e[0]+='"'}if(gO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",H_(r,e),e[0]+=`</${t}>`}},mp=class extends _n{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(Po.length===0)e.unshift("",r);else{const i=Po.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof _n&&(s.localContexts=i),s)))}else r instanceof _n?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):ho(r,e)}},o4=class extends _n{toStringToBuffer(e){H_(this.children,e)}},bO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Uc(e,t,n);return i.key=r,i},Eb=!1,Uc=(e,t,n)=>{if(!Eb){for(const r in Q0)_p[r][q_]=Q0[r];Eb=!0}return typeof e=="function"?new mp(e,t,n):_p[e]?new mp(_p[e],t,n):e==="svg"||e==="head"?(Sa||=Qk(""),new _n(e,t,[new mp(Sa,{value:e},n)])):new _n(e,t,n)},Oo=({children:e})=>new o4("",{children:e},Array.isArray(e)?e:e?[e]:[]),vO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return bO(e.tag,{...e.props,...t},...r)};function v(e,t,n){let r;if(!t||!("children"in t))r=Uc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Uc(e,t,i):Uc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new W(400,{message:"Login session not found"});e.set("loginSession",i);const s=await He(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new W(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new qt(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??df,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ci(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=pi(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&FA(c,n.continuationScope)){if(!c.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const gp={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function s4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Mo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Xn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Te}))?.app_metadata?.strategy;if(a&&gp[a])return gp[a];const c=t.connections.map(u=>gp[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const V_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?v("div",{className:"inline-flex h-9 items-center",children:v("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):v(Oo,{})},a4=e=>v("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&v("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",v("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var yp={exports:{}};var Cb;function wO(){return Cb||(Cb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(yp)),yp.exports}var kO=wO();const Be=Bw(kO),$O=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=$O(t);return v("span",{className:Be(`uicon-${e}`,n,r)})},SO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Ro="mmo0ln8p",xO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||SO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
|
|
87
87
|
body {
|
|
88
88
|
--primary-color: ${n};
|
|
89
89
|
--primary-hover: ${r};
|