@stytch/vanilla-js 6.0.6 → 6.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/cjs/{StytchSSRProxy-uT0ZmdOT.js → StytchSSRProxy-4bK96PqP.js} +2 -5
- package/dist/cjs/StytchSSRProxy-4bK96PqP.js.map +1 -0
- package/dist/cjs/b2b/index.cjs +2 -2
- package/dist/cjs/b2b/index.headless.cjs +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.headless.cjs +1 -1
- package/dist/cjs/{shadcn-DNo-Z1LB.js → shadcn-C9ZF6bjn.js} +2 -2
- package/dist/cjs/{shadcn-DNo-Z1LB.js.map → shadcn-C9ZF6bjn.js.map} +1 -1
- package/dist/cjs-dev/{StytchSSRProxy-Dz4qX2tJ.js → StytchSSRProxy-4d3oztg-.js} +2 -5
- package/dist/cjs-dev/StytchSSRProxy-4d3oztg-.js.map +1 -0
- package/dist/cjs-dev/b2b/index.cjs +2 -2
- package/dist/cjs-dev/b2b/index.headless.cjs +1 -1
- package/dist/cjs-dev/index.cjs +2 -2
- package/dist/cjs-dev/index.headless.cjs +1 -1
- package/dist/cjs-dev/{shadcn-JZgM-5AS.js → shadcn-BMlZ0kfy.js} +2 -2
- package/dist/cjs-dev/{shadcn-JZgM-5AS.js.map → shadcn-BMlZ0kfy.js.map} +1 -1
- package/dist/esm/_virtual/index3.mjs +3 -5
- package/dist/esm/_virtual/index3.mjs.map +1 -1
- package/dist/esm/_virtual/index4.mjs +5 -3
- package/dist/esm/_virtual/index4.mjs.map +1 -1
- package/dist/esm/packages/web/src/NetworkClient.mjs +1 -3
- package/dist/esm/packages/web/src/NetworkClient.mjs.map +1 -1
- package/dist/esm/packages/web/src/adminPortal/utils/theme.mjs +1 -1
- package/dist/esm/packages/web/src/utils/crypto.mjs +1 -1
- package/dist/esm-dev/packages/web/src/NetworkClient.mjs +1 -3
- package/dist/esm-dev/packages/web/src/NetworkClient.mjs.map +1 -1
- package/dist/iife/b2b/index.headless.js +1 -1
- package/dist/iife/b2b/index.headless.js.map +1 -1
- package/dist/iife/b2b/index.js +1 -1
- package/dist/iife/b2b/index.js.map +1 -1
- package/dist/iife/index.headless.js +1 -1
- package/dist/iife/index.headless.js.map +1 -1
- package/dist/iife/index.js +1 -1
- package/dist/iife/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/StytchSSRProxy-uT0ZmdOT.js.map +0 -1
- package/dist/cjs-dev/StytchSSRProxy-Dz4qX2tJ.js.map +0 -1
- package/dist/esm/packages/web/package.json.mjs +0 -4
- package/dist/esm/packages/web/package.json.mjs.map +0 -1
- package/dist/esm-dev/packages/web/package.json.mjs +0 -4
- package/dist/esm-dev/packages/web/package.json.mjs.map +0 -1
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { __require as requireLodash_merge } from '../node_modules/lodash.merge/index.mjs';
|
|
1
|
+
import { __require as requireBs58 } from '../node_modules/bs58/index.mjs';
|
|
3
2
|
|
|
4
|
-
var
|
|
5
|
-
var merge = /*@__PURE__*/getDefaultExportFromCjs(lodash_mergeExports);
|
|
3
|
+
var bs58Exports = requireBs58();
|
|
6
4
|
|
|
7
|
-
export {
|
|
5
|
+
export { bs58Exports as b };
|
|
8
6
|
//# sourceMappingURL=index3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index3.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index3.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getDefaultExportFromCjs } from './_commonjsHelpers.mjs';
|
|
2
|
+
import { __require as requireLodash_merge } from '../node_modules/lodash.merge/index.mjs';
|
|
2
3
|
|
|
3
|
-
var
|
|
4
|
+
var lodash_mergeExports = requireLodash_merge();
|
|
5
|
+
var merge = /*@__PURE__*/getDefaultExportFromCjs(lodash_mergeExports);
|
|
4
6
|
|
|
5
|
-
export {
|
|
7
|
+
export { merge as default };
|
|
6
8
|
//# sourceMappingURL=index4.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index4.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index4.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { version } from '../package.json.mjs';
|
|
2
1
|
import { isTestPublicToken, createPersistentId, createAppSessionId, createEventId } from '../../core/src/utils/index.mjs';
|
|
3
2
|
import { EventLogger, DEFAULT_INTERVAL_DURATION_MS, DEFAULT_MAX_BATCH_SIZE } from '../../core/src/EventLogger.mjs';
|
|
4
3
|
import { baseFetchSDK, baseSubmitFormSDK, retriableFetchSDK } from '../../core/src/NetworkClient.mjs';
|
|
@@ -64,10 +63,9 @@ class NetworkClient {
|
|
|
64
63
|
identifier: window.location.hostname
|
|
65
64
|
},
|
|
66
65
|
sdk: {
|
|
67
|
-
// TODO: Pull these from package.json when there is a package
|
|
68
66
|
// eslint-disable-next-line lingui/no-unlocalized-strings
|
|
69
67
|
identifier: 'Stytch.js Javascript SDK',
|
|
70
|
-
version:
|
|
68
|
+
version: "@stytch/vanilla-js" + '@' + "6.0.7"
|
|
71
69
|
}
|
|
72
70
|
};
|
|
73
71
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkClient.mjs","sources":["../../../../../../web/src/NetworkClient.ts"],"sourcesContent":["import {\n AdditionalTelemetryData,\n baseFetchSDK,\n baseSubmitFormSDK,\n createAppSessionId,\n createEventId,\n createPersistentId,\n DEFAULT_INTERVAL_DURATION_MS,\n DEFAULT_MAX_BATCH_SIZE,\n EventLogger,\n INetworkClient,\n isTestPublicToken,\n retriableFetchSDK,\n RetriableSDKRequestInfo,\n SDKRequestInfo,\n SDKTelemetry,\n} from '@stytch/core';\nimport { ResponseCommon } from '@stytch/core/public';\n\nimport { version as PACKAGE_VERSION } from '../package.json';\nimport { B2BSubscriptionDataLayer, ConsumerSubscriptionDataLayer } from './SubscriptionService';\n\nexport class NetworkClient implements INetworkClient {\n private eventLogger: EventLogger;\n private readonly baseURL: string;\n\n constructor(\n private _publicToken: string,\n private _subscriptionDataLayer: ConsumerSubscriptionDataLayer | B2BSubscriptionDataLayer,\n _liveAPIURL: string,\n _testAPIURL: string,\n private additionalTelemetryDataFn: () => AdditionalTelemetryData,\n ) {\n this.baseURL = _liveAPIURL;\n if (isTestPublicToken(_publicToken)) {\n this.baseURL = _testAPIURL;\n }\n this.eventLogger = new EventLogger({\n maxBatchSize: DEFAULT_MAX_BATCH_SIZE,\n intervalDurationMs: DEFAULT_INTERVAL_DURATION_MS,\n logEventURL: this.buildSDKUrl('/events'),\n });\n }\n\n // @deprecated Use the new sessions.updateSession() method instead\n updateSessionToken = () => {\n return null;\n };\n\n logEvent({\n name,\n details,\n error = {},\n }: {\n name: string;\n details: Record<string, unknown>;\n error?: { error_code?: string; error_description?: string; http_status_code?: string };\n }): void {\n this.eventLogger.logEvent(this.createTelemetryBlob(), {\n public_token: this._publicToken,\n event_name: name,\n details: details,\n\n // Error fields\n error_code: error.error_code,\n error_description: error.error_description,\n http_status_code: error.http_status_code,\n });\n }\n\n createTelemetryBlob(): SDKTelemetry {\n return {\n event_id: createEventId(),\n // TODO: These should be persisted somewhere, not generated per request\n app_session_id: createAppSessionId(),\n persistent_id: createPersistentId(),\n\n client_sent_at: new Date().toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n\n // Logged in data\n // This gets passed into the constructor from StytchClient or StytchB2BClient\n // We pass in the user & session id when the Consumer SDK is being used and member & session id\n // when the B2B SDK is being used.\n\n // Why don't we generate this from the session_token in the auth header?\n // - We don't want to tie analytics ingest to session validation. There's no need to put\n // that kind of pressure on API, and ingest could be moved to somewhere that doesn't\n // have the ability to validate tokens\n // - For bulk event batches, we want to keep track of whether or not a user was logged\n // in at each event. If we have 10 events, the user logs in at event 5, then they'll have\n // a token when they log the batch, but we want to know that they were not logged in for the\n // first 4 events\n ...this.additionalTelemetryDataFn(),\n\n // Versioning\n app: {\n identifier: window.location.hostname,\n },\n sdk: {\n // TODO: Pull these from package.json when there is a package\n // eslint-disable-next-line lingui/no-unlocalized-strings\n identifier: 'Stytch.js Javascript SDK',\n version: PACKAGE_VERSION,\n },\n };\n }\n\n async fetchSDK<T extends ResponseCommon>({ url, body, method }: SDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async submitFormSDK({ url, body, method }: SDKRequestInfo): Promise<void> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseSubmitFormSDK({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async retriableFetchSDK<T extends ResponseCommon>({\n url,\n body,\n method,\n retryCallback,\n }: RetriableSDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return retriableFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n retryCallback,\n });\n }\n\n buildSDKUrl(url: string): string {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n return `${this.baseURL}/sdk/v1${url}`;\n }\n}\n"],"names":["NetworkClient","eventLogger","baseURL","_subscriptionDataLayer","_liveAPIURL","_testAPIURL","_publicToken","additionalTelemetryDataFn","isTestPublicToken","EventLogger","maxBatchSize","DEFAULT_MAX_BATCH_SIZE","intervalDurationMs","DEFAULT_INTERVAL_DURATION_MS","logEventURL","buildSDKUrl","updateSessionToken","logEvent","name","details","error","createTelemetryBlob","public_token","event_name","error_code","error_description","http_status_code","event_id","createEventId","app_session_id","createAppSessionId","persistent_id","createPersistentId","client_sent_at","Date","toISOString","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","app","identifier","window","location","hostname","sdk","version","PACKAGE_VERSION","fetchSDK","url","body","method","sessionToken","readSessionCookie","session_token","basicAuthHeader","btoa","xSDKClientHeader","JSON","stringify","xSDKParentHostHeader","origin","baseFetchSDK","finalURL","submitFormSDK","baseSubmitFormSDK","retriableFetchSDK","retryCallback"],"mappings":";;;;;AAsBO,MAAMA,aAAAA,CAAAA;;;;IACHC,WAAAA;IACSC,OAAAA;AAEjB,IAAA,WAAA,CACE,YAA4B,EACpBC,sBAAgF,EACxFC,WAAmB,EACnBC,WAAmB,EACnB,yBAAgE,CAChE;aALQC,YAAAA,GAAAA,YAAAA;aACAH,sBAAAA,GAAAA,sBAAAA;aAGAI,yBAAAA,GAAAA,yBAAAA;QAER,IAAI,CAACL,OAAO,GAAGE,WAAAA;AACf,QAAA,IAAII,kBAAkBF,YAAAA,CAAAA,EAAe;YACnC,IAAI,CAACJ,OAAO,GAAGG,WAAAA;AACjB,QAAA;AACA,QAAA,IAAI,CAACJ,WAAW,GAAG,IAAIQ,WAAAA,CAAY;YACjCC,YAAA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C,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;IAEA,MAAMM,iBAAAA,CAA4C,EAChDjB,GAAG,EACHC,IAAI,EACJC,MAAM,EACNgB,aAAa,EACW,EAAc;AACtC,QAAA,MAAMf,eAAe,IAAI,CAAClD,sBAAsB,CAACmD,iBAAiB,GAAGC,aAAa;AAClF,QAAA,MAAMC,eAAAA,GAAkB,QAAA,GAAWb,MAAAA,CAAOc,IAAI,CAAC,IAAI,CAACnD,YAAY,GAAG,OAAO+C,YAAAA,IAAgB,IAAI,CAAC/C,YAAY,CAAD,CAAA;QAC1G,MAAMoD,gBAAAA,GAAmBf,OAAOc,IAAI,CAACE,KAAKC,SAAS,CAAC,IAAI,CAACvC,mBAAmB,EAAA,CAAA,CAAA;AAC5E,QAAA,MAAMwC,oBAAAA,GAAuBlB,MAAAA,CAAOC,QAAQ,CAACkB,MAAM;AAEnD,QAAA,OAAOK,iBAAAA,CAAqB;AAC1BX,YAAAA,eAAAA;AACAL,YAAAA,IAAAA;YACAa,QAAAA,EAAU,IAAI,CAACjD,WAAW,CAACmC,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA,oBAAAA;AACAO,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;AAEArD,IAAAA,WAAAA,CAAYmC,GAAW,EAAU;;AAE/B,QAAA,OAAO,GAAG,IAAI,CAAChD,OAAO,CAAC,OAAO,EAAEgD,GAAAA,CAAAA,CAAK;AACvC,IAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"NetworkClient.mjs","sources":["../../../../../../web/src/NetworkClient.ts"],"sourcesContent":["import {\n AdditionalTelemetryData,\n baseFetchSDK,\n baseSubmitFormSDK,\n createAppSessionId,\n createEventId,\n createPersistentId,\n DEFAULT_INTERVAL_DURATION_MS,\n DEFAULT_MAX_BATCH_SIZE,\n EventLogger,\n INetworkClient,\n isTestPublicToken,\n retriableFetchSDK,\n RetriableSDKRequestInfo,\n SDKRequestInfo,\n SDKTelemetry,\n} from '@stytch/core';\nimport { ResponseCommon } from '@stytch/core/public';\n\nimport { B2BSubscriptionDataLayer, ConsumerSubscriptionDataLayer } from './SubscriptionService';\n\nexport class NetworkClient implements INetworkClient {\n private eventLogger: EventLogger;\n private readonly baseURL: string;\n\n constructor(\n private _publicToken: string,\n private _subscriptionDataLayer: ConsumerSubscriptionDataLayer | B2BSubscriptionDataLayer,\n _liveAPIURL: string,\n _testAPIURL: string,\n private additionalTelemetryDataFn: () => AdditionalTelemetryData,\n ) {\n this.baseURL = _liveAPIURL;\n if (isTestPublicToken(_publicToken)) {\n this.baseURL = _testAPIURL;\n }\n this.eventLogger = new EventLogger({\n maxBatchSize: DEFAULT_MAX_BATCH_SIZE,\n intervalDurationMs: DEFAULT_INTERVAL_DURATION_MS,\n logEventURL: this.buildSDKUrl('/events'),\n });\n }\n\n // @deprecated Use the new sessions.updateSession() method instead\n updateSessionToken = () => {\n return null;\n };\n\n logEvent({\n name,\n details,\n error = {},\n }: {\n name: string;\n details: Record<string, unknown>;\n error?: { error_code?: string; error_description?: string; http_status_code?: string };\n }): void {\n this.eventLogger.logEvent(this.createTelemetryBlob(), {\n public_token: this._publicToken,\n event_name: name,\n details: details,\n\n // Error fields\n error_code: error.error_code,\n error_description: error.error_description,\n http_status_code: error.http_status_code,\n });\n }\n\n createTelemetryBlob(): SDKTelemetry {\n return {\n event_id: createEventId(),\n // TODO: These should be persisted somewhere, not generated per request\n app_session_id: createAppSessionId(),\n persistent_id: createPersistentId(),\n\n client_sent_at: new Date().toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n\n // Logged in data\n // This gets passed into the constructor from StytchClient or StytchB2BClient\n // We pass in the user & session id when the Consumer SDK is being used and member & session id\n // when the B2B SDK is being used.\n\n // Why don't we generate this from the session_token in the auth header?\n // - We don't want to tie analytics ingest to session validation. There's no need to put\n // that kind of pressure on API, and ingest could be moved to somewhere that doesn't\n // have the ability to validate tokens\n // - For bulk event batches, we want to keep track of whether or not a user was logged\n // in at each event. If we have 10 events, the user logs in at event 5, then they'll have\n // a token when they log the batch, but we want to know that they were not logged in for the\n // first 4 events\n ...this.additionalTelemetryDataFn(),\n\n // Versioning\n app: {\n identifier: window.location.hostname,\n },\n sdk: {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n identifier: 'Stytch.js Javascript SDK',\n version: STYTCH_PACKAGE_NAME + '@' + STYTCH_PACKAGE_VERSION,\n },\n };\n }\n\n async fetchSDK<T extends ResponseCommon>({ url, body, method }: SDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async submitFormSDK({ url, body, method }: SDKRequestInfo): Promise<void> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseSubmitFormSDK({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async retriableFetchSDK<T extends ResponseCommon>({\n url,\n body,\n method,\n retryCallback,\n }: RetriableSDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return retriableFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n retryCallback,\n });\n }\n\n buildSDKUrl(url: string): string {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n return `${this.baseURL}/sdk/v1${url}`;\n }\n}\n"],"names":["NetworkClient","eventLogger","baseURL","_subscriptionDataLayer","_liveAPIURL","_testAPIURL","_publicToken","additionalTelemetryDataFn","isTestPublicToken","EventLogger","maxBatchSize","DEFAULT_MAX_BATCH_SIZE","intervalDurationMs","DEFAULT_INTERVAL_DURATION_MS","logEventURL","buildSDKUrl","updateSessionToken","logEvent","name","details","error","createTelemetryBlob","public_token","event_name","error_code","error_description","http_status_code","event_id","createEventId","app_session_id","createAppSessionId","persistent_id","createPersistentId","client_sent_at","Date","toISOString","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","app","identifier","window","location","hostname","sdk","version","fetchSDK","url","body","method","sessionToken","readSessionCookie","session_token","basicAuthHeader","btoa","xSDKClientHeader","JSON","stringify","xSDKParentHostHeader","origin","baseFetchSDK","finalURL","submitFormSDK","baseSubmitFormSDK","retriableFetchSDK","retryCallback"],"mappings":";;;;AAqBO,MAAMA,aAAAA,CAAAA;;;;IACHC,WAAAA;IACSC,OAAAA;AAEjB,IAAA,WAAA,CACE,YAA4B,EACpBC,sBAAgF,EACxFC,WAAmB,EACnBC,WAAmB,EACnB,yBAAgE,CAChE;aALQC,YAAAA,GAAAA,YAAAA;aACAH,sBAAAA,GAAAA,sBAAAA;aAGAI,yBAAAA,GAAAA,yBAAAA;QAER,IAAI,CAACL,OAAO,GAAGE,WAAAA;AACf,QAAA,IAAII,kBAAkBF,YAAAA,CAAAA,EAAe;YACnC,IAAI,CAACJ,OAAO,GAAGG,WAAAA;AACjB,QAAA;AACA,QAAA,IAAI,CAACJ,WAAW,GAAG,IA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AL,YAAAA,IAAAA;YACAa,QAAAA,EAAU,IAAI,CAAChD,WAAW,CAACkC,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;IAEA,MAAMM,iBAAAA,CAA4C,EAChDjB,GAAG,EACHC,IAAI,EACJC,MAAM,EACNgB,aAAa,EACW,EAAc;AACtC,QAAA,MAAMf,eAAe,IAAI,CAACjD,sBAAsB,CAACkD,iBAAiB,GAAGC,aAAa;AAClF,QAAA,MAAMC,eAAAA,GAAkB,QAAA,GAAWZ,MAAAA,CAAOa,IAAI,CAAC,IAAI,CAAClD,YAAY,GAAG,OAAO8C,YAAAA,IAAgB,IAAI,CAAC9C,YAAY,CAAD,CAAA;QAC1G,MAAMmD,gBAAAA,GAAmBd,OAAOa,IAAI,CAACE,KAAKC,SAAS,CAAC,IAAI,CAACtC,mBAAmB,EAAA,CAAA,CAAA;AAC5E,QAAA,MAAMuC,oBAAAA,GAAuBjB,MAAAA,CAAOC,QAAQ,CAACiB,MAAM;AAEnD,QAAA,OAAOK,iBAAAA,CAAqB;AAC1BX,YAAAA,eAAAA;AACAL,YAAAA,IAAAA;YACAa,QAAAA,EAAU,IAAI,CAAChD,WAAW,CAACkC,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA,oBAAAA;AACAO,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;AAEApD,IAAAA,WAAAA,CAAYkC,GAAW,EAAU;;AAE/B,QAAA,OAAO,GAAG,IAAI,CAAC/C,OAAO,CAAC,OAAO,EAAE+C,GAAAA,CAAAA,CAAK;AACvC,IAAA;AACF;;;;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import merge from '../../../../../_virtual/
|
|
1
|
+
import merge from '../../../../../_virtual/index4.mjs';
|
|
2
2
|
import '../../../../../node_modules/preact/compat/dist/compat.module.mjs';
|
|
3
3
|
import createTheme from '../../../../../node_modules/@mui/material/styles/createTheme.mjs';
|
|
4
4
|
import selectClasses from '../../../../../node_modules/@mui/material/Select/selectClasses.mjs';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as bs58Exports } from '../../../../_virtual/
|
|
1
|
+
import { b as bs58Exports } from '../../../../_virtual/index3.mjs';
|
|
2
2
|
import '../../../../node_modules/preact/compat/dist/compat.module.mjs';
|
|
3
3
|
import { GenericWalletIcon } from '../assets/genericWallet.mjs';
|
|
4
4
|
import { usePresentation, getButtonId } from '../ui/components/PresentationConfig.mjs';
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { version } from '../package.json.mjs';
|
|
2
1
|
import { isTestPublicToken, createPersistentId, createAppSessionId, createEventId } from '../../core/src/utils/index.mjs';
|
|
3
2
|
import { EventLogger, DEFAULT_INTERVAL_DURATION_MS, DEFAULT_MAX_BATCH_SIZE } from '../../core/src/EventLogger.mjs';
|
|
4
3
|
import { baseFetchSDK, baseSubmitFormSDK, retriableFetchSDK } from '../../core/src/NetworkClient.mjs';
|
|
@@ -64,10 +63,9 @@ class NetworkClient {
|
|
|
64
63
|
identifier: window.location.hostname
|
|
65
64
|
},
|
|
66
65
|
sdk: {
|
|
67
|
-
// TODO: Pull these from package.json when there is a package
|
|
68
66
|
// eslint-disable-next-line lingui/no-unlocalized-strings
|
|
69
67
|
identifier: 'Stytch.js Javascript SDK',
|
|
70
|
-
version:
|
|
68
|
+
version: "@stytch/vanilla-js" + '@' + "6.0.7"
|
|
71
69
|
}
|
|
72
70
|
};
|
|
73
71
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NetworkClient.mjs","sources":["../../../../../../web/src/NetworkClient.ts"],"sourcesContent":["import {\n AdditionalTelemetryData,\n baseFetchSDK,\n baseSubmitFormSDK,\n createAppSessionId,\n createEventId,\n createPersistentId,\n DEFAULT_INTERVAL_DURATION_MS,\n DEFAULT_MAX_BATCH_SIZE,\n EventLogger,\n INetworkClient,\n isTestPublicToken,\n retriableFetchSDK,\n RetriableSDKRequestInfo,\n SDKRequestInfo,\n SDKTelemetry,\n} from '@stytch/core';\nimport { ResponseCommon } from '@stytch/core/public';\n\nimport { version as PACKAGE_VERSION } from '../package.json';\nimport { B2BSubscriptionDataLayer, ConsumerSubscriptionDataLayer } from './SubscriptionService';\n\nexport class NetworkClient implements INetworkClient {\n private eventLogger: EventLogger;\n private readonly baseURL: string;\n\n constructor(\n private _publicToken: string,\n private _subscriptionDataLayer: ConsumerSubscriptionDataLayer | B2BSubscriptionDataLayer,\n _liveAPIURL: string,\n _testAPIURL: string,\n private additionalTelemetryDataFn: () => AdditionalTelemetryData,\n ) {\n this.baseURL = _liveAPIURL;\n if (isTestPublicToken(_publicToken)) {\n this.baseURL = _testAPIURL;\n }\n this.eventLogger = new EventLogger({\n maxBatchSize: DEFAULT_MAX_BATCH_SIZE,\n intervalDurationMs: DEFAULT_INTERVAL_DURATION_MS,\n logEventURL: this.buildSDKUrl('/events'),\n });\n }\n\n // @deprecated Use the new sessions.updateSession() method instead\n updateSessionToken = () => {\n return null;\n };\n\n logEvent({\n name,\n details,\n error = {},\n }: {\n name: string;\n details: Record<string, unknown>;\n error?: { error_code?: string; error_description?: string; http_status_code?: string };\n }): void {\n this.eventLogger.logEvent(this.createTelemetryBlob(), {\n public_token: this._publicToken,\n event_name: name,\n details: details,\n\n // Error fields\n error_code: error.error_code,\n error_description: error.error_description,\n http_status_code: error.http_status_code,\n });\n }\n\n createTelemetryBlob(): SDKTelemetry {\n return {\n event_id: createEventId(),\n // TODO: These should be persisted somewhere, not generated per request\n app_session_id: createAppSessionId(),\n persistent_id: createPersistentId(),\n\n client_sent_at: new Date().toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n\n // Logged in data\n // This gets passed into the constructor from StytchClient or StytchB2BClient\n // We pass in the user & session id when the Consumer SDK is being used and member & session id\n // when the B2B SDK is being used.\n\n // Why don't we generate this from the session_token in the auth header?\n // - We don't want to tie analytics ingest to session validation. There's no need to put\n // that kind of pressure on API, and ingest could be moved to somewhere that doesn't\n // have the ability to validate tokens\n // - For bulk event batches, we want to keep track of whether or not a user was logged\n // in at each event. If we have 10 events, the user logs in at event 5, then they'll have\n // a token when they log the batch, but we want to know that they were not logged in for the\n // first 4 events\n ...this.additionalTelemetryDataFn(),\n\n // Versioning\n app: {\n identifier: window.location.hostname,\n },\n sdk: {\n // TODO: Pull these from package.json when there is a package\n // eslint-disable-next-line lingui/no-unlocalized-strings\n identifier: 'Stytch.js Javascript SDK',\n version: PACKAGE_VERSION,\n },\n };\n }\n\n async fetchSDK<T extends ResponseCommon>({ url, body, method }: SDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async submitFormSDK({ url, body, method }: SDKRequestInfo): Promise<void> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseSubmitFormSDK({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async retriableFetchSDK<T extends ResponseCommon>({\n url,\n body,\n method,\n retryCallback,\n }: RetriableSDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return retriableFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n retryCallback,\n });\n }\n\n buildSDKUrl(url: string): string {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n return `${this.baseURL}/sdk/v1${url}`;\n }\n}\n"],"names":["NetworkClient","eventLogger","baseURL","_subscriptionDataLayer","_liveAPIURL","_testAPIURL","_publicToken","additionalTelemetryDataFn","isTestPublicToken","EventLogger","maxBatchSize","DEFAULT_MAX_BATCH_SIZE","intervalDurationMs","DEFAULT_INTERVAL_DURATION_MS","logEventURL","buildSDKUrl","updateSessionToken","logEvent","name","details","error","createTelemetryBlob","public_token","event_name","error_code","error_description","http_status_code","event_id","createEventId","app_session_id","createAppSessionId","persistent_id","createPersistentId","client_sent_at","Date","toISOString","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","app","identifier","window","location","hostname","sdk","version","PACKAGE_VERSION","fetchSDK","url","body","method","sessionToken","readSessionCookie","session_token","basicAuthHeader","btoa","xSDKClientHeader","JSON","stringify","xSDKParentHostHeader","origin","baseFetchSDK","finalURL","submitFormSDK","baseSubmitFormSDK","retriableFetchSDK","retryCallback"],"mappings":";;;;;AAsBO,MAAMA,aAAAA,CAAAA;;;;IACHC,WAAAA;IACSC,OAAAA;AAEjB,IAAA,WAAA,CACE,YAA4B,EACpBC,sBAAgF,EACxFC,WAAmB,EACnBC,WAAmB,EACnB,yBAAgE,CAChE;aALQC,YAAAA,GAAAA,YAAAA;aACAH,sBAAAA,GAAAA,sBAAAA;aAGAI,yBAAAA,GAAAA,yBAAAA;QAER,IAAI,CAACL,OAAO,GAAGE,WAAAA;AACf,QAAA,IAAII,kBAAkBF,YAAAA,CAAAA,EAAe;YACnC,IAAI,CAACJ,OAAO,GAAGG,WAAAA;AACjB,QAAA;AACA,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;AACAL,YAAAA,IAAAA;YACAa,QAAAA,EAAU,IAAI,CAACjD,WAAW,CAACmC,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;IAEA,MAAMM,iBAAAA,CAA4C,EAChDjB,GAAG,EACHC,IAAI,EACJC,MAAM,EACNgB,aAAa,EACW,EAAc;AACtC,QAAA,MAAMf,eAAe,IAAI,CAAClD,sBAAsB,CAACmD,iBAAiB,GAAGC,aAAa;AAClF,QAAA,MAAMC,eAAAA,GAAkB,QAAA,GAAWb,MAAAA,CAAOc,IAAI,CAAC,IAAI,CAACnD,YAAY,GAAG,OAAO+C,YAAAA,IAAgB,IAAI,CAAC/C,YAAY,CAAD,CAAA;QAC1G,MAAMoD,gBAAAA,GAAmBf,OAAOc,IAAI,CAACE,KAAKC,SAAS,CAAC,IAAI,CAACvC,mBAAmB,EAAA,CAAA,CAAA;AAC5E,QAAA,MAAMwC,oBAAAA,GAAuBlB,MAAAA,CAAOC,QAAQ,CAACkB,MAAM;AAEnD,QAAA,OAAOK,iBAAAA,CAAqB;AAC1BX,YAAAA,eAAAA;AACAL,YAAAA,IAAAA;YACAa,QAAAA,EAAU,IAAI,CAACjD,WAAW,CAACmC,GAAAA,CAAAA;AAC3BE,YAAAA,MAAAA;AACAM,YAAAA,gBAAAA;AACAG,YAAAA,oBAAAA;AACAO,YAAAA;AACF,SAAA,CAAA;AACF,IAAA;AAEArD,IAAAA,WAAAA,CAAYmC,GAAW,EAAU;;AAE/B,QAAA,OAAO,GAAG,IAAI,CAAChD,OAAO,CAAC,OAAO,EAAEgD,GAAAA,CAAAA,CAAK;AACvC,IAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"NetworkClient.mjs","sources":["../../../../../../web/src/NetworkClient.ts"],"sourcesContent":["import {\n AdditionalTelemetryData,\n baseFetchSDK,\n baseSubmitFormSDK,\n createAppSessionId,\n createEventId,\n createPersistentId,\n DEFAULT_INTERVAL_DURATION_MS,\n DEFAULT_MAX_BATCH_SIZE,\n EventLogger,\n INetworkClient,\n isTestPublicToken,\n retriableFetchSDK,\n RetriableSDKRequestInfo,\n SDKRequestInfo,\n SDKTelemetry,\n} from '@stytch/core';\nimport { ResponseCommon } from '@stytch/core/public';\n\nimport { B2BSubscriptionDataLayer, ConsumerSubscriptionDataLayer } from './SubscriptionService';\n\nexport class NetworkClient implements INetworkClient {\n private eventLogger: EventLogger;\n private readonly baseURL: string;\n\n constructor(\n private _publicToken: string,\n private _subscriptionDataLayer: ConsumerSubscriptionDataLayer | B2BSubscriptionDataLayer,\n _liveAPIURL: string,\n _testAPIURL: string,\n private additionalTelemetryDataFn: () => AdditionalTelemetryData,\n ) {\n this.baseURL = _liveAPIURL;\n if (isTestPublicToken(_publicToken)) {\n this.baseURL = _testAPIURL;\n }\n this.eventLogger = new EventLogger({\n maxBatchSize: DEFAULT_MAX_BATCH_SIZE,\n intervalDurationMs: DEFAULT_INTERVAL_DURATION_MS,\n logEventURL: this.buildSDKUrl('/events'),\n });\n }\n\n // @deprecated Use the new sessions.updateSession() method instead\n updateSessionToken = () => {\n return null;\n };\n\n logEvent({\n name,\n details,\n error = {},\n }: {\n name: string;\n details: Record<string, unknown>;\n error?: { error_code?: string; error_description?: string; http_status_code?: string };\n }): void {\n this.eventLogger.logEvent(this.createTelemetryBlob(), {\n public_token: this._publicToken,\n event_name: name,\n details: details,\n\n // Error fields\n error_code: error.error_code,\n error_description: error.error_description,\n http_status_code: error.http_status_code,\n });\n }\n\n createTelemetryBlob(): SDKTelemetry {\n return {\n event_id: createEventId(),\n // TODO: These should be persisted somewhere, not generated per request\n app_session_id: createAppSessionId(),\n persistent_id: createPersistentId(),\n\n client_sent_at: new Date().toISOString(),\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n\n // Logged in data\n // This gets passed into the constructor from StytchClient or StytchB2BClient\n // We pass in the user & session id when the Consumer SDK is being used and member & session id\n // when the B2B SDK is being used.\n\n // Why don't we generate this from the session_token in the auth header?\n // - We don't want to tie analytics ingest to session validation. There's no need to put\n // that kind of pressure on API, and ingest could be moved to somewhere that doesn't\n // have the ability to validate tokens\n // - For bulk event batches, we want to keep track of whether or not a user was logged\n // in at each event. If we have 10 events, the user logs in at event 5, then they'll have\n // a token when they log the batch, but we want to know that they were not logged in for the\n // first 4 events\n ...this.additionalTelemetryDataFn(),\n\n // Versioning\n app: {\n identifier: window.location.hostname,\n },\n sdk: {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n identifier: 'Stytch.js Javascript SDK',\n version: STYTCH_PACKAGE_NAME + '@' + STYTCH_PACKAGE_VERSION,\n },\n };\n }\n\n async fetchSDK<T extends ResponseCommon>({ url, body, method }: SDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async submitFormSDK({ url, body, method }: SDKRequestInfo): Promise<void> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return baseSubmitFormSDK({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n });\n }\n\n async retriableFetchSDK<T extends ResponseCommon>({\n url,\n body,\n method,\n retryCallback,\n }: RetriableSDKRequestInfo): Promise<T> {\n const sessionToken = this._subscriptionDataLayer.readSessionCookie().session_token;\n const basicAuthHeader = 'Basic ' + window.btoa(this._publicToken + ':' + (sessionToken || this._publicToken));\n const xSDKClientHeader = window.btoa(JSON.stringify(this.createTelemetryBlob()));\n const xSDKParentHostHeader = window.location.origin;\n\n return retriableFetchSDK<T>({\n basicAuthHeader,\n body,\n finalURL: this.buildSDKUrl(url),\n method,\n xSDKClientHeader,\n xSDKParentHostHeader,\n retryCallback,\n });\n }\n\n buildSDKUrl(url: string): string {\n // eslint-disable-next-line lingui/no-unlocalized-strings\n return `${this.baseURL}/sdk/v1${url}`;\n }\n}\n"],"names":["NetworkClient","eventLogger","baseURL","_subscriptionDataLayer","_liveAPIURL","_testAPIURL","_publicToken","additionalTelemetryDataFn","isTestPublicToken","EventLogger","maxBatchSize","DEFAULT_MAX_BATCH_SIZE","intervalDurationMs","DEFAULT_INTERVAL_DURATION_MS","logEventURL","buildSDKUrl","updateSessionToken","logEvent","name","details","error","createTelemetryBlob","public_token","event_name","error_code","error_description","http_status_code","event_id","createEventId","app_session_id","createAppSessionId","persistent_id","createPersistentId","client_sent_at","Date","toISOString","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","app","identifier","window","location","hostname","sdk","version","fetchSDK","url","body","method","sessionToken","readSessionCookie","session_token","basicAuthHeader","btoa","xSDKClientHeader","JSON","stringify","xSDKParentHostHeader","origin","baseFetchSDK","finalURL","submitFormSDK","baseSubmitFormSDK","retriableFetchSDK","retryCallback"],"mappings":";;;;AAqBO,MAAMA,aAAAA,CAAAA;;;;IACHC,WAAAA;IACSC,OAAAA;AAEjB,IAAA,WAAA,CACE,YAA4B,EACpBC,sBAAgF,EACxFC,WAAmB,EACnBC,WAAmB,EACnB,yBAAgE,CAChE;aALQC,YAAAA,GAAAA,YAAAA;aACAH,sBAAAA,GAAAA,sBAAAA;aAGAI,yBAAAA,GAAAA,yBAAAA;QAER,IAAI,CAACL,OAAO,GAAGE,WAAAA;AACf,QAAA,IAAII,kBAAkBF,YAAAA,CAAAA,EAAe;YACnC,IAAI,CAACJ,OAAO,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environments, please use the Stytch Node Library
|
|
32
|
-
https://www.npmjs.com/package/stytch.`)}}),eY="bootstrap",eJ=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class eX{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,i){this._publicToken=e,this._networkClient=t,this._dataLayer=i,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(eX.mapBootstrapData).then(e=>(this._dataLayer.setItem(eY,JSON.stringify(e)),e)).catch(e=>(em(e),eJ()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(eY);if(null===e)return eJ();try{return JSON.parse(e)}catch{return eJ()}}getAsync(){return this._bootstrapDataPromise}}class eZ{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,eb(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:i}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(i,{action:"LOGIN"})}}class eQ{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new e$(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}class e2{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,i,r,s){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=s,this.baseURL=i,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=r),this.eventLogger=new ek({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:i={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:i.error_code,error_description:i.error_description,http_status_code:i.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${eh()}`,app_session_id:`app-session-id-${eh()}`,persistent_id:`persistent-id-${eh()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"0.0.0"}}}async fetchSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return eo({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async submitFormSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return en({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async retriableFetchSDK({url:e,body:t,method:i,retryCallback:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,o="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),n=window.btoa(JSON.stringify(this.createTelemetryBlob())),a=window.location.origin;return es({basicAuthHeader:o,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:n,xSDKParentHostHeader:a,retryCallback:r})}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}function e0(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class e1{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await e1.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{ep("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let i=Array.from(t).map(e0).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:i}}}function e6(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var e3=function e(t,i){function r(e,r,s){if("u">typeof document){"number"==typeof(s=e6({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var n in s)s[n]&&(o+="; "+n,!0!==s[n]&&(o+="="+s[n].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},s=0;s<i.length;s++){var o=i[s].split("="),n=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(r[a]=t.read(n,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",e6({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,e6({},this.attributes,t))},withConverter:function(t){return e(e6({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let e5=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[i]=t.split("=");return e===i}).length>1,e4=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function e9(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,i){let r=e4(t,i);try{return e.getItem(r)}catch{return null}},setItem(t,i,r){let s=e4(t,i);try{r&&e.setItem(s,r)}catch{}},removeItem(t,i){let r=e4(t,i);try{e.removeItem(r)}catch{}}}}let e8=e9(globalThis.localStorage),e7=e9(globalThis.sessionStorage);function te(e,t){return{getItem:i=>e.getItem(t,i),setItem(i,r){e.setItem(t,i,r)},removeItem(i){e.removeItem(t,i)}}}let tt="seen_domains";class ti{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let i;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=te(e8,e),this.browserSessionStorage=te(e7,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const r=this._localStorage.getItem("");if(!r)return;try{i=JSON.parse(r)}catch{this.syncToLocalStorage();return}this.state=i}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:e3.get(this.opaqueTokenCookieName),session_jwt:e3.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return e3.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:i,session_jwt:r}=e,s=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});s.domain&&this.addSeenDomain(s.domain),e3.set(this.opaqueTokenCookieName,i,s),e3.set(this.jwtCookieName,r,s);let o=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});o.domain&&this.addSeenDomain(o.domain),e5(this.jwtCookieName)&&e3.remove(this.jwtCookieName,o),e5(this.opaqueTokenCookieName)&&e3.remove(this.opaqueTokenCookieName,o),e5(this.jwtCookieName)&&ep("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),e5(this.opaqueTokenCookieName)&&ep("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),i=ti.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});e3.set(this.istCookieName,e,i)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}removeCookies(e){let t=this.getSeenDomains(),i=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(r=>{i.forEach(i=>{let s=ti.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:r,domain:i});e.forEach(e=>{e3.remove(e,s)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(tt);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(tt,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:i,expiresAt:r}){let s={expires:new Date(r),sameSite:"lax"};return e&&(s.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?s.secure=!1:(i&&(s.domain=t||window.location.host),s.secure=!0),s}}class tr extends ti{}let ts=Symbol.for("__stytch_b2b_DataLayer"),to=(e,t)=>{Object.values(e).forEach(e=>e(t))},tn=(({KEYS_TO_EXCLUDE:e=[]}={})=>{let t=(i,r)=>typeof i==typeof r&&(null===i||null===r?i===r:"object"==typeof i?!(Object.keys(i).length!==Object.keys(r).length||Object.keys(i).some(e=>!(e in r)))&&Object.entries(i).filter(([t])=>!e.includes(t)).every(([e,i])=>t(i,r[e])):i===r);return t})({KEYS_TO_EXCLUDE:["last_accessed_at"]});class ta{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:i}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!i){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==e4(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let i=this._datalayer.state,r=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=r;let s=this.getFromCache();if(this.setCacheRefreshed(),s||!tn(i,r)){let e;e=null==r||t.fromCache?r:{...r,sessionDurationMinutes:t.sessionDurationMinutes},to(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let i=this._datalayer.state,r=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=r;let s=this.getFromCache();this.setCacheRefreshed();let o=!tn(i,r);(s||o)&&(to(this._datalayer.subscriptions,r),o&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:i}=e,r={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:i};"string"==typeof t||"string"==typeof i?(this._datalayer.writeSessionCookie(r),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let i;return t=this._datalayer.subscriptions,t[i=Math.random().toString(36).slice(-10)]=e,()=>delete t[i]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class tc extends ta{updateMember=e=>this.updateState({member:e});getMember=()=>this.getState()?.member??null;updateOrganization=e=>this.updateState({organization:e});getOrganization=()=>this.getState()?.organization??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{if("member_session"in e&&e.member_session){let i=e.session_token&&e.session_jwt?{session_token:e.session_token,session_jwt:e.session_jwt}:{session_token:!0,session_jwt:!0};this.updateStateAndTokens({state:{session:e.member_session,member:e.member,organization:e.organization},...i,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})}else this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:e.intermediate_session_token||!0},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async t=>{let i=await e(t);return this.updateSession(i,{sessionDurationMinutes:t?.session_duration_minutes}),i}}let tl=Symbol.for("stytch__internal_b2b");class td extends eD{_oneTap;constructor(e,t,i,r,s,o=ew(),n){super(e,t,i,r,s,o),this._oneTap=n}startOneTapDiscovery=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnDiscoverySuccessHandler({discoveryRedirectUrl:e.discovery_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};startOneTap=async e=>{if(!e.organization_id)throw new n("stytch.oauth.googleOneTap.start","organization_id is a required argument");let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnSuccessHandler({organizationId:e.organization_id,signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={discovery:{start:this.startOneTapDiscovery},start:this.startOneTap}}let th="u">typeof window&&"IdentityCredential"in window,tu=e=>e===Y.forceLegacyEmbedded?"force":e===Y.embeddedOnly||e===Y.embedded||e===Y.floatingOrEmbedded;class t_{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:i,cancelOnTapOutside:r=!0}){let s,o=tu(i.position),n="force"===(s=tu(i.position))||s&&!th,a={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==o,cancel_on_tap_outside:r};return n&&(a.prompt_parent_id="google-parent-prompt",a.cancel_on_tap_outside=!1),this._googleClient.initialize(a),new Promise(e=>{this._googleClient.prompt(i=>{if(i.isSkippedMoment()){let r=i.getSkippedReason?.()??"unknown_reason";return"user_cancel"===r&&t?.(),e({success:!1,reason:r})}return!i.isNotDisplayed&&n||i.isNotDisplayed?.()?e({success:!1,reason:i.getNotDisplayedReason?.()??"unknown_reason"}):i.isDismissedMoment()?void 0:(this.styleFrame(n),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEach(e=>{e.src.includes(t)&&(e.style.width="100%")})}}let tp=Promise.resolve({pkceRequiredForOAuth:!1});class tm{_networkClient;_pkceManager;_config;googleClientID;constructor(e,t,i=tp){this._networkClient=e,this._pkceManager=t,this._config=i}async fetchGoogleStart(){if(this.googleClientID)return this.googleClientID;let e=await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/start",method:"GET"});return this.googleClientID=e.google_client_id,this.googleClientID}async submitGoogleOneTapTokenDiscovery({credential:e,discoveryRedirectUrl:t}){let i,{pkceRequiredForOAuth:r}=await this._config;return r?i=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/discovery/submit",method:"POST",body:{id_token:e,discovery_redirect_url:t,pkce_code_challenge:i}})}async submitGoogleOneTapToken({credential:e,organizationId:t,signupRedirectUrl:i,loginRedirectUrl:r}){let s,{pkceRequiredForOAuth:o}=await this._config;return o?s=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/submit",method:"POST",body:{id_token:e,organization_id:t,signup_redirect_url:i,login_redirect_url:r,pkce_code_challenge:s}})}async createOneTapClient(){let e;try{e=await this.fetchGoogleStart()}catch(e){return{success:!1,reason:_.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new t_(await eb(i,()=>window.google.accounts.id),e)}}createOnDiscoverySuccessHandler=({discoveryRedirectUrl:e,onSuccess:t,onError:i})=>async r=>{let{credential:s}=r,o=this.submitGoogleOneTapTokenDiscovery({credential:s,discoveryRedirectUrl:e}).then(e=>t(e.redirect_url));i&&(o=o.catch(e=>i(e))),await o};createOnSuccessHandler=({organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i,onSuccess:r,onError:s})=>async o=>{let{credential:n}=o,a=this.submitGoogleOneTapToken({credential:n,organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i}).then(e=>r(e.redirect_url));s&&(a=a.catch(e=>s(e))),await a};redirectOnSuccess=e=>{window.location.href=e}}class tg{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;magicLinks;session;member;self;organization;oauth;sso;discovery;passwords;otps;totp;recoveryCodes;rbac;scim;impersonation;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchB2BClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchB2BClient()` instead.");(e=>{"string"!=typeof e?ep(`Public token is malformed. Expected a string, got ${typeof e}.${eg}`):""===e?ep(`Public token is malformed. Expected "public-token-...", got an empty string.${eg}`):e.startsWith("public-token-")||ep(`Public token is malformed. Expected "public-token-...", got ${e}.${eg}`)})(e);const i=e??"",r=((e,t={})=>{let{cookieOptions:i,keepSessionAlive:r}=t;return eC(e,t,{keepSessionAlive:"optionalBoolean"}),i&&eC(`${e}.cookieOptions`,i,{opaqueTokenCookieName:"optionalString",jwtCookieName:"optionalString",istCookieName:"optionalString",path:"optionalString",domain:"optionalString"}),{cookieOptions:i,keepSessionAlive:r,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"testApiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"apiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";ep(`Unable to use custom DFPPA domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";ep(`Unable to use custom DFP CDN domain \`${t}\`. ${i} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),s=((e,t={})=>{let{customBaseUrl:i,endpointOptions:r}=t;return e.includes("public-token-test")?!!(i||r?.testApiDomain):!!(i||r?.apiDomain)})(i,t);this._dataLayer=((e,t)=>{let i,r=((i=window)[ts]||(i[ts]={}),i[ts]);return r[e]||(r[e]=new tr(e,t)),r[e]})(i,r),this._subscriptionService=new tc(i,this._dataLayer,{usingCustomApiEndpoint:s}),this._stateChangeClient=new eq(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const o=()=>({stytch_member_id:this._dataLayer.state?.member?.member_id,stytch_member_session_id:this._dataLayer.state?.session?.member_session_id}),n=new e1(this._dataLayer,"passwords"),a=new e2(i,this._dataLayer,r.endpoints.liveAPIURL,r.endpoints.testAPIURL,o);this._networkClient=a;const c=new eX(i,a,this._dataLayer),l=new eZ(c.getAsync()),d=new eS(i,r.endpoints.dfpBackendURL,r.endpoints.dfpCdnURL,c.getAsync(),l.executeRecaptcha),h=new eQ(r.endpoints.clientsideServicesIframeURL),u=new e1(this._dataLayer,"oauth"),_=new tm(a,u,c.getAsync());this.organization=new eO(a,a,this._subscriptionService),this.member=new eN(a,a,this._subscriptionService),this.self=new eN(a,a,this._subscriptionService),this.session=new eM(a,this._subscriptionService),this.magicLinks=new eE(a,this._subscriptionService,new e1(this._dataLayer,"magic_links"),n,c.getAsync(),d),this.oauth=new td(a,this._subscriptionService,u,c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d,_),this.sso=new ex(a,this._subscriptionService,new e1(this._dataLayer,"sso"),c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d),this.discovery=new ev(a,this._subscriptionService),this.passwords=new eR(a,this._subscriptionService,n,c.getAsync(),d),this.otps=new eI(a,this._subscriptionService,d),this.totp=new ez(a,this._subscriptionService,d),this.recoveryCodes=new eF(a,this._subscriptionService,d),this.rbac=new eK(c.getSync(),c.getAsync(),this._subscriptionService),this.scim=new eL(this._networkClient,this._subscriptionService),this.impersonation=new eT(this._networkClient,this._subscriptionService,d),this.idp=new eP(a),this._sessionManager=new eG(this._subscriptionService,this.session,i,{keepSessionAlive:r.keepSessionAlive});const p=new ej(a,d);(s||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh();const{authenticateByUrl:m,parseAuthenticateUrl:g}=(e=>{let t=Object.keys(e),i=(e=window.location.href)=>{let i=new URL(e),r=i.searchParams.get("stytch_token_type"),s=i.searchParams.get("token");return s&&r?t.includes(r)?{handled:!0,token:s,tokenType:r}:{handled:!1,token:s,tokenType:r}:null};return{authenticateByUrl:async({clearParams:t,...r},s=window.location.href)=>{let o,n,a,c=t??s===window.location.href,l=i(s);if(null==l)return null;if(!l.handled)return l;let{token:d,tokenType:h}=l,u=e[h];return c&&((n=(o=new URL(window.location.toString())).searchParams).delete("token"),n.delete("stytch_token_type"),a=o,window.history.replaceState(null,document.title,a)),{handled:!0,tokenType:h,data:await u(d,r)}},parseAuthenticateUrl:i}})({discovery:e=>this.magicLinks.discovery.authenticate({discovery_magic_links_token:e}),discovery_oauth:e=>this.oauth.discovery.authenticate({discovery_oauth_token:e}),oauth:(e,t)=>this.oauth.authenticate({oauth_token:e,...t}),sso:(e,t)=>this.sso.authenticate({sso_token:e,...t}),multi_tenant_magic_links:(e,t)=>this.magicLinks.authenticate({magic_links_token:e,...t}),multi_tenant_impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=m,this.parseAuthenticateUrl=g,a.logEvent({name:"b2b_sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),c.getAsync().then(e=>{"CONSUMER"===e.vertical&&em("This application is using a Stytch client for B2B projects, but the public token is for a Stytch Consumer project. Use a Consumer Stytch client instead, or verify that the public token is correct.")}),((e,t)=>{Object.assign(e,{[tl]:t})})(this,{bootstrap:c,clientsideServices:h,publicToken:i,searchManager:p,dataLayer:this._dataLayer,networkClient:a,oneTap:_})}}let ty=["openid","email","profile"],tb=(...e)=>"u"<typeof window?eV("stytch"):new tg(...e);return e.AuthFlowType={Discovery:"Discovery",Organization:"Organization",PasswordReset:"PasswordReset"},e.B2BMFAProducts={smsOtp:"smsOtp",totp:"totp"},e.B2BOAuthProviders=s,e.BiometricRegistrationIdIsNullOrBlank=H,e.BiometricsAlreadyEnrolledError=class extends p{constructor(){super("BiometricsAlreadyEnrolledError","There is already a biometric factor enrolled on this device. Fully authenticate with all factors and remove the existing registration before attempting to register again.")}},e.BiometricsFailedError=U,e.BiometricsUnavailableError=b,e.ChallengeSigningFailedError=D,e.DFPNotConfigured=V,e.DeviceCredentialsNotAllowedError=v,e.FailedCodeChallengeError=I,e.FailedToDecryptDataError=R,e.IDPOAuthFlowMissingParamError=class extends p{constructor(e){super("IDPOAuthFlowMissingParamError",e)}},e.InternalError=g,e.InvalidAuthorizationCredentialError=T,e.InvalidCredentialTypeError=N,e.InvalidPrivateKeyLength=q,e.InvalidRedirectSchemeError=F,e.InvalidStartUrlError=K,e.JSONDataNotConvertibleToStringError=x,e.KeyInvalidatedError=S,e.KeystoreUnavailableError=w,e.MissingAttestationObjectError=M,e.MissingAuthorizationCredentialIDTokenError=P,e.MissingCipherIv=G,e.MissingGoogleClientIDError=class extends p{constructor(){super("MissingGoogleClientIDError","No Google client ID was found in the project.")}},e.MissingPKCEError=class extends p{constructor(){super("MissingPKCEError","Make sure this flow is completed on the same device on which it was started.")}},e.MissingPublicKeyError=E,e.MissingUrlError=L,e.NoBiometricsEnrolledError=f,e.NoBiometricsRegistrationError=y,e.NoCredentialsPresentError=A,e.NoCurrentSessionError=m,e.OAuthProviders={Google:"google",Microsoft:"microsoft",Apple:"apple",Github:"github",GitLab:"gitlab",Facebook:"facebook",Discord:"discord",Salesforce:"salesforce",Slack:"slack",Amazon:"amazon",Bitbucket:"bitbucket",LinkedIn:"linkedin",Coinbase:"coinbase",Twitch:"twitch",Twitter:"twitter",TikTok:"tiktok",Snapchat:"snapchat",Figma:"figma",Yahoo:"yahoo"},e.OTPMethods={SMS:"sms",WhatsApp:"whatsapp",Email:"email"},e.OneTapPositions=Y,e.PasskeysInvalidEncoding=$,e.PasskeysMisconfigured=j,e.PasskeysUnsupportedError=B,e.RNUIProducts=et,e.RandomNumberGenerationFailed=z,e.RedirectURLType={ResetPassword:"reset_password"},e.SDKAPIUnreachableError=o,e.SDKNotConfiguredError=O,e.SignInWithAppleMisconfigured=W,e.StytchAPIError=_,e.StytchAPISchemaError=u,e.StytchAPIUnreachableError=h,e.StytchB2BClient=tg,e.StytchB2BHeadlessClient=tg,e.StytchError=d,e.StytchEventType=ee,e.StytchSDKAPIError=c,e.StytchSDKError=p,e.StytchSDKSchemaError=a,e.StytchSDKUsageError=n,e.UNRECOVERABLE_ERROR_TYPES=l,e.UserCancellationError=k,e.UserLockedOutError=C,e.Wallets={Phantom:"Phantom",Metamask:"Metamask",Coinbase:"Coinbase",Binance:"Binance",GenericEthereumWallet:"GenericEthereumWallet",GenericSolanaWallet:"GenericSolanaWallet"},e.createStytchB2BClient=tb,e.createStytchB2BHeadlessClient=tb,e.errorToStytchError=function(e){if(e instanceof p)return e;switch(e.message){case"no_current_session":return new m;case"no_biometrics_registration":return new y;case"biometrics_unavailable":case"device_hardware_error":case"biometrics_not_available":return new b;case"key_invalidated":case"no_biometric_key":return new S;case"no_biometrics_enrolled":return new f;case"keystore_unavailable":return new w;case"device_credentials_not_allowed":return new v;case"user_cancellation":return new k;case"user_locked_out":return new C;case"google_onetap_missing_id_token":case"oauth_apple_missing_id_token":case"missing_authorization_credential_id_token":return new P;case"google_onetap_missing_member":case"oauth_apple_credential_invalid":case"invalid_authorization_credential":return new T;case"missing_public_key":return new E;case"challenge_signing_failed":return new D;case"no_credentials_present":return new A;case"sdk_not_configured":return new O;case"failed_code_challenge":return new I;case"passkeys_unsupported":return new B;case"failed_to_decrypt_data":return new R;case"biometrics_failed":return new U;case"invalid_start_url":return new K;case"invalid_redirect_scheme":return new F;case"missing_url":return new L;case"invalid_credential_type":return new N;case"missing_attestation_object":return new M;case"json_data_not_convertible_to_string":return new x;case"random_number_generation_failed":return new z;case"passkeys_invalid_encoding":return new $;case"passkeys_misconfigured":return new j;case"signinwithapple_misconfigured":return new W;case"missing_cipher_iv":return new G;case"invalid_private_key_length":return new q;case"biometric_registration_id_is_null_or_blank":return new H;case"dfp_not_configured":return new V;default:return new g(e)}},e.parseOAuthAuthorizeParams=e=>{let t={client_id:"",redirect_uri:"",response_type:"code",scopes:[...ty]};for(let i of["client_id","redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}for(let i of["response_type","scope","code_challenge","state","nonce","prompt"]){let r=e.get(i);r&&("scope"===i?t.scopes=r.split(" ").filter(Boolean):t[i]=r)}return e.has("resource")&&(t.resources=e.getAll("resource")),{error:null,result:t}},e.parseOAuthLogoutParams=e=>{let t={client_id:"",post_logout_redirect_uri:""};for(let i of["client_id","post_logout_redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}return t.id_token_hint=e.get("id_token_hint")||void 0,t.state=e.get("state")||void 0,{error:null,result:t}},e}({});
|
|
32
|
+
https://www.npmjs.com/package/stytch.`)}}),eY="bootstrap",eJ=()=>({displayWatermark:!1,projectName:null,cnameDomain:null,emailDomains:["stytch.com"],captchaSettings:{enabled:!1},pkceRequiredForEmailMagicLinks:!1,pkceRequiredForPasswordResets:!1,pkceRequiredForOAuth:!1,pkceRequiredForSso:!1,slugPattern:null,createOrganizationEnabled:!1,passwordConfig:null,runDFPProtectedAuth:!1,rbacPolicy:null,siweRequiredForCryptoWallets:!1,vertical:null});class eX{_publicToken;_networkClient;_dataLayer;_bootstrapDataPromise;constructor(e,t,i){this._publicToken=e,this._networkClient=t,this._dataLayer=i,this._bootstrapDataPromise=this._networkClient.fetchSDK({url:`/projects/bootstrap/${this._publicToken}`,method:"GET"}).then(eX.mapBootstrapData).then(e=>(this._dataLayer.setItem(eY,JSON.stringify(e)),e)).catch(e=>(em(e),eJ()))}static mapBootstrapData(e){let t=null!==e.password_config?{ludsComplexity:e.password_config.luds_complexity,ludsMinimumCount:e.password_config.luds_minimum_count}:null;return{projectName:e.project_name,displayWatermark:!e.disable_sdk_watermark,captchaSettings:e.captcha_settings,cnameDomain:e.cname_domain,emailDomains:e.email_domains,pkceRequiredForEmailMagicLinks:e.pkce_required_for_email_magic_links,pkceRequiredForPasswordResets:e.pkce_required_for_password_resets,pkceRequiredForOAuth:e.pkce_required_for_oauth,pkceRequiredForSso:e.pkce_required_for_sso,slugPattern:e.slug_pattern,createOrganizationEnabled:e.create_organization_enabled,passwordConfig:t,runDFPProtectedAuth:e.dfp_protected_auth_enabled??!1,dfpProtectedAuthMode:e.dfp_protected_auth_mode,rbacPolicy:e.rbac_policy??null,siweRequiredForCryptoWallets:e.siwe_required_for_crypto_wallets,vertical:e.vertical}}getSync(){let e=this._dataLayer.getItem(eY);if(null===e)return eJ();try{return JSON.parse(e)}catch{return eJ()}}getAsync(){return this._bootstrapDataPromise}}class eZ{bootstrapPromise;state;constructor(e){this.bootstrapPromise=e,this.state=e.then(async e=>{let t;return e.captchaSettings.enabled?{configured:!0,captchaClient:await (t=e.captchaSettings.siteKey,eb(`https://www.google.com/recaptcha/enterprise.js?render=${t}`,()=>window.grecaptcha.enterprise)),siteKey:e.captchaSettings.siteKey}:{configured:!1}})}executeRecaptcha=async()=>{let{captchaClient:e,configured:t,siteKey:i}=await this.state;if(t)return await new Promise(t=>e.ready(t)),e.execute(i,{action:"LOGIN"})}}class eQ{iframeURL;_frameClient;constructor(e){this.iframeURL=e}get frameClient(){return this._frameClient=this._frameClient??new e$(this.iframeURL),this._frameClient}call(e,t){return this.frameClient.call(e,[t])}oneTapStart=e=>this.call("oneTapStart",e);oneTapSubmit=e=>this.call("oneTapSubmit",e);parsedPhoneNumber=e=>this.call("parsedPhoneNumber",e);getExamplePhoneNumber=e=>this.call("getExamplePhoneNumber",e)}class e2{_publicToken;_subscriptionDataLayer;additionalTelemetryDataFn;eventLogger;baseURL;constructor(e,t,i,r,s){this._publicToken=e,this._subscriptionDataLayer=t,this.additionalTelemetryDataFn=s,this.baseURL=i,(e=>e.includes("public-token-test"))(e)&&(this.baseURL=r),this.eventLogger=new ek({maxBatchSize:15,intervalDurationMs:800,logEventURL:this.buildSDKUrl("/events")})}updateSessionToken=()=>null;logEvent({name:e,details:t,error:i={}}){this.eventLogger.logEvent(this.createTelemetryBlob(),{public_token:this._publicToken,event_name:e,details:t,error_code:i.error_code,error_description:i.error_description,http_status_code:i.http_status_code})}createTelemetryBlob(){return{event_id:`event-id-${eh()}`,app_session_id:`app-session-id-${eh()}`,persistent_id:`persistent-id-${eh()}`,client_sent_at:new Date().toISOString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,...this.additionalTelemetryDataFn(),app:{identifier:window.location.hostname},sdk:{identifier:"Stytch.js Javascript SDK",version:"@stytch/vanilla-js@6.0.7"}}}async fetchSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return eo({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async submitFormSDK({url:e,body:t,method:i}){let r=this._subscriptionDataLayer.readSessionCookie().session_token,s="Basic "+window.btoa(this._publicToken+":"+(r||this._publicToken)),o=window.btoa(JSON.stringify(this.createTelemetryBlob())),n=window.location.origin;return en({basicAuthHeader:s,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:o,xSDKParentHostHeader:n})}async retriableFetchSDK({url:e,body:t,method:i,retryCallback:r}){let s=this._subscriptionDataLayer.readSessionCookie().session_token,o="Basic "+window.btoa(this._publicToken+":"+(s||this._publicToken)),n=window.btoa(JSON.stringify(this.createTelemetryBlob())),a=window.location.origin;return es({basicAuthHeader:o,body:t,finalURL:this.buildSDKUrl(e),method:i,xSDKClientHeader:n,xSDKParentHostHeader:a,retryCallback:r})}buildSDKUrl(e){return`${this.baseURL}/sdk/v1${e}`}}function e0(e){let t=e.toString(16);return 1===t.length&&(t="0"+t),t}class e1{_dataLayer;namespace;constructor(e,t){this._dataLayer=e,this.namespace=t}key(){return`PKCE_VERIFIER:${this.namespace}`}async startPKCETransaction(){let e=await e1.createProofkeyPair();return this._dataLayer.setItem(this.key(),JSON.stringify(e)),e}getPKPair(){let e=this._dataLayer.getItem(this.key());if(null!==e)try{return JSON.parse(e)}catch{ep("Found malformed Proof Key pair in localstorage.");return}}clearPKPair(){return this._dataLayer.removeItem(this.key())}static async createProofkeyPair(){var e;let t=new Uint32Array(16);window.crypto.getRandomValues(t);let i=Array.from(t).map(e0).join("");return{code_challenge:(e=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(i)),btoa(String.fromCharCode.call(null,...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),code_verifier:i}}}function e6(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var e3=function e(t,i){function r(e,r,s){if("u">typeof document){"number"==typeof(s=e6({},i,s)).expires&&(s.expires=new Date(Date.now()+864e5*s.expires)),s.expires&&(s.expires=s.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var n in s)s[n]&&(o+="; "+n,!0!==s[n]&&(o+="="+s[n].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},s=0;s<i.length;s++){var o=i[s].split("="),n=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(r[a]=t.read(n,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",e6({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,e6({},this.attributes,t))},withConverter:function(t){return e(e6({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});let e5=e=>(document.cookie?document.cookie.split("; "):[]).filter(t=>{let[i]=t.split("=");return e===i}).length>1,e4=(e,t)=>`stytch_sdk_state_${e}${t?`::${t}`:""}`;function e9(e){return null==e?{getItem:()=>null,removeItem(){},setItem(){}}:{getItem(t,i){let r=e4(t,i);try{return e.getItem(r)}catch{return null}},setItem(t,i,r){let s=e4(t,i);try{r&&e.setItem(s,r)}catch{}},removeItem(t,i){let r=e4(t,i);try{e.removeItem(r)}catch{}}}}let e8=e9(globalThis.localStorage),e7=e9(globalThis.sessionStorage);function te(e,t){return{getItem:i=>e.getItem(t,i),setItem(i,r){e.setItem(t,i,r)},removeItem(i){e.removeItem(t,i)}}}let tt="seen_domains";class ti{publicToken;state;_opaqueTokenCookieName=null;_jwtCookieName=null;_cookiePath=null;_domain=null;_cookieAvailableToSubdomains=!1;_istCookieName=null;subscriptions;_localStorage;browserSessionStorage;constructor(e,t){let i;this.publicToken=e,this.state=null,this.subscriptions={},this._localStorage=te(e8,e),this.browserSessionStorage=te(e7,e),t?.cookieOptions&&(this._opaqueTokenCookieName=t.cookieOptions.opaqueTokenCookieName||null,this._jwtCookieName=t.cookieOptions.jwtCookieName||null,this._cookiePath=t.cookieOptions.path||null,this._domain=t.cookieOptions.domain||null,this._cookieAvailableToSubdomains=t.cookieOptions.availableToSubdomains||!1,this._istCookieName=t.cookieOptions.istCookieName||null);const r=this._localStorage.getItem("");if(!r)return;try{i=JSON.parse(r)}catch{this.syncToLocalStorage();return}this.state=i}get opaqueTokenCookieName(){return this._opaqueTokenCookieName??"stytch_session"}get jwtCookieName(){return this._jwtCookieName??"stytch_session_jwt"}get istCookieName(){return this._istCookieName??"stytch_intermediate_session_token"}readSessionCookie(){return{session_token:e3.get(this.opaqueTokenCookieName),session_jwt:e3.get(this.jwtCookieName)}}readIntermediateSessionTokenCookie(){return e3.get(this.istCookieName)}writeSessionCookie(e){let{state:t,session_token:i,session_jwt:r}=e,s=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});s.domain&&this.addSeenDomain(s.domain),e3.set(this.opaqueTokenCookieName,i,s),e3.set(this.jwtCookieName,r,s);let o=ti.generateCookieOpts({expiresAt:t?.session?.expires_at??"",availableToSubdomains:!this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});o.domain&&this.addSeenDomain(o.domain),e5(this.jwtCookieName)&&e3.remove(this.jwtCookieName,o),e5(this.opaqueTokenCookieName)&&e3.remove(this.opaqueTokenCookieName,o),e5(this.jwtCookieName)&&ep("Could not remove extraneous JWT cookie. This might happen if the cookie has been set using multiple `path` settings, and may produce unwanted behavior."),e5(this.opaqueTokenCookieName)&&ep("Could not remove extraneous opaque token cookie.")}writeIntermediateSessionTokenCookie(e){let t=new Date(Date.now()+6e5),i=ti.generateCookieOpts({expiresAt:t.toString(),availableToSubdomains:this._cookieAvailableToSubdomains,path:this._cookiePath,domain:this._domain});e3.set(this.istCookieName,e,i)}removeSessionCookie(){this.removeCookies([this.opaqueTokenCookieName,this.jwtCookieName])}removeISTCookie(){this.removeCookies([this.istCookieName])}removeCookies(e){let t=this.getSeenDomains(),i=[...new Set([this._domain,null,...t])];[!0,!1].forEach(t=>{[this._cookiePath,null].forEach(r=>{i.forEach(i=>{let s=ti.generateCookieOpts({expiresAt:new Date(0).toString(),availableToSubdomains:t,path:r,domain:i});e.forEach(e=>{e3.remove(e,s)})})})})}syncToLocalStorage(){this._localStorage.setItem("",JSON.stringify(this.state))}getItem(e){return this._localStorage.getItem(e)}setItem(e,t){this._localStorage.setItem(e,t)}removeItem(e){this._localStorage.removeItem(e)}getSeenDomains(){let e=this.getItem(tt);if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}addSeenDomain(e){if(!e)return;let t=this.getSeenDomains();t.includes(e)||(t.push(e),this.setItem(tt,JSON.stringify(t)))}static generateCookieOpts({path:e,domain:t,availableToSubdomains:i,expiresAt:r}){let s={expires:new Date(r),sameSite:"lax"};return e&&(s.path=e),"localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)?s.secure=!1:(i&&(s.domain=t||window.location.host),s.secure=!0),s}}class tr extends ti{}let ts=Symbol.for("__stytch_b2b_DataLayer"),to=(e,t)=>{Object.values(e).forEach(e=>e(t))},tn=(({KEYS_TO_EXCLUDE:e=[]}={})=>{let t=(i,r)=>typeof i==typeof r&&(null===i||null===r?i===r:"object"==typeof i?!(Object.keys(i).length!==Object.keys(r).length||Object.keys(i).some(e=>!(e in r)))&&Object.entries(i).filter(([t])=>!e.includes(t)).every(([e,i])=>t(i,r[e])):i===r);return t})({KEYS_TO_EXCLUDE:["last_accessed_at"]});class ta{_publicToken;_datalayer;fromCache=!0;constructor(e,t,{usingCustomApiEndpoint:i}){if(this._publicToken=e,this._datalayer=t,window.addEventListener("storage",this._listen),!i){const{session_token:e}=this._datalayer.readSessionCookie();if(!e)return void this.destroySession()}}_listen=e=>{if(e.key!==e4(this._publicToken,""))return;let t=null===e.newValue||"null"===e.newValue?null:JSON.parse(e.newValue);this.updateState(t,!0)};getTokens(){let{session_token:e,session_jwt:t}=this._datalayer.readSessionCookie();return"string"!=typeof e||"string"!=typeof t?null:{session_token:e,session_jwt:t}}getIntermediateSessionToken(){return this._datalayer.readIntermediateSessionTokenCookie()||null}destroyState(){this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:null})}destroySession(){this._datalayer.removeSessionCookie(),this.updateState(null)}_updateStateAndTokensInternal(e,t){let i=this._datalayer.state,r=null===e.state?null:{...this._datalayer.state,...e.state};this._datalayer.state=r;let s=this.getFromCache();if(this.setCacheRefreshed(),s||!tn(i,r)){let e;e=null==r||t.fromCache?r:{...r,sessionDurationMinutes:t.sessionDurationMinutes},to(this._datalayer.subscriptions,e)}}updateStateAndTokens(e,t={fromCache:!1}){e.state?("string"==typeof e.session_token?this._datalayer.writeSessionCookie(e):this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()):e.intermediate_session_token?("string"==typeof e.intermediate_session_token?this._datalayer.writeIntermediateSessionTokenCookie(e.intermediate_session_token):this._datalayer.removeISTCookie(),this._datalayer.removeSessionCookie()):(this._datalayer.removeSessionCookie(),this._datalayer.removeISTCookie()),this._updateStateAndTokensInternal(e,t),this._datalayer.syncToLocalStorage()}updateState(e,t=!1){let i=this._datalayer.state,r=null===e?null:{...this._datalayer.state,...e};this._datalayer.state=r;let s=this.getFromCache();this.setCacheRefreshed();let o=!tn(i,r);(s||o)&&(to(this._datalayer.subscriptions,r),o&&!t&&this._datalayer.syncToLocalStorage())}updateTokens(e){let{session_token:t,session_jwt:i}=e,r={...this._datalayer.readSessionCookie(),session_token:t,session_jwt:i};"string"==typeof t||"string"==typeof i?(this._datalayer.writeSessionCookie(r),this._datalayer.removeISTCookie()):this._datalayer.removeSessionCookie()}subscribeToState(e){var t;let i;return t=this._datalayer.subscriptions,t[i=Math.random().toString(36).slice(-10)]=e,()=>delete t[i]}getState(){return this._datalayer.state}destroy(){window.removeEventListener("storage",this._listen)}syncFromDeviceStorage(){return null}getFromCache(){return this.fromCache}setCacheRefreshed(){this.fromCache=!1}}class tc extends ta{updateMember=e=>this.updateState({member:e});getMember=()=>this.getState()?.member??null;updateOrganization=e=>this.updateState({organization:e});getOrganization=()=>this.getState()?.organization??null;getSession=()=>this.getState()?.session??null;updateSession=(e,t)=>{if("member_session"in e&&e.member_session){let i=e.session_token&&e.session_jwt?{session_token:e.session_token,session_jwt:e.session_jwt}:{session_token:!0,session_jwt:!0};this.updateStateAndTokens({state:{session:e.member_session,member:e.member,organization:e.organization},...i,intermediate_session_token:null},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})}else this.updateStateAndTokens({state:null,session_token:null,session_jwt:null,intermediate_session_token:e.intermediate_session_token||!0},{fromCache:!1,sessionDurationMinutes:t?.sessionDurationMinutes})};withUpdateSession=e=>async t=>{let i=await e(t);return this.updateSession(i,{sessionDurationMinutes:t?.session_duration_minutes}),i}}let tl=Symbol.for("stytch__internal_b2b");class td extends eD{_oneTap;constructor(e,t,i,r,s,o=ew(),n){super(e,t,i,r,s,o),this._oneTap=n}startOneTapDiscovery=async e=>{let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnDiscoverySuccessHandler({discoveryRedirectUrl:e.discovery_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};startOneTap=async e=>{if(!e.organization_id)throw new n("stytch.oauth.googleOneTap.start","organization_id is a required argument");let t=await this._oneTap.createOneTapClient();if(!t.success)throw Error(`One Tap could not load: ${t.reason}`);let{client:i}=t,r=this._oneTap.createOnSuccessHandler({organizationId:e.organization_id,signupRedirectUrl:e.signup_redirect_url,loginRedirectUrl:e.login_redirect_url,onSuccess:this._oneTap.redirectOnSuccess});return i.render({style:{position:Y.floating},callback:r,cancelOnTapOutside:e.cancel_on_tap_outside})};googleOneTap={discovery:{start:this.startOneTapDiscovery},start:this.startOneTap}}let th="u">typeof window&&"IdentityCredential"in window,tu=e=>e===Y.forceLegacyEmbedded?"force":e===Y.embeddedOnly||e===Y.embedded||e===Y.floatingOrEmbedded;class t_{_googleClient;_clientId;constructor(e,t){this._googleClient=e,this._clientId=t}cancel(){this._googleClient.cancel()}async render({callback:e,onOneTapCancelled:t,style:i,cancelOnTapOutside:r=!0}){let s,o=tu(i.position),n="force"===(s=tu(i.position))||s&&!th,a={client_id:this._clientId,callback:e,auto_select:!1,context:"use",itp_support:!0,use_fedcm_for_prompt:"force"!==o,cancel_on_tap_outside:r};return n&&(a.prompt_parent_id="google-parent-prompt",a.cancel_on_tap_outside=!1),this._googleClient.initialize(a),new Promise(e=>{this._googleClient.prompt(i=>{if(i.isSkippedMoment()){let r=i.getSkippedReason?.()??"unknown_reason";return"user_cancel"===r&&t?.(),e({success:!1,reason:r})}return!i.isNotDisplayed&&n||i.isNotDisplayed?.()?e({success:!1,reason:i.getNotDisplayedReason?.()??"unknown_reason"}):i.isDismissedMoment()?void 0:(this.styleFrame(n),e({success:!0}))})})}styleFrame(e){e&&Array.from(document.getElementsByTagName("iframe")).forEach(e=>{e.src.includes(t)&&(e.style.width="100%")})}}let tp=Promise.resolve({pkceRequiredForOAuth:!1});class tm{_networkClient;_pkceManager;_config;googleClientID;constructor(e,t,i=tp){this._networkClient=e,this._pkceManager=t,this._config=i}async fetchGoogleStart(){if(this.googleClientID)return this.googleClientID;let e=await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/start",method:"GET"});return this.googleClientID=e.google_client_id,this.googleClientID}async submitGoogleOneTapTokenDiscovery({credential:e,discoveryRedirectUrl:t}){let i,{pkceRequiredForOAuth:r}=await this._config;return r?i=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/discovery/submit",method:"POST",body:{id_token:e,discovery_redirect_url:t,pkce_code_challenge:i}})}async submitGoogleOneTapToken({credential:e,organizationId:t,signupRedirectUrl:i,loginRedirectUrl:r}){let s,{pkceRequiredForOAuth:o}=await this._config;return o?s=(await this._pkceManager.startPKCETransaction()).code_challenge:this._pkceManager.clearPKPair(),await this._networkClient.fetchSDK({url:"/b2b/oauth/google/onetap/submit",method:"POST",body:{id_token:e,organization_id:t,signup_redirect_url:i,login_redirect_url:r,pkce_code_challenge:s}})}async createOneTapClient(){let e;try{e=await this.fetchGoogleStart()}catch(e){return{success:!1,reason:_.from(e).error_type}}return""===e?{success:!1,reason:"oauth_config_not_found"}:{success:!0,client:new t_(await eb(i,()=>window.google.accounts.id),e)}}createOnDiscoverySuccessHandler=({discoveryRedirectUrl:e,onSuccess:t,onError:i})=>async r=>{let{credential:s}=r,o=this.submitGoogleOneTapTokenDiscovery({credential:s,discoveryRedirectUrl:e}).then(e=>t(e.redirect_url));i&&(o=o.catch(e=>i(e))),await o};createOnSuccessHandler=({organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i,onSuccess:r,onError:s})=>async o=>{let{credential:n}=o,a=this.submitGoogleOneTapToken({credential:n,organizationId:e,signupRedirectUrl:t,loginRedirectUrl:i}).then(e=>r(e.redirect_url));s&&(a=a.catch(e=>s(e))),await a};redirectOnSuccess=e=>{window.location.href=e}}class tg{_subscriptionService;_sessionManager;_networkClient;_dataLayer;_stateChangeClient;magicLinks;session;member;self;organization;oauth;sso;discovery;passwords;otps;totp;recoveryCodes;rbac;scim;impersonation;idp;onStateChange;parseAuthenticateUrl;authenticateByUrl;constructor(e,t){if("u"<typeof window)throw Error("`new StytchB2BClient()` is not supported in server environments. If using @stytch/react or @stytch/nextjs, use `createStytchB2BClient()` instead.");(e=>{"string"!=typeof e?ep(`Public token is malformed. Expected a string, got ${typeof e}.${eg}`):""===e?ep(`Public token is malformed. Expected "public-token-...", got an empty string.${eg}`):e.startsWith("public-token-")||ep(`Public token is malformed. Expected "public-token-...", got ${e}.${eg}`)})(e);const i=e??"",r=((e,t={})=>{let{cookieOptions:i,keepSessionAlive:r}=t;return eC(e,t,{keepSessionAlive:"optionalBoolean"}),i&&eC(`${e}.cookieOptions`,i,{opaqueTokenCookieName:"optionalString",jwtCookieName:"optionalString",istCookieName:"optionalString",path:"optionalString",domain:"optionalString"}),{cookieOptions:i,keepSessionAlive:r,endpoints:{testAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.testApiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"testApiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.testAPIURL??"https://test.stytch.com"})(t),liveAPIURL:(e=>{let t=e?.customBaseUrl??e?.endpointOptions?.apiDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.customBaseUrl?"customBaseUrl":"apiDomain";ep(`Unable to use custom API domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.liveAPIURL??"https://api.stytch.com"})(t),dfpBackendURL:(e=>{let t=e?.dfppaUrl??e?.endpointOptions?.dfppaDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfppaUrl?"dfppaUrl":"dfppaDomain";ep(`Unable to use custom DFPPA domain \`${t}\`. ${i} should be a valid domain.`)}}return e?.endpoints?.dfpBackendURL??"https://telemetry.stytch.com"})(t),dfpCdnURL:(e=>{let t=e?.dfpCdnUrl??e?.endpointOptions?.dfpCdnDomain;if(t){let i=eu(t);if(i)return i;{let i=e?.dfpCdnUrl?"dfpCdnUrl":"dfpCdnDomain";ep(`Unable to use custom DFP CDN domain \`${t}\`. ${i} should be a valid domain.`)}}return"https://elements.stytch.com"})(t),clientsideServicesIframeURL:t?.endpoints?.clientsideServicesIframeURL??"https://js.stytch.com/clientside-services/index.html"}}})(this.constructor.name,t),s=((e,t={})=>{let{customBaseUrl:i,endpointOptions:r}=t;return e.includes("public-token-test")?!!(i||r?.testApiDomain):!!(i||r?.apiDomain)})(i,t);this._dataLayer=((e,t)=>{let i,r=((i=window)[ts]||(i[ts]={}),i[ts]);return r[e]||(r[e]=new tr(e,t)),r[e]})(i,r),this._subscriptionService=new tc(i,this._dataLayer,{usingCustomApiEndpoint:s}),this._stateChangeClient=new eq(this._subscriptionService,{}),this.onStateChange=(...e)=>this._stateChangeClient.onStateChange(...e);const o=()=>({stytch_member_id:this._dataLayer.state?.member?.member_id,stytch_member_session_id:this._dataLayer.state?.session?.member_session_id}),n=new e1(this._dataLayer,"passwords"),a=new e2(i,this._dataLayer,r.endpoints.liveAPIURL,r.endpoints.testAPIURL,o);this._networkClient=a;const c=new eX(i,a,this._dataLayer),l=new eZ(c.getAsync()),d=new eS(i,r.endpoints.dfpBackendURL,r.endpoints.dfpCdnURL,c.getAsync(),l.executeRecaptcha),h=new eQ(r.endpoints.clientsideServicesIframeURL),u=new e1(this._dataLayer,"oauth"),_=new tm(a,u,c.getAsync());this.organization=new eO(a,a,this._subscriptionService),this.member=new eN(a,a,this._subscriptionService),this.self=new eN(a,a,this._subscriptionService),this.session=new eM(a,this._subscriptionService),this.magicLinks=new eE(a,this._subscriptionService,new e1(this._dataLayer,"magic_links"),n,c.getAsync(),d),this.oauth=new td(a,this._subscriptionService,u,c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d,_),this.sso=new ex(a,this._subscriptionService,new e1(this._dataLayer,"sso"),c.getAsync(),{publicToken:i,testAPIURL:r.endpoints.testAPIURL,liveAPIURL:r.endpoints.liveAPIURL},d),this.discovery=new ev(a,this._subscriptionService),this.passwords=new eR(a,this._subscriptionService,n,c.getAsync(),d),this.otps=new eI(a,this._subscriptionService,d),this.totp=new ez(a,this._subscriptionService,d),this.recoveryCodes=new eF(a,this._subscriptionService,d),this.rbac=new eK(c.getSync(),c.getAsync(),this._subscriptionService),this.scim=new eL(this._networkClient,this._subscriptionService),this.impersonation=new eT(this._networkClient,this._subscriptionService,d),this.idp=new eP(a),this._sessionManager=new eG(this._subscriptionService,this.session,i,{keepSessionAlive:r.keepSessionAlive});const p=new ej(a,d);(s||this._dataLayer.readSessionCookie().session_token)&&this._sessionManager.performBackgroundRefresh();const{authenticateByUrl:m,parseAuthenticateUrl:g}=(e=>{let t=Object.keys(e),i=(e=window.location.href)=>{let i=new URL(e),r=i.searchParams.get("stytch_token_type"),s=i.searchParams.get("token");return s&&r?t.includes(r)?{handled:!0,token:s,tokenType:r}:{handled:!1,token:s,tokenType:r}:null};return{authenticateByUrl:async({clearParams:t,...r},s=window.location.href)=>{let o,n,a,c=t??s===window.location.href,l=i(s);if(null==l)return null;if(!l.handled)return l;let{token:d,tokenType:h}=l,u=e[h];return c&&((n=(o=new URL(window.location.toString())).searchParams).delete("token"),n.delete("stytch_token_type"),a=o,window.history.replaceState(null,document.title,a)),{handled:!0,tokenType:h,data:await u(d,r)}},parseAuthenticateUrl:i}})({discovery:e=>this.magicLinks.discovery.authenticate({discovery_magic_links_token:e}),discovery_oauth:e=>this.oauth.discovery.authenticate({discovery_oauth_token:e}),oauth:(e,t)=>this.oauth.authenticate({oauth_token:e,...t}),sso:(e,t)=>this.sso.authenticate({sso_token:e,...t}),multi_tenant_magic_links:(e,t)=>this.magicLinks.authenticate({magic_links_token:e,...t}),multi_tenant_impersonation:e=>this.impersonation.authenticate({impersonation_token:e})});this.authenticateByUrl=m,this.parseAuthenticateUrl=g,a.logEvent({name:"b2b_sdk_instance_instantiated",details:{event_callback_registered:!1,error_callback_registered:!1,success_callback_registered:!1}}),c.getAsync().then(e=>{"CONSUMER"===e.vertical&&em("This application is using a Stytch client for B2B projects, but the public token is for a Stytch Consumer project. Use a Consumer Stytch client instead, or verify that the public token is correct.")}),((e,t)=>{Object.assign(e,{[tl]:t})})(this,{bootstrap:c,clientsideServices:h,publicToken:i,searchManager:p,dataLayer:this._dataLayer,networkClient:a,oneTap:_})}}let ty=["openid","email","profile"],tb=(...e)=>"u"<typeof window?eV("stytch"):new tg(...e);return e.AuthFlowType={Discovery:"Discovery",Organization:"Organization",PasswordReset:"PasswordReset"},e.B2BMFAProducts={smsOtp:"smsOtp",totp:"totp"},e.B2BOAuthProviders=s,e.BiometricRegistrationIdIsNullOrBlank=H,e.BiometricsAlreadyEnrolledError=class extends p{constructor(){super("BiometricsAlreadyEnrolledError","There is already a biometric factor enrolled on this device. Fully authenticate with all factors and remove the existing registration before attempting to register again.")}},e.BiometricsFailedError=U,e.BiometricsUnavailableError=b,e.ChallengeSigningFailedError=D,e.DFPNotConfigured=V,e.DeviceCredentialsNotAllowedError=v,e.FailedCodeChallengeError=I,e.FailedToDecryptDataError=R,e.IDPOAuthFlowMissingParamError=class extends p{constructor(e){super("IDPOAuthFlowMissingParamError",e)}},e.InternalError=g,e.InvalidAuthorizationCredentialError=T,e.InvalidCredentialTypeError=N,e.InvalidPrivateKeyLength=q,e.InvalidRedirectSchemeError=F,e.InvalidStartUrlError=K,e.JSONDataNotConvertibleToStringError=x,e.KeyInvalidatedError=S,e.KeystoreUnavailableError=w,e.MissingAttestationObjectError=M,e.MissingAuthorizationCredentialIDTokenError=P,e.MissingCipherIv=G,e.MissingGoogleClientIDError=class extends p{constructor(){super("MissingGoogleClientIDError","No Google client ID was found in the project.")}},e.MissingPKCEError=class extends p{constructor(){super("MissingPKCEError","Make sure this flow is completed on the same device on which it was started.")}},e.MissingPublicKeyError=E,e.MissingUrlError=L,e.NoBiometricsEnrolledError=f,e.NoBiometricsRegistrationError=y,e.NoCredentialsPresentError=A,e.NoCurrentSessionError=m,e.OAuthProviders={Google:"google",Microsoft:"microsoft",Apple:"apple",Github:"github",GitLab:"gitlab",Facebook:"facebook",Discord:"discord",Salesforce:"salesforce",Slack:"slack",Amazon:"amazon",Bitbucket:"bitbucket",LinkedIn:"linkedin",Coinbase:"coinbase",Twitch:"twitch",Twitter:"twitter",TikTok:"tiktok",Snapchat:"snapchat",Figma:"figma",Yahoo:"yahoo"},e.OTPMethods={SMS:"sms",WhatsApp:"whatsapp",Email:"email"},e.OneTapPositions=Y,e.PasskeysInvalidEncoding=$,e.PasskeysMisconfigured=j,e.PasskeysUnsupportedError=B,e.RNUIProducts=et,e.RandomNumberGenerationFailed=z,e.RedirectURLType={ResetPassword:"reset_password"},e.SDKAPIUnreachableError=o,e.SDKNotConfiguredError=O,e.SignInWithAppleMisconfigured=W,e.StytchAPIError=_,e.StytchAPISchemaError=u,e.StytchAPIUnreachableError=h,e.StytchB2BClient=tg,e.StytchB2BHeadlessClient=tg,e.StytchError=d,e.StytchEventType=ee,e.StytchSDKAPIError=c,e.StytchSDKError=p,e.StytchSDKSchemaError=a,e.StytchSDKUsageError=n,e.UNRECOVERABLE_ERROR_TYPES=l,e.UserCancellationError=k,e.UserLockedOutError=C,e.Wallets={Phantom:"Phantom",Metamask:"Metamask",Coinbase:"Coinbase",Binance:"Binance",GenericEthereumWallet:"GenericEthereumWallet",GenericSolanaWallet:"GenericSolanaWallet"},e.createStytchB2BClient=tb,e.createStytchB2BHeadlessClient=tb,e.errorToStytchError=function(e){if(e instanceof p)return e;switch(e.message){case"no_current_session":return new m;case"no_biometrics_registration":return new y;case"biometrics_unavailable":case"device_hardware_error":case"biometrics_not_available":return new b;case"key_invalidated":case"no_biometric_key":return new S;case"no_biometrics_enrolled":return new f;case"keystore_unavailable":return new w;case"device_credentials_not_allowed":return new v;case"user_cancellation":return new k;case"user_locked_out":return new C;case"google_onetap_missing_id_token":case"oauth_apple_missing_id_token":case"missing_authorization_credential_id_token":return new P;case"google_onetap_missing_member":case"oauth_apple_credential_invalid":case"invalid_authorization_credential":return new T;case"missing_public_key":return new E;case"challenge_signing_failed":return new D;case"no_credentials_present":return new A;case"sdk_not_configured":return new O;case"failed_code_challenge":return new I;case"passkeys_unsupported":return new B;case"failed_to_decrypt_data":return new R;case"biometrics_failed":return new U;case"invalid_start_url":return new K;case"invalid_redirect_scheme":return new F;case"missing_url":return new L;case"invalid_credential_type":return new N;case"missing_attestation_object":return new M;case"json_data_not_convertible_to_string":return new x;case"random_number_generation_failed":return new z;case"passkeys_invalid_encoding":return new $;case"passkeys_misconfigured":return new j;case"signinwithapple_misconfigured":return new W;case"missing_cipher_iv":return new G;case"invalid_private_key_length":return new q;case"biometric_registration_id_is_null_or_blank":return new H;case"dfp_not_configured":return new V;default:return new g(e)}},e.parseOAuthAuthorizeParams=e=>{let t={client_id:"",redirect_uri:"",response_type:"code",scopes:[...ty]};for(let i of["client_id","redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}for(let i of["response_type","scope","code_challenge","state","nonce","prompt"]){let r=e.get(i);r&&("scope"===i?t.scopes=r.split(" ").filter(Boolean):t[i]=r)}return e.has("resource")&&(t.resources=e.getAll("resource")),{error:null,result:t}},e.parseOAuthLogoutParams=e=>{let t={client_id:"",post_logout_redirect_uri:""};for(let i of["client_id","post_logout_redirect_uri"]){let r=e.get(i);if(!r)return{error:`Required parameter is missing: ${i}. Please reach out to the application developer.`,result:t};t[i]=r}return t.id_token_hint=e.get("id_token_hint")||void 0,t.state=e.get("state")||void 0,{error:null,result:t}},e}({});
|
|
33
33
|
//# sourceMappingURL=index.headless.js.map
|