@andco/sdk-script 0.0.3 → 0.0.4

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/LICENSE CHANGED
@@ -187,7 +187,7 @@
187
187
  same "printed page" as the copyright notice for easier
188
188
  identification within third-party archives.
189
189
 
190
- Copyright 2026 Andco
190
+ Copyright 2026 Haulmer
191
191
 
192
192
  Licensed under the Apache License, Version 2.0 (the "License");
193
193
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # `@andco/sdk-script`
2
2
 
3
+ > [!WARNING]
4
+ > **Pre-1.0 software.** Until version 1.0.0 is released, any new version may include breaking
5
+ > changes, including minor and patch releases. Expect any API incompatibility and data resets
6
+ > in the Andco environments without prior notice. Pin an exact version and review the release
7
+ > notes before upgrading.
8
+
3
9
  Classic-script and ESM distribution of `@andco/sdk`, built around one custom
4
10
  element: `<andco-button>`.
5
11
 
@@ -100,14 +106,19 @@ contribution — it is not serializable as an attribute, so it does not have an
100
106
  attribute counterpart:
101
107
 
102
108
  ```ts
109
+ import { Bank } from "@andco/bank-sdk";
110
+ import type { AndcoButtonElement } from "@andco/sdk-script";
111
+
112
+ const bank = new Bank();
103
113
  const button = document.querySelector<AndcoButtonElement>("andco-button")!;
104
- button.authorizations = [
105
- bank.authorization({ scopes: ["bank_accounts:read"] }),
106
- ];
114
+ button.authorizations = [bank.accounts.authorization({ actions: ["read"], subject: { type: "profile" } })];
107
115
  ```
108
116
 
109
- (`bank` above is a `Bank` Resource Server Definition from `@andco/bank-sdk`;
110
- `.authorization(...)` is how it produces that contribution.)
117
+ (`bank` above is a `Bank` Resource Server Definition from `@andco/bank-sdk`; each domain's
118
+ `.authorization(...)` produces that RAR contribution. Scopes stay OpenID Connect only.)
119
+
120
+ With `flow="intent"`, set the `intentId` property to an id or to a function that resolves it after
121
+ the person activates the control. The `andco-complete` event's `detail` is `{ outcome, intent }`.
111
122
 
112
123
  ## Events
113
124
 
@@ -131,5 +142,5 @@ not use a shadow root. That iframe is Andco-deployed and cross-origin: it is
131
142
  the trusted authorization and financial confirmation surface, and its code
132
143
  and DOM are not the Project's.
133
144
 
