@descope/web-js-sdk 0.1.0-alpha.3 → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldSet as t,__classPrivateFieldGet as e,__rest as s}from"tslib";import n from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import r from"js-cookie";const i=t=>new Proxy(new URLSearchParams(window.location.search),{get:(t,e)=>t.get(e.toString())})[t],o=t=>{const e=a({apiKey:t||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let t=sessionStorage.getItem("vsid");t||(t=i("vsid")),t||(t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",t);const s=await e,n=await s.get({linkedId:t});sessionStorage.setItem("vrid",n.requestId)}catch(t){global.FB_DEBUG&&console.error(t)}}}};var c,u,l,g,f;const p=t=>"string"==typeof t?t:Object.assign({},t);class h{constructor(e){c.add(this),u.set(this,void 0),l.set(this,{}),g.set(this,0),t(this,u,e,"f")}get current(){return p(e(this,u,"f"))}update(s){let n=s;if("object"==typeof s&&"object"==typeof e(this,u,"f")&&(n=Object.assign(Object.assign({},e(this,u,"f")),s)),!((t,e)=>{if("string"==typeof t)return t===e;const s=t&&Object.getOwnPropertyNames(t)||[],n=e&&Object.getOwnPropertyNames(e)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(t[a]!==e[a])return!1}return!0})(e(this,u,"f"),n)){const s=e(this,u,"f");t(this,u,n,"f"),Object.freeze(e(this,u,"f")),setTimeout((()=>{Object.values(e(this,l,"f")).forEach((t=>t(p(n),s)))}),0)}}subscribe(s){var n;t(this,g,e(this,g,"f")+1,"f"),e(this,l,"f")[e(this,g,"f")]=s,((n=e(this,u,"f"))&&"string"!=typeof n?0===Object.entries(n).length:!n)||s(p(e(this,u,"f")));const a=e(this,g,"f");return()=>e(this,c,"m",f).call(this,a.toString())}unsubscribeAll(){t(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,g=new WeakMap,c=new WeakSet,f=function(t){!!e(this,l,"f")[t]&&delete e(this,l,"f")[t]};let d=[];function b(t,e,s){const n=function(t){const e=t.split(".");try{if(3===e.length){const e=JSON.parse(window.atob(t.split(".")[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(t){}return null}(e);if(n){let e;for(;e=d.pop();)clearTimeout(e);const a=n.getTime()-2e4-(new Date).getTime(),r=setTimeout((()=>{t(s)}),a);d.push(r)}}function w(t,e,s){!function(t,{cookiePath:e,cookieDomain:s,cookieExpiration:n}){t&&r.set("DS",t,{path:e,domain:s,expires:n,sameSite:"None",secure:!0})}(t,s),function(t){localStorage&&t&&localStorage.setItem("DSR",t)}(e)}function m(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function S(t){const e=function(t){var e;const s=JSON.parse(t);return s.publicKey.challenge=v(s.publicKey.challenge),s.publicKey.user.id=v(s.publicKey.user.id),null===(e=s.publicKey.excludeCredentials)||void 0===e||e.forEach((t=>{t.id=v(t.id)})),s}(t),s=await navigator.credentials.create(e);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:O(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:O(n.response.attestationObject),clientDataJSON:O(n.response.clientDataJSON)})}));var n}async function y(t){const e=function(t){var e;const s=JSON.parse(t);return s.publicKey.challenge=v(s.publicKey.challenge),null===(e=s.publicKey.allowCredentials)||void 0===e||e.forEach((t=>{t.id=v(t.id)})),s}(t),s=await navigator.credentials.get(e);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:O(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:O(n.response.authenticatorData),clientDataJSON:O(n.response.clientDataJSON),signature:O(n.response.signature),userHandle:n.response.userHandle?O(n.response.userHandle):void 0})}));var n}function v(t){const e=t.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(e),(t=>t.charCodeAt(0))).buffer}function O(t){return btoa(String.fromCharCode.apply(null,new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var j=t=>{var{autoRefresh:e=!0,persistTokens:a=!0}=t,i=s(t,["autoRefresh","persistTokens"]);o(i.fpKey).get().catch((()=>null));const c=i;let u,l;const g=new h(""),f=new h({});c.hooks={beforeRequest:t=>null==u?void 0:u(t),afterRequest:(t,e)=>null==l?void 0:l(t,e)};const p=n(c),d=Object.assign(Object.assign({},p),{webauthn:(v=p,{async signUp(t,e){const s=await v.webauthn.signUp.start(t,window.location.origin,e),n=await S(s.data.options);return await v.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(t){const e=await v.webauthn.signIn.start(t,window.location.origin),s=await y(e.data.options);return await v.webauthn.signIn.finish(e.data.transactionId,s)},async update(t,e){const s=await v.webauthn.update.start(t,window.location.origin,e),n=await S(s.data.options);return await v.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:S,get:y}}),onSessionTokenChange:g.subscribe,onUserChange:f.subscribe});var v;return e&&(d.logout=(...t)=>{const e=m(),s=[(null==t?void 0:t.shift())||e,...t],n=p.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.remove("DS"),n}),u=t=>{var e;return t.queryParams=(e=t.queryParams,Object.assign(Object.assign({},e),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!t.token&&a&&(t.token=m()),t},(e||a)&&(l=(t,n)=>{!async function(t,e,n,a){try{const r=await(null==e?void 0:e.json());if(r){const e=function(t){return(null==t?void 0:t.authInfo)||t||{}}(r),{sessionJwt:i,refreshJwt:o,user:c}=e,u=s(e,["sessionJwt","refreshJwt","user"]);a.persistTokens&&w(i,o,u),n.sessionToken.update(i),n.user.update(c),i&&o&&a.autoRefresh&&b(t,i,o)}}catch(t){console.error("Could not set tokens from body",t)}}(d.refresh,n,{sessionToken:g,user:f},{autoRefresh:e,persistTokens:a})}),e&&d.refresh(),d};export{j as default};
1
+ import{__rest as t}from"tslib";import e,{wrapWith as n}from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import i from"js-cookie";const o=(t,e)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,a)=>{var i;return n[a]=[].concat((null===(i=t.hooks)||void 0===i?void 0:i[a])||[]).concat((null==e?void 0:e[a])||[]),n}),null!==(n=t.hooks)&&void 0!==n?n:t.hooks={}),t},s=async t=>{if(!(null==t?void 0:t.ok))return{};const e=await(null==t?void 0:t.clone().json());return(null==e?void 0:e.authInfo)||e||{}},r=async t=>{const e=await s(t);return(null==e?void 0:e.user)||((null==e?void 0:e.hasOwnProperty("userId"))?e:void 0)},l="undefined"!=typeof localStorage,c=(t,e)=>l&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(t,e)),u=t=>l&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(t)),d=t=>l&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(t)),g="undefined"!=typeof window,p=g&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",w=(t="",e="")=>({vsid:t,vrid:e}),f=(t=!1)=>{const e=localStorage.getItem("fp");if(!e)return null;const n=JSON.parse(e);return(new Date).getTime()>n.expiry&&!t?null:n.value},b=async t=>{try{if(f())return;const e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=a({apiKey:t,endpoint:p}),i=await n,{requestId:o}=await i.get({linkedId:e});(t=>{const e={value:t,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(e))})(w(e,o))}catch(t){global.FB_DEBUG&&console.error(t)}},h=t=>(t.body&&(t.body.fpData=f(!0)||w()),t),v=()=>u("dls_last_user_login_id"),y=()=>u("dls_last_user_display_name"),m=t=>async(...e)=>{var n;e[1]=e[1]||{};const[,a={}]=e,i=v(),o=y();i&&(null!==(n=a.lastAuth)&&void 0!==n||(a.lastAuth={}),a.lastAuth.loginId=i,a.lastAuth.name=o);return await t(...e)},S=t=>async(...e)=>{const n=await t(...e);return d("dls_last_user_login_id"),d("dls_last_user_display_name"),n};function O(){const t=[];return{pub:e=>{t.forEach((t=>t(e)))},sub:e=>{const n=t.push(e)-1;return()=>t.splice(n,1)}}}const I=(e={},n)=>{var{refreshJwt:a,sessionJwt:o}=e,s=t(e,["refreshJwt","sessionJwt"]);void 0===n&&(n=!1),a&&c("DSR",a),o&&(n?function(t,e,{cookiePath:n,cookieDomain:a,cookieExpiration:o}){if(e){const s=new Date(1e3*o);i.set(t,e,{path:n,domain:a,expires:s,sameSite:"None",secure:!0})}}("DS",o,s):c("DS",o))};function k(){return u("DSR")||""}function _(){return i.get("DS")||u("DS")||""}function j(){d("DSR"),d("DS"),i.remove("DS")}const D=t=>Object.assign(t,{token:t.token||k()}),U=t=>async(...e)=>{const n=await t(...e);return j(),n};async function A(t){const e=function(t){var e;const n=JSON.parse(t);return n.publicKey.challenge=C(n.publicKey.challenge),n.publicKey.user.id=C(n.publicKey.user.id),null===(e=n.publicKey.excludeCredentials)||void 0===e||e.forEach((t=>{t.id=C(t.id)})),n}(t),n=await navigator.credentials.create(e);return a=n,JSON.stringify({id:a.id,rawId:x(a.rawId),type:a.type,response:{attestationObject:x(a.response.attestationObject),clientDataJSON:x(a.response.clientDataJSON)}});var a}async function J(t){const e=N(t);return R(await navigator.credentials.get(e))}async function T(t,e){const n=N(t);n.signal=e.signal,n.mediation="conditional";return R(await navigator.credentials.get(n))}async function K(t=!1){if(!g)return Promise.resolve(!1);const e=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return e&&t&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():e}function N(t){var e;const n=JSON.parse(t);return n.publicKey.challenge=C(n.publicKey.challenge),null===(e=n.publicKey.allowCredentials)||void 0===e||e.forEach((t=>{t.id=C(t.id)})),n}function R(t){return JSON.stringify({id:t.id,rawId:x(t.rawId),type:t.type,response:{authenticatorData:x(t.response.authenticatorData),clientDataJSON:x(t.response.clientDataJSON),signature:x(t.response.signature),userHandle:t.response.userHandle?x(t.response.userHandle):void 0}})}function C(t){const e=t.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(e),(t=>t.charCodeAt(0))).buffer}function x(t){return btoa(String.fromCharCode.apply(null,new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var q,P=(q=t=>({async signUp(e,n){const a=await t.webauthn.signUp.start(e,window.location.origin,n);if(!a.ok)return a;const i=await A(a.data.options);return await t.webauthn.signUp.finish(a.data.transactionId,i)},async signIn(e){const n=await t.webauthn.signIn.start(e,window.location.origin);if(!n.ok)return n;const a=await J(n.data.options);return await t.webauthn.signIn.finish(n.data.transactionId,a)},async signUpOrIn(e){var n;const a=await t.webauthn.signUpOrIn.start(e,window.location.origin);if(!a.ok)return a;if(null===(n=a.data)||void 0===n?void 0:n.create){const e=await A(a.data.options);return await t.webauthn.signUp.finish(a.data.transactionId,e)}{const e=await J(a.data.options);return await t.webauthn.signIn.finish(a.data.transactionId,e)}},async update(e,n){const a=await t.webauthn.update.start(e,window.location.origin,n);if(!a.ok)return a;const i=await A(a.data.options);return await t.webauthn.update.finish(a.data.transactionId,i)},helpers:{create:A,get:J,isSupported:K,conditional:T}}),(...t)=>{const e=q(...t);return Object.assign(e.signUp,t[0].webauthn.signUp),Object.assign(e.signIn,t[0].webauthn.signIn),Object.assign(e.signUpOrIn,t[0].webauthn.signUpOrIn),Object.assign(e.update,t[0].webauthn.update),e}),E=t=>Object.assign(Object.assign({},t.flow),{start:async(...e)=>{const n=await K(),a=Object.assign(Object.assign({},e[1]),{redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:n}});return e[1]=a,t.flow.start(...e)}});const H=function(...t){return e=>t.reduce(((t,e)=>e(t)),e)}((e=>n=>{var{fpKey:a,fpLoad:i}=n,s=t(n,["fpKey","fpLoad"]);return a?(g?i&&b(a).catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(o(s,{beforeRequest:h}))):e(Object.assign({},s))}),(e=>a=>{var i=t(a,["autoRefresh"]);const{clearAllTimers:r,setTimer:l}=(()=>{const t=[];return{clearAllTimers:()=>{for(;t.length;)clearTimeout(t.pop())},setTimer:(e,n)=>{t.push(setTimeout(e,n))}}})(),c=e(o(i,{afterRequest:async(t,e)=>{const{refreshJwt:n,sessionJwt:a}=await s(e);if(401===(null==e?void 0:e.status))r();else if(a){const t=((i=(t=>{const e=t.split(".");try{if(3===e.length){const t=JSON.parse(window.atob(e[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(t){}return null})(a))?i.getTime()-(new Date).getTime():0)-2e4;r(),l((()=>c.refresh(n)),t)}var i}}));return n(c,["logout","logoutAll"],(t=>async(...e)=>{const n=await t(...e);return r(),n}))}),(t=>e=>t(Object.assign(Object.assign({},e),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.30"},e.baseHeaders)}))),(t=>e=>{const a=O(),i=O(),l=t(o(e,{afterRequest:async(t,e)=>{if(401===(null==e?void 0:e.status))a.pub(null),i.pub(null);else{const t=await r(e);t&&i.pub(t);const{sessionJwt:n}=await s(e);n&&a.pub(n)}}})),c=n(l,["logout","logoutAll"],(t=>async(...e)=>{const n=await t(...e);return a.pub(null),i.pub(null),n}));return Object.assign(c,{onSessionTokenChange:a.sub,onUserChange:i.sub})}),(t=>e=>{const a=t(o(e,{afterRequest:async(t,e)=>{var n;const a=await r(e),i=null===(n=null==a?void 0:a.loginIds)||void 0===n?void 0:n[0],o=null==a?void 0:a.name;i&&((t=>{c("dls_last_user_login_id",t)})(i),(t=>{c("dls_last_user_display_name",t)})(o))}}));let i=n(a,["flow.start"],m);return i=n(i,["logout","logoutAll"],S),Object.assign(i,{getLastUserLoginId:v,getLastUserDisplayName:y})}),(e=>a=>{var{persistTokens:i,sessionTokenViaCookie:r}=a,l=t(a,["persistTokens","sessionTokenViaCookie"]);if(!i||!g)return i&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(l);const c=e(o(l,{beforeRequest:D,afterRequest:async(t,e)=>{401===(null==e?void 0:e.status)?j():I(await s(e),r)}})),u=n(c,["logout","logoutAll"],U);return Object.assign(u,{getRefreshToken:k,getSessionToken:_})}))(((...t)=>{const n=e(...t);return Object.assign(Object.assign({},n),{flow:E(n),webauthn:P(n)})}));export{H as default};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/helpers.ts","../src/fp.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n // istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","// supported state types are string and object\ntype StateObject = string | Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject> (a: T, b: T) => {\n if (typeof a === 'string') {\n return a === b;\n }\n\tconst aProperties = a && Object.getOwnPropertyNames(a) || [];\n\tconst bProperties = b && Object.getOwnPropertyNames(b) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nconst clone = (state: StateObject): StateObject => {\n if (typeof state === 'string') {\n return state;\n }\n return { ...state };\n}\n\nconst isEmpty = (state: StateObject): boolean => {\n if (!state || typeof state === 'string') {\n return !state;\n }\n return Object.entries(state).length === 0;\n}\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n return clone(this.#state);\n\t}\n\n\tupdate(newState: T) {\n\t\tlet nextState: T = newState;\n\t\tif (typeof newState === 'object' && typeof this.#state === 'object') {\n\t\t\tnextState = { ...this.#state , ...newState };\n\t\t}\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) =>\n\t\t\t\t\tcb(clone(nextState) as T, prevState)\n\t\t\t\t);\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\tif (!isEmpty(this.#state)) {\n\t\t\tcb(clone(this.#state) as T);\n\t\t}\n\n // return unsubscribe function\n const currentToken = this.#token\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (\n\tstate: T,\n\tprevState?: T\n) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(sessionJwt: string, refreshJwt: string, cookieParams: Partial<JWTResponse>) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || {} as JWTResponse\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token \n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(refreshFn: RefreshFn, res: Response, state: SdkState, options: TokensOptions) {\n\ttry {\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\t\t\t\n\t\t\t// Update state\n\t\t\tstate.sessionToken.update(sessionJwt);\n\t\t\tstate.user.update(user);\n\t\t\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(startResponse.data.transactionId, createResponse);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(startResponse.data.transactionId, getResponse);\n\t\treturn finishResponse;\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(identifier, window.location.origin, token);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(startResponse.data.transactionId, createResponse);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(createOptions)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & { response: AuthenticatorAttestationResponse };\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t},\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & { response: AuthenticatorAssertionResponse };\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle ? encodeBase64Url(credential.response.userHandle) : undefined,\n\t\t},\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] & TokensOptions & {\n\t// FingerprintJS API key\n\tfpKey?: string;\n};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tfp(args.fpKey)\n\t\t.get()\n\t\t.catch(() => null);\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<string>('');\n\tconst user = new State<UserResponse | {}>({});\n\t\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t},\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: sessionToken.subscribe,\n\t\tonUserChange: user.subscribe\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\treturn config;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, res) => {\n\t\t\thandleDescopeTokens(webSdk.refresh, res, { sessionToken, user }, { autoRefresh, persistTokens });\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","entries","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","localStorage","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","index","autoRefresh","persistTokens","args","__rest","catch","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","helpers","onSessionTokenChange","onUserChange","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","body","json","authIn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AYmB,EAEjD,CAKD,CAJC,MAAOpE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CErDG2K,CAAoB7B,EAAO8B,QAAS/K,EAAK,CAAEyI,eAAc5C,QAAQ,CAAEoC,cAAcC,iBAAgB,GAI/FD,GAEHgB,EAAO8B,UAGD9B,CAAM"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/enhancers/helpers/index.ts","../src/constants.ts","../src/enhancers/withFingerprint/constants.ts","../src/enhancers/withFingerprint/helpers.ts","../src/enhancers/withFingerprint/index.ts","../src/enhancers/withLastLoggedInUser/helpers.ts","../src/enhancers/withLastLoggedInUser/constants.ts","../src/enhancers/withLastLoggedInUser/index.ts","../src/enhancers/withNotifications/helpers.ts","../src/enhancers/withPersistTokens/helpers.ts","../src/enhancers/withPersistTokens/constants.ts","../src/enhancers/withPersistTokens/index.ts","../src/sdk/webauthn.ts","../src/sdk/flow.ts","../src/sdk/index.ts","../src/index.ts","../src/enhancers/helpers/compose.ts","../src/enhancers/withAutoRefresh/index.ts","../src/enhancers/withAutoRefresh/helpers.ts","../src/enhancers/withAnalytics.ts","../src/enhancers/withNotifications/index.ts"],"sourcesContent":["import { JWTResponse, UserResponse } from '@descope/core-js-sdk';\nimport { CoreSdkConfig } from '../../types';\n\n/**\n * Add hooks to an existing core-sdk config\n */\nexport const addHooks = <Config extends CoreSdkConfig>(\n\tconfig: Config,\n\thooks: Config['hooks']\n): Config => {\n\t['beforeRequest', 'afterRequest'].reduce((acc, key) => {\n\t\tacc[key] = [].concat(config.hooks?.[key] || []).concat(hooks?.[key] || []);\n\n\t\treturn acc;\n\t}, (config.hooks ??= {}));\n\n\treturn config;\n};\n\nexport { compose } from './compose';\n\n/**\n * Extract auth info (JWT response) from fetch response\n * We assume that the auth info is under a \"authInfo\" attribute (flow response)\n * Or the body itself (other auth methods response)\n */\nexport const getAuthInfoFromResponse = async (res: Response): Promise<Partial<JWTResponse>> => {\n\tif (!res?.ok) return {};\n\tconst body = await res?.clone().json();\n\treturn body?.authInfo || body || {};\n};\n\n/**\n * Extract user from fetch response\n * User my exist under \"user\" attribute (auth methods response)\n * Or the body itself (when calling \"me\")\n */\nexport const getUserFromResponse = async (res: Response): Promise<UserResponse> | undefined => {\n\tconst authInfo = await getAuthInfoFromResponse(res);\n\n\treturn (\n\t\tauthInfo?.user || (authInfo?.hasOwnProperty('userId') ? (authInfo as UserResponse) : undefined)\n\t);\n};\n\nexport const isLocalStorage = typeof localStorage !== 'undefined';\n\nexport const setLocalStorage = (key: string, value: string) =>\n\tisLocalStorage && localStorage?.setItem(key, value);\nexport const getLocalStorage = (key: string) => isLocalStorage && localStorage?.getItem(key);\nexport const removeLocalStorage = (key: string) => isLocalStorage && localStorage?.removeItem(key);\n","// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import { IS_BROWSER } from '../../constants';\n\nconst FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** Fingerprint visitor data */\nexport const FP_BODY_DATA = 'fpData';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n/** FP storage key */\nexport const FP_STORAGE_KEY = 'fp';\n// Storage FP Keys TTL is 24 hours\nexport const STORAGE_TTL_MS = 24 * 60 * 60 * 1000;\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport {\n\tFP_EP_URL,\n\tFP_STORAGE_KEY,\n\tSTORAGE_TTL_MS,\n\tVISITOR_REQUEST_ID_PARAM,\n\tVISITOR_SESSION_ID_PARAM\n} from './constants';\nimport { FingerprintObject } from './types';\n\nconst createFingerprintObject = (\n\tsessionId: string = '',\n\trequestId: string = ''\n): FingerprintObject => ({\n\t[VISITOR_SESSION_ID_PARAM]: sessionId,\n\t[VISITOR_REQUEST_ID_PARAM]: requestId\n});\n\n/** Generate UUID based on current time and some randomness */\nconst generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n\n// Set FP data to storage with expiration\n// We set the request id and session id together so they will have the same TTL\n// This implementation is based on https://www.sohamkamani.com/javascript/localstorage-with-ttl-expiry/\nconst setFPToStorage = (value: FingerprintObject) => {\n\tconst now = new Date();\n\t// `item` is an object which contains the value\n\t// as well as the time when it's supposed to expire\n\tconst item = {\n\t\tvalue,\n\t\texpiry: now.getTime() + STORAGE_TTL_MS\n\t};\n\tlocalStorage.setItem(FP_STORAGE_KEY, JSON.stringify(item));\n};\n\n// Get Fingerprint from storage, will return null if not exists, of if expired\nconst getFPFromStorage = (returnExpired = false): FingerprintObject => {\n\tconst itemStr = localStorage.getItem(FP_STORAGE_KEY);\n\t// if the item doesn't exist, return null\n\tif (!itemStr) {\n\t\treturn null;\n\t}\n\tconst item = JSON.parse(itemStr);\n\tconst now = new Date();\n\t// compare the expiry time of the item with the current time\n\t// return null if needed\n\tif (now.getTime() > item.expiry && !returnExpired) {\n\t\treturn null;\n\t}\n\treturn item.value;\n};\n\n/**\n * Ensure fingerprint ids (request id, session id) exist.\n * If not, It will generate and load them into to browser storage.\n * NOTE: Using fingerprintJS data has cost, use considerably.\n * @param fpKey FingerprintJS API key\n */\nexport const ensureFingerprintIds = async (fpKey: string) => {\n\ttry {\n\t\tif (getFPFromStorage()) {\n\t\t\t// FP is already in storage, no need to\n\t\t\treturn;\n\t\t}\n\n\t\tconst sessionId = generateUUID();\n\t\tconst agentP = load({ apiKey: fpKey, endpoint: FP_EP_URL });\n\t\tconst agent = await agentP;\n\t\tconst { requestId } = await agent.get({ linkedId: sessionId });\n\t\tconst fpData = createFingerprintObject(sessionId, requestId);\n\t\tsetFPToStorage(fpData);\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\tif (global.FB_DEBUG) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.error(ex);\n\t\t}\n\t}\n};\n\n/**\n * Get Fingerprint data (request ids) from storage, or create empty object\n * If data is expired, return it anyway\n */\nexport const getFingerprintData = (): FingerprintObject => {\n\t// get from storage, fallback to default\n\treturn getFPFromStorage(true) || createFingerprintObject();\n};\n","import { IS_BROWSER } from '../../constants';\nimport { CreateWebSdk } from '../../sdk';\nimport { BeforeRequestHook } from '../../types';\nimport { addHooks } from '../helpers';\nimport { FP_BODY_DATA } from './constants';\nimport { ensureFingerprintIds, getFingerprintData } from './helpers';\nimport { FingerprintOptions } from './types';\n\nconst beforeRequest: BeforeRequestHook = (config) => {\n\tif (config.body) {\n\t\tconfig.body[FP_BODY_DATA] = getFingerprintData();\n\t}\n\n\treturn config;\n};\n\n/**\n * Add fingerprint data to outgoing requests\n */\nexport const withFingerprint =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t({ fpKey, fpLoad, ...config }: Parameters<T>[0] & FingerprintOptions) => {\n\t\t// relevant only if fpKey was provided\n\t\tif (!fpKey) {\n\t\t\treturn createSdk({\n\t\t\t\t...config\n\t\t\t});\n\t\t}\n\t\tif (!IS_BROWSER) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn(\n\t\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t\t);\n\t\t} else if (fpLoad) {\n\t\t\tensureFingerprintIds(fpKey).catch(() => null);\n\t\t}\n\n\t\treturn createSdk(addHooks(config, { beforeRequest }));\n\t};\n","import { getLocalStorage, removeLocalStorage, setLocalStorage } from '../helpers';\nimport {\n\tLOCAL_STORAGE_LAST_USER_LOGIN_ID,\n\tLOCAL_STORAGE_LAST_USER_DISPLAY_NAME\n} from './constants';\n\nexport const setLastUserLoginId = (loginId: string) => {\n\treturn setLocalStorage(LOCAL_STORAGE_LAST_USER_LOGIN_ID, loginId);\n};\n\nexport const getLastUserLoginId = () => {\n\treturn getLocalStorage(LOCAL_STORAGE_LAST_USER_LOGIN_ID);\n};\n\nexport const removeLastUserLoginId = () => {\n\treturn removeLocalStorage(LOCAL_STORAGE_LAST_USER_LOGIN_ID);\n};\n\nexport const setLastUserDisplayName = (displayName: string) => {\n\treturn setLocalStorage(LOCAL_STORAGE_LAST_USER_DISPLAY_NAME, displayName);\n};\n\nexport const getLastUserDisplayName = () => {\n\treturn getLocalStorage(LOCAL_STORAGE_LAST_USER_DISPLAY_NAME);\n};\n\nexport const removeLastUserDisplayName = () => {\n\treturn removeLocalStorage(LOCAL_STORAGE_LAST_USER_DISPLAY_NAME);\n};\n","/** Login Id of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_LOGIN_ID = 'dls_last_user_login_id';\n\n/** Display name of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_DISPLAY_NAME = 'dls_last_user_display_name';\n","import { SdkFnWrapper, wrapWith } from '@descope/core-js-sdk';\nimport { CreateWebSdk } from '../../sdk';\nimport { AfterRequestHook, CoreSdk } from '../../types';\nimport { addHooks, getUserFromResponse } from '../helpers';\nimport {\n\tgetLastUserLoginId,\n\tremoveLastUserLoginId,\n\tsetLastUserLoginId,\n\tgetLastUserDisplayName,\n\tremoveLastUserDisplayName,\n\tsetLastUserDisplayName\n} from './helpers';\n\n/**\n * Adds last logged in user to flow start request\n */\n// eslint-disable-next-line import/exports-last\nexport const withLastLoggedInUser =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t(\n\t\tconfig: Parameters<T>[0]\n\t): ReturnType<T> & {\n\t\tgetLastUserLoginId: typeof getLastUserLoginId;\n\t\tgetLastUserDisplayName: typeof getLastUserDisplayName;\n\t} => {\n\t\tconst afterRequest: AfterRequestHook = async (_req, res) => {\n\t\t\tconst userDetails = await getUserFromResponse(res);\n\t\t\tconst loginId = userDetails?.loginIds?.[0];\n\t\t\tconst displayName = userDetails?.name;\n\t\t\tif (loginId) {\n\t\t\t\tsetLastUserLoginId(loginId);\n\t\t\t\tsetLastUserDisplayName(displayName);\n\t\t\t}\n\t\t};\n\n\t\tconst sdk = createSdk(addHooks(config, { afterRequest }));\n\n\t\tlet wrappedSdk = wrapWith(sdk, ['flow.start'], startWrapper);\n\t\twrappedSdk = wrapWith(wrappedSdk, ['logout', 'logoutAll'], logoutWrapper);\n\t\treturn Object.assign(wrappedSdk, { getLastUserLoginId, getLastUserDisplayName }) as any;\n\t};\n\nconst startWrapper: SdkFnWrapper<{}> =\n\t(fn) =>\n\tasync (...args) => {\n\t\targs[1] = args[1] || {};\n\t\tconst [, options = {}] = args as unknown as Parameters<CoreSdk['flow']['start']>;\n\t\tconst loginId = getLastUserLoginId();\n\t\tconst displayName = getLastUserDisplayName();\n\n\t\tif (loginId) {\n\t\t\toptions.lastAuth ??= {};\n\t\t\toptions.lastAuth.loginId = loginId;\n\t\t\toptions.lastAuth.name = displayName;\n\t\t}\n\n\t\tconst resp = await fn(...args);\n\n\t\treturn resp;\n\t};\n\nconst logoutWrapper: SdkFnWrapper<{}> =\n\t(fn) =>\n\tasync (...args) => {\n\t\tconst resp = await fn(...args);\n\n\t\tremoveLastUserLoginId();\n\t\tremoveLastUserDisplayName();\n\n\t\treturn resp;\n\t};\n","// create publisher/subscriber instances\nexport function createPubSub<T extends any>() {\n\tconst cbs = [];\n\n\tconst sub = (cb: (data: T) => void) => {\n\t\tconst idx = cbs.push(cb) - 1;\n\t\treturn () => cbs.splice(idx, 1);\n\t};\n\n\tconst pub = (data: T) => {\n\t\tcbs.forEach((cb) => cb(data));\n\t};\n\n\treturn { pub, sub };\n}\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { BeforeRequestHook } from '../../types';\nimport { REFRESH_TOKEN_KEY, SESSION_TOKEN_KEY } from './constants';\nimport { getLocalStorage, removeLocalStorage, setLocalStorage } from '../helpers';\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param name cookie name\n * @param value The JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setJwtTokenCookie(\n\tname: string,\n\tvalue: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (value) {\n\t\tconst expires = new Date(cookieExpiration * 1000); // we are getting response from the server in seconds instead of ms\n\t\tCookies.set(name, value, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\nexport const persistTokens = (\n\t{ refreshJwt, sessionJwt, ...cookieParams } = {} as Partial<JWTResponse>,\n\tsessionTokenViaCookie = false\n) => {\n\t// persist refresh token\n\trefreshJwt && setLocalStorage(REFRESH_TOKEN_KEY, refreshJwt);\n\n\t// persist session token\n\tif (sessionJwt) {\n\t\tsessionTokenViaCookie\n\t\t\t? setJwtTokenCookie(SESSION_TOKEN_KEY, sessionJwt, cookieParams)\n\t\t\t: setLocalStorage(SESSION_TOKEN_KEY, sessionJwt);\n\t}\n};\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn getLocalStorage(REFRESH_TOKEN_KEY) || '';\n}\n\n/**\n * Return the session token. first try to get from cookie, and fallback to local storage\n * See sessionTokenViaCookie option for more details about session token location\n */\nexport function getSessionToken(): string {\n\treturn Cookies.get(SESSION_TOKEN_KEY) || getLocalStorage(SESSION_TOKEN_KEY) || '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tremoveLocalStorage(REFRESH_TOKEN_KEY);\n\tremoveLocalStorage(SESSION_TOKEN_KEY);\n\tCookies.remove(SESSION_TOKEN_KEY);\n}\n\nexport const beforeRequest: BeforeRequestHook = (config) =>\n\tObject.assign(config, { token: config.token || getRefreshToken() });\n","/** Default name for the session cookie name / local storage key */\nexport const SESSION_TOKEN_KEY = 'DS';\n/** Default name for the refresh local storage key */\nexport const REFRESH_TOKEN_KEY = 'DSR';\n","/* eslint-disable import/exports-last */\nimport { SdkFnWrapper, wrapWith } from '@descope/core-js-sdk';\nimport { IS_BROWSER } from '../../constants';\nimport { CreateWebSdk } from '../../sdk';\nimport { AfterRequestHook } from '../../types';\nimport { addHooks, getAuthInfoFromResponse } from '../helpers';\nimport {\n\tbeforeRequest,\n\tclearTokens,\n\tgetRefreshToken,\n\tgetSessionToken,\n\tpersistTokens\n} from './helpers';\nimport { PersistTokensOptions } from './types';\n\n/**\n * Persist authentication tokens in cookie/storage\n */\nexport const withPersistTokens =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t<A extends boolean>({\n\t\tpersistTokens: isPersistTokens,\n\t\tsessionTokenViaCookie,\n\t\t...config\n\t}: Parameters<T>[0] & PersistTokensOptions<A>): A extends true\n\t\t? ReturnType<T> & {\n\t\t\t\tgetRefreshToken: typeof getRefreshToken;\n\t\t\t\tgetSessionToken: typeof getSessionToken;\n\t\t }\n\t\t: ReturnType<T> => {\n\t\tif (!isPersistTokens || !IS_BROWSER) {\n\t\t\tif (isPersistTokens) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn createSdk(config) as any;\n\t\t}\n\n\t\tconst afterRequest: AfterRequestHook = async (_req, res) => {\n\t\t\tif (res?.status === 401) {\n\t\t\t\tclearTokens();\n\t\t\t} else {\n\t\t\t\tpersistTokens(await getAuthInfoFromResponse(res), sessionTokenViaCookie);\n\t\t\t}\n\t\t};\n\n\t\tconst sdk = createSdk(addHooks(config, { beforeRequest, afterRequest }));\n\n\t\tconst wrappedSdk = wrapWith(sdk, ['logout', 'logoutAll'], wrapper);\n\n\t\treturn Object.assign(wrappedSdk, { getRefreshToken, getSessionToken }) as any;\n\t};\n\nconst wrapper: SdkFnWrapper<{}> =\n\t(fn) =>\n\tasync (...args) => {\n\t\tconst resp = await fn(...args);\n\n\t\tclearTokens();\n\n\t\treturn resp;\n\t};\n\nexport default withPersistTokens;\n","import { JWTResponse, SdkResponse, ResponseData } from '@descope/core-js-sdk';\nimport { IS_BROWSER } from '../constants';\nimport { CoreSdk } from '../types';\n\ntype CreateWebauthn = typeof createWebAuthn;\n\nconst withCoreFns =\n\t<I extends Parameters<CreateWebauthn>, O extends ReturnType<CreateWebauthn>>(\n\t\tcreator: (...args: I) => O\n\t) =>\n\t(...args: I) => {\n\t\tconst obj = creator(...args);\n\n\t\tObject.assign(obj.signUp, args[0].webauthn.signUp);\n\t\tObject.assign(obj.signIn, args[0].webauthn.signIn);\n\t\tObject.assign(obj.signUpOrIn, args[0].webauthn.signUpOrIn);\n\t\tObject.assign(obj.update, args[0].webauthn.update);\n\n\t\treturn obj as {\n\t\t\t[K in keyof O]: K extends keyof I[0]['webauthn'] ? O[K] & I[0]['webauthn'][K] : O[K];\n\t\t};\n\t};\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tif (!startResponse.ok) {\n\t\t\treturn startResponse as unknown as SdkResponse<JWTResponse>;\n\t\t}\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tif (!startResponse.ok) {\n\t\t\treturn startResponse as unknown as SdkResponse<JWTResponse>;\n\t\t}\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (!startResponse.ok) {\n\t\t\treturn startResponse as unknown as SdkResponse<JWTResponse>;\n\t\t}\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tif (!startResponse.ok) {\n\t\t\treturn startResponse as SdkResponse<ResponseData>;\n\t\t}\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t\t/** Checks if the browser supports WebAuthn, and can optionally require in\n\t\t * addition that the browser supports WebAuthn with built-in biometrics */\n\t\tisSupported,\n\t\tconditional\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n/**\n * This function should be used in passkeys autofill (conditional UI)\n * It handles the call to \"navigator.credentials.get\" and adds the required options\n * @param options webauthn start options\n * @param abort: AbortController instance\n * @returns encoded \"navigator.credentials.get\" response\n */\nasync function conditional(options: string, abort: AbortController): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tgetOptions.signal = abort.signal;\n\tgetOptions.mediation = 'conditional' as any;\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// eslint-disable-next-line import/exports-last\nexport async function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tif (!IS_BROWSER) {\n\t\treturn Promise.resolve(false);\n\t}\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\tid: credential.id,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\ttype: credential.type,\n\t\tresponse: {\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\tid: credential.id,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\ttype: credential.type,\n\t\tresponse: {\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\nexport default withCoreFns(createWebAuthn);\n","import { CoreSdk, ReplaceParam } from '../types';\nimport { isSupported } from './webauthn';\n\ntype CoreSdkFlowStartArgs = Parameters<CoreSdk['flow']['start']>;\ntype Options = Pick<CoreSdkFlowStartArgs[1], 'tenant'> & {\n\tlastAuth?: Omit<CoreSdkFlowStartArgs[1]['lastAuth'], 'loginId' | 'name'>;\n};\n\nexport default (coreSdk: CoreSdk) => ({\n\t...coreSdk.flow,\n\t// wrap start fn and adds more data to the start options\n\tstart: async (...args: ReplaceParam<CoreSdkFlowStartArgs, '1', Options>) => {\n\t\tconst webAuthnSupport = await isSupported();\n\t\tconst decoratedOptions = {\n\t\t\t...args[1],\n\t\t\tredirectUrl: window.location.href,\n\t\t\tdeviceInfo: {\n\t\t\t\twebAuthnSupport\n\t\t\t}\n\t\t};\n\n\t\targs[1] = decoratedOptions;\n\n\t\treturn coreSdk.flow.start(...args);\n\t}\n});\n","import createCoreSdk from '@descope/core-js-sdk';\nimport createWebAuthn from './webauthn';\nimport withFlow from './flow';\n\nconst createSdk = (...args: Parameters<typeof createCoreSdk>) => {\n\tconst coreSdk = createCoreSdk(...args);\n\n\treturn {\n\t\t...coreSdk,\n\t\tflow: withFlow(coreSdk),\n\t\twebauthn: createWebAuthn(coreSdk)\n\t};\n};\n\nexport default createSdk;\n\nexport type CreateWebSdk = typeof createSdk;\nexport type WebSdk = ReturnType<CreateWebSdk>;\n","import { compose } from './enhancers/helpers';\nimport { withAnalytics } from './enhancers/withAnalytics';\nimport { withAutoRefresh } from './enhancers/withAutoRefresh';\nimport { withFingerprint } from './enhancers/withFingerprint';\nimport { withLastLoggedInUser } from './enhancers/withLastLoggedInUser';\nimport { withNotifications } from './enhancers/withNotifications';\nimport withPersistTokens from './enhancers/withPersistTokens';\nimport createSdk from './sdk';\n\nconst decoratedCreateSdk = compose(\n\twithFingerprint,\n\twithAutoRefresh,\n\twithAnalytics,\n\twithNotifications,\n\twithLastLoggedInUser, // must be one before last due to TS types\n\twithPersistTokens // must be last due to TS known limitation https://github.com/microsoft/TypeScript/issues/30727\n)(createSdk);\n\nexport type { UserResponse } from './types';\n\nexport default decoratedCreateSdk;\n","import { CreateWebSdk, WebSdk } from '../../sdk';\n\ntype Fn = (arg: any) => any;\n\nexport function compose<Input, A1>(fn1: (input: Input) => A1): (input: Input) => A1;\n\nexport function compose<Input, A1, A2>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2\n): (input: Input) => A2;\n\nexport function compose<Input, A1, A2, A3>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3\n): (input: Input) => A3;\n\nexport function compose<Input, A1, A2, A3, A4>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4\n): (input: Input) => A4;\n\nexport function compose<Input, A1, A2, A3, A4, A5>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5\n): (input: Input) => A5;\n\nexport function compose<Input, A1, A2, A3, A4, A5, A6>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5,\n\tfn6: (input: A5) => A6\n): (input: Input) => A6;\n\nexport function compose<Input, A1, A2, A3, A4, A5, A6, A7>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5,\n\tfn6: (input: A5) => A6,\n\tfn7: (input: A6) => A7\n): (input: Input) => A7;\n\nexport function compose<Input, A1, A2, A3, A4, A5, A6, A7, A8>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5,\n\tfn6: (input: A5) => A6,\n\tfn7: (input: A6) => A7,\n\tfn8: (input: A7) => A8\n): (input: Input) => A8;\n\nexport function compose<Input, A1, A2, A3, A4, A5, A6, A7, A8, A9>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5,\n\tfn6: (input: A5) => A6,\n\tfn7: (input: A6) => A7,\n\tfn8: (input: A7) => A8,\n\tfn9: (input: A8) => A9\n): (input: Input) => A9;\n\nexport function compose<Input, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>(\n\tfn1: (input: Input) => A1,\n\tfn2: (input: A1) => A2,\n\tfn3: (input: A2) => A3,\n\tfn4: (input: A3) => A4,\n\tfn5: (input: A4) => A5,\n\tfn6: (input: A5) => A6,\n\tfn7: (input: A6) => A7,\n\tfn8: (input: A7) => A8,\n\tfn9: (input: A8) => A9,\n\tfn10: (input: A9) => A10\n): (input: Input) => A10;\n\n/**\n * Currently there is no way to create a compose function in Typescript without using overloading\n * This function currently support up to 10 wrappers\n * If needed you can add more by duplicating the type and add more parameters\n */\n\nexport function compose(...args: Fn[]) {\n\treturn (data: any) => args.reduce((acc, elem) => elem(acc), data) as any;\n}\n","import { SdkFnWrapper, wrapWith } from '@descope/core-js-sdk';\nimport { CreateWebSdk } from '../../sdk';\nimport { AfterRequestHook } from '../../types';\nimport { addHooks, getAuthInfoFromResponse } from '../helpers';\nimport { createTimerFunctions, getTokenExpiration, millisecondsUntilDate } from './helpers';\nimport { AutoRefreshOptions } from './types';\n\n// The amount of time (ms) to trigger the refresh before session expires\nconst REFRESH_THRESHOLD = 20 * 1000; // 20 sec\n\n/**\n * Automatically refresh the session token before it expires\n * It uses the the refresh token that is extracted from API response to do that\n */\nexport const withAutoRefresh =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t({ autoRefresh, ...config }: Parameters<T>[0] & AutoRefreshOptions) => {\n\t\t// if we hold a single timer id, there might be a case where we override it before canceling the timer, this might cause many calls to refresh\n\t\t// in order to prevent it, we hold a list of timers and cancel all of them when a new timer is set, which means we should have one active timer only at a time\n\t\tconst { clearAllTimers, setTimer } = createTimerFunctions();\n\n\t\tconst afterRequest: AfterRequestHook = async (_req, res) => {\n\t\t\tconst { refreshJwt, sessionJwt } = await getAuthInfoFromResponse(res);\n\n\t\t\t// if we got 401 we want to cancel all timers\n\t\t\tif (res?.status === 401) {\n\t\t\t\tclearAllTimers();\n\t\t\t} else if (sessionJwt) {\n\t\t\t\tconst timeout = millisecondsUntilDate(getTokenExpiration(sessionJwt)) - REFRESH_THRESHOLD;\n\t\t\t\tclearAllTimers();\n\t\t\t\tsetTimer(() => sdk.refresh(refreshJwt), timeout);\n\t\t\t}\n\t\t};\n\n\t\tconst sdk = createSdk(addHooks(config, { afterRequest }));\n\n\t\tconst wrapper: SdkFnWrapper<{}> =\n\t\t\t(fn) =>\n\t\t\tasync (...args) => {\n\t\t\t\tconst resp = await fn(...args);\n\n\t\t\t\tclearAllTimers();\n\n\t\t\t\treturn resp;\n\t\t\t};\n\n\t\treturn wrapWith(sdk, ['logout', 'logoutAll'], wrapper);\n\t};\n","/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nexport const getTokenExpiration = (token: string) => {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(parts[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (e) {}\n\treturn null;\n};\n\nexport const millisecondsUntilDate = (date: Date) =>\n\tdate ? date.getTime() - new Date().getTime() : 0;\n\nexport const createTimerFunctions = () => {\n\tconst timerIds: NodeJS.Timeout[] = [];\n\n\tconst clearAllTimers = () => {\n\t\twhile (timerIds.length) {\n\t\t\tclearTimeout(timerIds.pop());\n\t\t}\n\t};\n\n\tconst setTimer = (cb: () => void, timeout: number) => {\n\t\ttimerIds.push(setTimeout(cb, timeout));\n\t};\n\n\treturn { clearAllTimers, setTimer };\n};\n","import { CreateWebSdk } from '../sdk';\nimport { BeforeRequestHook } from '../types';\nimport { addHooks } from './helpers';\n\n// this is replaced in build time\ndeclare const BUILD_VERSION: string;\n/**\n * Adds analytics headers to requests\n */\nexport const withAnalytics =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t(config: Parameters<T>[0]) =>\n\t\tcreateSdk({\n\t\t\t...config,\n\t\t\tbaseHeaders: {\n\t\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t\t'x-descope-sdk-version': BUILD_VERSION,\n\t\t\t\t...config.baseHeaders\n\t\t\t}\n\t\t});\n","import { SdkFnWrapper, UserResponse, wrapWith } from '@descope/core-js-sdk';\nimport { CreateWebSdk, WebSdk } from '../../sdk';\nimport { AfterRequestHook } from '../../types';\nimport { addHooks, getAuthInfoFromResponse, getUserFromResponse } from '../helpers';\nimport { createPubSub } from './helpers';\n\n/**\n * Adds 2 event functions to the sdk,\n * onSessionTokenChange: Gets a callback and call it whenever there is a change in session token\n * onUserChange: Gets a callback and call it whenever there is a change in current logged in user\n */\nexport const withNotifications =\n\t<T extends CreateWebSdk>(createSdk: T) =>\n\t(config: Parameters<T>[0]) => {\n\t\tconst sessionPS = createPubSub<string | null>();\n\t\tconst userPS = createPubSub<UserResponse | null>();\n\n\t\tconst afterRequest: AfterRequestHook = async (_req, res) => {\n\t\t\tif (res?.status === 401) {\n\t\t\t\tsessionPS.pub(null);\n\t\t\t\tuserPS.pub(null);\n\t\t\t} else {\n\t\t\t\tconst userDetails = await getUserFromResponse(res);\n\t\t\t\tif (userDetails) userPS.pub(userDetails);\n\n\t\t\t\tconst { sessionJwt } = await getAuthInfoFromResponse(res);\n\t\t\t\tif (sessionJwt) sessionPS.pub(sessionJwt);\n\t\t\t}\n\t\t};\n\n\t\tconst sdk = createSdk(addHooks(config, { afterRequest }));\n\n\t\tconst wrapper: SdkFnWrapper<{}> =\n\t\t\t(fn) =>\n\t\t\tasync (...args) => {\n\t\t\t\tconst resp = await fn(...args);\n\n\t\t\t\tsessionPS.pub(null);\n\t\t\t\tuserPS.pub(null);\n\n\t\t\t\treturn resp;\n\t\t\t};\n\n\t\tconst wrappedSdk = wrapWith(sdk, ['logout', 'logoutAll'], wrapper);\n\n\t\treturn Object.assign(wrappedSdk, {\n\t\t\tonSessionTokenChange: sessionPS.sub,\n\t\t\tonUserChange: userPS.sub\n\t\t});\n\t};\n"],"names":["addHooks","config","hooks","reduce","acc","key","concat","_a","getAuthInfoFromResponse","async","res","ok","body","clone","json","authInfo","getUserFromResponse","user","hasOwnProperty","undefined","isLocalStorage","localStorage","setLocalStorage","value","setItem","getLocalStorage","getItem","removeLocalStorage","removeItem","IS_BROWSER","window","FP_EP_URL","createFingerprintObject","sessionId","requestId","vsid","vrid","getFPFromStorage","returnExpired","itemStr","item","JSON","parse","Date","getTime","expiry","ensureFingerprintIds","fpKey","now","toString","Math","random","substring","agentP","load","apiKey","endpoint","agent","get","linkedId","stringify","setFPToStorage","ex","global","FB_DEBUG","console","error","beforeRequest","getLastUserLoginId","getLastUserDisplayName","startWrapper","fn","args","options","loginId","displayName","lastAuth","name","logoutWrapper","resp","createPubSub","cbs","pub","data","forEach","cb","sub","idx","push","splice","persistTokens","sessionTokenViaCookie","refreshJwt","sessionJwt","cookieParams","__rest","cookiePath","cookieDomain","cookieExpiration","expires","Cookies","set","path","domain","sameSite","secure","setJwtTokenCookie","getRefreshToken","getSessionToken","clearTokens","remove","Object","assign","token","wrapper","create","createOptions","publicKey","challenge","decodeBase64Url","id","excludeCredentials","decodeCreateOptions","createResponse","navigator","credentials","credential","rawId","encodeBase64Url","type","response","attestationObject","clientDataJSON","getOptions","decodeGetOptions","encodeGetResponse","conditional","abort","signal","mediation","isSupported","requirePlatformAuthenticator","Promise","resolve","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","allowCredentials","authenticatorData","signature","userHandle","base64","replace","Uint8Array","from","atob","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","creator","createWebAuthn$1","sdk","identifier","startResponse","webauthn","signUp","start","location","origin","finish","transactionId","signIn","getResponse","signUpOrIn","update","helpers","obj","withFlow","coreSdk","flow","webAuthnSupport","decoratedOptions","redirectUrl","href","deviceInfo","decoratedCreateSdk","elem","compose","createSdk","fpLoad","catch","warn","clearAllTimers","setTimer","timerIds","length","clearTimeout","pop","timeout","setTimeout","createTimerFunctions","afterRequest","_req","status","date","parts","split","claims","exp","e","getTokenExpiration","refresh","wrapWith","baseHeaders","sessionPS","userPS","userDetails","wrappedSdk","onSessionTokenChange","onUserChange","loginIds","setLastUserLoginId","setLastUserDisplayName","isPersistTokens","createCoreSdk","createWebAuthn"],"mappings":"mKAMO,MAAMA,EAAW,CACvBC,EACAC,WAQA,MANA,CAAC,gBAAiB,gBAAgBC,QAAO,CAACC,EAAKC,WAG9C,OAFAD,EAAIC,GAAO,GAAGC,QAAmB,UAAZL,EAAOC,aAAK,IAAAK,OAAA,EAAAA,EAAGF,KAAQ,IAAIC,QAAOJ,aAAA,EAAAA,EAAQG,KAAQ,IAEhED,CAAG,GACK,QAAbG,EAACN,EAAOC,aAAK,IAAAK,EAAAA,EAAZN,EAAOC,MAAU,CAAA,GAEdD,CAAM,EAUDO,EAA0BC,MAAOC,IAC7C,KAAKA,aAAA,EAAAA,EAAKC,IAAI,MAAO,GACrB,MAAMC,QAAaF,aAAA,EAAAA,EAAKG,QAAQC,QAChC,OAAOF,aAAA,EAAAA,EAAMG,WAAYH,GAAQ,CAAA,CAAE,EAQvBI,EAAsBP,MAAOC,IACzC,MAAMK,QAAiBP,EAAwBE,GAE/C,OACCK,aAAA,EAAAA,EAAUE,SAASF,aAAQ,EAARA,EAAUG,eAAe,WAAaH,OAA4BI,EACpF,EAGUC,EAAyC,oBAAjBC,aAExBC,EAAkB,CAACjB,EAAakB,IA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oK,EAAM2B,EAAUhM,EAASC,EAAQ,CAAEkE,gBAAe0I,aARjBpM,MAAOqM,EAAMpM,KAC/B,OAAhBA,aAAG,EAAHA,EAAKqM,QACRlG,IAEAnB,QAAoBlF,EAAwBE,GAAMiF,EAClD,KAKIkI,EAAaL,EAASnD,EAAK,CAAC,SAAU,aAAcnD,GAE1D,OAAOH,OAAOC,OAAO6G,EAAY,CAAElH,kBAAiBC,mBAAyB,GI3CpDmF,EDLT,IAAIvH,KACrB,MAAM8G,EAAU8C,KAAiB5J,GAEjC,OAAAuC,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EACIsE,GAAO,CACVC,KAAMF,EAASC,GACfd,SAAU6D,EAAe/C,IACxB"}
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).descopeSdk=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function n(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function r(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var i="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,a=0,s="";r=t.charAt(a++);~r&&(n=i%4?64*n+r:r,i++%4)?s+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function a(e){this.message=e}function s(e,t){if("string"!=typeof e)throw new a("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(i(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return i(t)}}(e.split(".")[n]))}catch(e){throw new a("Invalid token specified: "+e.message)}}a.prototype=new Error,a.prototype.name="InvalidTokenError";var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},u="__lodash_hash_undefined__",l="[object Function]",p="[object GeneratorFunction]",d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,f=/^\w*$/,h=/^\./,g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v=/\\(\\)?/g,y=/^\[object .+?Constructor\]$/,b="object"==typeof c&&c&&c.Object===Object&&c,m="object"==typeof self&&self&&self.Object===Object&&self,w=b||m||Function("return this")();var O,j=Array.prototype,k=Function.prototype,I=Object.prototype,_=w["__core-js_shared__"],S=(O=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+O:"",x=k.toString,P=I.hasOwnProperty,U=I.toString,R=RegExp("^"+x.call(P).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),E=w.Symbol,C=j.splice,T=z(w,"Map"),D=z(Object,"create"),q=E?E.prototype:void 0,A=q?q.toString:void 0;function $(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function J(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function M(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function N(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function K(e,t){var n;t=function(e,t){if(G(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||V(e))return!0;return f.test(e)||!d.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:G(n=t)?n:F(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[H(t[r++])];return r&&r==o?e:void 0}function L(e){if(!Z(e)||(t=e,S&&S in t))return!1;var t,n=function(e){var t=Z(e)?U.call(e):"";return t==l||t==p}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?R:y;return n.test(function(e){if(null!=e){try{return x.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function B(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function z(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return L(n)?n:void 0}$.prototype.clear=function(){this.__data__=D?D(null):{}},$.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},$.prototype.get=function(e){var t=this.__data__;if(D){var n=t[e];return n===u?void 0:n}return P.call(t,e)?t[e]:void 0},$.prototype.has=function(e){var t=this.__data__;return D?void 0!==t[e]:P.call(t,e)},$.prototype.set=function(e,t){return this.__data__[e]=D&&void 0===t?u:t,this},J.prototype.clear=function(){this.__data__=[]},J.prototype.delete=function(e){var t=this.__data__,n=N(t,e);return!(n<0)&&(n==t.length-1?t.pop():C.call(t,n,1),!0)},J.prototype.get=function(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]},J.prototype.has=function(e){return N(this.__data__,e)>-1},J.prototype.set=function(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},M.prototype.clear=function(){this.__data__={hash:new $,map:new(T||J),string:new $}},M.prototype.delete=function(e){return B(this,e).delete(e)},M.prototype.get=function(e){return B(this,e).get(e)},M.prototype.has=function(e){return B(this,e).has(e)},M.prototype.set=function(e,t){return B(this,e).set(e,t),this};var F=W((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(V(e))return A?A.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return h.test(e)&&n.push(""),e.replace(g,(function(e,t,r,o){n.push(r?o.replace(v,"$1"):t||e)})),n}));function H(e){if("string"==typeof e||V(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function W(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(W.Cache||M),n}W.Cache=M;var G=Array.isArray;function Z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function V(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==U.call(e)}var Q,X=function(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r},Y="/v1/auth/accesskey/exchange",ee="/v1/auth/otp/verify",te="/v1/auth/otp/signin",ne="/v1/auth/otp/signup",re={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},oe="/v1/auth/otp/signup-in",ie="/v1/auth/magiclink/verify",ae="/v1/auth/magiclink/signin",se="/v1/auth/magiclink/signup",ce="/v1/auth/magiclink/pending-session",ue={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/email"},le="/v1/auth/magiclink/signup-in",pe="/v1/auth/oauth/authorize",de="/v1/auth/saml/authorize",fe="/v1/auth/totp/verify",he="/v1/auth/totp/signup",ge="/v1/user/totp/update",ve={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},ye={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},be={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},me="/v1/flow/start",we="/v1/flow/next";!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Q||(Q={}));const Oe=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},je=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,r])=>(e[n]=r,e)),e),e}),{})),ke=e=>void 0===e?void 0:JSON.stringify(e),Ie=(e,t="")=>{let n=e;return""!==t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},_e=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:i})=>{const a=((e,t)=>{const n=t||fetch;if(!n)throw new Error("fetch is not defined");return e?async(...t)=>{e.log((e=>Oe().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Oe().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:c,body:u,headers:l,queryParams:p,method:d,token:f}=s,h=await a((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:c,baseUrl:e,queryParams:p}),{headers:je(Ie(t,f),(null==n?void 0:n.baseHeaders)||{},l),method:d,body:ke(u),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&o.afterRequest(r,null==h?void 0:h.clone()),h};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:Q.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.delete,token:o})}};function Se(e){const{exp:t}=Ce(e);return(new Date).getTime()/1e3>t}function xe(e,t){return Ee(e,t,"permissions")}function Pe(e,t){return Ee(e,t,"roles")}const Ue=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Re(e){const t=await e,n={code:t.status,ok:t.ok,response:t},r=await t.json();return t.ok?n.data=r:n.error=r,n}function Ee(e,t,n){var r;let o=Ce(e);t&&(o=null===(r=o.tenants)||void 0===r?void 0:r[t]);const i=o[n];return Array.isArray(i)?i:[]}function Ce(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return s(e)}const Te=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),De=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),qe=e=>t=>e.test(t),Ae=qe(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),$e=qe(/^\+[1-9]{1}[0-9]{3,14}$/),Je=Te(Ae,'"{val}" is not a valid email'),Me=Te($e,'"{val}" is not a valid phone number'),Ne=Te((1,e=>e.length>=1),"Minimum length is 1");const Ke=Te((e=>"string"==typeof e),"Input is not a string"),Le=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>De(...e).validate(n[t]))),t(...n)),Be=e=>[Ke(`"${e}" must be a string`),Ne(`"${e}" must not be empty`)],ze=e=>[Ke(`"${e}" must be a string`),Je()],Fe=e=>[Ke(`"${e}" must be a string`),Me()],He=Le(Be("accessKey")),We=e=>({exchange:He((t=>Re(e.get(Y,{token:t}))))});var Ge,Ze,Ve,Qe,Xe;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Ge||(Ge={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(Ze||(Ze={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Ve||(Ve={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(Qe||(Qe={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(Xe||(Xe={}));const Ye=Be("identifier"),et=Le(Ye,Be("code")),tt=Le(Ye),nt=Le(Ye,Fe("phone")),rt=Le(Ye,ze("email")),ot=e=>({verify:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:et(((t,r)=>Re(e.post(Ue(ee,n),{code:r,externalId:t}))))})),{}),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(te,n),{externalId:t}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt(((t,r)=>Re(e.post(Ue(ne,n),{externalId:t,user:r}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(oe,n),{externalId:t}))))})),{}),update:{email:rt(((t,n,r)=>Re(e.post(re.email,{externalId:t,email:n},{token:r})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nt(((t,r,o)=>Re(e.post(Ue(re.phone,n),{externalId:t,phone:r},{token:o}))))})),{})}}),it=Be("identifier"),at=Be("uri"),st=Le(Be("token")),ct=Le(it,at),ut=Le(Be("pendingRef")),lt=Le(it,Fe("phone"),at),pt=Le(it,ze("email"),at),dt=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o,crossDevice:!0}))))})),{}),waitForSession:ut(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let a;const s=setInterval((async()=>{const n=await e.post(ce,{pendingRef:t});n.ok&&(clearInterval(s),a&&clearTimeout(a),r(Re(Promise.resolve(n))))}),o);a=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${i}ms`,code:"0"},ok:!1}),clearInterval(s)}),i)})))),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r,crossDevice:!0},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o,crossDevice:!0},{token:i}))))})),{})}}),ft=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r}))))})),{}),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o},{token:i}))))})),{})},crossDevice:dt(e)}),ht=Le(Be("code")),gt=e=>({exchange:ht((t=>Re(e.get("/v1/auth/exchange",{queryParams:{code:t}}))))});var vt;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(vt||(vt={}));const yt=e=>Object.assign({start:Object.keys(vt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={})=>{const o=await e.get(pe,{queryParams:Object.assign({provider:n},t&&{redirectURL:t})});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}})),{})},gt(e)),bt=Le(Be("flowId")),mt=Le(Be("executionId"),Be("stepId"),Be("interactionId")),wt=e=>({start:bt((t=>Re(e.post(me,{flowId:t})))),next:mt(((t,n,r,o)=>Re(e.post(we,{executionId:t,stepId:n,interactionId:r,input:o}))))}),Ot=Le(Be("tenant")),jt=e=>Object.assign({start:Ot((async(t,n,{redirect:r=!1}={})=>{const o=await e.get(de,{queryParams:{tenant:t,redirectURL:n}});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}))},gt(e)),kt=Be("identifier"),It=Le(kt,Be("code")),_t=Le(kt),St=Le(kt),xt=e=>({signUp:_t(((t,n)=>Re(e.post(he,{externalId:t,user:n})))),verify:It(((t,n)=>Re(e.post(fe,{externalId:t,code:n})))),update:St(((t,n)=>Re(e.post(ge,{externalId:t},{token:n}))))}),Pt=Be("identifier"),Ut=Be("origin"),Rt=Le(Pt,Ut,Be("name")),Et=Le(Pt,Ut),Ct=Le(Pt,Ut,Be("token")),Tt=Le(Be("transactionId"),Be("response")),Dt=e=>({signUp:{start:Rt(((t,n,r)=>Re(e.post(ve.start,{user:{externalId:t,name:r},origin:n})))),finish:Tt(((t,n)=>Re(e.post(ve.finish,{transactionId:t,response:n}))))},signIn:{start:Et(((t,n)=>Re(e.post(ye.start,{externalId:t,origin:n})))),finish:Tt(((t,n)=>Re(e.post(ye.finish,{transactionId:t,response:n}))))},update:{start:Ct(((t,n,r)=>Re(e.post(be.start,{externalId:t,origin:n},{token:r})))),finish:Tt(((t,n)=>Re(e.post(be.finish,{transactionId:t,response:n}))))}}),qt=Le(Be("token"));var At;const $t=Le([("projectId",At=Be("projectId"),Te(((e,t)=>e=>De(...t).validate(X(e,"projectId")))(0,At))())])((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o})=>{return i=_e({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o}),{accessKey:We(i),otp:ot(i),magicLink:ft(i),oauth:yt(i),saml:jt(i),totp:xt(i),webauthn:Dt(i),flow:wt(i),refresh:e=>Re(i.get("/v1/auth/refresh",{token:e})),logout:e=>Re(i.get("/v1/auth/logoutall",{token:e})),me:e=>Re(i.get("/v1/auth/me",{token:e})),isJwtExpired:qt(Se),getJwtPermissions:qt(xe),getJwtRoles:qt(Pe),httpClient:i};var i}));$t.DeliveryMethods=Ze;const Jt="vsid",Mt="vrid";function Nt(e,t,n){return void 0===n&&(n=0),t(n).catch((function(r){if(n>=e.maxRetries||!e.shouldRetry(r))throw r;var o,i,a,s,c=(o=e.baseDelay,i=e.maxDelay,a=e.baseDelay*Math.pow(2,n),Math.max(o,Math.min(i,a)));return(s=c,new Promise((function(e){return setTimeout(e,s)}))).then((function(){return Nt(e,t,n+1)}))}))}var Kt="Failed to load the JS script of the agent";function Lt(n){var r,o=n.scriptUrlPattern,i=n.token,a=n.apiKey,s=void 0===a?i:a,c=t(n,["scriptUrlPattern","token","apiKey"]),u=(r=n,"scriptUrlPattern",Object.prototype.hasOwnProperty.call(r,"scriptUrlPattern")?o:void 0),l=[];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");return Nt({maxRetries:5,baseDelay:100,maxDelay:3e3,shouldRetry:function(e){return!(e instanceof Error&&"Blocked by CSP"===e.message)}},(function(){var e,t=new Date,n=function(){return l.push({startedAt:t,finishedAt:new Date})},r=function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(c(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e=function(e,t){void 0===t&&(t="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js");var n=encodeURIComponent;return t.replace(/<[^<>]+>/g,(function(t){return"<version>"===t?"3":"<apiKey>"===t?n(e):"<loaderVersion>"===t?n("3.7.1"):t}))}(s,u),(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(Kt))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)}));return r.then(n,n),r}))})).then((function(){var t=window,n="__fpjs_p_l_b",r=t[n];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(t,n),"function"!=typeof(null==r?void 0:r.load))throw new Error(Kt);return r.load(e(e({},c),{ldi:{attempts:l}}))}))}const Bt=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],zt=e=>{const t=Lt({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem(Jt);e||(e=Bt(Jt)),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem(Jt,e);const n=await t,r=await n.get({linkedId:e});sessionStorage.setItem(Mt,r.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var Ft,Ht,Wt,Gt,Zt;const Vt=e=>"string"==typeof e?e:Object.assign({},e);class Qt{constructor(e){Ft.add(this),Ht.set(this,void 0),Wt.set(this,{}),Gt.set(this,0),r(this,Ht,e,"f")}get current(){return Vt(n(this,Ht,"f"))}update(e){let t=e;if("object"==typeof e&&"object"==typeof n(this,Ht,"f")&&(t=Object.assign(Object.assign({},n(this,Ht,"f")),e)),!((e,t)=>{if("string"==typeof e)return e===t;const n=e&&Object.getOwnPropertyNames(e)||[],r=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const o=n[r];if(e[o]!==t[o])return!1}return!0})(n(this,Ht,"f"),t)){const e=n(this,Ht,"f");r(this,Ht,t,"f"),Object.freeze(n(this,Ht,"f")),setTimeout((()=>{Object.values(n(this,Wt,"f")).forEach((n=>n(Vt(t),e)))}),0)}}subscribe(e){var t;r(this,Gt,n(this,Gt,"f")+1,"f"),n(this,Wt,"f")[n(this,Gt,"f")]=e,((t=n(this,Ht,"f"))&&"string"!=typeof t?0===Object.entries(t).length:!t)||e(Vt(n(this,Ht,"f")));const o=n(this,Gt,"f");return()=>n(this,Ft,"m",Zt).call(this,o.toString())}unsubscribeAll(){r(this,Wt,{},"f")}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Descope=t()}(this,(function(){"use strict";const e=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,r)=>{var o;return n[r]=[].concat((null===(o=e.hooks)||void 0===o?void 0:o[r])||[]).concat((null==t?void 0:t[r])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},t=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json());return(null==t?void 0:t.authInfo)||t||{}},n=async e=>{const n=await t(e);return(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0)},r="undefined"!=typeof localStorage,o=(e,t)=>r&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),i=e=>r&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),a=e=>r&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e));var s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},s.apply(this,arguments)};function u(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function c(e){this.message=e}c.prototype=new Error,c.prototype.name="InvalidCharacterError";var l="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new c("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,o=0,i=0,a="";r=t.charAt(i++);~r&&(n=o%4?64*n+r:r,o++%4)?a+=String.fromCharCode(255&n>>(-2*o&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return a};function d(e){this.message=e}function p(e,t){if("string"!=typeof e)throw new d("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(l(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return l(t)}}(e.split(".")[n]))}catch(e){throw new d("Invalid token specified: "+e.message)}}d.prototype=new Error,d.prototype.name="InvalidTokenError";var f="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},h="__lodash_hash_undefined__",g="[object Function]",v="[object GeneratorFunction]",y=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,b=/^\w*$/,w=/^\./,m=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,k=/\\(\\)?/g,I=/^\[object .+?Constructor\]$/,O="object"==typeof f&&f&&f.Object===Object&&f,j="object"==typeof self&&self&&self.Object===Object&&self,_=O||j||Function("return this")();var S,U=Array.prototype,P=Function.prototype,R=Object.prototype,x=_["__core-js_shared__"],A=(S=/[^.]+$/.exec(x&&x.keys&&x.keys.IE_PROTO||""))?"Symbol(src)_1."+S:"",E=P.toString,C=R.hasOwnProperty,T=R.toString,q=RegExp("^"+E.call(C).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),D=_.Symbol,J=U.splice,$=Z(_,"Map"),K=Z(Object,"create"),N=D?D.prototype:void 0,M=N?N.toString:void 0;function L(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function F(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function B(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function H(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function z(e,t){var n;t=function(e,t){if(Y(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||te(e))return!0;return b.test(e)||!y.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:Y(n=t)?n:Q(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[W(t[r++])];return r&&r==o?e:void 0}function V(e){if(!ee(e)||(t=e,A&&A in t))return!1;var t,n=function(e){var t=ee(e)?T.call(e):"";return t==g||t==v}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?q:I;return n.test(function(e){if(null!=e){try{return E.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function G(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function Z(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return V(n)?n:void 0}L.prototype.clear=function(){this.__data__=K?K(null):{}},L.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},L.prototype.get=function(e){var t=this.__data__;if(K){var n=t[e];return n===h?void 0:n}return C.call(t,e)?t[e]:void 0},L.prototype.has=function(e){var t=this.__data__;return K?void 0!==t[e]:C.call(t,e)},L.prototype.set=function(e,t){return this.__data__[e]=K&&void 0===t?h:t,this},F.prototype.clear=function(){this.__data__=[]},F.prototype.delete=function(e){var t=this.__data__,n=H(t,e);return!(n<0)&&(n==t.length-1?t.pop():J.call(t,n,1),!0)},F.prototype.get=function(e){var t=this.__data__,n=H(t,e);return n<0?void 0:t[n][1]},F.prototype.has=function(e){return H(this.__data__,e)>-1},F.prototype.set=function(e,t){var n=this.__data__,r=H(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},B.prototype.clear=function(){this.__data__={hash:new L,map:new($||F),string:new L}},B.prototype.delete=function(e){return G(this,e).delete(e)},B.prototype.get=function(e){return G(this,e).get(e)},B.prototype.has=function(e){return G(this,e).has(e)},B.prototype.set=function(e,t){return G(this,e).set(e,t),this};var Q=X((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(te(e))return M?M.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return w.test(e)&&n.push(""),e.replace(m,(function(e,t,r,o){n.push(r?o.replace(k,"$1"):t||e)})),n}));function W(e){if("string"==typeof e||te(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function X(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(X.Cache||B),n}X.Cache=B;var Y=Array.isArray;function ee(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function te(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==T.call(e)}var ne=function(e,t,n){var r=null==e?void 0:z(e,t);return void 0===r?n:r},re="/v1/auth/accesskey/exchange",oe="/v1/auth/otp/verify",ie="/v1/auth/otp/signin",ae="/v1/auth/otp/signup",se={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},ue="/v1/auth/otp/signup-in",ce="/v1/auth/magiclink/verify",le="/v1/auth/magiclink/signin",de="/v1/auth/magiclink/signup",pe={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},fe="/v1/auth/magiclink/signup-in",he="/v1/auth/enchantedlink/verify",ge="/v1/auth/enchantedlink/signin",ve="/v1/auth/enchantedlink/signup",ye="/v1/auth/enchantedlink/pending-session",be={email:"/v1/auth/enchantedlink/update/email"},we="/v1/auth/enchantedlink/signup-in",me="/v1/auth/oauth/authorize",ke="/v1/auth/oauth/exchange",Ie="/v1/auth/saml/authorize",Oe="/v1/auth/saml/exchange",je="/v1/auth/totp/verify",_e="/v1/auth/totp/signup",Se="/v1/auth/totp/update",Ue={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Pe={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},Re={start:"/v1/auth/webauthn/signup-in/start"},xe={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},Ae="/v1/auth/refresh",Ee="/v1/auth/logout",Ce="/v1/auth/logoutall",Te="/v1/auth/me",qe="/v1/flow/start",De="/v1/flow/next";const Je=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};var $e;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}($e||($e={}));const Ke=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,r])=>(e[n]=r,e)),e),e}),{})),Ne=e=>void 0===e?void 0:JSON.stringify(e),Me=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},Le=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:i})=>{const a=((e,t)=>{const n=t||fetch;return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>Je().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await(e.clone?e.clone().text():e.text());return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Je().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:u,body:c,headers:l,queryParams:d,method:p,token:f}=s,h=await a((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:u,baseUrl:e,queryParams:d}),{headers:Ke(Me(t,f),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"0.0.41-alpha.53"},(null==n?void 0:n.baseHeaders)||{},l),method:p,body:Ne(c),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&await o.afterRequest(r,null==h?void 0:h.clone()),h};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:$e.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:$e.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:$e.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:$e.delete,token:o}),hooks:o}};var Fe=429;function Be(e,t,n){var r;let o=He(e);t&&(o=null===(r=null==o?void 0:o.tenants)||void 0===r?void 0:r[t]);const i=null==o?void 0:o[n];return Array.isArray(i)?i:[]}function He(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return p(e)}function ze(e){const{exp:t}=He(e);return(new Date).getTime()/1e3>t}function Ve(e,t){return Be(e,t,"permissions")}function Ge(e,t){return Be(e,t,"roles")}const Ze=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Qe(e,t){var n;const r=await e,o={code:r.status,ok:r.ok,response:r},i=await r.clone().json();return r.ok?o.data=t?t(i):i:(o.error=i,r.status===Fe&&Object.assign(o.error,{retryAfter:Number.parseInt(null===(n=r.headers)||void 0===n?void 0:n.get("retry-after"))||0})),o}const We=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),Xe=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),Ye=e=>t=>e.test(t),et=Ye(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),tt=Ye(/^\+[1-9]{1}[0-9]{3,14}$/),nt=We(et,'"{val}" is not a valid email'),rt=We(tt,'"{val}" is not a valid phone number'),ot=We((1,e=>e.length>=1),"Minimum length is 1");const it=We((e=>"string"==typeof e),"Input is not a string"),at=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>Xe(...e).validate(n[t]))),t(...n)),st=e=>[it(`"${e}" must be a string`),ot(`"${e}" must not be empty`)],ut=e=>[it(`"${e}" must be a string`),nt()],ct=e=>[it(`"${e}" must be a string`),rt()],lt=at(st("accessKey")),dt=e=>({exchange:lt((t=>Qe(e.post(re,{},{token:t}))))});var pt,ft,ht,gt;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(pt||(pt={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(ft||(ft={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(ht||(ht={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(gt||(gt={}));const vt=st("loginId"),yt=st("uri"),bt=at(st("token")),wt=at(vt,yt),mt=at(st("pendingRef")),kt=at(vt,ut("email"),yt),It=e=>({verify:bt((t=>Qe(e.post(he,{token:t})))),signIn:wt(((t,n,r,o)=>Qe(e.post(Ze(ge,ft.email),{loginId:t,URI:n,loginOptions:r},{token:o})))),signUpOrIn:wt(((t,n)=>Qe(e.post(Ze(we,ft.email),{loginId:t,URI:n})))),signUp:wt(((t,n,r)=>Qe(e.post(Ze(ve,ft.email),{loginId:t,URI:n,user:r})))),waitForSession:mt(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let a;const s=setInterval((async()=>{const n=await e.post(ye,{pendingRef:t});n.ok&&(clearInterval(s),a&&clearTimeout(a),r(Qe(Promise.resolve(n))))}),o);a=setTimeout((()=>{r({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(s)}),i)})))),update:{email:kt(((t,n,r,o)=>Qe(e.post(be.email,{loginId:t,email:n,URI:r},{token:o}))))}}),Ot=at(st("flowId")),jt=at(st("executionId"),st("stepId"),st("interactionId")),_t=e=>({start:Ot(((t,n,r,o,i)=>Qe(e.post(qe,{flowId:t,options:n,conditionInteractionId:r,interactionId:o,input:i})))),next:jt(((t,n,r,o)=>Qe(e.post(De,{executionId:t,stepId:n,interactionId:r,input:o}))))}),St=st("loginId"),Ut=st("uri"),Pt=at(st("token")),Rt=at(St,Ut),xt=at(St,ct("phone"),Ut),At=at(St,ut("email"),Ut),Et=e=>({verify:Pt((t=>Qe(e.post(ce,{token:t})))),signIn:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Rt(((t,r,o,i)=>Qe(e.post(Ze(le,n),{loginId:t,URI:r,loginOptions:o},{token:i}))))})),{}),signUp:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Rt(((t,r,o)=>Qe(e.post(Ze(de,n),{loginId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Rt(((t,r)=>Qe(e.post(Ze(fe,n),{loginId:t,URI:r}))))})),{}),update:{email:At(((t,n,r,o)=>Qe(e.post(pe.email,{loginId:t,email:n,URI:r},{token:o})))),phone:Object.keys(pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:xt(((t,r,o,i)=>Qe(e.post(Ze(pe.phone,n),{loginId:t,phone:r,URI:o},{token:i}))))})),{})}});var Ct;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin"}(Ct||(Ct={}));const Tt=at(st("code")),qt=e=>({start:Object.keys(Ct).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={},o,i)=>{const a=await e.post(me,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i});if(!r||!a.ok)return Qe(Promise.resolve(a));const{url:s}=await a.json();window.location.href=s}})),{}),exchange:Tt((t=>Qe(e.post(ke,{code:t}))))});var Dt;!function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(Dt||(Dt={}));const Jt=st("loginId"),$t=at(Jt,st("code")),Kt=at(Jt),Nt=at(Jt,ct("phone")),Mt=at(Jt,ut("email")),Lt=e=>({verify:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:$t(((t,r)=>Qe(e.post(Ze(oe,n),{code:r,loginId:t}))))})),{}),signIn:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Kt(((t,r,o)=>Qe(e.post(Ze(ie,n),{loginId:t,loginOptions:r},{token:o}))))})),{}),signUp:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Kt(((t,r)=>Qe(e.post(Ze(ae,n),{loginId:t,user:r}))))})),{}),signUpOrIn:Object.keys(ft).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Kt((t=>Qe(e.post(Ze(ue,n),{loginId:t}))))})),{}),update:{email:Mt(((t,n,r)=>Qe(e.post(se.email,{loginId:t,email:n},{token:r})))),phone:Object.keys(pt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Nt(((t,r,o)=>Qe(e.post(Ze(se.phone,n),{loginId:t,phone:r},{token:o}))))})),{})}}),Ft=at(st("tenant")),Bt=at(st("code")),Ht=e=>({start:Ft((async(t,n,{redirect:r=!1}={},o,i)=>{const a=await e.post(Ie,o||{},{queryParams:{tenant:t,redirectURL:n},token:i});if(!r||!a.ok)return Qe(Promise.resolve(a));const{url:s}=await a.json();window.location.href=s})),exchange:Bt((t=>Qe(e.post(Oe,{code:t}))))}),zt=st("loginId"),Vt=at(zt,st("code")),Gt=at(zt),Zt=at(zt),Qt=e=>({signUp:Gt(((t,n)=>Qe(e.post(_e,{loginId:t,user:n})))),verify:Vt(((t,n,r,o)=>Qe(e.post(je,{loginId:t,code:n,loginOptions:r},{token:o})))),update:Zt(((t,n)=>Qe(e.post(Se,{loginId:t},{token:n}))))}),Wt=[it('"loginId" must be a string')],Xt=st("loginId"),Yt=st("origin"),en=at(Xt,Yt,st("name")),tn=at(Xt,Yt),nn=at(Wt,Yt),rn=at(Xt,Yt,st("token")),on=at(st("transactionId"),st("response")),an=e=>({signUp:{start:en(((t,n,r)=>Qe(e.post(Ue.start,{user:{loginId:t,name:r},origin:n})))),finish:on(((t,n)=>Qe(e.post(Ue.finish,{transactionId:t,response:n}))))},signIn:{start:nn(((t,n,r,o)=>Qe(e.post(Pe.start,{loginId:t,origin:n,loginOptions:r},{token:o})))),finish:on(((t,n)=>Qe(e.post(Pe.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:tn(((t,n)=>Qe(e.post(Re.start,{loginId:t,origin:n}))))},update:{start:rn(((t,n,r)=>Qe(e.post(xe.start,{loginId:t,origin:n},{token:r})))),finish:on(((t,n)=>Qe(e.post(xe.finish,{transactionId:t,response:n}))))}}),sn=at(st("token"));var un,cn=at([("projectId",un=st("projectId"),We(((e,t)=>e=>Xe(...t).validate(ne(e,"projectId")))(0,un))())])((e=>{var t,n;const r=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),o=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o,baseHeaders:i={}})=>{return a=Le({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o,baseConfig:{baseHeaders:i}}),{accessKey:dt(a),otp:Lt(a),magicLink:Et(a),enchantedLink:It(a),oauth:qt(a),saml:Ht(a),totp:Qt(a),webauthn:an(a),flow:_t(a),refresh:e=>Qe(a.post(Ae,{},{token:e})),logout:e=>Qe(a.post(Ee,{},{token:e})),logoutAll:e=>Qe(a.post(Ce,{},{token:e})),me:e=>Qe(a.get(Te,{token:e})),isJwtExpired:sn(ze),getJwtPermissions:sn(Ve),getJwtRoles:sn(Ge),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==r?void 0:r.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(await Promise.allSettled(null==o?void 0:o.map((e=>e(t,null==n?void 0:n.clone()))))).forEach((t=>{var n;return"rejected"===t.status&&(null===(n=e.logger)||void 0===n?void 0:n.error(t.reason))}))}}}))}));const ln=(e,t,n)=>(t.forEach((t=>{const r=t.split(".");let o=r.shift(),i=e;for(;r.length>0;){if(i=i[o],!o||!i)throw Error(`Invalid path "${t}", "${o}" is missing or has no value`);o=r.shift()}if("function"!=typeof i[o])throw Error(`"${t}" is not a function`);const a=i[o];i[o]=n(a)})),e);var dn=Object.assign(cn,{DeliveryMethods:ft});const pn="undefined"!=typeof window,fn=pn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com";function hn(e,t){var n=[];return function(e,t){var n,r,o=(r=function(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),o=0;for(t=0;t<n;t++)for(var i=arguments[t],a=0,s=i.length;a<s;a++,o++)r[o]=i[a];return r}(e),{current:function(){return r[0]},postpone:function(){var e=r.shift();void 0!==e&&r.push(e)},exclude:function(){r.shift()}}),i=(100,3e3,n=0,function(){return Math.random()*Math.min(3e3,100*Math.pow(2,n++))}),a=o.current();if(void 0===a)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var s=function(e,n){return t(e).catch((function(e){if(n+1>=5)throw e;!function(e){if(!(e instanceof Error))return!1;var t=e.message;return"Blocked by CSP"===t||"9319"===t}(e)?o.postpone():o.exclude();var t,r=o.current();if(void 0===r)throw e;return(t=i(),new Promise((function(e){return setTimeout(e,t)}))).then((function(){return s(r,n+1)}))}))};return s(a,0)}(e,(function(e){var r=new Date,o=function(){return n.push({url:e,startedAt:r,finishedAt:new Date})},i=t(e);return i.then(o,o),i})).then((function(e){return[e,{attempts:n}]}))}var gn="Failed to load the JS script of the agent";function vn(e){var t;e.scriptUrlPattern;var n=e.token,r=e.apiKey,o=void 0===r?n:r,i=u(e,["scriptUrlPattern","token","apiKey"]),a=null!==(t=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==t?t:"https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";return Promise.resolve().then((function(){if(!o||"string"!=typeof o)throw new Error("API key required");return hn(function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.8.1"):e}))}(String(e),t)}))}(a,o),yn).catch(wn)})).then((function(e){var t=e[0],n=e[1];return t.load(s(s({},i),{ldi:n}))}))}function yn(e){return function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,u())};i.addEventListener(a,s);var u=function(){return i.removeEventListener(a,s)};return Promise.resolve().then(t).then((function(e){return u(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(u(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(gn))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)})).then(bn)}function bn(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error("9319");return n}function wn(e){throw e instanceof Error&&"9319"===e.message?new Error(gn):e}const mn=(e="",t="")=>({vsid:e,vrid:t}),kn=(e=!1)=>{const t=localStorage.getItem("fp");if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},In=async e=>{try{if(kn())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=vn({apiKey:e,endpoint:fn}),r=await n,{requestId:o}=await r.get({linkedId:t});(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(mn(t,o))}catch(e){global.FB_DEBUG&&console.error(e)}},On=e=>(e.body&&(e.body.fpData=kn(!0)||mn()),e),jn="dls_last_user_login_id",_n="dls_last_user_display_name",Sn=()=>i(jn),Un=()=>i(_n),Pn=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,r={}]=t,o=Sn(),i=Un();o&&(null!==(n=r.lastAuth)&&void 0!==n||(r.lastAuth={}),r.lastAuth.loginId=o,r.lastAuth.name=i);return await e(...t)},Rn=e=>async(...t)=>{const n=await e(...t);return a(jn),a(_n),n};function xn(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}
2
2
  /*! js-cookie v3.0.1 | MIT */
3
- function Xt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}Ht=new WeakMap,Wt=new WeakMap,Gt=new WeakMap,Ft=new WeakSet,Zt=function(e){!!n(this,Wt,"f")[e]&&delete n(this,Wt,"f")[e]};var Yt=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=Xt({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in o)o[a]&&(i+="; "+a,!0!==o[a]&&(i+="="+o[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var i=n[o].split("="),a=i.slice(1).join("=");try{var s=decodeURIComponent(i[0]);if(r[s]=t.read(a,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Xt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Xt({},this.attributes,t))},withConverter:function(t){return e(Xt({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const en="DSR";let tn=[];function nn(e,t,n){const r=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(r){let t;for(;t=tn.pop();)clearTimeout(t);const o=r.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),o);tn.push(i)}}function rn(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:r}){e&&Yt.set("DS",e,{path:t,domain:n,expires:r,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem(en,e)}(t)}function on(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem(en):""}async function an(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),n.publicKey.user.id=cn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{attestationObject:un(r.response.attestationObject),clientDataJSON:un(r.response.clientDataJSON)})}));var r}async function sn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.get(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{authenticatorData:un(r.response.authenticatorData),clientDataJSON:un(r.response.clientDataJSON),signature:un(r.response.signature),userHandle:r.response.userHandle?un(r.response.userHandle):void 0})}));var r}function cn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function un(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}return e=>{var{autoRefresh:n=!0,persistTokens:r=!0}=e,o=t(e,["autoRefresh","persistTokens"]);zt(o.fpKey).get().catch((()=>null));const i=o;let a,s;const c=new Qt(""),u=new Qt({});i.hooks={beforeRequest:e=>null==a?void 0:a(e),afterRequest:(e,t)=>null==s?void 0:s(e,t)};const l=$t(i),p=Object.assign(Object.assign({},l),{webauthn:(d=l,{async signUp(e,t){const n=await d.webauthn.signUp.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(e){const t=await d.webauthn.signIn.start(e,window.location.origin),n=await sn(t.data.options);return await d.webauthn.signIn.finish(t.data.transactionId,n)},async update(e,t){const n=await d.webauthn.update.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:an,get:sn}}),onSessionTokenChange:c.subscribe,onUserChange:u.subscribe});var d;return n&&(p.logout=(...e)=>{const t=on(),n=[(null==e?void 0:e.shift())||t,...e],r=l.logout(...n);return localStorage&&localStorage.removeItem(en),Yt.remove("DS"),r}),a=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{[Jt]:sessionStorage.getItem(Jt)||"",[Mt]:sessionStorage.getItem(Mt)||""})),!e.token&&r&&(e.token=on()),e},(n||r)&&(s=(e,o)=>{!async function(e,n,r,o){try{const i=await(null==n?void 0:n.json());if(i){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:a,refreshJwt:s,user:c}=n,u=t(n,["sessionJwt","refreshJwt","user"]);o.persistTokens&&rn(a,s,u),r.sessionToken.update(a),r.user.update(c),a&&s&&o.autoRefresh&&nn(e,a,s)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,o,{sessionToken:c,user:u},{autoRefresh:n,persistTokens:r})}),n&&p.refresh(),p}}));
3
+ function An(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var En=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=An({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in o)o[a]&&(i+="; "+a,!0!==o[a]&&(i+="="+o[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var i=n[o].split("="),a=i.slice(1).join("=");try{var s=decodeURIComponent(i[0]);if(r[s]=t.read(a,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",An({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,An({},this.attributes,t))},withConverter:function(t){return e(An({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const Cn="DS",Tn="DSR";const qn=(e={},t)=>{var{refreshJwt:n,sessionJwt:r}=e,i=u(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),n&&o(Tn,n),r&&(t?function(e,t,{cookiePath:n,cookieDomain:r,cookieExpiration:o}){if(t){const i=new Date(1e3*o);En.set(e,t,{path:n,domain:r,expires:i,sameSite:"None",secure:!0})}}(Cn,r,i):o(Cn,r))};function Dn(){return i(Tn)||""}function Jn(){return En.get(Cn)||i(Cn)||""}function $n(){a(Tn),a(Cn),En.remove(Cn)}const Kn=e=>Object.assign(e,{token:e.token||Dn()}),Nn=e=>async(...t)=>{const n=await e(...t);return $n(),n};async function Mn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Vn(n.publicKey.challenge),n.publicKey.user.id=Vn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=Vn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify({id:r.id,rawId:Gn(r.rawId),type:r.type,response:{attestationObject:Gn(r.response.attestationObject),clientDataJSON:Gn(r.response.clientDataJSON)}});var r}async function Ln(e){const t=Hn(e);return zn(await navigator.credentials.get(t))}async function Fn(e,t){const n=Hn(e);n.signal=t.signal,n.mediation="conditional";return zn(await navigator.credentials.get(n))}async function Bn(e=!1){if(!pn)return Promise.resolve(!1);const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function Hn(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Vn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=Vn(e.id)})),n}function zn(e){return JSON.stringify({id:e.id,rawId:Gn(e.rawId),type:e.type,response:{authenticatorData:Gn(e.response.authenticatorData),clientDataJSON:Gn(e.response.clientDataJSON),signature:Gn(e.response.signature),userHandle:e.response.userHandle?Gn(e.response.userHandle):void 0}})}function Vn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Gn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Zn,Qn=(Zn=e=>({async signUp(t,n){const r=await e.webauthn.signUp.start(t,window.location.origin,n);if(!r.ok)return r;const o=await Mn(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,o)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const r=await Ln(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,r)},async signUpOrIn(t){var n;const r=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!r.ok)return r;if(null===(n=r.data)||void 0===n?void 0:n.create){const t=await Mn(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,t)}{const t=await Ln(r.data.options);return await e.webauthn.signIn.finish(r.data.transactionId,t)}},async update(t,n){const r=await e.webauthn.update.start(t,window.location.origin,n);if(!r.ok)return r;const o=await Mn(r.data.options);return await e.webauthn.update.finish(r.data.transactionId,o)},helpers:{create:Mn,get:Ln,isSupported:Bn,conditional:Fn}}),(...e)=>{const t=Zn(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t}),Wn=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await Bn(),r=Object.assign(Object.assign({},t[1]),{redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:n}});return t[1]=r,e.flow.start(...t)}});const Xn=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((t=>n=>{var{fpKey:r,fpLoad:o}=n,i=u(n,["fpKey","fpLoad"]);return r?(pn?o&&In(r).catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server"),t(e(i,{beforeRequest:On}))):t(Object.assign({},i))}),(n=>r=>{var o=u(r,["autoRefresh"]);const{clearAllTimers:i,setTimer:a}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})(),s=n(e(o,{afterRequest:async(e,n)=>{const{refreshJwt:r,sessionJwt:o}=await t(n);if(401===(null==n?void 0:n.status))i();else if(o){const e=((u=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o))?u.getTime()-(new Date).getTime():0)-2e4;i(),a((()=>s.refresh(r)),e)}var u}}));return ln(s,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return i(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.30"},t.baseHeaders)}))),(r=>o=>{const i=xn(),a=xn(),s=r(e(o,{afterRequest:async(e,r)=>{if(401===(null==r?void 0:r.status))i.pub(null),a.pub(null);else{const e=await n(r);e&&a.pub(e);const{sessionJwt:o}=await t(r);o&&i.pub(o)}}})),u=ln(s,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return i.pub(null),a.pub(null),n}));return Object.assign(u,{onSessionTokenChange:i.sub,onUserChange:a.sub})}),(t=>r=>{const i=t(e(r,{afterRequest:async(e,t)=>{var r;const i=await n(t),a=null===(r=null==i?void 0:i.loginIds)||void 0===r?void 0:r[0],s=null==i?void 0:i.name;a&&((e=>{o(jn,e)})(a),(e=>{o(_n,e)})(s))}}));let a=ln(i,["flow.start"],Pn);return a=ln(a,["logout","logoutAll"],Rn),Object.assign(a,{getLastUserLoginId:Sn,getLastUserDisplayName:Un})}),(n=>r=>{var{persistTokens:o,sessionTokenViaCookie:i}=r,a=u(r,["persistTokens","sessionTokenViaCookie"]);if(!o||!pn)return o&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),n(a);const s=n(e(a,{beforeRequest:Kn,afterRequest:async(e,n)=>{401===(null==n?void 0:n.status)?$n():qn(await t(n),i)}})),c=ln(s,["logout","logoutAll"],Nn);return Object.assign(c,{getRefreshToken:Dn,getSessionToken:Jn})}))(((...e)=>{const t=dn(...e);return Object.assign(Object.assign({},t),{flow:Wn(t),webauthn:Qn(t)})}));return Xn}));
4
4
  //# sourceMappingURL=index.umd.js.map