@passflow/core 0.20.0 → 0.20.1

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.
Files changed (128) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +5944 -0
  4. package/dist/index.d.ts +5944 -0
  5. package/dist/index.mjs +1 -1
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +15 -7
  8. package/dist/lib/api/app.d.ts +0 -11
  9. package/dist/lib/api/app.d.ts.map +0 -1
  10. package/dist/lib/api/auth.d.ts +0 -42
  11. package/dist/lib/api/auth.d.ts.map +0 -1
  12. package/dist/lib/api/axios-client.d.ts +0 -109
  13. package/dist/lib/api/axios-client.d.ts.map +0 -1
  14. package/dist/lib/api/cli-auth.d.ts +0 -12
  15. package/dist/lib/api/cli-auth.d.ts.map +0 -1
  16. package/dist/lib/api/index.d.ts +0 -11
  17. package/dist/lib/api/index.d.ts.map +0 -1
  18. package/dist/lib/api/invitation.d.ts +0 -80
  19. package/dist/lib/api/invitation.d.ts.map +0 -1
  20. package/dist/lib/api/model.d.ts +0 -844
  21. package/dist/lib/api/model.d.ts.map +0 -1
  22. package/dist/lib/api/setting.d.ts +0 -13
  23. package/dist/lib/api/setting.d.ts.map +0 -1
  24. package/dist/lib/api/tenant.d.ts +0 -216
  25. package/dist/lib/api/tenant.d.ts.map +0 -1
  26. package/dist/lib/api/two-factor.d.ts +0 -137
  27. package/dist/lib/api/two-factor.d.ts.map +0 -1
  28. package/dist/lib/api/upgrade.d.ts +0 -39
  29. package/dist/lib/api/upgrade.d.ts.map +0 -1
  30. package/dist/lib/api/user.d.ts +0 -22
  31. package/dist/lib/api/user.d.ts.map +0 -1
  32. package/dist/lib/constants/index.d.ts +0 -33
  33. package/dist/lib/constants/index.d.ts.map +0 -1
  34. package/dist/lib/device/index.d.ts +0 -17
  35. package/dist/lib/device/index.d.ts.map +0 -1
  36. package/dist/lib/index.d.ts +0 -22
  37. package/dist/lib/index.d.ts.map +0 -1
  38. package/dist/lib/interceptors/fetch-registry.d.ts +0 -96
  39. package/dist/lib/interceptors/fetch-registry.d.ts.map +0 -1
  40. package/dist/lib/m2m/client.d.ts +0 -196
  41. package/dist/lib/m2m/client.d.ts.map +0 -1
  42. package/dist/lib/m2m/errors.d.ts +0 -107
  43. package/dist/lib/m2m/errors.d.ts.map +0 -1
  44. package/dist/lib/m2m/index.d.ts +0 -27
  45. package/dist/lib/m2m/index.d.ts.map +0 -1
  46. package/dist/lib/m2m/types.d.ts +0 -217
  47. package/dist/lib/m2m/types.d.ts.map +0 -1
  48. package/dist/lib/passflow.d.ts +0 -1224
  49. package/dist/lib/passflow.d.ts.map +0 -1
  50. package/dist/lib/pkce.d.ts +0 -13
  51. package/dist/lib/pkce.d.ts.map +0 -1
  52. package/dist/lib/platform/index.d.ts +0 -4
  53. package/dist/lib/platform/index.d.ts.map +0 -1
  54. package/dist/lib/platform/types.d.ts +0 -206
  55. package/dist/lib/platform/types.d.ts.map +0 -1
  56. package/dist/lib/platform/web-adapter.d.ts +0 -104
  57. package/dist/lib/platform/web-adapter.d.ts.map +0 -1
  58. package/dist/lib/services/auth-service.d.ts +0 -197
  59. package/dist/lib/services/auth-service.d.ts.map +0 -1
  60. package/dist/lib/services/index.d.ts +0 -8
  61. package/dist/lib/services/index.d.ts.map +0 -1
  62. package/dist/lib/services/invitation-service.d.ts +0 -44
  63. package/dist/lib/services/invitation-service.d.ts.map +0 -1
  64. package/dist/lib/services/logger.d.ts +0 -24
  65. package/dist/lib/services/logger.d.ts.map +0 -1
  66. package/dist/lib/services/tenant-service.d.ts +0 -200
  67. package/dist/lib/services/tenant-service.d.ts.map +0 -1
  68. package/dist/lib/services/tenant-user-membership.d.ts +0 -76
  69. package/dist/lib/services/tenant-user-membership.d.ts.map +0 -1
  70. package/dist/lib/services/token-cache-service.d.ts +0 -36
  71. package/dist/lib/services/token-cache-service.d.ts.map +0 -1
  72. package/dist/lib/services/two-factor-service.d.ts +0 -193
  73. package/dist/lib/services/two-factor-service.d.ts.map +0 -1
  74. package/dist/lib/services/user-service.d.ts +0 -41
  75. package/dist/lib/services/user-service.d.ts.map +0 -1
  76. package/dist/lib/storage/index.d.ts +0 -106
  77. package/dist/lib/storage/index.d.ts.map +0 -1
  78. package/dist/lib/store.d.ts +0 -175
  79. package/dist/lib/store.d.ts.map +0 -1
  80. package/dist/lib/token/delivery-manager.d.ts +0 -121
  81. package/dist/lib/token/delivery-manager.d.ts.map +0 -1
  82. package/dist/lib/token/index.d.ts +0 -4
  83. package/dist/lib/token/index.d.ts.map +0 -1
  84. package/dist/lib/token/membership.d.ts +0 -37
  85. package/dist/lib/token/membership.d.ts.map +0 -1
  86. package/dist/lib/token/service.d.ts +0 -47
  87. package/dist/lib/token/service.d.ts.map +0 -1
  88. package/dist/lib/token/token.d.ts +0 -55
  89. package/dist/lib/token/token.d.ts.map +0 -1
  90. package/dist/lib/types/index.d.ts +0 -24
  91. package/dist/lib/types/index.d.ts.map +0 -1
  92. package/dist/lib/upgrade/acr.d.ts +0 -85
  93. package/dist/lib/upgrade/acr.d.ts.map +0 -1
  94. package/dist/lib/upgrade/axios-adapter.d.ts +0 -81
  95. package/dist/lib/upgrade/axios-adapter.d.ts.map +0 -1
  96. package/dist/lib/upgrade/challenge.d.ts +0 -217
  97. package/dist/lib/upgrade/challenge.d.ts.map +0 -1
  98. package/dist/lib/upgrade/client.d.ts +0 -29
  99. package/dist/lib/upgrade/client.d.ts.map +0 -1
  100. package/dist/lib/upgrade/controller.d.ts +0 -435
  101. package/dist/lib/upgrade/controller.d.ts.map +0 -1
  102. package/dist/lib/upgrade/core.d.ts +0 -353
  103. package/dist/lib/upgrade/core.d.ts.map +0 -1
  104. package/dist/lib/upgrade/errors.d.ts +0 -208
  105. package/dist/lib/upgrade/errors.d.ts.map +0 -1
  106. package/dist/lib/upgrade/facade.d.ts +0 -188
  107. package/dist/lib/upgrade/facade.d.ts.map +0 -1
  108. package/dist/lib/upgrade/factors.d.ts +0 -97
  109. package/dist/lib/upgrade/factors.d.ts.map +0 -1
  110. package/dist/lib/upgrade/fetch-adapter.d.ts +0 -30
  111. package/dist/lib/upgrade/fetch-adapter.d.ts.map +0 -1
  112. package/dist/lib/upgrade/index.d.ts +0 -17
  113. package/dist/lib/upgrade/index.d.ts.map +0 -1
  114. package/dist/lib/upgrade/markers.d.ts +0 -64
  115. package/dist/lib/upgrade/markers.d.ts.map +0 -1
  116. package/dist/lib/upgrade/replay.d.ts +0 -132
  117. package/dist/lib/upgrade/replay.d.ts.map +0 -1
  118. package/dist/lib/upgrade/select.d.ts +0 -48
  119. package/dist/lib/upgrade/select.d.ts.map +0 -1
  120. package/dist/lib/upgrade/session.d.ts +0 -72
  121. package/dist/lib/upgrade/session.d.ts.map +0 -1
  122. package/dist/lib/upgrade/snapshot.d.ts +0 -196
  123. package/dist/lib/upgrade/snapshot.d.ts.map +0 -1
  124. package/dist/lib/upgrade/transport.d.ts +0 -69
  125. package/dist/lib/upgrade/transport.d.ts.map +0 -1
  126. package/dist/lib/utils/validation.d.ts +0 -54
  127. package/dist/lib/utils/validation.d.ts.map +0 -1
  128. package/dist/tsconfig.build.tsbuildinfo +0 -1
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("axios");c=s(c,1);let l=require("@simplewebauthn/browser");var u=`0.20.0`,d=`X-Passflow-Clientid`,f=`Authorization`,p=`X-Passflow-DeviceId`,m=`X-Passflow-DeviceType`,ee=u,te=[`id`,`offline`,`openid`],ne=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],re=`https://auth.passflow.cloud`,ie=`default`,ae=500,oe=600,se=100,ce=6e4,le=30,ue=3,de=30,fe=200,h=[];for(let e=0;e<256;++e)h.push((e+256).toString(16).slice(1));function pe(e,t=0){return(h[e[t+0]]+h[e[t+1]]+h[e[t+2]]+h[e[t+3]]+`-`+h[e[t+4]]+h[e[t+5]]+`-`+h[e[t+6]]+h[e[t+7]]+`-`+h[e[t+8]]+h[e[t+9]]+`-`+h[e[t+10]]+h[e[t+11]]+h[e[t+12]]+h[e[t+13]]+h[e[t+14]]+h[e[t+15]]).toLowerCase()}var me=new Uint8Array(16);function he(){return crypto.getRandomValues(me)}function ge(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():_e(e,t,n)}function _e(e,t,n){e=e||{};let r=e.random??e.rng?.()??he();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return pe(r)}var ve=e=>{let t=[],n;for(n in e){let r=e[n];if(r===void 0)continue;let i={tenant:{id:r.tenant_id,name:r.tenant_name}};i.groups=r.groups?Object.keys(r.groups).map(e=>{let t=r.groups[e]||[];return{group:{id:e,name:r.group_names?.[e]??`unknown`},roles:t}}):[],i.tenantRoles=i.groups?.find(e=>e.group.id===r.root_group_id),t.push(i)}return{raw:e,tenants:t}};function ye(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}var be=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=_(t);return!n||g(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return _(t)}};function g(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function _(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=ye(n+`=`.repeat((4-n.length%4)%4)),i=decodeURIComponent(r.split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),a=JSON.parse(i);return a.membership=a.passflow_tm&&a.type!==`invite`?ve(a.passflow_tm):void 0,a}var v=function(e){return e.id_token=`id_token`,e.access_token=`access`,e.refresh_token=`refresh`,e.invite_token=`invite`,e.reset_token=`reset`,e.web_cookie=`web-cookie`,e.management=`management`,e.signin=`signin`,e.actor=`actor`,e.two_factor=`2fa`,e}({}),y=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),xe=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),Se=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.STORAGE_PREFIX=`passflow_`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.SESSION_STATE_KEY=`${this.STORAGE_PREFIX}session_state`,this.loadPersistedMode(),this.loadPersistedSessionState()}setMode(e){this.mode=e,this.isInitializedFlag=!0,this.persistMode()}getMode(){return this.mode}isCookieMode(){return this.mode===`cookie`}isJsonMode(){return this.mode===`json_body`}isMobileMode(){return this.mode===`mobile`}isBFFMode(){return this.mode===`bff`}isInitialized(){return this.isInitializedFlag}setSessionValid(){this.sessionState=`valid`,this.persistSessionState()}setSessionInvalid(){this.sessionState=`invalid`,this.persistSessionState()}setSessionUnknown(){this.sessionState=`unknown`,this.persistSessionState()}isSessionValid(){return this.sessionState===`valid`}isSessionUnknown(){return this.sessionState===`unknown`}isSessionInvalid(){return this.sessionState===`invalid`}getSessionState(){return this.sessionState}reset(){this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.clearPersistedMode(),this.clearPersistedSessionState()}loadPersistedMode(){try{let e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(y).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(xe).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){try{this.storageManager.storage.setItem(this.DELIVERY_MODE_KEY,this.mode)}catch{}}persistSessionState(){try{this.storageManager.storage.setItem(this.SESSION_STATE_KEY,this.sessionState)}catch{}}clearPersistedMode(){try{this.storageManager.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.SESSION_STATE_KEY)}catch{}}},Ce=class{constructor({storage:e,prefix:t}={}){this.keyStoragePrefix=``,this.scopes=`${this.keyStoragePrefix}tokens_scopes`,this.deviceId=`${this.keyStoragePrefix}passflowDeviceId`,this.invitationToken=`${this.keyStoragePrefix}passflowInvitationToken`,this.previousRedirectUrl=`${this.keyStoragePrefix}passflowPreviousRedirectUrl`,this.STORAGE_PREFIX=`passflow_`,this.ID_TOKEN_KEY=`${this.STORAGE_PREFIX}id_token`,this.CSRF_TOKEN_KEY=`${this.STORAGE_PREFIX}csrf_token`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``}saveTokens(e,t){let{id_token:n,access_token:r,refresh_token:i,scopes:a}=e;t===y.Cookie||t===y.BFF?n&&this.storage.setItem(this.ID_TOKEN_KEY,n):(n&&this.storage.setItem(this.getKeyForTokenType(v.id_token),n),r&&this.storage.setItem(this.getKeyForTokenType(v.access_token),r),i&&this.storage.setItem(this.getKeyForTokenType(v.refresh_token),i),a&&this.storage.setItem(this.scopes,a.join(`,`)))}getToken(e){let t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){let e=this.getDeliveryMode();if(e===y.Cookie||e===y.BFF){let e=this.storage.getItem(this.ID_TOKEN_KEY);return e?{id_token:e}:void 0}let t=this.storage.getItem(this.getKeyForTokenType(v.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(v.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(v.refresh_token))??void 0,scopes:this.storage.getItem(this.scopes)?.split(`,`)??void 0}}getScopes(){return this.storage.getItem(this.scopes)?.split(`,`)??void 0}hasJsonModeTokens(){return!!this.storage.getItem(this.getKeyForTokenType(v.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(v.id_token)),this.storage.removeItem(this.getKeyForTokenType(v.access_token)),this.storage.removeItem(this.getKeyForTokenType(v.refresh_token)),this.storage.removeItem(this.scopes),this.clearIdToken(),this.clearDeliveryMode(),this.clearCsrfToken()}getDeviceId(){return this.storage.getItem(this.deviceId)??void 0}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.storage.removeItem(this.deviceId)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.storage.getItem(this.invitationToken)??void 0}deleteInvitationToken(){this.storage.removeItem(this.invitationToken)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.storage.getItem(this.previousRedirectUrl)??void 0}deletePreviousRedirectUrl(){this.storage.removeItem(this.previousRedirectUrl)}setDeliveryMode(e){try{this.storage.setItem(this.DELIVERY_MODE_KEY,e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(y).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}getIdToken(){try{return this.storage.getItem(this.ID_TOKEN_KEY)??void 0}catch{return}}setIdToken(e){try{this.storage.setItem(this.ID_TOKEN_KEY,e)}catch{}}clearIdToken(){try{this.storage.removeItem(this.ID_TOKEN_KEY)}catch{}}getCsrfToken(){try{return this.storage.getItem(this.CSRF_TOKEN_KEY)??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.CSRF_TOKEN_KEY,e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.CSRF_TOKEN_KEY)}catch{}}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},we=class{constructor(e){this.storageManager=e??new Ce}getDeviceId(){let e=this.storageManager.getDeviceId();if(!e){let e=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(e),e}return e}generateUniqueDeviceId(){return ge()}},Te=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},Ee=class{constructor(){this.passkeys={startRegistration:e=>(0,l.startRegistration)({optionsJSON:e}),startAuthentication:e=>(0,l.startAuthentication)({optionsJSON:e})}}get storage(){return typeof localStorage>`u`?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}getCurrentUrl(){return typeof window>`u`?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window<`u`&&window.history.replaceState({},document.title,e)}navigateTo(e){typeof window<`u`&&(window.location.href=e)}onForeground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden||e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBackground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden&&e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBeforeUnload(e){return typeof window>`u`?()=>{}:(window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e))}isInForeground(){return typeof document>`u`||!document.hidden}openAuthUrl(e,t={}){let n=t.mode??`popup`;if(n===`redirect`)return window.location.href=e,new Promise(()=>{});if(n===`deeplink`)return Promise.reject(Error(`openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.`));let r=t.width??500,i=t.height??600,a=t.expectedReturnOrigin??window.location.origin,o=window.open(e,`_blank`,`width=${r},height=${i}`);return o?new Promise((e,t)=>{let n=Date.now(),r=setInterval(()=>{if(o.closed)clearInterval(r),t(new Te);else if(Date.now()-n>6e4)clearInterval(r),o.close(),t(Error(`Authentication popup timed out`));else try{if(o.location.href.startsWith(a)){let t=o.location.search,n=o.location.hash;clearInterval(r),o.close(),e({callbackSearch:t,callbackHash:n})}}catch{}},100)}):(window.location.href=e,new Promise(()=>{}))}btoa(e){return btoa(e)}atob(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}cookiesSupported(){if(typeof document>`u`)return!1;try{document.cookie=`passflow_test=1; SameSite=Lax`;let e=document.cookie.indexOf(`passflow_test=1`)!==-1;return document.cookie=`passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC`,e}catch{return!1}}getDeviceType(){return`web`}},b=new Ee,De=/^[0-9]+$/,Oe=Object.freeze({unorderable:!1,zero:!1}),ke=e=>De.test(e)?Number.parseInt(e,10):void 0,Ae=e=>{if(!e)return Oe;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return Oe;let n=[];for(let e of t){let t=ke(e);t!==void 0&&n.push(t)}if(n.length===0)return{raw:e,unorderable:!0,zero:!1};let r=Math.min(...n);return r===0?{raw:e,unorderable:!1,zero:!0}:{level:r,raw:e,unorderable:!1,zero:!1}},je=e=>Ae(e).level,Me=`insufficient_user_authentication`,Ne=`upgrade_required`,Pe=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,Fe=e=>e.replace(/\\(.)/g,`$1`),Ie=e=>{let t={};Pe.lastIndex=0;for(let n of e.matchAll(Pe)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:Fe(r)}return t},Le=e=>{if(e==null||e===``)return{kind:`absent`};let t=typeof e==`number`?e:Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?{kind:`valid`,value:t}:{kind:`invalid`,raw:e}},Re=e=>{let t=Le(e);return t.kind===`valid`?t.value:void 0},ze=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=Ie(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:Re(n.max_age),status:t}},Be=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error===`upgrade_required`)return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:Re(n.max_age),status:t}},Ve=(e,t,n)=>({channel:e,acr:Ae(t.acrValues),maxAge:Le(n),raw:t.acrValues}),He=e=>e?Ie(e):{},Ue=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=ze(i,n),o=r?void 0:Be(e.body,n),s=[],c=(e,t)=>{s.push({status:n,url:``,reason:e,...t?{detail:t}:{}})};if(!a&&!o)return r&&c(`header-required-but-absent`,i?{header:i}:void 0),{diagnostics:s};let l=[];if(a&&l.push(Ve(`header`,a,He(i).max_age)),o){let t=e.body;l.push(Ve(`body`,o,t?.max_age))}let u=e=>e;for(let e of l)e.acr.unorderable&&c(`channels-unorderable`,{[u(e.channel)]:e.raw}),e.acr.zero&&c(`zero-constraint-ignored`,{field:`acr_values`,[u(e.channel)]:e.raw}),e.maxAge.kind===`invalid`&&c(`zero-constraint-ignored`,{field:`max_age`,[u(e.channel)]:String(e.maxAge.raw)});let d=l.filter(e=>e.acr.level!==void 0),f,p;for(let e of d){let t=e.acr.level;f===void 0||t>f?(f=t,p=e.raw):t===f&&e.channel===`header`&&(p=e.raw)}let m;for(let e of l)e.maxAge.kind===`valid`&&(m===void 0||e.maxAge.value<m)&&(m=e.maxAge.value);if(l.length===2){let[e,t]=l,n=e.acr.level!==void 0&&t.acr.level!==void 0&&e.acr.level!==t.acr.level,r=e.maxAge.kind===`valid`&&t.maxAge.kind===`valid`&&e.maxAge.value!==t.maxAge.value;(n||r)&&c(`channels-disagree`,{header:e.raw??t.raw,body:t.raw??e.raw})}return{challenge:{acrValues:p,requiredLevel:f,maxAge:m,status:n,channels:l.map(e=>e.channel)},diagnostics:s}},We=(e,t,n)=>Ue({status:e,getHeader:t,body:n}).challenge,Ge=`__passflowUpgradeTransaction`,Ke=`__passflowUpgradeReplayed`,qe=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,Je=e=>({...e??{},[Ge]:!0}),Ye=e=>qe(e,Ge),Xe=e=>({...e,[Ke]:!0}),Ze=e=>qe(e,Ke),x=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),S=function(e){return e.signin=`/auth/login`,e.signup=`/auth/register`,e.pkceExchange=`/auth/pkce_exchange`,e.signInWithProvider=`/auth/federated/start/`,e.passwordless=`/auth/passwordless/start`,e.passwordlessComplete=`/auth/passwordless/complete`,e.logout=`/user/logout`,e.refresh=`/auth/refresh`,e.validateSession=`/user/me`,e.sendPasswordResetEmail=`/auth/password/reset`,e.resetPassword=`/auth/password/change`,e.appSettings=`/app/settings`,e.passkeyRegisterStart=`/auth/passkey/register/start`,e.passkeyRegisterComplete=`/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/auth/passkey/authenticate/complete`,e.passkeyValidate=`/auth/validate`,e.settingsAll=`/settings`,e.settingsPasswordPolicy=`/settings/password`,e.settingsPasskey=`/settings/passkey`,e.userPasskey=`/user/passkey`,e.addUserPasskey=`/user/passkey/add/start`,e.completeAddUserPasskey=`/user/passkey/add/complete`,e.joinInvitation=`/user/tenant/join`,e.tenantPath=`/user/tenant`,e.invitationsPath=`/user/tenant/:tenantID/invitations`,e.requestInvitation=`/user/invite`,e.invitationDelete=`/user/invite/:invitationID`,e.invitationResend=`/user/invite/:invitationID/resend`,e.invitationGetLink=`/user/invite/:invitationID/link`,e.twoFactor=`/user/2fa`,e.twoFactorStatus=`/user/2fa/status`,e.twoFactorSetupBegin=`/user/2fa/setup/begin`,e.twoFactorSetupConfirm=`/user/2fa/setup/confirm`,e.twoFactorVerify=`/auth/2fa/verify`,e.twoFactorRecovery=`/auth/2fa/recovery`,e.twoFactorRegenerateCodes=`/user/2fa/recovery-codes/regenerate`,e.twoFactorSetupMagicLink=`/auth/2fa-setup`,e.TwoFactorMethodsAvailable=`/v2/user/2fa/methods/available`,e.TwoFactorMethodsRegistered=`/v2/user/2fa/methods`,e.TwoFactorSetupStart=`/v2/user/2fa/setup/start`,e.TwoFactorSetupComplete=`/v2/user/2fa/setup/complete`,e.TwoFactorMethodRemove=`/v2/user/2fa/methods/:id`,e.TwoFactorChallenge=`/v2/auth/2fa/challenge`,e.TwoFactorVerifyV2=`/v2/auth/2fa/verify`,e.TwoFactorAlternative=`/v2/auth/2fa/alternative`,e.TwoFactorTrustedDevices=`/v2/user/2fa/trusted-devices`,e.TwoFactorTrustedDeviceRevoke=`/v2/user/2fa/trusted-devices/:id`,e.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e}({}),C=function(e){return e.passkeyRegisterStart=`/admin/auth/passkey/register/start`,e.passkeyRegisterComplete=`/admin/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/admin/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/admin/auth/passkey/authenticate/complete`,e.passkeyValidate=`/admin/auth/validate`,e.logout=`/admin/auth/logout`,e}({}),Qe=e=>{if(!e)return null;try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return{origin:t.origin,pathPrefix:n===``?void 0:n}}catch{return null}},w=class extends Error{constructor(e){super(),this.id=e?.id??`unknown`,this.message=e?.message??e??`Something went wrong`,this.status=e?.status??500,this.location=e?.location??`unknown`,this.time=e?.time??new Date().toISOString()}},$e=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),et=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function T(e){return e}function E(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var tt=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),nt=3,rt=1e3,it=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},at=e=>We(e.status,it(e),e.data),ot=e=>at(e)!==void 0,D=class{get origin(){return this._platform.getCurrentUrl()?.origin??``}constructor(e,t,n){this.refreshPromise=null,this.isRefreshing=!1,this.defaultHeaders={Accept:`application/json`,"Content-Type":`application/json`},this.nonAccessTokenEndpoints=[`/auth/`,`/settings`,`/settings/`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??b,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=Qe(r),this.storageManager=t??new Ce({prefix:a??``}),this.deviceService=n??new we(this.storageManager),this.tokenService=new be(this.storageManager),this.tokenDeliveryManager=new Se(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[d]:i});let o=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[p]:o,[m]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{if(this.isNonAuthEndpoint(e.url))return e;if(this.tokenDeliveryManager.isCookieMode()){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(e.url?.includes(`refresh`)){if(this.isRefreshing){let t=new AbortController;return t.abort(),e.signal=t.signal,e}return e}let t=this.storageManager.getTokens();if(t?.access_token){if(g(_(t.access_token),30)&&t.refresh_token)try{if(this.refreshPromise){let t=await this.refreshPromise;return t?.data?.access_token&&(e.headers[f]=`Bearer ${t.data.access_token}`),e}this.refreshPromise=this.refreshTokens();try{let t=await this.refreshPromise;return t?.data?.access_token&&(e.headers[f]=`Bearer ${t.data.access_token}`),e}finally{this.refreshPromise=null}}catch(e){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(e)}return e.headers[f]=`Bearer ${t.access_token}`,e}return e}),this.instance.interceptors.response.use(e=>e,async e=>{if(e.response?.status===401&&!this.isUpgradeTransactionError(e)&&this.tokenDeliveryManager.setSessionInvalid(),e.response&&this.upgradeHandler){let t=at(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}return e.response?.status===429?await this.handleRateLimitError(e):this.handleAxiosError(e)})}isUpgradeTransactionError(e){return Ye(e.config)||e.response!==void 0&&ot(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw Error(`Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.`)}async refreshTokens(){if(this.tokenDeliveryManager.isCookieMode()){let e=await this.instance.post(S.refresh,{},{withCredentials:!0});return this.tokenDeliveryManager.setSessionValid(),e.data.csrf_token&&this.storageManager.setCsrfToken(e.data.csrf_token),e.data.id_token&&this.storageManager.setIdToken(e.data.id_token),e}{let e=this.storageManager.getTokens(),t=this.storageManager.getScopes();if(!e?.refresh_token)throw Error(`No refresh token available`);this.isRefreshing=!0;let n={refresh_token:e.refresh_token,scopes:t},r=await this.instance.post(S.refresh,n,{headers:{[f]:`Bearer ${e.refresh_token}`}});return r.data&&this.storageManager.saveTokens(r.data),this.isRefreshing=!1,r}}async handleRateLimitError(e){let t=e.config;if(!t)return Promise.reject(e);let n=t.method?.toUpperCase();if(![`GET`,`HEAD`,`OPTIONS`].includes(n||``))return Promise.reject(e);let r=t._retryCount||0;if(r>=nt)return Promise.reject(e);let i=rt*2**r,a=e.response?.headers?.[`retry-after`];if(a){let e=Number.parseInt(a,10);if(!Number.isNaN(e))i=e*1e3;else{let e=new Date(a);Number.isNaN(e.getTime())||(i=Math.max(0,e.getTime()-Date.now()))}}return await new Promise(e=>setTimeout(e,i)),t._retryCount=r+1,this.instance.request(t)}async handleAxiosError(e){if(!e.response)return Promise.reject(e);let t=e.response.status,n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:e}=n;return Promise.reject(new w(e))}return Promise.reject(new w({id:`error.http.${t}`,message:e.message||`An error occurred`,status:t,location:e.config?.url||`unknown`,time:new Date().toISOString()}))}async send(e,t,n){return(await this.instance.request({method:e,url:t,...n})).data}get(e,t){return this.send(x.GET,e,t)}post(e,t,n){return this.send(x.POST,e,{data:t,...n})}put(e,t,n){return this.send(x.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(x.PATCH,e,{data:t,...n})}delete(e,t){return this.send(x.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[d]:e},this.instance.defaults.headers.common[d]=e}},st=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(S.appSettings)}},O={withCredentials:!0},ct=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,n,r){let i={access:n,scopes:t,...r?{upgrade:r}:{}},a={headers:{[f]:`Bearer ${e}`}};return this.axiosClient.post(S.refresh,i,r?Je(a):a)}signIn(e,t,n){let r={...e,device:t,os:n};return this.axiosClient.post(S.signin,r,O)}signUp(e){let{create_tenant:t,anonymous:n}=e,r={...e,create_tenant:t??!1,anonymous:n??!1};return this.axiosClient.post(S.signup,r,O)}pkceExchange(e,t){return this.axiosClient.post(S.pkceExchange,{authz_code:e,verifier:t},O)}passwordlessSignIn(e,t,n){let{create_tenant:r}=e,i={...e,create_tenant:r??!1,device:t,os:n};return this.axiosClient.post(S.passwordless,i)}passwordlessSignInComplete(e){return this.axiosClient.post(S.passwordlessComplete,e,O)}logOut(e,t,n=!1){let r=n?void 0:{refresh_token:t,device:e},i=n?C.logout:S.logout;return this.axiosClient.post(i,r)}validateSession(){return this.axiosClient.get(S.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(S.sendPasswordResetEmail,e)}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(S.resetPassword,i,{headers:{[f]:`Bearer ${n}`,[d]:void 0}})}passkeyRegisterStart(e,t,n,r=!1){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n},o=r?C.passkeyRegisterStart:S.passkeyRegisterStart;return this.axiosClient.post(o,a)}passkeyRegisterComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?C.passkeyRegisterComplete:S.passkeyRegisterComplete;return this.axiosClient.post(a,i,O)}passkeyAuthenticateStart(e,t,n,r=!1){let i={...e,user_id:e.user_id??``,device:t,os:n},a=r?C.passkeyAuthenticateStart:S.passkeyAuthenticateStart;return this.axiosClient.post(a,i)}passkeyAuthenticateComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?C.passkeyAuthenticateComplete:S.passkeyAuthenticateComplete;return this.axiosClient.post(a,i,O)}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=S.passkeyValidate;!i&&r&&(o=C.passkeyValidate);let s=i?{[d]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},lt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=E(S.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(S.cliAuthComplete,e)}},ut=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(S.requestInvitation,e)}getInvitations(e){let t={};e.groupID&&(t.group_id=e.groupID.toString()),e.skip!==void 0&&(t.skip=e.skip.toString()),e.limit!==void 0&&(t.limit=e.limit.toString());let n=E(S.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(n,{params:t}).then(e=>({invites:e.invites,nextPageSkip:e.next_page_skip}))}deleteInvitation(e){let t=E(S.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=E(S.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=E(S.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},dt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(S.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(S.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(S.settingsPasskey)}},ft=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(S.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(S.tenantPath,t)}getTenantDetails(e){let t=`${S.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${S.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${S.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(S.tenantPath)}createGroup(e,t){let n=`${S.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${S.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${S.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}changeUserRoles(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${S.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${S.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${S.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${S.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${S.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${S.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},pt=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},mt=e=>({withCredentials:!0,...pt(e)}),ht=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(){return this.axiosClient.get(S.twoFactorStatus)}beginSetup(){return this.axiosClient.post(S.twoFactorSetupBegin,{})}confirmSetup(e){return this.axiosClient.post(S.twoFactorSetupConfirm,e)}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(S.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},mt(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(S.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},mt(t))}disable(e){return this.axiosClient.delete(S.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(S.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${S.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(e,t)=>(t&&delete t.Authorization,e)]}).then(e=>{let t=e;return{success:!0,sessionToken:t.session_token,userId:t.user_id,expiresIn:t.expires_in,appId:t.app_id}}).catch(e=>{if(e.response){let t=e.response.status,n=e.response.data||{},r=e.response.headers?.[`retry-after`]?parseInt(e.response.headers[`retry-after`],10):void 0;return{success:!1,error:{code:n.error||this.mapStatusToErrorCode(t),message:n.message||this.getDefaultErrorMessage(t),retryAfter:r}}}return{success:!1,error:{code:`SERVER_ERROR`,message:e instanceof Error?e.message:`Unable to connect to the server. Please check your connection.`}}})}mapStatusToErrorCode(e){switch(e){case 400:return`INVALID_TOKEN`;case 404:return`REVOKED_TOKEN`;case 410:return`EXPIRED_TOKEN`;case 429:return`RATE_LIMITED`;default:return`SERVER_ERROR`}}getDefaultErrorMessage(e){switch(e){case 400:return`The provided magic link is invalid or malformed.`;case 404:return`This magic link has been revoked or does not exist.`;case 410:return`This magic link has expired. Please request a new one from your administrator.`;case 429:return`Too many validation attempts. Please try again later.`;default:return`An error occurred while validating the magic link.`}}getAvailableMethods(){return this.axiosClient.get(S.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(S.TwoFactorMethodsRegistered)}startMethodSetup(e,t){return this.axiosClient.post(S.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(S.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){let t=E(S.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(S.TwoFactorChallenge,e,pt(t))}verifyV2(e,t){let{trust_device:n,...r}=e;return this.axiosClient.post(S.TwoFactorVerifyV2,{...r,...n?{trust_device:!0}:{}},mt(t))}switchToAlternative(e,t){return this.axiosClient.post(S.TwoFactorAlternative,e,pt(t))}async getTrustedDevices(){return(await this.axiosClient.get(S.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=E(S.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}},gt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(S.upgradeStart,e,Je({}))}},_t=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(S.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${S.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${S.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:n,passkeyDisplayName:r,passkeyUsername:i}){let a={passkey_display_name:r,passkey_username:i,relying_party_id:e,deviceId:t,os:n};return this.axiosClient.post(S.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(S.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}},vt=10,yt=20,bt=class extends Error{constructor(e){super(`Passflow fetch middleware '${e}' resolved without calling next(). Every registered middleware must delegate exactly once; swallowing a request would drop a caller's fetch inside the Passflow wrapper.`),this.name=`FetchMiddlewareContractError`,this.middlewareName=e}},k=[],xt=0,A=!1,j,M,St=(e,t)=>e.priority-t.priority||e.seq-t.seq,Ct=()=>typeof globalThis>`u`?void 0:globalThis,wt=async(e,t,n,r)=>{if(t>=e.length){let e=j;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return wt(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,wt(e,t+1,n,r)),n,r);if(!a)throw new bt(i.name);return o},Tt=()=>{let e=Ct();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>wt([...k].sort(St),0,e,t);return j=t,M=n,e.fetch=n,A=!0,!0},Et=()=>{let e=Ct();e&&M&&e.fetch===M&&(j&&(e.fetch=j),A=!1,M=void 0,j=void 0)},Dt=(e,t)=>{if(!A&&!Tt())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:xt++};k.push(n);let r=!1;return()=>{r||(r=!0,k=k.filter(e=>e!==n),k.length===0&&Et())}},Ot=()=>{let e=Ct();return{installed:A,names:[...k].sort(St).map(e=>e.name),foreignPatch:A&&!!e&&!!M&&e.fetch!==M}},N=class e extends Error{constructor(t){super(t.message),this.name=`M2MError`,this.code=t.code,this.status=t.status??400,this.errorUri=t.errorUri,this.rateLimitInfo=t.rateLimitInfo,this.headers=t.headers,this.cause=t.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromOAuthError(t,n,r){let i=r?e.parseRateLimitHeaders(r):void 0;return new e({code:t.error,message:t.error_description??e.getDefaultMessage(t.error),status:n,errorUri:t.error_uri,rateLimitInfo:i,headers:r})}static fromError(t,n=`server_error`){return new e({code:n,message:t.message||`An unexpected error occurred`,status:500,cause:t})}static parseRateLimitHeaders(e){let t=e[`x-ratelimit-limit`],n=e[`x-ratelimit-remaining`],r=e[`x-ratelimit-reset`]||e[`retry-after`];if(t&&n&&r)return{limit:parseInt(t,10),remaining:parseInt(n,10),reset:parseInt(r,10)}}static getDefaultMessage(e){return{invalid_request:`The request is missing a required parameter or is otherwise malformed.`,invalid_client:`Client authentication failed. Verify your client credentials.`,invalid_grant:`The provided authorization grant is invalid or expired.`,invalid_scope:`The requested scope is invalid, unknown, or exceeds the allowed scopes.`,unauthorized_client:`The client is not authorized to use this grant type.`,unsupported_grant_type:`The authorization grant type is not supported.`,rate_limit_exceeded:`Too many requests. Please retry after the rate limit window resets.`,server_error:`The authorization server encountered an unexpected error.`,temporarily_unavailable:`The authorization server is temporarily unavailable. Please try again later.`}[e]||`An unknown error occurred.`}isRetryable(){return this.code===`server_error`||this.code===`temporarily_unavailable`||this.code===`rate_limit_exceeded`||this.status>=500}getRetryAfter(){if(this.rateLimitInfo?.reset){let e=Math.floor(Date.now()/1e3),t=this.rateLimitInfo.reset-e;return Math.max(t*1e3,1e3)}return 1e3}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,errorUri:this.errorUri,rateLimitInfo:this.rateLimitInfo,timestamp:this.timestamp}}toString(){let e=`M2MError [${this.code}]: ${this.message}`;return this.status&&(e+=` (HTTP ${this.status})`),e}},kt=class extends N{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},P=class extends N{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},F=class extends N{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},At={InvalidRequest:`invalid_request`,InvalidClient:`invalid_client`,InvalidGrant:`invalid_grant`,InvalidScope:`invalid_scope`,UnauthorizedClient:`unauthorized_client`,UnsupportedGrantType:`unsupported_grant_type`,RateLimitExceeded:`rate_limit_exceeded`,ServerError:`server_error`,TemporarilyUnavailable:`temporarily_unavailable`},I={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},jt=class{constructor(){this.cache=new Map}get(e){let t=this.cache.get(e);return t?Date.now()>=t.expiresAt?(this.cache.delete(e),Promise.resolve(null)):Promise.resolve(t.token):Promise.resolve(null)}set(e,t,n){return this.cache.set(e,{token:t,expiresAt:Date.now()+n*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}},Mt={shouldRetry(e,t){return t>=3?!1:e.code===`server_error`||e.code===`temporarily_unavailable`||e.code===`rate_limit_exceeded`||e.status!==void 0&&e.status>=500},getDelay(e){return 2**(e-1)*1e3}},Nt=class{constructor(e){if(!e.url)throw new F(`M2M client requires a URL`);if(!e.clientId)throw new F(`M2M client requires a clientId`);if(!e.clientSecret)throw new F(`M2M client requires a clientSecret`);let t=e.url.replace(/\/$/,``);this.config={url:t,clientId:e.clientId,clientSecret:e.clientSecret,scopes:e.scopes,audience:e.audience,autoRefresh:e.autoRefresh??!1,refreshThreshold:e.refreshThreshold??I.REFRESH_THRESHOLD,timeout:e.timeout??I.TIMEOUT,retries:e.retries??I.RETRIES,retryDelay:e.retryDelay??I.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new jt,this.retryStrategy=e.retryStrategy??Mt,this.tokenEndpoint=`${t}${I.TOKEN_ENDPOINT}`}getCacheKey(e,t){let n=e?.sort().join(`,`)||``,r=t?.sort().join(`,`)||``;return`m2m:${this.config.clientId}:${n}:${r}`}async getToken(e){let t=e?.scopes??this.config.scopes,n=e?.audience??this.config.audience,r=this.getCacheKey(t,n);if(!e?.forceRefresh){let e=await this.cache.get(r);if(e&&!this.isTokenExpired(e))return e}return this.requestToken(t,n,r)}async getValidToken(){let e=this.config.scopes,t=this.config.audience,n=this.getCacheKey(e,t),r=await this.cache.get(n);if(r){if(this.config.autoRefresh&&this.isTokenExpired(r,this.config.refreshThreshold))return this.requestToken(e,t,n);if(!this.isTokenExpired(r))return r}return this.requestToken(e,t,n)}async requestToken(e,t,n){let r={grant_type:`client_credentials`,client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(r.scope=e.join(` `)),t&&t.length>0&&(r.audience=t.join(` `)),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});let i=await this.executeWithRetry(()=>this.doTokenRequest(r));return i.issued_at=Math.floor(Date.now()/1e3),n&&await this.cache.set(n,i,i.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(i),i}async doTokenRequest(e){let t=new URLSearchParams;t.append(`grant_type`,e.grant_type),t.append(`client_id`,e.client_id),t.append(`client_secret`,e.client_secret),e.scope&&t.append(`scope`,e.scope),e.audience&&t.append(`audience`,e.audience);let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let e=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":I.CONTENT_TYPE,Accept:`application/json`},body:t.toString(),signal:n.signal});clearTimeout(r);let i={};e.headers.forEach((e,t)=>{i[t.toLowerCase()]=e});let a=await e.json();if(!e.ok){let t=N.fromOAuthError({error:a.error||`server_error`,error_description:a.error_description||a.message,error_uri:a.error_uri},e.status,i);throw this.config.onError&&this.config.onError({error:t.code,error_description:t.message}),t}return a}catch(e){throw clearTimeout(r),e instanceof Error&&e.name===`AbortError`?new kt(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new kt(`Network error: ${e.message}`,e):e instanceof N?e:N.fromError(e instanceof Error?e:Error(String(e)))}}async executeWithRetry(e){let t;for(let n=1;n<=this.config.retries;n++)try{return await e()}catch(e){if(!(e instanceof N))throw e;if(t=e,n<this.config.retries&&this.retryStrategy.shouldRetry({code:e.code,status:e.status},n)){let e=this.retryStrategy.getDelay(n);await this.sleep(e);continue}throw e}throw t??new N({code:`server_error`,message:`Request failed after retries`})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){let e=this.cache;if(`cache`in e){let t=this.getCacheKey(this.config.scopes,this.config.audience);return e.cache.get(t)?.token??null}return null}isTokenExpired(e,t=0){if(!e)return!0;let n=Math.floor(Date.now()/1e3);return n>=(e.issued_at??n-e.expires_in)+e.expires_in-t}parseToken(e){try{let t=e.split(`.`);if(t.length!==3)throw new P(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new P(`Invalid JWT format: missing payload`);let r=atob(n.replace(/-/g,`+`).replace(/_/g,`/`)),i=JSON.parse(r);return i.scopes&&typeof i.scopes==`string`?i.scopes=i.scopes.split(` `):i.scopes||(i.scopes=[]),i}catch(e){throw e instanceof P?e:new P(`Failed to parse token: ${e instanceof Error?e.message:`Unknown error`}`)}}clearCache(){let e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){let e=this.getCachedToken();if(!e)return;let t=`${this.config.url}/oauth2/revoke`,n=new URLSearchParams;n.append(`token`,e.access_token),n.append(`client_id`,this.config.clientId),n.append(`client_secret`,this.config.clientSecret);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":I.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw N.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof N?e:N.fromError(e instanceof Error?e:Error(String(e)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}},L=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,Pt=32,Ft=e=>{let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1],a=e[n+2];t+=L.charAt(r>>2),t+=L.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=L.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=L.charAt(a&63))}return t},It=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`PKCE needs the Web Crypto API, which is available only in a secure context (https or localhost)`);return e},Lt=async e=>{let t=await It().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Ft(new Uint8Array(t))},Rt=async()=>{let e=Ft(It().getRandomValues(new Uint8Array(Pt)));return{verifier:e,challenge:await Lt(e)}},R=function(e){return e.SignIn=`signin`,e.SignInStart=`signin:start`,e.Register=`register`,e.RegisterStart=`register:start`,e.SignOut=`signout`,e.SessionRestored=`session:restored`,e.SessionExpired=`session:expired`,e.Error=`error`,e.Refresh=`refresh`,e.RefreshStart=`refresh:start`,e.TokenCacheExpired=`token-cache-expired`,e.TwoFactorRequired=`2fa:required`,e.TwoFactorSetupStarted=`2fa:setup_started`,e.TwoFactorEnabled=`2fa:enabled`,e.TwoFactorDisabled=`2fa:disabled`,e.TwoFactorVerified=`2fa:verified`,e.TwoFactorRecoveryUsed=`2fa:recovery_used`,e.TwoFactorRecoveryCodesLow=`2fa:recovery_low`,e.TwoFactorRecoveryCodesExhausted=`2fa:recovery_exhausted`,e.TwoFactorSetupMagicLinkValidated=`2fa:magic_link_validated`,e.TwoFactorSetupMagicLinkFailed=`2fa:magic_link_failed`,e.TwoFactorChallengeReceived=`two_factor_challenge_received`,e.TwoFactorMethodSwitched=`two_factor_method_switched`,e.TwoFactorDeviceTrusted=`two_factor_device_trusted`,e}({}),zt=class{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){let n=new Set(t);this.subscribers.set(e,n)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}let n=this.subscribers.get(e);n&&(t.forEach(e=>n.delete(e)),n.size===0&&this.subscribers.delete(e))}notify(e,t){this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}},z={twoFactorCodeInvalid:`error.api.request.2fa_code.invalid`,challengeInvalid:`error.upgrade.challenge_invalid`,challengeSessionMismatch:`error.upgrade.challenge_session_mismatch`,challengeTooManyAttempts:`error.upgrade.challenge_too_many_attempts`,unsupportedFactor:`error.upgrade.unsupported_factor`,noSession:`error.upgrade.no_session`,unavailable:`error.upgrade.unavailable`,methodNotRegistered:`error.upgrade.method_not_registered`,prepareNotRequired:`error.upgrade.prepare_not_required`,methodNotSupported:`error.2fa.method_not_supported`,twoFactorNotEnabled:`error.2fa.not_enabled`,notImplemented:`error.not.implemented`,tokenInvalid:`error.api.request.token.invalid`},Bt=Object.freeze([z.twoFactorCodeInvalid,z.twoFactorNotEnabled,z.challengeInvalid,z.challengeSessionMismatch,z.challengeTooManyAttempts]),Vt=Object.freeze([z.tokenInvalid]),Ht=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),Ut=e=>Ht.includes(e),Wt={wrong_code:`That code was not accepted. Try again.`,challenge_spent:`That verification challenge is no longer valid. Start again.`,exhausted:`Too many attempts. Try again later.`,attempts_exhausted:`Too many incorrect attempts. Verification was not completed.`,not_registered:`That verification method is not set up for this account.`,prepare_not_required:`This verification method needs no preparation round.`,fatal:`This verification method cannot be used right now.`,unavailable:`Step-up verification is not available on this deployment.`,protocol:`The server returned an unexpected upgrade response.`,network:`The verification request did not reach the server.`,session_changed:`The session ended during verification.`},B=class extends Error{constructor(e){super(e.message||Wt[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,this.retryable=Ut(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},Gt=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`]),Kt=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&Gt.includes(e.code),qt=e=>e instanceof B||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,Jt=e=>{if(typeof e!=`object`||!e)return{hasResponse:!1,message:typeof e==`string`?e:void 0};let t=e,n=t.response,r=n?.data,i=typeof r?.error?.id==`string`?r.error.id:void 0;return{status:typeof t.status==`number`?t.status:typeof n?.status==`number`?n.status:void 0,errorId:typeof t.id==`string`?t.id:i,message:typeof t.message==`string`?t.message:void 0,hasResponse:n!==void 0||typeof t.status==`number`}},Yt=(e,t)=>{switch(e){case z.twoFactorCodeInvalid:return`wrong_code`;case z.challengeInvalid:case z.challengeSessionMismatch:return`challenge_spent`;case z.challengeTooManyAttempts:return`exhausted`;case z.methodNotRegistered:return`not_registered`;case z.twoFactorNotEnabled:return t===`refresh`?`session_changed`:`not_registered`;case z.prepareNotRequired:return`prepare_not_required`;case z.unavailable:case z.notImplemented:return`unavailable`;case z.unsupportedFactor:case z.noSession:case z.methodNotSupported:return`fatal`;case z.tokenInvalid:return t===`refresh`?`session_changed`:`fatal`;default:return}},Xt=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,Zt=(e,t)=>{if(e instanceof B)return e;let n=Jt(e);return n.hasResponse?new B({kind:Yt(n.errorId,t)??Xt(n.status,t),message:n.message,status:n.status,errorId:n.errorId,cause:e}):new B({kind:`network`,message:n.message,cause:e})},Qt=e=>e.errorId!==void 0&&Bt.includes(e.errorId),$t=e=>e.errorId!==void 0&&Vt.includes(e.errorId),V=class extends Error{constructor(e,t,n){super(n??`The session was elevated, but this action requires a higher assurance level`),this.name=`UpgradeInsufficientError`,this.code=`upgrade_insufficient`,this.obtained=e,this.required=t}},H=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},U=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},en=e=>{if(e&&typeof e.sub==`string`&&e.sub!==``)return typeof e.sid==`string`&&e.sid!==``?{sub:e.sub,sid:e.sid}:{sub:e.sub}},tn=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function W(e){if(!e||typeof e!=`string`)return!1;let t=e.split(`.`);if(t.length!==3)return!1;let n=/^[A-Za-z0-9_-]+$/;return t.every(e=>n.test(e)&&e.length>0)}function nn(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function G(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function K(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function rn(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length<3||t.length>30?!1:/^[a-zA-Z0-9_-]+$/.test(t)}function q(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function an(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return/^[A-Z0-9-]{4,16}$/.test(t)?t:null}var on=class{error(e,...t){console.error(e,...t)}warn(e,...t){console.warn(e,...t)}info(e,...t){console.info(e,...t)}debug(e,...t){console.debug(e,...t)}};function sn(){return new on}var cn=`passflow_2fa_pkce`,ln=3e5,un=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=b,f){this.authApi=e,this.deviceService=t,this.storageManager=n,this.subscribeStore=r,this.tokenCacheService=i,this.scopes=a,this.createTenantForNewUser=o,this.url=s,this.sessionCallbacks=c,this.appId=l,this.platform=d,this.readPkceEnabled=f,this.tokenExchangeConfig=u,this.tokenDeliveryManager=new Se(n),u?.enabled&&this.tokenDeliveryManager.setMode(y.BFF),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`});return e.ok&&(await e.json()).authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(R.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);this.tokenExchangeConfig?.enabled||`token_delivery`in e&&e.token_delivery&&this.tokenDeliveryManager.setMode(e.token_delivery),this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.callbackUrl&&await this.forwardTokensToBFF(e),e.scopes=t,this.storageManager.saveTokens(e,this.tokenDeliveryManager.getMode()),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)}handlePendingSecondFactor(e,t,n,r){return e.requires_2fa!==!0&&!e.tfa_token?!1:(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(R.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0)}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+ln},typeof sessionStorage<`u`)try{sessionStorage.setItem(cn,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(cn);this.pendingPkce=e?JSON.parse(e):void 0}catch{this.pendingPkce=void 0}return this.pendingPkce&&Date.now()>=this.pendingPkce.expiresAt&&this.forgetPkceSignIn(),this.pendingPkce}hasPendingPkceSignIn(){return this.readPendingPkce()!==void 0}forgetPkceSignIn(){if(this.pendingPkce=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(cn)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){sn().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?Rt():void 0}async exchangeCode(e,t){return!e.code||!t?e:await this.authApi.pkceExchange(e.code,t.verifier)}async completePkceSignIn(e){let t=this.readPendingPkce();if(!t)throw Error(`The sign-in answered with a PKCE code, but its verifier is gone`);let n=await this.authApi.pkceExchange(e,t.verifier);return await this.processAuthResponse(n,t.scopes??this.scopes),n}async applyTokens(e){let t=e;(t.access_token||t.id_token||t.token_delivery)&&await this.processAuthResponse(t,t.scopes??this.readPendingPkce()?.scopes??this.scopes)}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;let t=await fetch(this.tokenExchangeConfig.callbackUrl,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`},body:JSON.stringify({access_token:e.access_token,refresh_token:e.refresh_token,id_token:e.id_token,expires_in:e.expires_in})});if(!t.ok)throw Error(`BFF token storage failed: ${t.status}`)}async signIn(e){if(`email`in e&&e.email&&!G(e.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(`username`in e&&e.username&&!rn(e.username)){let e=Error(`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`),t={message:`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(`phone`in e&&e.phone&&!K(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.SignInStart,{email:e.email});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),i=await this.authApi.signIn(r?{...e,code_challenge:r.challenge}:e,t,n);if(this.handlePendingSecondFactor(i,e.email,r,e.scopes))return i;let a=await this.exchangeCode(i,r);return this.handlePendingSecondFactor(a,e.email)||(await this.processAuthResponse(a,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),a}catch(e){let t={message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async signUp(e){if(e.user.email&&!G(e.user.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(e.user.phone_number&&!K(e.user.phone_number)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let t=await this.startPkce(),n=await this.authApi.signUp(t?{...e,code_challenge:t.challenge}:e);if(this.handlePendingSecondFactor(n,e.user.email,t,e.scopes))return n;let r=await this.exchangeCode(n,t);return this.handlePendingSecondFactor(r,e.user.email)||(await this.processAuthResponse(r,e.scopes),this.subscribeStore.notify(R.Register,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),r}catch(e){let t={message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passwordlessSignIn(e){if(e.email&&!G(e.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(e.phone&&!K(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());try{return await this.authApi.passwordlessSignIn(e,t,n)}catch(e){let t={message:e instanceof Error?e.message:`Failed to send passwordless sign-in link`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passwordlessSignInComplete(e){this.subscribeStore.notify(R.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();try{let t=await this.authApi.passwordlessSignInComplete(e);return this.handlePendingSecondFactor(t)||(await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),t}catch(e){let t={message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async logOut(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl)try{(await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})).ok}catch{}else{let e=this.storageManager.getToken(v.refresh_token),t=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(t,e,!this.appId)).status!==`ok`)throw Error(`Logout failed`)}catch{}}this.forgetPkceSignIn(),this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.subscribeStore.notify(R.SignOut,{})}readSessionPin(){try{let e=this.storageManager.getToken(v.access_token);return e?en(_(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!tn(e,this.readSessionPin()))throw console.warn(`[passflow] the session or user changed while a step-up upgrade was in flight; the elevated tokens were discarded and the live session was left untouched.`),new U(`The session changed during verification, so the elevated tokens were discarded`)}async refreshToken(e,t){if(this.subscribeStore.notify(R.RefreshStart,{}),e&&this.tokenDeliveryManager.isBFFMode())throw new B({kind:`unavailable`,message:`Step-up verification cannot be committed through a BFF refresh endpoint`});if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl)try{let e=await fetch(this.tokenExchangeConfig.refreshUrl,{method:`POST`,credentials:`include`});if(!e.ok)throw this.tokenDeliveryManager.setSessionInvalid(),Error(`BFF token refresh failed`);let t=await e.json();return this.tokenDeliveryManager.setSessionValid(),t.id_token&&this.storageManager.setIdToken(t.id_token),this.subscribeStore.notify(R.Refresh,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,t}catch(e){this.tokenDeliveryManager.setSessionInvalid();let t={message:e instanceof Error?e.message:`Token refresh failed`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}if(this.tokenDeliveryManager.isCookieMode())try{let n=e?await this.authApi.refreshToken(``,this.scopes,void 0,e):await this.authApi.refreshToken(``,this.scopes);return this.assertSessionPin(t),this.tokenDeliveryManager.setSessionValid(),await this.processAuthResponse(n,this.scopes),this.subscribeStore.notify(R.Refresh,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,n}catch(t){e||this.tokenDeliveryManager.setSessionInvalid();let n={message:t instanceof Error?t.message:`Token refresh failed`,originalError:t,code:t instanceof w?t.id:void 0};throw this.subscribeStore.notify(R.Error,n),t}let n=this.storageManager.getTokens();if(!n){let e=Error(`No tokens found`),t={message:`No tokens found`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}if(!n?.refresh_token){let e=Error(`No refresh token found`),t={message:`No refresh token found`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}let r=n?.scopes??this.scopes;try{let i=n?.refresh_token??``,a=n?.access_token,o=e?await this.authApi.refreshToken(i,r,a,e):await this.authApi.refreshToken(i,r,a);return this.assertSessionPin(t),o.scopes=r,this.storageManager.saveTokens(o),this.tokenCacheService.setTokensCache(o),this.subscribeStore.notify(R.Refresh,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,this.tokenCacheService.startTokenCheck(),o}catch(t){let n={message:t instanceof Error?t.message:`Token refresh failed`,originalError:t,code:t instanceof w?t.id:void 0,details:c.default.isAxiosError(t)&&t.response?{status:t.response.status,data:t.response.data}:void 0};this.subscribeStore.notify(R.Error,n);let r=c.default.isAxiosError(t)&&t.response?.status&&t.response.status>=400&&t.response.status<500;throw r&&!e&&(this.tokenCacheService.tokenExpiredFlag=!0,this.tokenCacheService.setTokensCache(void 0),this.storageManager.deleteTokens(),this.subscribeStore.notify(R.SessionExpired,{reason:`refresh_failed`})),t instanceof w?t:r&&!e?Error(`Getting unknown error message from server with code:${t.response?.status}`):t}}async sendPasswordResetEmail(e){try{return await this.authApi.sendPasswordResetEmail(e)}catch(e){let t={message:e instanceof Error?e.message:`Failed to send password reset email`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async resetPassword(e,t){this.subscribeStore.notify(R.SignInStart,{});let n=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`token`)??void 0,r=t??this.scopes;try{let t=await this.startPkce(),i=t?await this.authApi.resetPassword(e,r,n,t.challenge):await this.authApi.resetPassword(e,r,n);if(this.handlePendingSecondFactor(i,void 0,t,r))return i;let a=await this.exchangeCode(i,t);if(this.handlePendingSecondFactor(a))return a;let o=i.redirect_url?{...a,redirect_url:i.redirect_url}:a;return await this.processAuthResponse(o,r),this.subscribeStore.notify(R.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),o}catch(e){let t={message:e instanceof Error?e.message:`Password reset failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passkeyRegister(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(R.RegisterStart,{});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyRegisterStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId);a.user.id=this.platform.btoa(a.user.id);let o=await this.platform.passkeys.startRegistration(a);if(!o)throw Error(`Passkey registration was not completed`);let s=await this.authApi.passkeyRegisterComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(R.Register,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(R.SignInStart,{});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyAuthenticateStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId),o=await this.platform.passkeys.startAuthentication(a);if(!o)throw Error(`Passkey authentication was not completed`);let s=await this.authApi.passkeyAuthenticateComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||`access_token`in c&&(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}createFederatedAuthUrl(e){let t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw Error(`AppId is required for federated auth`);let n={scopes:(e.scopes??this.scopes).join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:this.appId,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{}},r=new URL(t,this.url);return r.search=new URLSearchParams(n).toString(),r.toString()}async federatedAuthWithPopup(e){this.subscribeStore.notify(R.SignInStart,{provider:e.provider});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=this.createFederatedAuthUrl({...e,scopes:t,device:n});try{let e=await this.platform.openAuthUrl(r,{mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``}),n=new URLSearchParams(e.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:n.get(`tfa_token`)??void 0}))return;let i=new URLSearchParams(e.callbackSearch),a=i.get(`access_token`)||``,o=i.get(`refresh_token`)||``,s=i.get(`id_token`)||``,c={access_token:a,refresh_token:o||void 0,id_token:s||void 0,scopes:t};await this.processAuthResponse(c,t),this.subscribeStore.notify(R.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){let t={message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof Te?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};this.subscribeStore.notify(R.Error,t)}}federatedAuthWithRedirect(e){this.subscribeStore.notify(R.SignInStart,{provider:e.provider});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=this.createFederatedAuthUrl({...e,scopes:t,device:n});this.platform.navigateTo(r)}authRedirectUrl(e={}){try{let{url:t,redirectUrl:n,scopes:r,appId:i}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith(`/`)?a.pathname:a.pathname+`/`)+`web`;let o=r??this.scopes,s={appId:i??this.appId??``,redirectto:n??this.platform.getCurrentUrl()?.href??``,scopes:o.join(`,`)};return a.search=new URLSearchParams(s).toString(),a.toString()}catch(e){let t={message:e instanceof Error?e.message:`Failed to create auth redirect URL`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}}authRedirect(e={}){try{this.platform.navigateTo(this.authRedirectUrl(e))}catch(e){let t={message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=!!e?.id_token||!!this.storageManager.getIdToken(),n=this.tokenDeliveryManager.isSessionValid(),r=this.tokenDeliveryManager.isSessionUnknown();return t&&(n||r)}return!e||!e.access_token?!1:!g(e.access_token)||e.refresh_token!==void 0&&!g(e.refresh_token)}catch(e){let t={message:e instanceof Error?e.message:`Failed to check authentication status`,originalError:e};return this.subscribeStore.notify(R.Error,t),!1}}async submitSessionCheck(e=!1){let t,n;try{t=await this.getTokens(e),n=this.tokenCacheService.getParsedTokens()}catch(e){let n={message:e instanceof Error||e instanceof w?e.message:`Session check failed`,originalError:e};this.subscribeStore.notify(R.Error,n),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:n}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=this.storageManager.getTokens();return t?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshToken():t:void 0}let t=this.storageManager.getTokens();return!t||!t.access_token?void 0:g(_(t.access_token))?e?await this.refreshToken():void 0:t}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t);return}}},dn=class{constructor(e){this.invitationApi=e}requestInviteLink(e){return this.invitationApi.requestInviteLink(e)}getInvitations(e){return this.invitationApi.getInvitations(e)}deleteInvitation(e){return this.invitationApi.deleteInvitation(e)}resendInvitation(e){return this.invitationApi.resendInvitation(e)}getInvitationLink(e){return this.invitationApi.getInvitationLink(e)}},fn=class{constructor(e){this.data=this.normalize(e)}normalize(e){let t=new Map,n=new Map,r=new Map,i=[];return e.groups?.forEach(e=>{n.set(e.id,{id:e.id,name:e.name,default:e.default??!1,updated_at:e.updated_at,created_at:e.created_at})}),e.roles?.forEach(e=>{r.set(e.id,{id:e.id,tenant_id:e.tenant_id,name:e.name})}),e.users_in_groups?.forEach(e=>{let r=e.user;r&&!t.has(r.id)&&t.set(r.id,{id:r.id,name:r.name??null,email:r.email??null,phone:r.phone??null}),r&&e.group_id&&n.has(e.group_id)&&i.push({userId:r.id,groupId:e.group_id,roleIds:e.roles?.map(e=>e.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(n.values()),roles:Array.from(r.values()),memberships:i,usersById:t,groupsById:n,rolesById:r}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(e=>this.data.usersById.get(e.userId)).filter(e=>e!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(e=>this.data.groupsById.get(e.groupId)).filter(e=>e!==void 0)}getUserRolesInGroup(e,t){let n=this.data.memberships.find(n=>n.userId===e&&n.groupId===t);return n?n.roleIds.map(e=>this.data.rolesById.get(e)).filter(e=>e!==void 0):[]}getData(){return this.data}},pn=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||sn()}handlePassflowError(e,t){if(c.default.isAxiosError(e)&&e.response?.data){let n=e.response.data;if(typeof n==`object`&&n&&`error`in n&&typeof n.error==`object`&&n.error!==null){let e=n.error;throw this.logger.error(`${t}: ${e.id} - ${e.message} (Status: ${e.status})`),Error(`Passflow API Error: ${e.id} - ${e.message} (Status: ${e.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:Error(String(e))}async joinInvitation(e,t){try{let n=t??this.scopes;return await this.tenantApi.joinInvitation(e,n)}catch(e){this.handlePassflowError(e,`Join invitation failed`)}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(e){this.handlePassflowError(e,`Tenant creation failed`)}}async getTenantDetails(e){try{return await this.tenantApi.getTenantDetails(e)}catch(t){this.handlePassflowError(t,`Get tenant details failed for tenant ID ${e}`)}}async getTenantUserMembership(e){try{return new fn(await this.tenantApi.getTenantDetails(e))}catch(t){this.handlePassflowError(t,`Get tenant user membership failed for tenant ID ${e}`)}}async updateTenant(e,t){try{return await this.tenantApi.updateTenant(e,t)}catch(t){this.handlePassflowError(t,`Update tenant failed for tenant ID ${e}`)}}async deleteTenant(e){try{return await this.tenantApi.deleteTenant(e)}catch(t){this.handlePassflowError(t,`Delete tenant failed for tenant ID ${e}`)}}async getUserTenantMembership(){try{return await this.tenantApi.getUserTenantMembership()}catch(e){this.handlePassflowError(e,`Get user tenant memberships failed`)}}async createGroup(e,t){try{return await this.tenantApi.createGroup(e,t)}catch(t){this.handlePassflowError(t,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(n){this.handlePassflowError(n,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,n){try{return await this.tenantApi.updateGroup(e,t,n)}catch(n){this.handlePassflowError(n,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(n){this.handlePassflowError(n,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,n,r){try{return await this.tenantApi.addUserToGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async removeUserRolesFromGroup(e,t,n,r){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async changeUserRoles(e,t,n,r){try{return await this.tenantApi.changeUserRoles(e,t,n,r)}catch(r){this.handlePassflowError(r,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async deleteUserFromGroup(e,t,n){try{return await this.tenantApi.deleteUserFromGroup(e,t,n)}catch(r){this.handlePassflowError(r,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async getRolesForTenant(e){try{return await this.tenantApi.getRolesForTenant(e)}catch(t){this.handlePassflowError(t,`Get roles for tenant failed for tenant ID ${e}`)}}async createRoleForTenant(e,t){try{return await this.tenantApi.createRoleForTenant(e,t)}catch(t){this.handlePassflowError(t,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,n){try{return await this.tenantApi.updateRole(e,t,n)}catch(n){this.handlePassflowError(n,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(n){this.handlePassflowError(n,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(n){this.handlePassflowError(n,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,n,r){try{return await this.tenantApi.getGroupInvitations(e,t,n,r)}catch(n){this.handlePassflowError(n,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,n){try{return await this.tenantApi.getTenantInvitations(e,t,n)}catch(t){this.handlePassflowError(t,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,n){try{return await this.tenantApi.invalidateInviteById(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${n}`)}}async invalidateInviteByEmail(e,t,n){try{return await this.tenantApi.invalidateInviteByEmail(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${n}`)}}},mn=class{constructor(e,t,n,r=b){this.storageManager=e,this.authApi=t,this.subscribeStore=n,this.platform=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.unsubscribeForeground=null,this.unsubscribeUnload=null,this.isRefreshing=!1,this.tokenExpiredFlag=!1,this.storageManager=e,this.authApi=t,this.setupLifecycleListeners()}initialize(){try{let e=this.storageManager.getTokens();if(!e)return;if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}g(_(e.access_token))?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0})):(this.setTokensCache(e),this.startTokenCheck())}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(R.RefreshStart,{});let t=await this.authApi.refreshToken(e?.refresh_token??``,e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(R.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenExpiredFlag=!1,this.startTokenCheck()}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(R.SessionExpired,{reason:`refresh_failed`})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),this.tokenExpiredFlag||(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,this.parsedTokensCache=e?{access_token:e.access_token?_(e.access_token):void 0,id_token:e.id_token?_(e.id_token):void 0,refresh_token:e.refresh_token?_(e.refresh_token):void 0,scopes:e.scopes}:void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{return!this.tokensCache||!this.tokensCache.access_token||g(_(this.tokensCache.access_token))&&!this.tokenExpiredFlag&&await this.refreshTokensCache(this.tokensCache),this.tokensCache}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){return this.tokensCache?this.tokensCache.access_token?g(_(this.tokensCache.access_token)):!1:!0}},hn=class{constructor(e,t,n){this.twoFactorApi=e,this.subscribeStore=t,this.signInCompleter=n,this.PARTIAL_AUTH_TIMEOUT_MS=3e5,this.SESSION_STORAGE_KEY=`passflow_2fa_challenge`,this.totpDigits=6,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===R.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===R.SignIn||e===R.Register)&&this.clearPartialAuthState()}},[R.TwoFactorRequired,R.SignIn,R.Register])}emitErrorAndThrow(e,t){let n=e,r={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:n?.id||void 0};throw this.subscribeStore.notify(R.Error,r),e}async getStatus(){try{let e=await this.twoFactorApi.getStatus();return e.totp_digits&&(this.totpDigits=e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`Get 2FA status`)}}async beginSetup(){try{let e=await this.twoFactorApi.beginSetup();return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(R.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,`Begin 2FA setup`)}}async confirmSetup(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.confirmSetup({code:e});return this.subscribeStore.notify(R.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(e){this.emitErrorAndThrow(e,`Confirm 2FA setup`)}}async verify(e,t){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);try{let n=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}),r=await this.finishSignIn(n);return this.subscribeStore.notify(R.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=an(e);if(!n)throw Error(`Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);let r=await this.finishSignIn(await this.twoFactorApi.useRecoveryCode({recovery_code:n,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}));return r.remaining_recovery_codes===0?this.subscribeStore.notify(R.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(R.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(R.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(R.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`Use recovery code`)}}async disable(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(R.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`Disable 2FA`)}}async regenerateRecoveryCodes(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),n=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=n,t}catch(e){this.emitErrorAndThrow(e,`Regenerate recovery codes`)}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,n){if(this.partialAuthState={email:e,challengeId:t,tfaToken:n,timestamp:Date.now(),expiresAt:Date.now()+this.PARTIAL_AUTH_TIMEOUT_MS},typeof sessionStorage<`u`)try{sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(this.partialAuthState))}catch{}}clearPartialAuthState(){if(this.partialAuthState=void 0,this.signInCompleter?.forgetPkceSignIn(),typeof sessionStorage<`u`)try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}async finishSignIn(e){let{code:t,...n}=e;if(t&&!this.signInCompleter?.hasPendingPkceSignIn()){this.clearPartialAuthState();let e=Error(`The sign-in answered with a PKCE code, but its verifier is gone`);throw e.id=`PKCE_VERIFIER_MISSING`,e}let r=e;if(t&&this.signInCompleter){let e=await this.signInCompleter.completePkceSignIn(t);r={...n,...e}}else await this.signInCompleter?.applyTokens(r);return this.clearPartialAuthState(),r}pendingTfaToken(){return this.isVerificationRequired()&&this.partialAuthState?.tfaToken||void 0}recoverPartialAuthState(){if(!this.partialAuthState&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;let t=JSON.parse(e);Date.now()<t.expiresAt?this.partialAuthState=t:sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}}async validateTwoFactorSetupMagicLink(e){let t=await this.twoFactorApi.validateTwoFactorSetupMagicLink(e);return t.success&&t.sessionToken&&t.userId?(this.magicLinkSession={sessionToken:t.sessionToken,userId:t.userId,appId:t.appId,scope:`2fa_setup`,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(R.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(R.TwoFactorSetupMagicLinkFailed,{error:t.error}),t}getMagicLinkSession(){return this.magicLinkSession?Date.now()>this.magicLinkSession.expiresAt?(this.clearMagicLinkSession(),null):this.magicLinkSession:null}clearMagicLinkSession(){this.magicLinkSession=void 0}hasMagicLinkSession(){return this.getMagicLinkSession()!==null}getMagicLinkSessionToken(){return this.getMagicLinkSession()?.sessionToken||null}getTotpDigits(){return this.totpDigits}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`Get available 2FA methods`)}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,`Get registered 2FA methods`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(R.TwoFactorSetupStarted,{secret:``,method:e}),n}catch(e){this.emitErrorAndThrow(e,`Start 2FA method setup`)}}async completeMethodSetup(e,t){try{let n=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(R.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),n}catch(e){this.emitErrorAndThrow(e,`Complete 2FA method setup`)}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(e){this.emitErrorAndThrow(e,`Remove 2FA method`)}}async requestChallenge(e){try{let t=await this.twoFactorApi.requestChallenge(e,this.pendingTfaToken());return this.subscribeStore.notify(R.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(e){this.emitErrorAndThrow(e,`Request 2FA challenge`)}}async verifyV2(e){try{let t=await this.twoFactorApi.verifyV2(e,this.pendingTfaToken());if(!t.success)return t;let n=await this.finishSignIn(t);return this.subscribeStore.notify(R.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),n.device_trusted&&this.subscribeStore.notify(R.TwoFactorDeviceTrusted,{}),n}catch(e){this.emitErrorAndThrow(e,`Verify 2FA challenge`)}}async switchToAlternative(e){try{let t=await this.twoFactorApi.switchToAlternative(e,this.pendingTfaToken());return this.subscribeStore.notify(R.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(e){this.emitErrorAndThrow(e,`Switch to alternative 2FA method`)}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(e){this.emitErrorAndThrow(e,`Revoke trusted device`)}}},gn=class{constructor(e,t,n=b){this.userAPI=e,this.deviceService=t,this.platform=n}getUserPasskeys(){return this.userAPI.getUserPasskeys()}renameUserPasskey(e,t){return this.userAPI.renameUserPasskey(e,t)}deleteUserPasskey(e){return this.userAPI.deleteUserPasskey(e)}async addUserPasskey({relyingPartyId:e,passkeyUsername:t,passkeyDisplayName:n}={}){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);let r=this.deviceService.getDeviceId(),i=T(this.platform.getDeviceType()),{challenge_id:a,publicKey:o}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??``,deviceId:r,os:i,passkeyDisplayName:n,passkeyUsername:t});o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);return await this.userAPI.addUserPasskeyComplete(s,r,a)}},J=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},_n=(e,t)=>{let n=t?.trim();if(!n)throw new J(e,`A verification code is required`);return n},vn={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_n(`totp`,e)})},yn={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_n(`recovery_codes`,e)})},bn={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new J(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new J(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new J(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new J(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},Y=Object.freeze([vn,bn,yn]),xn=(e=Y)=>new Map(e.map(e=>[e.type,e])),Sn=3,Cn={passkey:0,totp:1,email_otp:2,sms_otp:3,recovery_codes:9},wn=e=>e.requiredLevel??je(e.acrValues),Tn=(e,t)=>{let n=Cn[e.type]??5,r=t!==void 0&&t>=Sn,i=e.type===`passkey`;return(r&&!i?100:0)+n},En=(e,t)=>{let n=wn(t);return[...e].sort((e,t)=>Tn(e,n)-Tn(t,n))},X=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},Z=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Dn=4,On=3e4,kn=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Q=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),An=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,jn=(e,t)=>{let n=e.requiredLevel===void 0?t.requiredLevel:t.requiredLevel===void 0?e.requiredLevel:Math.max(e.requiredLevel,t.requiredLevel),r=n===void 0?e.acrValues??t.acrValues:n===e.requiredLevel?e.acrValues:t.acrValues,i=e.maxAge===void 0?t.maxAge:t.maxAge===void 0?e.maxAge:Math.min(e.maxAge,t.maxAge),a=Array.from(new Set([...e.channels??[],...t.channels??[]]));return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{}}},Mn=(e,t)=>{let n=t.requiredLevel!==void 0&&(e.requiredLevel===void 0||t.requiredLevel>e.requiredLevel),r=t.maxAge!==void 0&&(e.maxAge===void 0||t.maxAge<e.maxAge);return n||r},Nn=class{constructor(e){this.state=`idle`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.transport=e.transport,this.prompt=e.prompt,this.platform=e.platform,this.available=e.factors??Y,this.registry=xn(this.available),this.maxAttempts=e.maxAttempts??Dn,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??On}get currentState(){return this.state}get active(){return this.inFlight!==null}elevate(e,t={kind:`imperative`}){let n=this.register(e,t);if(this.state===`idle`)this.state=`collecting`,this.requirement=e,this.inFlight=this.runFlight();else{this.join(e);let t=this.proof;t?.status===`proven`?this.release(n,t.obtained):t?.status===`failed`&&(this.receiveReport(n,{outcome:`failed`}),n.settlement.reject(t.reason))}return n.settlement.promise}register(e,t){let n=t.kind===`imperative`&&t.requested!==void 0,r={demanded:t.kind===`imperative`&&t.requested?t.requested:Q(e),statedBar:n,settlement:kn(),reported:!1,entry:{...t,outcome:`pending`,report:e=>this.receiveReport(r,e)}};return this.registrations.push(r),r}join(e){let t=this.requirement;if(!t){this.requirement=e;return}let n=Mn(t,e);this.requirement=jn(t,e),n&&this.state===`collecting`&&this.selected===null&&this.openPrompt?.onRequirementRaised?.({challenge:this.requirement,factors:this.offeredFactors()})}offeredFactors(){let e=this.available.filter(e=>!this.pruned.has(e.type)),t=this.requirement;return t?En(e,t):e}receiveReport(e,t){e.reported||(e.reported=!0,e.entry.outcome=t.outcome,t.obtained&&(e.entry.obtained=t.obtained),t.required&&(e.entry.required=t.required),this.notifyReportsSettled())}notifyReportsSettled(){if(!this.reportsSettled||this.registrations.some(e=>!e.reported))return;let e=this.reportsSettled;this.reportsSettled=void 0,e()}async runFlight(){let e;try{e=await this.prove()}catch(t){e={status:`failed`,reason:t instanceof Error?t:Error(String(t))}}if(this.proof=e,e.status===`failed`)for(let t of this.registrations)this.receiveReport(t,{outcome:`failed`}),t.settlement.reject(e.reason);else{this.state=`replaying`;for(let t of this.registrations)this.release(t,e.obtained);await this.awaitReports()}this.state=`settling`;let t=this.summarise(e);try{this.onFlightSettled?.(t)}catch{}this.state=`done`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.reportsSettled=void 0,this.state=`idle`}release(e,t){if(e.entry.kind===`imperative`){if(e.statedBar&&!An(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new V(t,e.demanded));return}this.receiveReport(e,{outcome:`replayed`,obtained:t}),e.settlement.resolve({waiter:e.entry,obtained:t})}else e.settlement.resolve({waiter:e.entry,obtained:t})}awaitReports(){return this.registrations.some(e=>!e.reported)?new Promise(e=>{let t=setTimeout(()=>{this.reportsSettled=void 0;for(let e of this.registrations)e.reported||(e.reported=!0,e.entry.outcome=`failed`);e()},this.settleTimeoutMs);this.reportsSettled=()=>{clearTimeout(t),e()}}):Promise.resolve()}summarise(e){let t=this.registrations.map(e=>({...e.entry.kind===`request`?{url:e.entry.url,method:e.entry.method}:{},outcome:e.entry.outcome,...e.entry.obtained?{obtained:e.entry.obtained}:{},...e.entry.required?{required:e.entry.required}:{}}));if(e.status===`failed`)return{proof:e,waiters:t,terminal:`failed`,error:e.reason};let n;for(let e of t){if(e.outcome!==`insufficient`)continue;let t=e.required?.level??0;(!n||t>(n.required?.level??0))&&(n=e)}return n?{proof:e,waiters:t,terminal:`insufficient`,insufficient:{obtained:n.obtained??e.obtained,required:n.required??{}}}:t.some(e=>e.outcome===`failed`||e.outcome===`pending`)?{proof:e,waiters:t,terminal:`failed`}:{proof:e,waiters:t,terminal:`success`}}async prove(){let e;for(let t=0;t<this.maxAttempts;t++){let t=this.offeredFactors();if(t.length===0)return{status:`failed`,reason:new Z};let n=this.requirement,r;try{r=await this.collect(n,t,e)}catch(e){return{status:`failed`,reason:new X(e)}}if(r.type===`cancel`)return{status:`failed`,reason:new X};let i=this.registry.get(r.factor);if(!i)e=new Z(`Unknown authentication factor: ${r.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(i,r.code),{status:`proven`,obtained:this.readObtainedBar?.()??Q(this.rankedRequirement??n)}}catch(t){if(t instanceof J&&t.cancelled)return{status:`failed`,reason:new X};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof B&&t.kind===`not_registered`&&this.pruned.add(i.type),e=t,this.state=`collecting`,this.selected=null}}return{status:`failed`,reason:new B({kind:`attempts_exhausted`,...e?{cause:e}:{}})}}collect(e,t,n){let r={challenge:e,factors:t,...n?{previousError:n}:{},onFactorSelected:e=>{this.state===`collecting`&&(this.state=`proving`),this.selected=e,this.rankedRequirement=this.requirement}};return this.openPrompt=r,this.prompt(r)}classifyProofFailure(e){if(e instanceof V||e instanceof H||e instanceof U)return e;if(e instanceof B)switch(e.kind){case`unavailable`:return new H(e.message);case`exhausted`:case`attempts_exhausted`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new U(e.message);default:return}}async proveAndCommit(e,t){let n=e.requiresPrepare?await this.transport.prepare(e.type):void 0,r=await e.assert({code:t,prepared:n,platform:this.platform});await this.transport.commit(e.type,r)}},Pn=e=>typeof e==`function`?e():e,Fn=e=>{try{return new URL(e)}catch{return}},In=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},Ln=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&In(e.pathname,t.pathPrefix),Rn=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&In(e.pathname,n))return!0;continue}let t=Fn(n)??Fn(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&In(e.pathname,t.pathname))return!0}return!1},zn=(e,t,n)=>Ln(e,t.passflow)||Rn(e,t.backend)?!n||n(e.href)!==!1:!1,Bn=e=>{let t=e.detail,n=t?.message??`[passflow] upgrade challenge not actioned: ${e.reason}`;console.warn(n,{status:e.status,url:e.url,reason:e.reason,detail:t})},Vn=(e,t)=>{let n=t.onUpgradeDiagnostic??Bn;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Hn=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Bn;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},Un=/\bjson\b/i,Wn=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&Un.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return Ue(i?{status:e.status,getHeader:t=>e.getHeader(t)??void 0,body:a}:{status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:t.requireChallengeChannel})},Gn=e=>Ue({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,Kn=(e,t)=>t.passflow===null?`[passflow] a 401/403 from ${e} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.`:`[passflow] a 401/403 from ${e} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`,qn=(e,t)=>e instanceof X?{kind:`cancelled`}:e instanceof Z?{kind:`unsatisfiable`}:e instanceof H?{kind:`unavailable`}:e instanceof U?{kind:`session-changed`}:e instanceof V?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof B?e.kind===`exhausted`||e.kind===`attempts_exhausted`?{kind:`exhausted`,error:e}:e.kind===`unavailable`?{kind:`unavailable`}:e.kind===`session_changed`?{kind:`session-changed`}:{kind:`transport-failure`,status:e.status,retryable:e.retryable,error:e}:{kind:`transport-failure`,retryable:!1,error:e instanceof Error?e:Error(String(e))},Jn=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await Wn(e,t);if(Hn(a,e,t),!i)return{kind:`replayed`,response:e};let o=Q(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},Yn=async(e,t)=>{if(!t)return{aborted:!1,value:await e};if(t.aborted)return{aborted:!0,reason:t.reason};if(typeof t.addEventListener!=`function`)return{aborted:!1,value:await e};let n,r=new Promise(e=>{n=()=>e({aborted:!0,reason:t.reason}),t.addEventListener?.(`abort`,n)});try{return await Promise.race([e.then(e=>({aborted:!1,value:e})),r])}finally{n&&t.removeEventListener?.(`abort`,n)}},Xn=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Vn(e,t);if(e.markers.replayed){if(!zn(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Wn(e,t);if(Hn(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=Q(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!zn(e.request,t.scope,t.shouldIntercept))return Gn(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:Kn(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Wn(e,t);if(Hn(i,e,t),!r){let r=e.getHeader(`www-authenticate`);return t.requireChallengeChannel!==`header`&&n(`no-channel`,{...r?{header:r}:{},message:e.responseType===`cors`&&!r?`[passflow] a cross-origin ${e.status} from ${e.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.`:`[passflow] a ${e.status} from ${e.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${e.status}.`}),{kind:`not-a-challenge`}}if(e.replayable===!1)return n(`replay-unsupported`,{message:`[passflow] a ${e.status} from ${e.request.href} carried an upgrade challenge, but the request cannot be replayed (${e.replayUnsupportedReason??`unsupported body`}), so no prompt was opened.`}),{kind:`replay-unsupported`};let a=t.authorizationSwap?.(),o={kind:`request`,url:e.request.href,method:e.request.method},s,c;try{s=Promise.resolve(t.elevate(r,o)),c=await Yn(s,e.signal)}catch(e){return qn(e,void 0)}if(c.aborted)return s?.then(e=>e?.waiter.report({outcome:`failed`}),()=>{}),{kind:`aborted`,reason:c.reason};let l=c.value;if(e.signal?.aborted)return l?.waiter.report({outcome:`failed`}),{kind:`aborted`,reason:e.signal.reason};let u=l?.obtained??t.readObtainedBar?.()??Q(r),d=t.authorizationSwap?.(),f=d?{from:a?.from??d.from,to:d.to}:void 0;e.markers.replayed=!0;let p;try{p=await e.replay(f?{authorizationSwap:f}:void 0)}catch(t){if(t instanceof V)return l?.waiter.report({outcome:`insufficient`,obtained:t.obtained,required:t.required}),e.signal?.aborted?{kind:`aborted`,reason:e.signal.reason}:{kind:`insufficient`,obtained:t.obtained,required:t.required};if(l?.waiter.report({outcome:`failed`}),e.signal?.aborted)return{kind:`aborted`,reason:e.signal.reason};throw t}let m=await Jn(p,t,u,n);return m.kind===`insufficient`?l?.waiter.report({outcome:`insufficient`,obtained:m.obtained,required:m.required}):l?.waiter.report({outcome:`replayed`,obtained:u}),m},Zn=e=>{switch(e.kind){case`cancelled`:return new X;case`unsatisfiable`:return new Z;case`unavailable`:return new H;case`session-changed`:return new U;case`insufficient`:return new V(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},Qn=(e,t,n)=>{switch(e.kind){case`replayed`:return{settle:`resolve`,value:e.response.raw};case`not-a-challenge`:case`out-of-scope`:case`replay-unsupported`:return{settle:`resolve`,value:t};case`aborted`:return{settle:`reject`,error:e.reason};case`cancelled`:return n.onCancel===`reject`?{settle:`reject`,error:new X}:{settle:`resolve`,value:sr(t,e)};case`insufficient`:return{settle:`resolve`,value:sr(e.response?.raw??t,e)};default:return{settle:`resolve`,value:sr(t,e)}}},$n=(e,t)=>{switch(e.kind){case`replayed`:return e.response.rejected?{settle:`reject`,error:e.response.raw??t}:{settle:`resolve`,value:e.response.raw};case`aborted`:return{settle:`reject`,error:e.reason};default:return{settle:`reject`,error:Zn(e)??t}}},er=new WeakSet,tr=new WeakSet,nr=new WeakSet,rr=new WeakSet,ir=new WeakSet,ar=new WeakSet,or=new WeakSet,sr=(e,t)=>{switch(t.kind){case`cancelled`:er.add(e);break;case`exhausted`:tr.add(e);break;case`insufficient`:nr.add(e);break;case`unsatisfiable`:rr.add(e);break;case`unavailable`:ir.add(e);break;case`session-changed`:ar.add(e);break;case`transport-failure`:or.add(e)}return e},cr=e=>er.has(e),lr=e=>tr.has(e),ur=e=>nr.has(e),dr=e=>rr.has(e),fr=e=>ir.has(e),pr=e=>ar.has(e),mr=e=>or.has(e),hr=`https://passflow-relative.invalid`,gr=()=>{let e=globalThis,t=e.document?.baseURI;if(typeof t==`string`&&t!==``)return t;let n=e.location?.href;return typeof n==`string`&&n!==``&&n!==`about:blank`?n:hr},_r=(e,t=gr())=>{let n=t===hr,r;try{r=new URL(t).origin}catch{r=void 0}let i;try{i=new URL(e,t)}catch{i=void 0}return i?{href:i.href,origin:i.origin,pathname:i.pathname,resolved:!0,relativeToBase:r!==void 0&&i.origin===r,sentinelBase:n}:{href:e,pathname:e.split(/[?#]/)[0]??e,resolved:!1,relativeToBase:!1,sentinelBase:n}},vr=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,yr=e=>{let t=[];if(e==null)return Object.freeze(t);let n=e;if(typeof n.forEach==`function`&&typeof n.entries==`function`)return e.forEach((e,n)=>{let r=vr(n,e);r&&t.push(r)}),Object.freeze(t);if(Array.isArray(e)){for(let n of e)if(Array.isArray(n)&&n.length>=2){let e=vr(String(n[0]),n[1]);e&&t.push(e)}return Object.freeze(t)}if(typeof e==`object`)for(let[n,r]of Object.entries(e)){let e=vr(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},br=e=>{let t=e.base===void 0?_r(e.url):_r(e.url,e.base),n={raw:e.url,href:t.href,dispatchUrl:t.sentinelBase||!t.resolved?e.url:t.href,...t.origin===void 0?{}:{origin:t.origin},pathname:t.pathname,resolved:t.resolved,relativeToBase:t.relativeToBase,method:(e.method??`GET`).toUpperCase(),headers:yr(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},xr=(e,t)=>{if(!t||t.from===t.to)return e;let n=!1,r=e.map(([e,r])=>e===`authorization`&&r===t.from?(n=!0,[e,t.to]):[e,r]);return n?Object.freeze(r):e},Sr=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},Cr=new Set([`GET`,`HEAD`,`OPTIONS`]),wr=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,Tr=e=>typeof e==`string`?e:wr(e)?e.url:String(e),Er=(e,t)=>(t?.method??(wr(e)?e.method:void 0)??`GET`).toUpperCase(),Dr=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,Or=e=>{if(typeof e==`string`)return e.length;let t=e;if(typeof t?.size==`number`)return t.size;if(typeof t?.byteLength==`number`)return t.byteLength},kr=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?Cr.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),$=(e,t,n,r,i)=>({replayable:!1,bodyKind:e,reason:t,forwardInput:n,forwardInit:i,snapshot:r,replay:()=>Promise.reject(Error(`This request cannot be replayed: ${t}`))}),Ar=(e,t)=>Sr(xr(e.headers,t?.authorizationSwap)),jr=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},Mr=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:wr(e)?e.headers:void 0,Nr=e=>{if(e===null||typeof e==`string`)return e;if(typeof FormData<`u`&&e instanceof FormData){let t=new FormData;for(let[n,r]of e)t.append(n,r);return t}return typeof URLSearchParams<`u`&&e instanceof URLSearchParams?new URLSearchParams(e):e instanceof ArrayBuffer?e.slice(0):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice():e},Pr=(e,t,n)=>new Request(e,{headers:Ar(t,n)}),Fr=(e,t,n)=>{let r=Tr(e),i=Er(e,t),a=Mr(e,t),o=(e,t)=>br({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(wr(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return kr(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(Pr(e,a,r),jr(t))}:$(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!kr(n,{url:r,method:i,bodyKind:`request-clone`}))return $(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return $(`one-shot`,`the Request body was already consumed and cannot be cloned`,e,a,t)}return{replayable:!0,bodyKind:`request-clone`,forwardInput:e,forwardInit:t,snapshot:a,replay:(e,n)=>e(Pr(s,a,n),jr(t))}}let s=Dr(t?.body);if(s===`one-shot`)return $(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!kr(n,{url:r,method:i,bodyKind:s},Or(t?.body)))return $(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Nr(t.body??null):void 0,l=o(s,c);return{replayable:!0,bodyKind:s,forwardInput:e,forwardInit:t,snapshot:l,replay:(e,n)=>e(l.dispatchUrl,{...jr(t),...c===void 0?{}:{body:c},headers:Ar(l,n),method:l.method})}},Ir=e=>typeof e==`object`&&!!e,Lr=e=>t=>{if(!Ir(e))return;let n=e[t]??e[t.toLowerCase()]??(typeof e.get==`function`?e.get(t):void 0);return Array.isArray(n)?n.join(`, `):typeof n==`string`?n:void 0},Rr=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},zr=e=>(e?.method??`GET`).toUpperCase(),Br=e=>e==null?`none`:Ir(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,Vr=(e,t,n)=>{let r=Sr(xr(t.headers,n?.authorizationSwap)),i=t.dispatchUrl===t.href&&t.resolved;return{...e,...i?{baseURL:void 0}:{},url:t.dispatchUrl,method:t.method,headers:r,...`body`in t?{data:t.body}:{}}},Hr=(e,t,n,r,i,a)=>{let o=t??e?.config,s=Br(o?.data),c=a??br({url:Rr(o),method:zr(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&kr(i.replay,l);return{status:e?.status??0,getHeader:Lr(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=Xe(Vr(o??{},c,e));try{let e=await r(t);return Hr(e,e?.config??t,e,r,i,c)}catch(e){let n=Ir(e)?e:{};if(!n.response||typeof n.response.status!=`number`||Kt(e))throw e;return{...Hr(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...Ye(o)?{upgradeTransaction:!0}:{},...Ze(o)?{replayed:!0}:{}},raw:n,replayable:u,replayUnsupportedReason:s===`one-shot`?`a streaming request body is consumed by the first send`:`the replay policy refused this request`,signal:o?.signal}},Ur=(e,t)=>async n=>{let r=Pn(e),i=Ir(n)?n:{},a=$n(await Xn(Hr(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},Wr=(e,t,n)=>{let r=e.request,i=n??(typeof r==`function`?t=>r.call(e,t):()=>Promise.reject(Error(`Passflow: this client exposes no request() to replay through.`))),a=e.interceptors.response.use(void 0,Ur(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},Gr=(e,t)=>{let n=c.default.create(e);return t(n),n},Kr=0,qr=(e,t)=>{let n=t?.signal??(typeof e==`object`&&e?e.signal:void 0)??void 0;if(n)return{get aborted(){return n.aborted},get reason(){return n.reason},...typeof n.addEventListener==`function`?{addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)}:{}}},Jr=e=>t=>e.headers?.get(t),Yr=(e,t,n,r,i)=>({status:e.status,getHeader:Jr(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>Yr(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),Xr=(e,t)=>{let n=(t,n)=>{Kr+=1;try{return e(t,n)}finally{--Kr}};return async(e,r)=>{if(Kr>0)return n(e,r);let i=Pn(t),a=Fr(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=Qn(await Xn(Yr(o,a,n,{},qr(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},Zr=new Set(Y.filter(e=>!e.requiresPrepare).map(e=>e.type)),Qr=e=>{if(!e||typeof e!=`object`||!e.challenge_id||!e.expires_at)throw new B({kind:`protocol`,message:`The upgrade start response is missing challenge_id or expires_at`});return{challengeId:e.challenge_id,method:e.method,expiresAt:e.expires_at,webauthn:e.webauthn,codeSentTo:e.code_sent_to}},$r=e=>Kt(e)&&!qt(e),ei=e=>({async prepare(t){if(!Zr.has(t))try{let n=e.relyingPartyId?.();return Qr(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if($r(e))throw e;let t=Zt(e,`start`);if(t.kind===`prepare_not_required`)return;throw t}},async commit(t,n){let r=e.canCommit();if(!r.ok)throw new B({kind:`unavailable`,message:r.reason});try{await e.commitRefresh({type:t,assertion:n})}catch(t){if($r(t))throw t;let n=Zt(t,`refresh`);throw n.status===401&&$t(n)&&e.markSessionInvalid?.(),n}}}),ti=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),ni=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new B({kind:`session_changed`})};return ei({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new Nn({transport:r(()=>i.current),prompt:t.prompt,platform:e.platform,factors:t.factors??e.factors,...t.maxAttempts===void 0?{}:{maxAttempts:t.maxAttempts},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{},...t.onFlightSettled?{onFlightSettled:t.onFlightSettled}:{}}),options:t,scope:{passflow:e.passflowDomain,backend:ti(t.backend)},generation:n};return i.current=a,a},a=async(r,i)=>{let a=t;if(!a)throw new H(`Step-up verification is not enabled on this Passflow instance`);a.controller.active||(a.pin=e.readSessionPin?.());let o=await a.controller.elevate(r,i);if(!n(a))throw new U;return o},o=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:a,scope:r,...i?.requireChallengeChannel?{requireChallengeChannel:i.requireChallengeChannel}:{},...i?.shouldIntercept?{shouldIntercept:i.shouldIntercept}:{},...i?.replay===void 0?{}:{replay:i.replay},...i?.onCancel?{onCancel:i.onCancel}:{},...e.authorizationSwap?{authorizationSwap:e.authorizationSwap}:{},...i?.onUpgradeDiagnostic?{onUpgradeDiagnostic:i.onUpgradeDiagnostic}:{},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{}}},s;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:Ae(e.acrValues).level,n={status:401,...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{requiredLevel:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},r=e?.acrValues!==void 0||e?.maxAge!==void 0,i={...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{level:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},o=(await a(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...o===void 0?{}:{acr:o}}},{enable:{value:n=>{s?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>Ur(o,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(Dt((e,t,n)=>Xr(e,o)(t,n),{priority:20,name:`passflow-upgrade`})),e.onSessionChange&&r.push(e.onSessionChange(()=>{let e=t;e&&(t=i(e.options,e.generation+1))}));let a=!1;return s=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,s=void 0}},s},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>a(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:e=>{if(e)return Xr(e,o);let t=typeof globalThis>`u`?void 0:globalThis;if(!t||typeof t.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return Xr(t.fetch.bind(t),o)}},attachAuth:{enumerable:!0,value:e=>Wr(e,o)}})},ri,ii=class{get origin(){return this.platform.getCurrentUrl()?.origin??``}constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:e,expiredSession:t,doRefresh:n=!1})=>{this.createSessionCallback=e,this.expiredSessionCallback=t,this.doRefreshTokens=n,await this.submitSessionCheck()};let{url:t,appId:n,scopes:r}=e;this.url=t||`https://auth.passflow.cloud`,this.appId=n,this.platform=e.platform??b,this.storageManager=new Ce({prefix:e.keyStoragePrefix??``,storage:this.platform.storage}),this.deviceService=new we(this.storageManager),this.authApi=new ct(e,this.storageManager,this.deviceService),this.appApi=new st(e,this.storageManager,this.deviceService),this.userApi=new _t(e,this.storageManager,this.deviceService),this.settingApi=new dt(e,this.storageManager,this.deviceService),this.tenantApi=new ft(e,this.storageManager,this.deviceService),this.invitationApi=new ut(e,this.storageManager,this.deviceService),this.twoFactorApi=new ht(e,this.storageManager,this.deviceService),this.upgradeApi=new gt(e,this.storageManager,this.deviceService),this.upgradeDomain=Qe(e.url),this.subscribeStore=new zt,this.tokenCacheService=new mn(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??ne,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new un(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled()),this.userService=new gn(this.userApi,this.deviceService,this.platform),this.tenantService=new pn(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new dn(this.invitationApi),this.twoFactorService=new hn(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=ni({startUpgrade:e=>this.upgradeApi.startUpgrade(e),commitRefresh:async(e,t)=>{await this.authService.refreshToken(e,t)},readSessionPin:()=>this.authService.readSessionPin(),canCommit:()=>this.authService.tokenDeliveryManager.isBFFMode()?{ok:!1,reason:`Step-up verification cannot be committed through a BFF refresh endpoint`}:{ok:!0},markSessionInvalid:()=>this.authService.tokenDeliveryManager.setSessionInvalid(),platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{},readObtainedBar:()=>this.readAssuranceBar(),authorizationSwap:()=>{let e=this.storageManager.getToken(v.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e)}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readPkceEnabled(){if(!this.appId)return Promise.resolve(!1);if(!this.pkceEnabledRead){let e=this.appApi.getAppSettings().then(e=>e.pkce_enabled);this.pkceEnabledRead=e,e.catch(()=>{this.pkceEnabledRead===e&&(this.pkceEnabledRead=void 0)})}return this.pkceEnabledRead}setAppId(e){this.appId=e,this.pkceEnabledRead=void 0,this.authApi.setAppId(e),this.appApi.setAppId(e),this.userApi.setAppId(e),this.settingApi.setAppId(e),this.tenantApi.setAppId(e),this.invitationApi.setAppId(e),this.twoFactorApi.setAppId(e),this.upgradeApi.setAppId(e),this.authService}withAuth(e){return this.upgrade.withAuth(e)}attachAuth(e){return this.upgrade.attachAuth(e)}createClient(e){return Gr(e,e=>this.upgrade.attachAuth(e))}readAssuranceBar(){let e=this.storageManager.getToken(v.access_token);if(e)try{let t=_(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=Ae(n).level;return r===void 0?{acrValues:n}:{acrValues:n,level:r}}catch{return}}axiosClients(){return[this.authApi.axiosClient,this.appApi.axiosClient,this.userApi.axiosClient,this.settingApi.axiosClient,this.tenantApi.axiosClient,this.invitationApi.axiosClient,this.twoFactorApi.axiosClient,this.upgradeApi.axiosClient]}attachUpgradeSeam(e){for(let t of this.axiosClients()){if(!e){t.setUpgradeInterceptor(void 0);continue}let n=e(e=>t.replay(e));t.setUpgradeInterceptor(n)}}subscribeToSessionChange(e){let t={onAuthChange:()=>e()};return this.subscribeStore.subscribe(t,[R.SignIn,R.SignOut]),()=>this.subscribeStore.unsubscribe(t)}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(t){let n={message:t instanceof Error||t instanceof w?t.message:`Session check failed`,originalError:t};this.subscribeStore.notify(R.Error,n),e=void 0}e&&this.createSessionCallback&&await this.createSessionCallback({tokens:e,parsedTokens:t}),!e&&this.expiredSessionCallback&&await this.expiredSessionCallback()}subscribe(e,t){this.subscribeStore.subscribe(e,t),this.tokenCacheService.initialize()}unsubscribe(e,t){this.subscribeStore.unsubscribe(e,t)}handleTokensRedirect(){return this.checkAndSetTokens()}checkAndSetTokens(){let e=this.platform.getCurrentUrl(),t=new URLSearchParams(e?.search??``),n=!1;if(!t.get(`access_token`)&&e?.hash){let r=new URLSearchParams(e.hash.substring(1));r.get(`access_token`)&&(t=r,n=!0)}if(!t.get(`access_token`)&&this.adoptTwoFactorTokenFromUrl(e)){this.error=void 0;return}let r=t.get(`access_token`),i=t.get(`refresh_token`),a=t.get(`id_token`),o=t.get(`scopes`)?.split(`,`)??this.scopes,s;if(r){if(!W(r)){this.subscribeStore.notify(R.Error,{message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}if(i&&!W(i)){this.subscribeStore.notify(R.Error,{message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}if(a&&!W(a)){this.subscribeStore.notify(R.Error,{message:`Invalid ID token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}return s={access_token:r,refresh_token:i??void 0,id_token:a??void 0,scopes:o},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(s),this.tokenCacheService.setTokensCache(s),this.subscribeStore.notify(R.SignIn,{tokens:s,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(n,e),this.error=void 0,s}this.error=this.checkErrorsFromURL()}adoptTwoFactorTokenFromUrl(e){if(!e?.hash)return!1;let t=new URLSearchParams(e.hash.substring(1)),n=t.get(`tfa_token`);if(!n)return!1;t.delete(`tfa_token`);let r=t.toString();return this.platform.replaceUrl(e.pathname+e.search+(r?`#${r}`:``)),W(n)?(this.subscribeStore.notify(R.TwoFactorRequired,{email:``,challengeId:``,tfaToken:n}),!0):(this.subscribeStore.notify(R.Error,{message:`Invalid 2FA token format received`,code:`INVALID_TOKEN_FORMAT`}),!0)}checkErrorsFromURL(){let e=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`error`);if(e){let t=nn(e);return Error(t)}}cleanupUrlParams(e=!1,t=null){let n=t??this.platform.getCurrentUrl();if(n){if(e)this.platform.replaceUrl(n.pathname+n.search);else{let e=new URLSearchParams(n.search);e.delete(`access_token`),e.delete(`refresh_token`),e.delete(`id_token`),e.delete(`client_challenge`),e.size>0?this.platform.replaceUrl(`${n.pathname}?${e.toString()}`):this.platform.replaceUrl(n.pathname)}}}setTokensToCacheFromLocalStorage(){let e=this.storageManager.getTokens();if(!e?.access_token&&this.storageManager.getDeliveryMode()){if(e?.id_token&&this.storageManager.hasCookieModeIdToken()){this.tokenCacheService.setTokensCache(e);return}if(this.storageManager.hasJsonModeTokens())this.storageManager.clearDeliveryMode(),e=this.storageManager.getTokens();else{this.storageManager.deleteTokens();return}}e&&this.tokenCacheService.setTokensCache(e)}getCachedTokens(){return this.tokenCacheService.getTokens()}getTokensWithRefresh(){return this.tokenCacheService.getTokensWithRefresh()}getParsedTokens(){return this.tokenCacheService.getParsedTokens()}areTokensExpired(){return this.tokenCacheService.isExpired()}isAuthenticated(){let e=this.storageManager.getTokens();if(!e||!e.access_token)return!1;let t=this.tokenCacheService.getParsedTokens();return t?this.authService.isAuthenticated(t):!1}async signIn(e){return await this.authService.signIn(e)}async signUp(e){return await this.authService.signUp(e)}passwordlessSignIn(e){return this.authService.passwordlessSignIn(e)}async passwordlessSignInComplete(e){return await this.authService.passwordlessSignInComplete(e)}handleError(e,t){let n={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,n),e}async logOut(){try{await this.authService.logOut(),this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.twoFactorService.clearPartialAuthState(),await this.submitSessionCheck(),this.subscribeStore.notify(R.SignOut,{})}catch(e){this.handleError(e,`Log out`)}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}reset(e){if(this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.subscribeStore.notify(R.SignOut,{}),e){this.error=Error(e);let t={message:e,code:`RESET_ERROR`};throw this.subscribeStore.notify(R.Error,t),this.error}}async refreshToken(){if(!this.tokenCacheService.parsedTokensCache?.refresh_token)throw Error(`No refresh token found`);try{return await this.authService.refreshToken()}catch(e){throw e instanceof w||this.subscribeStore.notify(R.Error,{message:`Failed to refresh token`,originalError:e}),e}}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t){return await this.authService.resetPassword(e,t)}async getAppSettings(){try{return await this.appApi.getAppSettings()}catch(e){this.handleError(e,`Get app settings`)}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,`Get all settings`)}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,`Get password policy settings`)}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,`Get passkey settings`)}}async passkeyRegister(e){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){this.storageManager.saveTokens(e),this.tokenCacheService.setTokensCache(e),this.subscribeStore.notify(R.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()})}async getTokens(e=!1){return await this.authService.getTokens(e)}getToken(e){return this.storageManager.getToken(e)}async getUserPasskeys(){try{return await this.userService.getUserPasskeys()}catch(e){this.handleError(e,`Get user passkeys`)}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(e){this.handleError(e,`Rename user passkey`)}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(e){this.handleError(e,`Delete user passkey`)}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(e){this.handleError(e,`Add user passkey`)}}async joinInvitation(e,t){try{let n=await this.tenant.joinInvitation(e,t);return n.scopes=t??this.scopes,await this.authService.applyTokens(n),n}catch(e){this.handleError(e,`Join invitation`)}}async createTenant(e,t){try{let n=await this.tenant.createTenant(e);return t&&await this.refreshToken(),n}catch(e){this.handleError(e,`Create tenant`)}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(e){this.handleError(e,`Request invite link`)}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(e){this.handleError(e,`Get invitations`)}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(e){this.handleError(e,`Delete invitation`)}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(e){this.handleError(e,`Resend invitation`)}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(e){this.handleError(e,`Get invitation link`)}}authRedirectUrl(e={}){return this.authService.authRedirectUrl(e)}authRedirect(e={}){this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}async restoreSession(){return await this.authService.restoreSession()}async getTwoFactorStatus(){try{return await this.twoFactorService.getStatus()}catch(e){this.handleError(e,`Get 2FA status`)}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,`Begin 2FA setup`)}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(e){this.handleError(e,`Confirm 2FA setup`)}}async verifyTwoFactor(e,t){try{let n=await this.twoFactorService.verify(e,t);return this.subscribeStore.notify(R.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`Verify 2FA`)}}async useTwoFactorRecoveryCode(e,t){try{let n=await this.twoFactorService.useRecoveryCode(e,t);return this.subscribeStore.notify(R.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`Use 2FA recovery code`)}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(e){this.handleError(e,`Disable 2FA`)}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(e){this.handleError(e,`Regenerate 2FA recovery codes`)}}async getTrustedDevices(){try{return await this.twoFactorService.getTrustedDevices()}catch(e){this.handleError(e,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorService.revokeTrustedDevice(e)}catch(e){this.handleError(e,`Revoke trusted device`)}}isTwoFactorVerificationRequired(){return this.twoFactorService.isVerificationRequired()}getTotpDigits(){return this.twoFactorService.getTotpDigits()}async validateTwoFactorSetupMagicLink(e){return await this.twoFactorService.validateTwoFactorSetupMagicLink(e)}getMagicLinkSession(){return this.twoFactorService.getMagicLinkSession()}hasMagicLinkSession(){return this.twoFactorService.hasMagicLinkSession()}clearMagicLinkSession(){this.twoFactorService.clearMagicLinkSession()}};ri=ii,ri.version=ee,exports.APP_ID_HEADER_KEY=d,exports.AUTHORIZATION_HEADER_KEY=f,exports.AppAPI=st,exports.AuthAPI=ct,exports.AuthService=un,exports.CLIAuthAPI=lt,exports.DEFAULT_GROUP_NAME=ie,exports.DEFAULT_SCOPES=ne,exports.DEFAULT_UPGRADE_FACTORS=Y,exports.DEVICE_ID_HEADER_KEY=p,exports.DEVICE_TYPE_HEADER_KEY=m,exports.ERROR_MESSAGE_MAX_LENGTH=fe,exports.FETCH_PRIORITY_OIDC=vt,exports.FETCH_PRIORITY_UPGRADE=yt,exports.FetchMiddlewareContractError=bt,exports.INSUFFICIENT_USER_AUTHENTICATION=Me,exports.InvitationAPI=ut,exports.InvitationService=dn,exports.M2MClient=Nt,exports.M2MConfigError=F,exports.M2MError=N,exports.M2MErrorCodes=At,exports.M2MNetworkError=kt,exports.M2MTokenParseError=P,exports.M2M_DEFAULTS=I,exports.MINIMAL_DEFAULT_SCOPES=te,exports.OS=et,exports.PASSFLOW_CLOUD_URL=re,exports.POPUP_HEIGHT=oe,exports.POPUP_POLL_INTERVAL_MS=se,exports.POPUP_TIMEOUT_MS=ce,exports.POPUP_WIDTH=ae,exports.Passflow=ii,exports.PassflowAdminEndpointPaths=C,exports.PassflowEndpointPaths=S,exports.PassflowError=w,exports.PassflowEvent=R,exports.PopupClosedError=Te,exports.Providers=$e,exports.RECOVERABLE_COMMIT_ERROR_IDS=Bt,exports.RequestMethod=x,exports.SDK_VERSION=ee,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=Vt,exports.SessionState=xe,exports.SettingAPI=dt,exports.TOKEN_EXPIRY_BUFFER_SECONDS=le,exports.TenantAPI=ft,exports.TenantService=pn,exports.TenantUserMembership=fn,exports.TokenCacheService=mn,exports.TokenDeliveryMode=y,exports.TokenType=v,exports.TwoFactorApiClient=ht,exports.TwoFactorPolicy=tt,exports.TwoFactorService=hn,exports.UPGRADE_REQUIRED=Ne,exports.USERNAME_MAX_LENGTH=de,exports.USERNAME_MIN_LENGTH=ue,exports.UpgradeAPI=gt,exports.UpgradeCancelledError=X,exports.UpgradeController=Nn,exports.UpgradeErrorIds=z,exports.UpgradeFactorError=J,exports.UpgradeInsufficientError=V,exports.UpgradeSessionChangedError=U,exports.UpgradeTransportError=B,exports.UpgradeUnavailableError=H,exports.UpgradeUnsatisfiableError=Z,exports.UserAPI=_t,exports.UserService=gn,exports.WebAdapter=Ee,exports.classifyUpgradeError=Zt,exports.factorRegistry=xn,exports.fetchRegistryState=Ot,exports.getOSFromDeviceType=T,exports.invalidatesSessionOnCommit=$t,exports.isRecoverableCommitFailure=Qt,exports.isRetryableUpgradeKind=Ut,exports.isTokenExpired=g,exports.isUpgradeCancelled=cr,exports.isUpgradeExhausted=lr,exports.isUpgradeInsufficient=ur,exports.isUpgradeSessionChanged=pr,exports.isUpgradeTransportError=qt,exports.isUpgradeTransportFailure=mr,exports.isUpgradeUnavailable=fr,exports.isUpgradeUnsatisfiable=dr,exports.isValidEmail=G,exports.isValidJWTFormat=W,exports.isValidPhoneNumber=K,exports.isValidUsername=rn,exports.parseChallengeBody=Be,exports.parseChallengeHeader=ze,exports.parseToken=_,exports.parseUpgradeChallenge=We,exports.passkeyFactor=bn,exports.pathWithParams=E,exports.recoveryCodesFactor=yn,exports.registerFetchMiddleware=Dt,exports.requiredAcrLevel=je,exports.resolveUpgradeDomain=Qe,exports.sanitizeErrorMessage=nn,exports.selectFactors=En,exports.totpFactor=vn,exports.webAdapter=b;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("axios");c=s(c,1);let l=require("@simplewebauthn/browser");var u=`0.20.1`,d=`X-Passflow-Clientid`,f=`Authorization`,p=`X-Passflow-DeviceId`,m=`X-Passflow-DeviceType`,ee=u,te=[`id`,`offline`,`openid`],ne=[`id`,`offline`,`tenant`,`email`,`oidc`,`openid`,`access:tenant:all`],re=`https://auth.passflow.cloud`,ie=`default`,ae=500,oe=600,se=100,ce=6e4,le=30,ue=3,de=30,fe=200,h=[];for(let e=0;e<256;++e)h.push((e+256).toString(16).slice(1));function pe(e,t=0){return(h[e[t+0]]+h[e[t+1]]+h[e[t+2]]+h[e[t+3]]+`-`+h[e[t+4]]+h[e[t+5]]+`-`+h[e[t+6]]+h[e[t+7]]+`-`+h[e[t+8]]+h[e[t+9]]+`-`+h[e[t+10]]+h[e[t+11]]+h[e[t+12]]+h[e[t+13]]+h[e[t+14]]+h[e[t+15]]).toLowerCase()}var me=new Uint8Array(16);function he(){return crypto.getRandomValues(me)}function ge(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():_e(e,t,n)}function _e(e,t,n){e=e||{};let r=e.random??e.rng?.()??he();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return pe(r)}var ve=e=>{let t=[],n;for(n in e){let r=e[n];if(r===void 0)continue;let i={tenant:{id:r.tenant_id,name:r.tenant_name}};i.groups=r.groups?Object.keys(r.groups).map(e=>{let t=r.groups[e]||[];return{group:{id:e,name:r.group_names?.[e]??`unknown`},roles:t}}):[],i.tenantRoles=i.groups?.find(e=>e.group.id===r.root_group_id),t.push(i)}return{raw:e,tenants:t}};function ye(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}var be=class{constructor(e){this.storageManager=e}isTokenTypeExpired(e){let t=this.storageManager.getToken(e);if(!t)return!0;let n=_(t);return!n||g(n)}parseTokenType(e){let t=this.storageManager.getToken(e);if(t)return _(t)}};function g(e,t=30){return Math.floor(Date.now()/1e3)+t>e.exp}function _(e){let t=e.split(`.`)[1];if(!t)throw Error(`Invalid token string`);let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=ye(n+`=`.repeat((4-n.length%4)%4)),i=decodeURIComponent(r.split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)),a=JSON.parse(i);return a.membership=a.passflow_tm&&a.type!==`invite`?ve(a.passflow_tm):void 0,a}var v=function(e){return e.id_token=`id_token`,e.access_token=`access`,e.refresh_token=`refresh`,e.invite_token=`invite`,e.reset_token=`reset`,e.web_cookie=`web-cookie`,e.management=`management`,e.signin=`signin`,e.actor=`actor`,e.two_factor=`2fa`,e}({}),y=function(e){return e.JsonBody=`json_body`,e.Cookie=`cookie`,e.Mobile=`mobile`,e.BFF=`bff`,e}({}),xe=function(e){return e.Unknown=`unknown`,e.Valid=`valid`,e.Invalid=`invalid`,e}({}),Se=class{constructor(e){this.storageManager=e,this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.STORAGE_PREFIX=`passflow_`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.SESSION_STATE_KEY=`${this.STORAGE_PREFIX}session_state`,this.loadPersistedMode(),this.loadPersistedSessionState()}setMode(e){this.mode=e,this.isInitializedFlag=!0,this.persistMode()}getMode(){return this.mode}isCookieMode(){return this.mode===`cookie`}isJsonMode(){return this.mode===`json_body`}isMobileMode(){return this.mode===`mobile`}isBFFMode(){return this.mode===`bff`}isInitialized(){return this.isInitializedFlag}setSessionValid(){this.sessionState=`valid`,this.persistSessionState()}setSessionInvalid(){this.sessionState=`invalid`,this.persistSessionState()}setSessionUnknown(){this.sessionState=`unknown`,this.persistSessionState()}isSessionValid(){return this.sessionState===`valid`}isSessionUnknown(){return this.sessionState===`unknown`}isSessionInvalid(){return this.sessionState===`invalid`}getSessionState(){return this.sessionState}reset(){this.mode=`json_body`,this.sessionState=`unknown`,this.isInitializedFlag=!1,this.clearPersistedMode(),this.clearPersistedSessionState()}loadPersistedMode(){try{let e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(y).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{let e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(xe).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){try{this.storageManager.storage.setItem(this.DELIVERY_MODE_KEY,this.mode)}catch{}}persistSessionState(){try{this.storageManager.storage.setItem(this.SESSION_STATE_KEY,this.sessionState)}catch{}}clearPersistedMode(){try{this.storageManager.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.SESSION_STATE_KEY)}catch{}}},Ce=class{constructor({storage:e,prefix:t}={}){this.keyStoragePrefix=``,this.scopes=`${this.keyStoragePrefix}tokens_scopes`,this.deviceId=`${this.keyStoragePrefix}passflowDeviceId`,this.invitationToken=`${this.keyStoragePrefix}passflowInvitationToken`,this.previousRedirectUrl=`${this.keyStoragePrefix}passflowPreviousRedirectUrl`,this.STORAGE_PREFIX=`passflow_`,this.ID_TOKEN_KEY=`${this.STORAGE_PREFIX}id_token`,this.CSRF_TOKEN_KEY=`${this.STORAGE_PREFIX}csrf_token`,this.DELIVERY_MODE_KEY=`${this.STORAGE_PREFIX}delivery_mode`,this.storage=e??localStorage,this.keyStoragePrefix=t?`${t}_`:``}saveTokens(e,t){let{id_token:n,access_token:r,refresh_token:i,scopes:a}=e;t===y.Cookie||t===y.BFF?n&&this.storage.setItem(this.ID_TOKEN_KEY,n):(n&&this.storage.setItem(this.getKeyForTokenType(v.id_token),n),r&&this.storage.setItem(this.getKeyForTokenType(v.access_token),r),i&&this.storage.setItem(this.getKeyForTokenType(v.refresh_token),i),a&&this.storage.setItem(this.scopes,a.join(`,`)))}getToken(e){let t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){let e=this.getDeliveryMode();if(e===y.Cookie||e===y.BFF){let e=this.storage.getItem(this.ID_TOKEN_KEY);return e?{id_token:e}:void 0}let t=this.storage.getItem(this.getKeyForTokenType(v.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(v.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(v.refresh_token))??void 0,scopes:this.storage.getItem(this.scopes)?.split(`,`)??void 0}}getScopes(){return this.storage.getItem(this.scopes)?.split(`,`)??void 0}hasJsonModeTokens(){return!!this.storage.getItem(this.getKeyForTokenType(v.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){let t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(v.id_token)),this.storage.removeItem(this.getKeyForTokenType(v.access_token)),this.storage.removeItem(this.getKeyForTokenType(v.refresh_token)),this.storage.removeItem(this.scopes),this.clearIdToken(),this.clearDeliveryMode(),this.clearCsrfToken()}getDeviceId(){return this.storage.getItem(this.deviceId)??void 0}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.storage.removeItem(this.deviceId)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.storage.getItem(this.invitationToken)??void 0}deleteInvitationToken(){this.storage.removeItem(this.invitationToken)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.storage.getItem(this.previousRedirectUrl)??void 0}deletePreviousRedirectUrl(){this.storage.removeItem(this.previousRedirectUrl)}setDeliveryMode(e){try{this.storage.setItem(this.DELIVERY_MODE_KEY,e)}catch{}}getDeliveryMode(){try{let e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(y).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}getIdToken(){try{return this.storage.getItem(this.ID_TOKEN_KEY)??void 0}catch{return}}setIdToken(e){try{this.storage.setItem(this.ID_TOKEN_KEY,e)}catch{}}clearIdToken(){try{this.storage.removeItem(this.ID_TOKEN_KEY)}catch{}}getCsrfToken(){try{return this.storage.getItem(this.CSRF_TOKEN_KEY)??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.CSRF_TOKEN_KEY,e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.CSRF_TOKEN_KEY)}catch{}}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}},we=class{constructor(e){this.storageManager=e??new Ce}getDeviceId(){let e=this.storageManager.getDeviceId();if(!e){let e=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(e),e}return e}generateUniqueDeviceId(){return ge()}},Te=class extends Error{constructor(e=`Authentication popup was closed`){super(e),this.name=`PopupClosedError`}},Ee=class{constructor(){this.passkeys={startRegistration:e=>(0,l.startRegistration)({optionsJSON:e}),startAuthentication:e=>(0,l.startAuthentication)({optionsJSON:e})}}get storage(){return typeof localStorage>`u`?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}getCurrentUrl(){return typeof window>`u`?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window<`u`&&window.history.replaceState({},document.title,e)}navigateTo(e){typeof window<`u`&&(window.location.href=e)}onForeground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden||e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBackground(e){if(typeof document>`u`)return()=>{};let t=()=>{document.hidden&&e()};return document.addEventListener(`visibilitychange`,t),()=>document.removeEventListener(`visibilitychange`,t)}onBeforeUnload(e){return typeof window>`u`?()=>{}:(window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e))}isInForeground(){return typeof document>`u`||!document.hidden}openAuthUrl(e,t={}){let n=t.mode??`popup`;if(n===`redirect`)return window.location.href=e,new Promise(()=>{});if(n===`deeplink`)return Promise.reject(Error(`openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.`));let r=t.width??500,i=t.height??600,a=t.expectedReturnOrigin??window.location.origin,o=window.open(e,`_blank`,`width=${r},height=${i}`);return o?new Promise((e,t)=>{let n=Date.now(),r=setInterval(()=>{if(o.closed)clearInterval(r),t(new Te);else if(Date.now()-n>6e4)clearInterval(r),o.close(),t(Error(`Authentication popup timed out`));else try{if(o.location.href.startsWith(a)){let t=o.location.search,n=o.location.hash;clearInterval(r),o.close(),e({callbackSearch:t,callbackHash:n})}}catch{}},100)}):(window.location.href=e,new Promise(()=>{}))}btoa(e){return btoa(e)}atob(e){if(typeof window<`u`&&typeof window.atob==`function`)return window.atob(e);if(typeof Buffer<`u`)return Buffer.from(e,`base64`).toString(`utf-8`);throw Error(`No Base64 decoding method available in this environment`)}cookiesSupported(){if(typeof document>`u`)return!1;try{document.cookie=`passflow_test=1; SameSite=Lax`;let e=document.cookie.indexOf(`passflow_test=1`)!==-1;return document.cookie=`passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC`,e}catch{return!1}}getDeviceType(){return`web`}},b=new Ee,De=/^[0-9]+$/,Oe=Object.freeze({unorderable:!1,zero:!1}),ke=e=>De.test(e)?Number.parseInt(e,10):void 0,Ae=e=>{if(!e)return Oe;let t=e.split(/\s+/).filter(e=>e!==``);if(t.length===0)return Oe;let n=[];for(let e of t){let t=ke(e);t!==void 0&&n.push(t)}if(n.length===0)return{raw:e,unorderable:!0,zero:!1};let r=Math.min(...n);return r===0?{raw:e,unorderable:!1,zero:!0}:{level:r,raw:e,unorderable:!1,zero:!1}},je=e=>Ae(e).level,Me=`insufficient_user_authentication`,Ne=`upgrade_required`,Pe=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,Fe=e=>e.replace(/\\(.)/g,`$1`),Ie=e=>{let t={};Pe.lastIndex=0;for(let n of e.matchAll(Pe)){let e=n[1];if(!e)continue;let r=n[2],i=n[3];t[e.toLowerCase()]=r===void 0?i??``:Fe(r)}return t},Le=e=>{if(e==null||e===``)return{kind:`absent`};let t=typeof e==`number`?e:Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?{kind:`valid`,value:t}:{kind:`invalid`,raw:e}},Re=e=>{let t=Le(e);return t.kind===`valid`?t.value:void 0},ze=(e,t)=>{if(!e||!/(^|[\s,])Bearer\b/i.test(e))return;let n=Ie(e);if(n.error===`insufficient_user_authentication`)return{acrValues:n.acr_values||void 0,maxAge:Re(n.max_age),status:t}},Be=(e,t)=>{if(!e||typeof e!=`object`)return;let n=e;if(n.error===`upgrade_required`)return{acrValues:typeof n.acr_values==`string`&&n.acr_values?n.acr_values:void 0,maxAge:Re(n.max_age),status:t}},Ve=(e,t,n)=>({channel:e,acr:Ae(t.acrValues),maxAge:Le(n),raw:t.acrValues}),He=e=>e?Ie(e):{},Ue=(e,t)=>{let{status:n}=e;if(n!==401&&n!==403)return{diagnostics:[]};let r=t?.requireChallengeChannel===`header`,i=e.getHeader(`www-authenticate`),a=ze(i,n),o=r?void 0:Be(e.body,n),s=[],c=(e,t)=>{s.push({status:n,url:``,reason:e,...t?{detail:t}:{}})};if(!a&&!o)return r&&c(`header-required-but-absent`,i?{header:i}:void 0),{diagnostics:s};let l=[];if(a&&l.push(Ve(`header`,a,He(i).max_age)),o){let t=e.body;l.push(Ve(`body`,o,t?.max_age))}let u=e=>e;for(let e of l)e.acr.unorderable&&c(`channels-unorderable`,{[u(e.channel)]:e.raw}),e.acr.zero&&c(`zero-constraint-ignored`,{field:`acr_values`,[u(e.channel)]:e.raw}),e.maxAge.kind===`invalid`&&c(`zero-constraint-ignored`,{field:`max_age`,[u(e.channel)]:String(e.maxAge.raw)});let d=l.filter(e=>e.acr.level!==void 0),f,p;for(let e of d){let t=e.acr.level;f===void 0||t>f?(f=t,p=e.raw):t===f&&e.channel===`header`&&(p=e.raw)}let m;for(let e of l)e.maxAge.kind===`valid`&&(m===void 0||e.maxAge.value<m)&&(m=e.maxAge.value);if(l.length===2){let[e,t]=l,n=e.acr.level!==void 0&&t.acr.level!==void 0&&e.acr.level!==t.acr.level,r=e.maxAge.kind===`valid`&&t.maxAge.kind===`valid`&&e.maxAge.value!==t.maxAge.value;(n||r)&&c(`channels-disagree`,{header:e.raw??t.raw,body:t.raw??e.raw})}return{challenge:{acrValues:p,requiredLevel:f,maxAge:m,status:n,channels:l.map(e=>e.channel)},diagnostics:s}},We=(e,t,n)=>Ue({status:e,getHeader:t,body:n}).challenge,Ge=`__passflowUpgradeTransaction`,Ke=`__passflowUpgradeReplayed`,qe=(e,t)=>typeof e==`object`&&!!e&&e[t]===!0,Je=e=>({...e??{},[Ge]:!0}),Ye=e=>qe(e,Ge),Xe=e=>({...e,[Ke]:!0}),Ze=e=>qe(e,Ke),x=function(e){return e.GET=`get`,e.POST=`post`,e.PUT=`put`,e.PATCH=`patch`,e.DELETE=`delete`,e}({}),S=function(e){return e.signin=`/auth/login`,e.signup=`/auth/register`,e.pkceExchange=`/auth/pkce_exchange`,e.signInWithProvider=`/auth/federated/start/`,e.passwordless=`/auth/passwordless/start`,e.passwordlessComplete=`/auth/passwordless/complete`,e.logout=`/user/logout`,e.refresh=`/auth/refresh`,e.validateSession=`/user/me`,e.sendPasswordResetEmail=`/auth/password/reset`,e.resetPassword=`/auth/password/change`,e.appSettings=`/app/settings`,e.passkeyRegisterStart=`/auth/passkey/register/start`,e.passkeyRegisterComplete=`/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/auth/passkey/authenticate/complete`,e.passkeyValidate=`/auth/validate`,e.settingsAll=`/settings`,e.settingsPasswordPolicy=`/settings/password`,e.settingsPasskey=`/settings/passkey`,e.userPasskey=`/user/passkey`,e.addUserPasskey=`/user/passkey/add/start`,e.completeAddUserPasskey=`/user/passkey/add/complete`,e.joinInvitation=`/user/tenant/join`,e.tenantPath=`/user/tenant`,e.invitationsPath=`/user/tenant/:tenantID/invitations`,e.requestInvitation=`/user/invite`,e.invitationDelete=`/user/invite/:invitationID`,e.invitationResend=`/user/invite/:invitationID/resend`,e.invitationGetLink=`/user/invite/:invitationID/link`,e.twoFactor=`/user/2fa`,e.twoFactorStatus=`/user/2fa/status`,e.twoFactorSetupBegin=`/user/2fa/setup/begin`,e.twoFactorSetupConfirm=`/user/2fa/setup/confirm`,e.twoFactorVerify=`/auth/2fa/verify`,e.twoFactorRecovery=`/auth/2fa/recovery`,e.twoFactorRegenerateCodes=`/user/2fa/recovery-codes/regenerate`,e.twoFactorSetupMagicLink=`/auth/2fa-setup`,e.TwoFactorMethodsAvailable=`/v2/user/2fa/methods/available`,e.TwoFactorMethodsRegistered=`/v2/user/2fa/methods`,e.TwoFactorSetupStart=`/v2/user/2fa/setup/start`,e.TwoFactorSetupComplete=`/v2/user/2fa/setup/complete`,e.TwoFactorMethodRemove=`/v2/user/2fa/methods/:id`,e.TwoFactorChallenge=`/v2/auth/2fa/challenge`,e.TwoFactorVerifyV2=`/v2/auth/2fa/verify`,e.TwoFactorAlternative=`/v2/auth/2fa/alternative`,e.TwoFactorTrustedDevices=`/v2/user/2fa/trusted-devices`,e.TwoFactorTrustedDeviceRevoke=`/v2/user/2fa/trusted-devices/:id`,e.cliAuthStatus=`/cli/auth/status/:sessionId`,e.cliAuthComplete=`/cli/auth/complete`,e.upgradeStart=`/auth/upgrade/start`,e}({}),C=function(e){return e.passkeyRegisterStart=`/admin/auth/passkey/register/start`,e.passkeyRegisterComplete=`/admin/auth/passkey/register/complete`,e.passkeyAuthenticateStart=`/admin/auth/passkey/authenticate/start`,e.passkeyAuthenticateComplete=`/admin/auth/passkey/authenticate/complete`,e.passkeyValidate=`/admin/auth/validate`,e.logout=`/admin/auth/logout`,e}({}),Qe=e=>{if(!e)return null;try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return{origin:t.origin,pathPrefix:n===``?void 0:n}}catch{return null}},w=class extends Error{constructor(e){super(),this.id=e?.id??`unknown`,this.message=e?.message??e??`Something went wrong`,this.status=e?.status??500,this.location=e?.location??`unknown`,this.time=e?.time??new Date().toISOString()}},$e=function(e){return e.google=`google`,e.facebook=`facebook`,e}({}),et=function(e){return e.web=`web`,e.ios=`ios`,e.android=`android`,e}({});function T(e){return e}function E(e,t){let n=e;return Object.entries(t).forEach(([e,t])=>{n=n.replace(`:${e}`,t)}),n}var tt=function(e){return e.Disabled=`disabled`,e.Optional=`optional`,e.Required=`required`,e}({}),nt=3,rt=1e3,it=e=>t=>{let n=e.headers?.[t]??e.headers?.[t.toLowerCase()];return Array.isArray(n)?n.join(`, `):n},at=e=>We(e.status,it(e),e.data),ot=e=>at(e)!==void 0,D=class{get origin(){return this._platform.getCurrentUrl()?.origin??``}constructor(e,t,n){this.refreshPromise=null,this.isRefreshing=!1,this.defaultHeaders={Accept:`application/json`,"Content-Type":`application/json`},this.nonAccessTokenEndpoints=[`/auth/`,`/settings`,`/settings/`],this.protectedEndpoints=[`logout`,`refresh`,`upgrade`];let{url:r,appId:i,keyStoragePrefix:a}=e;this._platform=e.platform??b,this.url=r||`https://auth.passflow.cloud`,this.upgradeDomain=Qe(r),this.storageManager=t??new Ce({prefix:a??``}),this.deviceService=n??new we(this.storageManager),this.tokenService=new be(this.storageManager),this.tokenDeliveryManager=new Se(this.storageManager),i&&(this.appId=i,this.defaultHeaders={...this.defaultHeaders,[d]:i});let o=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[p]:o,[m]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=c.default.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async e=>{if(this.isNonAuthEndpoint(e.url))return e;if(this.tokenDeliveryManager.isCookieMode()){e.withCredentials=!0;let t=this.storageManager.getCsrfToken();return t&&(e.headers[`X-CSRF-Token`]=t),e}if(e.url?.includes(`refresh`)){if(this.isRefreshing){let t=new AbortController;return t.abort(),e.signal=t.signal,e}return e}let t=this.storageManager.getTokens();if(t?.access_token){if(g(_(t.access_token),30)&&t.refresh_token)try{if(this.refreshPromise){let t=await this.refreshPromise;return t?.data?.access_token&&(e.headers[f]=`Bearer ${t.data.access_token}`),e}this.refreshPromise=this.refreshTokens();try{let t=await this.refreshPromise;return t?.data?.access_token&&(e.headers[f]=`Bearer ${t.data.access_token}`),e}finally{this.refreshPromise=null}}catch(e){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(e)}return e.headers[f]=`Bearer ${t.access_token}`,e}return e}),this.instance.interceptors.response.use(e=>e,async e=>{if(e.response?.status===401&&!this.isUpgradeTransactionError(e)&&this.tokenDeliveryManager.setSessionInvalid(),e.response&&this.upgradeHandler){let t=at(e.response);if(t)try{return await this.upgradeHandler(e,t)}catch(t){if(t!==e)throw t}}return e.response?.status===429?await this.handleRateLimitError(e):this.handleAxiosError(e)})}isUpgradeTransactionError(e){return Ye(e.config)||e.response!==void 0&&ot(e.response)}setUpgradeInterceptor(e){this.upgradeHandler=e}replay(e){return this.instance.request(e)}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw Error(`Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.`)}async refreshTokens(){if(this.tokenDeliveryManager.isCookieMode()){let e=await this.instance.post(S.refresh,{},{withCredentials:!0});return this.tokenDeliveryManager.setSessionValid(),e.data.csrf_token&&this.storageManager.setCsrfToken(e.data.csrf_token),e.data.id_token&&this.storageManager.setIdToken(e.data.id_token),e}{let e=this.storageManager.getTokens(),t=this.storageManager.getScopes();if(!e?.refresh_token)throw Error(`No refresh token available`);this.isRefreshing=!0;let n={refresh_token:e.refresh_token,scopes:t},r=await this.instance.post(S.refresh,n,{headers:{[f]:`Bearer ${e.refresh_token}`}});return r.data&&this.storageManager.saveTokens(r.data),this.isRefreshing=!1,r}}async handleRateLimitError(e){let t=e.config;if(!t)return Promise.reject(e);let n=t.method?.toUpperCase();if(![`GET`,`HEAD`,`OPTIONS`].includes(n||``))return Promise.reject(e);let r=t._retryCount||0;if(r>=nt)return Promise.reject(e);let i=rt*2**r,a=e.response?.headers?.[`retry-after`];if(a){let e=Number.parseInt(a,10);if(!Number.isNaN(e))i=e*1e3;else{let e=new Date(a);Number.isNaN(e.getTime())||(i=Math.max(0,e.getTime()-Date.now()))}}return await new Promise(e=>setTimeout(e,i)),t._retryCount=r+1,this.instance.request(t)}async handleAxiosError(e){if(!e.response)return Promise.reject(e);let t=e.response.status,n=e.response.data;if(`error`in n&&typeof n.error==`object`&&n.error!==null){let{error:e}=n;return Promise.reject(new w(e))}return Promise.reject(new w({id:`error.http.${t}`,message:e.message||`An error occurred`,status:t,location:e.config?.url||`unknown`,time:new Date().toISOString()}))}async send(e,t,n){return(await this.instance.request({method:e,url:t,...n})).data}get(e,t){return this.send(x.GET,e,t)}post(e,t,n){return this.send(x.POST,e,{data:t,...n})}put(e,t,n){return this.send(x.PUT,e,{data:t,...n})}patch(e,t,n){return this.send(x.PATCH,e,{data:t,...n})}delete(e,t){return this.send(x.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[d]:e},this.instance.defaults.headers.common[d]=e}},st=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(S.appSettings)}},O={withCredentials:!0},ct=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,n,r){let i={access:n,scopes:t,...r?{upgrade:r}:{}},a={headers:{[f]:`Bearer ${e}`}};return this.axiosClient.post(S.refresh,i,r?Je(a):a)}signIn(e,t,n){let r={...e,device:t,os:n};return this.axiosClient.post(S.signin,r,O)}signUp(e){let{create_tenant:t,anonymous:n}=e,r={...e,create_tenant:t??!1,anonymous:n??!1};return this.axiosClient.post(S.signup,r,O)}pkceExchange(e,t){return this.axiosClient.post(S.pkceExchange,{authz_code:e,verifier:t},O)}passwordlessSignIn(e,t,n){let{create_tenant:r}=e,i={...e,create_tenant:r??!1,device:t,os:n};return this.axiosClient.post(S.passwordless,i)}passwordlessSignInComplete(e){return this.axiosClient.post(S.passwordlessComplete,e,O)}logOut(e,t,n=!1){let r=n?void 0:{refresh_token:t,device:e},i=n?C.logout:S.logout;return this.axiosClient.post(i,r)}validateSession(){return this.axiosClient.get(S.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(S.sendPasswordResetEmail,e)}resetPassword(e,t,n,r){let i={password:e,scopes:t,...r?{code_challenge:r}:{}};return this.axiosClient.post(S.resetPassword,i,{headers:{[f]:`Bearer ${n}`,[d]:void 0}})}passkeyRegisterStart(e,t,n,r=!1){let{create_tenant:i}=e,a={...e,create_tenant:i??!1,device:t,os:n},o=r?C.passkeyRegisterStart:S.passkeyRegisterStart;return this.axiosClient.post(o,a)}passkeyRegisterComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?C.passkeyRegisterComplete:S.passkeyRegisterComplete;return this.axiosClient.post(a,i,O)}passkeyAuthenticateStart(e,t,n,r=!1){let i={...e,user_id:e.user_id??``,device:t,os:n},a=r?C.passkeyAuthenticateStart:S.passkeyAuthenticateStart;return this.axiosClient.post(a,i)}passkeyAuthenticateComplete(e,t,n,r=!1){let i={challenge_id:n,device:t,passkey_data:e},a=r?C.passkeyAuthenticateComplete:S.passkeyAuthenticateComplete;return this.axiosClient.post(a,i,O)}passkeyValidate(e,t,n,r=!1,i){let a={otp:e,device:t,challenge_id:n},o=S.passkeyValidate;!i&&r&&(o=C.passkeyValidate);let s=i?{[d]:i}:{};return this.axiosClient.post(o,a,{headers:s})}},lt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){let t=E(S.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(S.cliAuthComplete,e)}},ut=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(S.requestInvitation,e)}getInvitations(e){let t={};e.groupID&&(t.group_id=e.groupID.toString()),e.skip!==void 0&&(t.skip=e.skip.toString()),e.limit!==void 0&&(t.limit=e.limit.toString());let n=E(S.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(n,{params:t}).then(e=>({invites:e.invites,nextPageSkip:e.next_page_skip}))}deleteInvitation(e){let t=E(S.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){let t=E(S.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){let t=E(S.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}},dt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(S.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(S.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(S.settingsPasskey)}},ft=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){let n={invite_token:e,scopes:t};return this.axiosClient.post(S.joinInvitation,n)}createTenant(e){let t={name:e};return this.axiosClient.post(S.tenantPath,t)}getTenantDetails(e){let t=`${S.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){let n=`${S.tenantPath}/${e}`,r={name:t};return this.axiosClient.put(n,r)}deleteTenant(e){let t=`${S.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(S.tenantPath)}createGroup(e,t){let n=`${S.tenantPath}/${e}/group`,r={name:t};return this.axiosClient.post(n,r)}getGroupInfo(e,t){let n=`${S.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(n)}updateGroup(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteGroup(e,t){let n=`${S.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(n)}addUserToGroup(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/add`,a={user_id:n,role:r};return this.axiosClient.post(i,a)}removeUserRolesFromGroup(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/remove_roles`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}changeUserRoles(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/change`,a={user_id:n,roles:r};return this.axiosClient.post(i,a)}deleteUserFromGroup(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/${n}`;return this.axiosClient.delete(r)}getRolesForTenant(e){let t=`${S.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){let n=`${S.tenantPath}/${e}/role`,r={name:t};return this.axiosClient.post(n,r)}updateRole(e,t,n){let r=`${S.tenantPath}/${e}/role/${t}`,i={name:n};return this.axiosClient.put(r,i)}deleteRole(e,t){let n=`${S.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(n)}deleteUserFromTenant(e,t){let n=`${S.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(n)}getGroupInvitations(e,t,n,r){let i=`${S.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(i,{params:{limit:n,skip:r}})}getTenantInvitations(e,t,n){let r=`${S.tenantPath}/${e}/invitations`;return this.axiosClient.get(r,{params:{limit:t,skip:n}})}invalidateInviteById(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/invite/${n}`;return this.axiosClient.delete(r)}invalidateInviteByEmail(e,t,n){let r=`${S.tenantPath}/${e}/group/${t}/invite/email/${n}`;return this.axiosClient.delete(r)}},pt=e=>e?{headers:{Authorization:`Bearer ${e}`}}:{},mt=e=>({withCredentials:!0,...pt(e)}),ht=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(){return this.axiosClient.get(S.twoFactorStatus)}beginSetup(){return this.axiosClient.post(S.twoFactorSetupBegin,{})}confirmSetup(e){return this.axiosClient.post(S.twoFactorSetupConfirm,e)}verify(e){let{tfa_token:t,code:n,trust_device:r}=e;return this.axiosClient.post(S.twoFactorVerify,{code:n,...r?{trust_device:!0}:{}},mt(t))}useRecoveryCode(e){let{tfa_token:t,recovery_code:n,trust_device:r}=e;return this.axiosClient.post(S.twoFactorRecovery,{recovery_code:n,...r?{trust_device:!0}:{}},mt(t))}disable(e){return this.axiosClient.delete(S.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(S.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){let t=`${S.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(e,t)=>(t&&delete t.Authorization,e)]}).then(e=>{let t=e;return{success:!0,sessionToken:t.session_token,userId:t.user_id,expiresIn:t.expires_in,appId:t.app_id}}).catch(e=>{if(e.response){let t=e.response.status,n=e.response.data||{},r=e.response.headers?.[`retry-after`]?parseInt(e.response.headers[`retry-after`],10):void 0;return{success:!1,error:{code:n.error||this.mapStatusToErrorCode(t),message:n.message||this.getDefaultErrorMessage(t),retryAfter:r}}}return{success:!1,error:{code:`SERVER_ERROR`,message:e instanceof Error?e.message:`Unable to connect to the server. Please check your connection.`}}})}mapStatusToErrorCode(e){switch(e){case 400:return`INVALID_TOKEN`;case 404:return`REVOKED_TOKEN`;case 410:return`EXPIRED_TOKEN`;case 429:return`RATE_LIMITED`;default:return`SERVER_ERROR`}}getDefaultErrorMessage(e){switch(e){case 400:return`The provided magic link is invalid or malformed.`;case 404:return`This magic link has been revoked or does not exist.`;case 410:return`This magic link has expired. Please request a new one from your administrator.`;case 429:return`Too many validation attempts. Please try again later.`;default:return`An error occurred while validating the magic link.`}}getAvailableMethods(){return this.axiosClient.get(S.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(S.TwoFactorMethodsRegistered)}startMethodSetup(e,t){return this.axiosClient.post(S.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(S.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){let t=E(S.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e,t){return this.axiosClient.post(S.TwoFactorChallenge,e,pt(t))}verifyV2(e,t){let{trust_device:n,...r}=e;return this.axiosClient.post(S.TwoFactorVerifyV2,{...r,...n?{trust_device:!0}:{}},mt(t))}switchToAlternative(e,t){return this.axiosClient.post(S.TwoFactorAlternative,e,pt(t))}async getTrustedDevices(){return(await this.axiosClient.get(S.TwoFactorTrustedDevices,{withCredentials:!0}))?.devices??[]}revokeTrustedDevice(e){let t=E(S.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}},gt=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}startUpgrade(e){return this.axiosClient.post(S.upgradeStart,e,Je({}))}},_t=class{constructor(e,t,n){this.axiosClient=new D(e,t,n)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(S.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${S.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${S.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:n,passkeyDisplayName:r,passkeyUsername:i}){let a={passkey_display_name:r,passkey_username:i,relying_party_id:e,deviceId:t,os:n};return this.axiosClient.post(S.addUserPasskey,a)}addUserPasskeyComplete(e,t,n){return this.axiosClient.post(S.completeAddUserPasskey,{challenge_id:n,device:t,passkey_data:e})}},vt=10,yt=20,bt=class extends Error{constructor(e){super(`Passflow fetch middleware '${e}' resolved without calling next(). Every registered middleware must delegate exactly once; swallowing a request would drop a caller's fetch inside the Passflow wrapper.`),this.name=`FetchMiddlewareContractError`,this.middlewareName=e}},k=[],xt=0,A=!1,j,M,St=(e,t)=>e.priority-t.priority||e.seq-t.seq,Ct=()=>typeof globalThis>`u`?void 0:globalThis,wt=async(e,t,n,r)=>{if(t>=e.length){let e=j;if(!e)throw Error(`Passflow fetch registry: no captured fetch to delegate to.`);return e(n,r)}let i=e[t];if(!i)return wt(e,e.length,n,r);let a=!1,o=await i.middleware((n,r)=>(a=!0,wt(e,t+1,n,r)),n,r);if(!a)throw new bt(i.name);return o},Tt=()=>{let e=Ct();if(!e||typeof e.fetch!=`function`)return!1;let t=e.fetch.bind(e),n=(e,t)=>wt([...k].sort(St),0,e,t);return j=t,M=n,e.fetch=n,A=!0,!0},Et=()=>{let e=Ct();e&&M&&e.fetch===M&&(j&&(e.fetch=j),A=!1,M=void 0,j=void 0)},Dt=(e,t)=>{if(!A&&!Tt())return()=>{};let n={middleware:e,name:t.name,priority:t.priority,seq:xt++};k.push(n);let r=!1;return()=>{r||(r=!0,k=k.filter(e=>e!==n),k.length===0&&Et())}},Ot=()=>{let e=Ct();return{installed:A,names:[...k].sort(St).map(e=>e.name),foreignPatch:A&&!!e&&!!M&&e.fetch!==M}},N=class e extends Error{constructor(t){super(t.message),this.name=`M2MError`,this.code=t.code,this.status=t.status??400,this.errorUri=t.errorUri,this.rateLimitInfo=t.rateLimitInfo,this.headers=t.headers,this.cause=t.cause,this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromOAuthError(t,n,r){let i=r?e.parseRateLimitHeaders(r):void 0;return new e({code:t.error,message:t.error_description??e.getDefaultMessage(t.error),status:n,errorUri:t.error_uri,rateLimitInfo:i,headers:r})}static fromError(t,n=`server_error`){return new e({code:n,message:t.message||`An unexpected error occurred`,status:500,cause:t})}static parseRateLimitHeaders(e){let t=e[`x-ratelimit-limit`],n=e[`x-ratelimit-remaining`],r=e[`x-ratelimit-reset`]||e[`retry-after`];if(t&&n&&r)return{limit:parseInt(t,10),remaining:parseInt(n,10),reset:parseInt(r,10)}}static getDefaultMessage(e){return{invalid_request:`The request is missing a required parameter or is otherwise malformed.`,invalid_client:`Client authentication failed. Verify your client credentials.`,invalid_grant:`The provided authorization grant is invalid or expired.`,invalid_scope:`The requested scope is invalid, unknown, or exceeds the allowed scopes.`,unauthorized_client:`The client is not authorized to use this grant type.`,unsupported_grant_type:`The authorization grant type is not supported.`,rate_limit_exceeded:`Too many requests. Please retry after the rate limit window resets.`,server_error:`The authorization server encountered an unexpected error.`,temporarily_unavailable:`The authorization server is temporarily unavailable. Please try again later.`}[e]||`An unknown error occurred.`}isRetryable(){return this.code===`server_error`||this.code===`temporarily_unavailable`||this.code===`rate_limit_exceeded`||this.status>=500}getRetryAfter(){if(this.rateLimitInfo?.reset){let e=Math.floor(Date.now()/1e3),t=this.rateLimitInfo.reset-e;return Math.max(t*1e3,1e3)}return 1e3}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,errorUri:this.errorUri,rateLimitInfo:this.rateLimitInfo,timestamp:this.timestamp}}toString(){let e=`M2MError [${this.code}]: ${this.message}`;return this.status&&(e+=` (HTTP ${this.status})`),e}},kt=class extends N{constructor(e,t){super({code:`temporarily_unavailable`,message:e,status:0,cause:t}),this.name=`M2MNetworkError`}},P=class extends N{constructor(e,t){super({code:`invalid_request`,message:e,status:400,cause:t}),this.name=`M2MTokenParseError`}},F=class extends N{constructor(e){super({code:`invalid_request`,message:e,status:400}),this.name=`M2MConfigError`}},At={InvalidRequest:`invalid_request`,InvalidClient:`invalid_client`,InvalidGrant:`invalid_grant`,InvalidScope:`invalid_scope`,UnauthorizedClient:`unauthorized_client`,UnsupportedGrantType:`unsupported_grant_type`,RateLimitExceeded:`rate_limit_exceeded`,ServerError:`server_error`,TemporarilyUnavailable:`temporarily_unavailable`},I={TOKEN_ENDPOINT:`/oauth2/token`,TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:`application/x-www-form-urlencoded`},jt=class{constructor(){this.cache=new Map}get(e){let t=this.cache.get(e);return t?Date.now()>=t.expiresAt?(this.cache.delete(e),Promise.resolve(null)):Promise.resolve(t.token):Promise.resolve(null)}set(e,t,n){return this.cache.set(e,{token:t,expiresAt:Date.now()+n*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}},Mt={shouldRetry(e,t){return t>=3?!1:e.code===`server_error`||e.code===`temporarily_unavailable`||e.code===`rate_limit_exceeded`||e.status!==void 0&&e.status>=500},getDelay(e){return 2**(e-1)*1e3}},Nt=class{constructor(e){if(!e.url)throw new F(`M2M client requires a URL`);if(!e.clientId)throw new F(`M2M client requires a clientId`);if(!e.clientSecret)throw new F(`M2M client requires a clientSecret`);let t=e.url.replace(/\/$/,``);this.config={url:t,clientId:e.clientId,clientSecret:e.clientSecret,scopes:e.scopes,audience:e.audience,autoRefresh:e.autoRefresh??!1,refreshThreshold:e.refreshThreshold??I.REFRESH_THRESHOLD,timeout:e.timeout??I.TIMEOUT,retries:e.retries??I.RETRIES,retryDelay:e.retryDelay??I.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new jt,this.retryStrategy=e.retryStrategy??Mt,this.tokenEndpoint=`${t}${I.TOKEN_ENDPOINT}`}getCacheKey(e,t){let n=e?.sort().join(`,`)||``,r=t?.sort().join(`,`)||``;return`m2m:${this.config.clientId}:${n}:${r}`}async getToken(e){let t=e?.scopes??this.config.scopes,n=e?.audience??this.config.audience,r=this.getCacheKey(t,n);if(!e?.forceRefresh){let e=await this.cache.get(r);if(e&&!this.isTokenExpired(e))return e}return this.requestToken(t,n,r)}async getValidToken(){let e=this.config.scopes,t=this.config.audience,n=this.getCacheKey(e,t),r=await this.cache.get(n);if(r){if(this.config.autoRefresh&&this.isTokenExpired(r,this.config.refreshThreshold))return this.requestToken(e,t,n);if(!this.isTokenExpired(r))return r}return this.requestToken(e,t,n)}async requestToken(e,t,n){let r={grant_type:`client_credentials`,client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(r.scope=e.join(` `)),t&&t.length>0&&(r.audience=t.join(` `)),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});let i=await this.executeWithRetry(()=>this.doTokenRequest(r));return i.issued_at=Math.floor(Date.now()/1e3),n&&await this.cache.set(n,i,i.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(i),i}async doTokenRequest(e){let t=new URLSearchParams;t.append(`grant_type`,e.grant_type),t.append(`client_id`,e.client_id),t.append(`client_secret`,e.client_secret),e.scope&&t.append(`scope`,e.scope),e.audience&&t.append(`audience`,e.audience);let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let e=await fetch(this.tokenEndpoint,{method:`POST`,headers:{"Content-Type":I.CONTENT_TYPE,Accept:`application/json`},body:t.toString(),signal:n.signal});clearTimeout(r);let i={};e.headers.forEach((e,t)=>{i[t.toLowerCase()]=e});let a=await e.json();if(!e.ok){let t=N.fromOAuthError({error:a.error||`server_error`,error_description:a.error_description||a.message,error_uri:a.error_uri},e.status,i);throw this.config.onError&&this.config.onError({error:t.code,error_description:t.message}),t}return a}catch(e){throw clearTimeout(r),e instanceof Error&&e.name===`AbortError`?new kt(`Request timed out after ${this.config.timeout}ms`):e instanceof TypeError&&e.message.includes(`fetch`)?new kt(`Network error: ${e.message}`,e):e instanceof N?e:N.fromError(e instanceof Error?e:Error(String(e)))}}async executeWithRetry(e){let t;for(let n=1;n<=this.config.retries;n++)try{return await e()}catch(e){if(!(e instanceof N))throw e;if(t=e,n<this.config.retries&&this.retryStrategy.shouldRetry({code:e.code,status:e.status},n)){let e=this.retryStrategy.getDelay(n);await this.sleep(e);continue}throw e}throw t??new N({code:`server_error`,message:`Request failed after retries`})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){let e=this.cache;if(`cache`in e){let t=this.getCacheKey(this.config.scopes,this.config.audience);return e.cache.get(t)?.token??null}return null}isTokenExpired(e,t=0){if(!e)return!0;let n=Math.floor(Date.now()/1e3);return n>=(e.issued_at??n-e.expires_in)+e.expires_in-t}parseToken(e){try{let t=e.split(`.`);if(t.length!==3)throw new P(`Invalid JWT format: expected 3 parts`);let n=t[1];if(!n)throw new P(`Invalid JWT format: missing payload`);let r=atob(n.replace(/-/g,`+`).replace(/_/g,`/`)),i=JSON.parse(r);return i.scopes&&typeof i.scopes==`string`?i.scopes=i.scopes.split(` `):i.scopes||(i.scopes=[]),i}catch(e){throw e instanceof P?e:new P(`Failed to parse token: ${e instanceof Error?e.message:`Unknown error`}`)}}clearCache(){let e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){let e=this.getCachedToken();if(!e)return;let t=`${this.config.url}/oauth2/revoke`,n=new URLSearchParams;n.append(`token`,e.access_token),n.append(`client_id`,this.config.clientId),n.append(`client_secret`,this.config.clientSecret);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":I.CONTENT_TYPE},body:n.toString()});if(!e.ok&&e.status!==200){let t=await e.json().catch(()=>({}));throw N.fromOAuthError({error:t.error||`server_error`,error_description:t.error_description||`Token revocation failed`},e.status)}this.clearCache()}catch(e){throw e instanceof N?e:N.fromError(e instanceof Error?e:Error(String(e)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}},L=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,Pt=32,Ft=e=>{let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=e[n+1],a=e[n+2];t+=L.charAt(r>>2),t+=L.charAt((r&3)<<4|(i??0)>>4),i!==void 0&&(t+=L.charAt((i&15)<<2|(a??0)>>6)),a!==void 0&&(t+=L.charAt(a&63))}return t},It=()=>{let e=globalThis.crypto;if(!e?.subtle)throw Error(`PKCE needs the Web Crypto API, which is available only in a secure context (https or localhost)`);return e},Lt=async e=>{let t=await It().subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Ft(new Uint8Array(t))},Rt=async()=>{let e=Ft(It().getRandomValues(new Uint8Array(Pt)));return{verifier:e,challenge:await Lt(e)}},R=function(e){return e.SignIn=`signin`,e.SignInStart=`signin:start`,e.Register=`register`,e.RegisterStart=`register:start`,e.SignOut=`signout`,e.SessionRestored=`session:restored`,e.SessionExpired=`session:expired`,e.Error=`error`,e.Refresh=`refresh`,e.RefreshStart=`refresh:start`,e.TokenCacheExpired=`token-cache-expired`,e.TwoFactorRequired=`2fa:required`,e.TwoFactorSetupStarted=`2fa:setup_started`,e.TwoFactorEnabled=`2fa:enabled`,e.TwoFactorDisabled=`2fa:disabled`,e.TwoFactorVerified=`2fa:verified`,e.TwoFactorRecoveryUsed=`2fa:recovery_used`,e.TwoFactorRecoveryCodesLow=`2fa:recovery_low`,e.TwoFactorRecoveryCodesExhausted=`2fa:recovery_exhausted`,e.TwoFactorSetupMagicLinkValidated=`2fa:magic_link_validated`,e.TwoFactorSetupMagicLinkFailed=`2fa:magic_link_failed`,e.TwoFactorChallengeReceived=`two_factor_challenge_received`,e.TwoFactorMethodSwitched=`two_factor_method_switched`,e.TwoFactorDeviceTrusted=`two_factor_device_trusted`,e}({}),zt=class{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){let n=new Set(t);this.subscribers.set(e,n)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}let n=this.subscribers.get(e);n&&(t.forEach(e=>n.delete(e)),n.size===0&&this.subscribers.delete(e))}notify(e,t){this.subscribers.forEach((n,r)=>{(!n||n.has(e))&&r.onAuthChange?.(e,t)})}},z={twoFactorCodeInvalid:`error.api.request.2fa_code.invalid`,challengeInvalid:`error.upgrade.challenge_invalid`,challengeSessionMismatch:`error.upgrade.challenge_session_mismatch`,challengeTooManyAttempts:`error.upgrade.challenge_too_many_attempts`,unsupportedFactor:`error.upgrade.unsupported_factor`,noSession:`error.upgrade.no_session`,unavailable:`error.upgrade.unavailable`,methodNotRegistered:`error.upgrade.method_not_registered`,prepareNotRequired:`error.upgrade.prepare_not_required`,methodNotSupported:`error.2fa.method_not_supported`,twoFactorNotEnabled:`error.2fa.not_enabled`,notImplemented:`error.not.implemented`,tokenInvalid:`error.api.request.token.invalid`},Bt=Object.freeze([z.twoFactorCodeInvalid,z.twoFactorNotEnabled,z.challengeInvalid,z.challengeSessionMismatch,z.challengeTooManyAttempts]),Vt=Object.freeze([z.tokenInvalid]),Ht=Object.freeze([`wrong_code`,`challenge_spent`,`not_registered`,`prepare_not_required`]),Ut=e=>Ht.includes(e),Wt={wrong_code:`That code was not accepted. Try again.`,challenge_spent:`That verification challenge is no longer valid. Start again.`,exhausted:`Too many attempts. Try again later.`,attempts_exhausted:`Too many incorrect attempts. Verification was not completed.`,not_registered:`That verification method is not set up for this account.`,prepare_not_required:`This verification method needs no preparation round.`,fatal:`This verification method cannot be used right now.`,unavailable:`Step-up verification is not available on this deployment.`,protocol:`The server returned an unexpected upgrade response.`,network:`The verification request did not reach the server.`,session_changed:`The session ended during verification.`},B=class extends Error{constructor(e){super(e.message||Wt[e.kind]),this.name=`UpgradeTransportError`,this.code=`upgrade_transport`,this.kind=e.kind,this.status=e.status,this.errorId=e.errorId,this.retryable=Ut(e.kind),e.cause!==void 0&&(this.cause=e.cause)}},Gt=Object.freeze([`upgrade_transport`,`upgrade_insufficient`,`upgrade_unavailable`,`upgrade_session_changed`,`upgrade_cancelled`,`upgrade_unsatisfiable`]),Kt=e=>typeof e==`object`&&!!e&&typeof e.code==`string`&&Gt.includes(e.code),qt=e=>e instanceof B||typeof e==`object`&&!!e&&e.code===`upgrade_transport`,Jt=e=>{if(typeof e!=`object`||!e)return{hasResponse:!1,message:typeof e==`string`?e:void 0};let t=e,n=t.response,r=n?.data,i=typeof r?.error?.id==`string`?r.error.id:void 0;return{status:typeof t.status==`number`?t.status:typeof n?.status==`number`?n.status:void 0,errorId:typeof t.id==`string`?t.id:i,message:typeof t.message==`string`?t.message:void 0,hasResponse:n!==void 0||typeof t.status==`number`}},Yt=(e,t)=>{switch(e){case z.twoFactorCodeInvalid:return`wrong_code`;case z.challengeInvalid:case z.challengeSessionMismatch:return`challenge_spent`;case z.challengeTooManyAttempts:return`exhausted`;case z.methodNotRegistered:return`not_registered`;case z.twoFactorNotEnabled:return t===`refresh`?`session_changed`:`not_registered`;case z.prepareNotRequired:return`prepare_not_required`;case z.unavailable:case z.notImplemented:return`unavailable`;case z.unsupportedFactor:case z.noSession:case z.methodNotSupported:return`fatal`;case z.tokenInvalid:return t===`refresh`?`session_changed`:`fatal`;default:return}},Xt=(e,t)=>e===void 0?`network`:e===501?`unavailable`:e===400?`fatal`:e===401||e===403?t===`start`?`challenge_spent`:`session_changed`:e>=500?`network`:`fatal`,Zt=(e,t)=>{if(e instanceof B)return e;let n=Jt(e);return n.hasResponse?new B({kind:Yt(n.errorId,t)??Xt(n.status,t),message:n.message,status:n.status,errorId:n.errorId,cause:e}):new B({kind:`network`,message:n.message,cause:e})},Qt=e=>e.errorId!==void 0&&Bt.includes(e.errorId),$t=e=>e.errorId!==void 0&&Vt.includes(e.errorId),V=class extends Error{constructor(e,t,n){super(n??`The session was elevated, but this action requires a higher assurance level`),this.name=`UpgradeInsufficientError`,this.code=`upgrade_insufficient`,this.obtained=e,this.required=t}},H=class extends Error{constructor(e=`Step-up verification is not available on this deployment`){super(e),this.name=`UpgradeUnavailableError`,this.code=`upgrade_unavailable`}},U=class extends Error{constructor(e=`The session changed during verification`){super(e),this.name=`UpgradeSessionChangedError`,this.code=`upgrade_session_changed`}},en=e=>{if(e&&typeof e.sub==`string`&&e.sub!==``)return typeof e.sid==`string`&&e.sid!==``?{sub:e.sub,sid:e.sid}:{sub:e.sub}},tn=(e,t)=>!t||t.sub!==e.sub?!1:e.sid!==void 0&&t.sid!==void 0?e.sid===t.sid:!0;function W(e){if(!e||typeof e!=`string`)return!1;let t=e.split(`.`);if(t.length!==3)return!1;let n=/^[A-Za-z0-9_-]+$/;return t.every(e=>n.test(e)&&e.length>0)}function nn(e){return e.replace(/<[^>]*>/g,``).substring(0,200)}function G(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length!==0&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function K(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return/^\+[1-9]\d{1,14}$/.test(t)}function rn(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return t.length<3||t.length>30?!1:/^[a-zA-Z0-9_-]+$/.test(t)}function q(e,t=6){return!e||typeof e!=`string`?!1:(t===8?/^\d{8}$/:/^\d{6}$/).test(e)}function an(e){if(!e||typeof e!=`string`)return null;let t=e.toUpperCase().replace(/\s+/g,``);return/^[A-Z0-9-]{4,16}$/.test(t)?t:null}var on=class{error(e,...t){console.error(e,...t)}warn(e,...t){console.warn(e,...t)}info(e,...t){console.info(e,...t)}debug(e,...t){console.debug(e,...t)}};function sn(){return new on}var cn=`passflow_2fa_pkce`,ln=3e5,un=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d=b,f){this.authApi=e,this.deviceService=t,this.storageManager=n,this.subscribeStore=r,this.tokenCacheService=i,this.scopes=a,this.createTenantForNewUser=o,this.url=s,this.sessionCallbacks=c,this.appId=l,this.platform=d,this.readPkceEnabled=f,this.tokenExchangeConfig=u,this.tokenDeliveryManager=new Se(n),u?.enabled&&this.tokenDeliveryManager.setMode(y.BFF),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{let e=await fetch(this.tokenExchangeConfig.statusUrl,{method:`GET`,credentials:`include`});return e.ok&&(await e.json()).authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{let e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(R.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){if(e.code&&!e.access_token)throw Error(`A PKCE authorization code was not exchanged, so there are no tokens to apply`);this.tokenExchangeConfig?.enabled||`token_delivery`in e&&e.token_delivery&&this.tokenDeliveryManager.setMode(e.token_delivery),this.tokenDeliveryManager.setSessionValid(),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.callbackUrl&&await this.forwardTokensToBFF(e),e.scopes=t,this.storageManager.saveTokens(e,this.tokenDeliveryManager.getMode()),this.tokenCacheService.setTokensCache(e),e.csrf_token&&this.storageManager.setCsrfToken(e.csrf_token)}handlePendingSecondFactor(e,t,n,r){return e.requires_2fa!==!0&&!e.tfa_token?!1:(n?this.rememberPkceSignIn(n.verifier,r):this.forgetPkceSignIn(),this.subscribeStore.notify(R.TwoFactorRequired,{email:t||``,challengeId:e.challenge_id||``,tfaToken:e.tfa_token||``}),!0)}rememberPkceSignIn(e,t){if(this.pendingPkce={verifier:e,scopes:t,expiresAt:Date.now()+ln},typeof sessionStorage<`u`)try{sessionStorage.setItem(cn,JSON.stringify(this.pendingPkce))}catch{}}readPendingPkce(){if(!this.pendingPkce&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(cn);this.pendingPkce=e?JSON.parse(e):void 0}catch{this.pendingPkce=void 0}return this.pendingPkce&&Date.now()>=this.pendingPkce.expiresAt&&this.forgetPkceSignIn(),this.pendingPkce}hasPendingPkceSignIn(){return this.readPendingPkce()!==void 0}forgetPkceSignIn(){if(this.pendingPkce=void 0,typeof sessionStorage<`u`)try{sessionStorage.removeItem(cn)}catch{}}async startPkce(){let e=!1;try{e=await this.readPkceEnabled?.()??!1}catch(e){sn().warn(`Passflow: could not read the app settings, so this sign-in sends no PKCE challenge`,e);return}return e?Rt():void 0}async exchangeCode(e,t){return!e.code||!t?e:await this.authApi.pkceExchange(e.code,t.verifier)}async completePkceSignIn(e){let t=this.readPendingPkce();if(!t)throw Error(`The sign-in answered with a PKCE code, but its verifier is gone`);let n=await this.authApi.pkceExchange(e,t.verifier);return await this.processAuthResponse(n,t.scopes??this.scopes),n}async applyTokens(e){let t=e;(t.access_token||t.id_token||t.token_delivery)&&await this.processAuthResponse(t,t.scopes??this.readPendingPkce()?.scopes??this.scopes)}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;let t=await fetch(this.tokenExchangeConfig.callbackUrl,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`},body:JSON.stringify({access_token:e.access_token,refresh_token:e.refresh_token,id_token:e.id_token,expires_in:e.expires_in})});if(!t.ok)throw Error(`BFF token storage failed: ${t.status}`)}async signIn(e){if(`email`in e&&e.email&&!G(e.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(`username`in e&&e.username&&!rn(e.username)){let e=Error(`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`),t={message:`Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(`phone`in e&&e.phone&&!K(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.SignInStart,{email:e.email});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),i=await this.authApi.signIn(r?{...e,code_challenge:r.challenge}:e,t,n);if(this.handlePendingSecondFactor(i,e.email,r,e.scopes))return i;let a=await this.exchangeCode(i,r);return this.handlePendingSecondFactor(a,e.email)||(await this.processAuthResponse(a,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:a,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),a}catch(e){let t={message:e instanceof Error?e.message:`Sign in failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async signUp(e){if(e.user.email&&!G(e.user.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(e.user.phone_number&&!K(e.user.phone_number)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let t=await this.startPkce(),n=await this.authApi.signUp(t?{...e,code_challenge:t.challenge}:e);if(this.handlePendingSecondFactor(n,e.user.email,t,e.scopes))return n;let r=await this.exchangeCode(n,t);return this.handlePendingSecondFactor(r,e.user.email)||(await this.processAuthResponse(r,e.scopes),this.subscribeStore.notify(R.Register,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),r}catch(e){let t={message:e instanceof Error?e.message:`Sign up failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passwordlessSignIn(e){if(e.email&&!G(e.email)){let e=Error(`Invalid email format`),t={message:`Invalid email format`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}if(e.phone&&!K(e.phone)){let e=Error(`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`),t={message:`Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)`,originalError:e,code:`VALIDATION_ERROR`};throw this.subscribeStore.notify(R.Error,t),e}this.subscribeStore.notify(R.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());try{return await this.authApi.passwordlessSignIn(e,t,n)}catch(e){let t={message:e instanceof Error?e.message:`Failed to send passwordless sign-in link`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passwordlessSignInComplete(e){this.subscribeStore.notify(R.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();try{let t=await this.authApi.passwordlessSignInComplete(e);return this.handlePendingSecondFactor(t)||(await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),t}catch(e){let t={message:e instanceof Error?e.message:`Passwordless sign in failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async logOut(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl)try{(await fetch(this.tokenExchangeConfig.logoutUrl,{method:`POST`,credentials:`include`})).ok}catch{}else{let e=this.storageManager.getToken(v.refresh_token),t=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(t,e,!this.appId)).status!==`ok`)throw Error(`Logout failed`)}catch{}}this.forgetPkceSignIn(),this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.subscribeStore.notify(R.SignOut,{})}readSessionPin(){try{let e=this.storageManager.getToken(v.access_token);return e?en(_(e)):void 0}catch{return}}assertSessionPin(e){if(e&&!tn(e,this.readSessionPin()))throw console.warn(`[passflow] the session or user changed while a step-up upgrade was in flight; the elevated tokens were discarded and the live session was left untouched.`),new U(`The session changed during verification, so the elevated tokens were discarded`)}async refreshToken(e,t){if(this.subscribeStore.notify(R.RefreshStart,{}),e&&this.tokenDeliveryManager.isBFFMode())throw new B({kind:`unavailable`,message:`Step-up verification cannot be committed through a BFF refresh endpoint`});if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl)try{let e=await fetch(this.tokenExchangeConfig.refreshUrl,{method:`POST`,credentials:`include`});if(!e.ok)throw this.tokenDeliveryManager.setSessionInvalid(),Error(`BFF token refresh failed`);let t=await e.json();return this.tokenDeliveryManager.setSessionValid(),t.id_token&&this.storageManager.setIdToken(t.id_token),this.subscribeStore.notify(R.Refresh,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,t}catch(e){this.tokenDeliveryManager.setSessionInvalid();let t={message:e instanceof Error?e.message:`Token refresh failed`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}if(this.tokenDeliveryManager.isCookieMode())try{let n=e?await this.authApi.refreshToken(``,this.scopes,void 0,e):await this.authApi.refreshToken(``,this.scopes);return this.assertSessionPin(t),this.tokenDeliveryManager.setSessionValid(),await this.processAuthResponse(n,this.scopes),this.subscribeStore.notify(R.Refresh,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,n}catch(t){e||this.tokenDeliveryManager.setSessionInvalid();let n={message:t instanceof Error?t.message:`Token refresh failed`,originalError:t,code:t instanceof w?t.id:void 0};throw this.subscribeStore.notify(R.Error,n),t}let n=this.storageManager.getTokens();if(!n){let e=Error(`No tokens found`),t={message:`No tokens found`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}if(!n?.refresh_token){let e=Error(`No refresh token found`),t={message:`No refresh token found`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}let r=n?.scopes??this.scopes;try{let i=n?.refresh_token??``,a=n?.access_token,o=e?await this.authApi.refreshToken(i,r,a,e):await this.authApi.refreshToken(i,r,a);return this.assertSessionPin(t),o.scopes=r,this.storageManager.saveTokens(o),this.tokenCacheService.setTokensCache(o),this.subscribeStore.notify(R.Refresh,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,this.tokenCacheService.startTokenCheck(),o}catch(t){let n={message:t instanceof Error?t.message:`Token refresh failed`,originalError:t,code:t instanceof w?t.id:void 0,details:c.default.isAxiosError(t)&&t.response?{status:t.response.status,data:t.response.data}:void 0};this.subscribeStore.notify(R.Error,n);let r=c.default.isAxiosError(t)&&t.response?.status&&t.response.status>=400&&t.response.status<500;throw r&&!e&&(this.tokenCacheService.tokenExpiredFlag=!0,this.tokenCacheService.setTokensCache(void 0),this.storageManager.deleteTokens(),this.subscribeStore.notify(R.SessionExpired,{reason:`refresh_failed`})),t instanceof w?t:r&&!e?Error(`Getting unknown error message from server with code:${t.response?.status}`):t}}async sendPasswordResetEmail(e){try{return await this.authApi.sendPasswordResetEmail(e)}catch(e){let t={message:e instanceof Error?e.message:`Failed to send password reset email`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async resetPassword(e,t){this.subscribeStore.notify(R.SignInStart,{});let n=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`token`)??void 0,r=t??this.scopes;try{let t=await this.startPkce(),i=t?await this.authApi.resetPassword(e,r,n,t.challenge):await this.authApi.resetPassword(e,r,n);if(this.handlePendingSecondFactor(i,void 0,t,r))return i;let a=await this.exchangeCode(i,t);if(this.handlePendingSecondFactor(a))return a;let o=i.redirect_url?{...a,redirect_url:i.redirect_url}:a;return await this.processAuthResponse(o,r),this.subscribeStore.notify(R.SignIn,{tokens:o,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),o}catch(e){let t={message:e instanceof Error?e.message:`Password reset failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passkeyRegister(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(R.RegisterStart,{});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyRegisterStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId);a.user.id=this.platform.btoa(a.user.id);let o=await this.platform.passkeys.startRegistration(a);if(!o)throw Error(`Passkey registration was not completed`);let s=await this.authApi.passkeyRegisterComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(R.Register,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={message:e instanceof Error?e.message:`Passkey registration failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);this.subscribeStore.notify(R.SignInStart,{});let t=this.deviceService.getDeviceId(),n=T(this.platform.getDeviceType());e.scopes=e.scopes??this.scopes;try{let r=await this.startPkce(),{challenge_id:i,publicKey:a}=await this.authApi.passkeyAuthenticateStart(r?{...e,code_challenge:r.challenge}:e,t,n,!this.appId),o=await this.platform.passkeys.startAuthentication(a);if(!o)throw Error(`Passkey authentication was not completed`);let s=await this.authApi.passkeyAuthenticateComplete(o,t,i,!this.appId);if(this.handlePendingSecondFactor(s,void 0,r,e.scopes))return s;let c=await this.exchangeCode(s,r);return this.handlePendingSecondFactor(c)||`access_token`in c&&(await this.processAuthResponse(c,e.scopes),this.subscribeStore.notify(R.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),c}catch(e){let t={message:e instanceof Error?e.message:`Passkey authentication failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,t),e}}createFederatedAuthUrl(e){let t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw Error(`AppId is required for federated auth`);let n={scopes:(e.scopes??this.scopes).join(` `),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??``,appId:this.appId,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{}},r=new URL(t,this.url);return r.search=new URLSearchParams(n).toString(),r.toString()}async federatedAuthWithPopup(e){this.subscribeStore.notify(R.SignInStart,{provider:e.provider});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=this.createFederatedAuthUrl({...e,scopes:t,device:n});try{let e=await this.platform.openAuthUrl(r,{mode:`popup`,expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??``}),n=new URLSearchParams(e.callbackHash.replace(/^#/,``));if(this.handlePendingSecondFactor({tfa_token:n.get(`tfa_token`)??void 0}))return;let i=new URLSearchParams(e.callbackSearch),a=i.get(`access_token`)||``,o=i.get(`refresh_token`)||``,s=i.get(`id_token`)||``,c={access_token:a,refresh_token:o||void 0,id_token:s||void 0,scopes:t};await this.processAuthResponse(c,t),this.subscribeStore.notify(R.SignIn,{tokens:c,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??``)}catch(e){let t={message:e instanceof Error?e.message:`Authentication failed`,code:e instanceof Te?`POPUP_CLOSED`:`AUTH_FAILED`,originalError:e};this.subscribeStore.notify(R.Error,t)}}federatedAuthWithRedirect(e){this.subscribeStore.notify(R.SignInStart,{provider:e.provider});let t=e.scopes??this.scopes,n=this.deviceService.getDeviceId(),r=this.createFederatedAuthUrl({...e,scopes:t,device:n});this.platform.navigateTo(r)}authRedirectUrl(e={}){try{let{url:t,redirectUrl:n,scopes:r,appId:i}=e??{},a=new URL(t??this.url);a.pathname=(a.pathname.endsWith(`/`)?a.pathname:a.pathname+`/`)+`web`;let o=r??this.scopes,s={appId:i??this.appId??``,redirectto:n??this.platform.getCurrentUrl()?.href??``,scopes:o.join(`,`)};return a.search=new URLSearchParams(s).toString(),a.toString()}catch(e){let t={message:e instanceof Error?e.message:`Failed to create auth redirect URL`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}}authRedirect(e={}){try{this.platform.navigateTo(this.authRedirectUrl(e))}catch(e){let t={message:e instanceof Error?e.message:`Failed to redirect to auth page`,originalError:e};throw this.subscribeStore.notify(R.Error,t),e}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=!!e?.id_token||!!this.storageManager.getIdToken(),n=this.tokenDeliveryManager.isSessionValid(),r=this.tokenDeliveryManager.isSessionUnknown();return t&&(n||r)}return!e||!e.access_token?!1:!g(e.access_token)||e.refresh_token!==void 0&&!g(e.refresh_token)}catch(e){let t={message:e instanceof Error?e.message:`Failed to check authentication status`,originalError:e};return this.subscribeStore.notify(R.Error,t),!1}}async submitSessionCheck(e=!1){let t,n;try{t=await this.getTokens(e),n=this.tokenCacheService.getParsedTokens()}catch(e){let n={message:e instanceof Error||e instanceof w?e.message:`Session check failed`,originalError:e};this.subscribeStore.notify(R.Error,n),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:n}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){let t=this.storageManager.getTokens();return t?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshToken():t:void 0}let t=this.storageManager.getTokens();return!t||!t.access_token?void 0:g(_(t.access_token))?e?await this.refreshToken():void 0:t}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t);return}}},dn=class{constructor(e){this.invitationApi=e}requestInviteLink(e){return this.invitationApi.requestInviteLink(e)}getInvitations(e){return this.invitationApi.getInvitations(e)}deleteInvitation(e){return this.invitationApi.deleteInvitation(e)}resendInvitation(e){return this.invitationApi.resendInvitation(e)}getInvitationLink(e){return this.invitationApi.getInvitationLink(e)}},fn=class{constructor(e){this.data=this.normalize(e)}normalize(e){let t=new Map,n=new Map,r=new Map,i=[];return e.groups?.forEach(e=>{n.set(e.id,{id:e.id,name:e.name,default:e.default??!1,updated_at:e.updated_at,created_at:e.created_at})}),e.roles?.forEach(e=>{r.set(e.id,{id:e.id,tenant_id:e.tenant_id,name:e.name})}),e.users_in_groups?.forEach(e=>{let r=e.user;r&&!t.has(r.id)&&t.set(r.id,{id:r.id,name:r.name??null,email:r.email??null,phone:r.phone??null}),r&&e.group_id&&n.has(e.group_id)&&i.push({userId:r.id,groupId:e.group_id,roleIds:e.roles?.map(e=>e.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(n.values()),roles:Array.from(r.values()),memberships:i,usersById:t,groupsById:n,rolesById:r}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(e=>this.data.usersById.get(e.userId)).filter(e=>e!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(e=>this.data.groupsById.get(e.groupId)).filter(e=>e!==void 0)}getUserRolesInGroup(e,t){let n=this.data.memberships.find(n=>n.userId===e&&n.groupId===t);return n?n.roleIds.map(e=>this.data.rolesById.get(e)).filter(e=>e!==void 0):[]}getData(){return this.data}},pn=class{constructor(e,t,n){this.tenantApi=e,this.scopes=t,this.logger=n||sn()}handlePassflowError(e,t){if(c.default.isAxiosError(e)&&e.response?.data){let n=e.response.data;if(typeof n==`object`&&n&&`error`in n&&typeof n.error==`object`&&n.error!==null){let e=n.error;throw this.logger.error(`${t}: ${e.id} - ${e.message} (Status: ${e.status})`),Error(`Passflow API Error: ${e.id} - ${e.message} (Status: ${e.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:Error(String(e))}async joinInvitation(e,t){try{let n=t??this.scopes;return await this.tenantApi.joinInvitation(e,n)}catch(e){this.handlePassflowError(e,`Join invitation failed`)}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(e){this.handlePassflowError(e,`Tenant creation failed`)}}async getTenantDetails(e){try{return await this.tenantApi.getTenantDetails(e)}catch(t){this.handlePassflowError(t,`Get tenant details failed for tenant ID ${e}`)}}async getTenantUserMembership(e){try{return new fn(await this.tenantApi.getTenantDetails(e))}catch(t){this.handlePassflowError(t,`Get tenant user membership failed for tenant ID ${e}`)}}async updateTenant(e,t){try{return await this.tenantApi.updateTenant(e,t)}catch(t){this.handlePassflowError(t,`Update tenant failed for tenant ID ${e}`)}}async deleteTenant(e){try{return await this.tenantApi.deleteTenant(e)}catch(t){this.handlePassflowError(t,`Delete tenant failed for tenant ID ${e}`)}}async getUserTenantMembership(){try{return await this.tenantApi.getUserTenantMembership()}catch(e){this.handlePassflowError(e,`Get user tenant memberships failed`)}}async createGroup(e,t){try{return await this.tenantApi.createGroup(e,t)}catch(t){this.handlePassflowError(t,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(n){this.handlePassflowError(n,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,n){try{return await this.tenantApi.updateGroup(e,t,n)}catch(n){this.handlePassflowError(n,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(n){this.handlePassflowError(n,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,n,r){try{return await this.tenantApi.addUserToGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async removeUserRolesFromGroup(e,t,n,r){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,n,r)}catch(r){this.handlePassflowError(r,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async changeUserRoles(e,t,n,r){try{return await this.tenantApi.changeUserRoles(e,t,n,r)}catch(r){this.handlePassflowError(r,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async deleteUserFromGroup(e,t,n){try{return await this.tenantApi.deleteUserFromGroup(e,t,n)}catch(r){this.handlePassflowError(r,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${n}`)}}async getRolesForTenant(e){try{return await this.tenantApi.getRolesForTenant(e)}catch(t){this.handlePassflowError(t,`Get roles for tenant failed for tenant ID ${e}`)}}async createRoleForTenant(e,t){try{return await this.tenantApi.createRoleForTenant(e,t)}catch(t){this.handlePassflowError(t,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,n){try{return await this.tenantApi.updateRole(e,t,n)}catch(n){this.handlePassflowError(n,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(n){this.handlePassflowError(n,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(n){this.handlePassflowError(n,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,n,r){try{return await this.tenantApi.getGroupInvitations(e,t,n,r)}catch(n){this.handlePassflowError(n,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,n){try{return await this.tenantApi.getTenantInvitations(e,t,n)}catch(t){this.handlePassflowError(t,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,n){try{return await this.tenantApi.invalidateInviteById(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${n}`)}}async invalidateInviteByEmail(e,t,n){try{return await this.tenantApi.invalidateInviteByEmail(e,t,n)}catch(r){this.handlePassflowError(r,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${n}`)}}},mn=class{constructor(e,t,n,r=b){this.storageManager=e,this.authApi=t,this.subscribeStore=n,this.platform=r,this.checkInterval=null,this.CHECK_INTERVAL=6e4,this.unsubscribeForeground=null,this.unsubscribeUnload=null,this.isRefreshing=!1,this.tokenExpiredFlag=!1,this.storageManager=e,this.authApi=t,this.setupLifecycleListeners()}initialize(){try{let e=this.storageManager.getTokens();if(!e)return;if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}g(_(e.access_token))?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0})):(this.setTokensCache(e),this.startTokenCheck())}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(R.RefreshStart,{});let t=await this.authApi.refreshToken(e?.refresh_token??``,e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(R.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!1}),this.tokenExpiredFlag=!1,this.startTokenCheck()}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(R.SessionExpired,{reason:`refresh_failed`})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),this.tokenExpiredFlag||(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(R.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,this.parsedTokensCache=e?{access_token:e.access_token?_(e.access_token):void 0,id_token:e.id_token?_(e.id_token):void 0,refresh_token:e.refresh_token?_(e.refresh_token):void 0,scopes:e.scopes}:void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{return!this.tokensCache||!this.tokensCache.access_token||g(_(this.tokensCache.access_token))&&!this.tokenExpiredFlag&&await this.refreshTokensCache(this.tokensCache),this.tokensCache}catch(e){let t={message:e instanceof Error?e.message:`Failed to get tokens`,originalError:e};this.subscribeStore.notify(R.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){return this.tokensCache?this.tokensCache.access_token?g(_(this.tokensCache.access_token)):!1:!0}},hn=class{constructor(e,t,n){this.twoFactorApi=e,this.subscribeStore=t,this.signInCompleter=n,this.PARTIAL_AUTH_TIMEOUT_MS=3e5,this.SESSION_STORAGE_KEY=`passflow_2fa_challenge`,this.totpDigits=6,this.subscribeStore.subscribe({onAuthChange:(e,t)=>{if(e===R.TwoFactorRequired){let e=t;this.setPartialAuthState(e.email,e.challengeId,e.tfaToken)}(e===R.SignIn||e===R.Register)&&this.clearPartialAuthState()}},[R.TwoFactorRequired,R.SignIn,R.Register])}emitErrorAndThrow(e,t){let n=e,r={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:n?.id||void 0};throw this.subscribeStore.notify(R.Error,r),e}async getStatus(){try{let e=await this.twoFactorApi.getStatus();return e.totp_digits&&(this.totpDigits=e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,`Get 2FA status`)}}async beginSetup(){try{let e=await this.twoFactorApi.beginSetup();return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(R.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,`Begin 2FA setup`)}}async confirmSetup(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.confirmSetup({code:e});return this.subscribeStore.notify(R.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(e){this.emitErrorAndThrow(e,`Confirm 2FA setup`)}}async verify(e,t){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);try{let n=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}),r=await this.finishSignIn(n);return this.subscribeStore.notify(R.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`Verify 2FA code`)}}async useRecoveryCode(e,t){try{let n=an(e);if(!n)throw Error(`Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw Error(`2FA verification expired or not required. User must sign in first.`);if(!this.partialAuthState?.tfaToken)throw Error(`No TFA token found. User must sign in first.`);let r=await this.finishSignIn(await this.twoFactorApi.useRecoveryCode({recovery_code:n,tfa_token:this.partialAuthState.tfaToken,...t?.trustDevice?{trust_device:!0}:{}}));return r.remaining_recovery_codes===0?this.subscribeStore.notify(R.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(R.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(R.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(R.TwoFactorVerified,{tokens:r}),r}catch(e){this.emitErrorAndThrow(e,`Use recovery code`)}}async disable(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(R.TwoFactorDisabled,{}),t}catch(e){this.emitErrorAndThrow(e,`Disable 2FA`)}}async regenerateRecoveryCodes(e){if(!q(e,this.totpDigits))throw Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{let t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),n=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=n,t}catch(e){this.emitErrorAndThrow(e,`Regenerate recovery codes`)}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,n){if(this.partialAuthState={email:e,challengeId:t,tfaToken:n,timestamp:Date.now(),expiresAt:Date.now()+this.PARTIAL_AUTH_TIMEOUT_MS},typeof sessionStorage<`u`)try{sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(this.partialAuthState))}catch{}}clearPartialAuthState(){if(this.partialAuthState=void 0,this.signInCompleter?.forgetPkceSignIn(),typeof sessionStorage<`u`)try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}async finishSignIn(e){let{code:t,...n}=e;if(t&&!this.signInCompleter?.hasPendingPkceSignIn()){this.clearPartialAuthState();let e=Error(`The sign-in answered with a PKCE code, but its verifier is gone`);throw e.id=`PKCE_VERIFIER_MISSING`,e}let r=e;if(t&&this.signInCompleter){let e=await this.signInCompleter.completePkceSignIn(t);r={...n,...e}}else await this.signInCompleter?.applyTokens(r);return this.clearPartialAuthState(),r}pendingTfaToken(){return this.isVerificationRequired()&&this.partialAuthState?.tfaToken||void 0}recoverPartialAuthState(){if(!this.partialAuthState&&typeof sessionStorage<`u`)try{let e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;let t=JSON.parse(e);Date.now()<t.expiresAt?this.partialAuthState=t:sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}}async validateTwoFactorSetupMagicLink(e){let t=await this.twoFactorApi.validateTwoFactorSetupMagicLink(e);return t.success&&t.sessionToken&&t.userId?(this.magicLinkSession={sessionToken:t.sessionToken,userId:t.userId,appId:t.appId,scope:`2fa_setup`,timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(R.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(R.TwoFactorSetupMagicLinkFailed,{error:t.error}),t}getMagicLinkSession(){return this.magicLinkSession?Date.now()>this.magicLinkSession.expiresAt?(this.clearMagicLinkSession(),null):this.magicLinkSession:null}clearMagicLinkSession(){this.magicLinkSession=void 0}hasMagicLinkSession(){return this.getMagicLinkSession()!==null}getMagicLinkSessionToken(){return this.getMagicLinkSession()?.sessionToken||null}getTotpDigits(){return this.totpDigits}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,`Get available 2FA methods`)}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,`Get registered 2FA methods`)}}async startMethodSetup(e,t){try{let n=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(R.TwoFactorSetupStarted,{secret:``,method:e}),n}catch(e){this.emitErrorAndThrow(e,`Start 2FA method setup`)}}async completeMethodSetup(e,t){try{let n=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(R.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),n}catch(e){this.emitErrorAndThrow(e,`Complete 2FA method setup`)}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(e){this.emitErrorAndThrow(e,`Remove 2FA method`)}}async requestChallenge(e){try{let t=await this.twoFactorApi.requestChallenge(e,this.pendingTfaToken());return this.subscribeStore.notify(R.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(e){this.emitErrorAndThrow(e,`Request 2FA challenge`)}}async verifyV2(e){try{let t=await this.twoFactorApi.verifyV2(e,this.pendingTfaToken());if(!t.success)return t;let n=await this.finishSignIn(t);return this.subscribeStore.notify(R.TwoFactorVerified,{tokens:{access_token:n.access_token,refresh_token:n.refresh_token}}),n.device_trusted&&this.subscribeStore.notify(R.TwoFactorDeviceTrusted,{}),n}catch(e){this.emitErrorAndThrow(e,`Verify 2FA challenge`)}}async switchToAlternative(e){try{let t=await this.twoFactorApi.switchToAlternative(e,this.pendingTfaToken());return this.subscribeStore.notify(R.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(e){this.emitErrorAndThrow(e,`Switch to alternative 2FA method`)}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(e){this.emitErrorAndThrow(e,`Revoke trusted device`)}}},gn=class{constructor(e,t,n=b){this.userAPI=e,this.deviceService=t,this.platform=n}getUserPasskeys(){return this.userAPI.getUserPasskeys()}renameUserPasskey(e,t){return this.userAPI.renameUserPasskey(e,t)}deleteUserPasskey(e){return this.userAPI.deleteUserPasskey(e)}async addUserPasskey({relyingPartyId:e,passkeyUsername:t,passkeyDisplayName:n}={}){if(!this.platform.passkeys)throw Error(`Passkeys are not supported on this platform`);let r=this.deviceService.getDeviceId(),i=T(this.platform.getDeviceType()),{challenge_id:a,publicKey:o}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??``,deviceId:r,os:i,passkeyDisplayName:n,passkeyUsername:t});o.user.id=this.platform.btoa(o.user.id);let s=await this.platform.passkeys.startRegistration(o);if(!s)throw Error(`Passkey registration was not completed`);return await this.userAPI.addUserPasskeyComplete(s,r,a)}},J=class extends Error{constructor(e,t,n=!1){super(t),this.name=`UpgradeFactorError`,this.factor=e,this.cancelled=n}},_n=(e,t)=>{let n=t?.trim();if(!n)throw new J(e,`A verification code is required`);return n},vn={type:`totp`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_n(`totp`,e)})},yn={type:`recovery_codes`,requiresPrepare:!1,input:`code`,assert:async({code:e})=>({code:_n(`recovery_codes`,e)})},bn={type:`passkey`,requiresPrepare:!0,input:`none`,assert:async({prepared:e,platform:t})=>{if(!e?.webauthn)throw new J(`passkey`,`The upgrade challenge carried no WebAuthn options`);let n=t.passkeys;if(!n)throw new J(`passkey`,`This platform does not support passkeys`);let r;try{r=await n.startAuthentication(e.webauthn)}catch(e){throw new J(`passkey`,e?.message||`Passkey verification was cancelled`,!0)}if(!r)throw new J(`passkey`,`Passkey verification was cancelled`,!0);return{challenge_id:e.challengeId,credential:r}}},Y=Object.freeze([vn,bn,yn]),xn=(e=Y)=>new Map(e.map(e=>[e.type,e])),Sn=3,Cn={passkey:0,totp:1,email_otp:2,sms_otp:3,recovery_codes:9},wn=e=>e.requiredLevel??je(e.acrValues),Tn=(e,t)=>{let n=Cn[e.type]??5,r=t!==void 0&&t>=Sn,i=e.type===`passkey`;return(r&&!i?100:0)+n},En=(e,t)=>{let n=wn(t);return[...e].sort((e,t)=>Tn(e,n)-Tn(t,n))},X=class extends Error{constructor(e){super(`Upgrade authentication was cancelled`),this.code=`upgrade_cancelled`,this.name=`UpgradeCancelledError`,e!==void 0&&(this.cause=e)}},Z=class extends Error{constructor(e=`No available authentication factor can satisfy this challenge`){super(e),this.code=`upgrade_unsatisfiable`,this.name=`UpgradeUnsatisfiableError`}},Dn=4,On=3e4,kn=()=>{let e=()=>void 0,t=()=>void 0;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Q=e=>({acrValues:e.acrValues,level:e.requiredLevel,maxAge:e.maxAge}),An=(e,t)=>t.level===void 0||e.level!==void 0&&e.level>=t.level,jn=(e,t)=>{let n=e.requiredLevel===void 0?t.requiredLevel:t.requiredLevel===void 0?e.requiredLevel:Math.max(e.requiredLevel,t.requiredLevel),r=n===void 0?e.acrValues??t.acrValues:n===e.requiredLevel?e.acrValues:t.acrValues,i=e.maxAge===void 0?t.maxAge:t.maxAge===void 0?e.maxAge:Math.min(e.maxAge,t.maxAge),a=Array.from(new Set([...e.channels??[],...t.channels??[]]));return{acrValues:r,requiredLevel:n,maxAge:i,status:e.status,...a.length>0?{channels:a}:{}}},Mn=(e,t)=>{let n=t.requiredLevel!==void 0&&(e.requiredLevel===void 0||t.requiredLevel>e.requiredLevel),r=t.maxAge!==void 0&&(e.maxAge===void 0||t.maxAge<e.maxAge);return n||r},Nn=class{constructor(e){this.state=`idle`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.transport=e.transport,this.prompt=e.prompt,this.platform=e.platform,this.available=e.factors??Y,this.registry=xn(this.available),this.maxAttempts=e.maxAttempts??Dn,this.readObtainedBar=e.readObtainedBar,this.onFlightSettled=e.onFlightSettled,this.settleTimeoutMs=e.replaySettleTimeoutMs??On}get currentState(){return this.state}get active(){return this.inFlight!==null}elevate(e,t={kind:`imperative`}){let n=this.register(e,t);if(this.state===`idle`)this.state=`collecting`,this.requirement=e,this.inFlight=this.runFlight();else{this.join(e);let t=this.proof;t?.status===`proven`?this.release(n,t.obtained):t?.status===`failed`&&(this.receiveReport(n,{outcome:`failed`}),n.settlement.reject(t.reason))}return n.settlement.promise}register(e,t){let n=t.kind===`imperative`&&t.requested!==void 0,r={demanded:t.kind===`imperative`&&t.requested?t.requested:Q(e),statedBar:n,settlement:kn(),reported:!1,entry:{...t,outcome:`pending`,report:e=>this.receiveReport(r,e)}};return this.registrations.push(r),r}join(e){let t=this.requirement;if(!t){this.requirement=e;return}let n=Mn(t,e);this.requirement=jn(t,e),n&&this.state===`collecting`&&this.selected===null&&this.openPrompt?.onRequirementRaised?.({challenge:this.requirement,factors:this.offeredFactors()})}offeredFactors(){let e=this.available.filter(e=>!this.pruned.has(e.type)),t=this.requirement;return t?En(e,t):e}receiveReport(e,t){e.reported||(e.reported=!0,e.entry.outcome=t.outcome,t.obtained&&(e.entry.obtained=t.obtained),t.required&&(e.entry.required=t.required),this.notifyReportsSettled())}notifyReportsSettled(){if(!this.reportsSettled||this.registrations.some(e=>!e.reported))return;let e=this.reportsSettled;this.reportsSettled=void 0,e()}async runFlight(){let e;try{e=await this.prove()}catch(t){e={status:`failed`,reason:t instanceof Error?t:Error(String(t))}}if(this.proof=e,e.status===`failed`)for(let t of this.registrations)this.receiveReport(t,{outcome:`failed`}),t.settlement.reject(e.reason);else{this.state=`replaying`;for(let t of this.registrations)this.release(t,e.obtained);await this.awaitReports()}this.state=`settling`;let t=this.summarise(e);try{this.onFlightSettled?.(t)}catch{}this.state=`done`,this.inFlight=null,this.requirement=null,this.selected=null,this.rankedRequirement=null,this.registrations=[],this.proof=null,this.pruned=new Set,this.openPrompt=null,this.reportsSettled=void 0,this.state=`idle`}release(e,t){if(e.entry.kind===`imperative`){if(e.statedBar&&!An(t,e.demanded)){this.receiveReport(e,{outcome:`insufficient`,obtained:t,required:e.demanded}),e.settlement.reject(new V(t,e.demanded));return}this.receiveReport(e,{outcome:`replayed`,obtained:t}),e.settlement.resolve({waiter:e.entry,obtained:t})}else e.settlement.resolve({waiter:e.entry,obtained:t})}awaitReports(){return this.registrations.some(e=>!e.reported)?new Promise(e=>{let t=setTimeout(()=>{this.reportsSettled=void 0;for(let e of this.registrations)e.reported||(e.reported=!0,e.entry.outcome=`failed`);e()},this.settleTimeoutMs);this.reportsSettled=()=>{clearTimeout(t),e()}}):Promise.resolve()}summarise(e){let t=this.registrations.map(e=>({...e.entry.kind===`request`?{url:e.entry.url,method:e.entry.method}:{},outcome:e.entry.outcome,...e.entry.obtained?{obtained:e.entry.obtained}:{},...e.entry.required?{required:e.entry.required}:{}}));if(e.status===`failed`)return{proof:e,waiters:t,terminal:`failed`,error:e.reason};let n;for(let e of t){if(e.outcome!==`insufficient`)continue;let t=e.required?.level??0;(!n||t>(n.required?.level??0))&&(n=e)}return n?{proof:e,waiters:t,terminal:`insufficient`,insufficient:{obtained:n.obtained??e.obtained,required:n.required??{}}}:t.some(e=>e.outcome===`failed`||e.outcome===`pending`)?{proof:e,waiters:t,terminal:`failed`}:{proof:e,waiters:t,terminal:`success`}}async prove(){let e;for(let t=0;t<this.maxAttempts;t++){let t=this.offeredFactors();if(t.length===0)return{status:`failed`,reason:new Z};let n=this.requirement,r;try{r=await this.collect(n,t,e)}catch(e){return{status:`failed`,reason:new X(e)}}if(r.type===`cancel`)return{status:`failed`,reason:new X};let i=this.registry.get(r.factor);if(!i)e=new Z(`Unknown authentication factor: ${r.factor}`),this.state=`collecting`,this.selected=null;else try{return await this.proveAndCommit(i,r.code),{status:`proven`,obtained:this.readObtainedBar?.()??Q(this.rankedRequirement??n)}}catch(t){if(t instanceof J&&t.cancelled)return{status:`failed`,reason:new X};let n=this.classifyProofFailure(t);if(n)return{status:`failed`,reason:n};t instanceof B&&t.kind===`not_registered`&&this.pruned.add(i.type),e=t,this.state=`collecting`,this.selected=null}}return{status:`failed`,reason:new B({kind:`attempts_exhausted`,...e?{cause:e}:{}})}}collect(e,t,n){let r={challenge:e,factors:t,...n?{previousError:n}:{},onFactorSelected:e=>{this.state===`collecting`&&(this.state=`proving`),this.selected=e,this.rankedRequirement=this.requirement}};return this.openPrompt=r,this.prompt(r)}classifyProofFailure(e){if(e instanceof V||e instanceof H||e instanceof U)return e;if(e instanceof B)switch(e.kind){case`unavailable`:return new H(e.message);case`exhausted`:case`attempts_exhausted`:case`fatal`:case`protocol`:case`network`:return e;case`session_changed`:return new U(e.message);default:return}}async proveAndCommit(e,t){let n=e.requiresPrepare?await this.transport.prepare(e.type):void 0,r=await e.assert({code:t,prepared:n,platform:this.platform});await this.transport.commit(e.type,r)}},Pn=e=>typeof e==`function`?e():e,Fn=e=>{try{return new URL(e)}catch{return}},In=(e,t)=>{if(!t||t===`/`)return!0;let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)},Ln=(e,t)=>!t||e.origin===void 0?!1:e.origin===t.origin&&In(e.pathname,t.pathPrefix),Rn=(e,t)=>{for(let n of t){if(n===``)continue;if(n.startsWith(`/`)){if(e.relativeToBase&&In(e.pathname,n))return!0;continue}let t=Fn(n)??Fn(`https://${n}`);if(t&&e.origin!==void 0&&e.origin===t.origin&&In(e.pathname,t.pathname))return!0}return!1},zn=(e,t,n)=>Ln(e,t.passflow)||Rn(e,t.backend)?!n||n(e.href)!==!1:!1,Bn=e=>{let t=e.detail,n=t?.message??`[passflow] upgrade challenge not actioned: ${e.reason}`;console.warn(n,{status:e.status,url:e.url,reason:e.reason,detail:t})},Vn=(e,t)=>{let n=t.onUpgradeDiagnostic??Bn;return(t,r)=>{n({status:e.status,url:e.request.href,reason:t,detail:{method:e.request.method,...r??{}}})}},Hn=(e,t,n)=>{let r=n.onUpgradeDiagnostic??Bn;for(let n of e)r({...n,url:t.request.href,detail:{method:t.request.method,...n.detail??{}}})},Un=/\bjson\b/i,Wn=async(e,t)=>{let n=t.requireChallengeChannel===`header`,r=e.getHeader(`content-type`)??``,i=!n&&Un.test(r),a;if(i)try{a=await e.readBody()}catch{a=void 0}return Ue(i?{status:e.status,getHeader:t=>e.getHeader(t)??void 0,body:a}:{status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:t.requireChallengeChannel})},Gn=e=>Ue({status:e.status,getHeader:t=>e.getHeader(t)??void 0},{requireChallengeChannel:`header`}).challenge,Kn=(e,t)=>t.passflow===null?`[passflow] a 401/403 from ${e} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.`:`[passflow] a 401/403 from ${e} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`,qn=(e,t)=>e instanceof X?{kind:`cancelled`}:e instanceof Z?{kind:`unsatisfiable`}:e instanceof H?{kind:`unavailable`}:e instanceof U?{kind:`session-changed`}:e instanceof V?{kind:`insufficient`,obtained:e.obtained,required:e.required}:e instanceof B?e.kind===`exhausted`||e.kind===`attempts_exhausted`?{kind:`exhausted`,error:e}:e.kind===`unavailable`?{kind:`unavailable`}:e.kind===`session_changed`?{kind:`session-changed`}:{kind:`transport-failure`,status:e.status,retryable:e.retryable,error:e}:{kind:`transport-failure`,retryable:!1,error:e instanceof Error?e:Error(String(e))},Jn=async(e,t,n,r)=>{if(e.status!==401&&e.status!==403)return{kind:`replayed`,response:e};let{challenge:i,diagnostics:a}=await Wn(e,t);if(Hn(a,e,t),!i)return{kind:`replayed`,response:e};let o=Q(i);return r(`elevated-insufficient`,{obtained:n,required:o}),{kind:`insufficient`,obtained:n,required:o,response:e}},Yn=async(e,t)=>{if(!t)return{aborted:!1,value:await e};if(t.aborted)return{aborted:!0,reason:t.reason};if(typeof t.addEventListener!=`function`)return{aborted:!1,value:await e};let n,r=new Promise(e=>{n=()=>e({aborted:!0,reason:t.reason}),t.addEventListener?.(`abort`,n)});try{return await Promise.race([e.then(e=>({aborted:!1,value:e})),r])}finally{n&&t.removeEventListener?.(`abort`,n)}},Xn=async(e,t)=>{if(e.status!==401&&e.status!==403||e.markers.upgradeTransaction)return{kind:`not-a-challenge`};let n=Vn(e,t);if(e.markers.replayed){if(!zn(e.request,t.scope,t.shouldIntercept))return{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Wn(e,t);if(Hn(i,e,t),!r)return{kind:`not-a-challenge`};let a=t.readObtainedBar?.()??{},o=Q(r);return n(`elevated-insufficient`,{obtained:a,required:o}),{kind:`insufficient`,obtained:a,required:o,response:e}}if(!zn(e.request,t.scope,t.shouldIntercept))return Gn(e)?(n(`challenge-out-of-scope`,{header:e.getHeader(`www-authenticate`)??void 0,message:Kn(e.request.href,t.scope)}),{kind:`out-of-scope`}):{kind:`not-a-challenge`};let{challenge:r,diagnostics:i}=await Wn(e,t);if(Hn(i,e,t),!r){let r=e.getHeader(`www-authenticate`);return t.requireChallengeChannel!==`header`&&n(`no-channel`,{...r?{header:r}:{},message:e.responseType===`cors`&&!r?`[passflow] a cross-origin ${e.status} from ${e.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.`:`[passflow] a ${e.status} from ${e.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${e.status}.`}),{kind:`not-a-challenge`}}if(e.replayable===!1)return n(`replay-unsupported`,{message:`[passflow] a ${e.status} from ${e.request.href} carried an upgrade challenge, but the request cannot be replayed (${e.replayUnsupportedReason??`unsupported body`}), so no prompt was opened.`}),{kind:`replay-unsupported`};let a=t.authorizationSwap?.(),o={kind:`request`,url:e.request.href,method:e.request.method},s,c;try{s=Promise.resolve(t.elevate(r,o)),c=await Yn(s,e.signal)}catch(e){return qn(e,void 0)}if(c.aborted)return s?.then(e=>e?.waiter.report({outcome:`failed`}),()=>{}),{kind:`aborted`,reason:c.reason};let l=c.value;if(e.signal?.aborted)return l?.waiter.report({outcome:`failed`}),{kind:`aborted`,reason:e.signal.reason};let u=l?.obtained??t.readObtainedBar?.()??Q(r),d=t.authorizationSwap?.(),f=d?{from:a?.from??d.from,to:d.to}:void 0;e.markers.replayed=!0;let p;try{p=await e.replay(f?{authorizationSwap:f}:void 0)}catch(t){if(t instanceof V)return l?.waiter.report({outcome:`insufficient`,obtained:t.obtained,required:t.required}),e.signal?.aborted?{kind:`aborted`,reason:e.signal.reason}:{kind:`insufficient`,obtained:t.obtained,required:t.required};if(l?.waiter.report({outcome:`failed`}),e.signal?.aborted)return{kind:`aborted`,reason:e.signal.reason};throw t}let m=await Jn(p,t,u,n);return m.kind===`insufficient`?l?.waiter.report({outcome:`insufficient`,obtained:m.obtained,required:m.required}):l?.waiter.report({outcome:`replayed`,obtained:u}),m},Zn=e=>{switch(e.kind){case`cancelled`:return new X;case`unsatisfiable`:return new Z;case`unavailable`:return new H;case`session-changed`:return new U;case`insufficient`:return new V(e.obtained,e.required);case`exhausted`:return e.error;case`transport-failure`:return e.error;default:return}},Qn=(e,t,n)=>{switch(e.kind){case`replayed`:return{settle:`resolve`,value:e.response.raw};case`not-a-challenge`:case`out-of-scope`:case`replay-unsupported`:return{settle:`resolve`,value:t};case`aborted`:return{settle:`reject`,error:e.reason};case`cancelled`:return n.onCancel===`reject`?{settle:`reject`,error:new X}:{settle:`resolve`,value:sr(t,e)};case`insufficient`:return{settle:`resolve`,value:sr(e.response?.raw??t,e)};default:return{settle:`resolve`,value:sr(t,e)}}},$n=(e,t)=>{switch(e.kind){case`replayed`:return e.response.rejected?{settle:`reject`,error:e.response.raw??t}:{settle:`resolve`,value:e.response.raw};case`aborted`:return{settle:`reject`,error:e.reason};default:return{settle:`reject`,error:Zn(e)??t}}},er=new WeakSet,tr=new WeakSet,nr=new WeakSet,rr=new WeakSet,ir=new WeakSet,ar=new WeakSet,or=new WeakSet,sr=(e,t)=>{switch(t.kind){case`cancelled`:er.add(e);break;case`exhausted`:tr.add(e);break;case`insufficient`:nr.add(e);break;case`unsatisfiable`:rr.add(e);break;case`unavailable`:ir.add(e);break;case`session-changed`:ar.add(e);break;case`transport-failure`:or.add(e)}return e},cr=e=>er.has(e),lr=e=>tr.has(e),ur=e=>nr.has(e),dr=e=>rr.has(e),fr=e=>ir.has(e),pr=e=>ar.has(e),mr=e=>or.has(e),hr=`https://passflow-relative.invalid`,gr=()=>{let e=globalThis,t=e.document?.baseURI;if(typeof t==`string`&&t!==``)return t;let n=e.location?.href;return typeof n==`string`&&n!==``&&n!==`about:blank`?n:hr},_r=(e,t=gr())=>{let n=t===hr,r;try{r=new URL(t).origin}catch{r=void 0}let i;try{i=new URL(e,t)}catch{i=void 0}return i?{href:i.href,origin:i.origin,pathname:i.pathname,resolved:!0,relativeToBase:r!==void 0&&i.origin===r,sentinelBase:n}:{href:e,pathname:e.split(/[?#]/)[0]??e,resolved:!1,relativeToBase:!1,sentinelBase:n}},vr=(e,t)=>typeof t==`string`?[e.toLowerCase(),t]:void 0,yr=e=>{let t=[];if(e==null)return Object.freeze(t);let n=e;if(typeof n.forEach==`function`&&typeof n.entries==`function`)return e.forEach((e,n)=>{let r=vr(n,e);r&&t.push(r)}),Object.freeze(t);if(Array.isArray(e)){for(let n of e)if(Array.isArray(n)&&n.length>=2){let e=vr(String(n[0]),n[1]);e&&t.push(e)}return Object.freeze(t)}if(typeof e==`object`)for(let[n,r]of Object.entries(e)){let e=vr(n,Array.isArray(r)?r.join(`, `):r);e&&t.push(e)}return Object.freeze(t)},br=e=>{let t=e.base===void 0?_r(e.url):_r(e.url,e.base),n={raw:e.url,href:t.href,dispatchUrl:t.sentinelBase||!t.resolved?e.url:t.href,...t.origin===void 0?{}:{origin:t.origin},pathname:t.pathname,resolved:t.resolved,relativeToBase:t.relativeToBase,method:(e.method??`GET`).toUpperCase(),headers:yr(e.headers),bodyKind:e.bodyKind,...`body`in e?{body:e.body}:{}};return Object.freeze(n)},xr=(e,t)=>{if(!t||t.from===t.to)return e;let n=!1,r=e.map(([e,r])=>e===`authorization`&&r===t.from?(n=!0,[e,t.to]):[e,r]);return n?Object.freeze(r):e},Sr=e=>{let t={};for(let[n,r]of e)t[n]=r;return t},Cr=new Set([`GET`,`HEAD`,`OPTIONS`]),wr=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.clone==`function`&&`method`in e,Tr=e=>typeof e==`string`?e:wr(e)?e.url:String(e),Er=(e,t)=>(t?.method??(wr(e)?e.method:void 0)??`GET`).toUpperCase(),Dr=e=>e==null?`none`:typeof e==`string`?`reusable`:typeof e.getReader==`function`?`one-shot`:`reusable`,Or=e=>{if(typeof e==`string`)return e.length;let t=e;if(typeof t?.size==`number`)return t.size;if(typeof t?.byteLength==`number`)return t.byteLength},kr=(e,t,n)=>e===void 0||e===`always`?!0:e===`idempotent-only`?Cr.has(t.method):typeof e==`function`?e(t):!(e.maxBodyBytes!==void 0&&n!==void 0&&n>e.maxBodyBytes),$=(e,t,n,r,i)=>({replayable:!1,bodyKind:e,reason:t,forwardInput:n,forwardInit:i,snapshot:r,replay:()=>Promise.reject(Error(`This request cannot be replayed: ${t}`))}),Ar=(e,t)=>Sr(xr(e.headers,t?.authorizationSwap)),jr=e=>{if(!e||!(`headers`in e))return e;let{headers:t,...n}=e;return n},Mr=(e,t)=>t&&`headers`in t&&t.headers!==void 0?t.headers:wr(e)?e.headers:void 0,Nr=e=>{if(e===null||typeof e==`string`)return e;if(typeof FormData<`u`&&e instanceof FormData){let t=new FormData;for(let[n,r]of e)t.append(n,r);return t}return typeof URLSearchParams<`u`&&e instanceof URLSearchParams?new URLSearchParams(e):e instanceof ArrayBuffer?e.slice(0):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice():e},Pr=(e,t,n)=>new Request(e,{headers:Ar(t,n)}),Fr=(e,t,n)=>{let r=Tr(e),i=Er(e,t),a=Mr(e,t),o=(e,t)=>br({url:r,method:i,headers:a,bodyKind:e,...t===void 0?{}:{body:t}});if(wr(e)){if(e.body===null||e.body===void 0){let a=o(`none`);return kr(n,{url:r,method:i,bodyKind:`none`})?{replayable:!0,bodyKind:`none`,forwardInput:e,forwardInit:t,snapshot:a,replay:(n,r)=>n(Pr(e,a,r),jr(t))}:$(`none`,`the replay policy refused this request`,e,a,t)}let a=o(`request-clone`);if(!kr(n,{url:r,method:i,bodyKind:`request-clone`}))return $(`request-clone`,`the replay policy refused this request`,e,a,t);let s;try{s=e.clone()}catch{return $(`one-shot`,`the Request body was already consumed and cannot be cloned`,e,a,t)}return{replayable:!0,bodyKind:`request-clone`,forwardInput:e,forwardInit:t,snapshot:a,replay:(e,n)=>e(Pr(s,a,n),jr(t))}}let s=Dr(t?.body);if(s===`one-shot`)return $(`one-shot`,`a streaming request body is consumed by the first send`,e,o(`one-shot`),t);if(!kr(n,{url:r,method:i,bodyKind:s},Or(t?.body)))return $(s,`the replay policy refused this request`,e,o(s),t);let c=t&&`body`in t?Nr(t.body??null):void 0,l=o(s,c);return{replayable:!0,bodyKind:s,forwardInput:e,forwardInit:t,snapshot:l,replay:(e,n)=>e(l.dispatchUrl,{...jr(t),...c===void 0?{}:{body:c},headers:Ar(l,n),method:l.method})}},Ir=e=>typeof e==`object`&&!!e,Lr=e=>t=>{if(!Ir(e))return;let n=e[t]??e[t.toLowerCase()]??(typeof e.get==`function`?e.get(t):void 0);return Array.isArray(n)?n.join(`, `):typeof n==`string`?n:void 0},Rr=e=>{let t=e?.url??``,n=e?.baseURL;return!n||/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:`${n.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`},zr=e=>(e?.method??`GET`).toUpperCase(),Br=e=>e==null?`none`:Ir(e)&&(typeof e.pipe==`function`||typeof e.getReader==`function`)?`one-shot`:`reusable`,Vr=(e,t,n)=>{let r=Sr(xr(t.headers,n?.authorizationSwap)),i=t.dispatchUrl===t.href&&t.resolved;return{...e,...i?{baseURL:void 0}:{},url:t.dispatchUrl,method:t.method,headers:r,...`body`in t?{data:t.body}:{}}},Hr=(e,t,n,r,i,a)=>{let o=t??e?.config,s=Br(o?.data),c=a??br({url:Rr(o),method:zr(o),headers:o?.headers,bodyKind:s,body:o?.data}),l={url:c.href,method:c.method,bodyKind:s},u=s!==`one-shot`&&kr(i.replay,l);return{status:e?.status??0,getHeader:Lr(e?.headers),readBody:async()=>e?.data,request:c,replay:async e=>{let t=Xe(Vr(o??{},c,e));try{let e=await r(t);return Hr(e,e?.config??t,e,r,i,c)}catch(e){let n=Ir(e)?e:{};if(!n.response||typeof n.response.status!=`number`||Kt(e))throw e;return{...Hr(n.response,n.config??t,e,r,i,c),rejected:!0}}},markers:{...Ye(o)?{upgradeTransaction:!0}:{},...Ze(o)?{replayed:!0}:{}},raw:n,replayable:u,replayUnsupportedReason:s===`one-shot`?`a streaming request body is consumed by the first send`:`the replay policy refused this request`,signal:o?.signal}},Ur=(e,t)=>async n=>{let r=Pn(e),i=Ir(n)?n:{},a=$n(await Xn(Hr(i.response,i.config,i.response,t,r),r),n);if(a.settle===`reject`)throw a.error;return a.value},Wr=(e,t,n)=>{let r=e.request,i=n??(typeof r==`function`?t=>r.call(e,t):()=>Promise.reject(Error(`Passflow: this client exposes no request() to replay through.`))),a=e.interceptors.response.use(void 0,Ur(t,i)),o=!1;return()=>{o||(o=!0,e.interceptors.response.eject(a))}},Gr=(e,t)=>{let n=c.default.create(e);return t(n),n},Kr=0,qr=(e,t)=>{let n=t?.signal??(typeof e==`object`&&e?e.signal:void 0)??void 0;if(n)return{get aborted(){return n.aborted},get reason(){return n.reason},...typeof n.addEventListener==`function`?{addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)}:{}}},Jr=e=>t=>e.headers?.get(t),Yr=(e,t,n,r,i)=>({status:e.status,getHeader:Jr(e),readBody:()=>e.clone().json(),request:t.snapshot,replay:async e=>Yr(await t.replay(n,e),t,n,r,i),markers:r,raw:e,replayable:t.replayable,replayUnsupportedReason:t.reason,signal:i,responseType:e.type}),Xr=(e,t)=>{let n=(t,n)=>{Kr+=1;try{return e(t,n)}finally{--Kr}};return async(e,r)=>{if(Kr>0)return n(e,r);let i=Pn(t),a=Fr(e,r,i.replay),o=await n(a.forwardInput,a.forwardInit),s=Qn(await Xn(Yr(o,a,n,{},qr(e,r)),i),o,i);if(s.settle===`reject`)throw s.error;return s.value}},Zr=new Set(Y.filter(e=>!e.requiresPrepare).map(e=>e.type)),Qr=e=>{if(!e||typeof e!=`object`||!e.challenge_id||!e.expires_at)throw new B({kind:`protocol`,message:`The upgrade start response is missing challenge_id or expires_at`});return{challengeId:e.challenge_id,method:e.method,expiresAt:e.expires_at,webauthn:e.webauthn,codeSentTo:e.code_sent_to}},$r=e=>Kt(e)&&!qt(e),ei=e=>({async prepare(t){if(!Zr.has(t))try{let n=e.relyingPartyId?.();return Qr(await e.startUpgrade(n?{method:t,relying_party_id:n}:{method:t}))}catch(e){if($r(e))throw e;let t=Zt(e,`start`);if(t.kind===`prepare_not_required`)return;throw t}},async commit(t,n){let r=e.canCommit();if(!r.ok)throw new B({kind:`unavailable`,message:r.reason});try{await e.commitRefresh({type:t,assertion:n})}catch(t){if($r(t))throw t;let n=Zt(t,`refresh`);throw n.status===401&&$t(n)&&e.markSessionInvalid?.(),n}}}),ti=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).filter(e=>e!==``),ni=e=>{let t,n=e=>e!==void 0&&t===e,r=r=>{let i=()=>{if(!n(r()))throw new B({kind:`session_changed`})};return ei({...e,relyingPartyId:()=>t?.options.relyingPartyId??e.relyingPartyId?.(),startUpgrade:t=>(i(),e.startUpgrade(t)),commitRefresh:t=>(i(),e.commitRefresh(t,r()?.pin)),...e.markSessionInvalid?{markSessionInvalid:()=>{n(r())&&e.markSessionInvalid?.()}}:{}})},i=(t,n)=>{let i={},a={controller:new Nn({transport:r(()=>i.current),prompt:t.prompt,platform:e.platform,factors:t.factors??e.factors,...t.maxAttempts===void 0?{}:{maxAttempts:t.maxAttempts},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{},...t.onFlightSettled?{onFlightSettled:t.onFlightSettled}:{}}),options:t,scope:{passflow:e.passflowDomain,backend:ti(t.backend)},generation:n};return i.current=a,a},a=async(r,i)=>{let a=t;if(!a)throw new H(`Step-up verification is not enabled on this Passflow instance`);a.controller.active||(a.pin=e.readSessionPin?.());let o=await a.controller.elevate(r,i);if(!n(a))throw new U;return o},o=()=>{let n=t,r=n?.scope??{passflow:e.passflowDomain,backend:[]},i=n?.options;return{elevate:a,scope:r,...i?.requireChallengeChannel?{requireChallengeChannel:i.requireChallengeChannel}:{},...i?.shouldIntercept?{shouldIntercept:i.shouldIntercept}:{},...i?.replay===void 0?{}:{replay:i.replay},...i?.onCancel?{onCancel:i.onCancel}:{},...e.authorizationSwap?{authorizationSwap:e.authorizationSwap}:{},...i?.onUpgradeDiagnostic?{onUpgradeDiagnostic:i.onUpgradeDiagnostic}:{},...e.readObtainedBar?{readObtainedBar:e.readObtainedBar}:{}}},s;return Object.defineProperties(async e=>{let t=e?.acrValues===void 0?void 0:Ae(e.acrValues).level,n={status:401,...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{requiredLevel:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},r=e?.acrValues!==void 0||e?.maxAge!==void 0,i={...e?.acrValues===void 0?{}:{acrValues:e.acrValues},...t===void 0?{}:{level:t},...e?.maxAge===void 0?{}:{maxAge:e.maxAge}},o=(await a(n,{kind:`imperative`,...r?{requested:i}:{}})).obtained.acrValues;return{status:`elevated`,...o===void 0?{}:{acr:o}}},{enable:{value:n=>{s?.(),t=i(n,0);let r=[];if(e.attachInternalSeam){let t=e.attachInternalSeam;t(e=>Ur(o,e)),r.push(()=>t(void 0))}n.interceptFetch&&r.push(Dt((e,t,n)=>Xr(e,o)(t,n),{priority:20,name:`passflow-upgrade`})),e.onSessionChange&&r.push(e.onSessionChange(()=>{let e=t;e&&(t=i(e.options,e.generation+1))}));let a=!1;return s=()=>{if(!a){a=!0;for(let e of r)e();t=void 0,s=void 0}},s},enumerable:!0},enabled:{enumerable:!0,get(){return t!==void 0&&e.canCommit().ok}},elevate:{enumerable:!0,value:(e,t)=>a(e,t??{kind:`imperative`})},withAuth:{enumerable:!0,value:e=>{if(e)return Xr(e,o);let t=typeof globalThis>`u`?void 0:globalThis;if(!t||typeof t.fetch!=`function`)throw Error(`Passflow: withAuth() needs a fetch to wrap — this runtime has none.`);return Xr(t.fetch.bind(t),o)}},attachAuth:{enumerable:!0,value:e=>Wr(e,o)}})},ri,ii=class{get origin(){return this.platform.getCurrentUrl()?.origin??``}constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:e,expiredSession:t,doRefresh:n=!1})=>{this.createSessionCallback=e,this.expiredSessionCallback=t,this.doRefreshTokens=n,await this.submitSessionCheck()};let{url:t,appId:n,scopes:r}=e;this.url=t||`https://auth.passflow.cloud`,this.appId=n,this.platform=e.platform??b,this.storageManager=new Ce({prefix:e.keyStoragePrefix??``,storage:this.platform.storage}),this.deviceService=new we(this.storageManager),this.authApi=new ct(e,this.storageManager,this.deviceService),this.appApi=new st(e,this.storageManager,this.deviceService),this.userApi=new _t(e,this.storageManager,this.deviceService),this.settingApi=new dt(e,this.storageManager,this.deviceService),this.tenantApi=new ft(e,this.storageManager,this.deviceService),this.invitationApi=new ut(e,this.storageManager,this.deviceService),this.twoFactorApi=new ht(e,this.storageManager,this.deviceService),this.upgradeApi=new gt(e,this.storageManager,this.deviceService),this.upgradeDomain=Qe(e.url),this.subscribeStore=new zt,this.tokenCacheService=new mn(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=r??ne,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new un(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??``,e.tokenExchange,this.platform,()=>this.readPkceEnabled()),this.userService=new gn(this.userApi,this.deviceService,this.platform),this.tenantService=new pn(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new dn(this.invitationApi),this.twoFactorService=new hn(this.twoFactorApi,this.subscribeStore,this.authService),this.twoFactor=this.twoFactorService,this.upgrade=ni({startUpgrade:e=>this.upgradeApi.startUpgrade(e),commitRefresh:async(e,t)=>{await this.authService.refreshToken(e,t)},readSessionPin:()=>this.authService.readSessionPin(),canCommit:()=>this.authService.tokenDeliveryManager.isBFFMode()?{ok:!1,reason:`Step-up verification cannot be committed through a BFF refresh endpoint`}:{ok:!0},markSessionInvalid:()=>this.authService.tokenDeliveryManager.setSessionInvalid(),platform:this.platform,passflowDomain:this.upgradeDomain,...e.upgrade?.factors?{factors:e.upgrade.factors}:{},...e.upgrade?.relyingPartyId?{relyingPartyId:()=>e.upgrade?.relyingPartyId}:{},readObtainedBar:()=>this.readAssuranceBar(),authorizationSwap:()=>{let e=this.storageManager.getToken(v.access_token);return e?{from:`Bearer ${e}`,to:`Bearer ${e}`}:void 0},attachInternalSeam:e=>this.attachUpgradeSeam(e),onSessionChange:e=>this.subscribeToSessionChange(e)}),e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}readPkceEnabled(){if(!this.appId)return Promise.resolve(!1);if(!this.pkceEnabledRead){let e=this.appApi.getAppSettings().then(e=>e.pkce_enabled);this.pkceEnabledRead=e,e.catch(()=>{this.pkceEnabledRead===e&&(this.pkceEnabledRead=void 0)})}return this.pkceEnabledRead}setAppId(e){this.appId=e,this.pkceEnabledRead=void 0,this.authApi.setAppId(e),this.appApi.setAppId(e),this.userApi.setAppId(e),this.settingApi.setAppId(e),this.tenantApi.setAppId(e),this.invitationApi.setAppId(e),this.twoFactorApi.setAppId(e),this.upgradeApi.setAppId(e),this.authService}withAuth(e){return this.upgrade.withAuth(e)}attachAuth(e){return this.upgrade.attachAuth(e)}createClient(e){return Gr(e,e=>this.upgrade.attachAuth(e))}readAssuranceBar(){let e=this.storageManager.getToken(v.access_token);if(e)try{let t=_(e),n=typeof t.acr==`string`?t.acr:void 0;if(!n)return;let r=Ae(n).level;return r===void 0?{acrValues:n}:{acrValues:n,level:r}}catch{return}}axiosClients(){return[this.authApi.axiosClient,this.appApi.axiosClient,this.userApi.axiosClient,this.settingApi.axiosClient,this.tenantApi.axiosClient,this.invitationApi.axiosClient,this.twoFactorApi.axiosClient,this.upgradeApi.axiosClient]}attachUpgradeSeam(e){for(let t of this.axiosClients()){if(!e){t.setUpgradeInterceptor(void 0);continue}let n=e(e=>t.replay(e));t.setUpgradeInterceptor(n)}}subscribeToSessionChange(e){let t={onAuthChange:()=>e()};return this.subscribeStore.subscribe(t,[R.SignIn,R.SignOut]),()=>this.subscribeStore.unsubscribe(t)}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(t){let n={message:t instanceof Error||t instanceof w?t.message:`Session check failed`,originalError:t};this.subscribeStore.notify(R.Error,n),e=void 0}e&&this.createSessionCallback&&await this.createSessionCallback({tokens:e,parsedTokens:t}),!e&&this.expiredSessionCallback&&await this.expiredSessionCallback()}subscribe(e,t){this.subscribeStore.subscribe(e,t),this.tokenCacheService.initialize()}unsubscribe(e,t){this.subscribeStore.unsubscribe(e,t)}handleTokensRedirect(){return this.checkAndSetTokens()}checkAndSetTokens(){let e=this.platform.getCurrentUrl(),t=new URLSearchParams(e?.search??``),n=!1;if(!t.get(`access_token`)&&e?.hash){let r=new URLSearchParams(e.hash.substring(1));r.get(`access_token`)&&(t=r,n=!0)}if(!t.get(`access_token`)&&this.adoptTwoFactorTokenFromUrl(e)){this.error=void 0;return}let r=t.get(`access_token`),i=t.get(`refresh_token`),a=t.get(`id_token`),o=t.get(`scopes`)?.split(`,`)??this.scopes,s;if(r){if(!W(r)){this.subscribeStore.notify(R.Error,{message:`Invalid access token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}if(i&&!W(i)){this.subscribeStore.notify(R.Error,{message:`Invalid refresh token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}if(a&&!W(a)){this.subscribeStore.notify(R.Error,{message:`Invalid ID token format received`,code:`INVALID_TOKEN_FORMAT`}),this.cleanupUrlParams(n,e);return}return s={access_token:r,refresh_token:i??void 0,id_token:a??void 0,scopes:o},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(s),this.tokenCacheService.setTokensCache(s),this.subscribeStore.notify(R.SignIn,{tokens:s,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(n,e),this.error=void 0,s}this.error=this.checkErrorsFromURL()}adoptTwoFactorTokenFromUrl(e){if(!e?.hash)return!1;let t=new URLSearchParams(e.hash.substring(1)),n=t.get(`tfa_token`);if(!n)return!1;t.delete(`tfa_token`);let r=t.toString();return this.platform.replaceUrl(e.pathname+e.search+(r?`#${r}`:``)),W(n)?(this.subscribeStore.notify(R.TwoFactorRequired,{email:``,challengeId:``,tfaToken:n}),!0):(this.subscribeStore.notify(R.Error,{message:`Invalid 2FA token format received`,code:`INVALID_TOKEN_FORMAT`}),!0)}checkErrorsFromURL(){let e=new URLSearchParams(this.platform.getCurrentUrl()?.search??``).get(`error`);if(e){let t=nn(e);return Error(t)}}cleanupUrlParams(e=!1,t=null){let n=t??this.platform.getCurrentUrl();if(n){if(e)this.platform.replaceUrl(n.pathname+n.search);else{let e=new URLSearchParams(n.search);e.delete(`access_token`),e.delete(`refresh_token`),e.delete(`id_token`),e.delete(`client_challenge`),e.size>0?this.platform.replaceUrl(`${n.pathname}?${e.toString()}`):this.platform.replaceUrl(n.pathname)}}}setTokensToCacheFromLocalStorage(){let e=this.storageManager.getTokens();if(!e?.access_token&&this.storageManager.getDeliveryMode()){if(e?.id_token&&this.storageManager.hasCookieModeIdToken()){this.tokenCacheService.setTokensCache(e);return}if(this.storageManager.hasJsonModeTokens())this.storageManager.clearDeliveryMode(),e=this.storageManager.getTokens();else{this.storageManager.deleteTokens();return}}e&&this.tokenCacheService.setTokensCache(e)}getCachedTokens(){return this.tokenCacheService.getTokens()}getTokensWithRefresh(){return this.tokenCacheService.getTokensWithRefresh()}getParsedTokens(){return this.tokenCacheService.getParsedTokens()}areTokensExpired(){return this.tokenCacheService.isExpired()}isAuthenticated(){let e=this.storageManager.getTokens();if(!e||!e.access_token)return!1;let t=this.tokenCacheService.getParsedTokens();return t?this.authService.isAuthenticated(t):!1}async signIn(e){return await this.authService.signIn(e)}async signUp(e){return await this.authService.signUp(e)}passwordlessSignIn(e){return this.authService.passwordlessSignIn(e)}async passwordlessSignInComplete(e){return await this.authService.passwordlessSignInComplete(e)}handleError(e,t){let n={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:e instanceof w?e.id:void 0};throw this.subscribeStore.notify(R.Error,n),e}async logOut(){try{await this.authService.logOut(),this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.twoFactorService.clearPartialAuthState(),await this.submitSessionCheck(),this.subscribeStore.notify(R.SignOut,{})}catch(e){this.handleError(e,`Log out`)}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}reset(e){if(this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.subscribeStore.notify(R.SignOut,{}),e){this.error=Error(e);let t={message:e,code:`RESET_ERROR`};throw this.subscribeStore.notify(R.Error,t),this.error}}async refreshToken(){if(!this.tokenCacheService.parsedTokensCache?.refresh_token)throw Error(`No refresh token found`);try{return await this.authService.refreshToken()}catch(e){throw e instanceof w||this.subscribeStore.notify(R.Error,{message:`Failed to refresh token`,originalError:e}),e}}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t){return await this.authService.resetPassword(e,t)}async getAppSettings(){try{return await this.appApi.getAppSettings()}catch(e){this.handleError(e,`Get app settings`)}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,`Get all settings`)}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,`Get password policy settings`)}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,`Get passkey settings`)}}async passkeyRegister(e){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){this.storageManager.saveTokens(e),this.tokenCacheService.setTokensCache(e),this.subscribeStore.notify(R.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()})}async getTokens(e=!1){return await this.authService.getTokens(e)}getToken(e){return this.storageManager.getToken(e)}async getUserPasskeys(){try{return await this.userService.getUserPasskeys()}catch(e){this.handleError(e,`Get user passkeys`)}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(e){this.handleError(e,`Rename user passkey`)}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(e){this.handleError(e,`Delete user passkey`)}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(e){this.handleError(e,`Add user passkey`)}}async joinInvitation(e,t){try{let n=await this.tenant.joinInvitation(e,t);return n.scopes=t??this.scopes,await this.authService.applyTokens(n),n}catch(e){this.handleError(e,`Join invitation`)}}async createTenant(e,t){try{let n=await this.tenant.createTenant(e);return t&&await this.refreshToken(),n}catch(e){this.handleError(e,`Create tenant`)}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(e){this.handleError(e,`Request invite link`)}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(e){this.handleError(e,`Get invitations`)}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(e){this.handleError(e,`Delete invitation`)}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(e){this.handleError(e,`Resend invitation`)}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(e){this.handleError(e,`Get invitation link`)}}authRedirectUrl(e={}){return this.authService.authRedirectUrl(e)}authRedirect(e={}){this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}async restoreSession(){return await this.authService.restoreSession()}async getTwoFactorStatus(){try{return await this.twoFactorService.getStatus()}catch(e){this.handleError(e,`Get 2FA status`)}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,`Begin 2FA setup`)}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(e){this.handleError(e,`Confirm 2FA setup`)}}async verifyTwoFactor(e,t){try{let n=await this.twoFactorService.verify(e,t);return this.subscribeStore.notify(R.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`Verify 2FA`)}}async useTwoFactorRecoveryCode(e,t){try{let n=await this.twoFactorService.useRecoveryCode(e,t);return this.subscribeStore.notify(R.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(e){this.handleError(e,`Use 2FA recovery code`)}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(e){this.handleError(e,`Disable 2FA`)}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(e){this.handleError(e,`Regenerate 2FA recovery codes`)}}async getTrustedDevices(){try{return await this.twoFactorService.getTrustedDevices()}catch(e){this.handleError(e,`Get trusted devices`)}}async revokeTrustedDevice(e){try{await this.twoFactorService.revokeTrustedDevice(e)}catch(e){this.handleError(e,`Revoke trusted device`)}}isTwoFactorVerificationRequired(){return this.twoFactorService.isVerificationRequired()}getTotpDigits(){return this.twoFactorService.getTotpDigits()}async validateTwoFactorSetupMagicLink(e){return await this.twoFactorService.validateTwoFactorSetupMagicLink(e)}getMagicLinkSession(){return this.twoFactorService.getMagicLinkSession()}hasMagicLinkSession(){return this.twoFactorService.hasMagicLinkSession()}clearMagicLinkSession(){this.twoFactorService.clearMagicLinkSession()}};ri=ii,ri.version=ee,exports.APP_ID_HEADER_KEY=d,exports.AUTHORIZATION_HEADER_KEY=f,exports.AppAPI=st,exports.AuthAPI=ct,exports.AuthService=un,exports.CLIAuthAPI=lt,exports.DEFAULT_GROUP_NAME=ie,exports.DEFAULT_SCOPES=ne,exports.DEFAULT_UPGRADE_FACTORS=Y,exports.DEVICE_ID_HEADER_KEY=p,exports.DEVICE_TYPE_HEADER_KEY=m,exports.ERROR_MESSAGE_MAX_LENGTH=fe,exports.FETCH_PRIORITY_OIDC=vt,exports.FETCH_PRIORITY_UPGRADE=yt,exports.FetchMiddlewareContractError=bt,exports.INSUFFICIENT_USER_AUTHENTICATION=Me,exports.InvitationAPI=ut,exports.InvitationService=dn,exports.M2MClient=Nt,exports.M2MConfigError=F,exports.M2MError=N,exports.M2MErrorCodes=At,exports.M2MNetworkError=kt,exports.M2MTokenParseError=P,exports.M2M_DEFAULTS=I,exports.MINIMAL_DEFAULT_SCOPES=te,exports.OS=et,exports.PASSFLOW_CLOUD_URL=re,exports.POPUP_HEIGHT=oe,exports.POPUP_POLL_INTERVAL_MS=se,exports.POPUP_TIMEOUT_MS=ce,exports.POPUP_WIDTH=ae,exports.Passflow=ii,exports.PassflowAdminEndpointPaths=C,exports.PassflowEndpointPaths=S,exports.PassflowError=w,exports.PassflowEvent=R,exports.PopupClosedError=Te,exports.Providers=$e,exports.RECOVERABLE_COMMIT_ERROR_IDS=Bt,exports.RequestMethod=x,exports.SDK_VERSION=ee,exports.SESSION_INVALIDATING_COMMIT_ERROR_IDS=Vt,exports.SessionState=xe,exports.SettingAPI=dt,exports.TOKEN_EXPIRY_BUFFER_SECONDS=le,exports.TenantAPI=ft,exports.TenantService=pn,exports.TenantUserMembership=fn,exports.TokenCacheService=mn,exports.TokenDeliveryMode=y,exports.TokenType=v,exports.TwoFactorApiClient=ht,exports.TwoFactorPolicy=tt,exports.TwoFactorService=hn,exports.UPGRADE_REQUIRED=Ne,exports.USERNAME_MAX_LENGTH=de,exports.USERNAME_MIN_LENGTH=ue,exports.UpgradeAPI=gt,exports.UpgradeCancelledError=X,exports.UpgradeController=Nn,exports.UpgradeErrorIds=z,exports.UpgradeFactorError=J,exports.UpgradeInsufficientError=V,exports.UpgradeSessionChangedError=U,exports.UpgradeTransportError=B,exports.UpgradeUnavailableError=H,exports.UpgradeUnsatisfiableError=Z,exports.UserAPI=_t,exports.UserService=gn,exports.WebAdapter=Ee,exports.classifyUpgradeError=Zt,exports.factorRegistry=xn,exports.fetchRegistryState=Ot,exports.getOSFromDeviceType=T,exports.invalidatesSessionOnCommit=$t,exports.isRecoverableCommitFailure=Qt,exports.isRetryableUpgradeKind=Ut,exports.isTokenExpired=g,exports.isUpgradeCancelled=cr,exports.isUpgradeExhausted=lr,exports.isUpgradeInsufficient=ur,exports.isUpgradeSessionChanged=pr,exports.isUpgradeTransportError=qt,exports.isUpgradeTransportFailure=mr,exports.isUpgradeUnavailable=fr,exports.isUpgradeUnsatisfiable=dr,exports.isValidEmail=G,exports.isValidJWTFormat=W,exports.isValidPhoneNumber=K,exports.isValidUsername=rn,exports.parseChallengeBody=Be,exports.parseChallengeHeader=ze,exports.parseToken=_,exports.parseUpgradeChallenge=We,exports.passkeyFactor=bn,exports.pathWithParams=E,exports.recoveryCodesFactor=yn,exports.registerFetchMiddleware=Dt,exports.requiredAcrLevel=je,exports.resolveUpgradeDomain=Qe,exports.sanitizeErrorMessage=nn,exports.selectFactors=En,exports.totpFactor=vn,exports.webAdapter=b;
2
2
  //# sourceMappingURL=index.cjs.map