134
- See [`apps/example-js`](../../apps/example-js/README.md) for the complete session
145
+ See [`apps/example-js`](https://github.com/haulmer/andco-sdk-js/tree/main/apps/example-js) for the complete session
135
146
  → Grant → resource flow.
package/dist/andco.js CHANGED
@@ -1,3 +1,3 @@
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})({});
1
+ var Andco=(function(Pe){Object.defineProperty(Pe,Symbol.toStringTag,{value:"Module"});var Ke,as={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Er(e){return!e&&!Ke?as:{lang:e?.lang??Ke?.lang,message:e?.message,abortEarly:e?.abortEarly??Ke?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ke?.abortPipeEarly}}var cs;function us(e){return cs?.get(e)}var ls;function ds(e){return ls?.get(e)}var hs;function fs(e,t){return hs?.get(e)?.get(t)}function ke(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 L(e,t,r,n,s){const i=s&&"input"in s?s.input:r.value,o=s?.expected??e.expects??null,a=s?.received??ke(i),c={kind:e.kind,type:e.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:s?.path,issues:s?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=e.kind==="schema",d=s?.message??e.message??fs(e.reference,c.lang)??(u?ds(c.lang):null)??n.message??us(c.lang);d!==void 0&&(c.message=typeof d=="function"?d(c):d),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function ps(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function ys(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Ir(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function M(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Er())},e}var ms=/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iu;function V(e,t){return{kind:"validation",type:"check",reference:V,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&L(this,"input",r,n),r}}}function K(e){return{kind:"validation",type:"integer",reference:K,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&L(this,"integer",t,r),t}}}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&&L(this,"length",r,n,{received:`${r.value.length}`}),r}}}function te(e,t){return{kind:"validation",type:"min_length",reference:te,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&L(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Tr(e,t){return{kind:"validation",type:"min_value",reference:Tr,async:!1,expects:`>=${e instanceof Date?e.toJSON():ke(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value>=this.requirement)&&L(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():ke(r.value)}),r}}}function $(e,t){return{kind:"validation",type:"regex",reference:$,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&L(this,"format",r,n),r}}}function Ce(){return{kind:"transformation",type:"trim",reference:Ce,async:!1,"~run"(e){return e.value=e.value.trim(),e}}}function Sr(e){return{kind:"validation",type:"uuid",reference:Sr,async:!1,expects:null,requirement:ms,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&L(this,"UUID",t,r),t}}}var _s={abortEarly:!0};function Rr(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function De(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function ue(e){return M({kind:"schema",type:"boolean",reference:ue,expects:"boolean",async:!1,message:e,"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:L(this,"type",t,r),t}})}function m(e,t){return M({kind:"schema",type:"literal",reference:m,expects:ke(e),async:!1,literal:e,message:t,"~run"(r,n){return ps(r.value,this.literal)?r.typed=!0:L(this,"type",r,n),r}})}function Et(e,t){return M({kind:"schema",type:"nullable",reference:Et,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=De(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function B(e,t){return M({kind:"schema",type:"nullish",reference:B,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=De(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function Y(e){return M({kind:"schema",type:"number",reference:Y,expects:"number",async:!1,message:e,"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:L(this,"type",t,r),t}})}function Ze(e,t){return M({kind:"schema",type:"object",reference:Ze,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const i in this.entries){const o=this.entries[i];if(i in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=i in s?s[i]:De(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:s,key:i,value:a};for(const d of c.issues)d.path?d.path.unshift(u):d.path=[u],r.issues?.push(d);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[i]=c.value}else if(o.fallback!==void 0)r.value[i]=Rr(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(L(this,"key",r,n,{input:void 0,expected:`"${i}"`,path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]}),n.abortEarly))break}}else L(this,"type",r,n);return r}})}function w(e,t){return M({kind:"schema",type:"optional",reference:w,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=De(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function Le(e,t){return M({kind:"schema",type:"picklist",reference:Le,expects:Ir(e.map(ke),"|"),async:!1,options:e,message:t,"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:L(this,"type",r,n),r}})}function Ue(e,t,r){return M({kind:"schema",type:"record",reference:Ue,expects:"Object",async:!1,key:e,value:t,message:r,"~run"(n,s){const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const o in i)if(ys(i,o)){const a=i[o],c=this.key["~run"]({value:o},s);if(c.issues){const d={type:"object",origin:"key",input:i,key:o,value:a};for(const h of c.issues)h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=c.issues),s.abortEarly){n.typed=!1;break}}const u=this.value["~run"]({value:a},s);if(u.issues){const d={type:"object",origin:"value",input:i,key:o,value:a};for(const h of u.issues)h.path?h.path.unshift(d):h.path=[d],n.issues?.push(h);if(n.issues||(n.issues=u.issues),s.abortEarly){n.typed=!1;break}}(!c.typed||!u.typed)&&(n.typed=!1),c.typed&&(n.value[c.value]=u.value)}}else L(this,"type",n,s);return n}})}function _(e,t){return M({kind:"schema",type:"strict_object",reference:_,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const s=r.value;if(s&&typeof s=="object"){r.typed=!0,r.value={};for(const i in this.entries){const o=this.entries[i];if(i in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=i in s?s[i]:De(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:s,key:i,value:a};for(const d of c.issues)d.path?d.path.unshift(u):d.path=[u],r.issues?.push(d);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[i]=c.value}else if(o.fallback!==void 0)r.value[i]=Rr(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(L(this,"key",r,n,{input:void 0,expected:`"${i}"`,path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly){for(const i in s)if(!Object.prototype.hasOwnProperty.call(this.entries,i)){L(this,"key",r,n,{input:i,expected:"never",path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]});break}}}else L(this,"type",r,n);return r}})}function R(e){return M({kind:"schema",type:"string",reference:R,expects:"string",async:!1,message:e,"~run"(t,r){return typeof t.value=="string"?t.typed=!0:L(this,"type",t,r),t}})}function xe(){return M({kind:"schema",type:"unknown",reference:xe,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}function se(e,t,r){return M({kind:"schema",type:"variant",reference:se,expects:"Object",async:!1,key:e,options:t,message:r,"~run"(n,s){const i=n.value;if(i&&typeof i=="object"){let o,a=0,c=this.key,u=[];const d=(h,f)=>{for(const y of h.options){if(y.type==="variant")d(y,new Set(f).add(y.key));else{let A=!0,N=0;for(const S of f){const D=y.entries[S];if(S in i?D["~run"]({typed:!1,value:i[S]},_s).issues:D.type!=="exact_optional"&&D.type!=="optional"&&D.type!=="nullish"){A=!1,c!==S&&(a<N||a===N&&S in i&&!(c in i))&&(a=N,c=S,u=[]),c===S&&u.push(y.entries[S].expects);break}N++}if(A){const S=y["~run"]({value:i},s);(!o||!o.typed&&S.typed)&&(o=S)}}if(o&&!o.issues)break}};if(d(this,new Set([this.key])),o)return o;L(this,"type",n,s,{input:i[c],expected:Ir(u,"|"),path:[{type:"object",origin:"value",input:i,key:c,value:i[c]}]})}else L(this,"type",n,s);return n}})}function T(...e){return M({...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 Se(e,t,r){const n=e["~run"]({value:t},Er(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var Or="^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",Nr="^[1-9][0-9]{0,9}$",It=T(R(),$(new RegExp(Or))),Pr=T(R(),$(new RegExp(Nr)),V(e=>Number(e)<=Ts,"identifier_exceeds_organization_id")),gs=_({type:m("profile"),identifier:B(It)}),ws=_({type:m("organization"),identifier:B(Pr),editable:B(ue())}),vs=B(se("type",[gs,ws])),As=_({type:m("organization"),identifier:Pr}),Wa=se("type",[_({type:m("profile"),identifier:It}),As]),Ga=_({type:m("profile"),identifier:It}),Tt=e=>({anyOf:[{type:"null"},e]}),Ja={type:"object",additionalProperties:!1,required:["type"],properties:{type:{const:"profile"},identifier:Tt({type:"string",pattern:Or})}},Ka={type:"object",additionalProperties:!1,required:["type"],properties:{type:{const:"organization"},identifier:Tt({type:"string",pattern:Nr}),editable:Tt({type:"boolean"})}};function kr(e){const t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||t==="::1"?!0:/^127(?:\.\d{1,3}){3}$/.test(t)}var bs=["hash","host","hostname","password","pathname","port","protocol","search","username"],Es=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 kr(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 bs){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))}},F=class extends Es{constructor(e,t,r){if(super(e,t,r),!(this.protocol==="https:"||this.protocol==="http:"&&kr(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")}},Re=class extends Error{code;status;constructor(e,t=e,r,n){super(t,n),this.code=e,this.status=r}};function Is(e){try{new F(e)}catch(t){throw new Re("invalid_authorization_request",`resource must be an absolute HTTPS URL without credentials or a fragment: ${e}`,void 0,{cause:t})}}var Ts=2147483647,Za=Ze({expires_in:T(Y(),K(),Tr(1)),request_uri:T(R(),$(/^urn:ietf:params:oauth:request_uri:[A-Za-z0-9._~:+/-]{1,1900}$/))});function Ss(e=[]){let t;const r=new Set,n=new Set,s=[];for(const i of e){const o=i.resource;if(o!==void 0&&(Is(o),r.add(o)),i.scopes)for(const a of i.scopes){if(!/^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/.test(a))throw new Re("invalid_authorization_request","Invalid OAuth scope");n.add(a)}if(i.authorizationDetails)for(const a of i.authorizationDetails){if(!a||typeof a!="object"||Array.isArray(a))throw new Re("invalid_authorization_request","Invalid authorization detail");const c=a.locations;if(c!==void 0&&(!Array.isArray(c)||o!==void 0&&c.some(d=>d!==o)))throw new Re("invalid_authorization_request","Authorization detail locations must match its Resource Server");const u=Rs(a.subject);if(u!==null){if(t!==void 0&&t.key!==u)throw console.debug("[createAndCoAuthorizationPlan] refused different subjects %o and %o",t.value,a.subject),new Re("not_implemented","multiple_subjects: every authorization detail of one request must name the same subject");t={key:u,value:a.subject}}s.push({...a,locations:o===void 0?c:[o]})}}return{resources:[...r],scopes:[...n],authorizationDetails:s}}function Rs(e){if(e==null)return null;const t=Se(vs,e);if(!t.success||!t.output)throw new Re("invalid_authorization_request",'An authorization detail subject is { type: "profile" | "organization", identifier? }');return`${t.output.type}:${t.output.identifier??""}`}var Oe="andco:sdk",Ya="https://auth.andco.com",St="https://api.andco.com",Xa="https://widgets.andco.com",Os="application/json",Ns="application/jwt";function Ps(e,t="_"){return new URL(`/oauth/api/versions/${t}`,e).href}var G={protocol:m(Oe),version:m(2)},Qa=T(R(),te(1),Z(128),$(/^[A-Za-z0-9_-]+$/)),re=T(R(),te(1),Z(128),$(/^[A-Za-z0-9_-]+$/)),p={BROWSER_REQUIRED:"browser_required",BROWSER_UNAVAILABLE:"browser_unavailable",BROWSER_FORBIDDEN:"browser_forbidden",FETCH_UNAVAILABLE:"fetch_unavailable",WEB_CRYPTO_UNAVAILABLE:"web_crypto_unavailable",INVALID_CONFIGURATION:"invalid_configuration",INVALID_ENDPOINT_AUTH:"invalid_endpoint_auth",INVALID_ENDPOINT_API:"invalid_endpoint_api",INVALID_ENDPOINT_BUTTON:"invalid_endpoint_button",INVALID_CLIENT_ID:"invalid_client_id",INVALID_REDIRECT_TO:"invalid_redirect_to",INVALID_AUTH_MODE:"invalid_auth_mode",INVALID_SCOPE:"invalid_scope",INVALID_VERSION:"invalid_version",UNSUPPORTED_THEME:"unsupported_theme",UNSUPPORTED_THEME_MODE:"unsupported_theme_mode",SAME_ORIGIN_ENDPOINT:"same_origin_endpoint",POPUP_BLOCKED:"popup_blocked",POPUP_NAVIGATION_FAILED:"popup_navigation_failed",POPUP_TIMEOUT:"popup_timeout",PRESENTATION_UNSUPPORTED:"presentation_unsupported",PRESENTATION_TARGET_FAILED:"presentation_target_failed",INTENT_CALLBACK_REQUIRED:"intent_callback_required",INVALID_IFRAME:"invalid_iframe",HANDSHAKE_TIMEOUT:"handshake_timeout",UNTRUSTED_ORIGIN:"untrusted_origin",AUTHORIZATION_CANCELLED:"authorization_cancelled",AUTHORIZATION_TIMEOUT:"authorization_timeout",AUTHORIZATION_REQUEST_FAILED:"authorization_request_failed",AUTHORIZATION_EXCHANGE_FAILED:"authorization_exchange_failed",DEVICE_AUTHORIZATION_FAILED:"device_authorization_failed",DEVICE_EXCHANGE_FAILED:"device_exchange_failed",REFRESH_FAILED:"refresh_failed",USERINFO_FAILED:"userinfo_failed",INVALID_CALLBACK:"invalid_callback",INVALID_TOKEN_RESPONSE:"invalid_token_response",SESSION_MISSING:"session_missing",STORAGE_FAILED:"storage_failed",CONFIDENTIAL_CLIENT_REQUIRED:"confidential_client_required",INVALID_PAR_RESPONSE:"invalid_par_response",INVALID_INTENT_ID:"invalid_intent_id",WATCH_STOPPED:"watch_stopped",REQUEST_FAILED:"request_failed",INVALID_RESPONSE:"invalid_response",UNKNOWN_ERROR:"unknown_error"},ks=[p.INVALID_ENDPOINT_AUTH,p.INVALID_AUTH_MODE,p.INVALID_CLIENT_ID,p.INVALID_REDIRECT_TO,p.INVALID_SCOPE,p.INVALID_VERSION,p.UNSUPPORTED_THEME,p.UNSUPPORTED_THEME_MODE,p.PRESENTATION_UNSUPPORTED,p.POPUP_BLOCKED,p.POPUP_NAVIGATION_FAILED,p.POPUP_TIMEOUT,p.HANDSHAKE_TIMEOUT,p.UNTRUSTED_ORIGIN,p.UNKNOWN_ERROR],Cr=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}},Dr=class extends Cr{code;payload;constructor(e,t,r){super(e,r),this.code=e,this.payload=t}};function Cs(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 Lr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"="),n=atob(r),s=Uint8Array.from(n,i=>i.charCodeAt(0));return new TextDecoder().decode(s)}function Rt(e){const t=e.split(".")[1];if(!t)return null;try{const r=JSON.parse(Lr(t));return r&&typeof r=="object"&&!Array.isArray(r)?r:(console.debug("[decodeJwtPayload] payload is not a JSON object"),null)}catch(r){return console.debug("[decodeJwtPayload] payload is not base64url JSON %o",r),null}}function ze(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(!e||typeof e.getRandomValues!="function")throw new Dr(p.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 Ot(e,t=ze()){if(!Se(re,t).success)throw new TypeError("Invalid AndCo presentation identifier");const r=new F(e).origin;return`${Cs(r)}.${t}`}function Nt(e){const t=e.indexOf("."),r=e.slice(t+1);if(t<1||t===e.length-1||!Se(re,r).success)return null;try{const n=Lr(e.slice(0,t));return{openerOrigin:new F(n).origin,presentationId:r}}catch{return null}}var Ds="^[a-z][a-z0-9_-]{0,63}$",Pt="^(?:\\*|[a-z][a-z0-9_-]{0,63}\\*?)$",kt="^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",Ct=T(R(),$(new RegExp(Ds))),Ur=T(R(),$(new RegExp(Pt))),xr=128,zr=["bank_id","account_type","account_id","holder_id","holder_name"],jr=T(R(),$(new RegExp(kt))),ne=T(R(),te(1),Z(xr),$(/\S/)),je=B(ue()),Mr=["single","multiple"],$r=B(Le(Mr)),ec=_({type:B(m("alias")),pattern:Ur,editable:je,selection:$r}),tc=_({type:m("account"),id:jr,editable:je}),rc=_({type:m("any"),limit:m("own"),editable:je,selection:$r}),nc=_({type:m("any"),limit:m("local"),editable:je}),sc=_({type:m("any"),limit:m("all")}),ic=_({type:m("external"),bank_id:B(ne),account_type:B(ne),account_id:B(ne),holder_id:B(ne),holder_name:B(ne),editable:je}),oc=_({type:m("alias"),pattern:Ur}),ac=_({type:m("account"),id:jr}),cc=_({type:m("any"),limit:m("own")}),uc=_({type:m("any"),limit:m("local")}),lc=_({type:m("external"),bank_id:w(ne),account_type:w(ne),account_id:w(ne),holder_id:w(ne),holder_name:w(ne)}),Ye=e=>({anyOf:[{type:"null"},e]}),Me=Ye({type:"boolean"}),Fr=Ye({enum:[...Mr]}),Hr={type:"string",minLength:1,maxLength:xr,pattern:"\\S"},Vr={type:"object",additionalProperties:!1,required:["pattern"],properties:{type:Ye({const:"alias"}),pattern:{type:"string",pattern:Pt},editable:Me,selection:Fr}},Br={type:"object",additionalProperties:!1,required:["type","id"],properties:{type:{const:"account"},id:{type:"string",pattern:kt},editable:Me}},Dt=e=>({type:"object",additionalProperties:!1,required:["type","limit"],properties:e==="own"?{type:{const:"any"},limit:{const:e},editable:Me,selection:Fr}:{type:{const:"any"},limit:{const:e},editable:Me}}),qr={type:"object",additionalProperties:!1,required:["type","limit"],properties:{type:{const:"any"},limit:{const:"all"}}},Ls={type:"object",additionalProperties:!1,required:["type"],properties:{type:{const:"external"},...Object.fromEntries(zr.map(e=>[e,Ye(Hr)])),editable:Me}},Wr={type:"object",additionalProperties:!1,required:["type","pattern"],properties:{type:{const:"alias"},pattern:{type:"string",pattern:Pt}}},Gr={type:"object",additionalProperties:!1,required:["type","id"],properties:{type:{const:"account"},id:{type:"string",pattern:kt}}},Lt=e=>({type:"object",additionalProperties:!1,required:["type","limit"],properties:{type:{const:"any"},limit:{const:e}}}),Us={type:"object",additionalProperties:!1,required:["type"],properties:{type:{const:"external"},...Object.fromEntries(zr.map(e=>[e,Hr]))}},dc={anyOf:[Vr,Br,Dt("own")]},hc={anyOf:[Vr,Br,Dt("own"),Dt("local"),qr,Ls]},fc={anyOf:[Wr,Gr,Lt("own")]},pc={anyOf:[Wr,Gr,Lt("own"),Lt("local"),qr,Us]},xs="^[1-9][0-9]{0,14}$",zs="^(0|[1-9][0-9]{0,14})$",js=T(R(),$(new RegExp(xs))),yc=T(R(),$(new RegExp(zs))),Ms="^[1-9][0-9]{3,14}$",mc=T(R(),$(new RegExp(Ms),"amount_below_minimum_or_malformed")),ie=e=>T(R(),Ce(),te(1),Z(e)),Ut=T(R(),Sr()),xt=T(js,V(e=>Number.isSafeInteger(Number(e)))),Jr={currency:m("CLP"),value:xt,editable:w(ue(),!1)},$s={currency:m("CLP"),value:xt},zt=T(R(),Ce(),V(e=>[...e].length<=140,"note_too_long")),jt={type:m("alias"),alias:Ct},Mt={type:m("account"),id:Ut},$t={type:m("external"),bank_id:T(R(),$(/^[a-z0-9][a-z0-9_-]{0,63}$/)),account_type:Le(["checking","debit","savings"]),account_id:ie(64),holder_id:ie(64),holder_name:ie(256)},Xe=se("type",[_(jt),_(Mt)]),Kr=Xe,Fs=se("type",[_(jt),_(Mt),_($t)]),Hs=se("type",[_({...jt,editable:w(m(!1),!1)}),_({...Mt,editable:w(m(!1),!1)}),_({...$t,editable:w(ue(),!1)})]),Zr=T(R(),Ce(),te(1),Z(80));function Vs(e){const t=/^([1-9][0-9]*)\s+(seconds?|minutes?|hours?|days?)$/.exec(e.trim());if(!t)return!1;const r=t[2]?.replace(/s$/,""),n=r==="day"?86400:r==="hour"?3600:r==="minute"?60:1,s=Number(t[1])*n;return Number.isSafeInteger(s)&&s<=253402300799}function Bs(e){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.test(e))return!1;const t=e.slice(0,10),r=new Date(`${t}T00:00:00Z`);return Number.isFinite(Date.parse(e))&&Number.isFinite(r.getTime())&&r.toISOString().slice(0,10)===t}var Qe=T(R(),V(Vs,"invalid_expiration_interval")),$e=T(R(),V(Bs,"invalid_expiration_datetime")),et={expires_in:w(Qe),expires_at:w($e),note:w(_({value:zt,editable:w(ue(),!1)})),metadata:w(Ue(R(),xe()),{})},_c=T(se("type",[_({...et,type:m("deposit"),destination:w(Xe),amount:w(_(Jr)),expires_at:w(Et($e))}),_({...et,type:m("transfer"),amount:_(Jr),source:w(Et(Kr),null),destination:Hs}),_({...et,type:m("account_opening"),alias:Ct,name:w(Zr),upsert:w(ue(),!1)}),_({...et,type:m("account_closure"),account:Xe})]),V(e=>e.expires_in!==void 0!=(e.expires_at!==void 0),"exactly_one_expiration_required"),V(e=>e.expires_at!==null||e.type==="deposit"&&e.amount===void 0,"passive_deposit_requires_no_target"),V(e=>JSON.stringify(e.metadata).length<=16384,"metadata_too_large")),gc=T(se("type",[_({iss:ie(64),aud:m(St),jti:ie(128),exp:T(Y(),K()),iat:w(T(Y(),K())),nbf:w(T(Y(),K())),type:m("transfer"),source:Kr,destination:Fs,amount:_($s),expires_in:w(Qe),expires_at:w($e),note:w(zt),metadata:w(Ue(R(),xe()),{})}),_({iss:ie(64),aud:m(St),jti:ie(128),exp:T(Y(),K()),iat:w(T(Y(),K())),nbf:w(T(Y(),K())),type:m("account_opening"),alias:Ct,name:w(Zr),upsert:w(ue(),!1),expires_in:w(Qe),expires_at:w($e),metadata:w(Ue(R(),xe()),{})}),_({iss:ie(64),aud:m(St),jti:ie(128),exp:T(Y(),K()),iat:w(T(Y(),K())),nbf:w(T(Y(),K())),type:m("account_closure"),account:Xe,expires_in:w(Qe),expires_at:w($e),metadata:w(Ue(R(),xe()),{})})]),V(e=>e.expires_in!==void 0!=(e.expires_at!==void 0),"exactly_one_expiration_required"),V(e=>JSON.stringify(e.metadata).length<=16384,"metadata_too_large")),Yr=T(R(),Ce(),te(1),V(e=>[...e].length<=280,"reason_too_long")),qs=_({reason:Yr});function Ws(e){return Se(qs,e)}var Gs=_({reason:Yr});function Js(e){return Se(Gs,e)}var wc=_({intent_id:Ut,source_account_id:w(Ut),amount:w(xt),destination:w(_($t)),note:w(zt)}),Ks=_({...G,type:m("click"),presentationId:w(re)}),Zs=Le(ks),Ys=_({...G,type:m("error"),error:_({code:Zs})}),Xs=_({...G,type:m("init")}),Qs=_({...G,type:m("oauth.authorization_code"),presentationId:re,authorizationCode:T(R(),te(1),Z(8192))}),ei=_({...G,type:m("oauth.complete"),presentationId:re}),ti=_({...G,type:m("oauth.dismiss"),presentationId:re}),ri=Ze({...G,type:m("intent.complete"),presentationId:re}),ni=Ze({...G,type:m("intent.dismiss"),presentationId:re}),si=_({...G,type:m("oauth.error"),presentationId:re,error:_({code:T(R(),te(1),Z(256)),description:w(T(R(),Z(2048)))})}),ii=_({...G,type:m("presentation-response"),presentationId:re,url:w(T(R(),te(1),Z(8192)))}),oi=_({...G,type:m("ready")}),ai=T(R(),Z(35),V(e=>{try{return Intl.getCanonicalLocales(e),!0}catch{return!1}})),ci=Le(["dark","light","system"]),ui=_({...G,type:m("set-preferences"),themeMode:w(ci),locale:w(ai)}),li=se("type",[ii,oi,Ks,Ys,Xs,ui,Qs,ei,ti,si,ri,ni]);function di(e){return Se(li,e).success}var vc=1780358400,Xr="andco-popup-",E=class bt 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(bt.is(t))return t;const n=t instanceof Error?t.message:void 0;return new bt(r,{message:n,cause:t})}static is(t){return t instanceof bt}},hi=class Te extends E{error;response;constructor(t,r){super(t,r),this.name="AndcoAPIError",this.error=t,this.response=r.response}static fromOpenAPIFetch(t,r){if(t instanceof E)return new Te(t.code,{response:r,status:t.status,message:t.message,details:t.details,cause:t});const{message:n,details:s}=Te.bodyOf(t),i=new Te(Te.codeOf(t),{response:r,status:Te.statusOf(r),message:n,details:s,cause:t});for(const[o,a]of Object.entries(s??{}))Te.OWN_FIELDS.has(o)||(i[o]=a);return i}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 p.REQUEST_FAILED}static bodyOf(t){if(!t||typeof t!="object")return{message:void 0,details:void 0};const{error:r,message:n,...s}=t,i=Object.keys(s).length>0;return{message:typeof n=="string"?n:void 0,details:i?s: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 E(e,t):e}}};function Ft(e={}){return{fetch:e.fetch??globalThis.fetch.bind(globalThis),crypto:e.crypto??globalThis.crypto}}var Qr=class{#e;#t;constructor(e){this.#e=e,this.#t=e.globals??Ft()}async signIn(e={}){const{config:t,oauth:r,presenter:n,store:s}=this.#e,i=this.#e.randomId?this.#e.randomId():ze(this.#t.crypto),o=e.redirectTo??t.redirectTo;if(!o)return l.fail(p.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 h=await r.createAuthorizationRequest(e);if(h.error)throw h.error;return await this.#e.persistTransaction?.(h.data),a=h.data,h.data.authorizationUrl},presentation:e.presentation??"popup",returnTo:new F(o),presentationId:i});if(c.error)return l.fail(c.error);if(!c.data)return l.ok(null);if(!a)return l.fail(p.INVALID_CALLBACK,{message:"no transaction was prepared"});const u=await r.exchangeCallback({callbackUrl:c.data,request:a});if(u.error)return l.fail(u.error);const d=await s.set(u.data);return d.error?l.fail(d.error):l.ok(u.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(){return this.#e.store.refresh()}},fi=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{2,8})*$/,pi=/^[A-Za-z0-9_-]{1,80}$/,yi=/^\d{10}$/,mi=class br{clientId;endpoints;apiVersion;redirectTo;locale;theme;themeMode;initialScopes;allowedPopupOrigins;constructor(t){if(!pi.test(t.clientId??""))throw new E(p.INVALID_CONFIGURATION,{message:"clientId is missing or malformed"});if(this.clientId=t.clientId,this.endpoints=Object.freeze({auth:new F(t.endpointAuth??"https://auth.andco.com"),api:new F(t.endpointApi??"https://api.andco.com"),widget:new F(t.endpointWidget??"https://widgets.andco.com")}),this.apiVersion=String(t.apiVersion??"_"),this.apiVersion!=="_"&&!yi.test(this.apiVersion))throw new E(p.INVALID_CONFIGURATION,{message:"apiVersion must be `_` or a ten-digit Unix timestamp"});if(this.redirectTo=t.redirectTo===void 0?void 0:new F(t.redirectTo),this.locale=t.locale??"es",!fi.test(this.locale))throw new E(p.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 F(n).origin)]))}static from(t){return new br(t)}with(t){return br.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]}}},Ac=30;function en(e,t=Math.floor(Date.now()/1e3)){return e.expiresAt<=t+30}function Ht(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 _i(e){return{accessTokenFor:async t=>Ht(e,t)}}function gi(e){return typeof e.accessTokenFor=="function"}var wi=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE","request"]);function vi(e,t){return new Proxy(e,{get(r,n,s){const i=Reflect.get(r,n,s);if(typeof n!="string"||!wi.has(n)||typeof i!="function")return i;const o=i;return(...a)=>Ai(o.apply(r,a),t)}})}function Ai(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 s=Response.error();return{error:t(n,s),response:s}});return Object.assign(r,{throwOnError:()=>r.then(n=>{if(n.error!==void 0)throw n.error;return n})})}function bi(e,t,r,n,s){const i=n.pollIntervalMs??1e3;if(!Number.isSafeInteger(i)||i<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:${s.kind}:${s.id.toLowerCase()}:`,a=f=>{if(typeof f!="string"||!f.startsWith(o)||!/^(0|[1-9][0-9]{0,18})$/.test(f.slice(o.length)))throw new TypeError("invalid_or_unsupported_event_cursor");const y=BigInt(f.slice(o.length));if(y>9223372036854775807n)throw new TypeError("invalid_or_unsupported_event_cursor");return y},c=new AbortController;let u=n.after,d;const h=async()=>{if(c.signal.aborted)return;let f=i;try{let y=u===void 0?0n:a(u);const A=await e(u,c.signal);if(c.signal.aborted)return;if(!A||!Array.isArray(A.events)||A.events.length>100||typeof A.has_more!="boolean"||!tn(A.server_time))throw new TypeError("invalid_event_response");const N=a(A.next_cursor),S=new Map;let D=-1n;const b=A.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)||!tn(g.occurred_at))throw new TypeError("invalid_event_response");const O=a(g.cursor);if(O===0n||O<D)throw new TypeError("invalid_event_response");const k=JSON.stringify(g);if(S.has(g.id)&&S.get(g.id)!==k||O===D&&S.get(g.id)!==k)throw new TypeError("invalid_event_response");return S.set(g.id,k),D=O,O});if(A.events.length?N!==b.at(-1):N!==y||A.has_more)throw new TypeError("invalid_event_response");if(A.has_more&&N<=y)throw new TypeError("invalid_event_response");for(let g=0;g<A.events.length;g++){if(c.signal.aborted)return;const O=A.events[g],k=b[g];if(k<=y)continue;const Ee=t(O);Ee!==null&&await r(Ee),u=O.cursor,y=k}u===void 0&&(u=A.next_cursor),A.has_more&&(f=0)}catch(y){if(c.signal.aborted)return;try{await n.onError(y)}catch{c.abort()}}finally{c.signal.aborted||(d=setTimeout(()=>{h()},f))}};return h(),{unsubscribe(){c.abort(),clearTimeout(d)},get checkpoint(){return u}}}function tn(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e))}var Vt=class extends Cr{code;status;details;constructor(e,t,r){super(e),this.code=e,this.status=t,this.details=r}};function Ei(e,t){try{const r=new F(t).origin,n=new F(e.authorization_url);if(n.origin!==r||n.protocol!=="https:")throw new Vt("invalid_authorization_url",500);return n}catch(r){throw r instanceof Vt?r:new Vt("invalid_authorization_url",500)}}var Ii="^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",Ti=/\{[^{}]+\}/g,Si=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Ri(){return Math.random().toString(36).slice(2,11)}function Oi(e){let{baseUrl:t="",Request:r=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:s,bodySerializer:i,pathSerializer:o,headers:a,requestInitExt:c=void 0,...u}={...e};c=Si()?c:void 0,t=an(t);const d=[];async function h(f,y){const{baseUrl:A,fetch:N=n,Request:S=r,headers:D,params:b={},parseAs:g="json",querySerializer:O,bodySerializer:k=i??Pi,pathSerializer:Ee,body:gt,middleware:mr=[],..._r}=y||{};let gr=t;A&&(gr=an(A)??t);let wr=typeof s=="function"?s:sn(s);O&&(wr=typeof O=="function"?O:sn({...typeof s=="object"?s:{},...O}));const rs=Ee||o||Ni,vr=gt===void 0?void 0:k(gt,on(a,D,b.header)),Ba=on(vr===void 0||vr instanceof FormData?{}:{"Content-Type":"application/json"},a,D,b.header),he=[...d,...mr],qa={redirect:"follow",...u,..._r,body:vr,headers:Ba};let wt,vt,fe=new S(ki(f,{baseUrl:gr,params:b,querySerializer:wr,pathSerializer:rs}),qa),U;for(const j in _r)j in fe||(fe[j]=_r[j]);if(he.length){wt=Ri(),vt=Object.freeze({baseUrl:gr,fetch:N,parseAs:g,querySerializer:wr,bodySerializer:k,pathSerializer:rs});for(const j of he)if(j&&typeof j=="object"&&typeof j.onRequest=="function"){const x=await j.onRequest({request:fe,schemaPath:f,params:b,options:vt,id:wt});if(x)if(x instanceof S)fe=x;else if(x instanceof Response){U=x;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!U){try{U=await N(fe,c)}catch(j){let x=j;if(he.length)for(let Ie=he.length-1;Ie>=0;Ie--){const At=he[Ie];if(At&&typeof At=="object"&&typeof At.onError=="function"){const Je=await At.onError({request:fe,error:x,schemaPath:f,params:b,options:vt,id:wt});if(Je){if(Je instanceof Response){x=void 0,U=Je;break}if(Je instanceof Error){x=Je;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(x)throw x}if(he.length)for(let j=he.length-1;j>=0;j--){const x=he[j];if(x&&typeof x=="object"&&typeof x.onResponse=="function"){const Ie=await x.onResponse({request:fe,response:U,schemaPath:f,params:b,options:vt,id:wt});if(Ie){if(!(Ie instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");U=Ie}}}}const ns=U.headers.get("Content-Length");if(U.status===204||fe.method==="HEAD"||ns==="0"&&!U.headers.get("Transfer-Encoding")?.includes("chunked"))return U.ok?{data:void 0,response:U}:{error:void 0,response:U};if(U.ok)return{data:await(async()=>{if(g==="stream")return U.body;if(g==="json"&&!ns){const x=await U.text();return x?JSON.parse(x):void 0}return await U[g]()})(),response:U};let Ar=await U.text();try{Ar=JSON.parse(Ar)}catch{}return{error:Ar,response:U}}return{request(f,y,A){return h(y,{...A,method:f.toUpperCase()})},GET(f,y){return h(f,{...y,method:"GET"})},PUT(f,y){return h(f,{...y,method:"PUT"})},POST(f,y){return h(f,{...y,method:"POST"})},DELETE(f,y){return h(f,{...y,method:"DELETE"})},OPTIONS(f,y){return h(f,{...y,method:"OPTIONS"})},HEAD(f,y){return h(f,{...y,method:"HEAD"})},PATCH(f,y){return h(f,{...y,method:"PATCH"})},TRACE(f,y){return h(f,{...y,method:"TRACE"})},use(...f){for(const y of f)if(y){if(typeof y!="object"||!("onRequest"in y||"onResponse"in y||"onError"in y))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");d.push(y)}},eject(...f){for(const y of f){const A=d.indexOf(y);A!==-1&&d.splice(A,1)}}}}function tt(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 rn(e,t,r){if(!t||typeof t!="object")return"";const n=[],s={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(tt(a,t[o],r))}const i=n.join(s);return r.style==="label"||r.style==="matrix"?`${s}${i}`:i}function nn(e,t,r){if(!Array.isArray(t))return"";if(r.explode===!1){const i={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[r.style]||",",o=(r.allowReserved===!0?t:t.map(a=>encodeURIComponent(a))).join(i);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]||"&",s=[];for(const i of t)r.style==="simple"||r.style==="label"?s.push(r.allowReserved===!0?i:encodeURIComponent(i)):s.push(tt(e,i,r));return r.style==="label"||r.style==="matrix"?`${n}${s.join(n)}`:s.join(n)}function sn(e){return function(r){const n=[];if(r&&typeof r=="object")for(const s in r){const i=r[s];if(i!=null){if(Array.isArray(i)){if(i.length===0)continue;n.push(nn(s,i,{style:"form",explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof i=="object"){n.push(rn(s,i,{style:"deepObject",explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(tt(s,i,e))}}return n.join("&")}}function Ni(e,t){let r=e;for(const n of e.match(Ti)??[]){let s=n.substring(1,n.length-1),i=!1,o="simple";if(s.endsWith("*")&&(i=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(o="label",s=s.substring(1)):s.startsWith(";")&&(o="matrix",s=s.substring(1)),!t||t[s]===void 0||t[s]===null)continue;const a=t[s];if(Array.isArray(a)){r=r.replace(n,nn(s,a,{style:o,explode:i}));continue}if(typeof a=="object"){r=r.replace(n,rn(s,a,{style:o,explode:i}));continue}if(o==="matrix"){r=r.replace(n,`;${tt(s,a)}`);continue}r=r.replace(n,o==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return r}function Pi(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 ki(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 on(...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[s,i]of n)if(i===null)t.delete(s);else if(Array.isArray(i))for(const o of i)t.append(s,o);else i!==void 0&&t.set(s,i)}return t}function an(e){return e.endsWith("/")?e.substring(0,e.length-1):e}function Ci(e){return((t,r)=>{const n=e??globalThis.fetch;return typeof n!="function"?Promise.reject(new Dr(p.FETCH_UNAVAILABLE,{missing:["fetch"]})):n(t,r)})}function Di(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 F(e.endpoint??"https://api.andco.com"),n=Oi({baseUrl:Ps(r,t),fetch:e.fetch??Ci()});return n.use({async onRequest({request:s}){let i;return typeof e.accessToken=="function"?i=await e.accessToken(s):i=e.accessToken,i&&s.headers.set("Authorization",`Bearer ${i}`),s}}),n}var Bt=class ss{#e;#t;#n;#r;#s=[];http;raw;forOperation(){const t=new ss({config:this.#e,globals:this.#t,credentials:this.#n.forOperation?.()??this.#n,resource:this.#r});return t.raw.use(...this.#s),t}constructor(t){this.#e=t.config,this.#t=t.globals,this.#n=t.credentials,this.#r=t.resource??t.config.endpoints.api.origin;const r=(o={})=>Di({endpoint:this.#e.endpoints.api,apiVersion:this.#e.apiVersion,accessToken:()=>this.#n.accessTokenFor(this.#r,{grant:o.grant}),fetch:this.#t.fetch}),n=r(),s=this.#s,i=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE","request"]);this.raw=new Proxy(n,{get(o,a,c){return a==="use"?(...u)=>{s.push(...u)}:a==="eject"?(...u)=>{for(const d of u){const h=s.indexOf(d);h>=0&&s.splice(h,1)}}:typeof a!="string"||!i.has(a)?Reflect.get(o,a,c):(...u)=>{const d=a==="request"?3:2,h=u[d]??{},f=r(h);return f.use(...s),Reflect.get(f,a).apply(f,u.slice(0,d))}}}),this.http=vi(this.raw,hi.fromOpenAPIFetch)}},Li=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ui=class{#e;#t;constructor(e){this.#e=e.config,this.#t=e.globals}async get(e){if(Li.test(e))return console.debug("[grants.get] a grant id was given, but no endpoint reads a Grant by id"),l.fail(new E("not_implemented",{message:"Grants can only be read with the token that carries them"}));const{data:t,error:r}=await new Bt({config:this.#e,globals:this.#t,credentials:{accessTokenFor:async()=>e}}).http.GET("/authorization");return r||!t?(console.debug("[grants.get] lookup failed status=%s code=%s",r?.status,r?.code),l.fail(r??new E("invalid_response"))):(console.debug("[grants.get] grant %s active=%s",t.grantId,t.active),l.ok(t))}},xi=new RegExp(Ii,"i"),zi=/^[A-Za-z0-9._:-]{1,128}$/,ji=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,qt="andco.intent_presentation",Mi=new Set(["succeeded","completed","closed","cancelled","rejected","expired"]),cn=class is{#e;#t;#n;#r;#s;#i=new Map;constructor(t){this.#e=t.rest,this.#t=t.config,this.#n=t.presenter,this.#r=t.globals??Ft(),this.#s=t.presentationStorage??Fi()}static isTerminal(t){return Mi.has(t.status)||t.status.startsWith("failed")}async create(t,r,n={}){const s=n.idempotencyKey??ze(this.#r.crypto);if(!zi.test(s))return l.fail(p.INVALID_CONFIGURATION,{message:"malformed Idempotency-Key"});let i;try{({data:i}=await this.#e.http.POST("/intents",{headers:{"Content-Type":Os},params:{header:{"Idempotency-Key":s}},body:{...r,type:t}}).throwOnError())}catch(o){return l.fail(o)}return i?.type!==t?l.fail(p.INVALID_RESPONSE,{message:`expected a ${t} intent`}):l.ok(i)}async createSigned(t,r){if(!ji.test(r))return l.fail(p.INVALID_CONFIGURATION,{message:"malformed Signed Instruction"});let n;try{({data:n}=await this.#e.http.POST("/intents",{headers:{"Content-Type":Ns},bodySerializer:s=>s,body:r}).throwOnError())}catch(s){return l.fail(s)}return n?.type!==t?l.fail(p.INVALID_RESPONSE,{message:`expected a ${t} intent`}):l.ok(n)}presentationURL(t,r){if(!this.#t)return l.fail(rt());const n=this.#c(r);if(n.error)return l.fail(n.error);const{returnTo:s,errorReturnTo:i}=n.data;let o,a;try{o=Ei(t,this.#t.endpoints.api),a=r.state??Ot(s.origin,ze(this.#r.crypto))}catch(c){return console.error("[AndcoIntents.presentationURL] invalid authorization_url %o",c),l.fail(E.from(c,p.INVALID_RESPONSE))}return o.searchParams.set("return_uri",s.href),o.searchParams.set("error_return_uri",i.href),o.searchParams.set("presentation",r.presentation),o.searchParams.set("state",a),console.debug("[AndcoIntents.presentationURL] built %s for %s",r.presentation,o.origin+o.pathname),l.ok(o)}async presentationURLFor(t,r){if(!this.#t)return l.fail(rt());const n=await this.get(t);return n.error?l.fail(n.error):this.presentationURL(n.data,r)}present(t,r={}){const n=r.presentation??"popup",s=typeof t=="string"?t:typeof t=="object"?t.id:void 0;if(s!==void 0&&n!=="redirect"){const d=this.#i.get(s);if(d&&d.controller.status==="presenting")return console.debug("[AndcoIntents.present] %s is already presenting; focusing %s",s,d.presentationId),this.#n?.focus?.(d.presentationId),d.controller}let i="presenting";const o=new AbortController;r.signal?.aborted&&o.abort(),r.signal?.addEventListener("abort",()=>o.abort(),{once:!0});const a=ze(this.#r.crypto),c=this.#a(t,r,a,o.signal,d=>{i=d}),u={get status(){return i},result:c,close:()=>{console.debug("[AndcoIntents.present] close requested while %s",i),o.abort()}};if(s!==void 0&&n!=="redirect"){this.#i.set(s,{controller:u,presentationId:a});const d=()=>{this.#i.get(s)?.controller===u&&this.#i.delete(s)};c.then(d,d)}return u}async#a(t,r,n,s,i){const o=b=>(console.error("[AndcoIntents.present] %o",b),i("error"),l.fail(b));if(!this.#t||!this.#n)return o(rt());const a=r.presentation??"popup",c=this.#c(r);if(c.error)return o(c.error);const{returnTo:u,errorReturnTo:d}=c.data,h={presentation:a,returnTo:u,errorReturnTo:d,state:Ot(u.origin,n)};let f;const y=b=>{const g=this.presentationURL(b,h);if(g.error)throw g.error;return f=b.id,a!=="popup"&&this.#o(n,{intentId:b.id,presentation:a}),g.data};let A;if(typeof t=="object")try{A=y(t)}catch(b){return o(E.from(b,p.INVALID_RESPONSE))}else A=async()=>{let b;try{b=typeof t=="string"?t:await t()}catch(O){throw E.from(O,p.INVALID_CONFIGURATION)}if(typeof b=="object"&&"authorization_url"in b)return y(b);const g=await this.get(typeof b=="string"?b:b.id);if(g.error)throw g.error;return y(g.data)};console.debug("[AndcoIntents.present] presenting %s presentationId=%s",a,n);const N=await this.#n.present({kind:"intent",presentation:a,url:A,get intentId(){return f??""},returnTo:u,errorReturnTo:d,presentationId:n,signal:s});if(N.error)return this.#d(n),o(N.error);if(f){if(a==="redirect"&&N.data===null)return console.debug("[AndcoIntents.present] navigated away intentId=%s",f),i("navigated"),new Promise(()=>{})}else return o(rt());this.#d(n);const S=$i(N.data,{presentationId:n});if(S.error)return o(S.error);console.debug("[AndcoIntents.present] settled: %s intentId=%s presentationId=%s",S.data,f,n);const D=await this.get(f);return D.error?o(D.error):(i(S.data==="complete"?"complete":"dismissed"),l.ok({outcome:S.data,intent:D.data}))}async fromCallback(t,r={}){const n=h=>(console.error("[AndcoIntents.fromCallback] %s",h),l.fail(p.INVALID_CALLBACK,{message:h}));let s;try{s=new URL(t)}catch{return n("the callback is not a URL")}const i=s.searchParams.get("state"),o=i?Nt(i):null;if(!i||!o)return n("the callback carries no valid state");const a=s.searchParams.get("intent_id");let c;if(r.state!==void 0){if(i!==r.state)return n("the callback does not belong to this presentation");c=a}else{const h=this.#u(o.presentationId);if(!h)return n("the callback does not belong to a presentation this browser started");if(this.#d(o.presentationId),a&&a!==h.intentId)return n("the callback names a different Intent than the one presented");c=h.intentId}if(!c)return n("the callback names no Intent");const u=s.searchParams.get("andco_intent_result");if(u!=="complete"&&u!=="dismiss")return n("the callback carries no Intent result");console.debug("[AndcoIntents.fromCallback] %s intentId=%s",u,c);const d=await this.get(c);return d.error?l.fail(d.error):l.ok({outcome:u,intent:d.data})}async get(t){const r=pe(t),n=ye(r);if(n)return l.fail(n);try{const{data:s}=await this.#e.http.GET("/intents/{intent_id}",{params:{path:{intent_id:r}}}).throwOnError();return l.ok(s)}catch(s){return l.fail(s)}}watch(t,r={}){const n=pe(t),s=Math.max(r.pollIntervalMs??1e3,100);let i="watching",o=null,a,c=()=>{},u=()=>{};const d=new Promise(b=>{u=(g,O)=>{i==="watching"&&(i=O,clearTimeout(a),c(),r.signal?.removeEventListener("abort",h),console.debug("[AndcoIntents.watch] %s ended %s %o",n,O,g.error??g.data?.status),b(g))}}),h=()=>u(l.fail(p.WATCH_STOPPED),"stopped"),f={get status(){return i},get intent(){return o},result:d,stop:h},y=ye(n);if(y)return u(l.fail(y),"settled"),f;if(r.signal?.aborted)return h(),f;r.signal?.addEventListener("abort",h,{once:!0});let A=!1,N=!1;const S=async()=>{if(A)return;A=!0,clearTimeout(a);const b=await this.get(n);if(A=!1,i==="watching"){if(b.error)console.error("[AndcoIntents.watch] read of %s failed, retrying: %o",n,b.error),r.onError?.(b.error);else if(o=b.data,r.onChange?.(b.data),N||is.isTerminal(b.data))return u(l.ok(b.data),"settled");a=setTimeout(()=>{S()},s)}},D=r.types?new Set(r.types):null;return console.debug("[AndcoIntents.watch] %s until=%s types=%o",n,r.until??"terminal",r.types),c=this.subscribe(n,{pollIntervalMs:s,onError:()=>{}},b=>{D?.has(b.type)&&(N=!0),S()}),S(),f}async approve(t,r={}){const n=pe(t),s=ye(n);if(s)return l.fail(s);console.debug("[AndcoIntents.approve] approving %s with grant %o",n,r.grant??"selected");try{const{data:i}=await this.#e.http.POST("/intents/{intent_id}/approve",{params:{path:{intent_id:n}}},{grant:r.grant}).throwOnError();return l.ok(i)}catch(i){return l.fail(i)}}async reject(t,r){const n=pe(t),s=ye(n);if(s)return l.fail(s);const i=Js({reason:r.reason});if(!i.success)return l.fail(p.INVALID_CONFIGURATION,{message:"rejection reason must be 1-280 characters"});console.debug("[AndcoIntents.reject] rejecting %s",n);try{const{data:o}=await this.#e.http.POST("/intents/{intent_id}/reject",{params:{path:{intent_id:n}},body:{reason:i.output.reason}},{grant:r.grant}).throwOnError();return l.ok(o)}catch(o){return l.fail(o)}}async cancel(t,r){const n=pe(t),s=ye(n);if(s)return l.fail(s);const i=Ws({reason:r.reason});if(!i.success)return l.fail(p.INVALID_CONFIGURATION,{message:"cancellation reason must be 1-280 characters"});console.debug("[AndcoIntents.cancel] cancelling %s",n);try{const{data:o}=await this.#e.http.POST("/intents/{intent_id}/cancel",{params:{path:{intent_id:n}},body:{reason:i.output.reason}},{grant:r.grant}).throwOnError();return l.ok(o)}catch(o){return l.fail(o)}}async events(t,r,n){const s=pe(t),i=ye(s);if(i)return l.fail(i);try{const{data:o}=await this.#e.http.GET("/intents/{intent_id}/events",{params:{path:{intent_id:s},query:{after:r,limit:100}},signal:n}).throwOnError();return l.ok(o)}catch(o){return l.fail(o)}}subscribe(t,r,n){const s=typeof r=="function"?{}:r,i=typeof r=="function"?r:n,o=pe(t),a=s.onError??(h=>console.error("[AndcoIntents.subscribe] %s %o",o,h)),c=ye(o);if(c)return queueMicrotask(()=>a(c)),()=>{};const u=s.types?new Set(s.types):null;console.debug("[AndcoIntents.subscribe] %s types=%o after=%s",o,s.types,s.after);const d=bi(async(h,f)=>{const y=await this.events(o,h,f);if(y.error)throw y.error;return y.data},h=>u===null||u.has(h.type)?h:null,async h=>{await i(h),s.onCheckpoint?.(h.cursor)},{after:s.after,onError:a,pollIntervalMs:s.pollIntervalMs},{kind:"intent",id:o});return()=>d.unsubscribe()}#c(t){let r,n;try{if(r=t.returnTo?new F(t.returnTo):this.#t?.redirectTo,!r)return l.fail(p.INVALID_CONFIGURATION,{message:"an Intent Presentation needs a returnTo, and this instance has no redirectTo"});n=t.errorReturnTo?new F(t.errorReturnTo):r}catch(s){return l.fail(E.from(s,p.INVALID_CONFIGURATION))}return r.origin!==n.origin?l.fail(p.INVALID_CONFIGURATION,{message:"returnTo and errorReturnTo must share one origin"}):l.ok({returnTo:r,errorReturnTo:n})}#o(t,r){if(!this.#s){console.warn("[AndcoIntents.present] no presentationStorage; fromCallback will refuse this return");return}this.#s.setItem(`${qt}.${t}`,JSON.stringify(r))}#u(t){const r=this.#s?.getItem(`${qt}.${t}`);if(!r)return null;try{const n=JSON.parse(r);return typeof n.intentId=="string"&&typeof n.presentation=="string"?n:null}catch{return null}}#d(t){this.#s?.removeItem(`${qt}.${t}`)}};function $i(e,t){if(!e)return l.ok("dismiss");const r=e.searchParams.get("state"),n=r?Nt(r):null;if(!n||n.presentationId!==t.presentationId)return l.fail(p.INVALID_CALLBACK,{message:"the callback does not belong to this presentation"});const s=e.searchParams.get("andco_intent_result");return s==="complete"?l.ok("complete"):s==="dismiss"?l.ok("dismiss"):l.fail(p.INVALID_CALLBACK,{message:"the callback carries no Intent result"})}function Fi(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}function rt(){return new E(p.PRESENTATION_UNSUPPORTED,{message:"this Intent surface was composed without a presenter; present through the Andco Instance instead"})}function pe(e){return typeof e=="string"?e:e.id}function ye(e){return xi.test(e)?null:new E(p.INVALID_INTENT_ID,{message:`${e} is not a valid identifier`})}var Wt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Wt="oauth4webapi/v3.8.8");function me(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 q="ERR_INVALID_ARG_VALUE",J="ERR_INVALID_ARG_TYPE";function P(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}var X=Symbol(),nt=Symbol(),Gt=Symbol(),oe=Symbol(),ae=Symbol(),Hi=new TextEncoder,Vi=new TextDecoder;function Jt(e){return typeof e=="string"?Hi.encode(e):Vi.decode(e)}var Kt;Uint8Array.prototype.toBase64?Kt=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Kt=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 Zt;Uint8Array.fromBase64?Zt=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw P("The input to be decoded is not correctly encoded.",q,t)}}:Zt=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 P("The input to be decoded is not correctly encoded.",q,t)}};function st(e){return typeof e=="string"?Zt(e):Kt(e)}var Fe=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=or,Error.captureStackTrace?.(this,this.constructor)}},Yt=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 v(e,t,r){return new Yt(e,{code:t,cause:r})}function it(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function He(e){me(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(e??{});if(Wt&&!t.has("user-agent")&&t.set("user-agent",Wt),t.has("authorization"))throw P('"options.headers" must not include the "authorization" header name',q);return t}function un(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw P('"options.signal" must return or be an instance of AbortSignal',J);return t}}function _e(e,t,r,n,s){try{if(typeof e!="number"||!Number.isFinite(e))throw P(`${r} must be a number`,J,s);if(e>0)return;if(t){if(e!==0)throw P(`${r} must be a non-negative number`,q,s);return}throw P(`${r} must be a positive number`,q,s)}catch(i){throw n?v(i.message,n,s):i}}function C(e,t,r,n){try{if(typeof e!="string")throw P(`${t} must be a string`,J,n);if(e.length===0)throw P(`${t} must not be empty`,q,n)}catch(s){throw r?v(s.message,r,n):s}}function ln(e){qi(e,"application/json")}function Bi(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 v(r,Pn,e)}function qi(e,t){if(ct(e)!==t)throw Bi(e,t)}function dn(){return st(crypto.getRandomValues(new Uint8Array(32)))}function Wi(){return dn()}function Gi(){return dn()}async function Ji(e){return C(e,"codeVerifier"),st(await crypto.subtle.digest("SHA-256",Jt(e)))}function ot(e){const t=e?.[nt];return typeof t=="number"&&Number.isFinite(t)?t:0}function Xt(e){const t=e?.[Gt];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function hn(){return Math.floor(Date.now()/1e3)}function Q(e){if(typeof e!="object"||e===null)throw P('"as" must be an object',J);C(e.issuer,'"as.issuer"')}function ee(e){if(typeof e!="object"||e===null)throw P('"client" must be an object',J);C(e.client_id,'"client.client_id"')}function fn(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 pn(e){return C(e,'"clientSecret"'),(t,r,n,s)=>{n.set("client_id",r.client_id),n.set("client_secret",e)}}function yn(e){return C(e,'"clientSecret"'),(t,r,n,s)=>{const i=fn(r.client_id),o=fn(e),a=btoa(`${i}:${o}`);s.set("authorization",`Basic ${a}`)}}function Ki(){return(e,t,r,n)=>{r.set("client_id",t.client_id)}}var Zi=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function mn(e,t){if(t&&e.protocol!=="https:")throw v("only requests to HTTPS are allowed",kn,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw v("only HTTP and HTTPS requests are allowed",Cn,e)}function _n(e,t,r,n){let s;if(typeof e!="string"||!(s=Zi(e)))throw v(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Oo:No,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return mn(s,n),s}function Ve(e,t,r,n){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?_n(e.mtls_endpoint_aliases[t],t,r,n):_n(e[t],t,r,n)}async function Yi(e,t,r,n,s){Q(e),ee(t);const i=Ve(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,s?.[X]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=He(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(tr(s.DPoP),await s.DPoP.addProof(i,a,"POST"));const c=await rr(e,t,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}function Xi(e){return e instanceof Qt?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof at?e.error==="use_dpop_nonce":!1}var at=class extends Error{cause;code;error;status;error_description;response;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=To,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)}},gn=class extends Error{cause;code;error;error_description;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=So,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)}},Qt=class extends Error{cause;code;response;status;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Io,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Qi=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),eo=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),to=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),ro=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function no(e){if(!me(e,Response))throw P('"response" must be an instance of Response',J);const t=e.headers.get("www-authenticate");if(t===null)return;const r=[];let n=t;for(;n;){let s=n.match(Qi);const i=s?.[1].toLowerCase();if(!i)return;const o=n.substring(s[0].length);if(o&&!o.match(/^[\s,]/))return;const a=o.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;const u={};let d;if(c)for(;n;){let f,y;if(s=n.match(eo)){[,f,y,n]=s,y.includes("\\")&&(y=y.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=y;continue}if(s=n.match(to)){[,f,y,n]=s,u[f.toLowerCase()]=y;continue}if(s=n.match(ro)){if(Object.keys(u).length)break;[,d,n]=s;break}return}else n=o||void 0;const h={scheme:i,parameters:u};d&&(h.token68=d),r.push(h)}if(r.length)return r}async function so(e,t,r){if(Q(e),ee(t),!me(r,Response))throw P('"response" must be an instance of Response',J);await er(r,201,"Pushed Authorization Request Endpoint"),Be(r);const n=await pt(r);C(n.request_uri,'"response" body "request_uri" property',I,{body:n});let s=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return _e(s,!0,'"response" body "expires_in" property',I,{body:n}),n.expires_in=s,n}async function io(e){if(e.status>399&&e.status<500){Be(e),ln(e);try{const t=await e.clone().json();if(it(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function er(e,t,r){if(e.status!==t){bn(e);let n;throw(n=await io(e))?(await e.body?.cancel(),new at("server responded with an error in the response body",{cause:n,response:e})):v(`"response" is not a conform ${r} response (unexpected HTTP status code)`,ar,e)}}function tr(e){if(!ir.has(e))throw P('"options.DPoP" is not a valid DPoPHandle',q)}async function oo(e,t,r,n,s,i){if(C(e,'"accessToken"'),!(r instanceof URL))throw P('"url" must be an instance of URL',J);mn(r,i?.[X]!==!0),n=He(n),i?.DPoP&&(tr(i.DPoP),await i.DPoP.addProof(r,n,t.toUpperCase(),e)),n.set("authorization",`${n.has("dpop")?"DPoP":"Bearer"} ${e}`);const o=await(i?.[oe]||fetch)(r.href,{duplex:me(s,ReadableStream)?"half":void 0,body:s,headers:Object.fromEntries(n.entries()),method:t,redirect:"manual",signal:un(r,i?.signal)});return i?.DPoP?.cacheNonce(o,r),o}async function ao(e,t,r,n){Q(e),ee(t);const s=Ve(e,"userinfo_endpoint",t.use_mtls_endpoint_aliases,n?.[X]!==!0),i=He(n?.headers);return t.userinfo_signed_response_alg?i.set("accept","application/jwt"):(i.set("accept","application/json"),i.append("accept","application/jwt")),oo(r,"GET",s,i,null,{...n,[nt]:ot(t)})}var wn=Symbol();function ct(e){return e.headers.get("content-type")?.split(";")[0]}async function co(e,t,r,n,s){if(Q(e),ee(t),!me(n,Response))throw P('"response" must be an instance of Response',J);if(bn(n),n.status!==200)throw v('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)',ar,n);Be(n);let i;if(ct(n)==="application/jwt"){const{claims:o,jwt:a}=await Ln(await n.text(),Un.bind(void 0,t.userinfo_signed_response_alg,e.userinfo_signing_alg_values_supported,void 0),ot(t),Xt(t),s?.[ae]).then(ho.bind(void 0,t.client_id)).then(fo.bind(void 0,e));An.set(n,a),i=o}else{if(t.userinfo_signed_response_alg)throw v("JWT UserInfo Response expected",Ro,n);i=await pt(n)}switch(C(i.sub,'"response" body "sub" property',I,{body:i}),r){case wn:break;default:if(C(r,'"expectedSubject"'),i.sub!==r)throw v('unexpected "response" body "sub" property value',Dn,{expected:r,body:i,attribute:"sub"})}return i}async function rr(e,t,r,n,s,i,o){return await r(e,t,s,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(o?.[oe]||fetch)(n.href,{body:s,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:un(n,o?.signal)})}async function nr(e,t,r,n,s,i){const o=Ve(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[X]!==!0);s.set("grant_type",n);const a=He(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(tr(i.DPoP),await i.DPoP.addProof(o,a,"POST"));const c=await rr(e,t,r,o,s,a,i);return i?.DPoP?.cacheNonce(c,o),c}async function uo(e,t,r,n,s){Q(e),ee(t),C(n,'"refreshToken"');const i=new URLSearchParams(s?.additionalParameters);return i.set("refresh_token",n),nr(e,t,r,"refresh_token",i,s)}var vn=new WeakMap,An=new WeakMap;function sr(e){if(!e.id_token)return;const t=vn.get(e);if(!t)throw P('"ref" was already garbage collected or did not resolve from the proper sources',q);return t}async function ut(e,t,r,n,s,i){if(Q(e),ee(t),!me(r,Response))throw P('"response" must be an instance of Response',J);await er(r,200,"Token Endpoint"),Be(r);const o=await pt(r);if(C(o.access_token,'"response" body "access_token" property',I,{body:o}),C(o.token_type,'"response" body "token_type" property',I,{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;_e(a,!0,'"response" body "expires_in" property',I,{body:o}),o.expires_in=a}if(o.refresh_token!==void 0&&C(o.refresh_token,'"response" body "refresh_token" property',I,{body:o}),o.scope!==void 0&&typeof o.scope!="string")throw v('"response" body "scope" property must be a string',I,{body:o});if(o.id_token!==void 0){C(o.id_token,'"response" body "id_token" property',I,{body:o});const a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(_e(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);const{claims:c,jwt:u}=await go(e,t,o.id_token,a,s);vo(t,c),wo(c),An.set(r,u),vn.set(o,c)}if(i?.[o.token_type]!==void 0)i[o.token_type](r,o);else if(o.token_type!=="dpop"&&o.token_type!=="bearer")throw new Fe("unsupported `token_type` value",{cause:{body:o}});return o}function bn(e){let t;if(t=no(e))throw new Qt("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function lo(e,t,r,n){return ut(e,t,r,void 0,n?.[ae],n?.recognizedTokenTypes)}function ho(e,t){return t.claims.aud!==void 0?En(e,t):t}function En(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw v('unexpected JWT "aud" (audience) claim value',ge,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw v('unexpected JWT "aud" (audience) claim value',ge,{expected:e,claims:t.claims,claim:"aud"});return t}function fo(e,t){return t.claims.iss!==void 0?In(e,t):t}function In(e,t){const r=e[xn]?.(t)??e.issuer;if(t.claims.iss!==r)throw v('unexpected JWT "iss" (issuer) claim value',ge,{expected:r,claims:t.claims,claim:"iss"});return t}var ir=new WeakSet;function po(e){return ir.add(e),e}var Tn=Symbol();async function yo(e,t,r,n,s,i,o){if(Q(e),ee(t),!ir.has(n))throw P('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',q);C(s,'"redirectUri"');const a=we(n,"code");if(!a)throw v('no authorization code in "callbackParameters"',I);const c=new URLSearchParams(o?.additionalParameters);return c.set("redirect_uri",s),c.set("code",a),i!==Tn&&(C(i,'"codeVerifier"'),c.set("code_verifier",i)),nr(e,t,r,"authorization_code",c,o)}var Sn={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 mo(e,t){for(const r of e)if(t.claims[r]===void 0)throw v(`JWT "${r}" (${Sn[r]}) claim missing`,I,{claims:t.claims});return t}function _o(e,t){if(typeof t.claims[e]!="string")throw v(`unexpected JWT "${e}" (${Sn[e]}) claim type`,I,{claims:t.claims});return t}function go(e,t,r,n,s){return Ln(r,Un.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),ot(t),Xt(t),s).then(mo.bind(void 0,["aud","exp","iat","iss","sub",...n])).then(In.bind(void 0,e)).then(En.bind(void 0,t.client_id)).then(_o.bind(void 0,"sub"))}function Rn(e,t){if(t===dt)return t;const r=t===void 0;return r&&(t=e.default_max_age),t===void 0?dt:(_e(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function wo(e){e.auth_time!==void 0&&_e(e.auth_time,!0,'ID Token "auth_time" (authentication time)',I,{claims:e})}function On(e,t,r){if(r===dt)return;const n=hn()+ot(e),s=Xt(e);if(t.auth_time+r<n-s)throw v("too much time has elapsed since the last End-User authentication",ft,{claims:t,now:n,tolerance:s,claim:"auth_time"})}function Nn(e,t){const r=t===lt?void 0:t;if(e.nonce!==r)throw v('unexpected ID Token "nonce" claim value',ge,{expected:r,claims:e,claim:"nonce"})}function vo(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw v('ID Token "aud" (audience) claim includes additional untrusted audiences',ge,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw v('unexpected ID Token "azp" (authorized party) claim value',ge,{expected:e.client_id,claims:t,claim:"azp"})}}var lt=Symbol(),dt=Symbol();async function Ao(e,t,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?bo(e,t,r,n.expectedNonce,n.maxAge,n[ae],n.recognizedTokenTypes):Eo(e,t,r,n?.maxAge,n?.[ae],n?.recognizedTokenTypes)}async function bo(e,t,r,n,s,i,o){const a=[];switch(n){case void 0:n=lt;break;case lt:break;default:C(n,'"expectedNonce" argument'),a.push("nonce")}s=Rn(t,s),s!==dt&&a.push("auth_time");const c=await ut(e,t,r,a,i,o);C(c.id_token,'"response" body "id_token" property',I,{body:c});const u=sr(c);return On(t,u,s),Nn(u,n),c}async function Eo(e,t,r,n,s,i){const o=await ut(e,t,r,void 0,s,i),a=sr(o);return a&&(On(t,a,Rn(t,n)),Nn(a,lt)),o}var Io="OAUTH_WWW_AUTHENTICATE_CHALLENGE",To="OAUTH_RESPONSE_BODY_ERROR",or="OAUTH_UNSUPPORTED_OPERATION",So="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Ro="OAUTH_JWT_USERINFO_EXPECTED",ht="OAUTH_PARSE_ERROR",I="OAUTH_INVALID_RESPONSE",Pn="OAUTH_RESPONSE_IS_NOT_JSON",ar="OAUTH_RESPONSE_IS_NOT_CONFORM",kn="OAUTH_HTTP_REQUEST_FORBIDDEN",Cn="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",ft="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",ge="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Dn="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Oo="OAUTH_MISSING_SERVER_METADATA",No="OAUTH_INVALID_SERVER_METADATA";function Be(e){if(e.bodyUsed)throw P('"response" body has been used already',q)}async function Ln(e,t,r,n,s){let{0:i,1:o,length:a}=e.split(".");if(a===5)if(s!==void 0)e=await s(e),{0:i,1:o,length:a}=e.split(".");else throw new Fe("JWE decryption is not configured",{cause:e});if(a!==3)throw v("Invalid JWT",I,e);let c;try{c=JSON.parse(Jt(st(i)))}catch(h){throw v("failed to parse JWT Header body as base64url encoded JSON",ht,h)}if(!it(c))throw v("JWT Header must be a top level object",I,e);if(t(c),c.crit!==void 0)throw new Fe('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Jt(st(o)))}catch(h){throw v("failed to parse JWT Payload body as base64url encoded JSON",ht,h)}if(!it(u))throw v("JWT Payload must be a top level object",I,e);const d=hn()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw v('unexpected JWT "exp" (expiration time) claim type',I,{claims:u});if(u.exp<=d-n)throw v('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',ft,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw v('unexpected JWT "iat" (issued at) claim type',I,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw v('unexpected JWT "iss" (issuer) claim type',I,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw v('unexpected JWT "nbf" (not before) claim type',I,{claims:u});if(u.nbf>d+n)throw v('unexpected JWT "nbf" (not before) claim value',ft,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw v('unexpected JWT "aud" (audience) claim type',I,{claims:u});return{header:c,claims:u,jwt:e}}async function Po(e){if(e.bodyUsed)throw P("form_post Request instances must contain a readable body",q,{cause:e});return e.text()}async function ko(e){if(e.method!=="POST")throw P("form_post responses are expected to use the POST method",q,{cause:e});if(ct(e)!=="application/x-www-form-urlencoded")throw P("form_post responses are expected to use the application/x-www-form-urlencoded content-type",q,{cause:e});return Po(e)}function Un(e,t,r,n){if(e!==void 0){if(typeof e=="string"?n.alg!==e:!e.includes(n.alg))throw v('unexpected JWT "alg" header parameter',I,{header:n,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(n.alg))throw v('unexpected JWT "alg" header parameter',I,{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 v('unexpected JWT "alg" header parameter',I,{header:n,expected:r,reason:"default value"});return}throw v('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function we(e,t){const{0:r,length:n}=e.getAll(t);if(n>1)throw v(`"${t}" parameter must be provided only once`,I);return r}var Co=Symbol(),Do=Symbol();function Lo(e,t,r,n){if(Q(e),ee(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw P('"parameters" must be an instance of URLSearchParams, or URL',J);if(we(r,"response"))throw v('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',I,{parameters:r});const s=we(r,"iss"),i=we(r,"state");if(!s&&e.authorization_response_iss_parameter_supported)throw v('response parameter "iss" (issuer) missing',I,{parameters:r});if(s&&s!==e.issuer)throw v('unexpected "iss" (issuer) response parameter value',I,{expected:e.issuer,parameters:r});switch(n){case void 0:case Do:if(i!==void 0)throw v('unexpected "state" response parameter encountered',I,{expected:void 0,parameters:r});break;case Co:break;default:if(C(n,'"expectedState" argument'),i!==n)throw v(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',I,{expected:n,parameters:r})}if(we(r,"error"))throw new gn("authorization response from the server is an error",{cause:r});const o=we(r,"id_token"),a=we(r,"token");if(o!==void 0||a!==void 0)throw new Fe("implicit and hybrid flows are not supported");return po(new URLSearchParams(r))}async function Uo(e,t,r,n,s){Q(e),ee(t);const i=Ve(e,"device_authorization_endpoint",t.use_mtls_endpoint_aliases,s?.[X]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=He(s?.headers);return a.set("accept","application/json"),rr(e,t,r,i,o,a,s)}async function xo(e,t,r){if(Q(e),ee(t),!me(r,Response))throw P('"response" must be an instance of Response',J);await er(r,200,"Device Authorization Endpoint"),Be(r);const n=await pt(r);C(n.device_code,'"response" body "device_code" property',I,{body:n}),C(n.user_code,'"response" body "user_code" property',I,{body:n}),C(n.verification_uri,'"response" body "verification_uri" property',I,{body:n});let s=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return _e(s,!0,'"response" body "expires_in" property',I,{body:n}),n.expires_in=s,n.verification_uri_complete!==void 0&&C(n.verification_uri_complete,'"response" body "verification_uri_complete" property',I,{body:n}),n.interval!==void 0&&_e(n.interval,!1,'"response" body "interval" property',I,{body:n}),n}async function zo(e,t,r,n,s){Q(e),ee(t),C(n,'"deviceCode"');const i=new URLSearchParams(s?.additionalParameters);return i.set("device_code",n),nr(e,t,r,"urn:ietf:params:oauth:grant-type:device_code",i,s)}async function jo(e,t,r,n){return ut(e,t,r,void 0,n?.[ae],n?.recognizedTokenTypes)}async function pt(e,t=ln){let r;try{r=await e.json()}catch(n){throw t(e),v('failed to parse "response" body as JSON',ht,n)}if(!it(r))throw v('"response" body must be a top level object',I,{body:r});return r}var xn=Symbol(),ve,zn;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(zn="openid-client/v6.8.8",ve={"user-agent":zn});var H=e=>cr.get(e),cr;function Mo(e){if(e!==void 0)return pn(e);const t=new WeakMap;return(r,n,s,i)=>{let o;return(o=t.get(n))||(jn(n.client_secret,'"metadata.client_secret"'),o=pn(n.client_secret),t.set(n,o)),o(r,n,s,i)}}function jn(e,t){if(typeof e!="string")throw ce(`${t} must be a string`,yt);if(e.length===0)throw ce(`${t} must not be empty`,qe)}function $o(e){if(e!==void 0)return yn(e);const t=new WeakMap;return(r,n,s,i)=>{let o;return(o=t.get(n))||(jn(n.client_secret,'"metadata.client_secret"'),o=yn(n.client_secret),t.set(n,o)),o(r,n,s,i)}}function Mn(){return Ki()}var Fo=wn,ur=oe,qe="ERR_INVALID_ARG_VALUE",yt="ERR_INVALID_ARG_TYPE";function ce(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}function Ho(e){return Ji(e)}function Vo(){return Wi()}function Bo(){return Gi()}var lr=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=t?.code,Error.captureStackTrace?.(this,this.constructor)}},bc=new TextDecoder;function z(e,t,r){return new lr(e,{cause:t,code:r})}function W(e){if(e instanceof TypeError||e instanceof lr||e instanceof at||e instanceof gn||e instanceof Qt)throw e;if(e instanceof Yt)switch(e.code){case kn:throw z("only requests to HTTPS are allowed",e,e.code);case Cn:throw z("only requests to HTTP or HTTPS are allowed",e,e.code);case ar:throw z("unexpected HTTP response status code",e.cause,e.code);case Pn:throw z("unexpected response content-type",e.cause,e.code);case ht:throw z("parsing error occured",e,e.code);case I:throw z("invalid response encountered",e,e.code);case ge:throw z("unexpected JWT claim value encountered",e,e.code);case Dn:throw z("unexpected JSON attribute value encountered",e,e.code);case ft:throw z("JWT timestamp claim value failed validation",e,e.code);default:throw z(e.message,e,e.code)}if(e instanceof Fe)throw z("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw z("runtime operation error",e,or);case"NotSupportedError":throw z("runtime unsupported operation",e,or);case"TimeoutError":throw z("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw z("operation aborted",e,"OAUTH_ABORT")}throw new lr("something went wrong",{cause:e})}function qo(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Wo(e){Object.defineProperties(e,qo(e))}var Go=Symbol(),mt=class{constructor(e,t,r,n){if(typeof t!="string"||!t.length)throw ce('"clientId" must be a non-empty string',yt);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&t!==r.client_id)throw ce('"clientId" and "metadata.client_id" must be the same',qe);const s={...structuredClone(r),client_id:t};s[nt]=r?.[nt]??0,s[Gt]=r?.[Gt]??30;let i;n?i=n:typeof s.client_secret=="string"&&s.client_secret.length?i=Mo(s.client_secret):i=Mn();let o=Object.freeze(s);const a=structuredClone(e);Go in e&&(a[xn]=({claims:{tid:u}})=>e.issuer.replace("{tenantid}",u));let c=Object.freeze(a);cr||=new WeakMap,cr.set(this,{__proto__:null,as:c,c:o,auth:i,tlsOnly:!0,timeout:30,jwksCache:{}})}serverMetadata(){const e=structuredClone(H(this).as);return Wo(e),e}clientMetadata(){return structuredClone(H(this).c)}get timeout(){return H(this).timeout}set timeout(e){H(this).timeout=e}get[ur](){return H(this).fetch}set[ur](e){H(this).fetch=e}};Object.freeze(mt.prototype);function Jo(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 sr(e)}}}}function dr(e){Object.defineProperties(e,Jo(e))}async function $n(e,t,r,n=!1){const s=e.headers.get("retry-after")?.trim();if(s===void 0)return;let i;if(/^\d+$/.test(s))i=parseInt(s,10);else{const o=new Date(s);if(Number.isFinite(o.getTime())){const a=new Date,c=o.getTime()-a.getTime();c>0&&(i=Math.ceil(c/1e3))}}if(n&&!Number.isFinite(i))throw new Yt("invalid Retry-After header value",{cause:e});i>t&&await Fn(i-t,r)}function Fn(e,t){return new Promise((r,n)=>{const s=i=>{try{t.throwIfAborted()}catch(a){n(a);return}if(i<=0){r();return}const o=Math.min(i,5);setTimeout(()=>s(i-o),o*1e3)};s(e)})}function Ko(e,t){const r=Ne(t);if(!r)return{signal:e,cleanup(){}};const n=new AbortController,s=i=>{const o=i.target;n.abort(o.reason)};return e.aborted?n.abort(e.reason):r.aborted?n.abort(r.reason):(e.addEventListener("abort",s,{once:!0}),r.addEventListener("abort",s,{once:!0})),{signal:n.signal,cleanup(){e.removeEventListener("abort",s),r.removeEventListener("abort",s)}}}async function Zo(e,t,r,n,s,i,o){const a=new URLSearchParams(i);let c=t.interval??5;const u=o?.signal??AbortSignal.timeout(t.expires_in*1e3);for(;;){try{await Fn(c,u)}catch(g){W(g)}const{as:d,c:h,auth:f,fetch:y,tlsOnly:A,nonRepudiation:N,timeout:S,decrypt:D}=H(e),b=Ko(u,S);try{const g=await n(d,h,f,r,{[oe]:y,[X]:!A,additionalParameters:a,DPoP:o?.DPoP,headers:new Headers(ve),signal:b.signal}).catch(W);if(g.status===503&&g.headers.has("retry-after")){await g.body?.cancel(),await $n(g,c,u,!0),o={...o,flag:void 0};continue}let O;try{O=await s(d,h,g,{[ae]:D})}catch(k){if(We(k,o)){o={...o,flag:le};continue}if(k instanceof at&&(k.error==="slow_down"||k.error==="authorization_pending")){k.error==="slow_down"&&(c+=5),await $n(k.response,c,u),o={...o,flag:void 0};continue}W(k)}return O.id_token&&await N?.(g),dr(O),O}finally{b.cleanup()}}}async function Yo(e,t,r,n){return Ae(e),Zo(e,t,t.device_code,zo,jo,r,n)}async function Xo(e,t){Ae(e);const{as:r,c:n,auth:s,fetch:i,tlsOnly:o,timeout:a}=H(e);return Uo(r,n,s,t,{[oe]:i,[X]:!o,headers:new Headers(ve),signal:Ne(a)}).then(c=>xo(r,n,c)).catch(W)}function Qo(e){H(e).tlsOnly=!1}function ea(e){return e=new URL(e),e.search="",e.hash="",e.href}function ta(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Hn(e,t,r,n,s){if(Ae(e),s?.flag!==le&&!(t instanceof URL)&&!ta(t,"Request"))throw ce('"currentUrl" must be an instance of URL, or Request',yt);let i,o;const{as:a,c,auth:u,fetch:d,tlsOnly:h,jarm:f,hybrid:y,nonRepudiation:A,timeout:N,decrypt:S,implicit:D}=H(e);if(s?.flag===le)i=s.authResponse,o=s.redirectUri;else{if(!(t instanceof URL)){const k=t;switch(t=new URL(t.url),k.method){case"GET":break;case"POST":const Ee=new URLSearchParams(await ko(k));if(y)t.hash=Ee.toString();else for(const[gt,mr]of Ee.entries())t.searchParams.append(gt,mr);break;default:throw ce("unexpected Request HTTP method",qe)}}switch(o=ea(t),!0){case!!f:i=await f(t,r?.expectedState);break;case!!y:i=await y(t,r?.expectedNonce,r?.expectedState,r?.maxAge);break;case!!D:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=Lo(a,c,t.searchParams,r?.expectedState)}catch(k){W(k)}}}const b=await yo(a,c,u,i,o,r?.pkceCodeVerifier||Tn,{additionalParameters:n,[oe]:d,[X]:!h,DPoP:s?.DPoP,headers:new Headers(ve),signal:Ne(N)}).catch(W);(typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number")&&(r.idTokenExpected=!0);const g=Ao(a,c,b,{expectedNonce:r?.expectedNonce,maxAge:r?.maxAge,requireIdToken:r?.idTokenExpected,[ae]:S});let O;try{O=await g}catch(k){if(We(k,s))return Hn(e,void 0,r,n,{...s,flag:le,authResponse:i,redirectUri:o});W(k)}return O.id_token&&await A?.(b),dr(O),O}async function Vn(e,t,r,n){Ae(e),r=new URLSearchParams(r);const{as:s,c:i,auth:o,fetch:a,tlsOnly:c,nonRepudiation:u,timeout:d,decrypt:h}=H(e),f=await uo(s,i,o,t,{[oe]:a,[X]:!c,additionalParameters:r,DPoP:n?.DPoP,headers:new Headers(ve),signal:Ne(d)}).catch(W),y=lo(s,i,f,{[ae]:h});let A;try{A=await y}catch(N){if(We(N,n))return Vn(e,t,r,{...n,flag:le});W(N)}return A.id_token&&await u?.(f),dr(A),A}function hr(e,t){Ae(e);const{as:r,c:n,tlsOnly:s,hybrid:i,jarm:o,implicit:a}=H(e),c=Ve(r,"authorization_endpoint",!1,s);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",i?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw ce("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",qe);o&&t.set("response_mode","jwt")}for(const[u,d]of t.entries())c.searchParams.append(u,d);return c}async function Bn(e,t,r){Ae(e);const n=hr(e,t),{as:s,c:i,auth:o,fetch:a,tlsOnly:c,timeout:u}=H(e),d=await Yi(s,i,o,n.searchParams,{[oe]:a,[X]:!c,DPoP:r?.DPoP,headers:new Headers(ve),signal:Ne(u)}).catch(W),h=so(s,i,d);let f;try{f=await h}catch(y){if(We(y,r))return Bn(e,t,{...r,flag:le});W(y)}return hr(e,{request_uri:f.request_uri})}function Ae(e){if(!(e instanceof mt))throw ce('"config" must be an instance of Configuration',yt);if(Object.getPrototypeOf(e)!==mt.prototype)throw ce("subclassing Configuration is not allowed",qe)}function Ne(e){return e?AbortSignal.timeout(e*1e3):void 0}async function qn(e,t,r,n){Ae(e);const{as:s,c:i,fetch:o,tlsOnly:a,nonRepudiation:c,timeout:u,decrypt:d}=H(e),h=await ao(s,i,t,{[oe]:o,[X]:!a,DPoP:n?.DPoP,headers:new Headers(ve),signal:Ne(u)}).catch(W);let f=co(s,i,r,h,{[ae]:d}),y;try{y=await f}catch(A){if(We(A,n))return qn(e,t,r,{...n,flag:le});W(A)}return ct(h)==="application/jwt"&&await c?.(h),y}function We(e,t){return t?.DPoP&&t.flag!==le?Xi(e):!1}var le=Symbol(),ra={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",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","client_credentials"],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 Wn(e){return JSON.parse(JSON.stringify(ra).replaceAll("{issuer}",e))}var na=6e5,sa=2048,ia=["authorization_details","login_hint"],oa=class{#e;#t;#n;#r;#s;constructor(e){this.#e=e.config,this.#t=e.globals,this.#n=e.clientSecret??null,this.#r=e.transport??"auto"}get isConfidential(){return this.#n!==null}async createAuthorizationRequest(e={}){try{const t=this.#c(e.redirectTo),r=Vo(),n=await Ho(r),s=e.state??Bo(),i=this.#d(e,t,s,n),o=await this.#y(i);return l.ok({authorizationUrl:o,codeVerifier:r,state:s,redirectTo:t,createdAt:Date.now()})}catch(t){return l.fail(E.from(t,p.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>na)return l.fail(p.INVALID_CALLBACK,{message:"the authorization transaction expired"});if(ca(t,new URL(r.redirectTo))){if(t.searchParams.get("state")!==r.state)return l.fail(p.INVALID_CALLBACK,{message:"the callback state does not correlate"})}else return l.fail(p.INVALID_CALLBACK,{message:"the callback does not match redirectTo"});const n=t.searchParams.get("error");if(n)return l.fail(new E(n.slice(0,256),{message:t.searchParams.get("error_description")?.slice(0,2048)??n}));if(!t.searchParams.has("code"))return l.fail(p.INVALID_CALLBACK,{message:"the callback carries no authorization code"});const s=await Hn(this.#i(),t,{pkceCodeVerifier:r.codeVerifier,expectedState:r.state});return await this.#h(s)}catch(t){return l.fail(E.from(t,p.AUTHORIZATION_EXCHANGE_FAILED))}}async resolveAuthorizationUrl(e,t){try{return l.ok(await this.#y(e,t))}catch(r){return l.fail(E.from(r,p.AUTHORIZATION_REQUEST_FAILED))}}async refresh(e){try{const t=await Vn(this.#i(),e);return await this.#h(t)}catch(t){return l.fail(E.from(t,p.REFRESH_FAILED))}}async userInfo(e){try{const t=Rt(e)?.sub,r=await qn(this.#i(),e,typeof t=="string"?t:Fo);return l.ok({id:String(r.sub),name:typeof r.name=="string"?r.name:null,email:typeof r.email=="string"?r.email:null,avatarUrl:typeof r.picture=="string"?r.picture:null,emailVerified:typeof r.email_verified=="boolean"?r.email_verified:null,phone:typeof r.phone=="string"?r.phone:null,phoneVerified:typeof r.phone_verified=="boolean"?r.phone_verified:null})}catch(t){return l.fail(E.from(t,p.USERINFO_FAILED))}}async createDeviceAuthorizationRequest(e={}){try{const t=new URLSearchParams,r=this.#o(e);r.length&&t.set("scope",r.join(" ")),this.#u(t,e),console.debug("[AndcoOAuth.createDeviceAuthorizationRequest] scopes %s resources %o details %s",r.join(" "),t.getAll("resource"),t.has("authorization_details"));const n=await Xo(this.#i(),t);return l.ok({deviceCode:n.device_code,userCode:n.user_code,verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete??n.verification_uri,expiresIn:n.expires_in,interval:n.interval??5,raw:n})}catch(t){return l.fail(E.from(t,p.DEVICE_AUTHORIZATION_FAILED))}}async awaitDeviceAuthorization(e,t={}){try{const r=await Yo(this.#i(),e.raw,void 0,{signal:t.signal});return await this.#h(r)}catch(r){return l.fail(E.from(r,p.DEVICE_EXCHANGE_FAILED))}}configuration(){return this.#i()}#i(){return this.#s??=this.#a(),this.#s}#a(){const e=this.#e,t=e.endpoints.auth,r=`${t.origin}${t.pathname.replace(/\/+$/,"")}`,n=this.#n,s=new mt(Wn(r),e.clientId,n??void 0,n?$o(n):Mn());return s[ur]=((i,o)=>this.#t.fetch(i,o)),Qo(s),s}#c(e){const t=e??this.#e.redirectTo;if(!t)throw new E(p.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])]}#u(e,t){const r=new Set;for(const s of aa(t.resource))r.add(s);for(const s of t.authorizations??[])r.add(s.resource);for(const s of r)e.append("resource",s);const n=Ss([{authorizationDetails:t.authorizationDetails??[]},...t.authorizations??[]]);n.authorizationDetails.length&&e.set("authorization_details",JSON.stringify(n.authorizationDetails))}#d(e,t,r,n){const s=new URLSearchParams({client_id:this.#e.clientId,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"}),i=this.#o(e);return i.length&&s.set("scope",i.join(" ")),this.#u(s,e),e.externalId&&s.set("external_id",e.externalId),s}async#y(e,t){const r=this.#i(),n=hr(r,e),s=ia.some(o=>e.has(o)),i=t??this.#r;return(i==="auto"?s||n.href.length>sa?"par":"get":i)==="get"?n:await Bn(r,e)}async#h(e){if(e.token_type&&e.token_type.toLowerCase()!=="bearer")return l.fail(p.INVALID_TOKEN_RESPONSE,{message:"unsupported token type"});const t=Rt(e.access_token)?.sub,r=e.claims?.()?.sub??(typeof t=="string"?t:void 0);if(!r)return l.fail(p.INVALID_TOKEN_RESPONSE,{message:"the response carries no subject"});const n={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:r,name:null,email:null,avatarUrl:null,emailVerified:null,phone:null,phoneVerified:null}},s=await this.userInfo(n.accessToken);return l.ok(s.data?{...n,user:s.data}:n)}};function aa(e){return e===void 0?[]:typeof e=="string"?[e]:e}function ca(e,t){return e.origin!==t.origin||e.pathname!==t.pathname?!1:[...t.searchParams].every(([r,n])=>e.searchParams.getAll(r).includes(n))}var _t=class{static async present(e){if(e instanceof URL)return l.ok(e);try{return l.ok(await e())}catch(t){return l.fail(E.from(t,p.PRESENTATION_TARGET_FAILED))}}},ua=class{resource;resourceMetadata;#e;#t;constructor(e){this.resource=e.resource,this.resourceMetadata=e.resourceMetadata??da(e.resource),this.#e=e.tokens,this.#t=e.grants}metadata(e={}){return{resource:this.resource,authorization_servers:[this.#e.issuer],bearer_methods_supported:["header"],scopes_supported:e.scopesSupported}}protect(e={}){const t=r=>this.#n(r,e);return Object.assign(t,{hono:()=>async(r,n)=>{const s=await t(r.req.raw);if(s instanceof Response)return s;r.set("andcoGrant",s.data),await n()},express:()=>async(r,n,s)=>{const i=r.headers.authorization,o=new Headers;typeof i=="string"&&o.set("Authorization",i);const a=await t(new Request(this.resource,{headers:o}));if(a instanceof Response){n.status(a.status),a.headers.forEach((c,u)=>n.setHeader(u,c)),n.send(await a.text());return}n.locals.andcoGrant=a.data,s()}})}async#n(e,t){const r=/^Bearer ([^\s]+)$/i.exec(e.headers.get("Authorization")??"")?.[1];if(!r)return console.debug("[resource.protect] no bearer token for %s",this.resource),this.#r(401,"missing_token");if(t.verify){const a=await this.#e.verify(r,{audience:this.resource});if(a.error)return this.#r(401,"invalid_token",{description:a.error.message})}const{data:n,error:s}=await this.#t.get(r);if(s)return console.debug("[resource.protect] grant lookup failed status=%s code=%s",s.status,s.code),s.status===401||s.status===404?this.#r(401,"invalid_token"):this.#r(503,"temporarily_unavailable");if(!n.active)return this.#r(401,"invalid_token");if(n.resource!==this.resource)return console.debug("[resource.protect] grant resource %s is not %s",n.resource,this.resource),this.#r(403,"insufficient_authorization");const i=(t.scopes??[]).filter(a=>!n.scopes.includes(a));if(i.length)return console.debug("[resource.protect] grant lacks scopes %o",i),this.#r(403,"insufficient_scope",{scope:t.scopes.join(" ")});const o=(t.authorizationDetails??[]).find(a=>!la(n,a));return o?(console.debug("[resource.protect] grant lacks detail %o",o),this.#r(403,"insufficient_authorization",{detail:o})):l.ok(n)}#r(e,t,r={}){const n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store"});if(e===401){const s=[t==="missing_token"?null:`error="${t}"`,`resource_metadata="${this.resourceMetadata}"`];n.set("WWW-Authenticate",`Bearer ${s.filter(Boolean).join(", ")}`)}else e===403&&t==="insufficient_scope"&&n.set("WWW-Authenticate",`Bearer error="insufficient_scope", scope="${r.scope}", resource_metadata="${this.resourceMetadata}"`);return new Response(JSON.stringify({error:t,error_description:r.description,required:r.detail}),{status:e,headers:n})}};function la(e,t){return e.authorizationDetails.some(r=>{if(r.type!==t.type)return!1;const n=Array.isArray(r.actions)?r.actions:[];return(t.actions??[]).every(s=>n.includes(s))})}function da(e){const t=new URL(e),r=t.pathname.replace(/\/+$/,"");return new URL(`/.well-known/oauth-protected-resource${r}`,t.origin).href}var ha=class{#e=new Map;run(e,t){const r=this.#e.get(e);if(r)return console.debug("[AndcoInflight] sharing the running operation for %s",e),r;console.debug("[AndcoInflight] starting %s",e);const n=(async()=>t())();this.#e.set(e,n);const s=i=>{this.#e.get(e)===n&&this.#e.delete(e),console.debug("[AndcoInflight] %s %s",i,e)};return n.then(()=>s("settled"),()=>s("failed")),n}},fa=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)}},pa=class{getItem(e){return window.localStorage.getItem(e)}setItem(e,t){window.localStorage.setItem(e,t)}removeItem(e){window.localStorage.removeItem(e)}},Gn=class{#e;#t;#n;#r=new Set;#s;#i;#a;#c;constructor(e){this.#e=e,this.#t=e.storage??new fa,this.#n=e.inflight??new ha,this.#s=`andco.session.${e.config.clientId}`,this.#i=e.initialSession,this.#a=e.initialSession}getSnapshot(){return this.#a}getServerSnapshot(){return this.#i}subscribe(e){return this.#r.add(e),this.#u(),()=>{this.#r.delete(e)}}get ready(){return this.#u()}async accessTokenFor(e){await this.#u();const t=this.#a;if(!t)return null;if(!en(t))return Ht(t,e);const r=await this.#o(!1);return r.error?null:r.data?Ht(r.data,e):null}async refresh(){await this.#u();const e=await this.#o(!0);return e.error?l.fail(e.error):e.data?l.ok(e.data):l.fail(p.SESSION_MISSING)}async#o(e){return console.debug("[refresh] requested force=%s",e),this.#n.run(this.#s,async()=>{const t=await this.#y();if(!t)return l.ok(null);if(!e&&!en(t))return l.ok(t);if(!t.refreshToken)return l.fail(p.SESSION_MISSING);const r=await this.#e.oauth.refresh(t.refreshToken);return r.error?l.fail(r.error):(await this.#h(r.data),l.ok(r.data))})}async set(e){this.#c??=Promise.resolve(l.ok(void 0));try{return await this.#h(e),l.ok(void 0)}catch(t){return l.fail(E.from(t,p.STORAGE_FAILED))}}#u(){return this.#c??=this.#d(),this.#c}async#d(){try{const e=this.#e.source?await this.#e.source():null;if(e?.error)return this.#f(this.#a??null),l.fail(e.error);if(e?.data)return await this.#h(e.data),l.ok(void 0);if(this.#i!==void 0)return this.#f(this.#i),l.ok(void 0);const t=await this.#t.getItem(this.#s);return this.#f(t?Jn(t):null),l.ok(void 0)}catch(e){return this.#f(this.#a??null),l.fail(E.from(e,p.STORAGE_FAILED))}}async#y(){const e=this.#a??null;if(this.#e.persist===!1)return e;let t;try{const r=await this.#t.getItem(this.#s);t=r?Jn(r):null}catch(r){return console.warn("[AndcoSessionStore] could not read storage before refreshing: %o",r),e}return!t||e&&t.expiresAt<=e.expiresAt?e:(console.debug("[AndcoSessionStore] adopting a newer stored session expiring at %s",t.expiresAt),this.#f(t),t)}async#h(e){this.#e.persist!==!1&&(e?await this.#t.setItem(this.#s,JSON.stringify(e)):await this.#t.removeItem(this.#s)),this.#f(e)}#f(e){this.#a=e;for(const t of[...this.#r])t()}};function Jn(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 ya(){return new E(p.BROWSER_REQUIRED)}var Ge={RS256:{import:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},verify:{name:"RSASSA-PKCS1-v1_5"}},ES256:{import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}}},ma=1e4,_a=class{#e;#t;#n=new Map;#r=0;#s=null;constructor(e){this.#e=e.config,this.#t=e.globals}get issuer(){const e=this.#e.endpoints.auth;return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}async verify(e,t={}){const r=(n,s,i)=>(console.debug("[tokens.verify] rejected %s: %s",n,s),l.fail(new E(n,{message:s,cause:i})));try{const n=e.split("."),s=n.length===3?ga(n[0]):null;if(!s)return r("invalid_token","token is not a JWT");const i=s.alg;if(typeof s.alg!="string"||!Object.hasOwn(Ge,s.alg))return r("invalid_token",`unsupported signing algorithm ${String(s.alg)}`);const o=await this.#i(typeof s.kid=="string"?s.kid:void 0,i);if(!o)return r("invalid_token","no JWKS key matches the token kid");if(!await globalThis.crypto.subtle.verify(Ge[i].verify,o.key,Kn(n[2]),new TextEncoder().encode(`${n[0]}.${n[1]}`)))return r("invalid_token","signature does not verify");const a=Rt(e);if(!a)return r("invalid_token","payload is not a JSON object");const c=t.clockToleranceSeconds??30,u=Math.floor(Date.now()/1e3);if(typeof a.exp!="number")return r("invalid_token","exp claim is missing");if(a.exp+c<=u)return r("invalid_token","token is expired");if(typeof a.nbf=="number"&&a.nbf-c>u)return r("invalid_token","token is not yet valid");if(a.iss!==this.issuer)return r("invalid_token","issuer does not match the configured one");if(t.audience!==void 0){const d=a.aud;if(!(typeof d=="string"?[d]:Array.isArray(d)?d:[]).includes(t.audience))return r("invalid_token","audience does not match")}return console.debug("[tokens.verify] accepted sub=%s",a.sub),l.ok(a)}catch(n){return r("invalid_token","verification failed",n)}}async#i(e,t){const r=()=>e===void 0?this.#a():this.#n.get(e),n=r();return n||(Date.now()-this.#r<ma&&this.#r>0?null:(this.#s??=this.#c(t).finally(()=>{this.#s=null}),await this.#s,r()??null))}#a(){return this.#n.size===1?[...this.#n.values()][0]:void 0}async#c(e){this.#r=Date.now();const t=Wn(this.issuer).jwks_uri;console.debug("[tokens.refresh] fetching JWKS %s",t);const r=await this.#t.fetch(t,{headers:{Accept:"application/json"}});if(!r.ok)throw new E("jwks_unavailable",{message:`JWKS answered ${r.status}`});const n=await r.json(),s=new Map;for(const i of n.keys??[]){if(!i.kid||i.use&&i.use!=="sig")continue;const o=i.alg??(i.kty==="EC"?"ES256":"RS256");if(!Object.hasOwn(Ge,o))continue;const a=await globalThis.crypto.subtle.importKey("jwk",i,Ge[o].import,!1,["verify"]);s.set(i.kid,{key:a,algorithm:Ge[o].import})}this.#n.clear();for(const[i,o]of s)this.#n.set(i,o);console.debug("[tokens.refresh] cached kids %o for %s",[...s.keys()],e)}};function Kn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");return Uint8Array.from(atob(t),r=>r.charCodeAt(0))}function ga(e){try{const t=JSON.parse(new TextDecoder().decode(Kn(e)));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}var fr=class{config;clientSecret;globals;oauth;rest;intents;auth;session;tokens;grants;constructor(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,this.tokens=e.tokens,this.grants=e.grants}resource(e){return new ua({...e,tokens:this.tokens,grants:this.grants})}},wa=class os extends fr{isAuthed=!1;constructor(t){const r=mi.from(t),n=t.clientSecret??null,s=Ft(t.globals),i=new oa({config:r,globals:s,clientSecret:n,transport:t.transport}),o=new Gn({config:r,oauth:i,storage:t.storage,initialSession:t.initialSession,inflight:t.inflight,source:t.source,persist:t.persist}),a=t.presenter??new Zn,c=new Qr({config:r,oauth:i,store:o,presenter:a,persistTransaction:t.persistTransaction,globals:s}),u=new Bt({config:r,globals:s,credentials:o}),d=new cn({rest:u,config:r,presenter:a,globals:s}),h=new _a({config:r,globals:s}),f=new Ui({config:r,globals:s});super({config:r,clientSecret:n,globals:s,oauth:i,rest:u,intents:d,auth:c,session:o,tokens:h,grants:f})}with(t){return new va(this,os.resolveCredentials(t))}authorized(){return new Aa(this)}static resolveCredentials(t){return typeof t=="string"?{accessTokenFor:async()=>t}:gi(t)?t:_i(t)}},Zn=class extends _t{async present(){return l.fail(ya())}},va=class extends fr{credentials;isAuthed=!0;constructor(e,t){const r=new Bt({config:e.config,globals:e.globals,credentials:t}),n=new cn({rest:r,config:e.config,globals:e.globals}),s=new Gn({config:e.config,oauth:e.oauth,persist:!1}),i=new Qr({config:e.config,oauth:e.oauth,store:s,presenter:new Zn,globals:e.globals});super({config:e.config,clientSecret:e.clientSecret,globals:e.globals,oauth:e.oauth,rest:r,intents:n,auth:i,session:s,tokens:e.tokens,grants:e.grants}),this.credentials=t}accessTokenFor(e){return this.credentials.accessTokenFor(e)}},Aa=class extends fr{owner;isAuthed=!0;constructor(e){super({config:e.config,clientSecret:e.clientSecret,globals:e.globals,oauth:e.oauth,rest:e.rest,intents:e.intents,auth:e.auth,session:e.session,tokens:e.tokens,grants:e.grants}),this.owner=e}accessTokenFor(e){return this.owner.session.accessTokenFor(e)}},ba=/^[A-Za-z0-9_-]{8,128}$/,Ea=6e5,Ia=400;function Ta(){return typeof window<"u"&&window.__ANDCO_NATIVE_HOST__===!0&&typeof window.ReactNativeWebView?.postMessage=="function"}function Yn(){if(typeof window>"u"||!window.opener||window.opener===window||!window.name.startsWith("andco-popup-"))return null;const e=window.name.slice(Xr.length);return ba.test(e)?e:null}function Sa(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=Yn();if(!n)return{status:"not_popup"};const s=r.searchParams.get("state"),i=(s?Nt(s)?.openerOrigin:null)??window.location.origin;if(i!==window.location.origin&&!e.has(i))return{status:"rejected",error:new E(p.UNTRUSTED_ORIGIN)};const o=i===window.location.origin?Ra(n,r):Oa(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,i),window.close(),{status:"relayed",presentationId:n}}function Ra(e,t){return{protocol:"andco",version:1,presentationId:e,callbackUrl:t.href}}function Oa(e,t){const r={protocol:Oe,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 s=t.searchParams.get("code");if(s)return{...r,type:"oauth.authorization_code",authorizationCode:s};const i=t.searchParams.get("error")??"invalid_request";if(i==="access_denied")return{...r,type:"oauth.dismiss"};const o=t.searchParams.get("error_description");return{...r,type:"oauth.error",error:{code:i.slice(0,256),description:o?o.slice(0,2048):void 0}}}function Na(e){const t=`${Xr}${e.presentationId}`,r=e.url?.href??"about:blank";console.debug("[openAndcoPopupWindow] opening %s %s",e.target??"popup",t);const n=e.target==="newtab"?window.open(r,t):window.open(r,t,Pa({width:620,height:720}));return n?{blocked:!1,navigate:s=>n.location.assign(s.href),result:new Promise(s=>{let i=!1;const o=h=>{i||(i=!0,window.removeEventListener("message",a),window.clearInterval(c),window.clearTimeout(u),s(h))},a=h=>{if(h.origin!==e.expectedOrigin||h.source!==n)return;const f=h.data;if(!(!f||f.protocol!=="andco"||f.presentationId!==e.presentationId)&&typeof f.callbackUrl=="string"){n.close();try{o(l.ok(new URL(f.callbackUrl)))}catch{o(l.fail(p.INVALID_CALLBACK))}}};window.addEventListener("message",a);const c=window.setInterval(()=>{n.closed&&o(l.ok(null))},Ia),u=window.setTimeout(()=>{n.close(),o(l.fail(p.POPUP_TIMEOUT))},Ea),d=()=>{n.close(),o(l.ok(null))};e.signal?.aborted?d():e.signal?.addEventListener("abort",d,{once:!0})}),focus:()=>n.focus(),close:()=>n.close()}:{blocked:!0,navigate:()=>{},result:Promise.resolve(l.fail(p.POPUP_BLOCKED)),focus:()=>{},close:()=>{}}}function Pa(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 ka=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 E(p.BROWSER_UNAVAILABLE);if(!(e instanceof HTMLIFrameElement))throw new E(p.INVALID_IFRAME,{details:{iframe:e}});if(this.url=new URL(t.endpointButton),this.url.origin===window.location.origin)throw new E(p.SAME_ORIGIN_ENDPOINT,{details:{endpointButton:this.url.href}});console.debug("[AndcoButtonBridge] created: %s",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(di(e))switch(e.type){case"ready":if(this.settled)return;this.settled=!0,this.stopHandshake(),console.debug("[AndcoButtonBridge] handshake settled: attempts=%d transport=%s elapsedMs=%d",this.handshakeAttempts,this.transport,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:Oe,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,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: attempts=%d endpointButton=%s",this.handshakeAttempts,this.url.href);const e={protocol:Oe,version:2,type:"error",error:{code:p.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:Oe,version:2,type:"presentation-response",presentationId:e,url:t?.toString()};this.post(r)}forwardAuthorizationResult(e){this.post(e)}setPreferences(e){const t={protocol:Oe,version:2,type:"set-preferences",...e};this.post(t)}destroy(){this.destroyed||(console.debug("[AndcoButtonBridge] destroyed: settled=%s attempts=%d",this.settled,this.handshakeAttempts),this.destroyed=!0,window.removeEventListener("message",this.receiveWindow),this.iframe.removeEventListener("load",this.startHandshake),this.stopHandshake(),this.closePort())}},Ca="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox",Da="no-referrer",Xn={border:"0",display:"block"},Qn={height:"3rem",width:"18rem"},La={...Xn,...Qn};function Ua(e){return Object.entries(e).map(([t,r])=>`${t}:${r}`).join(";")}var de=class{static IFRAME_SANDBOX=Ca;static IFRAME_REFERRER_POLICY=Da;static IFRAME_BASE_STYLE=Xn;static DEFAULT_SIZE=Qn;static IFRAME_DEFAULT_STYLE=La;static frameStyleText=Ua;static frameProps(e){return{src:e.iframeURL,hidden:!e.ready}}#e;#t=new Set;#n;#r;#s;#i;#a;#c;#o=0;#u=!1;constructor(e){this.#e=e,this.#s={status:"idle",iframeURL:this.#m(),ready:!1,error:null}}get snapshot(){return this.#s}subscribe(e){return this.#t.add(e),e(this.#s),()=>{this.#t.delete(e)}}connect(e){this.disconnect(),this.#r=e,console.debug("[AndcoButtonController] connecting: %s",this.#s.iframeURL),this.#p({status:"connecting",ready:!1,error:null});try{this.#n=new ka(e,{endpointButton:this.#m(),onReady:t=>{this.#p({status:"ready",ready:!0}),this.#e.onReady?.(t)},onActivate:t=>{this.#a=t.presentationId,this.#e.onActivate?.(t),this.#d()},onComplete:t=>{this.#f(t)},onDismiss:()=>{this.#p({status:"dismissed"}),this.#e.onDismiss?.()},onAuthorizationError:t=>this.#l(new E(t.error.code,{message:t.error.description})),onError:t=>{if(t.error.code===p.HANDSHAKE_TIMEOUT&&!this.#u&&this.#r){this.#u=!0,console.debug("[AndcoButtonController] handshake timed out; reconnecting once"),this.connect(this.#r);return}this.#l(new E(t.error.code),t)}})}catch(t){this.#l(E.from(t,p.INVALID_IFRAME))}return()=>this.disconnect()}disconnect(){this.#n?.destroy(),this.#n=void 0}restart(){if(this.#o+=1,this.#i=void 0,this.#c=void 0,this.#s.status==="error"&&this.#r){this.#u=!1,console.debug("[AndcoButtonController] restarting after an error, reconnecting: %O",this.#s.error),this.connect(this.#r);return}this.#p({status:this.#n?"ready":"idle",error:null})}destroy(){this.disconnect(),this.#r=void 0,this.#t.clear()}async#d(){const e=++this.#o;this.#p({status:"authorizing",error:null});const t=this.#a,r=Ot(this.#e.client.config.endpoints.widget.origin,t);if(this.#e.flow==="intent")return this.#h(e,t,r);if(this.#e.presentation==="redirect")return this.#y(e,t);const n=await this.#e.client.oauth.createAuthorizationRequest({...this.#e.authorization??{},state:r});if(e===this.#o){if(n.error)return this.#l(n.error);this.#i=n.data,this.#n?.resolvePresentation(t,n.data.authorizationUrl.href)}}async#y(e,t){console.debug("[AndcoButtonController] presenting by redirect: presentationId=%s",t);const r=await this.#e.client.auth.signIn({...this.#e.authorization??{},presentation:"redirect"});if(e===this.#o&&r.error)return this.#n?.resolvePresentation(t),this.#l(r.error)}async#h(e,t,r){const n=this.#e.client,s=this.#e.intentId;if(!s)return this.#l(new E(p.INVALID_CONFIGURATION,{message:'a control with flow="intent" requires an intentId'}));if(this.#e.presentation==="redirect")return this.#l(new E(p.PRESENTATION_UNSUPPORTED,{message:'an Intent cannot be presented with presentation="redirect" yet'}));const i=n.config.redirectTo;if(!i)return this.#l(new E(p.INVALID_CONFIGURATION,{message:"an Intent Presentation needs the instance's redirectTo"}));let o;try{o=typeof s=="string"?s:await s()}catch(c){return this.#l(E.from(c,p.INVALID_CONFIGURATION))}if(e!==this.#o)return;const a=await n.intents.presentationURLFor(o,{presentation:"popup",returnTo:i,errorReturnTo:i,state:r});if(e===this.#o){if(a.error)return this.#l(a.error);this.#c=o,this.#n?.resolvePresentation(t,a.data.href)}}async#f(e){const t=this.#o,r=this.#i;if(this.#i=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 s=await this.#e.client.oauth.exchangeCallback({callbackUrl:n,request:r});if(t!==this.#o)return;if(s.error)return this.#l(s.error);const i=await this.#e.client.session.set(s.data);if(i.error)return this.#l(i.error)}if(t===this.#o){if(e.type==="intent.complete"&&this.#c){const n=await this.#e.client.intents.get(this.#c);if(t!==this.#o)return;if(n.error)return this.#l(n.error);this.#p({status:"complete",error:null}),this.#e.onComplete?.({outcome:"complete",intent:n.data});return}this.#p({status:"complete",error:null}),this.#e.onComplete?.()}}#l(e,t){console.error("[AndcoButtonController] %O",e),this.#p({status:"error",error:e}),this.#e.onError?.(e,t)}#m(){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}#p(e){this.#s={...this.#s,...e,iframeURL:this.#m()};for(const t of[...this.#t])t(this.#s)}},xa=class extends _t{#e=new Map;focus(e){console.debug("[AndcoPresenterBrowser.focus] %s open=%s",e,this.#e.has(e)),this.#e.get(e)?.focus()}async present(e){if(typeof window>"u")return l.fail(p.BROWSER_REQUIRED);if(e.presentation==="redirect"){const r=await _t.present(e.url);return r.error?(console.error("[AndcoPresenterBrowser] for options %O got error: %O",e,r.error),l.fail(r.error)):(console.debug("[AndcoPresenterBrowser] will window location assign: %s",r.data.href),window.location.assign(r.data.href),l.ok(null))}if(Ta()&&window.__ANDCO_NATIVE_POPUP_HANDLER__!==!0)return l.fail(p.PRESENTATION_UNSUPPORTED,{message:"the native Host cannot present a popup without navigating the Miniapp"});const t=Na({presentationId:e.presentationId,expectedOrigin:e.returnTo.origin,signal:e.signal,target:e.kind==="intent"&&e.presentation==="newtab"?"newtab":"popup"});if(t.blocked)return l.fail(p.POPUP_BLOCKED);this.#e.set(e.presentationId,t);try{const r=await _t.present(e.url);return r.error?(t.close(),l.fail(r.error)):(t.navigate(r.data),await t.result)}finally{this.#e.delete(e.presentationId)}}},pr="andco.transaction";function za(e){const t=e.presenter??new xa,r=e.storage??(typeof window>"u"?void 0:new pa),n=new wa({...e,presenter:t,storage:r,source:()=>ja(n.config,n.oauth,e),persistTransaction:s=>Ma(n.config.clientId,s,e.transactionStorage)});return e.relayPopupCallback!==!1&&typeof window<"u"&&Sa(n.config.allowedPopupOrigins),n}async function ja(e,t,r){if(r.detectSessionInUrl===!1||typeof window>"u"||Yn())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 s=r.transactionStorage??window.sessionStorage,i=s.getItem(`${pr}.${e.clientId}`);if(!i)return l.ok(null);s.removeItem(`${pr}.${e.clientId}`);let o;try{const c=JSON.parse(i);o={...c,authorizationUrl:new URL(c.authorizationUrl)}}catch{return l.fail(p.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 Ma(e,t,r){(r??window.sessionStorage).setItem(`${pr}.${e}`,JSON.stringify({...t,authorizationUrl:t.authorizationUrl.href}))}var yr=new Map;function es(e){const t=JSON.stringify(e,Object.keys(e).sort()),r=yr.get(t);if(r)return r;const n=za(e);return yr.set(t,n),n}function $a(){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; ${de.frameStyleText(de.DEFAULT_SIZE)} } }`,document.head.append(t)}var Fa=["client-id","endpoint-auth","endpoint-api","endpoint-widget","redirect-to","locale","theme-mode","scopes","flow","presentation","disabled","busy"],ts=class extends HTMLElement{static observedAttributes=Fa;#e;#t;#n;#r;authorizations;intentId;connectedCallback(){$a(),this.#i()}disconnectedCallback(){this.#s()}attributeChangedCallback(){this.isConnected&&this.#i()}#s(){this.#t?.(),this.#n?.(),this.#e?.destroy(),this.#t=void 0,this.#n=void 0,this.#e=void 0}#i(){this.#s();const e=this.getAttribute("client-id");if(!e)return;const t=es({clientId:e,...be("endpointAuth",this.getAttribute("endpoint-auth")),...be("endpointApi",this.getAttribute("endpoint-api")),...be("endpointWidget",this.getAttribute("endpoint-widget")),...be("redirectTo",this.getAttribute("redirect-to")),...be("locale",this.getAttribute("locale")),initialScopes:this.getAttribute("scopes")?.split(/\s+/).filter(Boolean)}),r=this.getAttribute("scopes")?.split(/\s+/).filter(Boolean);this.#e=new de({client:t,flow:this.getAttribute("flow")??void 0,presentation:this.getAttribute("presentation")??void 0,intentId:this.intentId,...be("themeMode",this.getAttribute("theme-mode")),...be("locale",this.getAttribute("locale")),disabled:this.hasAttribute("disabled"),busy:this.hasAttribute("busy"),authorization:{scopes:r,authorizations:this.authorizations},onReady:()=>this.dispatchEvent(new CustomEvent("andco-ready")),onActivate:()=>this.dispatchEvent(new CustomEvent("andco-activate")),onComplete:s=>this.dispatchEvent(new CustomEvent("andco-complete",{detail:s})),onDismiss:()=>this.dispatchEvent(new CustomEvent("andco-dismiss")),onError:s=>this.dispatchEvent(new CustomEvent("andco-error",{detail:s}))});const n=this.#r??document.createElement("iframe");this.#r=n,n.referrerPolicy=de.IFRAME_REFERRER_POLICY,n.setAttribute("sandbox",de.IFRAME_SANDBOX),n.title=this.getAttribute("title")??"Andco",n.style.cssText=de.frameStyleText({...de.IFRAME_BASE_STYLE,height:"100%",width:"100%"}),n.isConnected||this.append(n),this.#n=this.#e.subscribe(s=>{const i=de.frameProps(s);n.src!==i.src&&(n.src=i.src),n.hidden=i.hidden}),this.#t=this.#e.connect(n)}};function Ha(e){const t=e.getAttribute("client-id");for(const[r,n]of yr)if(t&&r.includes(`"${t}"`))return n.session.getSnapshot()}function Va(e){return es(e)}function be(e,t){return t?{[e]:t}:{}}return typeof customElements<"u"&&!customElements.get("andco-button")&&customElements.define("andco-button",ts),Pe.AndcoButtonElement=ts,Pe.andcoInstance=Va,Pe.andcoSessionFor=Ha,Pe})({});
2
2
 
3
3
  //# sourceMappingURL=andco.js.map
package/dist/index.d.ts CHANGED
@@ -9,11 +9,12 @@ import type { AndcoClient, AndcoIntentId, AndcoSession } from "@andco/sdk";
9
9
  * @example
10
10
  * ```html
11
11
  * <andco-button client-id="…" redirect-to="…" scopes="openid email profile"></andco-button>
12
+ * <andco-button client-id="…" redirect-to="…" scopes="openid" presentation="redirect"></andco-button>
12
13
  * ```
13
14
  */
14
15
  export declare class AndcoButtonElement extends HTMLElement {
15
16
  #private;
16
- static readonly observedAttributes: readonly ["client-id", "endpoint-auth", "endpoint-api", "endpoint-widget", "redirect-to", "locale", "theme-mode", "scopes", "flow", "disabled", "busy"];
17
+ static readonly observedAttributes: readonly ["client-id", "endpoint-auth", "endpoint-api", "endpoint-widget", "redirect-to", "locale", "theme-mode", "scopes", "flow", "presentation", "disabled", "busy"];
17
18
  /** Resource Server contributions. An object, so it arrives as a property rather than an attribute. */
18
19
  authorizations: unknown[] | undefined;
19
20
  /**
package/dist/index.js CHANGED
@@ -17,11 +17,15 @@ function instanceFor(options) {
17
17
  return created;
18
18
  }
19
19
  /**
20
- * Default box for the element.
20
+ * Default box for the custom element itself.
21
21
  *
22
22
  * A bare iframe is 300x150 with a border and the hosted control fills whatever box it is given, so
23
23
  * without this a plain page sees a bordered grey slab. It is a cascade layer because unlayered
24
24
  * author CSS beats a layer whatever the order, so a page that styles `andco-button` still wins.
25
+ *
26
+ * Uses {@link AndcoButtonController.DEFAULT_SIZE} so the visible default stays the same size as the
27
+ * other bindings, even though the size lives on this custom element rather than on the iframe it
28
+ * contains — see the iframe's own style in {@link AndcoButtonElement.#build}.
25
29
  */
26
30
  function installDefaultStyle() {
27
31
  const id = "andco-button-default-style";
@@ -29,7 +33,8 @@ function installDefaultStyle() {
29
33
  return;
30
34
  const style = document.createElement("style");
31
35
  style.id = id;
32
- style.textContent = "@layer andco { andco-button { display: block; height: 3rem; width: 18rem } }";
36
+ const size = AndcoButtonController.frameStyleText(AndcoButtonController.DEFAULT_SIZE);
37
+ style.textContent = `@layer andco { andco-button { display: block; ${size} } }`;
33
38
  document.head.append(style);
34
39
  }
35
40
  const SCALAR_ATTRIBUTES = [
@@ -42,6 +47,7 @@ const SCALAR_ATTRIBUTES = [
42
47
  "theme-mode",
43
48
  "scopes",
44
49
  "flow",
50
+ "presentation",
45
51
  "disabled",
46
52
  "busy",
47
53
  ];
@@ -55,6 +61,7 @@ const SCALAR_ATTRIBUTES = [
55
61
  * @example
56
62
  * ```html
57
63
  * <andco-button client-id="…" redirect-to="…" scopes="openid email profile"></andco-button>
64
+ * <andco-button client-id="…" redirect-to="…" scopes="openid" presentation="redirect"></andco-button>
58
65
  * ```
59
66
  */
60
67
  export class AndcoButtonElement extends HTMLElement {
@@ -109,13 +116,14 @@ export class AndcoButtonElement extends HTMLElement {
109
116
  this.#controller = new AndcoButtonController({
110
117
  client,
111
118
  flow: this.getAttribute("flow") ?? undefined,
119
+ presentation: this.getAttribute("presentation") ?? undefined,
112
120
  intentId: this.intentId,
113
121
  ...optional("themeMode", this.getAttribute("theme-mode")),
114
122
  ...optional("locale", this.getAttribute("locale")),
115
123
  disabled: this.hasAttribute("disabled"),
116
124
  busy: this.hasAttribute("busy"),
117
125
  authorization: {
118
- ...(scopes?.length ? { scopes } : {}),
126
+ scopes,
119
127
  authorizations: this.authorizations,
120
128
  },
121
129
  // Namespaced because a custom element dispatching a bare `error` shadows the platform's own
@@ -128,16 +136,23 @@ export class AndcoButtonElement extends HTMLElement {
128
136
  });
129
137
  const iframe = this.#iframe ?? document.createElement("iframe");
130
138
  this.#iframe = iframe;
131
- iframe.referrerPolicy = "no-referrer";
132
- iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox");
139
+ iframe.referrerPolicy = AndcoButtonController.IFRAME_REFERRER_POLICY;
140
+ iframe.setAttribute("sandbox", AndcoButtonController.IFRAME_SANDBOX);
133
141
  iframe.title = this.getAttribute("title") ?? "Andco";
134
- iframe.style.cssText = "border:0;display:block;height:100%;width:100%";
142
+ // The custom element sizes itself (see `installDefaultStyle`); this iframe just fills it, which
143
+ // is why it takes the shared base style but not the shared default size.
144
+ iframe.style.cssText = AndcoButtonController.frameStyleText({
145
+ ...AndcoButtonController.IFRAME_BASE_STYLE,
146
+ height: "100%",
147
+ width: "100%",
148
+ });
135
149
  if (!iframe.isConnected)
136
150
  this.append(iframe);
137
151
  this.#unsubscribe = this.#controller.subscribe((snapshot) => {
138
- if (iframe.src !== snapshot.iframeURL)
139
- iframe.src = snapshot.iframeURL;
140
- iframe.hidden = !snapshot.ready;
152
+ const frame = AndcoButtonController.frameProps(snapshot);
153
+ if (iframe.src !== frame.src)
154
+ iframe.src = frame.src;
155
+ iframe.hidden = frame.hidden;
141
156
  });
142
157
  this.#disconnect = this.#controller.connect(iframe);
143
158
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andco/sdk-script",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
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.3"
25
+ "@andco/sdk": "0.0.4"
26
26
  },
27
27
  "devDependencies": {
28
28
  "typescript": "^6.0.3",
@@ -30,6 +30,16 @@
30
30
  },
31
31
  "license": "Apache-2.0",
32
32
  "description": "Standalone browser bundle of the Andco SDK, for loading with a <script> tag.",
33
+ "author": "Patricio Lopez Juri <patricio.lopez@haulmer.com>",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/haulmer/andco-sdk-js.git",
37
+ "directory": "packages/sdk-script"
38
+ },
39
+ "homepage": "https://github.com/haulmer/andco-sdk-js#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/haulmer/andco-sdk-js/issues"
42
+ },
33
43
  "scripts": {
34
44
  "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
35
45
  "build": "pnpm run clean && tsc && vite build",