@andco/sdk-script 0.0.2 → 0.0.3
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/andco.js +1 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +9 -1
- package/package.json +2 -2
package/dist/andco.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Andco=(function(we){Object.defineProperty(we,Symbol.toStringTag,{value:"Module"});var Ie,Hr={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Nt(e){return!e&&!Ie?Hr:{lang:e?.lang??Ie?.lang,message:e?.message,abortEarly:e?.abortEarly??Ie?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ie?.abortPipeEarly}}var Br;function Vr(e){return Br?.get(e)}var Wr;function qr(e){return Wr?.get(e)}var Fr;function Jr(e,t){return Fr?.get(e)?.get(t)}function Fe(e){const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function C(e,t,r,n,i){const s=i&&"input"in i?i.input:r.value,o=i?.expected??e.expects??null,a=i?.received??Fe(s),c={kind:e.kind,type:e.type,input:s,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=e.kind==="schema",f=i?.message??e.message??Jr(e.reference,c.lang)??(u?qr(c.lang):null)??n.message??Vr(c.lang);f!==void 0&&(c.message=typeof f=="function"?f(c):f),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function Gr(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Ut(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function G(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Nt())},e}function Lt(e,t){return{kind:"validation",type:"check",reference:Lt,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&C(this,"input",r,n),r}}}function K(e,t){return{kind:"validation",type:"max_length",reference:K,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function he(e,t){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Je(e,t){return{kind:"validation",type:"regex",reference:Je,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&C(this,"format",r,n),r}}}var Kr={abortEarly:!0};function Ct(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Ge(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function k(e,t){return G({kind:"schema",type:"literal",reference:k,expects:Fe(e),async:!1,literal:e,message:t,"~run"(r,n){return Gr(r.value,this.literal)?r.typed=!0:C(this,"type",r,n),r}})}function Ke(e,t){return G({kind:"schema",type:"object",reference:Ke,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ge(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=Ct(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else C(this,"type",r,n);return r}})}function fe(e,t){return G({kind:"schema",type:"optional",reference:fe,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Ge(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function Ze(e,t){return G({kind:"schema",type:"picklist",reference:Ze,expects:Ut(e.map(Fe),"|"),async:!1,options:e,message:t,"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:C(this,"type",r,n),r}})}function x(e,t){return G({kind:"schema",type:"strict_object",reference:x,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ge(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=Ct(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly){for(const s in i)if(!Object.prototype.hasOwnProperty.call(this.entries,s)){C(this,"key",r,n,{input:s,expected:"never",path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]});break}}}else C(this,"type",r,n);return r}})}function Z(e){return G({kind:"schema",type:"string",reference:Z,expects:"string",async:!1,message:e,"~run"(t,r){return typeof t.value=="string"?t.typed=!0:C(this,"type",t,r),t}})}function Dt(e,t,r){return G({kind:"schema",type:"variant",reference:Dt,expects:"Object",async:!1,key:e,options:t,message:r,"~run"(n,i){const s=n.value;if(s&&typeof s=="object"){let o,a=0,c=this.key,u=[];const f=(_,h)=>{for(const d of _.options){if(d.type==="variant")f(d,new Set(h).add(d.key));else{let w=!0,R=0;for(const T of h){const N=d.entries[T];if(T in s?N["~run"]({typed:!1,value:s[T]},Kr).issues:N.type!=="exact_optional"&&N.type!=="optional"&&N.type!=="nullish"){w=!1,c!==T&&(a<R||a===R&&T in s&&!(c in s))&&(a=R,c=T,u=[]),c===T&&u.push(d.entries[T].expects);break}R++}if(w){const T=d["~run"]({value:s},i);(!o||!o.typed&&T.typed)&&(o=T)}}if(o&&!o.issues)break}};if(f(this,new Set([this.key])),o)return o;C(this,"type",n,i,{input:s[c],expected:Ut(u,"|"),path:[{type:"object",origin:"value",input:s,key:c,value:s[c]}]})}else C(this,"type",n,i);return n}})}function te(...e){return G({...e[0],pipe:e,"~run"(t,r){for(const n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}})}function Ye(e,t,r){const n=e["~run"]({value:t},Nt(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}function xt(e){const t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||t==="::1"?!0:/^127(?:\.\d{1,3}){3}$/.test(t)}var Zr=["hash","host","hostname","password","pathname","port","protocol","search","username"],Yr=class extends URL{constructor(e,t,r){try{super(e,t)}catch(n){throw new Error(`${n instanceof Error?n.message:String(n)} — new BetterURL('${e}', '${t}')`)}r&&this.assign(r)}get isLoopback(){return xt(this.hostname)}assign(e){if(e.replace){let{pathname:t}=this;for(const[r,n]of Object.entries(e.replace))t=t.replaceAll(`[${r}]`,encodeURIComponent(String(n)));this.pathname=t}for(const t of Zr){const r=e[t];r!==void 0&&(this[t]=r)}if(e.params)for(const[t,r]of Object.entries(e.params))r===void 0||(r===null?this.searchParams.delete(t):this.searchParams.set(t,r));return this}format(e){if(!e)return this.href;let t="";return e.protocol&&(t+=`${this.protocol}//`),e.hostname&&(t+=this.hostname),e.port&&this.port&&(t+=`:${this.port}`),e.pathname&&(t+=this.pathname),e.search&&(t+=this.search),e.hash&&(t+=this.hash),t}get hashParams(){return new URLSearchParams(this.hash.slice(1))}},Y=class extends Yr{constructor(e,t,r){if(super(e,t,r),!(this.protocol==="https:"||this.protocol==="http:"&&xt(this.hostname))||this.username||this.password||this.hash)throw new TypeError("AndCo URLs require HTTPS, except for loopback development hosts, and cannot contain credentials or a fragment")}},pe="andco:sdk",Hs="https://auth.andco.cl",Bs="https://api.andco.cl",Vs="https://widgets.andco.cl";function Qr(e,t="_"){return new URL(`/oauth/api/versions/${t}`,e).href}var j={protocol:k(pe),version:k(2)},Ws=te(Z(),he(1),K(128),Je(/^[A-Za-z0-9_-]+$/)),W=te(Z(),he(1),K(128),Je(/^[A-Za-z0-9_-]+$/)),re;(function(e){e.BROWSER_UNAVAILABLE="BROWSER_UNAVAILABLE",e.AUTH_CANCELLED="AUTH_CANCELLED",e.AUTH_EXCHANGE_FAILED="AUTH_EXCHANGE_FAILED",e.AUTH_TIMEOUT="AUTH_TIMEOUT",e.INVALID_ENDPOINT_AUTH="INVALID_ENDPOINT_AUTH",e.INVALID_ENDPOINT_API="INVALID_ENDPOINT_API",e.INVALID_ENDPOINT_BUTTON="INVALID_ENDPOINT_BUTTON",e.INVALID_IFRAME="INVALID_IFRAME",e.INVALID_AUTH_MODE="INVALID_AUTH_MODE",e.INVALID_CLIENT_ID="INVALID_CLIENT_ID",e.INVALID_REDIRECT_TO="INVALID_REDIRECT_TO",e.INVALID_CALLBACK="INVALID_CALLBACK",e.INVALID_SCOPE="INVALID_SCOPE",e.INVALID_VERSION="INVALID_VERSION",e.FETCH_UNAVAILABLE="FETCH_UNAVAILABLE",e.POPUP_BLOCKED="POPUP_BLOCKED",e.POPUP_NAVIGATION_FAILED="POPUP_NAVIGATION_FAILED",e.POPUP_TIMEOUT="POPUP_TIMEOUT",e.INTENT_CALLBACK_REQUIRED="INTENT_CALLBACK_REQUIRED",e.SAME_ORIGIN_ENDPOINT="SAME_ORIGIN_ENDPOINT",e.UNSUPPORTED_PRESENTATION="UNSUPPORTED_PRESENTATION",e.UNSUPPORTED_THEME="UNSUPPORTED_THEME",e.UNSUPPORTED_THEME_MODE="UNSUPPORTED_THEME_MODE",e.UNTRUSTED_ORIGIN="UNTRUSTED_ORIGIN",e.WEB_CRYPTO_UNAVAILABLE="WEB_CRYPTO_UNAVAILABLE",e.HANDSHAKE_TIMEOUT="HANDSHAKE_TIMEOUT",e.UNKNOWN_ERROR="UNKNOWN_ERROR"})(re||(re={}));var Xr=class extends Error{constructor(e,t){super(e,t),Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name}static is(e,t){return e instanceof t}},zt=class extends Xr{code;payload;constructor(e,t,r){super(e,r),this.code=e,this.payload=t}};function en(e){const t=new TextEncoder().encode(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function tn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"="),n=atob(r),i=Uint8Array.from(n,s=>s.charCodeAt(0));return new TextDecoder().decode(i)}function Qe(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(!e||typeof e.getRandomValues!="function")throw new zt(re.WEB_CRYPTO_UNAVAILABLE,{missing:["crypto.getRandomValues"]});const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function rn(e,t=Qe()){if(!Ye(W,t).success)throw new TypeError("Invalid AndCo presentation identifier");const r=new Y(e).origin;return`${en(r)}.${t}`}function nn(e){const t=e.indexOf("."),r=e.slice(t+1);if(t<1||t===e.length-1||!Ye(W,r).success)return null;try{const n=tn(e.slice(0,t));return{openerOrigin:new Y(n).origin,presentationId:r}}catch{return null}}var sn=x({...j,type:k("authorization-response"),presentationId:W,authorizationUrl:fe(te(Z(),he(1),K(8192)))}),on=x({...j,type:k("click"),presentationId:fe(W)}),an=Ze(Object.values(re)),cn=x({...j,type:k("error"),error:x({code:an})}),un=x({...j,type:k("init")}),ln=x({...j,type:k("oauth.authorization_code"),presentationId:W,authorizationCode:te(Z(),he(1),K(8192))}),dn=x({...j,type:k("oauth.complete"),presentationId:W}),hn=x({...j,type:k("oauth.dismiss"),presentationId:W}),fn=Ke({...j,type:k("intent.complete"),presentationId:W}),pn=Ke({...j,type:k("intent.dismiss"),presentationId:W}),mn=x({...j,type:k("oauth.error"),presentationId:W,error:x({code:te(Z(),he(1),K(256)),description:fe(te(Z(),K(2048)))})}),yn=x({...j,type:k("ready")}),wn=te(Z(),K(35),Lt(e=>{try{return Intl.getCanonicalLocales(e),!0}catch{return!1}})),_n=Ze(["dark","light","system"]),gn=x({...j,type:k("set-preferences"),themeMode:fe(_n),locale:fe(wn)}),vn=Dt("type",[sn,yn,on,cn,un,gn,ln,dn,hn,mn,fn,pn]);function bn(e){return Ye(vn,e).success}var qs=1780358400,Mt="andco-popup-",A=class qe extends Error{code;status;details;constructor(t,r={}){super(r.message??t,r.cause===void 0?void 0:{cause:r.cause}),this.name="AndcoError",this.code=t,this.status=r.status,this.details=r.details}static from(t,r){if(qe.is(t))return t;const n=t instanceof Error?t.message:void 0;return new qe(r,{message:n,cause:t})}static is(t){return t instanceof qe}},An=class ye extends A{error;response;constructor(t,r){super(t,r),this.name="AndcoAPIError",this.error=t,this.response=r.response}static fromOpenAPIFetch(t,r){const{message:n,details:i}=ye.bodyOf(t),s=new ye(ye.codeOf(t),{response:r,status:ye.statusOf(r),message:n,details:i,cause:t});for(const[o,a]of Object.entries(i??{}))ye.OWN_FIELDS.has(o)||(s[o]=a);return s}static OWN_FIELDS=new Set(["name","message","stack","cause","code","error","status","response","details"]);static codeOf(t){if(t&&typeof t=="object"){const{error:r}=t;if(typeof r=="string")return r}return"request_failed"}static bodyOf(t){if(!t||typeof t!="object")return{message:void 0,details:void 0};const{error:r,message:n,...i}=t,s=Object.keys(i).length>0;return{message:typeof n=="string"?n:void 0,details:s?i:void 0}}static statusOf(t){if(t.type!=="error")return t.status}},l={ok(e){return{data:e,error:null}},fail(e,t={}){return{data:null,error:typeof e=="string"?new A(e,t):e}}},g={BROWSER_REQUIRED:"browser_required",BROWSER_UNAVAILABLE:"browser_unavailable",BROWSER_FORBIDDEN:"browser_forbidden",INVALID_CALLBACK:"invalid_callback",INVALID_CONFIGURATION:"invalid_configuration",HANDSHAKE_TIMEOUT:"handshake_timeout",INVALID_IFRAME:"invalid_iframe",INVALID_INTENT_ID:"invalid_intent_id",INVALID_RESPONSE:"invalid_response",POPUP_BLOCKED:"popup_blocked",POPUP_TIMEOUT:"popup_timeout",PRESENTATION_UNSUPPORTED:"presentation_unsupported",SAME_ORIGIN_ENDPOINT:"same_origin_endpoint",SESSION_MISSING:"session_missing",STORAGE_FAILED:"storage_failed",UNTRUSTED_ORIGIN:"untrusted_origin"},jt=class{#e;constructor(e){this.#e=e}async signIn(e={}){const{oauth:t,presenter:r,store:n}=this.#e,i=this.#e.randomId?this.#e.randomId():Qe(this.#e.crypto),s=await t.createAuthorizationRequest(e);if(s.error)return l.fail(s.error);await this.#e.persistTransaction?.(s.data);const o=new URL(s.data.redirectTo),a=await r.present({url:s.data.authorizationUrl,presentation:e.presentation??"popup",returnTo:o,presentationId:i});if(a.error)return l.fail(a.error);if(!a.data)return l.ok(null);const c=await t.exchangeCallback({callbackUrl:a.data,request:s.data});if(c.error)return l.fail(c.error);const u=await n.set(c.data);return u.error?l.fail(u.error):l.ok(c.data)}async signOut(){return this.#e.store.set(null)}onChange(e){const t=this.#e.store;return t.subscribe(()=>e(t.getSnapshot()??null))}async getSession(){const e=this.#e.store,t=await e.ready;return t.error?l.fail(t.error):l.ok(e.getSnapshot()??null)}async refresh(){const e=this.#e.store;await e.ready;const t=e.getSnapshot();if(!t?.refreshToken)return l.fail(g.SESSION_MISSING);const r=await this.#e.oauth.refresh(t.refreshToken);if(r.error)return l.fail(r.error);const n=await e.set(r.data);return n.error?l.fail(n.error):l.ok(r.data)}},En=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{2,8})*$/,Tn=/^[A-Za-z0-9_-]{1,80}$/,In=/^\d{10}$/,Sn=class Ot{clientId;endpoints;apiVersion;redirectTo;locale;theme;themeMode;initialScopes;allowedPopupOrigins;constructor(t){if(!Tn.test(t.clientId??""))throw new A(g.INVALID_CONFIGURATION,{message:"clientId is missing or malformed"});if(this.clientId=t.clientId,this.endpoints=Object.freeze({auth:new Y(t.endpointAuth??"https://auth.andco.cl"),api:new Y(t.endpointApi??"https://api.andco.cl"),widget:new Y(t.endpointWidget??"https://widgets.andco.cl")}),this.apiVersion=String(t.apiVersion??"_"),this.apiVersion!=="_"&&!In.test(this.apiVersion))throw new A(g.INVALID_CONFIGURATION,{message:"apiVersion must be `_` or a ten-digit Unix timestamp"});if(this.redirectTo=t.redirectTo===void 0?void 0:new Y(t.redirectTo),this.locale=t.locale??"es",!En.test(this.locale))throw new A(g.INVALID_CONFIGURATION,{message:"locale must be a BCP 47 tag"});this.theme=t.theme??"base",this.themeMode=t.themeMode??"system",this.initialScopes=Object.freeze([...new Set(t.initialScopes??[])]);const r=t.allowedPopupOrigins??[];this.allowedPopupOrigins=Object.freeze(new Set([this.endpoints.widget.origin,...r.map(n=>new Y(n).origin)]))}static from(t){return new Ot(t)}with(t){return Ot.from({...this.toJSON(),...t})}authURL(t){const r=this.endpoints.auth,n=new URL(r.href);return n.pathname=`${r.pathname.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,n}apiURL(){return new URL(`/oauth/api/versions/${this.apiVersion}/`,this.endpoints.api)}widgetURL(t,r="button"){return new URL(`/embedded/versions/${t}/${r}`,this.endpoints.widget)}allowsPopupOrigin(t){return this.allowedPopupOrigins.has(t)}toJSON(){return{clientId:this.clientId,endpointAuth:this.endpoints.auth.href,endpointApi:this.endpoints.api.href,endpointWidget:this.endpoints.widget.href,apiVersion:this.apiVersion,redirectTo:this.redirectTo?.href,locale:this.locale,theme:this.theme,themeMode:this.themeMode,initialScopes:[...this.initialScopes],allowedPopupOrigins:[...this.allowedPopupOrigins]}}},Fs=30;function $t(e,t=Math.floor(Date.now()/1e3)){return e.expiresAt<=t+30}function Xe(e,t){const r=e.resourceAccessTokens;if(r){if(r[t])return r[t]??null}else return e.accessToken;try{return r[new URL(t).href]??e.accessToken}catch{return e.accessToken}}function Pn(e){return{accessTokenFor:async t=>Xe(e,t)}}function Rn(e){return typeof e.accessTokenFor=="function"}function kn(e,t,r,n,i){const s=n.pollIntervalMs??1e3;if(!Number.isSafeInteger(s)||s<100)throw new TypeError("Invalid event polling interval");if(typeof n.onError!="function")throw new TypeError("An event error handler is required");const o=`v1:${i.kind}:${i.id.toLowerCase()}:`,a=h=>{if(typeof h!="string"||!h.startsWith(o)||!/^(0|[1-9][0-9]{0,18})$/.test(h.slice(o.length)))throw new TypeError("invalid_or_unsupported_event_cursor");const d=BigInt(h.slice(o.length));if(d>9223372036854775807n)throw new TypeError("invalid_or_unsupported_event_cursor");return d},c=new AbortController;let u=n.after,f;const _=async()=>{if(c.signal.aborted)return;let h=s;try{let d=u===void 0?0n:a(u);const w=await e(u,c.signal);if(c.signal.aborted)return;if(!w||!Array.isArray(w.events)||w.events.length>100||typeof w.has_more!="boolean"||!Ht(w.server_time))throw new TypeError("invalid_event_response");const R=a(w.next_cursor),T=new Map;let N=-1n;const U=w.events.map(y=>{if(!y||y.version!==1||typeof y.id!="string"||!y.id||y.id.length>128||typeof y.type!="string"||!y.type||!y.payload||typeof y.payload!="object"||Array.isArray(y.payload)||!Ht(y.occurred_at))throw new TypeError("invalid_event_response");const I=a(y.cursor);if(I===0n||I<N)throw new TypeError("invalid_event_response");const b=JSON.stringify(y);if(T.has(y.id)&&T.get(y.id)!==b||I===N&&T.get(y.id)!==b)throw new TypeError("invalid_event_response");return T.set(y.id,b),N=I,I});if(w.events.length?R!==U.at(-1):R!==d||w.has_more)throw new TypeError("invalid_event_response");if(w.has_more&&R<=d)throw new TypeError("invalid_event_response");for(let y=0;y<w.events.length;y++){if(c.signal.aborted)return;const I=w.events[y],b=U[y];if(b<=d)continue;const le=t(I);le!==null&&await r(le),u=I.cursor,d=b}u===void 0&&(u=w.next_cursor),w.has_more&&(h=0)}catch(d){if(c.signal.aborted)return;try{await n.onError(d)}catch{c.abort()}}finally{c.signal.aborted||(f=setTimeout(()=>{_()},h))}};return _(),{unsubscribe(){c.abort(),clearTimeout(f)},get checkpoint(){return u}}}function Ht(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e))}var On=/\{[^{}]+\}/g,Nn=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Un(){return Math.random().toString(36).slice(2,11)}function Ln(e){let{baseUrl:t="",Request:r=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:s,pathSerializer:o,headers:a,requestInitExt:c=void 0,...u}={...e};c=Nn()?c:void 0,t=Ft(t);const f=[];async function _(h,d){const{baseUrl:w,fetch:R=n,Request:T=r,headers:N,params:U={},parseAs:y="json",querySerializer:I,bodySerializer:b=s??Dn,pathSerializer:le,body:He,middleware:Tt=[],...It}=d||{};let St=t;w&&(St=Ft(w)??t);let Pt=typeof i=="function"?i:Wt(i);I&&(Pt=typeof I=="function"?I:Wt({...typeof i=="object"?i:{},...I}));const Mr=le||o||Cn,Rt=He===void 0?void 0:b(He,qt(a,N,U.header)),js=qt(Rt===void 0||Rt instanceof FormData?{}:{"Content-Type":"application/json"},a,N,U.header),X=[...f,...Tt],$s={redirect:"follow",...u,...It,body:Rt,headers:js};let Be,Ve,ee=new T(xn(h,{baseUrl:St,params:U,querySerializer:Pt,pathSerializer:Mr}),$s),S;for(const L in It)L in ee||(ee[L]=It[L]);if(X.length){Be=Un(),Ve=Object.freeze({baseUrl:St,fetch:R,parseAs:y,querySerializer:Pt,bodySerializer:b,pathSerializer:Mr});for(const L of X)if(L&&typeof L=="object"&&typeof L.onRequest=="function"){const P=await L.onRequest({request:ee,schemaPath:h,params:U,options:Ve,id:Be});if(P)if(P instanceof T)ee=P;else if(P instanceof Response){S=P;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!S){try{S=await R(ee,c)}catch(L){let P=L;if(X.length)for(let de=X.length-1;de>=0;de--){const We=X[de];if(We&&typeof We=="object"&&typeof We.onError=="function"){const Te=await We.onError({request:ee,error:P,schemaPath:h,params:U,options:Ve,id:Be});if(Te){if(Te instanceof Response){P=void 0,S=Te;break}if(Te instanceof Error){P=Te;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(P)throw P}if(X.length)for(let L=X.length-1;L>=0;L--){const P=X[L];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const de=await P.onResponse({request:ee,response:S,schemaPath:h,params:U,options:Ve,id:Be});if(de){if(!(de instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");S=de}}}}const jr=S.headers.get("Content-Length");if(S.status===204||ee.method==="HEAD"||jr==="0"&&!S.headers.get("Transfer-Encoding")?.includes("chunked"))return S.ok?{data:void 0,response:S}:{error:void 0,response:S};if(S.ok)return{data:await(async()=>{if(y==="stream")return S.body;if(y==="json"&&!jr){const P=await S.text();return P?JSON.parse(P):void 0}return await S[y]()})(),response:S};let kt=await S.text();try{kt=JSON.parse(kt)}catch{}return{error:kt,response:S}}return{request(h,d,w){return _(d,{...w,method:h.toUpperCase()})},GET(h,d){return _(h,{...d,method:"GET"})},PUT(h,d){return _(h,{...d,method:"PUT"})},POST(h,d){return _(h,{...d,method:"POST"})},DELETE(h,d){return _(h,{...d,method:"DELETE"})},OPTIONS(h,d){return _(h,{...d,method:"OPTIONS"})},HEAD(h,d){return _(h,{...d,method:"HEAD"})},PATCH(h,d){return _(h,{...d,method:"PATCH"})},TRACE(h,d){return _(h,{...d,method:"TRACE"})},use(...h){for(const d of h)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d||"onError"in d))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");f.push(d)}},eject(...h){for(const d of h){const w=f.indexOf(d);w!==-1&&f.splice(w,1)}}}}function Se(e,t,r){if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${r?.allowReserved===!0?t:encodeURIComponent(t)}`}function Bt(e,t,r){if(!t||typeof t!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[r.style]||"&";if(r.style!=="deepObject"&&r.explode===!1){for(const a in t)n.push(a,r.allowReserved===!0?t[a]:encodeURIComponent(t[a]));const o=n.join(",");switch(r.style){case"form":return`${e}=${o}`;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return o}}for(const o in t){const a=r.style==="deepObject"?`${e}[${o}]`:o;n.push(Se(a,t[o],r))}const s=n.join(i);return r.style==="label"||r.style==="matrix"?`${i}${s}`:s}function Vt(e,t,r){if(!Array.isArray(t))return"";if(r.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[r.style]||",",o=(r.allowReserved===!0?t:t.map(a=>encodeURIComponent(a))).join(s);switch(r.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return`${e}=${o}`}}const n={simple:",",label:".",matrix:";"}[r.style]||"&",i=[];for(const s of t)r.style==="simple"||r.style==="label"?i.push(r.allowReserved===!0?s:encodeURIComponent(s)):i.push(Se(e,s,r));return r.style==="label"||r.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Wt(e){return function(r){const n=[];if(r&&typeof r=="object")for(const i in r){const s=r[i];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;n.push(Vt(i,s,{style:"form",explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof s=="object"){n.push(Bt(i,s,{style:"deepObject",explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(Se(i,s,e))}}return n.join("&")}}function Cn(e,t){let r=e;for(const n of e.match(On)??[]){let i=n.substring(1,n.length-1),s=!1,o="simple";if(i.endsWith("*")&&(s=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(o="label",i=i.substring(1)):i.startsWith(";")&&(o="matrix",i=i.substring(1)),!t||t[i]===void 0||t[i]===null)continue;const a=t[i];if(Array.isArray(a)){r=r.replace(n,Vt(i,a,{style:o,explode:s}));continue}if(typeof a=="object"){r=r.replace(n,Bt(i,a,{style:o,explode:s}));continue}if(o==="matrix"){r=r.replace(n,`;${Se(i,a)}`);continue}r=r.replace(n,o==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return r}function Dn(e,t){return e instanceof FormData?e:t&&(t.get instanceof Function?t.get("Content-Type")??t.get("content-type"):t["Content-Type"]??t["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(e).toString():JSON.stringify(e)}function xn(e,t){let r=`${t.baseUrl}${e}`;t.params?.path&&(r=t.pathSerializer(r,t.params.path));let n=t.querySerializer(t.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(r+=`?${n}`),r}function qt(...e){const t=new Headers;for(const r of e){if(!r||typeof r!="object")continue;const n=r instanceof Headers?r.entries():Object.entries(r);for(const[i,s]of n)if(s===null)t.delete(i);else if(Array.isArray(s))for(const o of s)t.append(i,o);else s!==void 0&&t.set(i,s)}return t}function Ft(e){return e.endsWith("/")?e.substring(0,e.length-1):e}function zn(e){return((t,r)=>{const n=e??globalThis.fetch;return typeof n!="function"?Promise.reject(new zt(re.FETCH_UNAVAILABLE,{missing:["fetch"]})):n(t,r)})}function Mn(e={}){const t=String(e.apiVersion??"_");if(t!=="_"&&!/^\d{10}$/.test(t))throw new TypeError("apiVersion must be `_` or a Unix timestamp in seconds");const r=new Y(e.endpoint??"https://api.andco.cl"),n=Ln({baseUrl:Qr(r,t),fetch:e.fetch??zn()});return n.use({async onRequest({request:i}){let s;return typeof e.accessToken=="function"?s=await e.accessToken():s=e.accessToken,s&&i.headers.set("Authorization",`Bearer ${s}`),i}}),n}var jn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$n=/^[A-Za-z0-9._:-]{1,128}$/,Jt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async create(e,t,r={}){const n=r.idempotencyKey??Qe(this.#t);if(!$n.test(n))return l.fail(g.INVALID_CONFIGURATION,{message:"malformed Idempotency-Key"});let i;try{({data:i}=await this.#e.http.POST("/intents",{params:{header:{"Idempotency-Key":n}},body:{...t,type:e}}).throwOnError())}catch(s){return l.fail(s)}return i?.type!==e?l.fail(g.INVALID_RESPONSE,{message:`expected a ${e} intent`}):l.ok(i)}async get(e){const t=et(e);if(t)return l.fail(t);try{const{data:r}=await this.#e.http.GET("/intents/{intent_id}",{params:{path:{intent_id:e}}}).throwOnError();return l.ok(r)}catch(r){return l.fail(r)}}async execute(e){const t=et(e);if(t)return l.fail(t);try{return await this.#e.http.POST("/intents/{intent_id}/execute",{params:{path:{intent_id:e}}}).throwOnError(),l.ok(void 0)}catch(r){return l.fail(r)}}async events(e,t,r){const n=et(e);if(n)return l.fail(n);try{const{data:i}=await this.#e.http.GET("/intents/{intent_id}/events",{params:{path:{intent_id:e},query:{after:t,limit:100}},signal:r}).throwOnError();return l.ok(i)}catch(i){return l.fail(i)}}subscribe(e,t,r,n,i){const s=kn(async(o,a)=>{const c=await t(o,a);if(c.error)throw c.error;return c.data},r,async o=>{await n(o),i.onCheckpoint?.(o.cursor)},{...i.after===void 0?{}:{after:i.after},onError:i.onError,...i.pollIntervalMs===void 0?{}:{pollIntervalMs:i.pollIntervalMs}},e);return()=>s.unsubscribe()}};function et(e){return jn.test(e)?null:new A(g.INVALID_INTENT_ID,{message:`${e} is not a valid identifier`})}var tt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(tt="oauth4webapi/v3.8.8");function ne(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var z="ERR_INVALID_ARG_VALUE",$="ERR_INVALID_ARG_TYPE";function v(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}var H=Symbol(),Pe=Symbol(),rt=Symbol(),q=Symbol(),F=Symbol(),Hn=new TextEncoder,Bn=new TextDecoder;function nt(e){return typeof e=="string"?Hn.encode(e):Bn.decode(e)}var it;Uint8Array.prototype.toBase64?it=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):it=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var st;Uint8Array.fromBase64?st=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw v("The input to be decoded is not correctly encoded.",z,t)}}:st=e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch(t){throw v("The input to be decoded is not correctly encoded.",z,t)}};function Re(e){return typeof e=="string"?st(e):it(e)}var _e=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=mt,Error.captureStackTrace?.(this,this.constructor)}},ot=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,t?.code&&(this.code=t?.code),Error.captureStackTrace?.(this,this.constructor)}};function p(e,t,r){return new ot(e,{code:t,cause:r})}function ke(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function ge(e){ne(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(e??{});if(tt&&!t.has("user-agent")&&t.set("user-agent",tt),t.has("authorization"))throw v('"options.headers" must not include the "authorization" header name',z);return t}function Gt(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw v('"options.signal" must return or be an instance of AbortSignal',$);return t}}function ie(e,t,r,n,i){try{if(typeof e!="number"||!Number.isFinite(e))throw v(`${r} must be a number`,$,i);if(e>0)return;if(t){if(e!==0)throw v(`${r} must be a non-negative number`,z,i);return}throw v(`${r} must be a positive number`,z,i)}catch(s){throw n?p(s.message,n,i):s}}function E(e,t,r,n){try{if(typeof e!="string")throw v(`${t} must be a string`,$,n);if(e.length===0)throw v(`${t} must not be empty`,z,n)}catch(i){throw r?p(i.message,r,n):i}}function Kt(e){Wn(e,"application/json")}function Vn(e,...t){let r='"response" content-type must be ';if(t.length>2){const n=t.pop();r+=`${t.join(", ")}, or ${n}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return p(r,mr,e)}function Wn(e,t){if(Ue(e)!==t)throw Vn(e,t)}function Zt(){return Re(crypto.getRandomValues(new Uint8Array(32)))}function qn(){return Zt()}function Fn(){return Zt()}async function Jn(e){return E(e,"codeVerifier"),Re(await crypto.subtle.digest("SHA-256",nt(e)))}function Oe(e){const t=e?.[Pe];return typeof t=="number"&&Number.isFinite(t)?t:0}function at(e){const t=e?.[rt];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Yt(){return Math.floor(Date.now()/1e3)}function B(e){if(typeof e!="object"||e===null)throw v('"as" must be an object',$);E(e.issuer,'"as.issuer"')}function V(e){if(typeof e!="object"||e===null)throw v('"client" must be an object',$);E(e.client_id,'"client.client_id"')}function Qt(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Xt(e){return E(e,'"clientSecret"'),(t,r,n,i)=>{n.set("client_id",r.client_id),n.set("client_secret",e)}}function er(e){return E(e,'"clientSecret"'),(t,r,n,i)=>{const s=Qt(r.client_id),o=Qt(e),a=btoa(`${s}:${o}`);i.set("authorization",`Basic ${a}`)}}function Gn(){return(e,t,r,n)=>{r.set("client_id",t.client_id)}}var Kn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function tr(e,t){if(t&&e.protocol!=="https:")throw p("only requests to HTTPS are allowed",yr,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw p("only HTTP and HTTPS requests are allowed",wr,e)}function rr(e,t,r,n){let i;if(typeof e!="string"||!(i=Kn(e)))throw p(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Si:Pi,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return tr(i,n),i}function ve(e,t,r,n){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?rr(e.mtls_endpoint_aliases[t],t,r,n):rr(e[t],t,r,n)}async function Zn(e,t,r,n,i){B(e),V(t);const s=ve(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,i?.[H]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=ge(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(lt(i.DPoP),await i.DPoP.addProof(s,a,"POST"));const c=await dt(e,t,r,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}function Yn(e){return e instanceof ct?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof Ne?e.error==="use_dpop_nonce":!1}var Ne=class extends Error{cause;code;error;status;error_description;response;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ei,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:t.response}),Error.captureStackTrace?.(this,this.constructor)}},nr=class extends Error{cause;code;error;error_description;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ti,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=t.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},ct=class extends Error{cause;code;response;status;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ai,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Qn=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),Xn=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),ei=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),ti=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function ri(e){if(!ne(e,Response))throw v('"response" must be an instance of Response',$);const t=e.headers.get("www-authenticate");if(t===null)return;const r=[];let n=t;for(;n;){let i=n.match(Qn);const s=i?.[1].toLowerCase();if(!s)return;const o=n.substring(i[0].length);if(o&&!o.match(/^[\s,]/))return;const a=o.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;const u={};let f;if(c)for(;n;){let h,d;if(i=n.match(Xn)){[,h,d,n]=i,d.includes("\\")&&(d=d.replace(/\\([\s\S])/g,"$1")),u[h.toLowerCase()]=d;continue}if(i=n.match(ei)){[,h,d,n]=i,u[h.toLowerCase()]=d;continue}if(i=n.match(ti)){if(Object.keys(u).length)break;[,f,n]=i;break}return}else n=o||void 0;const _={scheme:s,parameters:u};f&&(_.token68=f),r.push(_)}if(r.length)return r}async function ni(e,t,r){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,201,"Pushed Authorization Request Endpoint"),be(r);const n=await Me(r);E(n.request_uri,'"response" body "request_uri" property',m,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',m,{body:n}),n.expires_in=i,n}async function ii(e){if(e.status>399&&e.status<500){be(e),Kt(e);try{const t=await e.clone().json();if(ke(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ut(e,t,r){if(e.status!==t){ar(e);let n;throw(n=await ii(e))?(await e.body?.cancel(),new Ne("server responded with an error in the response body",{cause:n,response:e})):p(`"response" is not a conform ${r} response (unexpected HTTP status code)`,yt,e)}}function lt(e){if(!pt.has(e))throw v('"options.DPoP" is not a valid DPoPHandle',z)}async function si(e,t,r,n,i,s){if(E(e,'"accessToken"'),!(r instanceof URL))throw v('"url" must be an instance of URL',$);tr(r,s?.[H]!==!0),n=ge(n),s?.DPoP&&(lt(s.DPoP),await s.DPoP.addProof(r,n,t.toUpperCase(),e)),n.set("authorization",`${n.has("dpop")?"DPoP":"Bearer"} ${e}`);const o=await(s?.[q]||fetch)(r.href,{duplex:ne(i,ReadableStream)?"half":void 0,body:i,headers:Object.fromEntries(n.entries()),method:t,redirect:"manual",signal:Gt(r,s?.signal)});return s?.DPoP?.cacheNonce(o,r),o}async function oi(e,t,r,n){B(e),V(t);const i=ve(e,"userinfo_endpoint",t.use_mtls_endpoint_aliases,n?.[H]!==!0),s=ge(n?.headers);return t.userinfo_signed_response_alg?s.set("accept","application/jwt"):(s.set("accept","application/json"),s.append("accept","application/jwt")),si(r,"GET",i,s,null,{...n,[Pe]:Oe(t)})}var ir=Symbol();function Ue(e){return e.headers.get("content-type")?.split(";")[0]}async function ai(e,t,r,n,i){if(B(e),V(t),!ne(n,Response))throw v('"response" must be an instance of Response',$);if(ar(n),n.status!==200)throw p('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)',yt,n);be(n);let s;if(Ue(n)==="application/jwt"){const{claims:o,jwt:a}=await gr(await n.text(),vr.bind(void 0,t.userinfo_signed_response_alg,e.userinfo_signing_alg_values_supported,void 0),Oe(t),at(t),i?.[F]).then(li.bind(void 0,t.client_id)).then(di.bind(void 0,e));or.set(n,a),s=o}else{if(t.userinfo_signed_response_alg)throw p("JWT UserInfo Response expected",Ii,n);s=await Me(n)}switch(E(s.sub,'"response" body "sub" property',m,{body:s}),r){case ir:break;default:if(E(r,'"expectedSubject"'),s.sub!==r)throw p('unexpected "response" body "sub" property value',_r,{expected:r,body:s,attribute:"sub"})}return s}async function dt(e,t,r,n,i,s,o){return await r(e,t,i,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(o?.[q]||fetch)(n.href,{body:i,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Gt(n,o?.signal)})}async function ht(e,t,r,n,i,s){const o=ve(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[H]!==!0);i.set("grant_type",n);const a=ge(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(lt(s.DPoP),await s.DPoP.addProof(o,a,"POST"));const c=await dt(e,t,r,o,i,a,s);return s?.DPoP?.cacheNonce(c,o),c}async function ci(e,t,r,n,i){B(e),V(t),E(n,'"refreshToken"');const s=new URLSearchParams(i?.additionalParameters);return s.set("refresh_token",n),ht(e,t,r,"refresh_token",s,i)}var sr=new WeakMap,or=new WeakMap;function ft(e){if(!e.id_token)return;const t=sr.get(e);if(!t)throw v('"ref" was already garbage collected or did not resolve from the proper sources',z);return t}async function Le(e,t,r,n,i,s){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,200,"Token Endpoint"),be(r);const o=await Me(r);if(E(o.access_token,'"response" body "access_token" property',m,{body:o}),E(o.token_type,'"response" body "token_type" property',m,{body:o}),o.token_type=o.token_type.toLowerCase(),o.expires_in!==void 0){let a=typeof o.expires_in!="number"?parseFloat(o.expires_in):o.expires_in;ie(a,!0,'"response" body "expires_in" property',m,{body:o}),o.expires_in=a}if(o.refresh_token!==void 0&&E(o.refresh_token,'"response" body "refresh_token" property',m,{body:o}),o.scope!==void 0&&typeof o.scope!="string")throw p('"response" body "scope" property must be a string',m,{body:o});if(o.id_token!==void 0){E(o.id_token,'"response" body "id_token" property',m,{body:o});const a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ie(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);const{claims:c,jwt:u}=await yi(e,t,o.id_token,a,i);_i(t,c),wi(c),or.set(r,u),sr.set(o,c)}if(s?.[o.token_type]!==void 0)s[o.token_type](r,o);else if(o.token_type!=="dpop"&&o.token_type!=="bearer")throw new _e("unsupported `token_type` value",{cause:{body:o}});return o}function ar(e){let t;if(t=ri(e))throw new ct("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function ui(e,t,r,n){return Le(e,t,r,void 0,n?.[F],n?.recognizedTokenTypes)}function li(e,t){return t.claims.aud!==void 0?cr(e,t):t}function cr(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"});return t}function di(e,t){return t.claims.iss!==void 0?ur(e,t):t}function ur(e,t){const r=e[br]?.(t)??e.issuer;if(t.claims.iss!==r)throw p('unexpected JWT "iss" (issuer) claim value',se,{expected:r,claims:t.claims,claim:"iss"});return t}var pt=new WeakSet;function hi(e){return pt.add(e),e}var lr=Symbol();async function fi(e,t,r,n,i,s,o){if(B(e),V(t),!pt.has(n))throw v('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',z);E(i,'"redirectUri"');const a=oe(n,"code");if(!a)throw p('no authorization code in "callbackParameters"',m);const c=new URLSearchParams(o?.additionalParameters);return c.set("redirect_uri",i),c.set("code",a),s!==lr&&(E(s,'"codeVerifier"'),c.set("code_verifier",s)),ht(e,t,r,"authorization_code",c,o)}var dr={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function pi(e,t){for(const r of e)if(t.claims[r]===void 0)throw p(`JWT "${r}" (${dr[r]}) claim missing`,m,{claims:t.claims});return t}function mi(e,t){if(typeof t.claims[e]!="string")throw p(`unexpected JWT "${e}" (${dr[e]}) claim type`,m,{claims:t.claims});return t}function yi(e,t,r,n,i){return gr(r,vr.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Oe(t),at(t),i).then(pi.bind(void 0,["aud","exp","iat","iss","sub",...n])).then(ur.bind(void 0,e)).then(cr.bind(void 0,t.client_id)).then(mi.bind(void 0,"sub"))}function hr(e,t){if(t===De)return t;const r=t===void 0;return r&&(t=e.default_max_age),t===void 0?De:(ie(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function wi(e){e.auth_time!==void 0&&ie(e.auth_time,!0,'ID Token "auth_time" (authentication time)',m,{claims:e})}function fr(e,t,r){if(r===De)return;const n=Yt()+Oe(e),i=at(e);if(t.auth_time+r<n-i)throw p("too much time has elapsed since the last End-User authentication",ze,{claims:t,now:n,tolerance:i,claim:"auth_time"})}function pr(e,t){const r=t===Ce?void 0:t;if(e.nonce!==r)throw p('unexpected ID Token "nonce" claim value',se,{expected:r,claims:e,claim:"nonce"})}function _i(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw p('ID Token "aud" (audience) claim includes additional untrusted audiences',se,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw p('unexpected ID Token "azp" (authorized party) claim value',se,{expected:e.client_id,claims:t,claim:"azp"})}}var Ce=Symbol(),De=Symbol();async function gi(e,t,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?vi(e,t,r,n.expectedNonce,n.maxAge,n[F],n.recognizedTokenTypes):bi(e,t,r,n?.maxAge,n?.[F],n?.recognizedTokenTypes)}async function vi(e,t,r,n,i,s,o){const a=[];switch(n){case void 0:n=Ce;break;case Ce:break;default:E(n,'"expectedNonce" argument'),a.push("nonce")}i=hr(t,i),i!==De&&a.push("auth_time");const c=await Le(e,t,r,a,s,o);E(c.id_token,'"response" body "id_token" property',m,{body:c});const u=ft(c);return fr(t,u,i),pr(u,n),c}async function bi(e,t,r,n,i,s){const o=await Le(e,t,r,void 0,i,s),a=ft(o);return a&&(fr(t,a,hr(t,n)),pr(a,Ce)),o}var Ai="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ei="OAUTH_RESPONSE_BODY_ERROR",mt="OAUTH_UNSUPPORTED_OPERATION",Ti="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Ii="OAUTH_JWT_USERINFO_EXPECTED",xe="OAUTH_PARSE_ERROR",m="OAUTH_INVALID_RESPONSE",mr="OAUTH_RESPONSE_IS_NOT_JSON",yt="OAUTH_RESPONSE_IS_NOT_CONFORM",yr="OAUTH_HTTP_REQUEST_FORBIDDEN",wr="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",ze="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",se="OAUTH_JWT_CLAIM_COMPARISON_FAILED",_r="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Si="OAUTH_MISSING_SERVER_METADATA",Pi="OAUTH_INVALID_SERVER_METADATA";function be(e){if(e.bodyUsed)throw v('"response" body has been used already',z)}async function gr(e,t,r,n,i){let{0:s,1:o,length:a}=e.split(".");if(a===5)if(i!==void 0)e=await i(e),{0:s,1:o,length:a}=e.split(".");else throw new _e("JWE decryption is not configured",{cause:e});if(a!==3)throw p("Invalid JWT",m,e);let c;try{c=JSON.parse(nt(Re(s)))}catch(_){throw p("failed to parse JWT Header body as base64url encoded JSON",xe,_)}if(!ke(c))throw p("JWT Header must be a top level object",m,e);if(t(c),c.crit!==void 0)throw new _e('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(nt(Re(o)))}catch(_){throw p("failed to parse JWT Payload body as base64url encoded JSON",xe,_)}if(!ke(u))throw p("JWT Payload must be a top level object",m,e);const f=Yt()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw p('unexpected JWT "exp" (expiration time) claim type',m,{claims:u});if(u.exp<=f-n)throw p('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',ze,{claims:u,now:f,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw p('unexpected JWT "iat" (issued at) claim type',m,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw p('unexpected JWT "iss" (issuer) claim type',m,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw p('unexpected JWT "nbf" (not before) claim type',m,{claims:u});if(u.nbf>f+n)throw p('unexpected JWT "nbf" (not before) claim value',ze,{claims:u,now:f,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw p('unexpected JWT "aud" (audience) claim type',m,{claims:u});return{header:c,claims:u,jwt:e}}async function Ri(e){if(e.bodyUsed)throw v("form_post Request instances must contain a readable body",z,{cause:e});return e.text()}async function ki(e){if(e.method!=="POST")throw v("form_post responses are expected to use the POST method",z,{cause:e});if(Ue(e)!=="application/x-www-form-urlencoded")throw v("form_post responses are expected to use the application/x-www-form-urlencoded content-type",z,{cause:e});return Ri(e)}function vr(e,t,r,n){if(e!==void 0){if(typeof e=="string"?n.alg!==e:!e.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:r,reason:"default value"});return}throw p('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function oe(e,t){const{0:r,length:n}=e.getAll(t);if(n>1)throw p(`"${t}" parameter must be provided only once`,m);return r}var Oi=Symbol(),Ni=Symbol();function Ui(e,t,r,n){if(B(e),V(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw v('"parameters" must be an instance of URLSearchParams, or URL',$);if(oe(r,"response"))throw p('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',m,{parameters:r});const i=oe(r,"iss"),s=oe(r,"state");if(!i&&e.authorization_response_iss_parameter_supported)throw p('response parameter "iss" (issuer) missing',m,{parameters:r});if(i&&i!==e.issuer)throw p('unexpected "iss" (issuer) response parameter value',m,{expected:e.issuer,parameters:r});switch(n){case void 0:case Ni:if(s!==void 0)throw p('unexpected "state" response parameter encountered',m,{expected:void 0,parameters:r});break;case Oi:break;default:if(E(n,'"expectedState" argument'),s!==n)throw p(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',m,{expected:n,parameters:r})}if(oe(r,"error"))throw new nr("authorization response from the server is an error",{cause:r});const o=oe(r,"id_token"),a=oe(r,"token");if(o!==void 0||a!==void 0)throw new _e("implicit and hybrid flows are not supported");return hi(new URLSearchParams(r))}async function Li(e,t,r,n,i){B(e),V(t);const s=ve(e,"device_authorization_endpoint",t.use_mtls_endpoint_aliases,i?.[H]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=ge(i?.headers);return a.set("accept","application/json"),dt(e,t,r,s,o,a,i)}async function Ci(e,t,r){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,200,"Device Authorization Endpoint"),be(r);const n=await Me(r);E(n.device_code,'"response" body "device_code" property',m,{body:n}),E(n.user_code,'"response" body "user_code" property',m,{body:n}),E(n.verification_uri,'"response" body "verification_uri" property',m,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',m,{body:n}),n.expires_in=i,n.verification_uri_complete!==void 0&&E(n.verification_uri_complete,'"response" body "verification_uri_complete" property',m,{body:n}),n.interval!==void 0&&ie(n.interval,!1,'"response" body "interval" property',m,{body:n}),n}async function Di(e,t,r,n,i){B(e),V(t),E(n,'"deviceCode"');const s=new URLSearchParams(i?.additionalParameters);return s.set("device_code",n),ht(e,t,r,"urn:ietf:params:oauth:grant-type:device_code",s,i)}async function xi(e,t,r,n){return Le(e,t,r,void 0,n?.[F],n?.recognizedTokenTypes)}async function Me(e,t=Kt){let r;try{r=await e.json()}catch(n){throw t(e),p('failed to parse "response" body as JSON',xe,n)}if(!ke(r))throw p('"response" body must be a top level object',m,{body:r});return r}var br=Symbol(),ae,Ar;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ar="openid-client/v6.8.8",ae={"user-agent":Ar});var D=e=>wt.get(e),wt;function zi(e){if(e!==void 0)return Xt(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Er(n.client_secret,'"metadata.client_secret"'),o=Xt(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Er(e,t){if(typeof e!="string")throw J(`${t} must be a string`,je);if(e.length===0)throw J(`${t} must not be empty`,Ae)}function Mi(e){if(e!==void 0)return er(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Er(n.client_secret,'"metadata.client_secret"'),o=er(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Tr(){return Gn()}var ji=ir,_t=q,Ae="ERR_INVALID_ARG_VALUE",je="ERR_INVALID_ARG_TYPE";function J(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}function $i(e){return Jn(e)}function Hi(){return qn()}function Bi(){return Fn()}var gt=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=t?.code,Error.captureStackTrace?.(this,this.constructor)}},Js=new TextDecoder;function O(e,t,r){return new gt(e,{cause:t,code:r})}function M(e){if(e instanceof TypeError||e instanceof gt||e instanceof Ne||e instanceof nr||e instanceof ct)throw e;if(e instanceof ot)switch(e.code){case yr:throw O("only requests to HTTPS are allowed",e,e.code);case wr:throw O("only requests to HTTP or HTTPS are allowed",e,e.code);case yt:throw O("unexpected HTTP response status code",e.cause,e.code);case mr:throw O("unexpected response content-type",e.cause,e.code);case xe:throw O("parsing error occured",e,e.code);case m:throw O("invalid response encountered",e,e.code);case se:throw O("unexpected JWT claim value encountered",e,e.code);case _r:throw O("unexpected JSON attribute value encountered",e,e.code);case ze:throw O("JWT timestamp claim value failed validation",e,e.code);default:throw O(e.message,e,e.code)}if(e instanceof _e)throw O("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw O("runtime operation error",e,mt);case"NotSupportedError":throw O("runtime unsupported operation",e,mt);case"TimeoutError":throw O("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw O("operation aborted",e,"OAUTH_ABORT")}throw new gt("something went wrong",{cause:e})}function Vi(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Wi(e){Object.defineProperties(e,Vi(e))}var qi=Symbol(),$e=class{constructor(e,t,r,n){if(typeof t!="string"||!t.length)throw J('"clientId" must be a non-empty string',je);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&t!==r.client_id)throw J('"clientId" and "metadata.client_id" must be the same',Ae);const i={...structuredClone(r),client_id:t};i[Pe]=r?.[Pe]??0,i[rt]=r?.[rt]??30;let s;n?s=n:typeof i.client_secret=="string"&&i.client_secret.length?s=zi(i.client_secret):s=Tr();let o=Object.freeze(i);const a=structuredClone(e);qi in e&&(a[br]=({claims:{tid:u}})=>e.issuer.replace("{tenantid}",u));let c=Object.freeze(a);wt||=new WeakMap,wt.set(this,{__proto__:null,as:c,c:o,auth:s,tlsOnly:!0,timeout:30,jwksCache:{}})}serverMetadata(){const e=structuredClone(D(this).as);return Wi(e),e}clientMetadata(){return structuredClone(D(this).c)}get timeout(){return D(this).timeout}set timeout(e){D(this).timeout=e}get[_t](){return D(this).fetch}set[_t](e){D(this).fetch=e}};Object.freeze($e.prototype);function Fi(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){const r=Date.now();return t>r?Math.floor((t-r)/1e3):0}}},claims:{__proto__:null,value(){return ft(e)}}}}function vt(e){Object.defineProperties(e,Fi(e))}async function Ir(e,t,r,n=!1){const i=e.headers.get("retry-after")?.trim();if(i===void 0)return;let s;if(/^\d+$/.test(i))s=parseInt(i,10);else{const o=new Date(i);if(Number.isFinite(o.getTime())){const a=new Date,c=o.getTime()-a.getTime();c>0&&(s=Math.ceil(c/1e3))}}if(n&&!Number.isFinite(s))throw new ot("invalid Retry-After header value",{cause:e});s>t&&await Sr(s-t,r)}function Sr(e,t){return new Promise((r,n)=>{const i=s=>{try{t.throwIfAborted()}catch(a){n(a);return}if(s<=0){r();return}const o=Math.min(s,5);setTimeout(()=>i(s-o),o*1e3)};i(e)})}function Ji(e,t){const r=me(t);if(!r)return{signal:e,cleanup(){}};const n=new AbortController,i=s=>{const o=s.target;n.abort(o.reason)};return e.aborted?n.abort(e.reason):r.aborted?n.abort(r.reason):(e.addEventListener("abort",i,{once:!0}),r.addEventListener("abort",i,{once:!0})),{signal:n.signal,cleanup(){e.removeEventListener("abort",i),r.removeEventListener("abort",i)}}}async function Gi(e,t,r,n,i,s,o){const a=new URLSearchParams(s);let c=t.interval??5;const u=o?.signal??AbortSignal.timeout(t.expires_in*1e3);for(;;){try{await Sr(c,u)}catch(y){M(y)}const{as:f,c:_,auth:h,fetch:d,tlsOnly:w,nonRepudiation:R,timeout:T,decrypt:N}=D(e),U=Ji(u,T);try{const y=await n(f,_,h,r,{[q]:d,[H]:!w,additionalParameters:a,DPoP:o?.DPoP,headers:new Headers(ae),signal:U.signal}).catch(M);if(y.status===503&&y.headers.has("retry-after")){await y.body?.cancel(),await Ir(y,c,u,!0),o={...o,flag:void 0};continue}let I;try{I=await i(f,_,y,{[F]:N})}catch(b){if(Ee(b,o)){o={...o,flag:Q};continue}if(b instanceof Ne&&(b.error==="slow_down"||b.error==="authorization_pending")){b.error==="slow_down"&&(c+=5),await Ir(b.response,c,u),o={...o,flag:void 0};continue}M(b)}return I.id_token&&await R?.(y),vt(I),I}finally{U.cleanup()}}}async function Ki(e,t,r,n){return ce(e),Gi(e,t,t.device_code,Di,xi,r,n)}async function Zi(e,t){ce(e);const{as:r,c:n,auth:i,fetch:s,tlsOnly:o,timeout:a}=D(e);return Li(r,n,i,t,{[q]:s,[H]:!o,headers:new Headers(ae),signal:me(a)}).then(c=>Ci(r,n,c)).catch(M)}function Yi(e){D(e).tlsOnly=!1}function Qi(e){return e=new URL(e),e.search="",e.hash="",e.href}function Xi(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Pr(e,t,r,n,i){if(ce(e),i?.flag!==Q&&!(t instanceof URL)&&!Xi(t,"Request"))throw J('"currentUrl" must be an instance of URL, or Request',je);let s,o;const{as:a,c,auth:u,fetch:f,tlsOnly:_,jarm:h,hybrid:d,nonRepudiation:w,timeout:R,decrypt:T,implicit:N}=D(e);if(i?.flag===Q)s=i.authResponse,o=i.redirectUri;else{if(!(t instanceof URL)){const b=t;switch(t=new URL(t.url),b.method){case"GET":break;case"POST":const le=new URLSearchParams(await ki(b));if(d)t.hash=le.toString();else for(const[He,Tt]of le.entries())t.searchParams.append(He,Tt);break;default:throw J("unexpected Request HTTP method",Ae)}}switch(o=Qi(t),!0){case!!h:s=await h(t,r?.expectedState);break;case!!d:s=await d(t,r?.expectedNonce,r?.expectedState,r?.maxAge);break;case!!N:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{s=Ui(a,c,t.searchParams,r?.expectedState)}catch(b){M(b)}}}const U=await fi(a,c,u,s,o,r?.pkceCodeVerifier||lr,{additionalParameters:n,[q]:f,[H]:!_,DPoP:i?.DPoP,headers:new Headers(ae),signal:me(R)}).catch(M);(typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number")&&(r.idTokenExpected=!0);const y=gi(a,c,U,{expectedNonce:r?.expectedNonce,maxAge:r?.maxAge,requireIdToken:r?.idTokenExpected,[F]:T});let I;try{I=await y}catch(b){if(Ee(b,i))return Pr(e,void 0,r,n,{...i,flag:Q,authResponse:s,redirectUri:o});M(b)}return I.id_token&&await w?.(U),vt(I),I}async function Rr(e,t,r,n){ce(e),r=new URLSearchParams(r);const{as:i,c:s,auth:o,fetch:a,tlsOnly:c,nonRepudiation:u,timeout:f,decrypt:_}=D(e),h=await ci(i,s,o,t,{[q]:a,[H]:!c,additionalParameters:r,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(f)}).catch(M),d=ui(i,s,h,{[F]:_});let w;try{w=await d}catch(R){if(Ee(R,n))return Rr(e,t,r,{...n,flag:Q});M(R)}return w.id_token&&await u?.(h),vt(w),w}function bt(e,t){ce(e);const{as:r,c:n,tlsOnly:i,hybrid:s,jarm:o,implicit:a}=D(e),c=ve(r,"authorization_endpoint",!1,i);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",n.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",s?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw J("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Ae);o&&t.set("response_mode","jwt")}for(const[u,f]of t.entries())c.searchParams.append(u,f);return c}async function kr(e,t,r){ce(e);const n=bt(e,t),{as:i,c:s,auth:o,fetch:a,tlsOnly:c,timeout:u}=D(e),f=await Zn(i,s,o,n.searchParams,{[q]:a,[H]:!c,DPoP:r?.DPoP,headers:new Headers(ae),signal:me(u)}).catch(M),_=ni(i,s,f);let h;try{h=await _}catch(d){if(Ee(d,r))return kr(e,t,{...r,flag:Q});M(d)}return bt(e,{request_uri:h.request_uri})}function ce(e){if(!(e instanceof $e))throw J('"config" must be an instance of Configuration',je);if(Object.getPrototypeOf(e)!==$e.prototype)throw J("subclassing Configuration is not allowed",Ae)}function me(e){return e?AbortSignal.timeout(e*1e3):void 0}async function Or(e,t,r,n){ce(e);const{as:i,c:s,fetch:o,tlsOnly:a,nonRepudiation:c,timeout:u,decrypt:f}=D(e),_=await oi(i,s,t,{[q]:o,[H]:!a,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(u)}).catch(M);let h=ai(i,s,r,_,{[F]:f}),d;try{d=await h}catch(w){if(Ee(w,n))return Or(e,t,r,{...n,flag:Q});M(w)}return Ue(_)==="application/jwt"&&await c?.(_),d}function Ee(e,t){return t?.DPoP&&t.flag!==Q?Yn(e):!1}var Q=Symbol(),es={issuer:"{issuer}",authorization_endpoint:"{issuer}/oauth/authorize",token_endpoint:"{issuer}/oauth/token",device_authorization_endpoint:"{issuer}/oauth/device/authorize",jwks_uri:"{issuer}/.well-known/jwks.json",userinfo_endpoint:"{issuer}/oauth/userinfo",registration_endpoint:"{issuer}/oauth/clients/register",scopes_supported:["openid","profile","email","phone","offline_access"],response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:device_code"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256","HS256","ES256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],claims_supported:["sub","aud","iss","exp","iat","auth_time","nonce","email","email_verified","phone_number","phone_number_verified","name","picture","preferred_username","updated_at"],code_challenge_methods_supported:["S256","plain"],pushed_authorization_request_endpoint:"{issuer}/oauth/par"};function ts(e){return JSON.parse(JSON.stringify(es).replaceAll("{issuer}",e))}var rs=6e5,ns=2048,is=["authorization_details","login_hint"],ss=class{#e;#t;#i;#s;#r;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#i=e.clientSecret??null,this.#s=e.transport??"auto"}get isConfidential(){return this.#i!==null}async createAuthorizationRequest(e={}){try{const t=this.#c(e.redirectTo),r=Hi(),n=await $i(r),i=e.state??Bi(),s=this.#h(e,t,i,n),o=await this.#l(s);return l.ok({authorizationUrl:o,codeVerifier:r,state:i,redirectTo:t,createdAt:Date.now()})}catch(t){return l.fail(A.from(t,"authorization_request_failed"))}}async exchangeCallback(e){try{const t=new URL(e.callbackUrl),{request:r}=e;if(!Number.isSafeInteger(r.createdAt)||Date.now()-r.createdAt>rs)return l.fail(g.INVALID_CALLBACK,{message:"the authorization transaction expired"});if(as(t,new URL(r.redirectTo))){if(t.searchParams.get("state")!==r.state)return l.fail(g.INVALID_CALLBACK,{message:"the callback state does not correlate"})}else return l.fail(g.INVALID_CALLBACK,{message:"the callback does not match redirectTo"});const n=t.searchParams.get("error");if(n)return l.fail(n.slice(0,256),{message:t.searchParams.get("error_description")?.slice(0,2048)??n});if(!t.searchParams.has("code"))return l.fail(g.INVALID_CALLBACK,{message:"the callback carries no authorization code"});const i=await Pr(this.#n(),t,{pkceCodeVerifier:r.codeVerifier,expectedState:r.state});return await this.#o(i)}catch(t){return l.fail(A.from(t,"authorization_exchange_failed"))}}async resolveAuthorizationUrl(e,t){try{return l.ok(await this.#l(e,t))}catch(r){return l.fail(A.from(r,"authorization_request_failed"))}}async refresh(e){try{const t=await Rr(this.#n(),e);return await this.#o(t)}catch(t){return l.fail(A.from(t,"refresh_failed"))}}async userInfo(e){try{const t=Nr(e),r=await Or(this.#n(),e,t?t.sub:ji);return l.ok({id:String(r.sub),name:r.name,email:r.email,avatarUrl:r.picture})}catch(t){return l.fail(A.from(t,"userinfo_failed"))}}async createDeviceAuthorizationRequest(e={}){try{const t=await Zi(this.#n(),{scope:this.#u(e).join(" ")});return l.ok({deviceCode:t.device_code,userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete??t.verification_uri,expiresIn:t.expires_in,interval:t.interval??5,raw:t})}catch(t){return l.fail(A.from(t,"device_authorization_failed"))}}async awaitDeviceAuthorization(e,t={}){try{const r=await Ki(this.#n(),e.raw,void 0,{signal:t.signal});return await this.#o(r)}catch(r){return l.fail(A.from(r,"device_exchange_failed"))}}configuration(){return this.#n()}#n(){return this.#r??=this.#a(),this.#r}#a(){const e=this.#e,t=e.endpoints.auth,r=`${t.origin}${t.pathname.replace(/\/+$/,"")}`,n=this.#i,i=new $e(ts(r),e.clientId,n??void 0,n?Mi(n):Tr());return i[_t]=((s,o)=>this.#t(s,o)),Yi(i),i}#c(e){const t=e??this.#e.redirectTo;if(!t)throw new A(g.INVALID_CONFIGURATION,{message:"redirectTo is required, on the instance or on the request"});return new URL(t).href}#u(e){const t=(e.authorizations??[]).flatMap(n=>[...n.scopes]),r=e.scopes??this.#e.initialScopes;return[...new Set([...r,...t])]}#h(e,t,r,n){const i=new URLSearchParams({client_id:this.#e.clientId,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"}),s=this.#u(e);s.length&&i.set("scope",s.join(" "));const o=new Set;for(const u of os(e.resource))o.add(u);for(const u of e.authorizations??[])o.add(u.resource);for(const u of o)i.append("resource",u);const a=[...e.authorizationDetails??[],...(e.authorizations??[]).flatMap(u=>[...u.authorizationDetails??[]])];a.length&&i.set("authorization_details",JSON.stringify(a));const c=e.orgId??(e.authorizations??[]).find(u=>u.orgId)?.orgId;return c&&i.set("org_id",c),e.externalId&&i.set("external_id",e.externalId),i}async#l(e,t){const r=this.#n(),n=bt(r,e),i=is.some(o=>e.has(o)),s=t??this.#s;return(s==="auto"?i||n.href.length>ns?"par":"get":s)==="get"?n:await kr(r,e)}async#o(e){if(e.token_type&&e.token_type.toLowerCase()!=="bearer")return l.fail(g.INVALID_RESPONSE,{message:"unsupported token type"});const t=e.claims?.()?.sub??Nr(e.access_token)?.sub;if(!t)return l.fail(g.INVALID_RESPONSE,{message:"the response carries no subject"});const r={accessToken:e.access_token,refreshToken:e.refresh_token??null,tokenType:e.token_type??"bearer",expiresAt:Math.floor(Date.now()/1e3)+(e.expires_in??0),scopes:(e.scope??"").split(/\s+/).filter(Boolean),user:{id:t,name:null,email:null,avatarUrl:null}},n=await this.userInfo(r.accessToken);return l.ok(n.data?{...r,user:n.data}:r)}};function os(e){return e===void 0?[]:typeof e=="string"?[e]:e}function as(e,t){return e.origin!==t.origin||e.pathname!==t.pathname?!1:[...t.searchParams].every(([r,n])=>e.searchParams.getAll(r).includes(n))}function Nr(e){const t=e.split(".");if(t.length<2||!t[1])return null;try{const r=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")),n=>n.charCodeAt(0))));return r&&typeof r=="object"&&typeof r.sub=="string"?{sub:r.sub}:null}catch{return null}}var cs=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE","request"]);function us(e,t){return new Proxy(e,{get(r,n,i){const s=Reflect.get(r,n,i);if(typeof n!="string"||!cs.has(n)||typeof s!="function")return s;const o=s;return(...a)=>ls(o.apply(r,a),t)}})}function ls(e,t){const r=e.then(n=>n.error===void 0?{data:n.data,response:n.response}:{error:t(n.error,n.response),response:n.response},n=>{const i=Response.error();return{error:t(n,i),response:i}});return Object.assign(r,{throwOnError:()=>r.then(n=>{if(n.error!==void 0)throw n.error;return n})})}var Ur=class{#e;#t;#i;#s;http;raw;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#i=e.credentials,this.#s=e.resource??e.config.endpoints.api.origin,this.raw=Mn({endpoint:this.#e.endpoints.api,apiVersion:this.#e.apiVersion,accessToken:()=>this.#i.accessTokenFor(this.#s),fetch:this.#t}),this.http=us(this.raw,An.fromOpenAPIFetch)}},ds=class{#e=new Map;getItem(e){return this.#e.get(e)??null}setItem(e,t){this.#e.set(e,t)}removeItem(e){this.#e.delete(e)}},hs=class{storage;constructor(e){this.storage=e}getItem(e){return this.storage.getItem(e)}setItem(e,t){this.storage.setItem(e,t)}removeItem(e){this.storage.removeItem(e)}},fs=class{#e=new Map;async acquire(e,t){const r=(this.#e.get(e)??Promise.resolve()).then(t,t),n=r.then(()=>{},()=>{});this.#e.set(e,n);try{return await r}finally{this.#e.get(e)===n&&this.#e.delete(e)}}},Lr=class{#e;#t;#i;#s=new Set;#r;#n;#a;#c;constructor(e){this.#e=e,this.#t=e.storage??new ds,this.#i=e.lock??new fs,this.#r=`andco.session.${e.config.clientId}`,this.#n=e.initialSession,this.#a=e.initialSession}getSnapshot(){return this.#a}getServerSnapshot(){return this.#n}subscribe(e){return this.#s.add(e),this.#u(),()=>{this.#s.delete(e)}}get ready(){return this.#u()}async accessTokenFor(e){await this.#u();const t=this.#a;if(!t)return null;if(!$t(t))return Xe(t,e);const r=await this.#i.acquire(`${this.#r}:${e}`,async()=>{const n=this.#a;if(!n)return null;if(!$t(n))return n;if(!n.refreshToken)return null;const i=await this.#e.oauth.refresh(n.refreshToken);return i.error?null:(await this.#l(i.data),i.data)});return r?Xe(r,e):null}async set(e){this.#c??=Promise.resolve(l.ok(void 0));try{return await this.#l(e),l.ok(void 0)}catch(t){return l.fail(A.from(t,g.STORAGE_FAILED))}}#u(){return this.#c??=this.#h(),this.#c}async#h(){try{const e=this.#e.source?await this.#e.source():null;if(e?.error)return this.#o(this.#a??null),l.fail(e.error);if(e?.data)return await this.#l(e.data),l.ok(void 0);if(this.#n!==void 0)return this.#o(this.#n),l.ok(void 0);const t=await this.#t.getItem(this.#r);return this.#o(t?ps(t):null),l.ok(void 0)}catch(e){return this.#o(this.#a??null),l.fail(A.from(e,g.STORAGE_FAILED))}}async#l(e){this.#e.persist!==!1&&(e?await this.#t.setItem(this.#r,JSON.stringify(e)):await this.#t.removeItem(this.#r)),this.#o(e)}#o(e){this.#a=e;for(const t of[...this.#s])t()}};function ps(e){try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;const r=t;return typeof r.accessToken!="string"||typeof r.expiresAt!="number"||!r.user||typeof r.user.id!="string"?null:r}catch{return null}}function ms(){return new A(g.BROWSER_REQUIRED)}var ys=class $r{config;clientSecret;globals;oauth;rest;intents;auth;session;isAuthed=!1;constructor(t){this.config=Sn.from(t),this.clientSecret=t.clientSecret??null,this.globals={fetch:t.globals?.fetch??globalThis.fetch.bind(globalThis),crypto:t.globals?.crypto??globalThis.crypto},this.oauth=new ss({config:this.config,fetch:this.globals.fetch,clientSecret:this.clientSecret,transport:t.transport}),this.session=new Lr({config:this.config,oauth:this.oauth,storage:t.storage,initialSession:t.initialSession,lock:t.lock,source:t.source,persist:t.persist}),this.auth=new jt({oauth:this.oauth,store:this.session,presenter:t.presenter??Cr(),persistTransaction:t.persistTransaction,crypto:this.globals.crypto}),this.rest=new Ur({config:this.config,fetch:this.globals.fetch,credentials:this.session}),this.intents=new Jt(this.rest,this.globals.crypto)}with(t){return new ws(this,$r.resolveCredentials(t))}authorized(){return new _s(this)}static resolveCredentials(t){return typeof t=="string"?{accessTokenFor:async()=>t}:Rn(t)?t:Pn(t)}};function Cr(){return{async present(){return l.fail(ms())}}}var ws=class{credentials;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e,t){this.credentials=t,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=new Ur({config:e.config,fetch:e.globals.fetch,credentials:t}),this.intents=new Jt(this.rest,e.globals.crypto),this.session=new Lr({config:e.config,oauth:e.oauth,persist:!1}),this.auth=new jt({oauth:e.oauth,store:this.session,presenter:Cr(),crypto:e.globals.crypto})}accessTokenFor(e){return this.credentials.accessTokenFor(e)}},_s=class{owner;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e){this.owner=e,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=e.rest,this.intents=e.intents,this.auth=e.auth,this.session=e.session}accessTokenFor(e){return this.owner.session.accessTokenFor(e)}},gs=/^[A-Za-z0-9_-]{8,128}$/,vs=6e5,bs=400;function As(){return typeof window<"u"&&window.__ANDCO_NATIVE_HOST__===!0&&typeof window.ReactNativeWebView?.postMessage=="function"}function Dr(){if(typeof window>"u"||!window.opener||window.opener===window||!window.name.startsWith("andco-popup-"))return null;const e=window.name.slice(Mt.length);return gs.test(e)?e:null}function Es(e,t={}){if(typeof window>"u")return{status:"not_callback"};const r=t.callbackUrl?new URL(t.callbackUrl,window.location.href):new URL(window.location.href);if(!(t.callbackUrl||r.searchParams.has("code")||r.searchParams.has("error")))return{status:"not_callback"};const n=Dr();if(!n)return{status:"not_popup"};const i=r.searchParams.get("state"),s=(i?nn(i)?.openerOrigin:null)??window.location.origin;if(s!==window.location.origin&&!e.has(s))return{status:"rejected",error:new A(g.UNTRUSTED_ORIGIN)};const o=s===window.location.origin?Ts(n,r):Is(n,r);for(const a of["code","state","error","error_description"])r.searchParams.delete(a);return window.history.replaceState(window.history.state,"",r),window.name="",window.opener?.postMessage(o,s),window.close(),{status:"relayed",presentationId:n}}function Ts(e,t){return{protocol:"andco",version:1,presentationId:e,callbackUrl:t.href}}function Is(e,t){const r={protocol:pe,version:2,presentationId:e},n=t.searchParams.get("code");if(n)return{...r,type:"oauth.authorization_code",authorizationCode:n};const i=t.searchParams.get("error")??"invalid_request";if(i==="access_denied")return{...r,type:"oauth.dismiss"};const s=t.searchParams.get("error_description");return{...r,type:"oauth.error",error:{code:i.slice(0,256),description:s?s.slice(0,2048):void 0}}}function Ss(e){const t=window.open(e.url?.href??"about:blank",`${Mt}${e.presentationId}`,Rs({width:620,height:720}));return t?{blocked:!1,navigate:r=>t.location.assign(r.href),result:new Promise(r=>{let n=!1;const i=c=>{n||(n=!0,window.removeEventListener("message",s),window.clearInterval(o),window.clearTimeout(a),r(c))},s=c=>{if(c.origin!==e.expectedOrigin||c.source!==t)return;const u=c.data;if(!(!u||u.protocol!=="andco"||u.presentationId!==e.presentationId)&&typeof u.callbackUrl=="string"){t.close();try{i(l.ok(new URL(u.callbackUrl)))}catch{i(l.fail(g.INVALID_CALLBACK))}}};window.addEventListener("message",s);const o=window.setInterval(()=>{t.closed&&i(l.ok(null))},bs),a=window.setTimeout(()=>{t.close(),i(l.fail(g.POPUP_TIMEOUT))},vs);e.signal?.addEventListener("abort",()=>{t.close(),i(l.ok(null))})}),close:()=>t.close()}:{blocked:!0,navigate:()=>{},result:Promise.resolve(l.fail(g.POPUP_BLOCKED)),close:()=>{}}}function Ps(e){return Ss(e).result}function Rs(e){const t=Math.max(0,Math.round((window.screen.width-e.width)/2)),r=Math.max(0,Math.round((window.screen.height-e.height)/2));return`popup=1,width=${e.width},height=${e.height},left=${t},top=${r}`}var ks=class{iframe;options;url;settled=!1;transport="pending";port;handshakeTimer;handshakeTimeout;handshakeAttempts=0;handshakeStartedAt=0;destroyed=!1;constructor(e,t){if(this.iframe=e,this.options=t,typeof window>"u"||typeof document>"u")throw new A(g.BROWSER_UNAVAILABLE);if(!(e instanceof HTMLIFrameElement))throw new A(g.INVALID_IFRAME,{details:{iframe:e}});if(this.url=new URL(t.endpointButton),this.url.origin===window.location.origin)throw new A(g.SAME_ORIGIN_ENDPOINT,{details:{endpointButton:this.url.href}});console.debug("[AndcoButtonBridge] created: %o",{endpointButton:this.url.href}),e.addEventListener("load",this.startHandshake),this.startHandshake()}stopHandshake(){this.handshakeTimer!==void 0&&window.clearInterval(this.handshakeTimer),this.handshakeTimeout!==void 0&&window.clearTimeout(this.handshakeTimeout),this.handshakeTimer=void 0,this.handshakeTimeout=void 0}closePort(){this.port?.close(),this.port=void 0}receive(e){if(bn(e))switch(e.type){case"ready":if(this.settled)return;this.settled=!0,this.stopHandshake(),console.debug("[AndcoButtonBridge] handshake settled: %o",{attempts:this.handshakeAttempts,transport:this.transport,elapsedMs:Date.now()-this.handshakeStartedAt}),this.options.onReady?.(e);return;case"error":this.settled||(this.settled=!0,this.stopHandshake()),console.warn("[AndcoButtonBridge] hosted surface reported an error: %o",e.error),this.options.onError?.(e);return;case"oauth.authorization_code":case"oauth.complete":case"intent.complete":if(!this.settled)return;this.options.onComplete?.(e);return;case"oauth.dismiss":case"intent.dismiss":this.settled&&this.options.onDismiss?.(e);return;case"oauth.error":this.settled&&this.options.onAuthorizationError?.(e);return;case"click":this.settled&&this.options.onActivate?.(e);return}}receiveWindow=e=>{this.transport==="port"||e.origin!==this.url.origin||e.source!==this.iframe.contentWindow||(this.transport="window",this.receive(e.data))};initialize=()=>{const e=this.iframe.contentWindow;if(!e)return;this.handshakeAttempts+=1,this.closePort();const t=new MessageChannel;this.port=t.port1,this.port.onmessage=n=>{this.transport!=="window"&&(this.transport="port",window.removeEventListener("message",this.receiveWindow),this.receive(n.data))};const r={protocol:pe,version:2,type:"init"};try{e.postMessage(r,this.url.origin,[t.port2])}catch(n){console.debug("[AndcoButtonBridge] init attempt %d could not post yet, retrying: %o",this.handshakeAttempts,{cause:n})}};startHandshake=()=>{this.stopHandshake(),this.settled=!1,this.transport="pending",this.handshakeAttempts=0,this.handshakeStartedAt=Date.now(),window.addEventListener("message",this.receiveWindow),this.initialize(),this.handshakeTimer=window.setInterval(this.initialize,250),this.handshakeTimeout=window.setTimeout(()=>{this.settled=!0,this.stopHandshake(),this.closePort(),console.error("[AndcoButtonBridge] handshake timed out: %o",{attempts:this.handshakeAttempts,endpointButton:this.url.href});const e={protocol:pe,version:2,type:"error",error:{code:re.HANDSHAKE_TIMEOUT}};this.options.onError?.(e)},1e4)};post(e){if(!(this.destroyed||!this.settled)){if(this.transport==="port"&&this.port){this.port.postMessage(e);return}this.iframe.contentWindow?.postMessage(e,this.url.origin)}}resolveAuthorization(e,t){const r={protocol:pe,version:2,type:"authorization-response",presentationId:e,authorizationUrl:t?.toString()};this.post(r)}forwardAuthorizationResult(e){this.post(e)}setPreferences(e){const t={protocol:pe,version:2,type:"set-preferences",...e};this.post(t)}destroy(){this.destroyed||(console.debug("[AndcoButtonBridge] destroyed: %o",{settled:this.settled,attempts:this.handshakeAttempts}),this.destroyed=!0,window.removeEventListener("message",this.receiveWindow),this.iframe.removeEventListener("load",this.startHandshake),this.stopHandshake(),this.closePort())}},Os=class{#e;#t=new Set;#i;#s;#r;#n;#a;#c=0;#u=!1;constructor(e){this.#e=e,this.#r={status:"idle",iframeURL:this.#f(),ready:!1,error:null}}get snapshot(){return this.#r}subscribe(e){return this.#t.add(e),e(this.#r),()=>{this.#t.delete(e)}}connect(e){this.disconnect(),this.#s=e,console.debug("[AndcoButtonController] connecting: %o",{iframeURL:this.#r.iframeURL}),this.#d({status:"connecting",ready:!1,error:null});try{this.#i=new ks(e,{endpointButton:this.#f(),onReady:t=>{this.#d({status:"ready",ready:!0}),this.#e.onReady?.(t)},onActivate:t=>{this.#a=t.presentationId,this.#e.onActivate?.(t),this.#h()},onComplete:t=>{this.#l(t)},onDismiss:()=>{this.#d({status:"dismissed"}),this.#e.onDismiss?.()},onAuthorizationError:t=>this.#o(new A(t.error.code,{message:t.error.description})),onError:t=>{if(t.error.code===re.HANDSHAKE_TIMEOUT&&!this.#u&&this.#s){this.#u=!0,console.debug("[AndcoButtonController] handshake timed out",{action:"reconnect",retry:1}),this.connect(this.#s);return}this.#o(new A(t.error.code),t)}})}catch(t){this.#o(A.from(t,g.INVALID_IFRAME))}return()=>this.disconnect()}disconnect(){this.#i?.destroy(),this.#i=void 0}restart(){if(this.#c+=1,this.#n=void 0,this.#r.status==="error"&&this.#s){this.#u=!1,console.debug("[AndcoButtonController] restarting after an error, reconnecting: %o",{code:this.#r.error?.code}),this.connect(this.#s);return}this.#d({status:this.#i?"ready":"idle",error:null})}destroy(){this.disconnect(),this.#s=void 0,this.#t.clear()}async#h(){const e=++this.#c;this.#d({status:"authorizing",error:null});const t=await this.#e.client.oauth.createAuthorizationRequest({...this.#e.authorization??{},state:rn(this.#e.client.config.endpoints.widget.origin,this.#a)});if(e===this.#c){if(t.error)return this.#o(t.error);this.#n=t.data,this.#i?.resolveAuthorization(this.#a,t.data.authorizationUrl.href)}}async#l(e){const t=this.#c,r=this.#n;if(this.#n=void 0,e.type==="oauth.authorization_code"&&r){const n=new URL(r.redirectTo);n.searchParams.set("code",e.authorizationCode),n.searchParams.set("state",r.state);const i=await this.#e.client.oauth.exchangeCallback({callbackUrl:n,request:r});if(t!==this.#c)return;if(i.error)return this.#o(i.error);const s=await this.#e.client.session.set(i.data);if(s.error)return this.#o(s.error)}t===this.#c&&(this.#d({status:"complete",error:null}),this.#e.onComplete?.())}#o(e,t){console.error("[AndcoButtonController] %s: %o",e.code,{message:e.message,details:e.details}),this.#d({status:"error",error:e}),this.#e.onError?.(e,t)}#f(){const e=this.#e.client.config,t=e.widgetURL(this.#e.release??1780358400);return t.searchParams.set("themeMode",this.#e.themeMode??e.themeMode),t.searchParams.set("locale",this.#e.locale??e.locale),t.searchParams.set("theme",e.theme),t.searchParams.set("flow",this.#e.flow??"authorization"),t.searchParams.set("presentation",this.#e.presentation??"popup"),t.searchParams.set("endpointAuth",e.endpoints.auth.href),t.searchParams.set("clientId",e.clientId),e.redirectTo&&t.searchParams.set("redirectTo",e.redirectTo.href),this.#e.disabled!==void 0&&t.searchParams.set("disabled",String(this.#e.disabled)),this.#e.busy!==void 0&&t.searchParams.set("busy",String(this.#e.busy)),t.href}#d(e){this.#r={...this.#r,...e,iframeURL:this.#f()};for(const t of[...this.#t])t(this.#r)}};function Ns(){return{async present(e){return typeof window>"u"?l.fail(g.BROWSER_REQUIRED):e.presentation==="redirect"?(window.location.assign(e.url.href),l.ok(null)):As()&&window.__ANDCO_NATIVE_POPUP_HANDLER__!==!0?l.fail(g.PRESENTATION_UNSUPPORTED,{message:"the native Host cannot present a popup without navigating the Miniapp"}):Ps({url:e.url,presentationId:e.presentationId,expectedOrigin:e.returnTo.origin,signal:e.signal})}}}var At="andco.transaction";function Us(e){const t=e.presenter??Ns(),r=e.storage??(typeof window>"u"?void 0:new hs(window.sessionStorage)),n=new ys({...e,presenter:t,storage:r,source:()=>Ls(n.config,n.oauth,e),persistTransaction:i=>Cs(n.config.clientId,i,e.transactionStorage)});return e.relayPopupCallback!==!1&&typeof window<"u"&&Es(n.config.allowedPopupOrigins),n}async function Ls(e,t,r){if(r.detectSessionInUrl===!1||typeof window>"u"||Dr())return l.ok(null);const n=new URL(window.location.href);if(!n.searchParams.has("code")&&!n.searchParams.has("error"))return l.ok(null);const i=r.transactionStorage??window.sessionStorage,s=i.getItem(`${At}.${e.clientId}`);if(!s)return l.ok(null);i.removeItem(`${At}.${e.clientId}`);let o;try{const c=JSON.parse(s);o={...c,authorizationUrl:new URL(c.authorizationUrl)}}catch{return l.fail(g.INVALID_CALLBACK)}const a=await t.exchangeCallback({callbackUrl:n,request:o});for(const c of["code","state","error","error_description"])n.searchParams.delete(c);return(r.replaceUrl??(c=>window.history.replaceState(window.history.state,"",c)))(n),a.error?l.fail(a.error):l.ok(a.data)}function Cs(e,t,r){(r??window.sessionStorage).setItem(`${At}.${e}`,JSON.stringify({...t,authorizationUrl:t.authorizationUrl.href}))}var Et=new Map;function xr(e){const t=JSON.stringify(e,Object.keys(e).sort()),r=Et.get(t);if(r)return r;const n=Us(e);return Et.set(t,n),n}function Ds(){const e="andco-button-default-style";if(typeof document>"u"||document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="@layer andco { andco-button { display: block; height: 3rem; width: 18rem } }",document.head.append(t)}var xs=["client-id","endpoint-auth","endpoint-api","endpoint-widget","redirect-to","locale","theme-mode","scopes","flow","disabled","busy"],zr=class extends HTMLElement{static observedAttributes=xs;#e;#t;#i;#s;authorizations;connectedCallback(){Ds(),this.#n()}disconnectedCallback(){this.#r()}attributeChangedCallback(){this.isConnected&&this.#n()}#r(){this.#t?.(),this.#i?.(),this.#e?.destroy(),this.#t=void 0,this.#i=void 0,this.#e=void 0}#n(){this.#r();const e=this.getAttribute("client-id");if(!e)return;const t=xr({clientId:e,...ue("endpointAuth",this.getAttribute("endpoint-auth")),...ue("endpointApi",this.getAttribute("endpoint-api")),...ue("endpointWidget",this.getAttribute("endpoint-widget")),...ue("redirectTo",this.getAttribute("redirect-to")),...ue("locale",this.getAttribute("locale")),initialScopes:this.getAttribute("scopes")?.split(/\s+/).filter(Boolean)}),r=this.getAttribute("scopes")?.split(/\s+/).filter(Boolean);this.#e=new Os({client:t,flow:this.getAttribute("flow")??void 0,...ue("themeMode",this.getAttribute("theme-mode")),...ue("locale",this.getAttribute("locale")),disabled:this.hasAttribute("disabled"),busy:this.hasAttribute("busy"),authorization:{...r?.length?{scopes:r}:{},authorizations:this.authorizations},onReady:()=>this.dispatchEvent(new CustomEvent("andco-ready")),onActivate:()=>this.dispatchEvent(new CustomEvent("andco-activate")),onComplete:()=>this.dispatchEvent(new CustomEvent("andco-complete")),onDismiss:()=>this.dispatchEvent(new CustomEvent("andco-dismiss")),onError:i=>this.dispatchEvent(new CustomEvent("andco-error",{detail:i}))});const n=this.#s??document.createElement("iframe");this.#s=n,n.referrerPolicy="no-referrer",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"),n.title=this.getAttribute("title")??"Andco",n.style.cssText="border:0;display:block;height:100%;width:100%",n.isConnected||this.append(n),this.#i=this.#e.subscribe(i=>{n.src!==i.iframeURL&&(n.src=i.iframeURL),n.hidden=!i.ready}),this.#t=this.#e.connect(n)}};function zs(e){const t=e.getAttribute("client-id");for(const[r,n]of Et)if(t&&r.includes(`"${t}"`))return n.session.getSnapshot()}function Ms(e){return xr(e)}function ue(e,t){return t?{[e]:t}:{}}return typeof customElements<"u"&&!customElements.get("andco-button")&&customElements.define("andco-button",zr),we.AndcoButtonElement=zr,we.andcoInstance=Ms,we.andcoSessionFor=zs,we})({});
|
|
1
|
+
var Andco=(function(_e){Object.defineProperty(_e,Symbol.toStringTag,{value:"Module"});var Ee,Gr={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Lt(e){return!e&&!Ee?Gr:{lang:e?.lang??Ee?.lang,message:e?.message,abortEarly:e?.abortEarly??Ee?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ee?.abortPipeEarly}}var Jr;function Kr(e){return Jr?.get(e)}var Zr;function Yr(e){return Zr?.get(e)}var Qr;function Xr(e,t){return Qr?.get(e)?.get(t)}function Je(e){const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function C(e,t,r,n,i){const s=i&&"input"in i?i.input:r.value,o=i?.expected??e.expects??null,a=i?.received??Je(s),c={kind:e.kind,type:e.type,input:s,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},l=e.kind==="schema",f=i?.message??e.message??Xr(e.reference,c.lang)??(l?Yr(c.lang):null)??n.message??Kr(c.lang);f!==void 0&&(c.message=typeof f=="function"?f(c):f),l&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function en(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Ct(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function K(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Lt())},e}function Dt(e,t){return{kind:"validation",type:"check",reference:Dt,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&C(this,"input",r,n),r}}}function Z(e,t){return{kind:"validation",type:"max_length",reference:Z,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function he(e,t){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Ke(e,t){return{kind:"validation",type:"regex",reference:Ke,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&C(this,"format",r,n),r}}}var tn={abortEarly:!0};function xt(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Ze(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function O(e,t){return K({kind:"schema",type:"literal",reference:O,expects:Je(e),async:!1,literal:e,message:t,"~run"(r,n){return en(r.value,this.literal)?r.typed=!0:C(this,"type",r,n),r}})}function Ye(e,t){return K({kind:"schema",type:"object",reference:Ye,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ze(o),c=o["~run"]({value:a},n);if(c.issues){const l={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(l):f.path=[l],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=xt(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else C(this,"type",r,n);return r}})}function fe(e,t){return K({kind:"schema",type:"optional",reference:fe,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Ze(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function Qe(e,t){return K({kind:"schema",type:"picklist",reference:Qe,expects:Ct(e.map(Je),"|"),async:!1,options:e,message:t,"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:C(this,"type",r,n),r}})}function x(e,t){return K({kind:"schema",type:"strict_object",reference:x,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ze(o),c=o["~run"]({value:a},n);if(c.issues){const l={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(l):f.path=[l],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=xt(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly){for(const s in i)if(!Object.prototype.hasOwnProperty.call(this.entries,s)){C(this,"key",r,n,{input:s,expected:"never",path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]});break}}}else C(this,"type",r,n);return r}})}function Y(e){return K({kind:"schema",type:"string",reference:Y,expects:"string",async:!1,message:e,"~run"(t,r){return typeof t.value=="string"?t.typed=!0:C(this,"type",t,r),t}})}function zt(e,t,r){return K({kind:"schema",type:"variant",reference:zt,expects:"Object",async:!1,key:e,options:t,message:r,"~run"(n,i){const s=n.value;if(s&&typeof s=="object"){let o,a=0,c=this.key,l=[];const f=(y,h)=>{for(const d of y.options){if(d.type==="variant")f(d,new Set(h).add(d.key));else{let w=!0,R=0;for(const I of h){const k=d.entries[I];if(I in s?k["~run"]({typed:!1,value:s[I]},tn).issues:k.type!=="exact_optional"&&k.type!=="optional"&&k.type!=="nullish"){w=!1,c!==I&&(a<R||a===R&&I in s&&!(c in s))&&(a=R,c=I,l=[]),c===I&&l.push(d.entries[I].expects);break}R++}if(w){const I=d["~run"]({value:s},i);(!o||!o.typed&&I.typed)&&(o=I)}}if(o&&!o.issues)break}};if(f(this,new Set([this.key])),o)return o;C(this,"type",n,i,{input:s[c],expected:Ct(l,"|"),path:[{type:"object",origin:"value",input:s,key:c,value:s[c]}]})}else C(this,"type",n,i);return n}})}function te(...e){return K({...e[0],pipe:e,"~run"(t,r){for(const n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}})}function Xe(e,t,r){const n=e["~run"]({value:t},Lt(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}function Mt(e){const t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||t==="::1"?!0:/^127(?:\.\d{1,3}){3}$/.test(t)}var rn=["hash","host","hostname","password","pathname","port","protocol","search","username"],nn=class extends URL{constructor(e,t,r){try{super(e,t)}catch(n){throw new Error(`${n instanceof Error?n.message:String(n)} — new BetterURL('${e}', '${t}')`)}r&&this.assign(r)}get isLoopback(){return Mt(this.hostname)}assign(e){if(e.replace){let{pathname:t}=this;for(const[r,n]of Object.entries(e.replace))t=t.replaceAll(`[${r}]`,encodeURIComponent(String(n)));this.pathname=t}for(const t of rn){const r=e[t];r!==void 0&&(this[t]=r)}if(e.params)for(const[t,r]of Object.entries(e.params))r===void 0||(r===null?this.searchParams.delete(t):this.searchParams.set(t,r));return this}format(e){if(!e)return this.href;let t="";return e.protocol&&(t+=`${this.protocol}//`),e.hostname&&(t+=this.hostname),e.port&&this.port&&(t+=`:${this.port}`),e.pathname&&(t+=this.pathname),e.search&&(t+=this.search),e.hash&&(t+=this.hash),t}get hashParams(){return new URLSearchParams(this.hash.slice(1))}},z=class extends nn{constructor(e,t,r){if(super(e,t,r),!(this.protocol==="https:"||this.protocol==="http:"&&Mt(this.hostname))||this.username||this.password||this.hash)throw new TypeError("AndCo URLs require HTTPS, except for loopback development hosts, and cannot contain credentials or a fragment")}},pe="andco:sdk",Fs="https://auth.andco.cl",qs="https://api.andco.cl",Gs="https://widgets.andco.cl";function sn(e,t="_"){return new URL(`/oauth/api/versions/${t}`,e).href}var H={protocol:O(pe),version:O(2)},Js=te(Y(),he(1),Z(128),Ke(/^[A-Za-z0-9_-]+$/)),F=te(Y(),he(1),Z(128),Ke(/^[A-Za-z0-9_-]+$/)),re;(function(e){e.BROWSER_UNAVAILABLE="BROWSER_UNAVAILABLE",e.AUTH_CANCELLED="AUTH_CANCELLED",e.AUTH_EXCHANGE_FAILED="AUTH_EXCHANGE_FAILED",e.AUTH_TIMEOUT="AUTH_TIMEOUT",e.INVALID_ENDPOINT_AUTH="INVALID_ENDPOINT_AUTH",e.INVALID_ENDPOINT_API="INVALID_ENDPOINT_API",e.INVALID_ENDPOINT_BUTTON="INVALID_ENDPOINT_BUTTON",e.INVALID_IFRAME="INVALID_IFRAME",e.INVALID_AUTH_MODE="INVALID_AUTH_MODE",e.INVALID_CLIENT_ID="INVALID_CLIENT_ID",e.INVALID_REDIRECT_TO="INVALID_REDIRECT_TO",e.INVALID_CALLBACK="INVALID_CALLBACK",e.INVALID_SCOPE="INVALID_SCOPE",e.INVALID_VERSION="INVALID_VERSION",e.FETCH_UNAVAILABLE="FETCH_UNAVAILABLE",e.POPUP_BLOCKED="POPUP_BLOCKED",e.POPUP_NAVIGATION_FAILED="POPUP_NAVIGATION_FAILED",e.POPUP_TIMEOUT="POPUP_TIMEOUT",e.INTENT_CALLBACK_REQUIRED="INTENT_CALLBACK_REQUIRED",e.SAME_ORIGIN_ENDPOINT="SAME_ORIGIN_ENDPOINT",e.UNSUPPORTED_PRESENTATION="UNSUPPORTED_PRESENTATION",e.UNSUPPORTED_THEME="UNSUPPORTED_THEME",e.UNSUPPORTED_THEME_MODE="UNSUPPORTED_THEME_MODE",e.UNTRUSTED_ORIGIN="UNTRUSTED_ORIGIN",e.WEB_CRYPTO_UNAVAILABLE="WEB_CRYPTO_UNAVAILABLE",e.HANDSHAKE_TIMEOUT="HANDSHAKE_TIMEOUT",e.UNKNOWN_ERROR="UNKNOWN_ERROR"})(re||(re={}));var jt=class extends Error{constructor(e,t){super(e,t),Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name}static is(e,t){return e instanceof t}},Ht=class extends jt{code;payload;constructor(e,t,r){super(e,r),this.code=e,this.payload=t}};function on(e){const t=new TextEncoder().encode(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function an(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"="),n=atob(r),i=Uint8Array.from(n,s=>s.charCodeAt(0));return new TextDecoder().decode(i)}function Pe(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(!e||typeof e.getRandomValues!="function")throw new Ht(re.WEB_CRYPTO_UNAVAILABLE,{missing:["crypto.getRandomValues"]});const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function $t(e,t=Pe()){if(!Xe(F,t).success)throw new TypeError("Invalid AndCo presentation identifier");const r=new z(e).origin;return`${on(r)}.${t}`}function Bt(e){const t=e.indexOf("."),r=e.slice(t+1);if(t<1||t===e.length-1||!Xe(F,r).success)return null;try{const n=an(e.slice(0,t));return{openerOrigin:new z(n).origin,presentationId:r}}catch{return null}}var cn=x({...H,type:O("click"),presentationId:fe(F)}),un=Qe(Object.values(re)),ln=x({...H,type:O("error"),error:x({code:un})}),dn=x({...H,type:O("init")}),hn=x({...H,type:O("oauth.authorization_code"),presentationId:F,authorizationCode:te(Y(),he(1),Z(8192))}),fn=x({...H,type:O("oauth.complete"),presentationId:F}),pn=x({...H,type:O("oauth.dismiss"),presentationId:F}),mn=Ye({...H,type:O("intent.complete"),presentationId:F}),yn=Ye({...H,type:O("intent.dismiss"),presentationId:F}),_n=x({...H,type:O("oauth.error"),presentationId:F,error:x({code:te(Y(),he(1),Z(256)),description:fe(te(Y(),Z(2048)))})}),gn=x({...H,type:O("presentation-response"),presentationId:F,url:fe(te(Y(),he(1),Z(8192)))}),wn=x({...H,type:O("ready")}),vn=te(Y(),Z(35),Dt(e=>{try{return Intl.getCanonicalLocales(e),!0}catch{return!1}})),bn=Qe(["dark","light","system"]),An=x({...H,type:O("set-preferences"),themeMode:fe(bn),locale:fe(vn)}),Tn=zt("type",[gn,wn,cn,ln,dn,An,hn,fn,pn,_n,mn,yn]);function In(e){return Xe(Tn,e).success}var Ks=1780358400,Vt="andco-popup-",v=class Ge extends Error{code;status;details;constructor(t,r={}){super(r.message??t,r.cause===void 0?void 0:{cause:r.cause}),this.name="AndcoError",this.code=t,this.status=r.status,this.details=r.details}static from(t,r){if(Ge.is(t))return t;const n=t instanceof Error?t.message:void 0;return new Ge(r,{message:n,cause:t})}static is(t){return t instanceof Ge}},En=class ye extends v{error;response;constructor(t,r){super(t,r),this.name="AndcoAPIError",this.error=t,this.response=r.response}static fromOpenAPIFetch(t,r){const{message:n,details:i}=ye.bodyOf(t),s=new ye(ye.codeOf(t),{response:r,status:ye.statusOf(r),message:n,details:i,cause:t});for(const[o,a]of Object.entries(i??{}))ye.OWN_FIELDS.has(o)||(s[o]=a);return s}static OWN_FIELDS=new Set(["name","message","stack","cause","code","error","status","response","details"]);static codeOf(t){if(t&&typeof t=="object"){const{error:r}=t;if(typeof r=="string")return r}return"request_failed"}static bodyOf(t){if(!t||typeof t!="object")return{message:void 0,details:void 0};const{error:r,message:n,...i}=t,s=Object.keys(i).length>0;return{message:typeof n=="string"?n:void 0,details:s?i:void 0}}static statusOf(t){if(t.type!=="error")return t.status}},u={ok(e){return{data:e,error:null}},fail(e,t={}){return{data:null,error:typeof e=="string"?new v(e,t):e}}},m={BROWSER_REQUIRED:"browser_required",BROWSER_UNAVAILABLE:"browser_unavailable",BROWSER_FORBIDDEN:"browser_forbidden",INVALID_CALLBACK:"invalid_callback",INVALID_CONFIGURATION:"invalid_configuration",HANDSHAKE_TIMEOUT:"handshake_timeout",INVALID_IFRAME:"invalid_iframe",INVALID_INTENT_ID:"invalid_intent_id",INVALID_RESPONSE:"invalid_response",POPUP_BLOCKED:"popup_blocked",POPUP_TIMEOUT:"popup_timeout",PRESENTATION_UNSUPPORTED:"presentation_unsupported",SAME_ORIGIN_ENDPOINT:"same_origin_endpoint",SESSION_MISSING:"session_missing",STORAGE_FAILED:"storage_failed",UNTRUSTED_ORIGIN:"untrusted_origin"},Wt=class{#e;constructor(e){this.#e=e}async signIn(e={}){const{config:t,oauth:r,presenter:n,store:i}=this.#e,s=this.#e.randomId?this.#e.randomId():Pe(this.#e.crypto),o=e.redirectTo??t.redirectTo;if(!o)return u.fail(m.INVALID_CONFIGURATION,{message:"redirectTo is required, on the instance or on the request"});let a;const c=await n.present({kind:"oauth",url:async()=>{const y=await r.createAuthorizationRequest(e);return y.error?u.fail(y.error):(await this.#e.persistTransaction?.(y.data),a=y.data,u.ok(y.data.authorizationUrl))},presentation:e.presentation??"popup",returnTo:new z(o),presentationId:s});if(c.error)return u.fail(c.error);if(!c.data)return u.ok(null);if(!a)return u.fail(m.INVALID_CALLBACK,{message:"no transaction was prepared"});const l=await r.exchangeCallback({callbackUrl:c.data,request:a});if(l.error)return u.fail(l.error);const f=await i.set(l.data);return f.error?u.fail(f.error):u.ok(l.data)}async signOut(){return this.#e.store.set(null)}onChange(e){const t=this.#e.store;return t.subscribe(()=>e(t.getSnapshot()??null))}async getSession(){const e=this.#e.store,t=await e.ready;return t.error?u.fail(t.error):u.ok(e.getSnapshot()??null)}async refresh(){const e=this.#e.store;await e.ready;const t=e.getSnapshot();if(!t?.refreshToken)return u.fail(m.SESSION_MISSING);const r=await this.#e.oauth.refresh(t.refreshToken);if(r.error)return u.fail(r.error);const n=await e.set(r.data);return n.error?u.fail(n.error):u.ok(r.data)}},Pn=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{2,8})*$/,Sn=/^[A-Za-z0-9_-]{1,80}$/,Rn=/^\d{10}$/,On=class Ut{clientId;endpoints;apiVersion;redirectTo;locale;theme;themeMode;initialScopes;allowedPopupOrigins;constructor(t){if(!Sn.test(t.clientId??""))throw new v(m.INVALID_CONFIGURATION,{message:"clientId is missing or malformed"});if(this.clientId=t.clientId,this.endpoints=Object.freeze({auth:new z(t.endpointAuth??"https://auth.andco.cl"),api:new z(t.endpointApi??"https://api.andco.cl"),widget:new z(t.endpointWidget??"https://widgets.andco.cl")}),this.apiVersion=String(t.apiVersion??"_"),this.apiVersion!=="_"&&!Rn.test(this.apiVersion))throw new v(m.INVALID_CONFIGURATION,{message:"apiVersion must be `_` or a ten-digit Unix timestamp"});if(this.redirectTo=t.redirectTo===void 0?void 0:new z(t.redirectTo),this.locale=t.locale??"es",!Pn.test(this.locale))throw new v(m.INVALID_CONFIGURATION,{message:"locale must be a BCP 47 tag"});this.theme=t.theme??"base",this.themeMode=t.themeMode??"system",this.initialScopes=Object.freeze([...new Set(t.initialScopes??[])]);const r=t.allowedPopupOrigins??[];this.allowedPopupOrigins=Object.freeze(new Set([this.endpoints.widget.origin,...r.map(n=>new z(n).origin)]))}static from(t){return new Ut(t)}with(t){return Ut.from({...this.toJSON(),...t})}authURL(t){const r=this.endpoints.auth,n=new URL(r.href);return n.pathname=`${r.pathname.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,n}apiURL(){return new URL(`/oauth/api/versions/${this.apiVersion}/`,this.endpoints.api)}widgetURL(t,r="button"){return new URL(`/embedded/versions/${t}/${r}`,this.endpoints.widget)}allowsPopupOrigin(t){return this.allowedPopupOrigins.has(t)}toJSON(){return{clientId:this.clientId,endpointAuth:this.endpoints.auth.href,endpointApi:this.endpoints.api.href,endpointWidget:this.endpoints.widget.href,apiVersion:this.apiVersion,redirectTo:this.redirectTo?.href,locale:this.locale,theme:this.theme,themeMode:this.themeMode,initialScopes:[...this.initialScopes],allowedPopupOrigins:[...this.allowedPopupOrigins]}}},Zs=30;function Ft(e,t=Math.floor(Date.now()/1e3)){return e.expiresAt<=t+30}function et(e,t){const r=e.resourceAccessTokens;if(r){if(r[t])return r[t]??null}else return e.accessToken;try{return r[new URL(t).href]??e.accessToken}catch{return e.accessToken}}function Nn(e){return{accessTokenFor:async t=>et(e,t)}}function kn(e){return typeof e.accessTokenFor=="function"}function Un(e,t,r,n,i){const s=n.pollIntervalMs??1e3;if(!Number.isSafeInteger(s)||s<100)throw new TypeError("Invalid event polling interval");if(typeof n.onError!="function")throw new TypeError("An event error handler is required");const o=`v1:${i.kind}:${i.id.toLowerCase()}:`,a=h=>{if(typeof h!="string"||!h.startsWith(o)||!/^(0|[1-9][0-9]{0,18})$/.test(h.slice(o.length)))throw new TypeError("invalid_or_unsupported_event_cursor");const d=BigInt(h.slice(o.length));if(d>9223372036854775807n)throw new TypeError("invalid_or_unsupported_event_cursor");return d},c=new AbortController;let l=n.after,f;const y=async()=>{if(c.signal.aborted)return;let h=s;try{let d=l===void 0?0n:a(l);const w=await e(l,c.signal);if(c.signal.aborted)return;if(!w||!Array.isArray(w.events)||w.events.length>100||typeof w.has_more!="boolean"||!qt(w.server_time))throw new TypeError("invalid_event_response");const R=a(w.next_cursor),I=new Map;let k=-1n;const U=w.events.map(g=>{if(!g||g.version!==1||typeof g.id!="string"||!g.id||g.id.length>128||typeof g.type!="string"||!g.type||!g.payload||typeof g.payload!="object"||Array.isArray(g.payload)||!qt(g.occurred_at))throw new TypeError("invalid_event_response");const E=a(g.cursor);if(E===0n||E<k)throw new TypeError("invalid_event_response");const A=JSON.stringify(g);if(I.has(g.id)&&I.get(g.id)!==A||E===k&&I.get(g.id)!==A)throw new TypeError("invalid_event_response");return I.set(g.id,A),k=E,E});if(w.events.length?R!==U.at(-1):R!==d||w.has_more)throw new TypeError("invalid_event_response");if(w.has_more&&R<=d)throw new TypeError("invalid_event_response");for(let g=0;g<w.events.length;g++){if(c.signal.aborted)return;const E=w.events[g],A=U[g];if(A<=d)continue;const le=t(E);le!==null&&await r(le),l=E.cursor,d=A}l===void 0&&(l=w.next_cursor),w.has_more&&(h=0)}catch(d){if(c.signal.aborted)return;try{await n.onError(d)}catch{c.abort()}}finally{c.signal.aborted||(f=setTimeout(()=>{y()},h))}};return y(),{unsubscribe(){c.abort(),clearTimeout(f)},get checkpoint(){return l}}}function qt(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e))}var tt=class extends jt{code;status;details;constructor(e,t,r){super(e),this.code=e,this.status=t,this.details=r}};function Ln(e,t){try{const r=new z(t).origin,n=new z(e.authorization_url);if(n.origin!==r||n.protocol!=="https:")throw new tt("invalid_authorization_url",500);return n}catch(r){throw r instanceof tt?r:new tt("invalid_authorization_url",500)}}var Cn=/\{[^{}]+\}/g,Dn=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function xn(){return Math.random().toString(36).slice(2,11)}function zn(e){let{baseUrl:t="",Request:r=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:s,pathSerializer:o,headers:a,requestInitExt:c=void 0,...l}={...e};c=Dn()?c:void 0,t=Yt(t);const f=[];async function y(h,d){const{baseUrl:w,fetch:R=n,Request:I=r,headers:k,params:U={},parseAs:g="json",querySerializer:E,bodySerializer:A=s??jn,pathSerializer:le,body:Ve,middleware:Pt=[],...St}=d||{};let Rt=t;w&&(Rt=Yt(w)??t);let Ot=typeof i=="function"?i:Kt(i);E&&(Ot=typeof E=="function"?E:Kt({...typeof i=="object"?i:{},...E}));const Wr=le||o||Mn,Nt=Ve===void 0?void 0:A(Ve,Zt(a,k,U.header)),Vs=Zt(Nt===void 0||Nt instanceof FormData?{}:{"Content-Type":"application/json"},a,k,U.header),X=[...f,...Pt],Ws={redirect:"follow",...l,...St,body:Nt,headers:Vs};let We,Fe,ee=new I(Hn(h,{baseUrl:Rt,params:U,querySerializer:Ot,pathSerializer:Wr}),Ws),P;for(const L in St)L in ee||(ee[L]=St[L]);if(X.length){We=xn(),Fe=Object.freeze({baseUrl:Rt,fetch:R,parseAs:g,querySerializer:Ot,bodySerializer:A,pathSerializer:Wr});for(const L of X)if(L&&typeof L=="object"&&typeof L.onRequest=="function"){const S=await L.onRequest({request:ee,schemaPath:h,params:U,options:Fe,id:We});if(S)if(S instanceof I)ee=S;else if(S instanceof Response){P=S;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!P){try{P=await R(ee,c)}catch(L){let S=L;if(X.length)for(let de=X.length-1;de>=0;de--){const qe=X[de];if(qe&&typeof qe=="object"&&typeof qe.onError=="function"){const Ie=await qe.onError({request:ee,error:S,schemaPath:h,params:U,options:Fe,id:We});if(Ie){if(Ie instanceof Response){S=void 0,P=Ie;break}if(Ie instanceof Error){S=Ie;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(S)throw S}if(X.length)for(let L=X.length-1;L>=0;L--){const S=X[L];if(S&&typeof S=="object"&&typeof S.onResponse=="function"){const de=await S.onResponse({request:ee,response:P,schemaPath:h,params:U,options:Fe,id:We});if(de){if(!(de instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");P=de}}}}const Fr=P.headers.get("Content-Length");if(P.status===204||ee.method==="HEAD"||Fr==="0"&&!P.headers.get("Transfer-Encoding")?.includes("chunked"))return P.ok?{data:void 0,response:P}:{error:void 0,response:P};if(P.ok)return{data:await(async()=>{if(g==="stream")return P.body;if(g==="json"&&!Fr){const S=await P.text();return S?JSON.parse(S):void 0}return await P[g]()})(),response:P};let kt=await P.text();try{kt=JSON.parse(kt)}catch{}return{error:kt,response:P}}return{request(h,d,w){return y(d,{...w,method:h.toUpperCase()})},GET(h,d){return y(h,{...d,method:"GET"})},PUT(h,d){return y(h,{...d,method:"PUT"})},POST(h,d){return y(h,{...d,method:"POST"})},DELETE(h,d){return y(h,{...d,method:"DELETE"})},OPTIONS(h,d){return y(h,{...d,method:"OPTIONS"})},HEAD(h,d){return y(h,{...d,method:"HEAD"})},PATCH(h,d){return y(h,{...d,method:"PATCH"})},TRACE(h,d){return y(h,{...d,method:"TRACE"})},use(...h){for(const d of h)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d||"onError"in d))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");f.push(d)}},eject(...h){for(const d of h){const w=f.indexOf(d);w!==-1&&f.splice(w,1)}}}}function Se(e,t,r){if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${r?.allowReserved===!0?t:encodeURIComponent(t)}`}function Gt(e,t,r){if(!t||typeof t!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[r.style]||"&";if(r.style!=="deepObject"&&r.explode===!1){for(const a in t)n.push(a,r.allowReserved===!0?t[a]:encodeURIComponent(t[a]));const o=n.join(",");switch(r.style){case"form":return`${e}=${o}`;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return o}}for(const o in t){const a=r.style==="deepObject"?`${e}[${o}]`:o;n.push(Se(a,t[o],r))}const s=n.join(i);return r.style==="label"||r.style==="matrix"?`${i}${s}`:s}function Jt(e,t,r){if(!Array.isArray(t))return"";if(r.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[r.style]||",",o=(r.allowReserved===!0?t:t.map(a=>encodeURIComponent(a))).join(s);switch(r.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return`${e}=${o}`}}const n={simple:",",label:".",matrix:";"}[r.style]||"&",i=[];for(const s of t)r.style==="simple"||r.style==="label"?i.push(r.allowReserved===!0?s:encodeURIComponent(s)):i.push(Se(e,s,r));return r.style==="label"||r.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Kt(e){return function(r){const n=[];if(r&&typeof r=="object")for(const i in r){const s=r[i];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;n.push(Jt(i,s,{style:"form",explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof s=="object"){n.push(Gt(i,s,{style:"deepObject",explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(Se(i,s,e))}}return n.join("&")}}function Mn(e,t){let r=e;for(const n of e.match(Cn)??[]){let i=n.substring(1,n.length-1),s=!1,o="simple";if(i.endsWith("*")&&(s=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(o="label",i=i.substring(1)):i.startsWith(";")&&(o="matrix",i=i.substring(1)),!t||t[i]===void 0||t[i]===null)continue;const a=t[i];if(Array.isArray(a)){r=r.replace(n,Jt(i,a,{style:o,explode:s}));continue}if(typeof a=="object"){r=r.replace(n,Gt(i,a,{style:o,explode:s}));continue}if(o==="matrix"){r=r.replace(n,`;${Se(i,a)}`);continue}r=r.replace(n,o==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return r}function jn(e,t){return e instanceof FormData?e:t&&(t.get instanceof Function?t.get("Content-Type")??t.get("content-type"):t["Content-Type"]??t["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(e).toString():JSON.stringify(e)}function Hn(e,t){let r=`${t.baseUrl}${e}`;t.params?.path&&(r=t.pathSerializer(r,t.params.path));let n=t.querySerializer(t.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(r+=`?${n}`),r}function Zt(...e){const t=new Headers;for(const r of e){if(!r||typeof r!="object")continue;const n=r instanceof Headers?r.entries():Object.entries(r);for(const[i,s]of n)if(s===null)t.delete(i);else if(Array.isArray(s))for(const o of s)t.append(i,o);else s!==void 0&&t.set(i,s)}return t}function Yt(e){return e.endsWith("/")?e.substring(0,e.length-1):e}function $n(e){return((t,r)=>{const n=e??globalThis.fetch;return typeof n!="function"?Promise.reject(new Ht(re.FETCH_UNAVAILABLE,{missing:["fetch"]})):n(t,r)})}function Bn(e={}){const t=String(e.apiVersion??"_");if(t!=="_"&&!/^\d{10}$/.test(t))throw new TypeError("apiVersion must be `_` or a Unix timestamp in seconds");const r=new z(e.endpoint??"https://api.andco.cl"),n=zn({baseUrl:sn(r,t),fetch:e.fetch??$n()});return n.use({async onRequest({request:i}){let s;return typeof e.accessToken=="function"?s=await e.accessToken():s=e.accessToken,s&&i.headers.set("Authorization",`Bearer ${s}`),i}}),n}var Vn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wn=/^[A-Za-z0-9._:-]{1,128}$/,Qt=class{#e;#t;#r;#n;constructor(e){this.#e=e.rest,this.#t=e.config,this.#r=e.presenter,this.#n=e.crypto}async create(e,t,r={}){const n=r.idempotencyKey??Pe(this.#n);if(!Wn.test(n))return u.fail(m.INVALID_CONFIGURATION,{message:"malformed Idempotency-Key"});let i;try{({data:i}=await this.#e.http.POST("/intents",{params:{header:{"Idempotency-Key":n}},body:{...t,type:e}}).throwOnError())}catch(s){return u.fail(s)}return i?.type!==e?u.fail(m.INVALID_RESPONSE,{message:`expected a ${e} intent`}):u.ok(i)}async presentationURL(e){if(!this.#t)return u.fail(rt());const t=Re(e.intentId);if(t)return u.fail(t);if(e.returnTo.origin!==e.errorReturnTo.origin)return u.fail(m.INVALID_CONFIGURATION,{message:"returnTo and errorReturnTo must share one origin"});const r=await this.get(e.intentId);if(r.error)return u.fail(r.error);let n;try{n=Ln(r.data,this.#t.endpoints.api)}catch(i){return u.fail(v.from(i,m.INVALID_RESPONSE))}return n.searchParams.set("return_uri",e.returnTo.href),n.searchParams.set("error_return_uri",e.errorReturnTo.href),n.searchParams.set("presentation",e.presentation),n.searchParams.set("state",e.state),u.ok(n)}async present(e){if(!this.#t||!this.#r)return u.fail(rt());const t=e.returnTo?new z(e.returnTo):this.#t.redirectTo;if(!t)return u.fail(m.INVALID_CONFIGURATION,{message:"an Intent Presentation needs a returnTo, and this instance has no redirectTo"});const r=e.errorReturnTo?new z(e.errorReturnTo):t,n=Pe(this.#n),i=$t(t.origin,n);let s;const o=await this.#r.present({kind:"intent",presentation:"popup",url:async()=>{try{s=typeof e.intentId=="string"?e.intentId:await e.intentId()}catch(l){return u.fail(v.from(l,m.INVALID_CONFIGURATION))}return this.presentationURL({intentId:s,presentation:"popup",returnTo:t,errorReturnTo:r,state:i})},get intentId(){return s??""},returnTo:t,errorReturnTo:r,presentationId:n,...e.signal===void 0?{}:{signal:e.signal}});if(o.error)return u.fail(o.error);if(!s)return u.fail(rt());const a=Fn(o.data,{presentationId:n});if(a.error)return u.fail(a.error);console.debug("[AndcoIntents.present] settled: %s %o",a.data,{intentId:s,presentationId:n});const c=await this.get(s);return c.error?u.fail(c.error):u.ok({outcome:a.data,intent:c.data})}async get(e){const t=Re(e);if(t)return u.fail(t);try{const{data:r}=await this.#e.http.GET("/intents/{intent_id}",{params:{path:{intent_id:e}}}).throwOnError();return u.ok(r)}catch(r){return u.fail(r)}}async execute(e){const t=Re(e);if(t)return u.fail(t);try{return await this.#e.http.POST("/intents/{intent_id}/execute",{params:{path:{intent_id:e}}}).throwOnError(),u.ok(void 0)}catch(r){return u.fail(r)}}async events(e,t,r){const n=Re(e);if(n)return u.fail(n);try{const{data:i}=await this.#e.http.GET("/intents/{intent_id}/events",{params:{path:{intent_id:e},query:{after:t,limit:100}},signal:r}).throwOnError();return u.ok(i)}catch(i){return u.fail(i)}}subscribe(e,t,r,n,i){const s=Un(async(o,a)=>{const c=await t(o,a);if(c.error)throw c.error;return c.data},r,async o=>{await n(o),i.onCheckpoint?.(o.cursor)},{...i.after===void 0?{}:{after:i.after},onError:i.onError,...i.pollIntervalMs===void 0?{}:{pollIntervalMs:i.pollIntervalMs}},e);return()=>s.unsubscribe()}};function Fn(e,t){if(!e)return u.ok("dismiss");const r=e.searchParams.get("state"),n=r?Bt(r):null;if(!n||n.presentationId!==t.presentationId)return u.fail(m.INVALID_CALLBACK,{message:"the callback does not belong to this presentation"});const i=e.searchParams.get("andco_intent_result");return i==="complete"?u.ok("complete"):i==="dismiss"?u.ok("dismiss"):u.fail(m.INVALID_CALLBACK,{message:"the callback carries no Intent result"})}function rt(){return new v(m.PRESENTATION_UNSUPPORTED,{message:"this Intent surface was composed without a presenter; present through the Andco Instance instead"})}function Re(e){return Vn.test(e)?null:new v(m.INVALID_INTENT_ID,{message:`${e} is not a valid identifier`})}var nt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(nt="oauth4webapi/v3.8.8");function ne(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var M="ERR_INVALID_ARG_VALUE",$="ERR_INVALID_ARG_TYPE";function b(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}var B=Symbol(),Oe=Symbol(),it=Symbol(),q=Symbol(),G=Symbol(),qn=new TextEncoder,Gn=new TextDecoder;function st(e){return typeof e=="string"?qn.encode(e):Gn.decode(e)}var ot;Uint8Array.prototype.toBase64?ot=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):ot=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var at;Uint8Array.fromBase64?at=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw b("The input to be decoded is not correctly encoded.",M,t)}}:at=e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch(t){throw b("The input to be decoded is not correctly encoded.",M,t)}};function Ne(e){return typeof e=="string"?at(e):ot(e)}var ge=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=_t,Error.captureStackTrace?.(this,this.constructor)}},ct=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,t?.code&&(this.code=t?.code),Error.captureStackTrace?.(this,this.constructor)}};function p(e,t,r){return new ct(e,{code:t,cause:r})}function ke(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function we(e){ne(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(e??{});if(nt&&!t.has("user-agent")&&t.set("user-agent",nt),t.has("authorization"))throw b('"options.headers" must not include the "authorization" header name',M);return t}function Xt(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw b('"options.signal" must return or be an instance of AbortSignal',$);return t}}function ie(e,t,r,n,i){try{if(typeof e!="number"||!Number.isFinite(e))throw b(`${r} must be a number`,$,i);if(e>0)return;if(t){if(e!==0)throw b(`${r} must be a non-negative number`,M,i);return}throw b(`${r} must be a positive number`,M,i)}catch(s){throw n?p(s.message,n,i):s}}function T(e,t,r,n){try{if(typeof e!="string")throw b(`${t} must be a string`,$,n);if(e.length===0)throw b(`${t} must not be empty`,M,n)}catch(i){throw r?p(i.message,r,n):i}}function er(e){Kn(e,"application/json")}function Jn(e,...t){let r='"response" content-type must be ';if(t.length>2){const n=t.pop();r+=`${t.join(", ")}, or ${n}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return p(r,vr,e)}function Kn(e,t){if(Ce(e)!==t)throw Jn(e,t)}function tr(){return Ne(crypto.getRandomValues(new Uint8Array(32)))}function Zn(){return tr()}function Yn(){return tr()}async function Qn(e){return T(e,"codeVerifier"),Ne(await crypto.subtle.digest("SHA-256",st(e)))}function Ue(e){const t=e?.[Oe];return typeof t=="number"&&Number.isFinite(t)?t:0}function ut(e){const t=e?.[it];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function rr(){return Math.floor(Date.now()/1e3)}function V(e){if(typeof e!="object"||e===null)throw b('"as" must be an object',$);T(e.issuer,'"as.issuer"')}function W(e){if(typeof e!="object"||e===null)throw b('"client" must be an object',$);T(e.client_id,'"client.client_id"')}function nr(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function ir(e){return T(e,'"clientSecret"'),(t,r,n,i)=>{n.set("client_id",r.client_id),n.set("client_secret",e)}}function sr(e){return T(e,'"clientSecret"'),(t,r,n,i)=>{const s=nr(r.client_id),o=nr(e),a=btoa(`${s}:${o}`);i.set("authorization",`Basic ${a}`)}}function Xn(){return(e,t,r,n)=>{r.set("client_id",t.client_id)}}var ei=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function or(e,t){if(t&&e.protocol!=="https:")throw p("only requests to HTTPS are allowed",br,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw p("only HTTP and HTTPS requests are allowed",Ar,e)}function ar(e,t,r,n){let i;if(typeof e!="string"||!(i=ei(e)))throw p(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?ki:Ui,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return or(i,n),i}function ve(e,t,r,n){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?ar(e.mtls_endpoint_aliases[t],t,r,n):ar(e[t],t,r,n)}async function ti(e,t,r,n,i){V(e),W(t);const s=ve(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,i?.[B]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=we(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(ht(i.DPoP),await i.DPoP.addProof(s,a,"POST"));const c=await ft(e,t,r,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}function ri(e){return e instanceof lt?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof Le?e.error==="use_dpop_nonce":!1}var Le=class extends Error{cause;code;error;status;error_description;response;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ri,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:t.response}),Error.captureStackTrace?.(this,this.constructor)}},cr=class extends Error{cause;code;error;error_description;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Oi,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=t.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},lt=class extends Error{cause;code;response;status;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Si,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ni=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),ii=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),si=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),oi=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function ai(e){if(!ne(e,Response))throw b('"response" must be an instance of Response',$);const t=e.headers.get("www-authenticate");if(t===null)return;const r=[];let n=t;for(;n;){let i=n.match(ni);const s=i?.[1].toLowerCase();if(!s)return;const o=n.substring(i[0].length);if(o&&!o.match(/^[\s,]/))return;const a=o.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;const l={};let f;if(c)for(;n;){let h,d;if(i=n.match(ii)){[,h,d,n]=i,d.includes("\\")&&(d=d.replace(/\\([\s\S])/g,"$1")),l[h.toLowerCase()]=d;continue}if(i=n.match(si)){[,h,d,n]=i,l[h.toLowerCase()]=d;continue}if(i=n.match(oi)){if(Object.keys(l).length)break;[,f,n]=i;break}return}else n=o||void 0;const y={scheme:s,parameters:l};f&&(y.token68=f),r.push(y)}if(r.length)return r}async function ci(e,t,r){if(V(e),W(t),!ne(r,Response))throw b('"response" must be an instance of Response',$);await dt(r,201,"Pushed Authorization Request Endpoint"),be(r);const n=await He(r);T(n.request_uri,'"response" body "request_uri" property',_,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',_,{body:n}),n.expires_in=i,n}async function ui(e){if(e.status>399&&e.status<500){be(e),er(e);try{const t=await e.clone().json();if(ke(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function dt(e,t,r){if(e.status!==t){hr(e);let n;throw(n=await ui(e))?(await e.body?.cancel(),new Le("server responded with an error in the response body",{cause:n,response:e})):p(`"response" is not a conform ${r} response (unexpected HTTP status code)`,gt,e)}}function ht(e){if(!yt.has(e))throw b('"options.DPoP" is not a valid DPoPHandle',M)}async function li(e,t,r,n,i,s){if(T(e,'"accessToken"'),!(r instanceof URL))throw b('"url" must be an instance of URL',$);or(r,s?.[B]!==!0),n=we(n),s?.DPoP&&(ht(s.DPoP),await s.DPoP.addProof(r,n,t.toUpperCase(),e)),n.set("authorization",`${n.has("dpop")?"DPoP":"Bearer"} ${e}`);const o=await(s?.[q]||fetch)(r.href,{duplex:ne(i,ReadableStream)?"half":void 0,body:i,headers:Object.fromEntries(n.entries()),method:t,redirect:"manual",signal:Xt(r,s?.signal)});return s?.DPoP?.cacheNonce(o,r),o}async function di(e,t,r,n){V(e),W(t);const i=ve(e,"userinfo_endpoint",t.use_mtls_endpoint_aliases,n?.[B]!==!0),s=we(n?.headers);return t.userinfo_signed_response_alg?s.set("accept","application/jwt"):(s.set("accept","application/json"),s.append("accept","application/jwt")),li(r,"GET",i,s,null,{...n,[Oe]:Ue(t)})}var ur=Symbol();function Ce(e){return e.headers.get("content-type")?.split(";")[0]}async function hi(e,t,r,n,i){if(V(e),W(t),!ne(n,Response))throw b('"response" must be an instance of Response',$);if(hr(n),n.status!==200)throw p('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)',gt,n);be(n);let s;if(Ce(n)==="application/jwt"){const{claims:o,jwt:a}=await Ir(await n.text(),Er.bind(void 0,t.userinfo_signed_response_alg,e.userinfo_signing_alg_values_supported,void 0),Ue(t),ut(t),i?.[G]).then(mi.bind(void 0,t.client_id)).then(yi.bind(void 0,e));dr.set(n,a),s=o}else{if(t.userinfo_signed_response_alg)throw p("JWT UserInfo Response expected",Ni,n);s=await He(n)}switch(T(s.sub,'"response" body "sub" property',_,{body:s}),r){case ur:break;default:if(T(r,'"expectedSubject"'),s.sub!==r)throw p('unexpected "response" body "sub" property value',Tr,{expected:r,body:s,attribute:"sub"})}return s}async function ft(e,t,r,n,i,s,o){return await r(e,t,i,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(o?.[q]||fetch)(n.href,{body:i,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Xt(n,o?.signal)})}async function pt(e,t,r,n,i,s){const o=ve(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[B]!==!0);i.set("grant_type",n);const a=we(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(ht(s.DPoP),await s.DPoP.addProof(o,a,"POST"));const c=await ft(e,t,r,o,i,a,s);return s?.DPoP?.cacheNonce(c,o),c}async function fi(e,t,r,n,i){V(e),W(t),T(n,'"refreshToken"');const s=new URLSearchParams(i?.additionalParameters);return s.set("refresh_token",n),pt(e,t,r,"refresh_token",s,i)}var lr=new WeakMap,dr=new WeakMap;function mt(e){if(!e.id_token)return;const t=lr.get(e);if(!t)throw b('"ref" was already garbage collected or did not resolve from the proper sources',M);return t}async function De(e,t,r,n,i,s){if(V(e),W(t),!ne(r,Response))throw b('"response" must be an instance of Response',$);await dt(r,200,"Token Endpoint"),be(r);const o=await He(r);if(T(o.access_token,'"response" body "access_token" property',_,{body:o}),T(o.token_type,'"response" body "token_type" property',_,{body:o}),o.token_type=o.token_type.toLowerCase(),o.expires_in!==void 0){let a=typeof o.expires_in!="number"?parseFloat(o.expires_in):o.expires_in;ie(a,!0,'"response" body "expires_in" property',_,{body:o}),o.expires_in=a}if(o.refresh_token!==void 0&&T(o.refresh_token,'"response" body "refresh_token" property',_,{body:o}),o.scope!==void 0&&typeof o.scope!="string")throw p('"response" body "scope" property must be a string',_,{body:o});if(o.id_token!==void 0){T(o.id_token,'"response" body "id_token" property',_,{body:o});const a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ie(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);const{claims:c,jwt:l}=await bi(e,t,o.id_token,a,i);Ti(t,c),Ai(c),dr.set(r,l),lr.set(o,c)}if(s?.[o.token_type]!==void 0)s[o.token_type](r,o);else if(o.token_type!=="dpop"&&o.token_type!=="bearer")throw new ge("unsupported `token_type` value",{cause:{body:o}});return o}function hr(e){let t;if(t=ai(e))throw new lt("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function pi(e,t,r,n){return De(e,t,r,void 0,n?.[G],n?.recognizedTokenTypes)}function mi(e,t){return t.claims.aud!==void 0?fr(e,t):t}function fr(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"});return t}function yi(e,t){return t.claims.iss!==void 0?pr(e,t):t}function pr(e,t){const r=e[Pr]?.(t)??e.issuer;if(t.claims.iss!==r)throw p('unexpected JWT "iss" (issuer) claim value',se,{expected:r,claims:t.claims,claim:"iss"});return t}var yt=new WeakSet;function _i(e){return yt.add(e),e}var mr=Symbol();async function gi(e,t,r,n,i,s,o){if(V(e),W(t),!yt.has(n))throw b('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',M);T(i,'"redirectUri"');const a=oe(n,"code");if(!a)throw p('no authorization code in "callbackParameters"',_);const c=new URLSearchParams(o?.additionalParameters);return c.set("redirect_uri",i),c.set("code",a),s!==mr&&(T(s,'"codeVerifier"'),c.set("code_verifier",s)),pt(e,t,r,"authorization_code",c,o)}var yr={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function wi(e,t){for(const r of e)if(t.claims[r]===void 0)throw p(`JWT "${r}" (${yr[r]}) claim missing`,_,{claims:t.claims});return t}function vi(e,t){if(typeof t.claims[e]!="string")throw p(`unexpected JWT "${e}" (${yr[e]}) claim type`,_,{claims:t.claims});return t}function bi(e,t,r,n,i){return Ir(r,Er.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Ue(t),ut(t),i).then(wi.bind(void 0,["aud","exp","iat","iss","sub",...n])).then(pr.bind(void 0,e)).then(fr.bind(void 0,t.client_id)).then(vi.bind(void 0,"sub"))}function _r(e,t){if(t===ze)return t;const r=t===void 0;return r&&(t=e.default_max_age),t===void 0?ze:(ie(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function Ai(e){e.auth_time!==void 0&&ie(e.auth_time,!0,'ID Token "auth_time" (authentication time)',_,{claims:e})}function gr(e,t,r){if(r===ze)return;const n=rr()+Ue(e),i=ut(e);if(t.auth_time+r<n-i)throw p("too much time has elapsed since the last End-User authentication",je,{claims:t,now:n,tolerance:i,claim:"auth_time"})}function wr(e,t){const r=t===xe?void 0:t;if(e.nonce!==r)throw p('unexpected ID Token "nonce" claim value',se,{expected:r,claims:e,claim:"nonce"})}function Ti(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw p('ID Token "aud" (audience) claim includes additional untrusted audiences',se,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw p('unexpected ID Token "azp" (authorized party) claim value',se,{expected:e.client_id,claims:t,claim:"azp"})}}var xe=Symbol(),ze=Symbol();async function Ii(e,t,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?Ei(e,t,r,n.expectedNonce,n.maxAge,n[G],n.recognizedTokenTypes):Pi(e,t,r,n?.maxAge,n?.[G],n?.recognizedTokenTypes)}async function Ei(e,t,r,n,i,s,o){const a=[];switch(n){case void 0:n=xe;break;case xe:break;default:T(n,'"expectedNonce" argument'),a.push("nonce")}i=_r(t,i),i!==ze&&a.push("auth_time");const c=await De(e,t,r,a,s,o);T(c.id_token,'"response" body "id_token" property',_,{body:c});const l=mt(c);return gr(t,l,i),wr(l,n),c}async function Pi(e,t,r,n,i,s){const o=await De(e,t,r,void 0,i,s),a=mt(o);return a&&(gr(t,a,_r(t,n)),wr(a,xe)),o}var Si="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ri="OAUTH_RESPONSE_BODY_ERROR",_t="OAUTH_UNSUPPORTED_OPERATION",Oi="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Ni="OAUTH_JWT_USERINFO_EXPECTED",Me="OAUTH_PARSE_ERROR",_="OAUTH_INVALID_RESPONSE",vr="OAUTH_RESPONSE_IS_NOT_JSON",gt="OAUTH_RESPONSE_IS_NOT_CONFORM",br="OAUTH_HTTP_REQUEST_FORBIDDEN",Ar="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",je="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",se="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Tr="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",ki="OAUTH_MISSING_SERVER_METADATA",Ui="OAUTH_INVALID_SERVER_METADATA";function be(e){if(e.bodyUsed)throw b('"response" body has been used already',M)}async function Ir(e,t,r,n,i){let{0:s,1:o,length:a}=e.split(".");if(a===5)if(i!==void 0)e=await i(e),{0:s,1:o,length:a}=e.split(".");else throw new ge("JWE decryption is not configured",{cause:e});if(a!==3)throw p("Invalid JWT",_,e);let c;try{c=JSON.parse(st(Ne(s)))}catch(y){throw p("failed to parse JWT Header body as base64url encoded JSON",Me,y)}if(!ke(c))throw p("JWT Header must be a top level object",_,e);if(t(c),c.crit!==void 0)throw new ge('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let l;try{l=JSON.parse(st(Ne(o)))}catch(y){throw p("failed to parse JWT Payload body as base64url encoded JSON",Me,y)}if(!ke(l))throw p("JWT Payload must be a top level object",_,e);const f=rr()+r;if(l.exp!==void 0){if(typeof l.exp!="number")throw p('unexpected JWT "exp" (expiration time) claim type',_,{claims:l});if(l.exp<=f-n)throw p('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',je,{claims:l,now:f,tolerance:n,claim:"exp"})}if(l.iat!==void 0&&typeof l.iat!="number")throw p('unexpected JWT "iat" (issued at) claim type',_,{claims:l});if(l.iss!==void 0&&typeof l.iss!="string")throw p('unexpected JWT "iss" (issuer) claim type',_,{claims:l});if(l.nbf!==void 0){if(typeof l.nbf!="number")throw p('unexpected JWT "nbf" (not before) claim type',_,{claims:l});if(l.nbf>f+n)throw p('unexpected JWT "nbf" (not before) claim value',je,{claims:l,now:f,tolerance:n,claim:"nbf"})}if(l.aud!==void 0&&typeof l.aud!="string"&&!Array.isArray(l.aud))throw p('unexpected JWT "aud" (audience) claim type',_,{claims:l});return{header:c,claims:l,jwt:e}}async function Li(e){if(e.bodyUsed)throw b("form_post Request instances must contain a readable body",M,{cause:e});return e.text()}async function Ci(e){if(e.method!=="POST")throw b("form_post responses are expected to use the POST method",M,{cause:e});if(Ce(e)!=="application/x-www-form-urlencoded")throw b("form_post responses are expected to use the application/x-www-form-urlencoded content-type",M,{cause:e});return Li(e)}function Er(e,t,r,n){if(e!==void 0){if(typeof e=="string"?n.alg!==e:!e.includes(n.alg))throw p('unexpected JWT "alg" header parameter',_,{header:n,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(n.alg))throw p('unexpected JWT "alg" header parameter',_,{header:n,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw p('unexpected JWT "alg" header parameter',_,{header:n,expected:r,reason:"default value"});return}throw p('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function oe(e,t){const{0:r,length:n}=e.getAll(t);if(n>1)throw p(`"${t}" parameter must be provided only once`,_);return r}var Di=Symbol(),xi=Symbol();function zi(e,t,r,n){if(V(e),W(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw b('"parameters" must be an instance of URLSearchParams, or URL',$);if(oe(r,"response"))throw p('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',_,{parameters:r});const i=oe(r,"iss"),s=oe(r,"state");if(!i&&e.authorization_response_iss_parameter_supported)throw p('response parameter "iss" (issuer) missing',_,{parameters:r});if(i&&i!==e.issuer)throw p('unexpected "iss" (issuer) response parameter value',_,{expected:e.issuer,parameters:r});switch(n){case void 0:case xi:if(s!==void 0)throw p('unexpected "state" response parameter encountered',_,{expected:void 0,parameters:r});break;case Di:break;default:if(T(n,'"expectedState" argument'),s!==n)throw p(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',_,{expected:n,parameters:r})}if(oe(r,"error"))throw new cr("authorization response from the server is an error",{cause:r});const o=oe(r,"id_token"),a=oe(r,"token");if(o!==void 0||a!==void 0)throw new ge("implicit and hybrid flows are not supported");return _i(new URLSearchParams(r))}async function Mi(e,t,r,n,i){V(e),W(t);const s=ve(e,"device_authorization_endpoint",t.use_mtls_endpoint_aliases,i?.[B]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=we(i?.headers);return a.set("accept","application/json"),ft(e,t,r,s,o,a,i)}async function ji(e,t,r){if(V(e),W(t),!ne(r,Response))throw b('"response" must be an instance of Response',$);await dt(r,200,"Device Authorization Endpoint"),be(r);const n=await He(r);T(n.device_code,'"response" body "device_code" property',_,{body:n}),T(n.user_code,'"response" body "user_code" property',_,{body:n}),T(n.verification_uri,'"response" body "verification_uri" property',_,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',_,{body:n}),n.expires_in=i,n.verification_uri_complete!==void 0&&T(n.verification_uri_complete,'"response" body "verification_uri_complete" property',_,{body:n}),n.interval!==void 0&&ie(n.interval,!1,'"response" body "interval" property',_,{body:n}),n}async function Hi(e,t,r,n,i){V(e),W(t),T(n,'"deviceCode"');const s=new URLSearchParams(i?.additionalParameters);return s.set("device_code",n),pt(e,t,r,"urn:ietf:params:oauth:grant-type:device_code",s,i)}async function $i(e,t,r,n){return De(e,t,r,void 0,n?.[G],n?.recognizedTokenTypes)}async function He(e,t=er){let r;try{r=await e.json()}catch(n){throw t(e),p('failed to parse "response" body as JSON',Me,n)}if(!ke(r))throw p('"response" body must be a top level object',_,{body:r});return r}var Pr=Symbol(),ae,Sr;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Sr="openid-client/v6.8.8",ae={"user-agent":Sr});var D=e=>wt.get(e),wt;function Bi(e){if(e!==void 0)return ir(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Rr(n.client_secret,'"metadata.client_secret"'),o=ir(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Rr(e,t){if(typeof e!="string")throw J(`${t} must be a string`,$e);if(e.length===0)throw J(`${t} must not be empty`,Ae)}function Vi(e){if(e!==void 0)return sr(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Rr(n.client_secret,'"metadata.client_secret"'),o=sr(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Or(){return Xn()}var Wi=ur,vt=q,Ae="ERR_INVALID_ARG_VALUE",$e="ERR_INVALID_ARG_TYPE";function J(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}function Fi(e){return Qn(e)}function qi(){return Zn()}function Gi(){return Yn()}var bt=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=t?.code,Error.captureStackTrace?.(this,this.constructor)}},Ys=new TextDecoder;function N(e,t,r){return new bt(e,{cause:t,code:r})}function j(e){if(e instanceof TypeError||e instanceof bt||e instanceof Le||e instanceof cr||e instanceof lt)throw e;if(e instanceof ct)switch(e.code){case br:throw N("only requests to HTTPS are allowed",e,e.code);case Ar:throw N("only requests to HTTP or HTTPS are allowed",e,e.code);case gt:throw N("unexpected HTTP response status code",e.cause,e.code);case vr:throw N("unexpected response content-type",e.cause,e.code);case Me:throw N("parsing error occured",e,e.code);case _:throw N("invalid response encountered",e,e.code);case se:throw N("unexpected JWT claim value encountered",e,e.code);case Tr:throw N("unexpected JSON attribute value encountered",e,e.code);case je:throw N("JWT timestamp claim value failed validation",e,e.code);default:throw N(e.message,e,e.code)}if(e instanceof ge)throw N("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw N("runtime operation error",e,_t);case"NotSupportedError":throw N("runtime unsupported operation",e,_t);case"TimeoutError":throw N("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw N("operation aborted",e,"OAUTH_ABORT")}throw new bt("something went wrong",{cause:e})}function Ji(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Ki(e){Object.defineProperties(e,Ji(e))}var Zi=Symbol(),Be=class{constructor(e,t,r,n){if(typeof t!="string"||!t.length)throw J('"clientId" must be a non-empty string',$e);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&t!==r.client_id)throw J('"clientId" and "metadata.client_id" must be the same',Ae);const i={...structuredClone(r),client_id:t};i[Oe]=r?.[Oe]??0,i[it]=r?.[it]??30;let s;n?s=n:typeof i.client_secret=="string"&&i.client_secret.length?s=Bi(i.client_secret):s=Or();let o=Object.freeze(i);const a=structuredClone(e);Zi in e&&(a[Pr]=({claims:{tid:l}})=>e.issuer.replace("{tenantid}",l));let c=Object.freeze(a);wt||=new WeakMap,wt.set(this,{__proto__:null,as:c,c:o,auth:s,tlsOnly:!0,timeout:30,jwksCache:{}})}serverMetadata(){const e=structuredClone(D(this).as);return Ki(e),e}clientMetadata(){return structuredClone(D(this).c)}get timeout(){return D(this).timeout}set timeout(e){D(this).timeout=e}get[vt](){return D(this).fetch}set[vt](e){D(this).fetch=e}};Object.freeze(Be.prototype);function Yi(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){const r=Date.now();return t>r?Math.floor((t-r)/1e3):0}}},claims:{__proto__:null,value(){return mt(e)}}}}function At(e){Object.defineProperties(e,Yi(e))}async function Nr(e,t,r,n=!1){const i=e.headers.get("retry-after")?.trim();if(i===void 0)return;let s;if(/^\d+$/.test(i))s=parseInt(i,10);else{const o=new Date(i);if(Number.isFinite(o.getTime())){const a=new Date,c=o.getTime()-a.getTime();c>0&&(s=Math.ceil(c/1e3))}}if(n&&!Number.isFinite(s))throw new ct("invalid Retry-After header value",{cause:e});s>t&&await kr(s-t,r)}function kr(e,t){return new Promise((r,n)=>{const i=s=>{try{t.throwIfAborted()}catch(a){n(a);return}if(s<=0){r();return}const o=Math.min(s,5);setTimeout(()=>i(s-o),o*1e3)};i(e)})}function Qi(e,t){const r=me(t);if(!r)return{signal:e,cleanup(){}};const n=new AbortController,i=s=>{const o=s.target;n.abort(o.reason)};return e.aborted?n.abort(e.reason):r.aborted?n.abort(r.reason):(e.addEventListener("abort",i,{once:!0}),r.addEventListener("abort",i,{once:!0})),{signal:n.signal,cleanup(){e.removeEventListener("abort",i),r.removeEventListener("abort",i)}}}async function Xi(e,t,r,n,i,s,o){const a=new URLSearchParams(s);let c=t.interval??5;const l=o?.signal??AbortSignal.timeout(t.expires_in*1e3);for(;;){try{await kr(c,l)}catch(g){j(g)}const{as:f,c:y,auth:h,fetch:d,tlsOnly:w,nonRepudiation:R,timeout:I,decrypt:k}=D(e),U=Qi(l,I);try{const g=await n(f,y,h,r,{[q]:d,[B]:!w,additionalParameters:a,DPoP:o?.DPoP,headers:new Headers(ae),signal:U.signal}).catch(j);if(g.status===503&&g.headers.has("retry-after")){await g.body?.cancel(),await Nr(g,c,l,!0),o={...o,flag:void 0};continue}let E;try{E=await i(f,y,g,{[G]:k})}catch(A){if(Te(A,o)){o={...o,flag:Q};continue}if(A instanceof Le&&(A.error==="slow_down"||A.error==="authorization_pending")){A.error==="slow_down"&&(c+=5),await Nr(A.response,c,l),o={...o,flag:void 0};continue}j(A)}return E.id_token&&await R?.(g),At(E),E}finally{U.cleanup()}}}async function es(e,t,r,n){return ce(e),Xi(e,t,t.device_code,Hi,$i,r,n)}async function ts(e,t){ce(e);const{as:r,c:n,auth:i,fetch:s,tlsOnly:o,timeout:a}=D(e);return Mi(r,n,i,t,{[q]:s,[B]:!o,headers:new Headers(ae),signal:me(a)}).then(c=>ji(r,n,c)).catch(j)}function rs(e){D(e).tlsOnly=!1}function ns(e){return e=new URL(e),e.search="",e.hash="",e.href}function is(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Ur(e,t,r,n,i){if(ce(e),i?.flag!==Q&&!(t instanceof URL)&&!is(t,"Request"))throw J('"currentUrl" must be an instance of URL, or Request',$e);let s,o;const{as:a,c,auth:l,fetch:f,tlsOnly:y,jarm:h,hybrid:d,nonRepudiation:w,timeout:R,decrypt:I,implicit:k}=D(e);if(i?.flag===Q)s=i.authResponse,o=i.redirectUri;else{if(!(t instanceof URL)){const A=t;switch(t=new URL(t.url),A.method){case"GET":break;case"POST":const le=new URLSearchParams(await Ci(A));if(d)t.hash=le.toString();else for(const[Ve,Pt]of le.entries())t.searchParams.append(Ve,Pt);break;default:throw J("unexpected Request HTTP method",Ae)}}switch(o=ns(t),!0){case!!h:s=await h(t,r?.expectedState);break;case!!d:s=await d(t,r?.expectedNonce,r?.expectedState,r?.maxAge);break;case!!k:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{s=zi(a,c,t.searchParams,r?.expectedState)}catch(A){j(A)}}}const U=await gi(a,c,l,s,o,r?.pkceCodeVerifier||mr,{additionalParameters:n,[q]:f,[B]:!y,DPoP:i?.DPoP,headers:new Headers(ae),signal:me(R)}).catch(j);(typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number")&&(r.idTokenExpected=!0);const g=Ii(a,c,U,{expectedNonce:r?.expectedNonce,maxAge:r?.maxAge,requireIdToken:r?.idTokenExpected,[G]:I});let E;try{E=await g}catch(A){if(Te(A,i))return Ur(e,void 0,r,n,{...i,flag:Q,authResponse:s,redirectUri:o});j(A)}return E.id_token&&await w?.(U),At(E),E}async function Lr(e,t,r,n){ce(e),r=new URLSearchParams(r);const{as:i,c:s,auth:o,fetch:a,tlsOnly:c,nonRepudiation:l,timeout:f,decrypt:y}=D(e),h=await fi(i,s,o,t,{[q]:a,[B]:!c,additionalParameters:r,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(f)}).catch(j),d=pi(i,s,h,{[G]:y});let w;try{w=await d}catch(R){if(Te(R,n))return Lr(e,t,r,{...n,flag:Q});j(R)}return w.id_token&&await l?.(h),At(w),w}function Tt(e,t){ce(e);const{as:r,c:n,tlsOnly:i,hybrid:s,jarm:o,implicit:a}=D(e),c=ve(r,"authorization_endpoint",!1,i);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",n.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",s?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw J("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Ae);o&&t.set("response_mode","jwt")}for(const[l,f]of t.entries())c.searchParams.append(l,f);return c}async function Cr(e,t,r){ce(e);const n=Tt(e,t),{as:i,c:s,auth:o,fetch:a,tlsOnly:c,timeout:l}=D(e),f=await ti(i,s,o,n.searchParams,{[q]:a,[B]:!c,DPoP:r?.DPoP,headers:new Headers(ae),signal:me(l)}).catch(j),y=ci(i,s,f);let h;try{h=await y}catch(d){if(Te(d,r))return Cr(e,t,{...r,flag:Q});j(d)}return Tt(e,{request_uri:h.request_uri})}function ce(e){if(!(e instanceof Be))throw J('"config" must be an instance of Configuration',$e);if(Object.getPrototypeOf(e)!==Be.prototype)throw J("subclassing Configuration is not allowed",Ae)}function me(e){return e?AbortSignal.timeout(e*1e3):void 0}async function Dr(e,t,r,n){ce(e);const{as:i,c:s,fetch:o,tlsOnly:a,nonRepudiation:c,timeout:l,decrypt:f}=D(e),y=await di(i,s,t,{[q]:o,[B]:!a,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(l)}).catch(j);let h=hi(i,s,r,y,{[G]:f}),d;try{d=await h}catch(w){if(Te(w,n))return Dr(e,t,r,{...n,flag:Q});j(w)}return Ce(y)==="application/jwt"&&await c?.(y),d}function Te(e,t){return t?.DPoP&&t.flag!==Q?ri(e):!1}var Q=Symbol(),ss={issuer:"{issuer}",authorization_endpoint:"{issuer}/oauth/authorize",token_endpoint:"{issuer}/oauth/token",device_authorization_endpoint:"{issuer}/oauth/device/authorize",jwks_uri:"{issuer}/.well-known/jwks.json",userinfo_endpoint:"{issuer}/oauth/userinfo",registration_endpoint:"{issuer}/oauth/clients/register",scopes_supported:["openid","profile","email","phone","offline_access"],response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:device_code"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256","HS256","ES256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],claims_supported:["sub","aud","iss","exp","iat","auth_time","nonce","email","email_verified","phone_number","phone_number_verified","name","picture","preferred_username","updated_at"],code_challenge_methods_supported:["S256","plain"],pushed_authorization_request_endpoint:"{issuer}/oauth/par"};function os(e){return JSON.parse(JSON.stringify(ss).replaceAll("{issuer}",e))}var as=6e5,cs=2048,us=["authorization_details","login_hint"],ls=class{#e;#t;#r;#n;#i;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#r=e.clientSecret??null,this.#n=e.transport??"auto"}get isConfidential(){return this.#r!==null}async createAuthorizationRequest(e={}){try{const t=this.#l(e.redirectTo),r=qi(),n=await Fi(r),i=e.state??Gi(),s=this.#f(e,t,i,n),o=await this.#d(s);return u.ok({authorizationUrl:o,codeVerifier:r,state:i,redirectTo:t,createdAt:Date.now()})}catch(t){return u.fail(v.from(t,"authorization_request_failed"))}}async exchangeCallback(e){try{const t=new URL(e.callbackUrl),{request:r}=e;if(!Number.isSafeInteger(r.createdAt)||Date.now()-r.createdAt>as)return u.fail(m.INVALID_CALLBACK,{message:"the authorization transaction expired"});if(hs(t,new URL(r.redirectTo))){if(t.searchParams.get("state")!==r.state)return u.fail(m.INVALID_CALLBACK,{message:"the callback state does not correlate"})}else return u.fail(m.INVALID_CALLBACK,{message:"the callback does not match redirectTo"});const n=t.searchParams.get("error");if(n)return u.fail(n.slice(0,256),{message:t.searchParams.get("error_description")?.slice(0,2048)??n});if(!t.searchParams.has("code"))return u.fail(m.INVALID_CALLBACK,{message:"the callback carries no authorization code"});const i=await Ur(this.#s(),t,{pkceCodeVerifier:r.codeVerifier,expectedState:r.state});return await this.#u(i)}catch(t){return u.fail(v.from(t,"authorization_exchange_failed"))}}async resolveAuthorizationUrl(e,t){try{return u.ok(await this.#d(e,t))}catch(r){return u.fail(v.from(r,"authorization_request_failed"))}}async refresh(e){try{const t=await Lr(this.#s(),e);return await this.#u(t)}catch(t){return u.fail(v.from(t,"refresh_failed"))}}async userInfo(e){try{const t=xr(e),r=await Dr(this.#s(),e,t?t.sub:Wi);return u.ok({id:String(r.sub),name:r.name,email:r.email,avatarUrl:r.picture})}catch(t){return u.fail(v.from(t,"userinfo_failed"))}}async createDeviceAuthorizationRequest(e={}){try{const t=await ts(this.#s(),{scope:this.#o(e).join(" ")});return u.ok({deviceCode:t.device_code,userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete??t.verification_uri,expiresIn:t.expires_in,interval:t.interval??5,raw:t})}catch(t){return u.fail(v.from(t,"device_authorization_failed"))}}async awaitDeviceAuthorization(e,t={}){try{const r=await es(this.#s(),e.raw,void 0,{signal:t.signal});return await this.#u(r)}catch(r){return u.fail(v.from(r,"device_exchange_failed"))}}configuration(){return this.#s()}#s(){return this.#i??=this.#a(),this.#i}#a(){const e=this.#e,t=e.endpoints.auth,r=`${t.origin}${t.pathname.replace(/\/+$/,"")}`,n=this.#r,i=new Be(os(r),e.clientId,n??void 0,n?Vi(n):Or());return i[vt]=((s,o)=>this.#t(s,o)),rs(i),i}#l(e){const t=e??this.#e.redirectTo;if(!t)throw new v(m.INVALID_CONFIGURATION,{message:"redirectTo is required, on the instance or on the request"});return new URL(t).href}#o(e){const t=(e.authorizations??[]).flatMap(n=>[...n.scopes]),r=e.scopes??this.#e.initialScopes;return[...new Set([...r,...t])]}#f(e,t,r,n){const i=new URLSearchParams({client_id:this.#e.clientId,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"}),s=this.#o(e);s.length&&i.set("scope",s.join(" "));const o=new Set;for(const l of ds(e.resource))o.add(l);for(const l of e.authorizations??[])o.add(l.resource);for(const l of o)i.append("resource",l);const a=[...e.authorizationDetails??[],...(e.authorizations??[]).flatMap(l=>[...l.authorizationDetails??[]])];a.length&&i.set("authorization_details",JSON.stringify(a));const c=e.orgId??(e.authorizations??[]).find(l=>l.orgId)?.orgId;return c&&i.set("org_id",c),e.externalId&&i.set("external_id",e.externalId),i}async#d(e,t){const r=this.#s(),n=Tt(r,e),i=us.some(o=>e.has(o)),s=t??this.#n;return(s==="auto"?i||n.href.length>cs?"par":"get":s)==="get"?n:await Cr(r,e)}async#u(e){if(e.token_type&&e.token_type.toLowerCase()!=="bearer")return u.fail(m.INVALID_RESPONSE,{message:"unsupported token type"});const t=e.claims?.()?.sub??xr(e.access_token)?.sub;if(!t)return u.fail(m.INVALID_RESPONSE,{message:"the response carries no subject"});const r={accessToken:e.access_token,refreshToken:e.refresh_token??null,tokenType:e.token_type??"bearer",expiresAt:Math.floor(Date.now()/1e3)+(e.expires_in??0),scopes:(e.scope??"").split(/\s+/).filter(Boolean),user:{id:t,name:null,email:null,avatarUrl:null}},n=await this.userInfo(r.accessToken);return u.ok(n.data?{...r,user:n.data}:r)}};function ds(e){return e===void 0?[]:typeof e=="string"?[e]:e}function hs(e,t){return e.origin!==t.origin||e.pathname!==t.pathname?!1:[...t.searchParams].every(([r,n])=>e.searchParams.getAll(r).includes(n))}function xr(e){const t=e.split(".");if(t.length<2||!t[1])return null;try{const r=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")),n=>n.charCodeAt(0))));return r&&typeof r=="object"&&typeof r.sub=="string"?{sub:r.sub}:null}catch{return null}}var fs=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE","request"]);function ps(e,t){return new Proxy(e,{get(r,n,i){const s=Reflect.get(r,n,i);if(typeof n!="string"||!fs.has(n)||typeof s!="function")return s;const o=s;return(...a)=>ms(o.apply(r,a),t)}})}function ms(e,t){const r=e.then(n=>n.error===void 0?{data:n.data,response:n.response}:{error:t(n.error,n.response),response:n.response},n=>{const i=Response.error();return{error:t(n,i),response:i}});return Object.assign(r,{throwOnError:()=>r.then(n=>{if(n.error!==void 0)throw n.error;return n})})}var zr=class{#e;#t;#r;#n;http;raw;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#r=e.credentials,this.#n=e.resource??e.config.endpoints.api.origin,this.raw=Bn({endpoint:this.#e.endpoints.api,apiVersion:this.#e.apiVersion,accessToken:()=>this.#r.accessTokenFor(this.#n),fetch:this.#t}),this.http=ps(this.raw,En.fromOpenAPIFetch)}},ys=class{#e=new Map;getItem(e){return this.#e.get(e)??null}setItem(e,t){this.#e.set(e,t)}removeItem(e){this.#e.delete(e)}},_s=class{storage;constructor(e){this.storage=e}getItem(e){return this.storage.getItem(e)}setItem(e,t){this.storage.setItem(e,t)}removeItem(e){this.storage.removeItem(e)}},gs=class{#e=new Map;async acquire(e,t){const r=(this.#e.get(e)??Promise.resolve()).then(t,t),n=r.then(()=>{},()=>{});this.#e.set(e,n);try{return await r}finally{this.#e.get(e)===n&&this.#e.delete(e)}}},Mr=class{#e;#t;#r;#n=new Set;#i;#s;#a;#l;constructor(e){this.#e=e,this.#t=e.storage??new ys,this.#r=e.lock??new gs,this.#i=`andco.session.${e.config.clientId}`,this.#s=e.initialSession,this.#a=e.initialSession}getSnapshot(){return this.#a}getServerSnapshot(){return this.#s}subscribe(e){return this.#n.add(e),this.#o(),()=>{this.#n.delete(e)}}get ready(){return this.#o()}async accessTokenFor(e){await this.#o();const t=this.#a;if(!t)return null;if(!Ft(t))return et(t,e);const r=await this.#r.acquire(`${this.#i}:${e}`,async()=>{const n=this.#a;if(!n)return null;if(!Ft(n))return n;if(!n.refreshToken)return null;const i=await this.#e.oauth.refresh(n.refreshToken);return i.error?null:(await this.#d(i.data),i.data)});return r?et(r,e):null}async set(e){this.#l??=Promise.resolve(u.ok(void 0));try{return await this.#d(e),u.ok(void 0)}catch(t){return u.fail(v.from(t,m.STORAGE_FAILED))}}#o(){return this.#l??=this.#f(),this.#l}async#f(){try{const e=this.#e.source?await this.#e.source():null;if(e?.error)return this.#u(this.#a??null),u.fail(e.error);if(e?.data)return await this.#d(e.data),u.ok(void 0);if(this.#s!==void 0)return this.#u(this.#s),u.ok(void 0);const t=await this.#t.getItem(this.#i);return this.#u(t?ws(t):null),u.ok(void 0)}catch(e){return this.#u(this.#a??null),u.fail(v.from(e,m.STORAGE_FAILED))}}async#d(e){this.#e.persist!==!1&&(e?await this.#t.setItem(this.#i,JSON.stringify(e)):await this.#t.removeItem(this.#i)),this.#u(e)}#u(e){this.#a=e;for(const t of[...this.#n])t()}};function ws(e){try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;const r=t;return typeof r.accessToken!="string"||typeof r.expiresAt!="number"||!r.user||typeof r.user.id!="string"?null:r}catch{return null}}function vs(){return new v(m.BROWSER_REQUIRED)}var bs=class qr{config;clientSecret;globals;oauth;rest;intents;auth;session;isAuthed=!1;constructor(t){this.config=On.from(t),this.clientSecret=t.clientSecret??null,this.globals={fetch:t.globals?.fetch??globalThis.fetch.bind(globalThis),crypto:t.globals?.crypto??globalThis.crypto},this.oauth=new ls({config:this.config,fetch:this.globals.fetch,clientSecret:this.clientSecret,transport:t.transport}),this.session=new Mr({config:this.config,oauth:this.oauth,storage:t.storage,initialSession:t.initialSession,lock:t.lock,source:t.source,persist:t.persist});const r=t.presenter??jr();this.auth=new Wt({config:this.config,oauth:this.oauth,store:this.session,presenter:r,persistTransaction:t.persistTransaction,crypto:this.globals.crypto}),this.rest=new zr({config:this.config,fetch:this.globals.fetch,credentials:this.session}),this.intents=new Qt({rest:this.rest,config:this.config,presenter:r,crypto:this.globals.crypto})}with(t){return new As(this,qr.resolveCredentials(t))}authorized(){return new Ts(this)}static resolveCredentials(t){return typeof t=="string"?{accessTokenFor:async()=>t}:kn(t)?t:Nn(t)}};function jr(){return{async present(){return u.fail(vs())}}}var As=class{credentials;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e,t){this.credentials=t,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=new zr({config:e.config,fetch:e.globals.fetch,credentials:t}),this.intents=new Qt({rest:this.rest,config:e.config,crypto:e.globals.crypto}),this.session=new Mr({config:e.config,oauth:e.oauth,persist:!1}),this.auth=new Wt({config:e.config,oauth:e.oauth,store:this.session,presenter:jr(),crypto:e.globals.crypto})}accessTokenFor(e){return this.credentials.accessTokenFor(e)}},Ts=class{owner;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e){this.owner=e,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=e.rest,this.intents=e.intents,this.auth=e.auth,this.session=e.session}accessTokenFor(e){return this.owner.session.accessTokenFor(e)}};function Hr(e){return e instanceof URL?Promise.resolve(u.ok(e)):e()}var Is=/^[A-Za-z0-9_-]{8,128}$/,Es=6e5,Ps=400;function Ss(){return typeof window<"u"&&window.__ANDCO_NATIVE_HOST__===!0&&typeof window.ReactNativeWebView?.postMessage=="function"}function $r(){if(typeof window>"u"||!window.opener||window.opener===window||!window.name.startsWith("andco-popup-"))return null;const e=window.name.slice(Vt.length);return Is.test(e)?e:null}function Rs(e,t={}){if(typeof window>"u")return{status:"not_callback"};const r=t.callbackUrl?new URL(t.callbackUrl,window.location.href):new URL(window.location.href);if(!(t.callbackUrl||r.searchParams.has("code")||r.searchParams.has("error")||r.searchParams.has("andco_intent_result")))return{status:"not_callback"};const n=$r();if(!n)return{status:"not_popup"};const i=r.searchParams.get("state"),s=(i?Bt(i)?.openerOrigin:null)??window.location.origin;if(s!==window.location.origin&&!e.has(s))return{status:"rejected",error:new v(m.UNTRUSTED_ORIGIN)};const o=s===window.location.origin?Os(n,r):Ns(n,r);for(const a of["code","state","error","error_description","andco_intent_result","intent_id"])r.searchParams.delete(a);return window.history.replaceState(window.history.state,"",r),window.name="",window.opener?.postMessage(o,s),window.close(),{status:"relayed",presentationId:n}}function Os(e,t){return{protocol:"andco",version:1,presentationId:e,callbackUrl:t.href}}function Ns(e,t){const r={protocol:pe,version:2,presentationId:e},n=t.searchParams.get("andco_intent_result");if(n==="complete")return{...r,type:"intent.complete"};if(n)return{...r,type:"intent.dismiss"};const i=t.searchParams.get("code");if(i)return{...r,type:"oauth.authorization_code",authorizationCode:i};const s=t.searchParams.get("error")??"invalid_request";if(s==="access_denied")return{...r,type:"oauth.dismiss"};const o=t.searchParams.get("error_description");return{...r,type:"oauth.error",error:{code:s.slice(0,256),description:o?o.slice(0,2048):void 0}}}function ks(e){const t=window.open(e.url?.href??"about:blank",`${Vt}${e.presentationId}`,Us({width:620,height:720}));return t?{blocked:!1,navigate:r=>t.location.assign(r.href),result:new Promise(r=>{let n=!1;const i=c=>{n||(n=!0,window.removeEventListener("message",s),window.clearInterval(o),window.clearTimeout(a),r(c))},s=c=>{if(c.origin!==e.expectedOrigin||c.source!==t)return;const l=c.data;if(!(!l||l.protocol!=="andco"||l.presentationId!==e.presentationId)&&typeof l.callbackUrl=="string"){t.close();try{i(u.ok(new URL(l.callbackUrl)))}catch{i(u.fail(m.INVALID_CALLBACK))}}};window.addEventListener("message",s);const o=window.setInterval(()=>{t.closed&&i(u.ok(null))},Ps),a=window.setTimeout(()=>{t.close(),i(u.fail(m.POPUP_TIMEOUT))},Es);e.signal?.addEventListener("abort",()=>{t.close(),i(u.ok(null))})}),close:()=>t.close()}:{blocked:!0,navigate:()=>{},result:Promise.resolve(u.fail(m.POPUP_BLOCKED)),close:()=>{}}}function Us(e){const t=Math.max(0,Math.round((window.screen.width-e.width)/2)),r=Math.max(0,Math.round((window.screen.height-e.height)/2));return`popup=1,width=${e.width},height=${e.height},left=${t},top=${r}`}var Ls=class{iframe;options;url;settled=!1;transport="pending";port;handshakeTimer;handshakeTimeout;handshakeAttempts=0;handshakeStartedAt=0;destroyed=!1;constructor(e,t){if(this.iframe=e,this.options=t,typeof window>"u"||typeof document>"u")throw new v(m.BROWSER_UNAVAILABLE);if(!(e instanceof HTMLIFrameElement))throw new v(m.INVALID_IFRAME,{details:{iframe:e}});if(this.url=new URL(t.endpointButton),this.url.origin===window.location.origin)throw new v(m.SAME_ORIGIN_ENDPOINT,{details:{endpointButton:this.url.href}});console.debug("[AndcoButtonBridge] created: %o",{endpointButton:this.url.href}),e.addEventListener("load",this.startHandshake),this.startHandshake()}stopHandshake(){this.handshakeTimer!==void 0&&window.clearInterval(this.handshakeTimer),this.handshakeTimeout!==void 0&&window.clearTimeout(this.handshakeTimeout),this.handshakeTimer=void 0,this.handshakeTimeout=void 0}closePort(){this.port?.close(),this.port=void 0}receive(e){if(In(e))switch(e.type){case"ready":if(this.settled)return;this.settled=!0,this.stopHandshake(),console.debug("[AndcoButtonBridge] handshake settled: %o",{attempts:this.handshakeAttempts,transport:this.transport,elapsedMs:Date.now()-this.handshakeStartedAt}),this.options.onReady?.(e);return;case"error":this.settled||(this.settled=!0,this.stopHandshake()),console.warn("[AndcoButtonBridge] hosted surface reported an error: %o",e.error),this.options.onError?.(e);return;case"oauth.authorization_code":case"oauth.complete":case"intent.complete":if(!this.settled)return;this.options.onComplete?.(e);return;case"oauth.dismiss":case"intent.dismiss":this.settled&&this.options.onDismiss?.(e);return;case"oauth.error":this.settled&&this.options.onAuthorizationError?.(e);return;case"click":this.settled&&this.options.onActivate?.(e);return}}receiveWindow=e=>{this.transport==="port"||e.origin!==this.url.origin||e.source!==this.iframe.contentWindow||(this.transport="window",this.receive(e.data))};initialize=()=>{const e=this.iframe.contentWindow;if(!e)return;this.handshakeAttempts+=1,this.closePort();const t=new MessageChannel;this.port=t.port1,this.port.onmessage=n=>{this.transport!=="window"&&(this.transport="port",window.removeEventListener("message",this.receiveWindow),this.receive(n.data))};const r={protocol:pe,version:2,type:"init"};try{e.postMessage(r,this.url.origin,[t.port2])}catch(n){console.debug("[AndcoButtonBridge] init attempt %d could not post yet, retrying: %o",this.handshakeAttempts,{cause:n})}};startHandshake=()=>{this.stopHandshake(),this.settled=!1,this.transport="pending",this.handshakeAttempts=0,this.handshakeStartedAt=Date.now(),window.addEventListener("message",this.receiveWindow),this.initialize(),this.handshakeTimer=window.setInterval(this.initialize,250),this.handshakeTimeout=window.setTimeout(()=>{this.settled=!0,this.stopHandshake(),this.closePort(),console.error("[AndcoButtonBridge] handshake timed out: %o",{attempts:this.handshakeAttempts,endpointButton:this.url.href});const e={protocol:pe,version:2,type:"error",error:{code:re.HANDSHAKE_TIMEOUT}};this.options.onError?.(e)},1e4)};post(e){if(!(this.destroyed||!this.settled)){if(this.transport==="port"&&this.port){this.port.postMessage(e);return}this.iframe.contentWindow?.postMessage(e,this.url.origin)}}resolvePresentation(e,t){const r={protocol:pe,version:2,type:"presentation-response",presentationId:e,url:t?.toString()};this.post(r)}forwardAuthorizationResult(e){this.post(e)}setPreferences(e){const t={protocol:pe,version:2,type:"set-preferences",...e};this.post(t)}destroy(){this.destroyed||(console.debug("[AndcoButtonBridge] destroyed: %o",{settled:this.settled,attempts:this.handshakeAttempts}),this.destroyed=!0,window.removeEventListener("message",this.receiveWindow),this.iframe.removeEventListener("load",this.startHandshake),this.stopHandshake(),this.closePort())}},Cs=class{#e;#t=new Set;#r;#n;#i;#s;#a;#l;#o=0;#f=!1;constructor(e){this.#e=e,this.#i={status:"idle",iframeURL:this.#p(),ready:!1,error:null}}get snapshot(){return this.#i}subscribe(e){return this.#t.add(e),e(this.#i),()=>{this.#t.delete(e)}}connect(e){this.disconnect(),this.#n=e,console.debug("[AndcoButtonController] connecting: %o",{iframeURL:this.#i.iframeURL}),this.#h({status:"connecting",ready:!1,error:null});try{this.#r=new Ls(e,{endpointButton:this.#p(),onReady:t=>{this.#h({status:"ready",ready:!0}),this.#e.onReady?.(t)},onActivate:t=>{this.#a=t.presentationId,this.#e.onActivate?.(t),this.#d()},onComplete:t=>{this.#m(t)},onDismiss:()=>{this.#h({status:"dismissed"}),this.#e.onDismiss?.()},onAuthorizationError:t=>this.#c(new v(t.error.code,{message:t.error.description})),onError:t=>{if(t.error.code===re.HANDSHAKE_TIMEOUT&&!this.#f&&this.#n){this.#f=!0,console.debug("[AndcoButtonController] handshake timed out",{action:"reconnect",retry:1}),this.connect(this.#n);return}this.#c(new v(t.error.code),t)}})}catch(t){this.#c(v.from(t,m.INVALID_IFRAME))}return()=>this.disconnect()}disconnect(){this.#r?.destroy(),this.#r=void 0}restart(){if(this.#o+=1,this.#s=void 0,this.#l=void 0,this.#i.status==="error"&&this.#n){this.#f=!1,console.debug("[AndcoButtonController] restarting after an error, reconnecting: %o",{code:this.#i.error?.code}),this.connect(this.#n);return}this.#h({status:this.#r?"ready":"idle",error:null})}destroy(){this.disconnect(),this.#n=void 0,this.#t.clear()}async#d(){const e=++this.#o;this.#h({status:"authorizing",error:null});const t=this.#a,r=$t(this.#e.client.config.endpoints.widget.origin,t);if(this.#e.flow==="intent")return this.#u(e,t,r);const n=await this.#e.client.oauth.createAuthorizationRequest({...this.#e.authorization??{},state:r});if(e===this.#o){if(n.error)return this.#c(n.error);this.#s=n.data,this.#r?.resolvePresentation(t,n.data.authorizationUrl.href)}}async#u(e,t,r){const n=this.#e.client,i=this.#e.intentId;if(!i)return this.#c(new v(m.INVALID_CONFIGURATION,{message:'a control with flow="intent" requires an intentId'}));if(this.#e.presentation==="redirect")return this.#c(new v(m.PRESENTATION_UNSUPPORTED,{message:'an Intent cannot be presented with presentation="redirect" yet'}));const s=n.config.redirectTo;if(!s)return this.#c(new v(m.INVALID_CONFIGURATION,{message:"an Intent Presentation needs the instance's redirectTo"}));let o;try{o=typeof i=="string"?i:await i()}catch(c){return this.#c(v.from(c,m.INVALID_CONFIGURATION))}if(e!==this.#o)return;const a=await n.intents.presentationURL({intentId:o,presentation:"popup",returnTo:s,errorReturnTo:s,state:r});if(e===this.#o){if(a.error)return this.#c(a.error);this.#l=o,this.#r?.resolvePresentation(t,a.data.href)}}async#m(e){const t=this.#o,r=this.#s;if(this.#s=void 0,e.type==="oauth.authorization_code"&&r){const n=new URL(r.redirectTo);n.searchParams.set("code",e.authorizationCode),n.searchParams.set("state",r.state);const i=await this.#e.client.oauth.exchangeCallback({callbackUrl:n,request:r});if(t!==this.#o)return;if(i.error)return this.#c(i.error);const s=await this.#e.client.session.set(i.data);if(s.error)return this.#c(s.error)}if(t===this.#o){if(e.type==="intent.complete"&&this.#l){const n=await this.#e.client.intents.get(this.#l);if(t!==this.#o)return;if(n.error)return this.#c(n.error);this.#h({status:"complete",error:null}),this.#e.onComplete?.({outcome:"complete",intent:n.data});return}this.#h({status:"complete",error:null}),this.#e.onComplete?.()}}#c(e,t){console.error("[AndcoButtonController] %s: %o",e.code,{message:e.message,details:e.details}),this.#h({status:"error",error:e}),this.#e.onError?.(e,t)}#p(){const e=this.#e.client.config,t=e.widgetURL(this.#e.release??1780358400);return t.searchParams.set("themeMode",this.#e.themeMode??e.themeMode),t.searchParams.set("locale",this.#e.locale??e.locale),t.searchParams.set("theme",e.theme),t.searchParams.set("flow",this.#e.flow??"authorization"),t.searchParams.set("presentation",this.#e.presentation??"popup"),t.searchParams.set("endpointAuth",e.endpoints.auth.href),t.searchParams.set("clientId",e.clientId),e.redirectTo&&t.searchParams.set("redirectTo",e.redirectTo.href),this.#e.disabled!==void 0&&t.searchParams.set("disabled",String(this.#e.disabled)),this.#e.busy!==void 0&&t.searchParams.set("busy",String(this.#e.busy)),t.href}#h(e){this.#i={...this.#i,...e,iframeURL:this.#p()};for(const t of[...this.#t])t(this.#i)}};function Ds(){return{async present(e){if(typeof window>"u")return u.fail(m.BROWSER_REQUIRED);if(e.kind==="oauth"&&e.presentation==="redirect"){const n=await Hr(e.url);return n.error?u.fail(n.error):(window.location.assign(n.data.href),u.ok(null))}if(Ss()&&window.__ANDCO_NATIVE_POPUP_HANDLER__!==!0)return u.fail(m.PRESENTATION_UNSUPPORTED,{message:"the native Host cannot present a popup without navigating the Miniapp"});const t=ks({presentationId:e.presentationId,expectedOrigin:e.returnTo.origin,signal:e.signal});if(t.blocked)return u.fail(m.POPUP_BLOCKED);const r=await Hr(e.url);return r.error?(t.close(),u.fail(r.error)):(t.navigate(r.data),t.result)}}}var It="andco.transaction";function xs(e){const t=e.presenter??Ds(),r=e.storage??(typeof window>"u"?void 0:new _s(window.sessionStorage)),n=new bs({...e,presenter:t,storage:r,source:()=>zs(n.config,n.oauth,e),persistTransaction:i=>Ms(n.config.clientId,i,e.transactionStorage)});return e.relayPopupCallback!==!1&&typeof window<"u"&&Rs(n.config.allowedPopupOrigins),n}async function zs(e,t,r){if(r.detectSessionInUrl===!1||typeof window>"u"||$r())return u.ok(null);const n=new URL(window.location.href);if(!n.searchParams.has("code")&&!n.searchParams.has("error"))return u.ok(null);const i=r.transactionStorage??window.sessionStorage,s=i.getItem(`${It}.${e.clientId}`);if(!s)return u.ok(null);i.removeItem(`${It}.${e.clientId}`);let o;try{const c=JSON.parse(s);o={...c,authorizationUrl:new URL(c.authorizationUrl)}}catch{return u.fail(m.INVALID_CALLBACK)}const a=await t.exchangeCallback({callbackUrl:n,request:o});for(const c of["code","state","error","error_description"])n.searchParams.delete(c);return(r.replaceUrl??(c=>window.history.replaceState(window.history.state,"",c)))(n),a.error?u.fail(a.error):u.ok(a.data)}function Ms(e,t,r){(r??window.sessionStorage).setItem(`${It}.${e}`,JSON.stringify({...t,authorizationUrl:t.authorizationUrl.href}))}var Et=new Map;function Br(e){const t=JSON.stringify(e,Object.keys(e).sort()),r=Et.get(t);if(r)return r;const n=xs(e);return Et.set(t,n),n}function js(){const e="andco-button-default-style";if(typeof document>"u"||document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="@layer andco { andco-button { display: block; height: 3rem; width: 18rem } }",document.head.append(t)}var Hs=["client-id","endpoint-auth","endpoint-api","endpoint-widget","redirect-to","locale","theme-mode","scopes","flow","disabled","busy"],Vr=class extends HTMLElement{static observedAttributes=Hs;#e;#t;#r;#n;authorizations;intentId;connectedCallback(){js(),this.#s()}disconnectedCallback(){this.#i()}attributeChangedCallback(){this.isConnected&&this.#s()}#i(){this.#t?.(),this.#r?.(),this.#e?.destroy(),this.#t=void 0,this.#r=void 0,this.#e=void 0}#s(){this.#i();const e=this.getAttribute("client-id");if(!e)return;const t=Br({clientId:e,...ue("endpointAuth",this.getAttribute("endpoint-auth")),...ue("endpointApi",this.getAttribute("endpoint-api")),...ue("endpointWidget",this.getAttribute("endpoint-widget")),...ue("redirectTo",this.getAttribute("redirect-to")),...ue("locale",this.getAttribute("locale")),initialScopes:this.getAttribute("scopes")?.split(/\s+/).filter(Boolean)}),r=this.getAttribute("scopes")?.split(/\s+/).filter(Boolean);this.#e=new Cs({client:t,flow:this.getAttribute("flow")??void 0,intentId:this.intentId,...ue("themeMode",this.getAttribute("theme-mode")),...ue("locale",this.getAttribute("locale")),disabled:this.hasAttribute("disabled"),busy:this.hasAttribute("busy"),authorization:{...r?.length?{scopes:r}:{},authorizations:this.authorizations},onReady:()=>this.dispatchEvent(new CustomEvent("andco-ready")),onActivate:()=>this.dispatchEvent(new CustomEvent("andco-activate")),onComplete:i=>this.dispatchEvent(new CustomEvent("andco-complete",{detail:i})),onDismiss:()=>this.dispatchEvent(new CustomEvent("andco-dismiss")),onError:i=>this.dispatchEvent(new CustomEvent("andco-error",{detail:i}))});const n=this.#n??document.createElement("iframe");this.#n=n,n.referrerPolicy="no-referrer",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"),n.title=this.getAttribute("title")??"Andco",n.style.cssText="border:0;display:block;height:100%;width:100%",n.isConnected||this.append(n),this.#r=this.#e.subscribe(i=>{n.src!==i.iframeURL&&(n.src=i.iframeURL),n.hidden=!i.ready}),this.#t=this.#e.connect(n)}};function $s(e){const t=e.getAttribute("client-id");for(const[r,n]of Et)if(t&&r.includes(`"${t}"`))return n.session.getSnapshot()}function Bs(e){return Br(e)}function ue(e,t){return t?{[e]:t}:{}}return typeof customElements<"u"&&!customElements.get("andco-button")&&customElements.define("andco-button",Vr),_e.AndcoButtonElement=Vr,_e.andcoInstance=Bs,_e.andcoSessionFor=$s,_e})({});
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=andco.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AndcoClient, AndcoSession } from "@andco/sdk";
|
|
1
|
+
import type { AndcoClient, AndcoIntentId, AndcoSession } from "@andco/sdk";
|
|
2
2
|
/**
|
|
3
3
|
* The hosted Andco control as a custom element.
|
|
4
4
|
*
|
|
@@ -16,6 +16,13 @@ export declare class AndcoButtonElement extends HTMLElement {
|
|
|
16
16
|
static readonly observedAttributes: readonly ["client-id", "endpoint-auth", "endpoint-api", "endpoint-widget", "redirect-to", "locale", "theme-mode", "scopes", "flow", "disabled", "busy"];
|
|
17
17
|
/** Resource Server contributions. An object, so it arrives as a property rather than an attribute. */
|
|
18
18
|
authorizations: unknown[] | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* The Intent this control presents, required when `flow="intent"`.
|
|
21
|
+
*
|
|
22
|
+
* A property rather than an attribute because the useful form is a function: it runs after the
|
|
23
|
+
* user activates, so the window is already open when the Intent is created.
|
|
24
|
+
*/
|
|
25
|
+
intentId: AndcoIntentId | undefined;
|
|
19
26
|
connectedCallback(): void;
|
|
20
27
|
disconnectedCallback(): void;
|
|
21
28
|
attributeChangedCallback(): void;
|
package/dist/index.js
CHANGED
|
@@ -65,6 +65,13 @@ export class AndcoButtonElement extends HTMLElement {
|
|
|
65
65
|
#iframe;
|
|
66
66
|
/** Resource Server contributions. An object, so it arrives as a property rather than an attribute. */
|
|
67
67
|
authorizations;
|
|
68
|
+
/**
|
|
69
|
+
* The Intent this control presents, required when `flow="intent"`.
|
|
70
|
+
*
|
|
71
|
+
* A property rather than an attribute because the useful form is a function: it runs after the
|
|
72
|
+
* user activates, so the window is already open when the Intent is created.
|
|
73
|
+
*/
|
|
74
|
+
intentId;
|
|
68
75
|
connectedCallback() {
|
|
69
76
|
installDefaultStyle();
|
|
70
77
|
this.#build();
|
|
@@ -102,6 +109,7 @@ export class AndcoButtonElement extends HTMLElement {
|
|
|
102
109
|
this.#controller = new AndcoButtonController({
|
|
103
110
|
client,
|
|
104
111
|
flow: this.getAttribute("flow") ?? undefined,
|
|
112
|
+
intentId: this.intentId,
|
|
105
113
|
...optional("themeMode", this.getAttribute("theme-mode")),
|
|
106
114
|
...optional("locale", this.getAttribute("locale")),
|
|
107
115
|
disabled: this.hasAttribute("disabled"),
|
|
@@ -114,7 +122,7 @@ export class AndcoButtonElement extends HTMLElement {
|
|
|
114
122
|
// ErrorEvent, and a listener cannot tell the two apart.
|
|
115
123
|
onReady: () => this.dispatchEvent(new CustomEvent("andco-ready")),
|
|
116
124
|
onActivate: () => this.dispatchEvent(new CustomEvent("andco-activate")),
|
|
117
|
-
onComplete: () => this.dispatchEvent(new CustomEvent("andco-complete")),
|
|
125
|
+
onComplete: (outcome) => this.dispatchEvent(new CustomEvent("andco-complete", { detail: outcome })),
|
|
118
126
|
onDismiss: () => this.dispatchEvent(new CustomEvent("andco-dismiss")),
|
|
119
127
|
onError: (error) => this.dispatchEvent(new CustomEvent("andco-error", { detail: error })),
|
|
120
128
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@andco/sdk-script",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"!dist/*.map"
|
|
23
23
|
],
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@andco/sdk": "0.0.
|
|
25
|
+
"@andco/sdk": "0.0.3"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"typescript": "^6.0.3",
|