@teamhanko/hanko-frontend-sdk 1.1.0 → 1.2.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.
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.umd.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 */\nexport interface HttpClientOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n localStorageKey: 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\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 }\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\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\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\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 }\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 const expires = new Date(new Date().getTime() + expirationSeconds * 1000);\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\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\ntype ExtendedHandlers = Handlers & { onError?: (e: unknown) => any };\ntype GetInitState = (flow: Flow) => MaybePromise<State<any> | null>;\n\n// eslint-disable-next-line require-jsdoc\nclass Flow extends Client {\n public async init(\n initPath: FlowPath,\n handlers: ExtendedHandlers,\n // getInitState: GetInitState = () => this.fetchNextState(initPath),\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 Error {\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 );\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 */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: 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\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// 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}\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","_proto2","parseNumericHeader","parseInt","isNaN","result","timeout","sessionState","dispatcher","_fetch","bearerToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","self","processHeaders","onerror","ontimeout","send","body","toString","expirationSeconds","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","jwt","RegExp","match","https","location","href","getTime","_proto3","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","state","handlers","_catch","InvalidStateError","handler","maybeNextState","isAction","_maybeNextState$run","_temp","_temp2","onError","initPath","initState","fromString","HandlerNotFoundError","_Error2","SessionClient","Hanko","_Listener","user","thirdParty","enterprise","sessionClient","relay","flow","Flow","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable"],"mappings":"ugEAUeA,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,EAA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GAACvR,EAAK0P,IAC5B,CAAC,cAAAqB,CAAA,EAlFiBzF,GC9BdkG,gBAQGC,WAAAA,SAAAA,IAAAA,CA4DN,OA5DMA,EAAAA,UAAP,WACE,SACEC,UAAUC,aACVD,UAAUC,YAAY3Q,QACtB0Q,UAAUC,YAAY1Q,KACtBjF,OAAO4V,oBAEX,EAACJ,EAOYK,iCAAgC,WAAA,IAC3C,OACEra,KAAKia,aACLzV,OAAO4V,oBAAoBE,8CAE3BrN,QAAAC,QAAO1I,OAAO4V,oBAAoBE,iDAG7BrN,QAAAC,SAAA,GACR,sCAOYqN,uBAAsB,WAAA,IACjC,YACiCnP,IAA/B5G,OAAO4V,qBAEP5V,OAAO4V,oBAAoBI,oCAG3BvN,QAAAC,QAAO1I,OAAO4V,oBAAoBI,uCAG7BvN,QAAAC,QAAAlN,KAAKia,YAQDQ,CAPZ,MAOYA,GAAAA,OAAAA,QAAAA,OAAAA,EAAAA,CAAAA,EAAAA,EAAAA,gCAA+B,WAAA,IAC1C,OAEEjW,OAAO4V,qBAEP5V,OAAO4V,oBAAoBK,gCAGpBjW,QAAAA,QAAAA,OAAO4V,oBAAoBK,mCAGpCxN,QAAAC,SAAO,EACR,CAAA,MAAAtI,GAAA,OAAAqI,QAAAE,OAAAvI,EAAA,CAAA,EAAAoV,CAAA,CA5DMC"}
1
+ {"version":3,"file":"sdk.umd.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 */\nexport interface HttpClientOptions {\n timeout: number;\n cookieName: string;\n cookieDomain?: string;\n localStorageKey: 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\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 }\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\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\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\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 }\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 const expires = new Date(new Date().getTime() + expirationSeconds * 1000);\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 MaybePromise<T> = T | Promise<T>;\n\ntype ExtendedHandlers = Handlers & { onError?: (e: unknown) => any };\ntype GetInitState = (flow: Flow) => MaybePromise<State<any> | null>;\n\n// eslint-disable-next-line require-jsdoc\nclass Flow extends Client {\n public async init(\n initPath: FlowPath,\n handlers: ExtendedHandlers,\n // getInitState: GetInitState = () => this.fetchNextState(initPath),\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 */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: 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\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// 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}\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","_proto2","parseNumericHeader","parseInt","isNaN","result","timeout","sessionState","dispatcher","_fetch","bearerToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","self","processHeaders","onerror","ontimeout","send","body","toString","expirationSeconds","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","jwt","RegExp","match","https","location","href","getTime","_proto3","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","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable"],"mappings":"ugEAUeA,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,OAAOC,eAAqBY,EAAAA,GAAAA,EAAoBX,WAAWY,CAC7D,CAAC,cAAAD,CAAA,EAL+BrB,kBAkBhC,SAAAwB,GAAA,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