@teamhanko/hanko-frontend-sdk 1.4.0 → 1.5.0
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/README.md +8 -11
- package/dist/Hanko.d.ts +8 -3
- package/dist/lib/Dto.d.ts +38 -0
- package/dist/lib/client/HttpClient.d.ts +1 -2
- package/dist/lib/client/SessionClient.d.ts +12 -1
- package/dist/lib/events/CustomEvents.d.ts +4 -3
- package/dist/lib/events/Dispatcher.d.ts +0 -15
- package/dist/lib/events/Relay.d.ts +44 -39
- package/dist/lib/events/Scheduler.d.ts +51 -24
- package/dist/lib/events/SessionChannel.d.ts +61 -0
- package/dist/lib/events/SessionState.d.ts +38 -0
- package/dist/lib/events/WindowActivityManager.d.ts +36 -0
- package/dist/lib/flow-api/types/payload.d.ts +2 -0
- package/dist/lib/state/State.d.ts +0 -3
- package/dist/sdk.cjs +1 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.modern.js +1 -1
- package/dist/sdk.modern.js.map +1 -1
- package/dist/sdk.module.js +1 -1
- package/dist/sdk.module.js.map +1 -1
- package/dist/sdk.umd.js +1 -1
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/lib/Session.d.ts +0 -61
- package/dist/lib/state/session/SessionState.d.ts +0 -76
package/dist/sdk.module.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.module.js","sources":["../src/lib/Errors.ts","../src/lib/state/State.ts","../src/lib/state/session/SessionState.ts","../src/lib/events/CustomEvents.ts","../src/lib/events/Dispatcher.ts","../../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/flow-api/State.ts","../src/lib/Cookie.ts","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/EnterpriseClient.ts","../src/lib/client/UserClient.ts","../src/lib/client/EmailClient.ts","../src/lib/client/ThirdPartyClient.ts","../src/lib/client/TokenClient.ts","../src/lib/Throttle.ts","../src/lib/events/Listener.ts","../src/lib/events/Scheduler.ts","../src/lib/Session.ts","../src/lib/events/Relay.ts","../src/lib/flow-api/Flow.ts","../src/lib/client/SessionClient.ts","../src/Hanko.ts","../src/lib/WebauthnSupport.ts"],"sourcesContent":["/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\n/**\n * A 'ForbiddenError' occurs when the user is not allowed to perform the requested action.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ForbiddenError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Forbidden error\", \"forbidden\", cause);\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * A 'UserVerificationError' occurs when the user verification requirements\n * for a WebAuthn ceremony are not met.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UserVerificationError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"User verification error\", \"userVerification\", cause);\n Object.setPrototypeOf(this, UserVerificationError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfEmailAddressesReachedError' occurs when the user tries to add a new email address while the maximum number\n * of email addresses (see backend configuration) equals the number of email addresses already registered.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfEmailAddressesReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of email addresses reached error\",\n \"maxNumOfEmailAddressesReached\",\n cause\n );\n Object.setPrototypeOf(this, MaxNumOfEmailAddressesReachedError.prototype);\n }\n}\n\n/**\n * An 'EmailAddressAlreadyExistsError' occurs when the user tries to add a new email address which already exists.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass EmailAddressAlreadyExistsError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"The email address already exists\",\n \"emailAddressAlreadyExistsError\",\n cause\n );\n Object.setPrototypeOf(this, EmailAddressAlreadyExistsError.prototype);\n }\n}\n\n/**\n * A `ThirdPartyError` may occur during a sign in/sign up with a third party\n * provider.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ThirdPartyError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(code: string, cause?: Error) {\n super(\"An error occurred during third party sign up/sign in\", code, cause);\n Object.setPrototypeOf(this, ThirdPartyError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n ForbiddenError,\n UserVerificationError,\n MaxNumOfEmailAddressesReachedError,\n EmailAddressAlreadyExistsError,\n ThirdPartyError,\n};\n","import { LocalStorageSession } from \"./session/SessionState\";\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {LocalStorageUsers=} users - The user states.\n */\ninterface LocalStorage {\n session?: LocalStorageSession;\n}\n\n/**\n * A class to read and write local storage contents.\n *\n * @abstract\n * @param {string} key - The local storage key.\n * @category SDK\n * @subcategory Internal\n */\nabstract class State {\n key: string;\n ls: LocalStorage;\n\n // eslint-disable-next-line require-jsdoc\n constructor(key: string) {\n /**\n * @private\n * @type {string}\n */\n this.key = key;\n /**\n * @type {LocalStorage}\n */\n this.ls = {};\n }\n\n /**\n * Reads and decodes the locally stored data.\n *\n * @return {State}\n */\n read(): State {\n let store: LocalStorage;\n\n try {\n const data = localStorage.getItem(this.key);\n const decoded = decodeURIComponent(decodeURI(window.atob(data)));\n store = JSON.parse(decoded);\n } catch (e) {\n this.ls = {};\n\n return this;\n }\n\n this.ls = store;\n\n return this;\n }\n\n /**\n * Encodes and writes the data to the local storage.\n *\n * @return {State}\n */\n write(): State {\n const data = JSON.stringify(this.ls);\n const encoded = window.btoa(encodeURI(encodeURIComponent(data)));\n\n localStorage.setItem(this.key, encoded);\n\n return this;\n }\n\n /**\n * Converts a timestamp into remaining seconds that you can count down.\n *\n * @static\n * @param {number} time - Timestamp in seconds (since January 1, 1970 00:00:00 UTC).\n * @return {number}\n */\n static timeToRemainingSeconds(time = 0) {\n return time - Math.floor(Date.now() / 1000);\n }\n\n /**\n * Converts a number of seconds into a timestamp.\n *\n * @static\n * @param {number} seconds - Remaining seconds to be converted into a timestamp.\n * @return {number}\n */\n static remainingSecondsToTime(seconds = 0) {\n return Math.floor(Date.now() / 1000) + seconds;\n }\n}\n\nexport { State };\nexport type { LocalStorage };\n","import { State } from \"../State\";\n\n/**\n * Options for SessionState\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n */\ninterface SessionStateOptions {\n localStorageKey: string;\n}\n\n/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {Object.<string, LocalStorageSession>} - A dictionary for mapping users to their states.\n */\nexport interface LocalStorageSession {\n expiry: number;\n authFlowCompleted: boolean;\n}\n\n/**\n * A class to read and write local storage contents regarding sessions.\n *\n * @extends State\n * @param {SessionStateOptions} options - The options that can be used\n * @category SDK\n * @subcategory Internal\n */\nclass SessionState extends State {\n // eslint-disable-next-line require-jsdoc\n constructor(options: SessionStateOptions) {\n super(`${options.localStorageKey}_session`);\n }\n\n /**\n * Reads the current state.\n *\n * @public\n * @return {SessionState}\n */\n read(): SessionState {\n super.read();\n\n return this;\n }\n\n /**\n * Gets the session state.\n *\n * @return {LocalStorageSession}\n */\n getState(): LocalStorageSession {\n this.ls.session ||= { expiry: 0, authFlowCompleted: false };\n return this.ls.session;\n }\n\n /**\n * Gets the number of seconds until the active session is valid.\n *\n * @return {number}\n */\n getExpirationSeconds(): number {\n return State.timeToRemainingSeconds(this.getState().expiry);\n }\n\n /**\n * Sets the number of seconds until the active session is valid.\n *\n * @param {number} seconds - The number of seconds\n * @return {SessionState}\n */\n setExpirationSeconds(seconds: number): SessionState {\n this.getState().expiry = State.remainingSecondsToTime(seconds);\n return this;\n }\n\n /**\n * Gets the authFlowCompleted indicator.\n */\n getAuthFlowCompleted(): boolean {\n return this.getState().authFlowCompleted;\n }\n\n /**\n * Sets the authFlowCompleted indicator.\n *\n * @param {string} completed - The authFlowCompleted indicator.\n * @return {SessionState}\n */\n setAuthFlowCompleted(completed: boolean): SessionState {\n this.getState().authFlowCompleted = completed;\n return this;\n }\n\n /**\n * Removes the session details.\n *\n * @return {SessionState}\n */\n reset(): SessionState {\n const session = this.getState();\n\n delete session.expiry;\n\n return this;\n }\n}\n\nexport { SessionState };\n","/**\n * The type of the `hanko-session-created` event.\n * @typedef {string} sessionCreatedType\n * @memberOf Listener\n */\nexport const sessionCreatedType: \"hanko-session-created\" =\n \"hanko-session-created\";\n\n/**\n * The type of the `hanko-session-expired` event.\n * @typedef {string} sessionExpiredType\n * @memberOf Listener\n */\nexport const sessionExpiredType: \"hanko-session-expired\" =\n \"hanko-session-expired\";\n\n/**\n * The type of the `hanko-user-logged-out` event.\n * @typedef {string} userLoggedOutType\n * @memberOf Listener\n */\nexport const userLoggedOutType: \"hanko-user-logged-out\" =\n \"hanko-user-logged-out\";\n\n/**\n * The type of the `hanko-user-deleted` event.\n * @typedef {string} userDeletedType\n * @memberOf Listener\n */\nexport const userDeletedType: \"hanko-user-deleted\" = \"hanko-user-deleted\";\n\n/**\n * The type of the `hanko-user-logged-in` event.\n * @typedef {string} userLoggedInType\n * @memberOf Listener\n */\nexport const userLoggedInType: \"hanko-user-logged-in\" = \"hanko-user-logged-in\";\n\n/**\n * The type of the `hanko-user-created` event.\n * @typedef {string} userCreatedType\n * @memberOf Listener\n */\nexport const userCreatedType: \"hanko-user-created\" = \"hanko-user-created\";\n\n/**\n * The data passed in the `hanko-session-created` or `hanko-session-resumed` event.\n *\n * @interface\n * @category SDK\n * @subcategory Events\n * @property {string=} jwt - The JSON web token associated with the session. Only present when the Hanko-API allows the JWT to be accessible client-side.\n * @property {number} expirationSeconds - The number of seconds until the JWT expires.\n */\nexport interface SessionDetail {\n jwt?: string;\n expirationSeconds: number;\n}\n\n/**\n * A custom event that includes a detail object.\n *\n * @category SDK\n * @subcategory Events\n * @extends CustomEvent\n * @ignore\n * @param {string} type - The type of the event.\n * @param {T} detail - The detail object to include in the event.\n */\nexport class CustomEventWithDetail<T> extends CustomEvent<T> {\n // eslint-disable-next-line require-jsdoc\n constructor(type: string, detail: T) {\n super(type, { detail });\n }\n}\n","import {\n SessionDetail,\n CustomEventWithDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n} from \"./CustomEvents\";\nimport { SessionState } from \"../state/session/SessionState\";\n\n/**\n * Options for Dispatcher\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n */\ninterface DispatcherOptions {\n localStorageKey: string;\n}\n\n/**\n * A class that dispatches custom events.\n *\n * @category SDK\n * @subcategory Internal\n * @param {DispatcherOptions} options - The options that can be used\n */\nexport class Dispatcher {\n _dispatchEvent = document.dispatchEvent.bind(document);\n _sessionState: SessionState;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: DispatcherOptions) {\n this._sessionState = new SessionState({ ...options });\n }\n\n /**\n * Dispatches a custom event.\n *\n * @param {string} type\n * @param {T} detail\n * @private\n */\n private dispatch<T>(type: string, detail: T) {\n this._dispatchEvent(new CustomEventWithDetail(type, detail));\n }\n\n /**\n * Dispatches a \"hanko-session-created\" event to the document with the specified detail.\n *\n * @param {SessionDetail} detail - The event detail.\n */\n public dispatchSessionCreatedEvent(detail: SessionDetail) {\n this.dispatch(sessionCreatedType, detail);\n }\n\n /**\n * Dispatches a \"hanko-session-expired\" event to the document.\n */\n public dispatchSessionExpiredEvent() {\n this.dispatch(sessionExpiredType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-logged-out\" event to the document.\n */\n public dispatchUserLoggedOutEvent() {\n this.dispatch(userLoggedOutType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-deleted\" event to the document.\n */\n public dispatchUserDeletedEvent() {\n this.dispatch(userDeletedType, null);\n }\n}\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import {\n FetchNextState,\n StateName,\n Actions,\n Payloads,\n} from \"./types/state-handling\";\nimport { Error } from \"./types/error\";\nimport { Action } from \"./types/action\";\nimport { Input } from \"./types/input\";\n\ntype InputValues<TInput extends Record<string, Input<any>>> = {\n [K in keyof TInput]?: TInput[K][\"value\"];\n};\n\ntype CreateAction<TAction extends Action<any>> = (\n inputs: InputValues<TAction[\"inputs\"]>\n) => TAction & {\n run: () => Promise<State<any>>;\n validate: () => TAction;\n tryValidate: () => ValidationError | void;\n};\n\ntype ActionFunctions = {\n [TStateName in keyof Actions]: {\n [TActionName in keyof Actions[TStateName]]: Actions[TStateName][TActionName] extends Action<\n infer Inputs\n >\n ? CreateAction<Action<Inputs>>\n : never;\n };\n};\n\ninterface StateResponse<TStateName extends StateName> {\n name: StateName;\n status: number;\n payload?: Payloads[TStateName];\n actions?: Actions[TStateName];\n csrf_token: string;\n error: Error;\n}\n\n// State class represents a state in the flow\n// eslint-disable-next-line require-jsdoc\nclass State<TStateName extends StateName>\n implements Omit<StateResponse<TStateName>, \"actions\">\n{\n readonly name: StateName;\n readonly payload?: Payloads[TStateName];\n readonly error: Error;\n readonly status: number;\n readonly csrf_token: string;\n\n readonly #actionDefinitions: Actions[TStateName];\n readonly actions: ActionFunctions[TStateName];\n\n private readonly fetchNextState: FetchNextState;\n\n toJSON() {\n return {\n name: this.name,\n payload: this.payload,\n error: this.error,\n status: this.status,\n csrf_token: this.csrf_token,\n actions: this.#actionDefinitions,\n };\n }\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n { name, payload, error, status, actions, csrf_token }: StateResponse<TStateName>,\n fetchNextState: FetchNextState\n ) {\n this.name = name;\n this.payload = payload;\n this.error = error;\n this.status = status;\n this.csrf_token = csrf_token;\n this.#actionDefinitions = actions;\n\n // We're doing something really hacky here, but hear me out\n //\n // `actions` is an object like this:\n //\n // { login_password_recovery: { inputs: { new_password: { min_length: 8, value: \"this still needs to be set\" } } } }\n //\n // However, we don't want users to have to mutate the `actions` object manually.\n // They WOULD have to do this:\n //\n // actions.login_password_recovery.inputs.new_password.value = \"password\";\n //\n // Instead, we're going to wrap the `actions` object in a Proxy.\n // This Proxy transforms the manual mutation you're seeing above into a function call.\n // The following is doing the same thing as the manual mutation above:\n //\n // actions.login_password_recovery({ new_password: \"password\" });\n //\n // Okay, there's one difference, the function call creates a copy of the action, so it's not mutating the original object.\n // The newly created action is returned. It also has a `run` method, which sends the action to the server (fetchNextState)\n this.actions = this.#createActionsProxy(actions, csrf_token);\n\n // Do not remove! `this.fetchNextState` has to be set for `this.#runAction` to work\n this.fetchNextState = fetchNextState;\n }\n\n /**\n * We get the `actions` object from the server. That object is essentially a definition of actions that can be performed in the current state.\n *\n * For example:\n *\n * actions = {\n * login_password_recovery: {\n * inputs: {\n * email: { value: undefined, required: true, ... },\n * password: { value: undefined, required: true, min_length: 8, ... }\n * }\n * },\n * create_account: { inputs: ... },\n * some_other_action: { inputs: ... },\n * };\n *\n * The proxy returned by this method creates \"action functions\".\n *\n * Each action function copies the original definition (`{ inputs: ... }`) and modifies that copy with the inputs provided by the user.\n *\n * In practice, it looks like this:\n *\n * actions.login_password_recovery({ new_password: \"very-secure-123\" });\n * // => { inputs: { password: { value: \"very-secure-123\", min_length: 8, ... }}}\n *\n * Additionally, helper methods like `run` (to send the action to the server) and `validate` (to validate the inputs; the `inputs` object also contains validation rules)\n */\n #createActionsProxy(actions: Actions[TStateName], csrfToken: string) {\n const runAction = (action: Action<any>) => this.runAction(action, csrfToken);\n const validateAction = (action: Action<any>) => this.validateAction(action);\n\n return new Proxy(actions, {\n get(target, prop): CreateAction<Action<unknown>> | undefined {\n if (typeof prop === \"symbol\") return (target as any)[prop];\n\n type Original = Actions[TStateName][keyof Actions[TStateName]];\n type Prop = keyof typeof target;\n\n /**\n * This is the action defintion.\n * Running the function returned by this getter creates a **deep copy**\n * with values set by the user.\n */\n const originalAction = target[\n prop as Prop\n ] satisfies Original as Action<unknown>;\n\n if (originalAction == null) {\n return null;\n }\n\n return (newInputs: any) => {\n const action = Object.assign(deepCopy(originalAction), {\n validate() {\n validateAction(action);\n return action;\n },\n tryValidate() {\n try {\n validateAction(action);\n } catch (e) {\n if (e instanceof ValidationError) return e;\n\n // We still want to throw non-ValidationErrors since they're unexpected (and indicate a bug on our side)\n throw e;\n }\n },\n run() {\n return runAction(action);\n },\n });\n\n // If `actions` is an object that has inputs,\n //\n // Transform this:\n // actions.login_password_recovery({ new_password: \"password\" });\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n // Into this:\n // action.inputs = { new_password: { min_length: 8, value: \"password\", ... }}\n if (\n action !== null &&\n typeof action === \"object\" &&\n \"inputs\" in action\n ) {\n for (const inputName in newInputs) {\n const actionInputs = action.inputs as Record<\n string,\n Input<unknown>\n >;\n\n if (!actionInputs[inputName]) {\n actionInputs[inputName] = { name: inputName, type: \"\" };\n }\n\n actionInputs[inputName].value = newInputs[inputName];\n }\n }\n\n return action;\n };\n },\n }) satisfies Actions[TStateName] as any;\n }\n\n runAction(action: Action<any>, csrfToken: string): Promise<State<any>> {\n const data: Record<string, any> = {};\n\n // Deal with object-type inputs\n // i.e. actions.some_action({ ... })\n // ^^^^^^^\n // Other input types would look like this:\n //\n // actions.another_action(1234);\n // actions.yet_another_action(\"foo\");\n //\n // Meaning\n if (\n \"inputs\" in action &&\n typeof action.inputs === \"object\" &&\n action.inputs !== null\n ) {\n // This looks horrible, but at this point we're sure that `action.inputs` is a Record<string, Input>\n // Because there are no object-type inputs that AREN'T a Record<string, Input>\n const inputs = action.inputs satisfies object as Record<\n string,\n Input<unknown>\n >;\n\n for (const inputName in action.inputs) {\n const input = inputs[inputName];\n\n if (input && \"value\" in input) {\n data[inputName] = input.value;\n }\n }\n }\n\n // (Possibly add more input types here?)\n\n // Use the fetch function to perform the action\n return this.fetchNextState(action.href, {\n input_data: data,\n csrf_token: csrfToken,\n });\n }\n\n validateAction(action: Action<{ [key: string]: Input<unknown> }>) {\n if (!(\"inputs\" in action)) return;\n\n for (const inputName in action.inputs) {\n const input = action.inputs[inputName];\n\n function reject<T>(\n reason: ValidationReason,\n message: string,\n wanted?: T,\n actual?: T\n ) {\n throw new ValidationError({\n reason,\n inputName,\n wanted,\n actual,\n message,\n });\n }\n\n const value = input.value as any; // TS gets in the way here\n\n // TODO is !input.value right here? this will also reject empty strings, `0`, ... and will never reject an empty array/object\n if (input.required && !value) {\n reject(ValidationReason.Required, \"is required\");\n }\n\n const hasLengthRequirement =\n input.min_length != null || input.max_length != null;\n\n if (hasLengthRequirement) {\n if (!(\"length\" in value)) {\n reject(\n ValidationReason.InvalidInputDefinition,\n 'has min/max length requirement, but is missing \"length\" property',\n \"string\",\n typeof value\n );\n }\n\n if (input.min_length != null && value < input.min_length) {\n reject(\n ValidationReason.MinLength,\n `too short (min ${input.min_length})`,\n input.min_length,\n value.length\n );\n }\n\n if (input.max_length != null && value > input.max_length) {\n reject(\n ValidationReason.MaxLength,\n `too long (max ${input.max_length})`,\n input.max_length,\n value.length\n );\n }\n }\n }\n }\n}\n\nexport enum ValidationReason {\n InvalidInputDefinition,\n MinLength,\n MaxLength,\n Required,\n}\n\nexport class ValidationError<TWanted = undefined> extends Error {\n reason: ValidationReason;\n inputName: string;\n wanted: TWanted;\n actual: TWanted;\n\n constructor(opts: {\n reason: ValidationReason;\n inputName: string;\n wanted: TWanted;\n actual: TWanted;\n message: string;\n }) {\n super(`\"${opts.inputName}\" ${opts.message}`);\n\n this.name = \"ValidationError\";\n this.reason = opts.reason;\n this.inputName = opts.inputName;\n this.wanted = opts.wanted;\n this.actual = opts.actual;\n }\n}\n\nfunction deepCopy<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj));\n}\n\nexport function isState(x: any): x is State<any> {\n return (\n typeof x === \"object\" &&\n x !== null &&\n \"status\" in x &&\n \"error\" in x &&\n \"name\" in x &&\n Boolean(x.name) &&\n Boolean(x.status)\n );\n}\n\nexport { State };\n","import JSCookie, { CookieAttributes } from \"js-cookie\";\nimport { TechnicalError } from \"./Errors\";\n\n/**\n * Options for Cookie\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite -Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n */\ninterface CookieOptions {\n cookieName: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n}\n\nexport type CookieSameSite =\n | \"strict\"\n | \"Strict\"\n | \"lax\"\n | \"Lax\"\n | \"none\"\n | \"None\";\n\n/**\n * A class to manage cookies.\n *\n * @category SDK\n * @subcategory Internal\n * @param {CookieOptions} options - The options that can be used\n */\nexport class Cookie {\n authCookieName: string;\n authCookieDomain?: string;\n authCookieSameSite: CookieSameSite;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: CookieOptions) {\n this.authCookieName = options.cookieName;\n this.authCookieDomain = options.cookieDomain;\n this.authCookieSameSite = options.cookieSameSite ?? \"lax\";\n }\n\n /**\n * Returns the authentication token that was stored in the cookie.\n *\n * @return {string}\n */\n getAuthCookie(): string {\n return JSCookie.get(this.authCookieName);\n }\n\n /**\n * Stores the authentication token to the cookie.\n *\n * @param {string} token - The authentication token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n */\n setAuthCookie(token: string, options?: CookieAttributes) {\n const defaults: CookieAttributes = {\n secure: true,\n sameSite: this.authCookieSameSite,\n };\n\n if (this.authCookieDomain !== undefined) {\n defaults.domain = this.authCookieDomain;\n }\n\n const o: CookieAttributes = { ...defaults, ...options };\n\n if (\n (o.sameSite === \"none\" || o.sameSite === \"None\") &&\n o.secure === false\n ) {\n throw new TechnicalError(\n new Error(\"Secure attribute must be set when SameSite=None\"),\n );\n }\n\n JSCookie.set(this.authCookieName, token, o);\n }\n\n /**\n * Removes the cookie used for authentication.\n */\n removeAuthCookie() {\n JSCookie.remove(this.authCookieName);\n }\n}\n","import { RequestTimeoutError, TechnicalError } from \"../Errors\";\nimport { SessionState } from \"../state/session/SessionState\";\nimport { Dispatcher } from \"../events/Dispatcher\";\nimport { Cookie } from \"../Cookie\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n /**\n * Returns the response header with the given name.\n *\n * @param {string} name\n * @return {string}\n */\n getResponseHeader(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n /**\n * @private\n * @type {XMLHttpRequest}\n */\n this.xhr = xhr;\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n if (!this._decodedJSON) {\n this._decodedJSON = JSON.parse(this.xhr.response);\n }\n return this._decodedJSON;\n }\n\n /**\n * Returns the response header value with the given `name` as a number. When the value is not a number the return\n * value will be 0.\n *\n * @param {string} name - The name of the header field\n * @return {number}\n */\n parseNumericHeader(name: string): number {\n const result = parseInt(this.headers.getResponseHeader(name), 10);\n return isNaN(result) ? 0 : result;\n }\n}\n\n/**\n * Options for the HttpClient\n *\n * @category SDK\n * @subcategory Internal\n * @property {number} timeout - The http request timeout in milliseconds.\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n * @property {string} lang - The language used by the client(s) to convey to the Hanko API the language to use -\n * e.g. for translating outgoing emails - in a custom header (X-Language).\n */\nexport interface HttpClientOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n localStorageKey: string;\n lang?: string;\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options the HttpClient must be provided\n */\nclass HttpClient {\n timeout: number;\n api: string;\n sessionState: SessionState;\n dispatcher: Dispatcher;\n cookie: Cookie;\n lang: string;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n this.api = api;\n this.timeout = options.timeout;\n this.sessionState = new SessionState({ ...options });\n this.dispatcher = new Dispatcher({ ...options });\n this.cookie = new Cookie({ ...options });\n this.lang = options.lang;\n }\n\n // eslint-disable-next-line require-jsdoc\n _fetch(path: string, options: RequestInit, xhr = new XMLHttpRequest()) {\n const self = this;\n const url = this.api + path;\n const timeout = this.timeout;\n const bearerToken = this.cookie.getAuthCookie();\n const lang = this.lang;\n\n return new Promise<Response>(function (resolve, reject) {\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n xhr.setRequestHeader(\"X-Language\", lang);\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n self.processHeaders(xhr);\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n /**\n * Processes the response headers on login and extracts the JWT and expiration time.\n *\n * @param {XMLHttpRequest} xhr - The xhr object.\n */\n processHeaders(xhr: XMLHttpRequest) {\n let jwt = \"\";\n let expirationSeconds = 0;\n let retention = \"\";\n\n xhr\n .getAllResponseHeaders()\n .split(\"\\r\\n\")\n .forEach((h) => {\n const header = h.toLowerCase();\n if (header.startsWith(\"x-auth-token\")) {\n jwt = xhr.getResponseHeader(\"X-Auth-Token\");\n } else if (header.startsWith(\"x-session-lifetime\")) {\n expirationSeconds = parseInt(\n xhr.getResponseHeader(\"X-Session-Lifetime\"),\n 10,\n );\n } else if (header.startsWith(\"x-session-retention\")) {\n retention = xhr.getResponseHeader(\"X-Session-Retention\");\n }\n });\n\n if (jwt) {\n const https = new RegExp(\"^https://\");\n const secure =\n !!this.api.match(https) && !!window.location.href.match(https);\n\n const expires =\n retention === \"session\"\n ? undefined\n : new Date(new Date().getTime() + expirationSeconds * 1000);\n\n this.cookie.setAuthCookie(jwt, { secure, expires });\n }\n\n if (expirationSeconds > 0) {\n this.sessionState.read();\n this.sessionState.setExpirationSeconds(expirationSeconds);\n this.sessionState.setAuthFlowCompleted(false);\n this.sessionState.write();\n }\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PATCH request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n patch(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PATCH\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a DELETE request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n delete(path: string) {\n return this._fetch(path, {\n method: \"DELETE\",\n });\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient, HttpClientOptions } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options that can be used\n */\nabstract class Client {\n client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n /**\n * @public\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, options);\n }\n}\n\nexport { Client };\n","import { Client } from \"./Client\";\nimport { NotFoundError, TechnicalError, ThirdPartyError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of authenticating through a third party provider.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class EnterpriseClient extends Client {\n /**\n * Extracts the domain from an email address\n * @param {string} email E-Mail address of the user from which the domain will be extracted.\n * @throws {ThirdPartyError}\n * @private\n */\n private getDomain(email: string): string {\n if (!email) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email missing from request\"),\n );\n }\n\n const emailParts = email.split(\"@\");\n if (emailParts.length !== 2) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email is not in a valid email format.\"),\n );\n }\n\n const domain = emailParts[1].trim();\n if (domain === \"\") {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email is not in a valid email format.\"),\n );\n }\n\n return domain;\n }\n\n /**\n * Performs a request to the Hanko API to check if there is a provider for the users e-mail domain\n *\n * @param {string} email - E-Mail address of the user to login\n */\n async hasProvider(email: string): Promise<boolean> {\n const domain = this.getDomain(email);\n\n return this.client.get(`/saml/provider?domain=${domain}`).then((resp) => {\n if (resp.status == 404) {\n throw new NotFoundError(new Error(\"provider not found\"));\n }\n\n if (!resp.ok) {\n throw new TechnicalError(new Error(\"unable to fetch provider\"));\n }\n\n return resp.ok;\n });\n }\n\n /**\n * Performs a request to the Hanko API that redirects to the given\n * third party provider.\n *\n * @param {string} email - E-Mail address of the user\n * @param {string} redirectTo - The URL to redirect to after a successful third party authentication\n * @throws {ThirdPartyError}\n * @see http://docs.hanko.io/api/public#tag/Third-Party/operation/enterpriseAuth\n */\n auth(email: string, redirectTo: string): void {\n const url = new URL(\"/saml/auth\", this.client.api);\n const domain = this.getDomain(email);\n\n if (!redirectTo) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"redirectTo missing from request\"),\n );\n }\n\n url.searchParams.append(\"domain\", domain);\n url.searchParams.append(\"redirect_to\", redirectTo);\n\n window.location.assign(url.href);\n }\n\n /**\n * Get a third party error from the current location's query params.\n * @returns {(ThirdPartyError|undefined)} The ThirdPartyError.\n */\n getError() {\n const params = new URLSearchParams(window.location.search);\n const error = params.get(\"error\");\n const errorDescription = params.get(\"error_description\");\n if (error) {\n let code;\n switch (error) {\n case \"access_denied\":\n code = \"enterpriseAccessDenied\";\n break;\n case \"user_conflict\":\n code = \"emailAddressAlreadyExistsError\";\n break;\n case \"multiple_accounts\":\n code = \"enterpriseMultipleAccounts\";\n break;\n case \"unverified_email\":\n code = \"enterpriseUnverifiedEmail\";\n break;\n case \"email_maxnum\":\n code = \"maxNumOfEmailAddressesReached\";\n break;\n default:\n code = \"somethingWentWrong\";\n }\n\n return new ThirdPartyError(code, new Error(errorDescription));\n }\n }\n}\n","import { Me, User, UserInfo, UserCreated } from \"../Dto\";\nimport {\n ConflictError,\n NotFoundError,\n TechnicalError,\n UnauthorizedError,\n ForbiddenError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches basic information about the user identified by the given email address. Can be used while the user is logged out\n * and is helpful in deciding which type of login to choose. For example, if the user's email is not verified, you may\n * want to log in with a passcode, or if no WebAuthn credentials are registered, you may not want to use WebAuthn.\n *\n * @param {string} email - The user's email address.\n * @return {Promise<UserInfo>}\n * @throws {NotFoundError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/getUserId\n */\n async getInfo(email: string): Promise<UserInfo> {\n const response = await this.client.post(\"/user\", { email });\n\n if (response.status === 404) {\n throw new NotFoundError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Creates a new user. Afterwards, verify the email address via passcode. If a 'ConflictError'\n * occurred, you may want to prompt the user to log in.\n *\n * @param {string} email - The email address of the user to be created.\n * @return {Promise<UserCreated>}\n * @throws {ConflictError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/createUser\n */\n async create(email: string): Promise<UserCreated> {\n const response = await this.client.post(\"/users\", { email });\n\n if (response.status === 409) {\n throw new ConflictError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n async getCurrent(): Promise<User> {\n const meResponse = await this.client.get(\"/me\");\n\n if (meResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!meResponse.ok) {\n throw new TechnicalError();\n }\n\n const me: Me = meResponse.json();\n const userResponse = await this.client.get(`/users/${me.id}`);\n\n if (userResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!userResponse.ok) {\n throw new TechnicalError();\n }\n\n return userResponse.json();\n }\n\n /**\n * Deletes the current user and expires the existing session cookie.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n */\n async delete(): Promise<void> {\n const response = await this.client.delete(\"/user\");\n\n if (response.ok) {\n this.client.cookie.removeAuthCookie();\n this.client.sessionState.reset().write();\n this.client.dispatcher.dispatchUserDeletedEvent();\n return;\n } else if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n }\n\n /**\n * Logs out the current user and expires the existing session cookie. A valid session cookie is required to call the logout endpoint.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n async logout(): Promise<void> {\n const logoutResponse = await this.client.post(\"/logout\");\n\n // For cross-domain operations, the frontend SDK creates the cookie by reading the \"X-Auth-Token\" header, and\n // \"Set-Cookie\" headers sent by the backend have no effect due to the browser's security policy, which means that\n // the cookie must also be removed client-side in that case.\n this.client.cookie.removeAuthCookie();\n this.client.sessionState.reset().write();\n this.client.dispatcher.dispatchUserLoggedOutEvent();\n\n if (logoutResponse.status === 401) {\n // The user is logged out already\n return;\n } else if (!logoutResponse.ok) {\n throw new TechnicalError();\n }\n }\n}\n\nexport { UserClient };\n","import { Client } from \"./Client\";\nimport {\n EmailAddressAlreadyExistsError,\n MaxNumOfEmailAddressesReachedError,\n TechnicalError,\n UnauthorizedError,\n} from \"../Errors\";\nimport { Email, Emails } from \"../Dto\";\n\n/**\n * Manages email addresses of the current user.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass EmailClient extends Client {\n /**\n * Returns a list of all email addresses assigned to the current user.\n *\n * @return {Promise<Emails>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/listEmails\n */\n async list(): Promise<Emails> {\n const response = await this.client.get(\"/emails\");\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Adds a new email address to the current user.\n *\n * @param {string} address - The email address to be added.\n * @return {Promise<Email>}\n * @throws {EmailAddressAlreadyExistsError}\n * @throws {MaxNumOfEmailAddressesReachedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/createEmail\n */\n async create(address: string): Promise<Email> {\n const response = await this.client.post(\"/emails\", { address });\n\n if (response.ok) {\n return response.json();\n }\n\n if (response.status === 400) {\n throw new EmailAddressAlreadyExistsError();\n } else if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (response.status === 409) {\n throw new MaxNumOfEmailAddressesReachedError();\n }\n\n throw new TechnicalError();\n }\n\n /**\n * Marks the specified email address as primary.\n *\n * @param {string} emailID - The ID of the email address to be updated\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/setPrimaryEmail\n */\n async setPrimaryEmail(emailID: string): Promise<void> {\n const response = await this.client.post(`/emails/${emailID}/set_primary`);\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return;\n }\n\n /**\n * Deletes the specified email address.\n *\n * @param {string} emailID - The ID of the email address to be deleted\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/deleteEmail\n */\n async delete(emailID: string): Promise<void> {\n const response = await this.client.delete(`/emails/${emailID}`);\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return;\n }\n}\n\nexport { EmailClient };\n","import { Client } from \"./Client\";\nimport { ThirdPartyError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of authenticating through a third party provider.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class ThirdPartyClient extends Client {\n /**\n * Performs a request to the Hanko API that redirects to the given\n * third party provider.\n *\n * @param {string} provider - The name of the third party provider\n * @param {string} redirectTo - The URL to redirect to after a successful third party authentication\n * @throws {ThirdPartyError}\n * @see http://docs.hanko.io/api/public#tag/Third-Party/operation/thirdPartyAuth\n */\n async auth(provider: string, redirectTo: string): Promise<void> {\n const url = new URL(\"/thirdparty/auth\", this.client.api);\n\n if (!provider) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"provider missing from request\"),\n );\n }\n\n if (!redirectTo) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"redirectTo missing from request\"),\n );\n }\n\n url.searchParams.append(\"provider\", provider);\n url.searchParams.append(\"redirect_to\", redirectTo);\n\n window.location.assign(url.href);\n }\n\n /**\n * Get a third party error from the current location's query params.\n * @returns {(ThirdPartyError|undefined)} The ThirdPartyError.\n */\n getError() {\n const params = new URLSearchParams(window.location.search);\n const error = params.get(\"error\");\n const errorDescription = params.get(\"error_description\");\n if (error) {\n let code = \"\";\n switch (error) {\n case \"access_denied\":\n code = \"thirdPartyAccessDenied\";\n break;\n case \"user_conflict\":\n code = \"emailAddressAlreadyExistsError\";\n break;\n case \"multiple_accounts\":\n code = \"thirdPartyMultipleAccounts\";\n break;\n case \"unverified_email\":\n code = \"thirdPartyUnverifiedEmail\";\n break;\n case \"email_maxnum\":\n code = \"maxNumOfEmailAddressesReached\";\n break;\n case \"signup_disabled\":\n code = \"signupDisabled\";\n break;\n default:\n code = \"somethingWentWrong\";\n }\n\n return new ThirdPartyError(code, new Error(errorDescription));\n }\n }\n}\n","import { Client } from \"./Client\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * Client responsible for exchanging one time tokens for session JWTs.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class TokenClient extends Client {\n /**\n * Validate a one time token to retrieve a session JWT. Does nothing\n * if the current window location does not contain a 'hanko_token' in the\n * search query.\n *\n * @return {Promise<void>}\n * @throws {TechnicalError}\n * https://docs.hanko.io/api/api/public#tag/Token/operation/token\n */\n async validate(): Promise<void> {\n const params = new URLSearchParams(window.location.search);\n const token = params.get(\"hanko_token\");\n\n if (!token) return;\n\n window.history.replaceState(null, null, window.location.pathname);\n\n const response = await this.client.post(\"/token\", { value: token });\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n}\n","/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {boolean=} leading - Whether to allow the function to be called on the leading edge of the wait timeout.\n * @property {boolean=} trailing - Whether to allow the function to be called on the trailing edge of the wait timeout.\n */\ninterface ThrottleOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\n// eslint-disable-next-line no-unused-vars\ntype ThrottledFunction<T extends (...args: any[]) => any> = (\n // eslint-disable-next-line no-unused-vars\n ...args: Parameters<T>\n) => void;\n\n/**\n * Provides throttle functionality.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Internal\n */\nexport class Throttle {\n /**\n * Throttles a function, ensuring that it can only be called once per `wait` milliseconds.\n *\n * @static\n * @param {function} func - The function to throttle.\n * @param {number} wait - The number of milliseconds to wait between function invocations.\n * @param {ThrottleOptions} options - Optional configuration for the throttle.\n * @returns {function} A throttled version of the original function.\n */\n // eslint-disable-next-line no-unused-vars,require-jsdoc\n static throttle<T extends (...args: any[]) => any>(\n func: T,\n wait: number,\n options: ThrottleOptions = {}\n ): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let context: any;\n let args: any;\n let timeoutID: number;\n let previous = 0;\n\n // This function is used to invoke the original function.\n const executeThrottledFunction = () => {\n // If 'leading' is false and this is not the first invocation of the throttled function, set 'previous' to 0 to\n // ensure that the function is not called immediately.\n previous = leading === false ? 0 : Date.now();\n timeoutID = null;\n // Invoke the original function.\n func.apply(context, args);\n };\n\n // This is the throttled function that will be returned.\n const throttled = function (...funcArgs: Parameters<T>) {\n const now = Date.now();\n\n // If this is the first time the throttled function is being called, and 'leading' is false,\n // set 'previous' to the current time to ensure that the function is not called immediately.\n if (!previous && leading === false) previous = now;\n\n // The remaining wait time.\n const remaining = wait - (now - previous);\n\n // Save the context and arguments of the function call.\n // eslint-disable-next-line no-invalid-this\n context = this;\n args = funcArgs;\n\n // Check whether it's time to call the function immediately based on the leading and trailing options. If leading\n // is enabled and there was no previous invocation, or if trailing is enabled and the wait time has already passed,\n // the function will be invoked immediately.\n if (remaining <= 0 || remaining > wait) {\n // If there is a pending timeout, clear it.\n if (timeoutID) {\n window.clearTimeout(timeoutID);\n timeoutID = null;\n }\n\n // Invoke the original function and update the previous timestamp.\n previous = now;\n func.apply(context, args);\n } else if (!timeoutID && trailing !== false) {\n // If there is no pending timeout and trailing is allowed, start a new timeout.\n timeoutID = window.setTimeout(executeThrottledFunction, remaining);\n }\n };\n\n return throttled;\n }\n}\n","import { Throttle } from \"../Throttle\";\nimport {\n CustomEventWithDetail,\n SessionDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n} from \"./CustomEvents\";\n\n/**\n * A callback function to be executed when an event is triggered.\n *\n * @alias CallbackFunc\n * @typedef {function} CallbackFunc\n * @memberOf Listener\n */\n// eslint-disable-next-line no-unused-vars\ntype CallbackFunc<T> = (detail: T) => any;\n\n/**\n * A wrapped callback function that will execute the original callback.\n *\n * @ignore\n * @param {T} event - The event object passed in the event.\n */\n// eslint-disable-next-line no-unused-vars\ntype WrappedCallback<T> = (event: CustomEventWithDetail<T>) => void;\n\n/**\n * A function returned when adding an event listener. The function can be called to remove the corresponding event\n * listener.\n *\n * @alias CleanupFunc\n * @typedef {function} CleanupFunc\n * @memberOf Listener\n */\ntype CleanupFunc = () => void;\n\n/**\n * @interface\n * @ignore\n * @property {Function} callback - The function to be executed.\n * @property {boolean=} once - Whether the event listener should be removed after being called once.\n */\ninterface EventListenerParams<T> {\n callback: CallbackFunc<T>;\n once?: boolean;\n}\n\n/**\n * @interface\n * @ignore\n * @extends {EventListenerParams<T>}\n * @property {string} type - The type of the event.\n * @property {boolean=} throttle - Whether the event listener should be throttled.\n */\ninterface EventListenerWithTypeParams<T> extends EventListenerParams<T> {\n type: string;\n throttle?: boolean;\n}\n\n/**\n * A class to bind event listener for custom events.\n *\n * @category SDK\n * @subcategory Events\n */\nexport class Listener {\n public throttleLimit = 1000;\n _addEventListener = document.addEventListener.bind(document);\n _removeEventListener = document.removeEventListener.bind(document);\n _throttle = Throttle.throttle;\n\n /**\n * Wraps the given callback.\n *\n * @param callback\n * @param throttle\n * @private\n * @return {WrappedCallback}\n */\n private wrapCallback<T>(\n callback: CallbackFunc<T>,\n throttle: boolean,\n ): WrappedCallback<T> {\n // The function that will be called when the event is triggered.\n const wrappedCallback = (event: CustomEventWithDetail<T>) => {\n callback(event.detail);\n };\n\n // Throttle the listener if multiple SDK instances could trigger the same event at the same time,\n // but the callback function should only be executed once.\n if (throttle) {\n return this._throttle(wrappedCallback, this.throttleLimit, {\n leading: true,\n trailing: false,\n });\n }\n\n return wrappedCallback;\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {EventListenerWithTypeParams<T>} params - The parameters for the event listener.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListenerWithType<T>({\n type,\n callback,\n once = false,\n throttle = false,\n }: EventListenerWithTypeParams<T>): CleanupFunc {\n const wrappedCallback = this.wrapCallback(callback, throttle);\n this._addEventListener(type, wrappedCallback, { once });\n return () => this._removeEventListener(type, wrappedCallback);\n }\n\n /**\n * Maps the parameters for an event listener to the `EventListenerWithTypeParams` interface.\n *\n * @static\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean} [throttle=false] - Whether the event listener should be throttled.\n * @returns {EventListenerWithTypeParams<T>}\n **/\n private static mapAddEventListenerParams<T>(\n type: string,\n { once, callback }: EventListenerParams<T>,\n throttle?: boolean,\n ): EventListenerWithTypeParams<T> {\n return {\n type,\n callback,\n once,\n throttle,\n };\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean=} throttle - Whether the event listener should be throttled.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListener<T>(\n type: string,\n params: EventListenerParams<T>,\n throttle?: boolean,\n ) {\n return this.addEventListenerWithType(\n Listener.mapAddEventListenerParams(type, params, throttle),\n );\n }\n\n /**\n * Adds an event listener for \"hanko-session-created\" events. Will be triggered across all browser windows, when the user\n * logs in, or when the page has been loaded or refreshed and there is a valid session.\n *\n * @param {CallbackFunc<SessionDetail>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionCreated(\n callback: CallbackFunc<SessionDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionCreatedType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for \"hanko-session-expired\" events. The event will be triggered across all browser windows\n * as soon as the current JWT expires or the user logs out. It also triggers, when the user deletes the account in\n * another window.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionExpired(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionExpiredType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account in\n * the browser window where the deletion happened.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserLoggedOut(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userLoggedOutType, { callback, once });\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserDeleted(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userDeletedType, { callback, once });\n }\n}\n","/**\n * Represents a task to be scheduled in the scheduler.\n *\n * @ignore\n * @param {number} timeoutID - the ID returned by `setTimeout()`\n * @param {string} type - The type, helps to organize the tasks.\n * @param {Function} func - The function to be called within the task.\n */\nexport type Task = {\n timeoutID: number;\n type: string;\n func: () => any;\n};\n\n/**\n * A class that manages scheduled tasks.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class Scheduler {\n // An array of scheduled tasks.\n _tasks: Task[] = [];\n\n /**\n * Removes a task from the scheduler.\n *\n * @private\n * @param {Task} task - The task to be removed.\n */\n private removeTask(task: Task) {\n window.clearTimeout(task.timeoutID);\n this._tasks = this._tasks.filter((_task) => _task !== task);\n }\n\n /**\n * Removes all tasks with a given type from the scheduler.\n *\n * @param {string} type - The type of tasks to be removed.\n */\n removeTasksWithType(type: string) {\n const tasks = this._tasks.filter((task) => task.type === type);\n tasks.forEach((task) => this.removeTask(task));\n }\n\n /**\n * Schedules a task to be executed after a given timeout.\n *\n * @param {string} type - The type of the task.\n * @param {Function} func - The function to be executed when the task is triggered.\n * @param {number} timeoutSeconds - The timeout after which the task should be executed, in seconds.\n */\n scheduleTask(type: string, func: () => any, timeoutSeconds: number) {\n const task: Task = {\n timeoutID: window.setTimeout(() => {\n func();\n this.removeTask(task);\n }, timeoutSeconds * 1000),\n type,\n func,\n };\n this._tasks.push(task);\n }\n}\n","import { SessionDetail } from \"./events/CustomEvents\";\nimport { SessionState } from \"./state/session/SessionState\";\nimport { Cookie } from \"./Cookie\";\n\n/**\n * Options for Session\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n */\ninterface SessionOptions {\n cookieName: string;\n localStorageKey: string;\n}\n\n/**\n A class representing a session.\n\n @category SDK\n @subcategory Session\n @param {SessionOptions} options - The options that can be used\n */\nexport class Session {\n _sessionState: SessionState;\n _cookie: Cookie;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: SessionOptions) {\n this._sessionState = new SessionState({ ...options });\n this._cookie = new Cookie({ ...options });\n }\n\n /**\n Retrieves the session details.\n\n @returns {SessionDetail} The session details.\n */\n public get(): SessionDetail {\n const detail = this._get();\n return Session.validate(detail) ? detail : null;\n }\n\n /**\n Checks if the user is logged in.\n\n @returns {boolean} true if the user is logged in, false otherwise.\n */\n public isValid(): boolean {\n const session = this._get();\n return Session.validate(session);\n }\n\n /**\n Retrieves the session details.\n\n @ignore\n @returns {SessionDetail} The session details.\n */\n public _get(): SessionDetail {\n this._sessionState.read();\n\n const expirationSeconds = this._sessionState.getExpirationSeconds();\n const jwt = this._cookie.getAuthCookie();\n\n return {\n expirationSeconds,\n jwt,\n };\n }\n\n /**\n Checks if the auth flow is completed. The value resets after the next login attempt.\n\n @returns {boolean} Returns true if the authentication flow is completed, false otherwise\n */\n public isAuthFlowCompleted() {\n this._sessionState.read();\n return this._sessionState.getAuthFlowCompleted();\n }\n\n /**\n Validates the session.\n\n @private\n @param {SessionDetail} detail - The session details to validate.\n @returns {boolean} true if the session is valid, false otherwise.\n */\n private static validate(detail: SessionDetail): boolean {\n return detail.expirationSeconds > 0;\n }\n}\n","import { SessionDetail, sessionExpiredType } from \"./CustomEvents\";\nimport { Listener } from \"./Listener\";\nimport { Scheduler } from \"./Scheduler\";\nimport { Dispatcher } from \"./Dispatcher\";\nimport { Session } from \"../Session\";\n\n/**\n * Options for Relay\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n */\ninterface RelayOptions {\n cookieName: string;\n localStorageKey: string;\n}\n\n/**\n * A class that dispatches events and scheduled events, based on other events.\n *\n * @category SDK\n * @subcategory Internal\n * @extends Dispatcher\n * @param {RelayOptions} options - The options that can be used\n */\nexport class Relay extends Dispatcher {\n _listener = new Listener();\n _scheduler = new Scheduler();\n _session: Session;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: RelayOptions) {\n super({ ...options });\n this._session = new Session({ ...options });\n this.listenEventDependencies();\n }\n\n /**\n * Removes the scheduled \"hanko-session-expired\" event and re-schedules a new event with updated expirationSeconds, to\n * ensure the \"hanko-session-expired\" event won't be triggered too early.\n *\n * @private\n * @param {SessionDetail} detail - The event detail.\n */\n private scheduleSessionExpiredEvent = (detail: SessionDetail) => {\n this._scheduler.removeTasksWithType(sessionExpiredType);\n this._scheduler.scheduleTask(\n sessionExpiredType,\n () => this.dispatchSessionExpiredEvent(),\n detail.expirationSeconds,\n );\n };\n\n /**\n * Cancels scheduled \"hanko-session-expired\" events, to prevent it from being triggered again (e.g. when there are\n * multiple SDK instances).\n *\n * @private\n */\n private cancelSessionExpiredEvent = () => {\n this._scheduler.removeTasksWithType(sessionExpiredType);\n };\n\n /**\n * Handles the \"storage\" event in case the local storage entry, that contains the session detail has been changed by\n * another window. Depending on the new value of `expirationSeconds`, it either dispatches a \"hanko-session-created\"\n * or a \"hanko-session-expired\" event.\n *\n * @private\n * @param {StorageEvent} event - The storage event object.\n */\n private handleStorageEvent = (event: StorageEvent) => {\n if (event.key !== \"hanko_session\") return;\n\n const sessionDetail = this._session.get();\n\n if (!sessionDetail) {\n this.dispatchSessionExpiredEvent();\n return;\n }\n\n this.dispatchSessionCreatedEvent(sessionDetail);\n };\n\n /**\n * Listens for events sent in the current browser.\n *\n * @private\n */\n private listenEventDependencies() {\n this._listener.onSessionCreated(this.scheduleSessionExpiredEvent);\n this._listener.onSessionExpired(this.cancelSessionExpiredEvent);\n this._listener.onUserDeleted(this.cancelSessionExpiredEvent);\n this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent);\n\n // Handle cases, where the session has been changed by another window.\n window.addEventListener(\"storage\", this.handleStorageEvent);\n\n const sessionDetail = this._session.get();\n\n if (sessionDetail) {\n this.scheduleSessionExpiredEvent(sessionDetail);\n }\n }\n}\n","import { Client } from \"../client/Client\";\nimport { State, isState } from \"./State\";\nimport { Action } from \"./types/action\";\nimport { FetchNextState, FlowPath, Handlers } from \"./types/state-handling\";\nimport { HankoError } from \"../Errors\";\n\ntype ExtendedHandlers = Handlers & { onError?: (e: unknown) => any };\n\n// eslint-disable-next-line require-jsdoc\nclass Flow extends Client {\n public async init(\n initPath: FlowPath,\n handlers: ExtendedHandlers,\n ): Promise<void> {\n const fetchNextState: FetchNextState = async (href: string, body?: any) => {\n try {\n const response = await this.client.post(href, body);\n return new State(response.json(), fetchNextState);\n } catch (e) {\n handlers.onError?.(e);\n }\n };\n\n const initState = await fetchNextState(initPath);\n await this.run(initState, handlers);\n }\n\n public async fromString(init: string, handlers: ExtendedHandlers) {\n const fetchNextState: FetchNextState = async (href: string, body?: any) => {\n try {\n const response = await this.client.post(href, body);\n return new State(response.json(), fetchNextState);\n } catch (e) {\n handlers.onError?.(e);\n }\n };\n\n const initState = new State(JSON.parse(init), fetchNextState);\n await this.run(initState, handlers);\n }\n\n /**\n * Runs a handler for a given state.\n *\n * If the handler returns an action or a state, this method will run the next\n * appropriate handler for that state. (Recursively)\n *\n * If the handlers passed to `init` do not contain an `onError` handler,\n * this method will throw.\n *\n * @see InvalidStateError\n * @see HandlerNotFoundError\n *\n * @example\n * const handlerResult = await run(\"/login\", {\n * // all login handlers are in here, one of which will be called\n * // based on what the /login endpoint returns\n * });\n */\n run = async (\n state: State<any>,\n handlers: ExtendedHandlers,\n ): Promise<unknown> => {\n try {\n if (!isState(state)) {\n throw new InvalidStateError(state);\n }\n\n const handler = handlers[state.name];\n if (!handler) {\n throw new HandlerNotFoundError(state);\n }\n\n let maybeNextState = await handler(state);\n\n // handler can return an action, which we'll run (and turn into state)...\n if (isAction(maybeNextState)) {\n maybeNextState = await (maybeNextState as any).run();\n }\n\n // ...or a state, to continue the \"run loop\"\n if (isState(maybeNextState)) {\n return this.run(maybeNextState, handlers);\n }\n } catch (e) {\n if (typeof handlers.onError === \"function\") {\n return handlers.onError(e);\n }\n }\n };\n}\n\nexport class HandlerNotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(public state: State<any>) {\n super(\n `No handler found for state: ${\n typeof state.name === \"string\"\n ? `\"${state.name}\"`\n : `(${typeof state.name})`\n }`,\n \"handlerNotFoundError\",\n );\n Object.setPrototypeOf(this, HandlerNotFoundError.prototype);\n }\n}\n\nexport class InvalidStateError extends Error {\n constructor(public state: State<any>) {\n super(\n `Invalid state: ${\n typeof state.name === \"string\"\n ? `\"${state.name}\"`\n : `(${typeof state.name})`\n }`,\n );\n }\n}\n\nexport function isAction(x: any): x is Action<unknown> {\n return typeof x === \"object\" && x !== null && \"href\" in x && \"inputs\" in x;\n}\n\nexport { Flow };\n","import { Client } from \"./Client\";\nimport { SessionCheckResponse } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of sessions.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class SessionClient extends Client {\n /**\n * Checks if the current session is still valid.\n *\n * @return {Promise<SessionCheckResponse>}\n * @throws {TechnicalError}\n */\n async isValid(): Promise<SessionCheckResponse> {\n const response = await this.client.get(\"/sessions/validate\");\n\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n}\n","import { EnterpriseClient } from \"./lib/client/EnterpriseClient\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { EmailClient } from \"./lib/client/EmailClient\";\nimport { ThirdPartyClient } from \"./lib/client/ThirdPartyClient\";\nimport { TokenClient } from \"./lib/client/TokenClient\";\nimport { Listener } from \"./lib/events/Listener\";\nimport { Relay } from \"./lib/events/Relay\";\nimport { Session } from \"./lib/Session\";\nimport { CookieSameSite } from \"./lib/Cookie\";\nimport { Flow } from \"./lib/flow-api/Flow\";\nimport { SessionClient } from \"./lib/client/SessionClient\";\n\n/**\n * The options for the Hanko class\n *\n * @interface\n * @property {number=} timeout - The http request timeout in milliseconds. Defaults to 13000ms\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\"\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite - Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n * @property {string=} localStorageKey - The prefix / name of the local storage keys. Defaults to \"hanko\"\n * @property {string=} lang - Used to convey the preferred language to the API, e.g. for translating outgoing emails.\n * It is transmitted to the API in a custom header (X-Language).\n * Should match one of the supported languages (\"bn\", \"de\", \"en\", \"fr\", \"it, \"pt-BR\", \"zh\")\n * if email delivery by Hanko is enabled. If email delivery by Hanko is disabled and the\n * relying party configures a webhook for the \"email.send\" event, then the set language is\n * reflected in the payload of the token contained in the webhook request.\n */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: string;\n lang?: string;\n}\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @extends {Listener}\n * @param {string} api - The URL of your Hanko API instance\n * @param {HankoOptions=} options - The options that can be used\n */\nclass Hanko extends Listener {\n api: string;\n user: UserClient;\n email: EmailClient;\n thirdParty: ThirdPartyClient;\n enterprise: EnterpriseClient;\n token: TokenClient;\n sessionClient: SessionClient;\n relay: Relay;\n session: Session;\n flow: Flow;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options?: HankoOptions) {\n super();\n const opts: InternalOptions = {\n timeout: 13000,\n cookieName: \"hanko\",\n localStorageKey: \"hanko\",\n };\n if (options?.cookieName !== undefined) {\n opts.cookieName = options.cookieName;\n }\n if (options?.timeout !== undefined) {\n opts.timeout = options.timeout;\n }\n if (options?.localStorageKey !== undefined) {\n opts.localStorageKey = options.localStorageKey;\n }\n if (options?.cookieDomain !== undefined) {\n opts.cookieDomain = options.cookieDomain;\n }\n if (options?.cookieSameSite !== undefined) {\n opts.cookieSameSite = options.cookieSameSite;\n }\n if (options?.lang !== undefined) {\n opts.lang = options.lang;\n }\n\n this.api = api;\n /**\n * @public\n * @type {UserClient}\n */\n this.user = new UserClient(api, opts);\n /**\n * @public\n * @type {EmailClient}\n */\n this.email = new EmailClient(api, opts);\n /**\n * @public\n * @type {ThirdPartyClient}\n */\n this.thirdParty = new ThirdPartyClient(api, opts);\n /**\n * @public\n * @type {EnterpriseClient}\n */\n this.enterprise = new EnterpriseClient(api, opts);\n /**\n * @public\n * @type {TokenClient}\n */\n this.token = new TokenClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.sessionClient = new SessionClient(api, opts);\n /**\n * @public\n * @type {Relay}\n */\n this.relay = new Relay({ ...opts });\n /**\n * @public\n * @type {Session}\n */\n this.session = new Session({ ...opts });\n /**\n * @public\n * @type {Flow}\n */\n this.flow = new Flow(api, opts);\n }\n\n /**\n * Sets the preferred language on the underlying sub-clients. The clients'\n * base HttpClient uses this language to transmit an X-Language header to the\n * API which is then used to e.g. translate outgoing emails.\n *\n * @public\n * @param lang {string} - The preferred language to convey to the API.\n */\n setLang(lang: string) {\n this.flow.client.lang = lang;\n }\n}\n\n// eslint-disable-next-line require-jsdoc\nexport interface InternalOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey: string;\n lang?: string;\n}\n\nexport { Hanko };\n","/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n\n /**\n * Checks whether autofill assisted requests are supported.\n *\n * @return Promise<boolean>\n */\n static async isConditionalMediationAvailable(): Promise<boolean> {\n if (\n // @ts-ignore\n window.PublicKeyCredential &&\n // @ts-ignore\n window.PublicKeyCredential.isConditionalMediationAvailable\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isConditionalMediationAvailable();\n }\n\n return false;\n }\n}\n\nexport { WebauthnSupport };\n"],"names":["HankoError","_Error","message","code","cause","_this","call","this","Object","setPrototypeOf","prototype","_inheritsLoose","Error","TechnicalError","_HankoError","_this2","_assertThisInitialized","ConflictError","_HankoError2","userID","_this3","RequestTimeoutError","_this4","_HankoError3","_HankoError4","WebauthnRequestCancelledError","_this5","InvalidPasswordError","_HankoError5","_this6","InvalidPasscodeError","_HankoError6","_this7","InvalidWebauthnCredentialError","_HankoError7","_this8","PasscodeExpiredError","_HankoError8","_this9","MaxNumOfPasscodeAttemptsReachedError","_HankoError9","_this10","NotFoundError","_this11","_HankoError10","_HankoError11","TooManyRequestsError","retryAfter","_this12","UnauthorizedError","_HankoError12","_this13","ForbiddenError","_HankoError13","_this14","UserVerificationError","_HankoError14","_this15","MaxNumOfEmailAddressesReachedError","_HankoError15","_this16","EmailAddressAlreadyExistsError","_HankoError16","_this17","ThirdPartyError","_this18","_HankoError17","State","key","ls","_proto","read","store","data","localStorage","getItem","decoded","decodeURIComponent","decodeURI","window","atob","JSON","parse","e","write","stringify","btoa","encodeURI","encodeURIComponent","setItem","encoded","timeToRemainingSeconds","time","Math","floor","Date","now","remainingSecondsToTime","seconds","_State","SessionState","options","localStorageKey","getState","_this$ls","session","expiry","authFlowCompleted","getExpirationSeconds","setExpirationSeconds","getAuthFlowCompleted","setAuthFlowCompleted","completed","reset","sessionCreatedType","sessionExpiredType","userDeletedType","CustomEventWithDetail","_CustomEvent","type","detail","_wrapNativeSuper","CustomEvent","Dispatcher","_dispatchEvent","document","dispatchEvent","bind","_sessionState","_extends","dispatch","dispatchSessionCreatedEvent","dispatchSessionExpiredEvent","dispatchUserLoggedOutEvent","userLoggedOutType","dispatchUserDeletedEvent","assign","target","i","arguments","length","source","ValidationReason","api","init","converter","defaultAttributes","set","name","value","attributes","expires","toUTCString","replace","escape","stringifiedAttributes","attributeName","split","cookie","create","get","cookies","jar","parts","slice","join","found","remove","withAttributes","withConverter","freeze","path","Cookie","_options$cookieSameSi","authCookieName","authCookieDomain","authCookieSameSite","cookieName","cookieDomain","cookieSameSite","getAuthCookie","JSCookie","setAuthCookie","token","defaults","secure","sameSite","undefined","domain","o","removeAuthCookie","Headers","xhr","_xhr","getResponseHeader","Response","headers","ok","status","statusText","url","_decodedJSON","responseURL","json","HttpClient","response","parseNumericHeader","result","parseInt","isNaN","timeout","sessionState","dispatcher","lang","_fetch","XMLHttpRequest","bearerToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","self","processHeaders","onerror","ontimeout","send","body","toString","_proto3","expirationSeconds","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","jwt","retention","https","RegExp","match","location","href","getTime","post","put","patch","Client","client","EnterpriseClient","getDomain","email","emailParts","trim","hasProvider","then","resp","auth","redirectTo","URL","searchParams","append","getError","params","URLSearchParams","search","error","errorDescription","UserClient","getInfo","getCurrent","meResponse","me","id","userResponse","logout","logoutResponse","EmailClient","_Client","apply","list","address","setPrimaryEmail","emailID","ThirdPartyClient","provider","validate","history","replaceState","pathname","TokenClient","Throttle","throttle","func","wait","context","args","timeoutID","_options$leading","leading","_options$trailing","trailing","previous","remaining","clearTimeout","setTimeout","executeThrottledFunction","throttleLimit","_addEventListener","addEventListener","_removeEventListener","removeEventListener","_throttle","wrapCallback","callback","event","wrappedCallback","addEventListenerWithType","once","_ref$once","_ref$throttle","mapAddEventListenerParams","_ref2","Listener","onSessionCreated","onSessionExpired","onUserLoggedOut","onUserDeleted","Scheduler","_tasks","removeTask","task","filter","_task","removeTasksWithType","scheduleTask","timeoutSeconds","push","Session","_cookie","_get","isValid","isAuthFlowCompleted","Relay","_Dispatcher","_listener","_scheduler","_session","scheduleSessionExpiredEvent","cancelSessionExpiredEvent","handleStorageEvent","sessionDetail","listenEventDependencies","_ref","fetchNextState","payload","actions","csrf_token","defineProperty","_createActionsProxy","_createActionsProxy2","_actionDefinitions","writable","_classPrivateFieldLooseBase","toJSON","runAction","action","csrfToken","inputs","input","inputName","input_data","validateAction","_loop","reason","wanted","actual","ValidationError","required","Required","min_length","max_length","InvalidInputDefinition","MinLength","MaxLength","prop","originalAction","newInputs","tryValidate","run","actionInputs","opts","isState","x","Boolean","Flow","_len","Array","_key","concat","state","handlers","_catch","InvalidStateError","handler","HandlerNotFoundError","maybeNextState","_temp2","_temp","_maybeNextState$run","onError","initPath","initState","fromString","SessionClient","Hanko","_Listener","user","thirdParty","enterprise","sessionClient","relay","flow","setLang","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable"],"mappings":"6xDAUeA,IAAAA,eAKb,SAAAC,GAAA,SAAAD,EAAsBE,EAAiBC,EAAcC,GACnD,IAAAC,EAWkD,OAXlDA,EAAAJ,EAAAK,KAAAC,KAAML,UALRC,UACAC,EAAAA,EAAAA,WASE,EAAAC,EAAKF,KAAOA,EAKZE,EAAKD,MAAQA,EACbI,OAAOC,eAAqBT,EAAAA,GAAAA,EAAWU,WACzCL,CAAA,CAAC,OAbDM,EAAAX,EAAAC,KAAA,gBALgCW,QA6BbC,e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AAA,IACjC,YACiCxP,IAA/B5G,OAAOiW,qBAEPjW,OAAOiW,oBAAoBI,oCAG3B3N,QAAAC,QAAO3I,OAAOiW,oBAAoBI,uCAG7B3N,QAAAC,QAAAnN,KAAKsa,YAQDQ,CAPZ,MAOYA,GAAAA,OAAAA,QAAAA,OAAAA,EAAAA,CAAAA,EAAAA,EAAAA,gCAA+B,WAAA,IAC1C,OAEEtW,OAAOiW,qBAEPjW,OAAOiW,oBAAoBK,gCAGpBtW,QAAAA,QAAAA,OAAOiW,oBAAoBK,mCAGpC5N,QAAAC,SAAO,EACR,CAAA,MAAAvI,GAAA,OAAAsI,QAAAE,OAAAxI,EAAA,CAAA,EAAAyV,CAAA,CA5DMC"}
|
|
1
|
+
{"version":3,"file":"sdk.module.js","sources":["../src/lib/Errors.ts","../src/lib/events/CustomEvents.ts","../src/lib/events/Dispatcher.ts","../../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/flow-api/State.ts","../src/lib/Cookie.ts","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/EnterpriseClient.ts","../src/lib/client/UserClient.ts","../src/lib/client/EmailClient.ts","../src/lib/client/ThirdPartyClient.ts","../src/lib/client/TokenClient.ts","../src/lib/Throttle.ts","../src/lib/events/Listener.ts","../src/lib/client/SessionClient.ts","../src/lib/events/SessionState.ts","../src/lib/events/WindowActivityManager.ts","../src/lib/events/Scheduler.ts","../src/lib/events/SessionChannel.ts","../src/lib/events/Relay.ts","../src/lib/flow-api/Flow.ts","../src/Hanko.ts","../src/lib/WebauthnSupport.ts"],"sourcesContent":["/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause,\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\n/**\n * A 'ForbiddenError' occurs when the user is not allowed to perform the requested action.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ForbiddenError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Forbidden error\", \"forbidden\", cause);\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * A 'UserVerificationError' occurs when the user verification requirements\n * for a WebAuthn ceremony are not met.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UserVerificationError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"User verification error\", \"userVerification\", cause);\n Object.setPrototypeOf(this, UserVerificationError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfEmailAddressesReachedError' occurs when the user tries to add a new email address while the maximum number\n * of email addresses (see backend configuration) equals the number of email addresses already registered.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfEmailAddressesReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of email addresses reached error\",\n \"maxNumOfEmailAddressesReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfEmailAddressesReachedError.prototype);\n }\n}\n\n/**\n * An 'EmailAddressAlreadyExistsError' occurs when the user tries to add a new email address which already exists.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass EmailAddressAlreadyExistsError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"The email address already exists\",\n \"emailAddressAlreadyExistsError\",\n cause,\n );\n Object.setPrototypeOf(this, EmailAddressAlreadyExistsError.prototype);\n }\n}\n\n/**\n * A `ThirdPartyError` may occur during a sign in/sign up with a third party\n * provider.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ThirdPartyError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(code: string, cause?: Error) {\n super(\"An error occurred during third party sign up/sign in\", code, cause);\n Object.setPrototypeOf(this, ThirdPartyError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n ForbiddenError,\n UserVerificationError,\n MaxNumOfEmailAddressesReachedError,\n EmailAddressAlreadyExistsError,\n ThirdPartyError,\n};\n","import { Claims } from \"../Dto\";\n\n/**\n * The type of the `hanko-session-created` event.\n * @typedef {string} sessionCreatedType\n * @memberOf Listener\n */\nexport const sessionCreatedType: \"hanko-session-created\" =\n \"hanko-session-created\";\n\n/**\n * The type of the `hanko-session-expired` event.\n * @typedef {string} sessionExpiredType\n * @memberOf Listener\n */\nexport const sessionExpiredType: \"hanko-session-expired\" =\n \"hanko-session-expired\";\n\n/**\n * The type of the `hanko-user-logged-out` event.\n * @typedef {string} userLoggedOutType\n * @memberOf Listener\n */\nexport const userLoggedOutType: \"hanko-user-logged-out\" =\n \"hanko-user-logged-out\";\n\n/**\n * The type of the `hanko-user-deleted` event.\n * @typedef {string} userDeletedType\n * @memberOf Listener\n */\nexport const userDeletedType: \"hanko-user-deleted\" = \"hanko-user-deleted\";\n\n/**\n * The type of the `hanko-user-logged-in` event.\n * @typedef {string} userLoggedInType\n * @memberOf Listener\n */\nexport const userLoggedInType: \"hanko-user-logged-in\" = \"hanko-user-logged-in\";\n\n/**\n * The type of the `hanko-user-created` event.\n * @typedef {string} userCreatedType\n * @memberOf Listener\n */\nexport const userCreatedType: \"hanko-user-created\" = \"hanko-user-created\";\n\n/**\n * The data passed in the `hanko-session-created` or `hanko-session-resumed` event.\n *\n * @interface\n * @category SDK\n * @subcategory Events\n * @property {number} expirationSeconds - This property is deprecated. The number of seconds until the JWT expires.\n * @property {Claims} claims - The JSON web token associated with the session. Only present when the Hanko-API allows the JWT to be accessible client-side.\n */\nexport interface SessionDetail {\n claims: Claims;\n expirationSeconds: number; // deprecated\n}\n\n/**\n * A custom event that includes a detail object.\n *\n * @category SDK\n * @subcategory Events\n * @extends CustomEvent\n * @ignore\n * @param {string} type - The type of the event.\n * @param {T} detail - The detail object to include in the event.\n */\nexport class CustomEventWithDetail<T> extends CustomEvent<T> {\n // eslint-disable-next-line require-jsdoc\n constructor(type: string, detail: T) {\n super(type, { detail });\n }\n}\n","import {\n SessionDetail,\n CustomEventWithDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n} from \"./CustomEvents\";\n\n/**\n * A class that dispatches custom events.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class Dispatcher {\n _dispatchEvent = document.dispatchEvent.bind(document);\n\n /**\n * Dispatches a custom event.\n *\n * @param {string} type\n * @param {T} detail\n * @private\n */\n private dispatch<T>(type: string, detail: T) {\n this._dispatchEvent(new CustomEventWithDetail(type, detail));\n }\n\n /**\n * Dispatches a \"hanko-session-created\" event to the document with the specified detail.\n *\n * @param {SessionDetail} detail - The event detail.\n */\n public dispatchSessionCreatedEvent(detail: SessionDetail) {\n this.dispatch(sessionCreatedType, detail);\n }\n\n /**\n * Dispatches a \"hanko-session-expired\" event to the document.\n */\n public dispatchSessionExpiredEvent() {\n this.dispatch(sessionExpiredType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-logged-out\" event to the document.\n */\n public dispatchUserLoggedOutEvent() {\n this.dispatch(userLoggedOutType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-deleted\" event to the document.\n */\n public dispatchUserDeletedEvent() {\n this.dispatch(userDeletedType, null);\n }\n}\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import {\n FetchNextState,\n StateName,\n Actions,\n Payloads,\n} from \"./types/state-handling\";\nimport { Error } from \"./types/error\";\nimport { Action } from \"./types/action\";\nimport { Input } from \"./types/input\";\n\ntype InputValues<TInput extends Record<string, Input<any>>> = {\n [K in keyof TInput]?: TInput[K][\"value\"];\n};\n\ntype CreateAction<TAction extends Action<any>> = (\n inputs: InputValues<TAction[\"inputs\"]>\n) => TAction & {\n run: () => Promise<State<any>>;\n validate: () => TAction;\n tryValidate: () => ValidationError | void;\n};\n\ntype ActionFunctions = {\n [TStateName in keyof Actions]: {\n [TActionName in keyof Actions[TStateName]]: Actions[TStateName][TActionName] extends Action<\n infer Inputs\n >\n ? CreateAction<Action<Inputs>>\n : never;\n };\n};\n\ninterface StateResponse<TStateName extends StateName> {\n name: StateName;\n status: number;\n payload?: Payloads[TStateName];\n actions?: Actions[TStateName];\n csrf_token: string;\n error: Error;\n}\n\n// State class represents a state in the flow\n// eslint-disable-next-line require-jsdoc\nclass State<TStateName extends StateName>\n implements Omit<StateResponse<TStateName>, \"actions\">\n{\n readonly name: StateName;\n readonly payload?: Payloads[TStateName];\n readonly error: Error;\n readonly status: number;\n readonly csrf_token: string;\n\n readonly #actionDefinitions: Actions[TStateName];\n readonly actions: ActionFunctions[TStateName];\n\n private readonly fetchNextState: FetchNextState;\n\n toJSON() {\n return {\n name: this.name,\n payload: this.payload,\n error: this.error,\n status: this.status,\n csrf_token: this.csrf_token,\n actions: this.#actionDefinitions,\n };\n }\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n { name, payload, error, status, actions, csrf_token }: StateResponse<TStateName>,\n fetchNextState: FetchNextState\n ) {\n this.name = name;\n this.payload = payload;\n this.error = error;\n this.status = status;\n this.csrf_token = csrf_token;\n this.#actionDefinitions = actions;\n\n // We're doing something really hacky here, but hear me out\n //\n // `actions` is an object like this:\n //\n // { login_password_recovery: { inputs: { new_password: { min_length: 8, value: \"this still needs to be set\" } } } }\n //\n // However, we don't want users to have to mutate the `actions` object manually.\n // They WOULD have to do this:\n //\n // actions.login_password_recovery.inputs.new_password.value = \"password\";\n //\n // Instead, we're going to wrap the `actions` object in a Proxy.\n // This Proxy transforms the manual mutation you're seeing above into a function call.\n // The following is doing the same thing as the manual mutation above:\n //\n // actions.login_password_recovery({ new_password: \"password\" });\n //\n // Okay, there's one difference, the function call creates a copy of the action, so it's not mutating the original object.\n // The newly created action is returned. It also has a `run` method, which sends the action to the server (fetchNextState)\n this.actions = this.#createActionsProxy(actions, csrf_token);\n\n // Do not remove! `this.fetchNextState` has to be set for `this.#runAction` to work\n this.fetchNextState = fetchNextState;\n }\n\n /**\n * We get the `actions` object from the server. That object is essentially a definition of actions that can be performed in the current state.\n *\n * For example:\n *\n * actions = {\n * login_password_recovery: {\n * inputs: {\n * email: { value: undefined, required: true, ... },\n * password: { value: undefined, required: true, min_length: 8, ... }\n * }\n * },\n * create_account: { inputs: ... },\n * some_other_action: { inputs: ... },\n * };\n *\n * The proxy returned by this method creates \"action functions\".\n *\n * Each action function copies the original definition (`{ inputs: ... }`) and modifies that copy with the inputs provided by the user.\n *\n * In practice, it looks like this:\n *\n * actions.login_password_recovery({ new_password: \"very-secure-123\" });\n * // => { inputs: { password: { value: \"very-secure-123\", min_length: 8, ... }}}\n *\n * Additionally, helper methods like `run` (to send the action to the server) and `validate` (to validate the inputs; the `inputs` object also contains validation rules)\n */\n #createActionsProxy(actions: Actions[TStateName], csrfToken: string) {\n const runAction = (action: Action<any>) => this.runAction(action, csrfToken);\n const validateAction = (action: Action<any>) => this.validateAction(action);\n\n return new Proxy(actions, {\n get(target, prop): CreateAction<Action<unknown>> | undefined {\n if (typeof prop === \"symbol\") return (target as any)[prop];\n\n type Original = Actions[TStateName][keyof Actions[TStateName]];\n type Prop = keyof typeof target;\n\n /**\n * This is the action defintion.\n * Running the function returned by this getter creates a **deep copy**\n * with values set by the user.\n */\n const originalAction = target[\n prop as Prop\n ] satisfies Original as Action<unknown>;\n\n if (originalAction == null) {\n return null;\n }\n\n return (newInputs: any) => {\n const action = Object.assign(deepCopy(originalAction), {\n validate() {\n validateAction(action);\n return action;\n },\n tryValidate() {\n try {\n validateAction(action);\n } catch (e) {\n if (e instanceof ValidationError) return e;\n\n // We still want to throw non-ValidationErrors since they're unexpected (and indicate a bug on our side)\n throw e;\n }\n },\n run() {\n return runAction(action);\n },\n });\n\n // If `actions` is an object that has inputs,\n //\n // Transform this:\n // actions.login_password_recovery({ new_password: \"password\" });\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n // Into this:\n // action.inputs = { new_password: { min_length: 8, value: \"password\", ... }}\n if (\n action !== null &&\n typeof action === \"object\" &&\n \"inputs\" in action\n ) {\n for (const inputName in newInputs) {\n const actionInputs = action.inputs as Record<\n string,\n Input<unknown>\n >;\n\n if (!actionInputs[inputName]) {\n actionInputs[inputName] = { name: inputName, type: \"\" };\n }\n\n actionInputs[inputName].value = newInputs[inputName];\n }\n }\n\n return action;\n };\n },\n }) satisfies Actions[TStateName] as any;\n }\n\n runAction(action: Action<any>, csrfToken: string): Promise<State<any>> {\n const data: Record<string, any> = {};\n\n // Deal with object-type inputs\n // i.e. actions.some_action({ ... })\n // ^^^^^^^\n // Other input types would look like this:\n //\n // actions.another_action(1234);\n // actions.yet_another_action(\"foo\");\n //\n // Meaning\n if (\n \"inputs\" in action &&\n typeof action.inputs === \"object\" &&\n action.inputs !== null\n ) {\n // This looks horrible, but at this point we're sure that `action.inputs` is a Record<string, Input>\n // Because there are no object-type inputs that AREN'T a Record<string, Input>\n const inputs = action.inputs satisfies object as Record<\n string,\n Input<unknown>\n >;\n\n for (const inputName in action.inputs) {\n const input = inputs[inputName];\n\n if (input && \"value\" in input) {\n data[inputName] = input.value;\n }\n }\n }\n\n // (Possibly add more input types here?)\n\n // Use the fetch function to perform the action\n return this.fetchNextState(action.href, {\n input_data: data,\n csrf_token: csrfToken,\n });\n }\n\n validateAction(action: Action<{ [key: string]: Input<unknown> }>) {\n if (!(\"inputs\" in action)) return;\n\n for (const inputName in action.inputs) {\n const input = action.inputs[inputName];\n\n function reject<T>(\n reason: ValidationReason,\n message: string,\n wanted?: T,\n actual?: T\n ) {\n throw new ValidationError({\n reason,\n inputName,\n wanted,\n actual,\n message,\n });\n }\n\n const value = input.value as any; // TS gets in the way here\n\n // TODO is !input.value right here? this will also reject empty strings, `0`, ... and will never reject an empty array/object\n if (input.required && !value) {\n reject(ValidationReason.Required, \"is required\");\n }\n\n const hasLengthRequirement =\n input.min_length != null || input.max_length != null;\n\n if (hasLengthRequirement) {\n if (!(\"length\" in value)) {\n reject(\n ValidationReason.InvalidInputDefinition,\n 'has min/max length requirement, but is missing \"length\" property',\n \"string\",\n typeof value\n );\n }\n\n if (input.min_length != null && value < input.min_length) {\n reject(\n ValidationReason.MinLength,\n `too short (min ${input.min_length})`,\n input.min_length,\n value.length\n );\n }\n\n if (input.max_length != null && value > input.max_length) {\n reject(\n ValidationReason.MaxLength,\n `too long (max ${input.max_length})`,\n input.max_length,\n value.length\n );\n }\n }\n }\n }\n}\n\nexport enum ValidationReason {\n InvalidInputDefinition,\n MinLength,\n MaxLength,\n Required,\n}\n\nexport class ValidationError<TWanted = undefined> extends Error {\n reason: ValidationReason;\n inputName: string;\n wanted: TWanted;\n actual: TWanted;\n\n constructor(opts: {\n reason: ValidationReason;\n inputName: string;\n wanted: TWanted;\n actual: TWanted;\n message: string;\n }) {\n super(`\"${opts.inputName}\" ${opts.message}`);\n\n this.name = \"ValidationError\";\n this.reason = opts.reason;\n this.inputName = opts.inputName;\n this.wanted = opts.wanted;\n this.actual = opts.actual;\n }\n}\n\nfunction deepCopy<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj));\n}\n\nexport function isState(x: any): x is State<any> {\n return (\n typeof x === \"object\" &&\n x !== null &&\n \"status\" in x &&\n \"error\" in x &&\n \"name\" in x &&\n Boolean(x.name) &&\n Boolean(x.status)\n );\n}\n\nexport { State };\n","import JSCookie, { CookieAttributes } from \"js-cookie\";\nimport { TechnicalError } from \"./Errors\";\n\n/**\n * Options for Cookie\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite -Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n */\ninterface CookieOptions {\n cookieName: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n}\n\nexport type CookieSameSite =\n | \"strict\"\n | \"Strict\"\n | \"lax\"\n | \"Lax\"\n | \"none\"\n | \"None\";\n\n/**\n * A class to manage cookies.\n *\n * @category SDK\n * @subcategory Internal\n * @param {CookieOptions} options - The options that can be used\n */\nexport class Cookie {\n authCookieName: string;\n authCookieDomain?: string;\n authCookieSameSite: CookieSameSite;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: CookieOptions) {\n this.authCookieName = options.cookieName;\n this.authCookieDomain = options.cookieDomain;\n this.authCookieSameSite = options.cookieSameSite ?? \"lax\";\n }\n\n /**\n * Returns the authentication token that was stored in the cookie.\n *\n * @return {string}\n */\n getAuthCookie(): string {\n return JSCookie.get(this.authCookieName);\n }\n\n /**\n * Stores the authentication token to the cookie.\n *\n * @param {string} token - The authentication token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n */\n setAuthCookie(token: string, options?: CookieAttributes) {\n const defaults: CookieAttributes = {\n secure: true,\n sameSite: this.authCookieSameSite,\n };\n\n if (this.authCookieDomain !== undefined) {\n defaults.domain = this.authCookieDomain;\n }\n\n const o: CookieAttributes = { ...defaults, ...options };\n\n if (\n (o.sameSite === \"none\" || o.sameSite === \"None\") &&\n o.secure === false\n ) {\n throw new TechnicalError(\n new Error(\"Secure attribute must be set when SameSite=None\"),\n );\n }\n\n JSCookie.set(this.authCookieName, token, o);\n }\n\n /**\n * Removes the cookie used for authentication.\n */\n removeAuthCookie() {\n JSCookie.remove(this.authCookieName);\n }\n}\n","import { RequestTimeoutError, TechnicalError } from \"../Errors\";\nimport { Dispatcher } from \"../events/Dispatcher\";\nimport { Cookie } from \"../Cookie\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n /**\n * Returns the response header with the given name.\n *\n * @param {string} name\n * @return {string}\n */\n getResponseHeader(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n /**\n * @private\n * @type {XMLHttpRequest}\n */\n this.xhr = xhr;\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n if (!this._decodedJSON) {\n this._decodedJSON = JSON.parse(this.xhr.response);\n }\n return this._decodedJSON;\n }\n\n /**\n * Returns the response header value with the given `name` as a number. When the value is not a number the return\n * value will be 0.\n *\n * @param {string} name - The name of the header field\n * @return {number}\n */\n parseNumericHeader(name: string): number {\n const result = parseInt(this.headers.getResponseHeader(name), 10);\n return isNaN(result) ? 0 : result;\n }\n}\n\n/**\n * Options for the HttpClient\n *\n * @category SDK\n * @subcategory Internal\n * @property {number} timeout - The http request timeout in milliseconds.\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string} localStorageKey - The prefix / name of the local storage keys.\n * @property {string} lang - The language used by the client(s) to convey to the Hanko API the language to use -\n * e.g. for translating outgoing emails - in a custom header (X-Language).\n */\nexport interface HttpClientOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n localStorageKey: string;\n lang?: string;\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options the HttpClient must be provided\n */\nclass HttpClient {\n timeout: number;\n api: string;\n dispatcher: Dispatcher;\n cookie: Cookie;\n lang: string;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n this.api = api;\n this.timeout = options.timeout;\n this.dispatcher = new Dispatcher();\n this.cookie = new Cookie({ ...options });\n this.lang = options.lang;\n }\n\n // eslint-disable-next-line require-jsdoc\n _fetch(path: string, options: RequestInit, xhr = new XMLHttpRequest()) {\n const self = this;\n const url = this.api + path;\n const timeout = this.timeout;\n const bearerToken = this.cookie.getAuthCookie();\n const lang = this.lang;\n\n return new Promise<Response>(function (resolve, reject) {\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n xhr.setRequestHeader(\"X-Language\", lang);\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n self.processHeaders(xhr);\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n // This function is to be removed along with the \"Session.isValid()\" function, where it is used to check the\n // session without returning a promise.\n _fetch_blocking(\n path: string,\n options: RequestInit,\n xhr = new XMLHttpRequest(),\n ) {\n const url = this.api + path;\n const bearerToken = this.cookie.getAuthCookie();\n\n xhr.open(options.method, url, false);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.withCredentials = true;\n xhr.send(options.body ? options.body.toString() : null);\n\n return xhr.responseText;\n }\n /**\n * Processes the response headers on login and extracts the JWT and expiration time.\n *\n * @param {XMLHttpRequest} xhr - The xhr object.\n */\n processHeaders(xhr: XMLHttpRequest) {\n let jwt = \"\";\n let expirationSeconds = 0;\n let retention = \"\";\n\n xhr\n .getAllResponseHeaders()\n .split(\"\\r\\n\")\n .forEach((h) => {\n const header = h.toLowerCase();\n if (header.startsWith(\"x-auth-token\")) {\n jwt = xhr.getResponseHeader(\"X-Auth-Token\");\n } else if (header.startsWith(\"x-session-lifetime\")) {\n expirationSeconds = parseInt(\n xhr.getResponseHeader(\"X-Session-Lifetime\"),\n 10,\n );\n } else if (header.startsWith(\"x-session-retention\")) {\n retention = xhr.getResponseHeader(\"X-Session-Retention\");\n }\n });\n\n if (jwt) {\n const https = new RegExp(\"^https://\");\n const secure =\n !!this.api.match(https) && !!window.location.href.match(https);\n\n const expires =\n retention === \"session\"\n ? undefined\n : new Date(new Date().getTime() + expirationSeconds * 1000);\n\n this.cookie.setAuthCookie(jwt, { secure, expires });\n }\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PATCH request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n patch(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PATCH\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a DELETE request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n delete(path: string) {\n return this._fetch(path, {\n method: \"DELETE\",\n });\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient, HttpClientOptions } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options that can be used\n */\nabstract class Client {\n client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n /**\n * @public\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, options);\n }\n}\n\nexport { Client };\n","import { Client } from \"./Client\";\nimport { NotFoundError, TechnicalError, ThirdPartyError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of authenticating through a third party provider.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class EnterpriseClient extends Client {\n /**\n * Extracts the domain from an email address\n * @param {string} email E-Mail address of the user from which the domain will be extracted.\n * @throws {ThirdPartyError}\n * @private\n */\n private getDomain(email: string): string {\n if (!email) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email missing from request\"),\n );\n }\n\n const emailParts = email.split(\"@\");\n if (emailParts.length !== 2) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email is not in a valid email format.\"),\n );\n }\n\n const domain = emailParts[1].trim();\n if (domain === \"\") {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"email is not in a valid email format.\"),\n );\n }\n\n return domain;\n }\n\n /**\n * Performs a request to the Hanko API to check if there is a provider for the users e-mail domain\n *\n * @param {string} email - E-Mail address of the user to login\n */\n async hasProvider(email: string): Promise<boolean> {\n const domain = this.getDomain(email);\n\n return this.client.get(`/saml/provider?domain=${domain}`).then((resp) => {\n if (resp.status == 404) {\n throw new NotFoundError(new Error(\"provider not found\"));\n }\n\n if (!resp.ok) {\n throw new TechnicalError(new Error(\"unable to fetch provider\"));\n }\n\n return resp.ok;\n });\n }\n\n /**\n * Performs a request to the Hanko API that redirects to the given\n * third party provider.\n *\n * @param {string} email - E-Mail address of the user\n * @param {string} redirectTo - The URL to redirect to after a successful third party authentication\n * @throws {ThirdPartyError}\n * @see http://docs.hanko.io/api/public#tag/Third-Party/operation/enterpriseAuth\n */\n auth(email: string, redirectTo: string): void {\n const url = new URL(\"/saml/auth\", this.client.api);\n const domain = this.getDomain(email);\n\n if (!redirectTo) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"redirectTo missing from request\"),\n );\n }\n\n url.searchParams.append(\"domain\", domain);\n url.searchParams.append(\"redirect_to\", redirectTo);\n\n window.location.assign(url.href);\n }\n\n /**\n * Get a third party error from the current location's query params.\n * @returns {(ThirdPartyError|undefined)} The ThirdPartyError.\n */\n getError() {\n const params = new URLSearchParams(window.location.search);\n const error = params.get(\"error\");\n const errorDescription = params.get(\"error_description\");\n if (error) {\n let code;\n switch (error) {\n case \"access_denied\":\n code = \"enterpriseAccessDenied\";\n break;\n case \"user_conflict\":\n code = \"emailAddressAlreadyExistsError\";\n break;\n case \"multiple_accounts\":\n code = \"enterpriseMultipleAccounts\";\n break;\n case \"unverified_email\":\n code = \"enterpriseUnverifiedEmail\";\n break;\n case \"email_maxnum\":\n code = \"maxNumOfEmailAddressesReached\";\n break;\n default:\n code = \"somethingWentWrong\";\n }\n\n return new ThirdPartyError(code, new Error(errorDescription));\n }\n }\n}\n","import { Me, User, UserInfo, UserCreated } from \"../Dto\";\nimport {\n ConflictError,\n NotFoundError,\n TechnicalError,\n UnauthorizedError,\n ForbiddenError,\n} from \"../Errors\";\nimport { Client } from \"./Client\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches basic information about the user identified by the given email address. Can be used while the user is logged out\n * and is helpful in deciding which type of login to choose. For example, if the user's email is not verified, you may\n * want to log in with a passcode, or if no WebAuthn credentials are registered, you may not want to use WebAuthn.\n *\n * @param {string} email - The user's email address.\n * @return {Promise<UserInfo>}\n * @throws {NotFoundError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/getUserId\n */\n async getInfo(email: string): Promise<UserInfo> {\n const response = await this.client.post(\"/user\", { email });\n\n if (response.status === 404) {\n throw new NotFoundError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Creates a new user. Afterwards, verify the email address via passcode. If a 'ConflictError'\n * occurred, you may want to prompt the user to log in.\n *\n * @param {string} email - The email address of the user to be created.\n * @return {Promise<UserCreated>}\n * @throws {ConflictError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/createUser\n */\n async create(email: string): Promise<UserCreated> {\n const response = await this.client.post(\"/users\", { email });\n\n if (response.status === 409) {\n throw new ConflictError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n async getCurrent(): Promise<User> {\n const meResponse = await this.client.get(\"/me\");\n\n if (meResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!meResponse.ok) {\n throw new TechnicalError();\n }\n\n const me: Me = meResponse.json();\n const userResponse = await this.client.get(`/users/${me.id}`);\n\n if (userResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!userResponse.ok) {\n throw new TechnicalError();\n }\n\n return userResponse.json();\n }\n\n /**\n * Deletes the current user and expires the existing session cookie.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n */\n async delete(): Promise<void> {\n const response = await this.client.delete(\"/user\");\n\n if (response.ok) {\n this.client.cookie.removeAuthCookie();\n this.client.dispatcher.dispatchUserDeletedEvent();\n return;\n } else if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n }\n\n throw new TechnicalError();\n }\n\n /**\n * Logs out the current user and expires the existing session cookie. A valid session cookie is required to call the logout endpoint.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n async logout(): Promise<void> {\n const logoutResponse = await this.client.post(\"/logout\");\n\n // For cross-domain operations, the frontend SDK creates the cookie by reading the \"X-Auth-Token\" header, and\n // \"Set-Cookie\" headers sent by the backend have no effect due to the browser's security policy, which means that\n // the cookie must also be removed client-side in that case.\n this.client.cookie.removeAuthCookie();\n this.client.dispatcher.dispatchUserLoggedOutEvent();\n\n if (logoutResponse.status === 401) {\n // The user is logged out already\n return;\n } else if (!logoutResponse.ok) {\n throw new TechnicalError();\n }\n }\n}\n\nexport { UserClient };\n","import { Client } from \"./Client\";\nimport {\n EmailAddressAlreadyExistsError,\n MaxNumOfEmailAddressesReachedError,\n TechnicalError,\n UnauthorizedError,\n} from \"../Errors\";\nimport { Email, Emails } from \"../Dto\";\n\n/**\n * Manages email addresses of the current user.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass EmailClient extends Client {\n /**\n * Returns a list of all email addresses assigned to the current user.\n *\n * @return {Promise<Emails>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/listEmails\n */\n async list(): Promise<Emails> {\n const response = await this.client.get(\"/emails\");\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n\n /**\n * Adds a new email address to the current user.\n *\n * @param {string} address - The email address to be added.\n * @return {Promise<Email>}\n * @throws {EmailAddressAlreadyExistsError}\n * @throws {MaxNumOfEmailAddressesReachedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/createEmail\n */\n async create(address: string): Promise<Email> {\n const response = await this.client.post(\"/emails\", { address });\n\n if (response.ok) {\n return response.json();\n }\n\n if (response.status === 400) {\n throw new EmailAddressAlreadyExistsError();\n } else if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (response.status === 409) {\n throw new MaxNumOfEmailAddressesReachedError();\n }\n\n throw new TechnicalError();\n }\n\n /**\n * Marks the specified email address as primary.\n *\n * @param {string} emailID - The ID of the email address to be updated\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/setPrimaryEmail\n */\n async setPrimaryEmail(emailID: string): Promise<void> {\n const response = await this.client.post(`/emails/${emailID}/set_primary`);\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return;\n }\n\n /**\n * Deletes the specified email address.\n *\n * @param {string} emailID - The ID of the email address to be deleted\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @throws {UnauthorizedError}\n * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/deleteEmail\n */\n async delete(emailID: string): Promise<void> {\n const response = await this.client.delete(`/emails/${emailID}`);\n\n if (response.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!response.ok) {\n throw new TechnicalError();\n }\n\n return;\n }\n}\n\nexport { EmailClient };\n","import { Client } from \"./Client\";\nimport { ThirdPartyError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of authenticating through a third party provider.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class ThirdPartyClient extends Client {\n /**\n * Performs a request to the Hanko API that redirects to the given\n * third party provider.\n *\n * @param {string} provider - The name of the third party provider\n * @param {string} redirectTo - The URL to redirect to after a successful third party authentication\n * @throws {ThirdPartyError}\n * @see http://docs.hanko.io/api/public#tag/Third-Party/operation/thirdPartyAuth\n */\n async auth(provider: string, redirectTo: string): Promise<void> {\n const url = new URL(\"/thirdparty/auth\", this.client.api);\n\n if (!provider) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"provider missing from request\"),\n );\n }\n\n if (!redirectTo) {\n throw new ThirdPartyError(\n \"somethingWentWrong\",\n new Error(\"redirectTo missing from request\"),\n );\n }\n\n url.searchParams.append(\"provider\", provider);\n url.searchParams.append(\"redirect_to\", redirectTo);\n\n window.location.assign(url.href);\n }\n\n /**\n * Get a third party error from the current location's query params.\n * @returns {(ThirdPartyError|undefined)} The ThirdPartyError.\n */\n getError() {\n const params = new URLSearchParams(window.location.search);\n const error = params.get(\"error\");\n const errorDescription = params.get(\"error_description\");\n if (error) {\n let code = \"\";\n switch (error) {\n case \"access_denied\":\n code = \"thirdPartyAccessDenied\";\n break;\n case \"user_conflict\":\n code = \"emailAddressAlreadyExistsError\";\n break;\n case \"multiple_accounts\":\n code = \"thirdPartyMultipleAccounts\";\n break;\n case \"unverified_email\":\n code = \"thirdPartyUnverifiedEmail\";\n break;\n case \"email_maxnum\":\n code = \"maxNumOfEmailAddressesReached\";\n break;\n case \"signup_disabled\":\n code = \"signupDisabled\";\n break;\n default:\n code = \"somethingWentWrong\";\n }\n\n return new ThirdPartyError(code, new Error(errorDescription));\n }\n }\n}\n","import { Client } from \"./Client\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * Client responsible for exchanging one time tokens for session JWTs.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class TokenClient extends Client {\n /**\n * Validate a one time token to retrieve a session JWT. Does nothing\n * if the current window location does not contain a 'hanko_token' in the\n * search query.\n *\n * @return {Promise<void>}\n * @throws {TechnicalError}\n * https://docs.hanko.io/api/api/public#tag/Token/operation/token\n */\n async validate(): Promise<void> {\n const params = new URLSearchParams(window.location.search);\n const token = params.get(\"hanko_token\");\n\n if (!token) return;\n\n window.history.replaceState(null, null, window.location.pathname);\n\n const response = await this.client.post(\"/token\", { value: token });\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return response.json();\n }\n}\n","/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {boolean=} leading - Whether to allow the function to be called on the leading edge of the wait timeout.\n * @property {boolean=} trailing - Whether to allow the function to be called on the trailing edge of the wait timeout.\n */\ninterface ThrottleOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\n// eslint-disable-next-line no-unused-vars\ntype ThrottledFunction<T extends (...args: any[]) => any> = (\n // eslint-disable-next-line no-unused-vars\n ...args: Parameters<T>\n) => void;\n\n/**\n * Provides throttle functionality.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Internal\n */\nexport class Throttle {\n /**\n * Throttles a function, ensuring that it can only be called once per `wait` milliseconds.\n *\n * @static\n * @param {function} func - The function to throttle.\n * @param {number} wait - The number of milliseconds to wait between function invocations.\n * @param {ThrottleOptions} options - Optional configuration for the throttle.\n * @returns {function} A throttled version of the original function.\n */\n // eslint-disable-next-line no-unused-vars,require-jsdoc\n static throttle<T extends (...args: any[]) => any>(\n func: T,\n wait: number,\n options: ThrottleOptions = {},\n ): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let context: any;\n let args: any;\n let timeoutID: number;\n let previous = 0;\n\n // This function is used to invoke the original function.\n const executeThrottledFunction = () => {\n // If 'leading' is false and this is not the first invocation of the throttled function, set 'previous' to 0 to\n // ensure that the function is not called immediately.\n previous = leading === false ? 0 : Date.now();\n timeoutID = null;\n // Invoke the original function.\n func.apply(context, args);\n };\n\n // This is the throttled function that will be returned.\n const throttled = function (...funcArgs: Parameters<T>) {\n const now = Date.now();\n\n // If this is the first time the throttled function is being called, and 'leading' is false,\n // set 'previous' to the current time to ensure that the function is not called immediately.\n if (!previous && leading === false) previous = now;\n\n // The remaining wait time.\n const remaining = wait - (now - previous);\n\n // Save the context and arguments of the function call.\n // eslint-disable-next-line no-invalid-this\n context = this;\n args = funcArgs;\n\n // Check whether it's time to call the function immediately based on the leading and trailing options. If leading\n // is enabled and there was no previous invocation, or if trailing is enabled and the wait time has already passed,\n // the function will be invoked immediately.\n if (remaining <= 0 || remaining > wait) {\n // If there is a pending timeout, clear it.\n if (timeoutID) {\n window.clearTimeout(timeoutID);\n timeoutID = null;\n }\n\n // Invoke the original function and update the previous timestamp.\n previous = now;\n func.apply(context, args);\n } else if (!timeoutID && trailing !== false) {\n // If there is no pending timeout and trailing is allowed, start a new timeout.\n timeoutID = window.setTimeout(executeThrottledFunction, remaining);\n }\n };\n\n return throttled;\n }\n}\n","import { Throttle } from \"../Throttle\";\nimport {\n CustomEventWithDetail,\n SessionDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n} from \"./CustomEvents\";\n\n/**\n * A callback function to be executed when an event is triggered.\n *\n * @alias CallbackFunc\n * @typedef {function} CallbackFunc\n * @memberOf Listener\n */\n// eslint-disable-next-line no-unused-vars\ntype CallbackFunc<T> = (detail: T) => any;\n\n/**\n * A wrapped callback function that will execute the original callback.\n *\n * @ignore\n * @param {T} event - The event object passed in the event.\n */\n// eslint-disable-next-line no-unused-vars\ntype WrappedCallback<T> = (event: CustomEventWithDetail<T>) => void;\n\n/**\n * A function returned when adding an event listener. The function can be called to remove the corresponding event\n * listener.\n *\n * @alias CleanupFunc\n * @typedef {function} CleanupFunc\n * @memberOf Listener\n */\ntype CleanupFunc = () => void;\n\n/**\n * @interface\n * @ignore\n * @property {Function} callback - The function to be executed.\n * @property {boolean=} once - Whether the event listener should be removed after being called once.\n */\ninterface EventListenerParams<T> {\n callback: CallbackFunc<T>;\n once?: boolean;\n}\n\n/**\n * @interface\n * @ignore\n * @extends {EventListenerParams<T>}\n * @property {string} type - The type of the event.\n * @property {boolean=} throttle - Whether the event listener should be throttled.\n */\ninterface EventListenerWithTypeParams<T> extends EventListenerParams<T> {\n type: string;\n throttle?: boolean;\n}\n\n/**\n * A class to bind event listener for custom events.\n *\n * @category SDK\n * @subcategory Events\n */\nexport class Listener {\n public throttleLimit = 1000;\n _addEventListener = document.addEventListener.bind(document);\n _removeEventListener = document.removeEventListener.bind(document);\n _throttle = Throttle.throttle;\n\n /**\n * Wraps the given callback.\n *\n * @param callback\n * @param throttle\n * @private\n * @return {WrappedCallback}\n */\n private wrapCallback<T>(\n callback: CallbackFunc<T>,\n throttle: boolean,\n ): WrappedCallback<T> {\n // The function that will be called when the event is triggered.\n const wrappedCallback = (event: CustomEventWithDetail<T>) => {\n callback(event.detail);\n };\n\n // Throttle the listener if multiple SDK instances could trigger the same event at the same time,\n // but the callback function should only be executed once.\n if (throttle) {\n return this._throttle(wrappedCallback, this.throttleLimit, {\n leading: true,\n trailing: false,\n });\n }\n\n return wrappedCallback;\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {EventListenerWithTypeParams<T>} params - The parameters for the event listener.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListenerWithType<T>({\n type,\n callback,\n once = false,\n throttle = false,\n }: EventListenerWithTypeParams<T>): CleanupFunc {\n const wrappedCallback = this.wrapCallback(callback, throttle);\n this._addEventListener(type, wrappedCallback, { once });\n return () => this._removeEventListener(type, wrappedCallback);\n }\n\n /**\n * Maps the parameters for an event listener to the `EventListenerWithTypeParams` interface.\n *\n * @static\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean} [throttle=false] - Whether the event listener should be throttled.\n * @returns {EventListenerWithTypeParams<T>}\n **/\n private static mapAddEventListenerParams<T>(\n type: string,\n { once, callback }: EventListenerParams<T>,\n throttle?: boolean,\n ): EventListenerWithTypeParams<T> {\n return {\n type,\n callback,\n once,\n throttle,\n };\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean=} throttle - Whether the event listener should be throttled.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListener<T>(\n type: string,\n params: EventListenerParams<T>,\n throttle?: boolean,\n ) {\n return this.addEventListenerWithType(\n Listener.mapAddEventListenerParams(type, params, throttle),\n );\n }\n\n /**\n * Adds an event listener for \"hanko-session-created\" events. Will be triggered across all browser windows, when the user\n * logs in, or when the page has been loaded or refreshed and there is a valid session.\n *\n * @param {CallbackFunc<SessionDetail>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionCreated(\n callback: CallbackFunc<SessionDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionCreatedType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for \"hanko-session-expired\" events. The event will be triggered across all browser windows\n * as soon as the current JWT expires or the user logs out. It also triggers, when the user deletes the account in\n * another window.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionExpired(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionExpiredType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account in\n * the browser window where the deletion happened.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserLoggedOut(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userLoggedOutType, { callback, once });\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserDeleted(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userDeletedType, { callback, once });\n }\n}\n","import { Client } from \"./Client\";\nimport { SessionCheckResponse } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of sessions.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class SessionClient extends Client {\n /**\n * Checks if the current session is still valid.\n *\n * @return {Promise<SessionCheckResponse>}\n * @throws {TechnicalError}\n */\n async validate(): Promise<SessionCheckResponse> {\n const response = await this.client.get(\"/sessions/validate\");\n\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return await response.json();\n }\n}\n\n// Class to maintain compatibility with previous versions.\nexport class Session extends Client {\n /**\n * Checks if the current session is still valid. This function is to be removed - please replace\n * any usage with the new 'SessionClient.validate()' function.\n *\n * @return {boolean}\n * @throws {TechnicalError}\n * @deprecated\n */\n isValid(): boolean {\n let session: SessionCheckResponse;\n try {\n const response = this.client._fetch_blocking(\"/sessions/validate\", {\n method: \"GET\",\n });\n session = JSON.parse(response);\n } catch (e) {\n throw new TechnicalError(e);\n }\n return session ? session.is_valid : false;\n }\n}\n","/**\n * Represents the session state with expiration and last check timestamps.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport interface State {\n expiration: number; // Timestamp (in milliseconds) when the session expires.\n lastCheck: number; // Timestamp (in milliseconds) of the last session check.\n}\n\n/**\n * Manages session state persistence using localStorage.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class SessionState {\n private readonly storageKey: string;\n private readonly defaultState: State = {\n expiration: 0,\n lastCheck: 0,\n };\n\n /**\n * Creates an instance of SessionState.\n *\n * @param {string} storageKey - The key used to store session state in localStorage.\n */\n constructor(storageKey: string) {\n this.storageKey = storageKey;\n }\n\n /**\n * Loads the current session state from localStorage.\n *\n * @returns {State} The parsed session state or a default state if not found.\n */\n load(): State {\n const item = window.localStorage.getItem(this.storageKey);\n return item == null ? this.defaultState : JSON.parse(item);\n }\n\n /**\n * Saves the session state to localStorage.\n *\n * @param {State | null} session - The session state to save. If null, the default state is used.\n */\n save(session: State | null): void {\n window.localStorage.setItem(\n this.storageKey,\n JSON.stringify(session ? session : this.defaultState),\n );\n }\n}\n","// Callback type for handling window activity changes.\ntype Callback = () => void;\n\n/**\n * Manages window focus and blur events.\n *\n * @class\n * @category SDK\n * @subcategory Internal\n * @param {Callback} onActivityCallback - Callback to invoke when the window gains focus.\n * @param {Callback} onInactivityCallback - Callback to invoke when the window loses focus.\n */\nexport class WindowActivityManager {\n private readonly onActivityCallback: Callback; // Callback for when the window or tab gains focus.\n private readonly onInactivityCallback: Callback; // Callback for when the window or tab loses focus.\n\n // eslint-disable-next-line require-jsdoc\n constructor(onActivityCallback: Callback, onInactivityCallback: Callback) {\n this.onActivityCallback = onActivityCallback;\n this.onInactivityCallback = onInactivityCallback;\n\n // Attach event listeners for focus and blur\n window.addEventListener(\"focus\", this.handleFocus);\n window.addEventListener(\"blur\", this.handleBlur);\n document.addEventListener(\"visibilitychange\", this.handleVisibilityChange);\n }\n\n /**\n * Handles the focus event and invokes the activity callback.\n * @private\n */\n private handleFocus = (): void => {\n this.onActivityCallback();\n };\n\n /**\n * Handles the blur event and invokes the inactivity callback.\n * @private\n */\n private handleBlur = (): void => {\n this.onInactivityCallback();\n };\n\n /**\n * Handles the visibility change event and invokes appropriate callbacks.\n * @private\n */\n private handleVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\") {\n this.onActivityCallback();\n } else {\n this.onInactivityCallback();\n }\n };\n\n /**\n * Checks if the current window has focus.\n * @returns {boolean} True if the window has focus; otherwise, false.\n */\n hasFocus = (): boolean => {\n return document.hasFocus();\n };\n}\n","import { SessionCheckResponse } from \"../Dto\";\n\n// Type representing data returned by the session check callback.\nexport type SessionCheckResult =\n | (Omit<SessionCheckResponse, \"expiration_time\"> & {\n expiration: number;\n })\n | null;\n\n/**\n * Callback type for performing a session check.\n * @ignore\n */\ntype SessionCheckCallback = () => Promise<SessionCheckResult>;\n\n/**\n * Callback type for handling session timeout events.\n * @ignore\n */\ntype SessionExpiredCallback = () => void;\n\n/**\n * Manages scheduling for periodic and timeout-based session checks.\n *\n * @category SDK\n * @subcategory Internal\n * @param {number} checkInterval - The interval in milliseconds between periodic session checks.\n * @param {SessionCheckCallback} checkSession - The callback function to perform a session check.\n * @param {SessionExpiredCallback} onSessionExpired - The callback function to handle session timeout events.\n */\nexport class Scheduler {\n private intervalID: ReturnType<typeof setInterval> | null = null; // Identifier for the periodic check interval.\n private timeoutID: ReturnType<typeof setTimeout> | null = null; // Identifier for the session expiration timeout.\n private readonly checkInterval: number; // The interval between periodic session checks.\n private readonly checkSession: SessionCheckCallback; // The callback function to perform a session check.\n private readonly onSessionExpired: SessionExpiredCallback; // The callback function to handle session expired events.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n checkInterval: number,\n checkSession: SessionCheckCallback,\n onSessionExpired: SessionExpiredCallback,\n ) {\n this.checkInterval = checkInterval;\n this.checkSession = checkSession;\n this.onSessionExpired = onSessionExpired;\n }\n\n /**\n * Handles the session expiration when it is about to expire soon.\n * Stops any ongoing checks and schedules a timeout for the expiration.\n *\n * @param {number} timeToExpiration - The time in milliseconds until the session expires.\n */\n scheduleSessionExpiry(timeToExpiration: number): void {\n this.stop();\n this.timeoutID = setTimeout(async () => {\n this.stop();\n this.onSessionExpired();\n }, timeToExpiration);\n }\n\n /**\n * Starts the session check process.\n * Determines when the next check should run based on the last known check time and session expiration.\n * If the session is expiring soon, schedules an expiration event instead of starting periodic checks.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @param {number} expiration - The timestamp (in milliseconds) of when the session expires.\n */\n start(lastCheck: number = 0, expiration: number = 0): void {\n const timeToNextCheck = this.calcTimeToNextCheck(lastCheck);\n\n if (this.sessionExpiresSoon(expiration)) {\n this.scheduleSessionExpiry(timeToNextCheck);\n return;\n }\n\n // Schedule the first check after an optional delay\n this.timeoutID = setTimeout(async () => {\n let result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n return;\n }\n\n // Begin periodic checks\n this.intervalID = setInterval(async () => {\n result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n }\n } else {\n this.stop();\n }\n }, this.checkInterval);\n } else {\n this.stop();\n }\n }, timeToNextCheck);\n }\n\n /**\n * Stops the session check process and clears all timers.\n */\n stop(): void {\n if (this.timeoutID) {\n clearTimeout(this.timeoutID);\n this.timeoutID = null;\n }\n\n if (this.intervalID) {\n clearInterval(this.intervalID);\n this.intervalID = null;\n }\n }\n\n /**\n * Checks if the scheduler is currently running.\n * @returns {boolean} True if the scheduler is running; otherwise, false.\n */\n isRunning(): boolean {\n return this.timeoutID !== null || this.intervalID !== null;\n }\n /**\n * Checks if the session is about to expire.\n * @param {number} expiration - Timestamp when the session will expire.\n * @returns {boolean} True if the session is about to expire; otherwise, false.\n */\n sessionExpiresSoon(expiration: number): boolean {\n return expiration > 0 && expiration - Date.now() <= this.checkInterval;\n }\n\n /**\n * Calculates the time until the next session check should occur.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @returns {number} The time in milliseconds until the next check should be performed.\n */\n calcTimeToNextCheck(lastCheck: number): number {\n const timeSinceLastCheck = Date.now() - lastCheck;\n return this.checkInterval >= timeSinceLastCheck\n ? this.checkInterval - (timeSinceLastCheck % this.checkInterval)\n : 0;\n }\n}\n","import { Claims } from \"../Dto\";\n\n/**\n * Enum-like type defining the actions that can be broadcasted.\n *\n * @ignore\n * @category SDK\n * @subcategory Internal\n */\ntype Action = \"sessionExpired\" | \"sessionCreated\" | \"requestLeadership\";\n\n/**\n * Interface representing the data structure of a channel event.\n *\n * @interface\n * @property {Action} action - The type of action being broadcasted.\n * @property {Claims=} claims - Optional claims associated with the event.\n * @property {boolean=} is_valid - Optional indication of the session validity.\n * @category SDK\n * @subcategory Internal\n */\nexport interface BroadcastMessage {\n action: Action;\n claims?: Claims;\n is_valid?: boolean;\n}\n\n/**\n * Callback type for handling broadcast messages.\n *\n * @ignore\n */\n// eslint-disable-next-line no-unused-vars\ntype Callback = (msg: BroadcastMessage) => void;\n\n/**\n * Manages inter-tab communication using the BroadcastChannel API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} channelName - The name of the broadcast channel.\n * @param {Callback} onSessionExpired - Callback invoked when the session has expired.\n * @param {Callback} onSessionCreated - Callback invoked when a session is created.\n * @param {Callback} onLeadershipRequested - Callback invoked when a leadership request is received.\n */\nexport class SessionChannel {\n channel: BroadcastChannel; // The broadcast channel used for communication.\n onSessionExpired: Callback; // Callback invoked when the session has expired.\n onSessionCreated: Callback; // Callback invoked when a session is created.\n onLeadershipRequested: Callback; // Callback invoked when a leadership request is received.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n channelName: string = \"hanko_session\",\n onSessionExpired: Callback,\n onSessionCreated: Callback,\n onLeadershipRequested: Callback,\n ) {\n this.onSessionExpired = onSessionExpired;\n this.onSessionCreated = onSessionCreated;\n this.onLeadershipRequested = onLeadershipRequested;\n\n this.channel = new BroadcastChannel(channelName);\n this.channel.onmessage = this.handleMessage;\n }\n\n /**\n * Sends a message via the broadcast channel to inform other tabs of session changes.\n *\n * @param {BroadcastMessage} msg - The messsage to broadcast.\n */\n post(msg: BroadcastMessage) {\n this.channel.postMessage(msg);\n }\n\n /**\n * Handles incoming messages from the broadcast channel.\n *\n * @param {MessageEvent} event - The message event containing the broadcast data.\n * @private\n */\n private handleMessage = (event: MessageEvent) => {\n const data = event.data as BroadcastMessage;\n switch (data.action) {\n case \"sessionExpired\":\n this.onSessionExpired(data);\n break;\n case \"sessionCreated\":\n this.onSessionCreated(data);\n break;\n case \"requestLeadership\":\n this.onLeadershipRequested(data);\n break;\n }\n };\n}\n","import { Listener } from \"./Listener\";\nimport { Dispatcher } from \"./Dispatcher\";\nimport { SessionClient } from \"../client/SessionClient\";\nimport { SessionState } from \"./SessionState\";\nimport { WindowActivityManager } from \"./WindowActivityManager\";\nimport { Scheduler, SessionCheckResult } from \"./Scheduler\";\nimport { SessionChannel, BroadcastMessage } from \"./SessionChannel\";\nimport { InternalOptions } from \"../../Hanko\";\n\n/**\n * A class that manages session checks, dispatches events based on session status,\n * and uses broadcast channels for inter-tab communication.\n *\n * @category SDK\n * @subcategory Internal\n * @extends Dispatcher\n * @param {string} api - The API endpoint URL.\n * @param {InternalOptions} options - The internal configuration options of the SDK.\n */\nexport class Relay extends Dispatcher {\n listener = new Listener(); // Listener for session-related events.\n private readonly checkInterval: number = 30000; // Interval for session validity checks in milliseconds.\n private readonly client: SessionClient; // Client for session validation.\n private readonly sessionState: SessionState; // Manages session-related states.\n private readonly windowActivityManager: WindowActivityManager; // Manages window activity states.\n private readonly scheduler: Scheduler; // Schedules session validity checks.\n private readonly sessionChannel: SessionChannel; // Handles inter-tab communication via broadcast channels.\n private isLoggedIn: boolean;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: InternalOptions) {\n super();\n this.client = new SessionClient(api, options);\n this.checkInterval = options.sessionCheckInterval;\n this.sessionState = new SessionState(`${options.cookieName}_session_state`);\n this.sessionChannel = new SessionChannel(\n options.sessionCheckChannelName,\n () => this.onChannelSessionExpired(),\n (msg) => this.onChannelSessionCreated(msg),\n () => this.onChannelLeadershipRequested(),\n );\n this.scheduler = new Scheduler(\n this.checkInterval,\n () => this.checkSession(),\n () => this.onSessionExpired(),\n );\n this.windowActivityManager = new WindowActivityManager(\n () => this.startSessionCheck(),\n () => this.scheduler.stop(),\n );\n\n const now = Date.now();\n const { expiration } = this.sessionState.load();\n\n this.isLoggedIn = now < expiration;\n this.initializeEventListeners();\n this.startSessionCheck();\n }\n\n /**\n * Sets up all event listeners and initializes session management.\n * This method is crucial for ensuring the session is monitored across all tabs.\n * @private\n */\n private initializeEventListeners(): void {\n // Listen for session creation events\n this.listener.onSessionCreated((detail) => {\n const { claims } = detail;\n const expiration = Date.parse(claims.expiration);\n const lastCheck = Date.now();\n\n this.isLoggedIn = true;\n this.sessionState.save({ expiration, lastCheck }); // Save initial session state\n this.sessionChannel.post({ action: \"sessionCreated\", claims }); // Inform other tabs\n this.startSessionCheck(); // Begin session checks now that a user is logged in\n });\n\n // Listen for user logout events\n this.listener.onUserLoggedOut(() => {\n this.isLoggedIn = false;\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs session ended\n this.sessionState.save(null);\n this.scheduler.stop();\n });\n\n window.addEventListener(\"beforeunload\", () => this.scheduler.stop());\n }\n\n /**\n * Initiates session checking based on the last check time.\n * This method decides when the next check should occur to balance between performance and freshness.\n * @private\n */\n private startSessionCheck(): void {\n if (this.windowActivityManager.hasFocus()) {\n this.sessionChannel.post({ action: \"requestLeadership\" }); // Inform other tabs this tab is now checking\n } else {\n return;\n }\n\n if (this.scheduler.isRunning()) {\n return;\n }\n\n const { lastCheck, expiration } = this.sessionState.load();\n\n if (this.isLoggedIn) {\n this.scheduler.start(lastCheck, expiration);\n }\n }\n\n /**\n * Validates the current session and updates session information.\n * This method checks if the session is still valid and updates local data accordingly.\n * @returns {Promise<SessionCheckResult>} - A promise that resolves with the session check result.\n * @private\n */\n private async checkSession(): Promise<SessionCheckResult> {\n const lastCheck = Date.now();\n // eslint-disable-next-line camelcase\n const { is_valid, claims, expiration_time } = await this.client.validate();\n\n // eslint-disable-next-line camelcase\n const expiration = expiration_time ? Date.parse(expiration_time) : 0;\n\n // eslint-disable-next-line camelcase\n if (!is_valid && this.isLoggedIn) {\n this.dispatchSessionExpiredEvent();\n }\n\n // eslint-disable-next-line camelcase\n if (is_valid) {\n this.isLoggedIn = true;\n this.sessionState.save({ lastCheck, expiration });\n } else {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n }\n\n return {\n // eslint-disable-next-line camelcase\n is_valid,\n claims,\n expiration,\n };\n }\n\n /**\n * Resets session-related states when a session expires.\n * Ensures that authentication state is cleared and an expiration event is dispatched.\n * Assumes the user is logged out by default if the session state is unknown.\n * @private\n */\n private onSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session expired events from broadcast messages.\n * @private\n */\n private onChannelSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session creation events from broadcast messages.\n * @param {BroadcastMessage} msg - The broadcast message containing session details.\n * @private\n */\n private onChannelSessionCreated(msg: BroadcastMessage) {\n const { claims } = msg;\n const now = Date.now();\n const expiration = Date.parse(claims.expiration);\n const expirationSeconds = expiration - now;\n\n this.isLoggedIn = true;\n this.dispatchSessionCreatedEvent({\n claims,\n expirationSeconds, // deprecated\n });\n }\n\n /**\n * Handles leadership requests from other tabs.\n * @private\n */\n private onChannelLeadershipRequested() {\n if (!this.windowActivityManager.hasFocus()) {\n this.scheduler.stop();\n }\n }\n}\n","import { Client } from \"../client/Client\";\nimport { State, isState } from \"./State\";\nimport { Action } from \"./types/action\";\nimport { FetchNextState, FlowPath, Handlers } from \"./types/state-handling\";\nimport { HankoError } from \"../Errors\";\n\ntype ExtendedHandlers = Handlers & { onError?: (e: unknown) => any };\n\n// eslint-disable-next-line require-jsdoc\nclass Flow extends Client {\n public async init(\n initPath: FlowPath,\n handlers: ExtendedHandlers,\n ): Promise<void> {\n const fetchNextState: FetchNextState = async (href: string, body?: any) => {\n try {\n const response = await this.client.post(href, body);\n return new State(response.json(), fetchNextState);\n } catch (e) {\n handlers.onError?.(e);\n }\n };\n\n const initState = await fetchNextState(initPath);\n await this.run(initState, handlers);\n }\n\n public async fromString(init: string, handlers: ExtendedHandlers) {\n const fetchNextState: FetchNextState = async (href: string, body?: any) => {\n try {\n const response = await this.client.post(href, body);\n return new State(response.json(), fetchNextState);\n } catch (e) {\n handlers.onError?.(e);\n }\n };\n\n const initState = new State(JSON.parse(init), fetchNextState);\n await this.run(initState, handlers);\n }\n\n /**\n * Runs a handler for a given state.\n *\n * If the handler returns an action or a state, this method will run the next\n * appropriate handler for that state. (Recursively)\n *\n * If the handlers passed to `init` do not contain an `onError` handler,\n * this method will throw.\n *\n * @see InvalidStateError\n * @see HandlerNotFoundError\n *\n * @example\n * const handlerResult = await run(\"/login\", {\n * // all login handlers are in here, one of which will be called\n * // based on what the /login endpoint returns\n * });\n */\n run = async (\n state: State<any>,\n handlers: ExtendedHandlers,\n ): Promise<unknown> => {\n try {\n if (!isState(state)) {\n throw new InvalidStateError(state);\n }\n\n const handler = handlers[state.name];\n if (!handler) {\n throw new HandlerNotFoundError(state);\n }\n\n let maybeNextState = await handler(state);\n\n // handler can return an action, which we'll run (and turn into state)...\n if (isAction(maybeNextState)) {\n maybeNextState = await (maybeNextState as any).run();\n }\n\n // ...or a state, to continue the \"run loop\"\n if (isState(maybeNextState)) {\n return this.run(maybeNextState, handlers);\n }\n } catch (e) {\n if (typeof handlers.onError === \"function\") {\n return handlers.onError(e);\n }\n }\n };\n}\n\nexport class HandlerNotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(public state: State<any>) {\n super(\n `No handler found for state: ${\n typeof state.name === \"string\"\n ? `\"${state.name}\"`\n : `(${typeof state.name})`\n }`,\n \"handlerNotFoundError\",\n );\n Object.setPrototypeOf(this, HandlerNotFoundError.prototype);\n }\n}\n\nexport class InvalidStateError extends Error {\n constructor(public state: State<any>) {\n super(\n `Invalid state: ${\n typeof state.name === \"string\"\n ? `\"${state.name}\"`\n : `(${typeof state.name})`\n }`,\n );\n }\n}\n\nexport function isAction(x: any): x is Action<unknown> {\n return typeof x === \"object\" && x !== null && \"href\" in x && \"inputs\" in x;\n}\n\nexport { Flow };\n","import { EnterpriseClient } from \"./lib/client/EnterpriseClient\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { EmailClient } from \"./lib/client/EmailClient\";\nimport { ThirdPartyClient } from \"./lib/client/ThirdPartyClient\";\nimport { TokenClient } from \"./lib/client/TokenClient\";\nimport { Listener } from \"./lib/events/Listener\";\nimport { Relay } from \"./lib/events/Relay\";\nimport { CookieSameSite } from \"./lib/Cookie\";\nimport { Flow } from \"./lib/flow-api/Flow\";\nimport { SessionClient, Session } from \"./lib/client/SessionClient\";\n\n/**\n * The options for the Hanko class\n *\n * @interface\n * @property {number=} timeout - The http request timeout in milliseconds. Defaults to 13000ms\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\"\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite - Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n * @property {string=} localStorageKey - The prefix / name of the local storage keys. Defaults to \"hanko\"\n * @property {string=} lang - Used to convey the preferred language to the API, e.g. for translating outgoing emails.\n * It is transmitted to the API in a custom header (X-Language).\n * Should match one of the supported languages (\"bn\", \"de\", \"en\", \"fr\", \"it, \"pt-BR\", \"zh\")\n * if email delivery by Hanko is enabled. If email delivery by Hanko is disabled and the\n * relying party configures a webhook for the \"email.send\" event, then the set language is\n * reflected in the payload of the token contained in the webhook request.\n * @property {number=} sessionCheckInterval - Interval for session validity checks in milliseconds. Must be greater than 3000 (3s), defaults to 3000 otherwise.\n * @property {string=} sessionCheckChannelName - The broadcast channel name for inter-tab communication.\n */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: string;\n lang?: string;\n sessionCheckInterval?: number;\n sessionCheckChannelName?: string;\n}\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @extends {Listener}\n * @param {string} api - The URL of your Hanko API instance\n * @param {HankoOptions=} options - The options that can be used\n */\nclass Hanko extends Listener {\n api: string;\n user: UserClient;\n email: EmailClient;\n thirdParty: ThirdPartyClient;\n enterprise: EnterpriseClient;\n token: TokenClient;\n sessionClient: SessionClient;\n session: Session;\n relay: Relay;\n flow: Flow;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options?: HankoOptions) {\n super();\n const opts: InternalOptions = {\n timeout: 13000,\n cookieName: \"hanko\",\n localStorageKey: \"hanko\",\n sessionCheckInterval: 30000,\n sessionCheckChannelName: \"hanko-session-check\",\n };\n if (options?.cookieName !== undefined) {\n opts.cookieName = options.cookieName;\n }\n if (options?.timeout !== undefined) {\n opts.timeout = options.timeout;\n }\n if (options?.localStorageKey !== undefined) {\n opts.localStorageKey = options.localStorageKey;\n }\n if (options?.cookieDomain !== undefined) {\n opts.cookieDomain = options.cookieDomain;\n }\n if (options?.cookieSameSite !== undefined) {\n opts.cookieSameSite = options.cookieSameSite;\n }\n if (options?.lang !== undefined) {\n opts.lang = options.lang;\n }\n if (options?.sessionCheckInterval !== undefined) {\n if (options.sessionCheckInterval < 3000) {\n opts.sessionCheckInterval = 3000;\n } else {\n opts.sessionCheckInterval = options.sessionCheckInterval;\n }\n }\n if (options?.sessionCheckChannelName !== undefined) {\n opts.sessionCheckChannelName = options.sessionCheckChannelName;\n }\n\n this.api = api;\n /**\n * @public\n * @type {UserClient}\n */\n this.user = new UserClient(api, opts);\n /**\n * @public\n * @type {EmailClient}\n */\n this.email = new EmailClient(api, opts);\n /**\n * @public\n * @type {ThirdPartyClient}\n */\n this.thirdParty = new ThirdPartyClient(api, opts);\n /**\n * @public\n * @type {EnterpriseClient}\n */\n this.enterprise = new EnterpriseClient(api, opts);\n /**\n * @public\n * @type {TokenClient}\n */\n this.token = new TokenClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.sessionClient = new SessionClient(api, opts);\n /**\n * @public\n * @deprecated\n * @type {Session}\n */\n this.session = new Session(api, opts);\n /**\n * @public\n * @type {Relay}\n */\n this.relay = new Relay(api, opts);\n /**\n * @public\n * @type {Flow}\n */\n this.flow = new Flow(api, opts);\n }\n\n /**\n * Sets the preferred language on the underlying sub-clients. The clients'\n * base HttpClient uses this language to transmit an X-Language header to the\n * API which is then used to e.g. translate outgoing emails.\n *\n * @public\n * @param lang {string} - The preferred language to convey to the API.\n */\n setLang(lang: string) {\n this.flow.client.lang = lang;\n }\n}\n\n// eslint-disable-next-line require-jsdoc\nexport interface InternalOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey: string;\n lang?: string;\n sessionCheckInterval?: number;\n sessionCheckChannelName?: string;\n}\n\nexport { Hanko };\n","/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n\n /**\n * Checks whether autofill assisted requests are supported.\n *\n * @return Promise<boolean>\n */\n static async isConditionalMediationAvailable(): Promise<boolean> {\n if (\n // @ts-ignore\n window.PublicKeyCredential &&\n // @ts-ignore\n window.PublicKeyCredential.isConditionalMediationAvailable\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isConditionalMediationAvailable();\n }\n\n return false;\n }\n}\n\nexport { WebauthnSupport };\n"],"names":["HankoError","_Error","message","code","cause","_this","call","this","Object","setPrototypeOf","prototype","_inheritsLoose","Error","TechnicalError","_HankoError","_this2","_assertThisInitialized","ConflictError","_HankoError2","userID","_this3","RequestTimeoutError","_this4","_HankoError3","_HankoError4","WebauthnRequestCancelledError","_this5","InvalidPasswordError","_HankoError5","_this6","InvalidPasscodeError","_HankoError6","_this7","InvalidWebauthnCredentialError","_HankoError7","_this8","PasscodeExpiredError","_HankoError8","_this9","MaxNumOfPasscodeAttemptsReachedError","_HankoError9","_this10","NotFoundError","_this11","_HankoError10","_HankoError11","TooManyRequestsError","retryAfter","_this12","UnauthorizedError","_HankoError12","_this13","ForbiddenError","_HankoError13","_this14","UserVerificationError","_HankoError14","_this15","MaxNumOfEmailAddressesReachedError","_HankoError15","_this16","EmailAddressAlreadyExistsError","_HankoError16","_this17","ThirdPartyError","_this18","_HankoError17","sessionCreatedType","sessionExpiredType","userDeletedType","CustomEventWithDetail","_CustomEvent","type","detail","_wrapNativeSuper","CustomEvent","Dispatcher","_dispatchEvent","document","dispatchEvent","bind","dispatch","_proto","dispatchSessionCreatedEvent","dispatchSessionExpiredEvent","dispatchUserLoggedOutEvent","userLoggedOutType","dispatchUserDeletedEvent","assign","target","i","arguments","length","source","key","ValidationReason","api","init","converter","defaultAttributes","set","name","value","attributes","expires","Date","now","toUTCString","encodeURIComponent","replace","decodeURIComponent","escape","stringifiedAttributes","attributeName","split","cookie","write","create","get","cookies","jar","parts","slice","join","found","read","e","remove","withAttributes","withConverter","freeze","path","Cookie","options","_options$cookieSameSi","authCookieName","authCookieDomain","authCookieSameSite","cookieName","cookieDomain","cookieSameSite","getAuthCookie","JSCookie","setAuthCookie","token","defaults","secure","sameSite","undefined","domain","o","removeAuthCookie","Headers","xhr","_xhr","Response","getResponseHeader","headers","ok","status","statusText","url","_decodedJSON","responseURL","json","JSON","parse","response","parseNumericHeader","result","parseInt","isNaN","HttpClient","timeout","dispatcher","lang","_proto3","_fetch","XMLHttpRequest","self","bearerToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","processHeaders","onerror","ontimeout","send","body","toString","_fetch_blocking","responseText","jwt","expirationSeconds","retention","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","https","RegExp","match","window","location","href","getTime","post","stringify","put","patch","Client","client","EnterpriseClient","getDomain","email","emailParts","trim","hasProvider","then","resp","auth","redirectTo","URL","searchParams","append","getError","params","URLSearchParams","search","error","errorDescription","getInfo","getCurrent","meResponse","me","id","userResponse","logout","logoutResponse","EmailClient","_Client","apply","list","address","setPrimaryEmail","emailID","ThirdPartyClient","provider","validate","history","replaceState","pathname","TokenClient","Throttle","throttle","func","wait","context","args","timeoutID","_options$leading","leading","_options$trailing","trailing","previous","remaining","clearTimeout","setTimeout","executeThrottledFunction","throttleLimit","_addEventListener","addEventListener","_removeEventListener","removeEventListener","_throttle","wrapCallback","callback","event","wrappedCallback","addEventListenerWithType","once","_ref$once","_ref$throttle","mapAddEventListenerParams","_ref2","Listener","onSessionCreated","onSessionExpired","onUserLoggedOut","onUserDeleted","SessionClient","Session","isValid","session","is_valid","SessionState","storageKey","defaultState","expiration","lastCheck","load","item","localStorage","getItem","save","setItem","WindowActivityManager","onActivityCallback","onInactivityCallback","handleFocus","handleBlur","handleVisibilityChange","visibilityState","hasFocus","Scheduler","checkInterval","checkSession","intervalID","scheduleSessionExpiry","timeToExpiration","stop","start","timeToNextCheck","calcTimeToNextCheck","sessionExpiresSoon","setInterval","_this2$checkSession","clearInterval","isRunning","timeSinceLastCheck","SessionChannel","channelName","onLeadershipRequested","channel","handleMessage","data","action","BroadcastChannel","onmessage","msg","postMessage","Relay","_Dispatcher","listener","sessionState","windowActivityManager","scheduler","sessionChannel","isLoggedIn","sessionCheckInterval","sessionCheckChannelName","onChannelSessionExpired","onChannelSessionCreated","onChannelLeadershipRequested","startSessionCheck","_this$sessionState$lo","initializeEventListeners","claims","_this$sessionState$lo2","_ref","expiration_time","State","fetchNextState","payload","actions","csrf_token","defineProperty","_createActionsProxy","_createActionsProxy2","_actionDefinitions","writable","_classPrivateFieldLooseBase","toJSON","runAction","csrfToken","inputs","input","inputName","input_data","validateAction","_loop","reason","wanted","actual","ValidationError","required","Required","min_length","max_length","InvalidInputDefinition","MinLength","MaxLength","prop","originalAction","newInputs","tryValidate","run","actionInputs","opts","isState","x","Boolean","Flow","_len","Array","_key","concat","state","handlers","_catch","InvalidStateError","handler","HandlerNotFoundError","maybeNextState","_temp2","_temp","_maybeNextState$run","onError","initPath","initState","fromString","Hanko","_Listener","user","thirdParty","enterprise","sessionClient","relay","flow","localStorageKey","UserClient","setLang","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable"],"mappings":"6xDAUeA,IAAAA,eAKb,SAAAC,GAAA,SAAAD,EAAsBE,EAAiBC,EAAcC,GACnD,IAAAC,EAWkD,OAXlDA,EAAAJ,EAAAK,KAAAC,KAAML,UALRC,UACAC,EAAAA,EAAAA,WASE,EAAAC,EAAKF,KAAOA,EAKZE,EAAKD,MAAQA,EACbI,OAAOC,eAAqBT,EAAAA,GAAAA,EAAWU,WACzCL,CAAA,CAAC,OAbDM,EAAAX,EAAAC,KAAA,gBALgCW,QA6BbC,eAAA,SAAAC,GAEnB,SAAYV,EAAAA,GAAa,IAAAW,EAE+B,OADtDA,cAAM,kBAAmB,qBAAsBX,IAC/CI,KAAAA,OAAOC,eAAcO,EAAAD,GAAOF,EAAeH,WAAWK,CACxD,CAAC,OALkBJ,EAAAE,EAAAC,GAAQd,CAAAA,CAAR,CAAQA,GAevBiB,eAEJ,SAAAC,GAAA,SAAAD,EAAYE,EAAiBf,GAC3B,IAAAgB,EACqD,OADrDA,EAAAF,EAAAZ,KAAAC,KAAM,iBAAkB,WAAYH,IAAMG,KAC1CC,OAAOC,eAAcO,EAAAI,GAAOH,EAAcP,WAC5CU,CAAA,CAAC,OAHDT,EAAAM,EAAAC,GAF0BlB,CAAAA,CAE1B,CAF0BA,GAetBqB,2BAEJ,SAAYjB,EAAAA,GAAa,IAAAkB,EAEoC,OAD3DA,EAAMC,EAAAjB,KAAAC,KAAA,0BAA2B,iBAAkBH,IACnDI,KAAAA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