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IAAKkI,EAEH,MADA9G,KAAK8C,QAAQxD,MAAM,+BACb,IAAIV,MAAM,aAElB,MAAM8H,QAAcC,EAAYtG,OAAO,CACrCgC,KAAMkF,EACNnC,eACAC,YACAlD,eAAgBwF,EAChBhF,YACAmE,YACAC,eACAG,gBACAtE,gBACAoE,QACAC,mBACAE,iBAEIU,EAAY,IAAIC,IAAIT,GAC1BQ,EAAUE,aAAaC,OAAO,YAAarF,GAC3CkF,EAAUE,aAAaC,OAAO,eAAgBjB,GAC9Cc,EAAUE,aAAaC,OAAO,gBAAiBV,GAC/CO,EAAUE,aAAaC,OAAO,QAAShB,GACnCQ,GACFK,EAAUE,aAAaC,OAAO,QAASR,GAEzC,IAAIS,EAAavB,EAAMxB,GACnBG,IACF4C,EAAa,GAAGA,KAAmC5C,KAErDwC,EAAUE,aAAaC,OAAO,QAASC,GACnCvB,EAAMG,iBACRgB,EAAUE,aAAaC,OAAO,iBAAkBtB,EAAMG,gBACtDgB,EAAUE,aAAaC,OAAO,wBAAyB,SAErDP,IACgBS,MAAMC,QAAQV,GAAYA,EAAW,CAACA,IAC9CW,SAASC,GAAMR,EAAUE,aAAaC,OAAO,WAAYK,KAErE,IAAK,MAAO/B,EAAK5G,KAAUc,OAAO8H,QAAQ,CAAEpB,mBAAkBU,KAAmBF,IAClE,MAAThI,GACFmI,EAAUE,aAAaC,OAAO1B,EAAK5G,EAAMsC,YAG7C,OAAO,IAAIoF,EAAe,CACxBC,IAAKQ,EAAUU,KACf7B,SAEJ,IAEa5D,QAAU,IAAIlD,EAAO,gB","sources":["webpack:///../node_modules/jwt-decode/build/esm/index.js","webpack:///../node_modules/oidc-client-ts/dist/esm/oidc-client-ts.js"],"sourcesContent":["export class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {\n let code = p.charCodeAt(0).toString(16).toUpperCase();\n if (code.length < 2) {\n code = \"0\" + code;\n }\n return \"%\" + code;\n }));\n}\nfunction base64UrlDecode(str) {\n let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n switch (output.length % 4) {\n case 0:\n break;\n case 2:\n output += \"==\";\n break;\n case 3:\n output += \"=\";\n break;\n default:\n throw new Error(\"base64 string is not of the correct length\");\n }\n try {\n return b64DecodeUnicode(output);\n }\n catch (err) {\n return atob(output);\n }\n}\nexport function jwtDecode(token, options) {\n if (typeof token !== \"string\") {\n throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n }\n options || (options = {});\n const pos = options.header === true ? 0 : 1;\n const part = token.split(\".\")[pos];\n if (typeof part !== \"string\") {\n throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);\n }\n let decoded;\n try {\n decoded = base64UrlDecode(part);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);\n }\n try {\n return JSON.parse(decoded);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);\n }\n}\n","// src/utils/Logger.ts\nvar nopLogger = {\n debug: () => void 0,\n info: () => void 0,\n warn: () => void 0,\n error: () => void 0\n};\nvar level;\nvar logger;\nvar Log = /* @__PURE__ */ ((Log2) => {\n Log2[Log2[\"NONE\"] = 0] = \"NONE\";\n Log2[Log2[\"ERROR\"] = 1] = \"ERROR\";\n Log2[Log2[\"WARN\"] = 2] = \"WARN\";\n Log2[Log2[\"INFO\"] = 3] = \"INFO\";\n Log2[Log2[\"DEBUG\"] = 4] = \"DEBUG\";\n return Log2;\n})(Log || {});\n((Log2) => {\n function reset() {\n level = 3 /* INFO */;\n logger = nopLogger;\n }\n Log2.reset = reset;\n function setLevel(value) {\n if (!(0 /* NONE */ <= value && value <= 4 /* DEBUG */)) {\n throw new Error(\"Invalid log level\");\n }\n level = value;\n }\n Log2.setLevel = setLevel;\n function setLogger(value) {\n logger = value;\n }\n Log2.setLogger = setLogger;\n})(Log || (Log = {}));\nvar Logger = class _Logger {\n constructor(_name) {\n this._name = _name;\n }\n /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */\n debug(...args) {\n if (level >= 4 /* DEBUG */) {\n logger.debug(_Logger._format(this._name, this._method), ...args);\n }\n }\n info(...args) {\n if (level >= 3 /* INFO */) {\n logger.info(_Logger._format(this._name, this._method), ...args);\n }\n }\n warn(...args) {\n if (level >= 2 /* WARN */) {\n logger.warn(_Logger._format(this._name, this._method), ...args);\n }\n }\n error(...args) {\n if (level >= 1 /* ERROR */) {\n logger.error(_Logger._format(this._name, this._method), ...args);\n }\n }\n /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */\n throw(err) {\n this.error(err);\n throw err;\n }\n create(method) {\n const methodLogger = Object.create(this);\n methodLogger._method = method;\n methodLogger.debug(\"begin\");\n return methodLogger;\n }\n static createStatic(name, staticMethod) {\n const staticLogger = new _Logger(`${name}.${staticMethod}`);\n staticLogger.debug(\"begin\");\n return staticLogger;\n }\n static _format(name, method) {\n const prefix = `[${name}]`;\n return method ? `${prefix} ${method}:` : prefix;\n }\n /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */\n // helpers for static class methods\n static debug(name, ...args) {\n if (level >= 4 /* DEBUG */) {\n logger.debug(_Logger._format(name), ...args);\n }\n }\n static info(name, ...args) {\n if (level >= 3 /* INFO */) {\n logger.info(_Logger._format(name), ...args);\n }\n }\n static warn(name, ...args) {\n if (level >= 2 /* WARN */) {\n logger.warn(_Logger._format(name), ...args);\n }\n }\n static error(name, ...args) {\n if (level >= 1 /* ERROR */) {\n logger.error(_Logger._format(name), ...args);\n }\n }\n /* eslint-enable @typescript-eslint/no-unsafe-enum-comparison */\n};\nLog.reset();\n\n// src/utils/CryptoUtils.ts\nvar UUID_V4_TEMPLATE = \"10000000-1000-4000-8000-100000000000\";\nvar toBase64 = (val) => btoa([...new Uint8Array(val)].map((chr) => String.fromCharCode(chr)).join(\"\"));\nvar CryptoUtils = class _CryptoUtils {\n static _randomWord() {\n const arr = new Uint32Array(1);\n crypto.getRandomValues(arr);\n return arr[0];\n }\n /**\n * Generates RFC4122 version 4 guid\n */\n static generateUUIDv4() {\n const uuid = UUID_V4_TEMPLATE.replace(\n /[018]/g,\n (c) => (+c ^ _CryptoUtils._randomWord() & 15 >> +c / 4).toString(16)\n );\n return uuid.replace(/-/g, \"\");\n }\n /**\n * PKCE: Generate a code verifier\n */\n static generateCodeVerifier() {\n return _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4() + _CryptoUtils.generateUUIDv4();\n }\n /**\n * PKCE: Generate a code challenge\n */\n static async generateCodeChallenge(code_verifier) {\n if (!crypto.subtle) {\n throw new Error(\"Crypto.subtle is available only in secure contexts (HTTPS).\");\n }\n try {\n const encoder = new TextEncoder();\n const data = encoder.encode(code_verifier);\n const hashed = await crypto.subtle.digest(\"SHA-256\", data);\n return toBase64(hashed).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n } catch (err) {\n Logger.error(\"CryptoUtils.generateCodeChallenge\", err);\n throw err;\n }\n }\n /**\n * Generates a base64-encoded string for a basic auth header\n */\n static generateBasicAuth(client_id, client_secret) {\n const encoder = new TextEncoder();\n const data = encoder.encode([client_id, client_secret].join(\":\"));\n return toBase64(data);\n }\n};\n\n// src/utils/Event.ts\nvar Event = class {\n constructor(_name) {\n this._name = _name;\n this._logger = new Logger(`Event('${this._name}')`);\n this._callbacks = [];\n }\n addHandler(cb) {\n this._callbacks.push(cb);\n return () => this.removeHandler(cb);\n }\n removeHandler(cb) {\n const idx = this._callbacks.lastIndexOf(cb);\n if (idx >= 0) {\n this._callbacks.splice(idx, 1);\n }\n }\n async raise(...ev) {\n this._logger.debug(\"raise:\", ...ev);\n for (const cb of this._callbacks) {\n await cb(...ev);\n }\n }\n};\n\n// src/utils/JwtUtils.ts\nimport { jwtDecode } from \"jwt-decode\";\nvar JwtUtils = class {\n // IMPORTANT: doesn't validate the token\n static decode(token) {\n try {\n return jwtDecode(token);\n } catch (err) {\n Logger.error(\"JwtUtils.decode\", err);\n throw err;\n }\n }\n};\n\n// src/utils/PopupUtils.ts\nvar PopupUtils = class {\n /**\n * Populates a map of window features with a placement centered in front of\n * the current window. If no explicit width is given, a default value is\n * binned into [800, 720, 600, 480, 360] based on the current window's width.\n */\n static center({ ...features }) {\n var _a, _b, _c;\n if (features.width == null)\n features.width = (_a = [800, 720, 600, 480].find((width) => width <= window.outerWidth / 1.618)) != null ? _a : 360;\n (_b = features.left) != null ? _b : features.left = Math.max(0, Math.round(window.screenX + (window.outerWidth - features.width) / 2));\n if (features.height != null)\n (_c = features.top) != null ? _c : features.top = Math.max(0, Math.round(window.screenY + (window.outerHeight - features.height) / 2));\n return features;\n }\n static serialize(features) {\n return Object.entries(features).filter(([, value]) => value != null).map(([key, value]) => `${key}=${typeof value !== \"boolean\" ? value : value ? \"yes\" : \"no\"}`).join(\",\");\n }\n};\n\n// src/utils/Timer.ts\nvar Timer = class _Timer extends Event {\n constructor() {\n super(...arguments);\n this._logger = new Logger(`Timer('${this._name}')`);\n this._timerHandle = null;\n this._expiration = 0;\n this._callback = () => {\n const diff = this._expiration - _Timer.getEpochTime();\n this._logger.debug(\"timer completes in\", diff);\n if (this._expiration <= _Timer.getEpochTime()) {\n this.cancel();\n void super.raise();\n }\n };\n }\n // get the time\n static getEpochTime() {\n return Math.floor(Date.now() / 1e3);\n }\n init(durationInSeconds) {\n const logger2 = this._logger.create(\"init\");\n durationInSeconds = Math.max(Math.floor(durationInSeconds), 1);\n const expiration = _Timer.getEpochTime() + durationInSeconds;\n if (this.expiration === expiration && this._timerHandle) {\n logger2.debug(\"skipping since already initialized for expiration at\", this.expiration);\n return;\n }\n this.cancel();\n logger2.debug(\"using duration\", durationInSeconds);\n this._expiration = expiration;\n const timerDurationInSeconds = Math.min(durationInSeconds, 5);\n this._timerHandle = setInterval(this._callback, timerDurationInSeconds * 1e3);\n }\n get expiration() {\n return this._expiration;\n }\n cancel() {\n this._logger.create(\"cancel\");\n if (this._timerHandle) {\n clearInterval(this._timerHandle);\n this._timerHandle = null;\n }\n }\n};\n\n// src/utils/UrlUtils.ts\nvar UrlUtils = class {\n static readParams(url, responseMode = \"query\") {\n if (!url)\n throw new TypeError(\"Invalid URL\");\n const parsedUrl = new URL(url, \"http://127.0.0.1\");\n const params = parsedUrl[responseMode === \"fragment\" ? \"hash\" : \"search\"];\n return new URLSearchParams(params.slice(1));\n }\n};\nvar URL_STATE_DELIMITER = \";\";\n\n// src/errors/ErrorResponse.ts\nvar ErrorResponse = class extends Error {\n constructor(args, form) {\n var _a, _b, _c;\n super(args.error_description || args.error || \"\");\n this.form = form;\n /** Marker to detect class: \"ErrorResponse\" */\n this.name = \"ErrorResponse\";\n if (!args.error) {\n Logger.error(\"ErrorResponse\", \"No error passed\");\n throw new Error(\"No error passed\");\n }\n this.error = args.error;\n this.error_description = (_a = args.error_description) != null ? _a : null;\n this.error_uri = (_b = args.error_uri) != null ? _b : null;\n this.state = args.userState;\n this.session_state = (_c = args.session_state) != null ? _c : null;\n this.url_state = args.url_state;\n }\n};\n\n// src/errors/ErrorTimeout.ts\nvar ErrorTimeout = class extends Error {\n constructor(message) {\n super(message);\n /** Marker to detect class: \"ErrorTimeout\" */\n this.name = \"ErrorTimeout\";\n }\n};\n\n// src/AccessTokenEvents.ts\nvar AccessTokenEvents = class {\n constructor(args) {\n this._logger = new Logger(\"AccessTokenEvents\");\n this._expiringTimer = new Timer(\"Access token expiring\");\n this._expiredTimer = new Timer(\"Access token expired\");\n this._expiringNotificationTimeInSeconds = args.expiringNotificationTimeInSeconds;\n }\n load(container) {\n const logger2 = this._logger.create(\"load\");\n if (container.access_token && container.expires_in !== void 0) {\n const duration = container.expires_in;\n logger2.debug(\"access token present, remaining duration:\", duration);\n if (duration > 0) {\n let expiring = duration - this._expiringNotificationTimeInSeconds;\n if (expiring <= 0) {\n expiring = 1;\n }\n logger2.debug(\"registering expiring timer, raising in\", expiring, \"seconds\");\n this._expiringTimer.init(expiring);\n } else {\n logger2.debug(\"canceling existing expiring timer because we're past expiration.\");\n this._expiringTimer.cancel();\n }\n const expired = duration + 1;\n logger2.debug(\"registering expired timer, raising in\", expired, \"seconds\");\n this._expiredTimer.init(expired);\n } else {\n this._expiringTimer.cancel();\n this._expiredTimer.cancel();\n }\n }\n unload() {\n this._logger.debug(\"unload: canceling existing access token timers\");\n this._expiringTimer.cancel();\n this._expiredTimer.cancel();\n }\n /**\n * Add callback: Raised prior to the access token expiring.\n */\n addAccessTokenExpiring(cb) {\n return this._expiringTimer.addHandler(cb);\n }\n /**\n * Remove callback: Raised prior to the access token expiring.\n */\n removeAccessTokenExpiring(cb) {\n this._expiringTimer.removeHandler(cb);\n }\n /**\n * Add callback: Raised after the access token has expired.\n */\n addAccessTokenExpired(cb) {\n return this._expiredTimer.addHandler(cb);\n }\n /**\n * Remove callback: Raised after the access token has expired.\n */\n removeAccessTokenExpired(cb) {\n this._expiredTimer.removeHandler(cb);\n }\n};\n\n// src/CheckSessionIFrame.ts\nvar CheckSessionIFrame = class {\n constructor(_callback, _client_id, url, _intervalInSeconds, _stopOnError) {\n this._callback = _callback;\n this._client_id = _client_id;\n this._intervalInSeconds = _intervalInSeconds;\n this._stopOnError = _stopOnError;\n this._logger = new Logger(\"CheckSessionIFrame\");\n this._timer = null;\n this._session_state = null;\n this._message = (e) => {\n if (e.origin === this._frame_origin && e.source === this._frame.contentWindow) {\n if (e.data === \"error\") {\n this._logger.error(\"error message from check session op iframe\");\n if (this._stopOnError) {\n this.stop();\n }\n } else if (e.data === \"changed\") {\n this._logger.debug(\"changed message from check session op iframe\");\n this.stop();\n void this._callback();\n } else {\n this._logger.debug(e.data + \" message from check session op iframe\");\n }\n }\n };\n const parsedUrl = new URL(url);\n this._frame_origin = parsedUrl.origin;\n this._frame = window.document.createElement(\"iframe\");\n this._frame.style.visibility = \"hidden\";\n this._frame.style.position = \"fixed\";\n this._frame.style.left = \"-1000px\";\n this._frame.style.top = \"0\";\n this._frame.width = \"0\";\n this._frame.height = \"0\";\n this._frame.src = parsedUrl.href;\n }\n load() {\n return new Promise((resolve) => {\n this._frame.onload = () => {\n resolve();\n };\n window.document.body.appendChild(this._frame);\n window.addEventListener(\"message\", this._message, false);\n });\n }\n start(session_state) {\n if (this._session_state === session_state) {\n return;\n }\n this._logger.create(\"start\");\n this.stop();\n this._session_state = session_state;\n const send = () => {\n if (!this._frame.contentWindow || !this._session_state) {\n return;\n }\n this._frame.contentWindow.postMessage(this._client_id + \" \" + this._session_state, this._frame_origin);\n };\n send();\n this._timer = setInterval(send, this._intervalInSeconds * 1e3);\n }\n stop() {\n this._logger.create(\"stop\");\n this._session_state = null;\n if (this._timer) {\n clearInterval(this._timer);\n this._timer = null;\n }\n }\n};\n\n// src/InMemoryWebStorage.ts\nvar InMemoryWebStorage = class {\n constructor() {\n this._logger = new Logger(\"InMemoryWebStorage\");\n this._data = {};\n }\n clear() {\n this._logger.create(\"clear\");\n this._data = {};\n }\n getItem(key) {\n this._logger.create(`getItem('${key}')`);\n return this._data[key];\n }\n setItem(key, value) {\n this._logger.create(`setItem('${key}')`);\n this._data[key] = value;\n }\n removeItem(key) {\n this._logger.create(`removeItem('${key}')`);\n delete this._data[key];\n }\n get length() {\n return Object.getOwnPropertyNames(this._data).length;\n }\n key(index) {\n return Object.getOwnPropertyNames(this._data)[index];\n }\n};\n\n// src/JsonService.ts\nvar JsonService = class {\n constructor(additionalContentTypes = [], _jwtHandler = null, _extraHeaders = {}) {\n this._jwtHandler = _jwtHandler;\n this._extraHeaders = _extraHeaders;\n this._logger = new Logger(\"JsonService\");\n this._contentTypes = [];\n this._contentTypes.push(...additionalContentTypes, \"application/json\");\n if (_jwtHandler) {\n this._contentTypes.push(\"application/jwt\");\n }\n }\n async fetchWithTimeout(input, init = {}) {\n const { timeoutInSeconds, ...initFetch } = init;\n if (!timeoutInSeconds) {\n return await fetch(input, initFetch);\n }\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutInSeconds * 1e3);\n try {\n const response = await fetch(input, {\n ...init,\n signal: controller.signal\n });\n return response;\n } catch (err) {\n if (err instanceof DOMException && err.name === \"AbortError\") {\n throw new ErrorTimeout(\"Network timed out\");\n }\n throw err;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n async getJson(url, {\n token,\n credentials\n } = {}) {\n const logger2 = this._logger.create(\"getJson\");\n const headers = {\n \"Accept\": this._contentTypes.join(\", \")\n };\n if (token) {\n logger2.debug(\"token passed, setting Authorization header\");\n headers[\"Authorization\"] = \"Bearer \" + token;\n }\n this.appendExtraHeaders(headers);\n let response;\n try {\n logger2.debug(\"url:\", url);\n response = await this.fetchWithTimeout(url, { method: \"GET\", headers, credentials });\n } catch (err) {\n logger2.error(\"Network Error\");\n throw err;\n }\n logger2.debug(\"HTTP response received, status\", response.status);\n const contentType = response.headers.get(\"Content-Type\");\n if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) {\n logger2.throw(new Error(`Invalid response Content-Type: ${contentType != null ? contentType : \"undefined\"}, from URL: ${url}`));\n }\n if (response.ok && this._jwtHandler && (contentType == null ? void 0 : contentType.startsWith(\"application/jwt\"))) {\n return await this._jwtHandler(await response.text());\n }\n let json;\n try {\n json = await response.json();\n } catch (err) {\n logger2.error(\"Error parsing JSON response\", err);\n if (response.ok)\n throw err;\n throw new Error(`${response.statusText} (${response.status})`);\n }\n if (!response.ok) {\n logger2.error(\"Error from server:\", json);\n if (json.error) {\n throw new ErrorResponse(json);\n }\n throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);\n }\n return json;\n }\n async postForm(url, {\n body,\n basicAuth,\n timeoutInSeconds,\n initCredentials\n }) {\n const logger2 = this._logger.create(\"postForm\");\n const headers = {\n \"Accept\": this._contentTypes.join(\", \"),\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n };\n if (basicAuth !== void 0) {\n headers[\"Authorization\"] = \"Basic \" + basicAuth;\n }\n this.appendExtraHeaders(headers);\n let response;\n try {\n logger2.debug(\"url:\", url);\n response = await this.fetchWithTimeout(url, { method: \"POST\", headers, body, timeoutInSeconds, credentials: initCredentials });\n } catch (err) {\n logger2.error(\"Network error\");\n throw err;\n }\n logger2.debug(\"HTTP response received, status\", response.status);\n const contentType = response.headers.get(\"Content-Type\");\n if (contentType && !this._contentTypes.find((item) => contentType.startsWith(item))) {\n throw new Error(`Invalid response Content-Type: ${contentType != null ? contentType : \"undefined\"}, from URL: ${url}`);\n }\n const responseText = await response.text();\n let json = {};\n if (responseText) {\n try {\n json = JSON.parse(responseText);\n } catch (err) {\n logger2.error(\"Error parsing JSON response\", err);\n if (response.ok)\n throw err;\n throw new Error(`${response.statusText} (${response.status})`);\n }\n }\n if (!response.ok) {\n logger2.error(\"Error from server:\", json);\n if (json.error) {\n throw new ErrorResponse(json, body);\n }\n throw new Error(`${response.statusText} (${response.status}): ${JSON.stringify(json)}`);\n }\n return json;\n }\n appendExtraHeaders(headers) {\n const logger2 = this._logger.create(\"appendExtraHeaders\");\n const customKeys = Object.keys(this._extraHeaders);\n const protectedHeaders = [\n \"authorization\",\n \"accept\",\n \"content-type\"\n ];\n if (customKeys.length === 0) {\n return;\n }\n customKeys.forEach((headerName) => {\n if (protectedHeaders.includes(headerName.toLocaleLowerCase())) {\n logger2.warn(\"Protected header could not be overridden\", headerName, protectedHeaders);\n return;\n }\n const content = typeof this._extraHeaders[headerName] === \"function\" ? this._extraHeaders[headerName]() : this._extraHeaders[headerName];\n if (content && content !== \"\") {\n headers[headerName] = content;\n }\n });\n }\n};\n\n// src/MetadataService.ts\nvar MetadataService = class {\n constructor(_settings) {\n this._settings = _settings;\n this._logger = new Logger(\"MetadataService\");\n this._signingKeys = null;\n this._metadata = null;\n this._metadataUrl = this._settings.metadataUrl;\n this._jsonService = new JsonService(\n [\"application/jwk-set+json\"],\n null,\n this._settings.extraHeaders\n );\n if (this._settings.signingKeys) {\n this._logger.debug(\"using signingKeys from settings\");\n this._signingKeys = this._settings.signingKeys;\n }\n if (this._settings.metadata) {\n this._logger.debug(\"using metadata from settings\");\n this._metadata = this._settings.metadata;\n }\n if (this._settings.fetchRequestCredentials) {\n this._logger.debug(\"using fetchRequestCredentials from settings\");\n this._fetchRequestCredentials = this._settings.fetchRequestCredentials;\n }\n }\n resetSigningKeys() {\n this._signingKeys = null;\n }\n async getMetadata() {\n const logger2 = this._logger.create(\"getMetadata\");\n if (this._metadata) {\n logger2.debug(\"using cached values\");\n return this._metadata;\n }\n if (!this._metadataUrl) {\n logger2.throw(new Error(\"No authority or metadataUrl configured on settings\"));\n throw null;\n }\n logger2.debug(\"getting metadata from\", this._metadataUrl);\n const metadata = await this._jsonService.getJson(this._metadataUrl, { credentials: this._fetchRequestCredentials });\n logger2.debug(\"merging remote JSON with seed metadata\");\n this._metadata = Object.assign({}, this._settings.metadataSeed, metadata);\n return this._metadata;\n }\n getIssuer() {\n return this._getMetadataProperty(\"issuer\");\n }\n getAuthorizationEndpoint() {\n return this._getMetadataProperty(\"authorization_endpoint\");\n }\n getUserInfoEndpoint() {\n return this._getMetadataProperty(\"userinfo_endpoint\");\n }\n getTokenEndpoint(optional = true) {\n return this._getMetadataProperty(\"token_endpoint\", optional);\n }\n getCheckSessionIframe() {\n return this._getMetadataProperty(\"check_session_iframe\", true);\n }\n getEndSessionEndpoint() {\n return this._getMetadataProperty(\"end_session_endpoint\", true);\n }\n getRevocationEndpoint(optional = true) {\n return this._getMetadataProperty(\"revocation_endpoint\", optional);\n }\n getKeysEndpoint(optional = true) {\n return this._getMetadataProperty(\"jwks_uri\", optional);\n }\n async _getMetadataProperty(name, optional = false) {\n const logger2 = this._logger.create(`_getMetadataProperty('${name}')`);\n const metadata = await this.getMetadata();\n logger2.debug(\"resolved\");\n if (metadata[name] === void 0) {\n if (optional === true) {\n logger2.warn(\"Metadata does not contain optional property\");\n return void 0;\n }\n logger2.throw(new Error(\"Metadata does not contain property \" + name));\n }\n return metadata[name];\n }\n async getSigningKeys() {\n const logger2 = this._logger.create(\"getSigningKeys\");\n if (this._signingKeys) {\n logger2.debug(\"returning signingKeys from cache\");\n return this._signingKeys;\n }\n const jwks_uri = await this.getKeysEndpoint(false);\n logger2.debug(\"got jwks_uri\", jwks_uri);\n const keySet = await this._jsonService.getJson(jwks_uri);\n logger2.debug(\"got key set\", keySet);\n if (!Array.isArray(keySet.keys)) {\n logger2.throw(new Error(\"Missing keys on keyset\"));\n throw null;\n }\n this._signingKeys = keySet.keys;\n return this._signingKeys;\n }\n};\n\n// src/WebStorageStateStore.ts\nvar WebStorageStateStore = class {\n constructor({\n prefix = \"oidc.\",\n store = localStorage\n } = {}) {\n this._logger = new Logger(\"WebStorageStateStore\");\n this._store = store;\n this._prefix = prefix;\n }\n async set(key, value) {\n this._logger.create(`set('${key}')`);\n key = this._prefix + key;\n await this._store.setItem(key, value);\n }\n async get(key) {\n this._logger.create(`get('${key}')`);\n key = this._prefix + key;\n const item = await this._store.getItem(key);\n return item;\n }\n async remove(key) {\n this._logger.create(`remove('${key}')`);\n key = this._prefix + key;\n const item = await this._store.getItem(key);\n await this._store.removeItem(key);\n return item;\n }\n async getAllKeys() {\n this._logger.create(\"getAllKeys\");\n const len = await this._store.length;\n const keys = [];\n for (let index = 0; index < len; index++) {\n const key = await this._store.key(index);\n if (key && key.indexOf(this._prefix) === 0) {\n keys.push(key.substr(this._prefix.length));\n }\n }\n return keys;\n }\n};\n\n// src/OidcClientSettings.ts\nvar DefaultResponseType = \"code\";\nvar DefaultScope = \"openid\";\nvar DefaultClientAuthentication = \"client_secret_post\";\nvar DefaultStaleStateAgeInSeconds = 60 * 15;\nvar OidcClientSettingsStore = class {\n constructor({\n // metadata related\n authority,\n metadataUrl,\n metadata,\n signingKeys,\n metadataSeed,\n // client related\n client_id,\n client_secret,\n response_type = DefaultResponseType,\n scope = DefaultScope,\n redirect_uri,\n post_logout_redirect_uri,\n client_authentication = DefaultClientAuthentication,\n // optional protocol\n prompt,\n display,\n max_age,\n ui_locales,\n acr_values,\n resource,\n response_mode,\n // behavior flags\n filterProtocolClaims = true,\n loadUserInfo = false,\n staleStateAgeInSeconds = DefaultStaleStateAgeInSeconds,\n mergeClaimsStrategy = { array: \"replace\" },\n disablePKCE = false,\n // other behavior\n stateStore,\n revokeTokenAdditionalContentTypes,\n fetchRequestCredentials,\n refreshTokenAllowedScope,\n // extra\n extraQueryParams = {},\n extraTokenParams = {},\n extraHeaders = {}\n }) {\n this.authority = authority;\n if (metadataUrl) {\n this.metadataUrl = metadataUrl;\n } else {\n this.metadataUrl = authority;\n if (authority) {\n if (!this.metadataUrl.endsWith(\"/\")) {\n this.metadataUrl += \"/\";\n }\n this.metadataUrl += \".well-known/openid-configuration\";\n }\n }\n this.metadata = metadata;\n this.metadataSeed = metadataSeed;\n this.signingKeys = signingKeys;\n this.client_id = client_id;\n this.client_secret = client_secret;\n this.response_type = response_type;\n this.scope = scope;\n this.redirect_uri = redirect_uri;\n this.post_logout_redirect_uri = post_logout_redirect_uri;\n this.client_authentication = client_authentication;\n this.prompt = prompt;\n this.display = display;\n this.max_age = max_age;\n this.ui_locales = ui_locales;\n this.acr_values = acr_values;\n this.resource = resource;\n this.response_mode = response_mode;\n this.filterProtocolClaims = filterProtocolClaims != null ? filterProtocolClaims : true;\n this.loadUserInfo = !!loadUserInfo;\n this.staleStateAgeInSeconds = staleStateAgeInSeconds;\n this.mergeClaimsStrategy = mergeClaimsStrategy;\n this.disablePKCE = !!disablePKCE;\n this.revokeTokenAdditionalContentTypes = revokeTokenAdditionalContentTypes;\n this.fetchRequestCredentials = fetchRequestCredentials ? fetchRequestCredentials : \"same-origin\";\n if (stateStore) {\n this.stateStore = stateStore;\n } else {\n const store = typeof window !== \"undefined\" ? window.localStorage : new InMemoryWebStorage();\n this.stateStore = new WebStorageStateStore({ store });\n }\n this.refreshTokenAllowedScope = refreshTokenAllowedScope;\n this.extraQueryParams = extraQueryParams;\n this.extraTokenParams = extraTokenParams;\n this.extraHeaders = extraHeaders;\n }\n};\n\n// src/UserInfoService.ts\nvar UserInfoService = class {\n constructor(_settings, _metadataService) {\n this._settings = _settings;\n this._metadataService = _metadataService;\n this._logger = new Logger(\"UserInfoService\");\n this._getClaimsFromJwt = async (responseText) => {\n const logger2 = this._logger.create(\"_getClaimsFromJwt\");\n try {\n const payload = JwtUtils.decode(responseText);\n logger2.debug(\"JWT decoding successful\");\n return payload;\n } catch (err) {\n logger2.error(\"Error parsing JWT response\");\n throw err;\n }\n };\n this._jsonService = new JsonService(\n void 0,\n this._getClaimsFromJwt,\n this._settings.extraHeaders\n );\n }\n async getClaims(token) {\n const logger2 = this._logger.create(\"getClaims\");\n if (!token) {\n this._logger.throw(new Error(\"No token passed\"));\n }\n const url = await this._metadataService.getUserInfoEndpoint();\n logger2.debug(\"got userinfo url\", url);\n const claims = await this._jsonService.getJson(url, {\n token,\n credentials: this._settings.fetchRequestCredentials\n });\n logger2.debug(\"got claims\", claims);\n return claims;\n }\n};\n\n// src/TokenClient.ts\nvar TokenClient = class {\n constructor(_settings, _metadataService) {\n this._settings = _settings;\n this._metadataService = _metadataService;\n this._logger = new Logger(\"TokenClient\");\n this._jsonService = new JsonService(\n this._settings.revokeTokenAdditionalContentTypes,\n null,\n this._settings.extraHeaders\n );\n }\n /**\n * Exchange code.\n *\n * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3\n */\n async exchangeCode({\n grant_type = \"authorization_code\",\n redirect_uri = this._settings.redirect_uri,\n client_id = this._settings.client_id,\n client_secret = this._settings.client_secret,\n ...args\n }) {\n const logger2 = this._logger.create(\"exchangeCode\");\n if (!client_id) {\n logger2.throw(new Error(\"A client_id is required\"));\n }\n if (!redirect_uri) {\n logger2.throw(new Error(\"A redirect_uri is required\"));\n }\n if (!args.code) {\n logger2.throw(new Error(\"A code is required\"));\n }\n const params = new URLSearchParams({ grant_type, redirect_uri });\n for (const [key, value] of Object.entries(args)) {\n if (value != null) {\n params.set(key, value);\n }\n }\n let basicAuth;\n switch (this._settings.client_authentication) {\n case \"client_secret_basic\":\n if (!client_secret) {\n logger2.throw(new Error(\"A client_secret is required\"));\n throw null;\n }\n basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n break;\n case \"client_secret_post\":\n params.append(\"client_id\", client_id);\n if (client_secret) {\n params.append(\"client_secret\", client_secret);\n }\n break;\n }\n const url = await this._metadataService.getTokenEndpoint(false);\n logger2.debug(\"got token endpoint\");\n const response = await this._jsonService.postForm(url, { body: params, basicAuth, initCredentials: this._settings.fetchRequestCredentials });\n logger2.debug(\"got response\");\n return response;\n }\n /**\n * Exchange credentials.\n *\n * @see https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2\n */\n async exchangeCredentials({\n grant_type = \"password\",\n client_id = this._settings.client_id,\n client_secret = this._settings.client_secret,\n scope = this._settings.scope,\n ...args\n }) {\n const logger2 = this._logger.create(\"exchangeCredentials\");\n if (!client_id) {\n logger2.throw(new Error(\"A client_id is required\"));\n }\n const params = new URLSearchParams({ grant_type, scope });\n for (const [key, value] of Object.entries(args)) {\n if (value != null) {\n params.set(key, value);\n }\n }\n let basicAuth;\n switch (this._settings.client_authentication) {\n case \"client_secret_basic\":\n if (!client_secret) {\n logger2.throw(new Error(\"A client_secret is required\"));\n throw null;\n }\n basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n break;\n case \"client_secret_post\":\n params.append(\"client_id\", client_id);\n if (client_secret) {\n params.append(\"client_secret\", client_secret);\n }\n break;\n }\n const url = await this._metadataService.getTokenEndpoint(false);\n logger2.debug(\"got token endpoint\");\n const response = await this._jsonService.postForm(url, { body: params, basicAuth, initCredentials: this._settings.fetchRequestCredentials });\n logger2.debug(\"got response\");\n return response;\n }\n /**\n * Exchange a refresh token.\n *\n * @see https://www.rfc-editor.org/rfc/rfc6749#section-6\n */\n async exchangeRefreshToken({\n grant_type = \"refresh_token\",\n client_id = this._settings.client_id,\n client_secret = this._settings.client_secret,\n timeoutInSeconds,\n ...args\n }) {\n const logger2 = this._logger.create(\"exchangeRefreshToken\");\n if (!client_id) {\n logger2.throw(new Error(\"A client_id is required\"));\n }\n if (!args.refresh_token) {\n logger2.throw(new Error(\"A refresh_token is required\"));\n }\n const params = new URLSearchParams({ grant_type });\n for (const [key, value] of Object.entries(args)) {\n if (Array.isArray(value)) {\n value.forEach((param) => params.append(key, param));\n } else if (value != null) {\n params.set(key, value);\n }\n }\n let basicAuth;\n switch (this._settings.client_authentication) {\n case \"client_secret_basic\":\n if (!client_secret) {\n logger2.throw(new Error(\"A client_secret is required\"));\n throw null;\n }\n basicAuth = CryptoUtils.generateBasicAuth(client_id, client_secret);\n break;\n case \"client_secret_post\":\n params.append(\"client_id\", client_id);\n if (client_secret) {\n params.append(\"client_secret\", client_secret);\n }\n break;\n }\n const url = await this._metadataService.getTokenEndpoint(false);\n logger2.debug(\"got token endpoint\");\n const response = await this._jsonService.postForm(url, { body: params, basicAuth, timeoutInSeconds, initCredentials: this._settings.fetchRequestCredentials });\n logger2.debug(\"got response\");\n return response;\n }\n /**\n * Revoke an access or refresh token.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc7009#section-2.1\n */\n async revoke(args) {\n var _a;\n const logger2 = this._logger.create(\"revoke\");\n if (!args.token) {\n logger2.throw(new Error(\"A token is required\"));\n }\n const url = await this._metadataService.getRevocationEndpoint(false);\n logger2.debug(`got revocation endpoint, revoking ${(_a = args.token_type_hint) != null ? _a : \"default token type\"}`);\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(args)) {\n if (value != null) {\n params.set(key, value);\n }\n }\n params.set(\"client_id\", this._settings.client_id);\n if (this._settings.client_secret) {\n params.set(\"client_secret\", this._settings.client_secret);\n }\n await this._jsonService.postForm(url, { body: params });\n logger2.debug(\"got response\");\n }\n};\n\n// src/ResponseValidator.ts\nvar ResponseValidator = class {\n constructor(_settings, _metadataService, _claimsService) {\n this._settings = _settings;\n this._metadataService = _metadataService;\n this._claimsService = _claimsService;\n this._logger = new Logger(\"ResponseValidator\");\n this._userInfoService = new UserInfoService(this._settings, this._metadataService);\n this._tokenClient = new TokenClient(this._settings, this._metadataService);\n }\n async validateSigninResponse(response, state) {\n const logger2 = this._logger.create(\"validateSigninResponse\");\n this._processSigninState(response, state);\n logger2.debug(\"state processed\");\n await this._processCode(response, state);\n logger2.debug(\"code processed\");\n if (response.isOpenId) {\n this._validateIdTokenAttributes(response);\n }\n logger2.debug(\"tokens validated\");\n await this._processClaims(response, state == null ? void 0 : state.skipUserInfo, response.isOpenId);\n logger2.debug(\"claims processed\");\n }\n async validateCredentialsResponse(response, skipUserInfo) {\n const logger2 = this._logger.create(\"validateCredentialsResponse\");\n if (response.isOpenId && !!response.id_token) {\n this._validateIdTokenAttributes(response);\n }\n logger2.debug(\"tokens validated\");\n await this._processClaims(response, skipUserInfo, response.isOpenId);\n logger2.debug(\"claims processed\");\n }\n async validateRefreshResponse(response, state) {\n var _a, _b;\n const logger2 = this._logger.create(\"validateRefreshResponse\");\n response.userState = state.data;\n (_a = response.session_state) != null ? _a : response.session_state = state.session_state;\n (_b = response.scope) != null ? _b : response.scope = state.scope;\n if (response.isOpenId && !!response.id_token) {\n this._validateIdTokenAttributes(response, state.id_token);\n logger2.debug(\"ID Token validated\");\n }\n if (!response.id_token) {\n response.id_token = state.id_token;\n response.profile = state.profile;\n }\n const hasIdToken = response.isOpenId && !!response.id_token;\n await this._processClaims(response, false, hasIdToken);\n logger2.debug(\"claims processed\");\n }\n validateSignoutResponse(response, state) {\n const logger2 = this._logger.create(\"validateSignoutResponse\");\n if (state.id !== response.state) {\n logger2.throw(new Error(\"State does not match\"));\n }\n logger2.debug(\"state validated\");\n response.userState = state.data;\n if (response.error) {\n logger2.warn(\"Response was error\", response.error);\n throw new ErrorResponse(response);\n }\n }\n _processSigninState(response, state) {\n var _a;\n const logger2 = this._logger.create(\"_processSigninState\");\n if (state.id !== response.state) {\n logger2.throw(new Error(\"State does not match\"));\n }\n if (!state.client_id) {\n logger2.throw(new Error(\"No client_id on state\"));\n }\n if (!state.authority) {\n logger2.throw(new Error(\"No authority on state\"));\n }\n if (this._settings.authority !== state.authority) {\n logger2.throw(new Error(\"authority mismatch on settings vs. signin state\"));\n }\n if (this._settings.client_id && this._settings.client_id !== state.client_id) {\n logger2.throw(new Error(\"client_id mismatch on settings vs. signin state\"));\n }\n logger2.debug(\"state validated\");\n response.userState = state.data;\n response.url_state = state.url_state;\n (_a = response.scope) != null ? _a : response.scope = state.scope;\n if (response.error) {\n logger2.warn(\"Response was error\", response.error);\n throw new ErrorResponse(response);\n }\n if (state.code_verifier && !response.code) {\n logger2.throw(new Error(\"Expected code in response\"));\n }\n }\n async _processClaims(response, skipUserInfo = false, validateSub = true) {\n const logger2 = this._logger.create(\"_processClaims\");\n response.profile = this._claimsService.filterProtocolClaims(response.profile);\n if (skipUserInfo || !this._settings.loadUserInfo || !response.access_token) {\n logger2.debug(\"not loading user info\");\n return;\n }\n logger2.debug(\"loading user info\");\n const claims = await this._userInfoService.getClaims(response.access_token);\n logger2.debug(\"user info claims received from user info endpoint\");\n if (validateSub && claims.sub !== response.profile.sub) {\n logger2.throw(new Error(\"subject from UserInfo response does not match subject in ID Token\"));\n }\n response.profile = this._claimsService.mergeClaims(response.profile, this._claimsService.filterProtocolClaims(claims));\n logger2.debug(\"user info claims received, updated profile:\", response.profile);\n }\n async _processCode(response, state) {\n const logger2 = this._logger.create(\"_processCode\");\n if (response.code) {\n logger2.debug(\"Validating code\");\n const tokenResponse = await this._tokenClient.exchangeCode({\n client_id: state.client_id,\n client_secret: state.client_secret,\n code: response.code,\n redirect_uri: state.redirect_uri,\n code_verifier: state.code_verifier,\n ...state.extraTokenParams\n });\n Object.assign(response, tokenResponse);\n } else {\n logger2.debug(\"No code to process\");\n }\n }\n _validateIdTokenAttributes(response, existingToken) {\n var _a;\n const logger2 = this._logger.create(\"_validateIdTokenAttributes\");\n logger2.debug(\"decoding ID Token JWT\");\n const incoming = JwtUtils.decode((_a = response.id_token) != null ? _a : \"\");\n if (!incoming.sub) {\n logger2.throw(new Error(\"ID Token is missing a subject claim\"));\n }\n if (existingToken) {\n const existing = JwtUtils.decode(existingToken);\n if (incoming.sub !== existing.sub) {\n logger2.throw(new Error(\"sub in id_token does not match current sub\"));\n }\n if (incoming.auth_time && incoming.auth_time !== existing.auth_time) {\n logger2.throw(new Error(\"auth_time in id_token does not match original auth_time\"));\n }\n if (incoming.azp && incoming.azp !== existing.azp) {\n logger2.throw(new Error(\"azp in id_token does not match original azp\"));\n }\n if (!incoming.azp && existing.azp) {\n logger2.throw(new Error(\"azp not in id_token, but present in original id_token\"));\n }\n }\n response.profile = incoming;\n }\n};\n\n// src/State.ts\nvar State = class _State {\n constructor(args) {\n this.id = args.id || CryptoUtils.generateUUIDv4();\n this.data = args.data;\n if (args.created && args.created > 0) {\n this.created = args.created;\n } else {\n this.created = Timer.getEpochTime();\n }\n this.request_type = args.request_type;\n this.url_state = args.url_state;\n }\n toStorageString() {\n new Logger(\"State\").create(\"toStorageString\");\n return JSON.stringify({\n id: this.id,\n data: this.data,\n created: this.created,\n request_type: this.request_type,\n url_state: this.url_state\n });\n }\n static fromStorageString(storageString) {\n Logger.createStatic(\"State\", \"fromStorageString\");\n return Promise.resolve(new _State(JSON.parse(storageString)));\n }\n static async clearStaleState(storage, age) {\n const logger2 = Logger.createStatic(\"State\", \"clearStaleState\");\n const cutoff = Timer.getEpochTime() - age;\n const keys = await storage.getAllKeys();\n logger2.debug(\"got keys\", keys);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const item = await storage.get(key);\n let remove = false;\n if (item) {\n try {\n const state = await _State.fromStorageString(item);\n logger2.debug(\"got item from key:\", key, state.created);\n if (state.created <= cutoff) {\n remove = true;\n }\n } catch (err) {\n logger2.error(\"Error parsing state for key:\", key, err);\n remove = true;\n }\n } else {\n logger2.debug(\"no item in storage for key:\", key);\n remove = true;\n }\n if (remove) {\n logger2.debug(\"removed item for key:\", key);\n void storage.remove(key);\n }\n }\n }\n};\n\n// src/SigninState.ts\nvar SigninState = class _SigninState extends State {\n constructor(args) {\n super(args);\n this.code_verifier = args.code_verifier;\n this.code_challenge = args.code_challenge;\n this.authority = args.authority;\n this.client_id = args.client_id;\n this.redirect_uri = args.redirect_uri;\n this.scope = args.scope;\n this.client_secret = args.client_secret;\n this.extraTokenParams = args.extraTokenParams;\n this.response_mode = args.response_mode;\n this.skipUserInfo = args.skipUserInfo;\n }\n static async create(args) {\n const code_verifier = args.code_verifier === true ? CryptoUtils.generateCodeVerifier() : args.code_verifier || void 0;\n const code_challenge = code_verifier ? await CryptoUtils.generateCodeChallenge(code_verifier) : void 0;\n return new _SigninState({\n ...args,\n code_verifier,\n code_challenge\n });\n }\n toStorageString() {\n new Logger(\"SigninState\").create(\"toStorageString\");\n return JSON.stringify({\n id: this.id,\n data: this.data,\n created: this.created,\n request_type: this.request_type,\n url_state: this.url_state,\n code_verifier: this.code_verifier,\n authority: this.authority,\n client_id: this.client_id,\n redirect_uri: this.redirect_uri,\n scope: this.scope,\n client_secret: this.client_secret,\n extraTokenParams: this.extraTokenParams,\n response_mode: this.response_mode,\n skipUserInfo: this.skipUserInfo\n });\n }\n static fromStorageString(storageString) {\n Logger.createStatic(\"SigninState\", \"fromStorageString\");\n const data = JSON.parse(storageString);\n return _SigninState.create(data);\n }\n};\n\n// src/SigninRequest.ts\nvar _SigninRequest = class _SigninRequest {\n constructor(args) {\n this.url = args.url;\n this.state = args.state;\n }\n static async create({\n // mandatory\n url,\n authority,\n client_id,\n redirect_uri,\n response_type,\n scope,\n // optional\n state_data,\n response_mode,\n request_type,\n client_secret,\n nonce,\n url_state,\n resource,\n skipUserInfo,\n extraQueryParams,\n extraTokenParams,\n disablePKCE,\n ...optionalParams\n }) {\n if (!url) {\n this._logger.error(\"create: No url passed\");\n throw new Error(\"url\");\n }\n if (!client_id) {\n this._logger.error(\"create: No client_id passed\");\n throw new Error(\"client_id\");\n }\n if (!redirect_uri) {\n this._logger.error(\"create: No redirect_uri passed\");\n throw new Error(\"redirect_uri\");\n }\n if (!response_type) {\n this._logger.error(\"create: No response_type passed\");\n throw new Error(\"response_type\");\n }\n if (!scope) {\n this._logger.error(\"create: No scope passed\");\n throw new Error(\"scope\");\n }\n if (!authority) {\n this._logger.error(\"create: No authority passed\");\n throw new Error(\"authority\");\n }\n const state = await SigninState.create({\n data: state_data,\n request_type,\n url_state,\n code_verifier: !disablePKCE,\n client_id,\n authority,\n redirect_uri,\n response_mode,\n client_secret,\n scope,\n extraTokenParams,\n skipUserInfo\n });\n const parsedUrl = new URL(url);\n parsedUrl.searchParams.append(\"client_id\", client_id);\n parsedUrl.searchParams.append(\"redirect_uri\", redirect_uri);\n parsedUrl.searchParams.append(\"response_type\", response_type);\n parsedUrl.searchParams.append(\"scope\", scope);\n if (nonce) {\n parsedUrl.searchParams.append(\"nonce\", nonce);\n }\n let stateParam = state.id;\n if (url_state) {\n stateParam = `${stateParam}${URL_STATE_DELIMITER}${url_state}`;\n }\n parsedUrl.searchParams.append(\"state\", stateParam);\n if (state.code_challenge) {\n parsedUrl.searchParams.append(\"code_challenge\", state.code_challenge);\n parsedUrl.searchParams.append(\"code_challenge_method\", \"S256\");\n }\n if (resource) {\n const resources = Array.isArray(resource) ? resource : [resource];\n resources.forEach((r) => parsedUrl.searchParams.append(\"resource\", r));\n }\n for (const [key, value] of Object.entries({ response_mode, ...optionalParams, ...extraQueryParams })) {\n if (value != null) {\n parsedUrl.searchParams.append(key, value.toString());\n }\n }\n return new _SigninRequest({\n url: parsedUrl.href,\n state\n });\n }\n};\n_SigninRequest._logger = new Logger(\"SigninRequest\");\nvar SigninRequest = _SigninRequest;\n\n// src/SigninResponse.ts\nvar OidcScope = \"openid\";\nvar SigninResponse = class {\n constructor(params) {\n /** @see {@link User.access_token} */\n this.access_token = \"\";\n /** @see {@link User.token_type} */\n this.token_type = \"\";\n /** @see {@link User.profile} */\n this.profile = {};\n this.state = params.get(\"state\");\n this.session_state = params.get(\"session_state\");\n if (this.state) {\n const splitState = decodeURIComponent(this.state).split(URL_STATE_DELIMITER);\n this.state = splitState[0];\n if (splitState.length > 1) {\n this.url_state = splitState.slice(1).join(URL_STATE_DELIMITER);\n }\n }\n this.error = params.get(\"error\");\n this.error_description = params.get(\"error_description\");\n this.error_uri = params.get(\"error_uri\");\n this.code = params.get(\"code\");\n }\n get expires_in() {\n if (this.expires_at === void 0) {\n return void 0;\n }\n return this.expires_at - Timer.getEpochTime();\n }\n set expires_in(value) {\n if (typeof value === \"string\")\n value = Number(value);\n if (value !== void 0 && value >= 0) {\n this.expires_at = Math.floor(value) + Timer.getEpochTime();\n }\n }\n get isOpenId() {\n var _a;\n return ((_a = this.scope) == null ? void 0 : _a.split(\" \").includes(OidcScope)) || !!this.id_token;\n }\n};\n\n// src/SignoutRequest.ts\nvar SignoutRequest = class {\n constructor({\n url,\n state_data,\n id_token_hint,\n post_logout_redirect_uri,\n extraQueryParams,\n request_type,\n client_id\n }) {\n this._logger = new Logger(\"SignoutRequest\");\n if (!url) {\n this._logger.error(\"ctor: No url passed\");\n throw new Error(\"url\");\n }\n const parsedUrl = new URL(url);\n if (id_token_hint) {\n parsedUrl.searchParams.append(\"id_token_hint\", id_token_hint);\n }\n if (client_id) {\n parsedUrl.searchParams.append(\"client_id\", client_id);\n }\n if (post_logout_redirect_uri) {\n parsedUrl.searchParams.append(\"post_logout_redirect_uri\", post_logout_redirect_uri);\n if (state_data) {\n this.state = new State({ data: state_data, request_type });\n parsedUrl.searchParams.append(\"state\", this.state.id);\n }\n }\n for (const [key, value] of Object.entries({ ...extraQueryParams })) {\n if (value != null) {\n parsedUrl.searchParams.append(key, value.toString());\n }\n }\n this.url = parsedUrl.href;\n }\n};\n\n// src/SignoutResponse.ts\nvar SignoutResponse = class {\n constructor(params) {\n this.state = params.get(\"state\");\n this.error = params.get(\"error\");\n this.error_description = params.get(\"error_description\");\n this.error_uri = params.get(\"error_uri\");\n }\n};\n\n// src/ClaimsService.ts\nvar DefaultProtocolClaims = [\n \"nbf\",\n \"jti\",\n \"auth_time\",\n \"nonce\",\n \"acr\",\n \"amr\",\n \"azp\",\n \"at_hash\"\n // https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken\n];\nvar InternalRequiredProtocolClaims = [\"sub\", \"iss\", \"aud\", \"exp\", \"iat\"];\nvar ClaimsService = class {\n constructor(_settings) {\n this._settings = _settings;\n this._logger = new Logger(\"ClaimsService\");\n }\n filterProtocolClaims(claims) {\n const result = { ...claims };\n if (this._settings.filterProtocolClaims) {\n let protocolClaims;\n if (Array.isArray(this._settings.filterProtocolClaims)) {\n protocolClaims = this._settings.filterProtocolClaims;\n } else {\n protocolClaims = DefaultProtocolClaims;\n }\n for (const claim of protocolClaims) {\n if (!InternalRequiredProtocolClaims.includes(claim)) {\n delete result[claim];\n }\n }\n }\n return result;\n }\n mergeClaims(claims1, claims2) {\n const result = { ...claims1 };\n for (const [claim, values] of Object.entries(claims2)) {\n if (result[claim] !== values) {\n if (Array.isArray(result[claim]) || Array.isArray(values)) {\n if (this._settings.mergeClaimsStrategy.array == \"replace\") {\n result[claim] = values;\n } else {\n const mergedValues = Array.isArray(result[claim]) ? result[claim] : [result[claim]];\n for (const value of Array.isArray(values) ? values : [values]) {\n if (!mergedValues.includes(value)) {\n mergedValues.push(value);\n }\n }\n result[claim] = mergedValues;\n }\n } else if (typeof result[claim] === \"object\" && typeof values === \"object\") {\n result[claim] = this.mergeClaims(result[claim], values);\n } else {\n result[claim] = values;\n }\n }\n }\n return result;\n }\n};\n\n// src/OidcClient.ts\nvar OidcClient = class {\n constructor(settings, metadataService) {\n this._logger = new Logger(\"OidcClient\");\n this.settings = settings instanceof OidcClientSettingsStore ? settings : new OidcClientSettingsStore(settings);\n this.metadataService = metadataService != null ? metadataService : new MetadataService(this.settings);\n this._claimsService = new ClaimsService(this.settings);\n this._validator = new ResponseValidator(this.settings, this.metadataService, this._claimsService);\n this._tokenClient = new TokenClient(this.settings, this.metadataService);\n }\n async createSigninRequest({\n state,\n request,\n request_uri,\n request_type,\n id_token_hint,\n login_hint,\n skipUserInfo,\n nonce,\n url_state,\n response_type = this.settings.response_type,\n scope = this.settings.scope,\n redirect_uri = this.settings.redirect_uri,\n prompt = this.settings.prompt,\n display = this.settings.display,\n max_age = this.settings.max_age,\n ui_locales = this.settings.ui_locales,\n acr_values = this.settings.acr_values,\n resource = this.settings.resource,\n response_mode = this.settings.response_mode,\n extraQueryParams = this.settings.extraQueryParams,\n extraTokenParams = this.settings.extraTokenParams\n }) {\n const logger2 = this._logger.create(\"createSigninRequest\");\n if (response_type !== \"code\") {\n throw new Error(\"Only the Authorization Code flow (with PKCE) is supported\");\n }\n const url = await this.metadataService.getAuthorizationEndpoint();\n logger2.debug(\"Received authorization endpoint\", url);\n const signinRequest = await SigninRequest.create({\n url,\n authority: this.settings.authority,\n client_id: this.settings.client_id,\n redirect_uri,\n response_type,\n scope,\n state_data: state,\n url_state,\n prompt,\n display,\n max_age,\n ui_locales,\n id_token_hint,\n login_hint,\n acr_values,\n resource,\n request,\n request_uri,\n extraQueryParams,\n extraTokenParams,\n request_type,\n response_mode,\n client_secret: this.settings.client_secret,\n skipUserInfo,\n nonce,\n disablePKCE: this.settings.disablePKCE\n });\n await this.clearStaleState();\n const signinState = signinRequest.state;\n await this.settings.stateStore.set(signinState.id, signinState.toStorageString());\n return signinRequest;\n }\n async readSigninResponseState(url, removeState = false) {\n const logger2 = this._logger.create(\"readSigninResponseState\");\n const response = new SigninResponse(UrlUtils.readParams(url, this.settings.response_mode));\n if (!response.state) {\n logger2.throw(new Error(\"No state in response\"));\n throw null;\n }\n const storedStateString = await this.settings.stateStore[removeState ? \"remove\" : \"get\"](response.state);\n if (!storedStateString) {\n logger2.throw(new Error(\"No matching state found in storage\"));\n throw null;\n }\n const state = await SigninState.fromStorageString(storedStateString);\n return { state, response };\n }\n async processSigninResponse(url) {\n const logger2 = this._logger.create(\"processSigninResponse\");\n const { state, response } = await this.readSigninResponseState(url, true);\n logger2.debug(\"received state from storage; validating response\");\n await this._validator.validateSigninResponse(response, state);\n return response;\n }\n async processResourceOwnerPasswordCredentials({\n username,\n password,\n skipUserInfo = false,\n extraTokenParams = {}\n }) {\n const tokenResponse = await this._tokenClient.exchangeCredentials({ username, password, ...extraTokenParams });\n const signinResponse = new SigninResponse(new URLSearchParams());\n Object.assign(signinResponse, tokenResponse);\n await this._validator.validateCredentialsResponse(signinResponse, skipUserInfo);\n return signinResponse;\n }\n async useRefreshToken({\n state,\n redirect_uri,\n resource,\n timeoutInSeconds,\n extraTokenParams\n }) {\n var _a;\n const logger2 = this._logger.create(\"useRefreshToken\");\n let scope;\n if (this.settings.refreshTokenAllowedScope === void 0) {\n scope = state.scope;\n } else {\n const allowableScopes = this.settings.refreshTokenAllowedScope.split(\" \");\n const providedScopes = ((_a = state.scope) == null ? void 0 : _a.split(\" \")) || [];\n scope = providedScopes.filter((s) => allowableScopes.includes(s)).join(\" \");\n }\n const result = await this._tokenClient.exchangeRefreshToken({\n refresh_token: state.refresh_token,\n // provide the (possible filtered) scope list\n scope,\n redirect_uri,\n resource,\n timeoutInSeconds,\n ...extraTokenParams\n });\n const response = new SigninResponse(new URLSearchParams());\n Object.assign(response, result);\n logger2.debug(\"validating response\", response);\n await this._validator.validateRefreshResponse(response, {\n ...state,\n // override the scope in the state handed over to the validator\n // so it can set the granted scope to the requested scope in case none is included in the response\n scope\n });\n return response;\n }\n async createSignoutRequest({\n state,\n id_token_hint,\n client_id,\n request_type,\n post_logout_redirect_uri = this.settings.post_logout_redirect_uri,\n extraQueryParams = this.settings.extraQueryParams\n } = {}) {\n const logger2 = this._logger.create(\"createSignoutRequest\");\n const url = await this.metadataService.getEndSessionEndpoint();\n if (!url) {\n logger2.throw(new Error(\"No end session endpoint\"));\n throw null;\n }\n logger2.debug(\"Received end session endpoint\", url);\n if (!client_id && post_logout_redirect_uri && !id_token_hint) {\n client_id = this.settings.client_id;\n }\n const request = new SignoutRequest({\n url,\n id_token_hint,\n client_id,\n post_logout_redirect_uri,\n state_data: state,\n extraQueryParams,\n request_type\n });\n await this.clearStaleState();\n const signoutState = request.state;\n if (signoutState) {\n logger2.debug(\"Signout request has state to persist\");\n await this.settings.stateStore.set(signoutState.id, signoutState.toStorageString());\n }\n return request;\n }\n async readSignoutResponseState(url, removeState = false) {\n const logger2 = this._logger.create(\"readSignoutResponseState\");\n const response = new SignoutResponse(UrlUtils.readParams(url, this.settings.response_mode));\n if (!response.state) {\n logger2.debug(\"No state in response\");\n if (response.error) {\n logger2.warn(\"Response was error:\", response.error);\n throw new ErrorResponse(response);\n }\n return { state: void 0, response };\n }\n const storedStateString = await this.settings.stateStore[removeState ? \"remove\" : \"get\"](response.state);\n if (!storedStateString) {\n logger2.throw(new Error(\"No matching state found in storage\"));\n throw null;\n }\n const state = await State.fromStorageString(storedStateString);\n return { state, response };\n }\n async processSignoutResponse(url) {\n const logger2 = this._logger.create(\"processSignoutResponse\");\n const { state, response } = await this.readSignoutResponseState(url, true);\n if (state) {\n logger2.debug(\"Received state from storage; validating response\");\n this._validator.validateSignoutResponse(response, state);\n } else {\n logger2.debug(\"No state from storage; skipping response validation\");\n }\n return response;\n }\n clearStaleState() {\n this._logger.create(\"clearStaleState\");\n return State.clearStaleState(this.settings.stateStore, this.settings.staleStateAgeInSeconds);\n }\n async revokeToken(token, type) {\n this._logger.create(\"revokeToken\");\n return await this._tokenClient.revoke({\n token,\n token_type_hint: type\n });\n }\n};\n\n// src/SessionMonitor.ts\nvar SessionMonitor = class {\n constructor(_userManager) {\n this._userManager = _userManager;\n this._logger = new Logger(\"SessionMonitor\");\n this._start = async (user) => {\n const session_state = user.session_state;\n if (!session_state) {\n return;\n }\n const logger2 = this._logger.create(\"_start\");\n if (user.profile) {\n this._sub = user.profile.sub;\n logger2.debug(\"session_state\", session_state, \", sub\", this._sub);\n } else {\n this._sub = void 0;\n logger2.debug(\"session_state\", session_state, \", anonymous user\");\n }\n if (this._checkSessionIFrame) {\n this._checkSessionIFrame.start(session_state);\n return;\n }\n try {\n const url = await this._userManager.metadataService.getCheckSessionIframe();\n if (url) {\n logger2.debug(\"initializing check session iframe\");\n const client_id = this._userManager.settings.client_id;\n const intervalInSeconds = this._userManager.settings.checkSessionIntervalInSeconds;\n const stopOnError = this._userManager.settings.stopCheckSessionOnError;\n const checkSessionIFrame = new CheckSessionIFrame(this._callback, client_id, url, intervalInSeconds, stopOnError);\n await checkSessionIFrame.load();\n this._checkSessionIFrame = checkSessionIFrame;\n checkSessionIFrame.start(session_state);\n } else {\n logger2.warn(\"no check session iframe found in the metadata\");\n }\n } catch (err) {\n logger2.error(\"Error from getCheckSessionIframe:\", err instanceof Error ? err.message : err);\n }\n };\n this._stop = () => {\n const logger2 = this._logger.create(\"_stop\");\n this._sub = void 0;\n if (this._checkSessionIFrame) {\n this._checkSessionIFrame.stop();\n }\n if (this._userManager.settings.monitorAnonymousSession) {\n const timerHandle = setInterval(async () => {\n clearInterval(timerHandle);\n try {\n const session = await this._userManager.querySessionStatus();\n if (session) {\n const tmpUser = {\n session_state: session.session_state,\n profile: session.sub ? {\n sub: session.sub\n } : null\n };\n void this._start(tmpUser);\n }\n } catch (err) {\n logger2.error(\"error from querySessionStatus\", err instanceof Error ? err.message : err);\n }\n }, 1e3);\n }\n };\n this._callback = async () => {\n const logger2 = this._logger.create(\"_callback\");\n try {\n const session = await this._userManager.querySessionStatus();\n let raiseEvent = true;\n if (session && this._checkSessionIFrame) {\n if (session.sub === this._sub) {\n raiseEvent = false;\n this._checkSessionIFrame.start(session.session_state);\n logger2.debug(\"same sub still logged in at OP, session state has changed, restarting check session iframe; session_state\", session.session_state);\n await this._userManager.events._raiseUserSessionChanged();\n } else {\n logger2.debug(\"different subject signed into OP\", session.sub);\n }\n } else {\n logger2.debug(\"subject no longer signed into OP\");\n }\n if (raiseEvent) {\n if (this._sub) {\n await this._userManager.events._raiseUserSignedOut();\n } else {\n await this._userManager.events._raiseUserSignedIn();\n }\n } else {\n logger2.debug(\"no change in session detected, no event to raise\");\n }\n } catch (err) {\n if (this._sub) {\n logger2.debug(\"Error calling queryCurrentSigninSession; raising signed out event\", err);\n await this._userManager.events._raiseUserSignedOut();\n }\n }\n };\n if (!_userManager) {\n this._logger.throw(new Error(\"No user manager passed\"));\n }\n this._userManager.events.addUserLoaded(this._start);\n this._userManager.events.addUserUnloaded(this._stop);\n this._init().catch((err) => {\n this._logger.error(err);\n });\n }\n async _init() {\n this._logger.create(\"_init\");\n const user = await this._userManager.getUser();\n if (user) {\n void this._start(user);\n } else if (this._userManager.settings.monitorAnonymousSession) {\n const session = await this._userManager.querySessionStatus();\n if (session) {\n const tmpUser = {\n session_state: session.session_state,\n profile: session.sub ? {\n sub: session.sub\n } : null\n };\n void this._start(tmpUser);\n }\n }\n }\n};\n\n// src/User.ts\nvar User = class _User {\n constructor(args) {\n var _a;\n this.id_token = args.id_token;\n this.session_state = (_a = args.session_state) != null ? _a : null;\n this.access_token = args.access_token;\n this.refresh_token = args.refresh_token;\n this.token_type = args.token_type;\n this.scope = args.scope;\n this.profile = args.profile;\n this.expires_at = args.expires_at;\n this.state = args.userState;\n this.url_state = args.url_state;\n }\n /** Computed number of seconds the access token has remaining. */\n get expires_in() {\n if (this.expires_at === void 0) {\n return void 0;\n }\n return this.expires_at - Timer.getEpochTime();\n }\n set expires_in(value) {\n if (value !== void 0) {\n this.expires_at = Math.floor(value) + Timer.getEpochTime();\n }\n }\n /** Computed value indicating if the access token is expired. */\n get expired() {\n const expires_in = this.expires_in;\n if (expires_in === void 0) {\n return void 0;\n }\n return expires_in <= 0;\n }\n /** Array representing the parsed values from the `scope`. */\n get scopes() {\n var _a, _b;\n return (_b = (_a = this.scope) == null ? void 0 : _a.split(\" \")) != null ? _b : [];\n }\n toStorageString() {\n new Logger(\"User\").create(\"toStorageString\");\n return JSON.stringify({\n id_token: this.id_token,\n session_state: this.session_state,\n access_token: this.access_token,\n refresh_token: this.refresh_token,\n token_type: this.token_type,\n scope: this.scope,\n profile: this.profile,\n expires_at: this.expires_at\n });\n }\n static fromStorageString(storageString) {\n Logger.createStatic(\"User\", \"fromStorageString\");\n return new _User(JSON.parse(storageString));\n }\n};\n\n// src/navigators/AbstractChildWindow.ts\nvar messageSource = \"oidc-client\";\nvar AbstractChildWindow = class {\n constructor() {\n this._abort = new Event(\"Window navigation aborted\");\n this._disposeHandlers = /* @__PURE__ */ new Set();\n this._window = null;\n }\n async navigate(params) {\n const logger2 = this._logger.create(\"navigate\");\n if (!this._window) {\n throw new Error(\"Attempted to navigate on a disposed window\");\n }\n logger2.debug(\"setting URL in window\");\n this._window.location.replace(params.url);\n const { url, keepOpen } = await new Promise((resolve, reject) => {\n const listener = (e) => {\n var _a;\n const data = e.data;\n const origin = (_a = params.scriptOrigin) != null ? _a : window.location.origin;\n if (e.origin !== origin || (data == null ? void 0 : data.source) !== messageSource) {\n return;\n }\n try {\n const state = UrlUtils.readParams(data.url, params.response_mode).get(\"state\");\n if (!state) {\n logger2.warn(\"no state found in response url\");\n }\n if (e.source !== this._window && state !== params.state) {\n return;\n }\n } catch (err) {\n this._dispose();\n reject(new Error(\"Invalid response from window\"));\n }\n resolve(data);\n };\n window.addEventListener(\"message\", listener, false);\n this._disposeHandlers.add(() => window.removeEventListener(\"message\", listener, false));\n this._disposeHandlers.add(this._abort.addHandler((reason) => {\n this._dispose();\n reject(reason);\n }));\n });\n logger2.debug(\"got response from window\");\n this._dispose();\n if (!keepOpen) {\n this.close();\n }\n return { url };\n }\n _dispose() {\n this._logger.create(\"_dispose\");\n for (const dispose of this._disposeHandlers) {\n dispose();\n }\n this._disposeHandlers.clear();\n }\n static _notifyParent(parent, url, keepOpen = false, targetOrigin = window.location.origin) {\n parent.postMessage({\n source: messageSource,\n url,\n keepOpen\n }, targetOrigin);\n }\n};\n\n// src/UserManagerSettings.ts\nvar DefaultPopupWindowFeatures = {\n location: false,\n toolbar: false,\n height: 640,\n closePopupWindowAfterInSeconds: -1\n};\nvar DefaultPopupTarget = \"_blank\";\nvar DefaultAccessTokenExpiringNotificationTimeInSeconds = 60;\nvar DefaultCheckSessionIntervalInSeconds = 2;\nvar DefaultSilentRequestTimeoutInSeconds = 10;\nvar UserManagerSettingsStore = class extends OidcClientSettingsStore {\n constructor(args) {\n const {\n popup_redirect_uri = args.redirect_uri,\n popup_post_logout_redirect_uri = args.post_logout_redirect_uri,\n popupWindowFeatures = DefaultPopupWindowFeatures,\n popupWindowTarget = DefaultPopupTarget,\n redirectMethod = \"assign\",\n redirectTarget = \"self\",\n iframeNotifyParentOrigin = args.iframeNotifyParentOrigin,\n iframeScriptOrigin = args.iframeScriptOrigin,\n silent_redirect_uri = args.redirect_uri,\n silentRequestTimeoutInSeconds = DefaultSilentRequestTimeoutInSeconds,\n automaticSilentRenew = true,\n validateSubOnSilentRenew = true,\n includeIdTokenInSilentRenew = false,\n monitorSession = false,\n monitorAnonymousSession = false,\n checkSessionIntervalInSeconds = DefaultCheckSessionIntervalInSeconds,\n query_status_response_type = \"code\",\n stopCheckSessionOnError = true,\n revokeTokenTypes = [\"access_token\", \"refresh_token\"],\n revokeTokensOnSignout = false,\n includeIdTokenInSilentSignout = false,\n accessTokenExpiringNotificationTimeInSeconds = DefaultAccessTokenExpiringNotificationTimeInSeconds,\n userStore\n } = args;\n super(args);\n this.popup_redirect_uri = popup_redirect_uri;\n this.popup_post_logout_redirect_uri = popup_post_logout_redirect_uri;\n this.popupWindowFeatures = popupWindowFeatures;\n this.popupWindowTarget = popupWindowTarget;\n this.redirectMethod = redirectMethod;\n this.redirectTarget = redirectTarget;\n this.iframeNotifyParentOrigin = iframeNotifyParentOrigin;\n this.iframeScriptOrigin = iframeScriptOrigin;\n this.silent_redirect_uri = silent_redirect_uri;\n this.silentRequestTimeoutInSeconds = silentRequestTimeoutInSeconds;\n this.automaticSilentRenew = automaticSilentRenew;\n this.validateSubOnSilentRenew = validateSubOnSilentRenew;\n this.includeIdTokenInSilentRenew = includeIdTokenInSilentRenew;\n this.monitorSession = monitorSession;\n this.monitorAnonymousSession = monitorAnonymousSession;\n this.checkSessionIntervalInSeconds = checkSessionIntervalInSeconds;\n this.stopCheckSessionOnError = stopCheckSessionOnError;\n this.query_status_response_type = query_status_response_type;\n this.revokeTokenTypes = revokeTokenTypes;\n this.revokeTokensOnSignout = revokeTokensOnSignout;\n this.includeIdTokenInSilentSignout = includeIdTokenInSilentSignout;\n this.accessTokenExpiringNotificationTimeInSeconds = accessTokenExpiringNotificationTimeInSeconds;\n if (userStore) {\n this.userStore = userStore;\n } else {\n const store = typeof window !== \"undefined\" ? window.sessionStorage : new InMemoryWebStorage();\n this.userStore = new WebStorageStateStore({ store });\n }\n }\n};\n\n// src/navigators/IFrameWindow.ts\nvar IFrameWindow = class _IFrameWindow extends AbstractChildWindow {\n constructor({\n silentRequestTimeoutInSeconds = DefaultSilentRequestTimeoutInSeconds\n }) {\n super();\n this._logger = new Logger(\"IFrameWindow\");\n this._timeoutInSeconds = silentRequestTimeoutInSeconds;\n this._frame = _IFrameWindow.createHiddenIframe();\n this._window = this._frame.contentWindow;\n }\n static createHiddenIframe() {\n const iframe = window.document.createElement(\"iframe\");\n iframe.style.visibility = \"hidden\";\n iframe.style.position = \"fixed\";\n iframe.style.left = \"-1000px\";\n iframe.style.top = \"0\";\n iframe.width = \"0\";\n iframe.height = \"0\";\n window.document.body.appendChild(iframe);\n return iframe;\n }\n async navigate(params) {\n this._logger.debug(\"navigate: Using timeout of:\", this._timeoutInSeconds);\n const timer = setTimeout(() => void this._abort.raise(new ErrorTimeout(\"IFrame timed out without a response\")), this._timeoutInSeconds * 1e3);\n this._disposeHandlers.add(() => clearTimeout(timer));\n return await super.navigate(params);\n }\n close() {\n var _a;\n if (this._frame) {\n if (this._frame.parentNode) {\n this._frame.addEventListener(\"load\", (ev) => {\n var _a2;\n const frame = ev.target;\n (_a2 = frame.parentNode) == null ? void 0 : _a2.removeChild(frame);\n void this._abort.raise(new Error(\"IFrame removed from DOM\"));\n }, true);\n (_a = this._frame.contentWindow) == null ? void 0 : _a.location.replace(\"about:blank\");\n }\n this._frame = null;\n }\n this._window = null;\n }\n static notifyParent(url, targetOrigin) {\n return super._notifyParent(window.parent, url, false, targetOrigin);\n }\n};\n\n// src/navigators/IFrameNavigator.ts\nvar IFrameNavigator = class {\n constructor(_settings) {\n this._settings = _settings;\n this._logger = new Logger(\"IFrameNavigator\");\n }\n async prepare({\n silentRequestTimeoutInSeconds = this._settings.silentRequestTimeoutInSeconds\n }) {\n return new IFrameWindow({ silentRequestTimeoutInSeconds });\n }\n async callback(url) {\n this._logger.create(\"callback\");\n IFrameWindow.notifyParent(url, this._settings.iframeNotifyParentOrigin);\n }\n};\n\n// src/navigators/PopupWindow.ts\nvar checkForPopupClosedInterval = 500;\nvar second = 1e3;\nvar PopupWindow = class extends AbstractChildWindow {\n constructor({\n popupWindowTarget = DefaultPopupTarget,\n popupWindowFeatures = {}\n }) {\n super();\n this._logger = new Logger(\"PopupWindow\");\n const centeredPopup = PopupUtils.center({ ...DefaultPopupWindowFeatures, ...popupWindowFeatures });\n this._window = window.open(void 0, popupWindowTarget, PopupUtils.serialize(centeredPopup));\n if (popupWindowFeatures.closePopupWindowAfterInSeconds && popupWindowFeatures.closePopupWindowAfterInSeconds > 0) {\n setTimeout(() => {\n if (!this._window || typeof this._window.closed !== \"boolean\" || this._window.closed) {\n void this._abort.raise(new Error(\"Popup blocked by user\"));\n return;\n }\n this.close();\n }, popupWindowFeatures.closePopupWindowAfterInSeconds * second);\n }\n }\n async navigate(params) {\n var _a;\n (_a = this._window) == null ? void 0 : _a.focus();\n const popupClosedInterval = setInterval(() => {\n if (!this._window || this._window.closed) {\n void this._abort.raise(new Error(\"Popup closed by user\"));\n }\n }, checkForPopupClosedInterval);\n this._disposeHandlers.add(() => clearInterval(popupClosedInterval));\n return await super.navigate(params);\n }\n close() {\n if (this._window) {\n if (!this._window.closed) {\n this._window.close();\n void this._abort.raise(new Error(\"Popup closed\"));\n }\n }\n this._window = null;\n }\n static notifyOpener(url, keepOpen) {\n if (!window.opener) {\n throw new Error(\"No window.opener. Can't complete notification.\");\n }\n return super._notifyParent(window.opener, url, keepOpen);\n }\n};\n\n// src/navigators/PopupNavigator.ts\nvar PopupNavigator = class {\n constructor(_settings) {\n this._settings = _settings;\n this._logger = new Logger(\"PopupNavigator\");\n }\n async prepare({\n popupWindowFeatures = this._settings.popupWindowFeatures,\n popupWindowTarget = this._settings.popupWindowTarget\n }) {\n return new PopupWindow({ popupWindowFeatures, popupWindowTarget });\n }\n async callback(url, { keepOpen = false }) {\n this._logger.create(\"callback\");\n PopupWindow.notifyOpener(url, keepOpen);\n }\n};\n\n// src/navigators/RedirectNavigator.ts\nvar RedirectNavigator = class {\n constructor(_settings) {\n this._settings = _settings;\n this._logger = new Logger(\"RedirectNavigator\");\n }\n async prepare({\n redirectMethod = this._settings.redirectMethod,\n redirectTarget = this._settings.redirectTarget\n }) {\n var _a;\n this._logger.create(\"prepare\");\n let targetWindow = window.self;\n if (redirectTarget === \"top\") {\n targetWindow = (_a = window.top) != null ? _a : window.self;\n }\n const redirect = targetWindow.location[redirectMethod].bind(targetWindow.location);\n let abort;\n return {\n navigate: async (params) => {\n this._logger.create(\"navigate\");\n const promise = new Promise((resolve, reject) => {\n abort = reject;\n });\n redirect(params.url);\n return await promise;\n },\n close: () => {\n this._logger.create(\"close\");\n abort == null ? void 0 : abort(new Error(\"Redirect aborted\"));\n targetWindow.stop();\n }\n };\n }\n async callback() {\n return;\n }\n};\n\n// src/UserManagerEvents.ts\nvar UserManagerEvents = class extends AccessTokenEvents {\n constructor(settings) {\n super({ expiringNotificationTimeInSeconds: settings.accessTokenExpiringNotificationTimeInSeconds });\n this._logger = new Logger(\"UserManagerEvents\");\n this._userLoaded = new Event(\"User loaded\");\n this._userUnloaded = new Event(\"User unloaded\");\n this._silentRenewError = new Event(\"Silent renew error\");\n this._userSignedIn = new Event(\"User signed in\");\n this._userSignedOut = new Event(\"User signed out\");\n this._userSessionChanged = new Event(\"User session changed\");\n }\n async load(user, raiseEvent = true) {\n super.load(user);\n if (raiseEvent) {\n await this._userLoaded.raise(user);\n }\n }\n async unload() {\n super.unload();\n await this._userUnloaded.raise();\n }\n /**\n * Add callback: Raised when a user session has been established (or re-established).\n */\n addUserLoaded(cb) {\n return this._userLoaded.addHandler(cb);\n }\n /**\n * Remove callback: Raised when a user session has been established (or re-established).\n */\n removeUserLoaded(cb) {\n return this._userLoaded.removeHandler(cb);\n }\n /**\n * Add callback: Raised when a user session has been terminated.\n */\n addUserUnloaded(cb) {\n return this._userUnloaded.addHandler(cb);\n }\n /**\n * Remove callback: Raised when a user session has been terminated.\n */\n removeUserUnloaded(cb) {\n return this._userUnloaded.removeHandler(cb);\n }\n /**\n * Add callback: Raised when the automatic silent renew has failed.\n */\n addSilentRenewError(cb) {\n return this._silentRenewError.addHandler(cb);\n }\n /**\n * Remove callback: Raised when the automatic silent renew has failed.\n */\n removeSilentRenewError(cb) {\n return this._silentRenewError.removeHandler(cb);\n }\n /**\n * @internal\n */\n async _raiseSilentRenewError(e) {\n await this._silentRenewError.raise(e);\n }\n /**\n * Add callback: Raised when the user is signed in (when `monitorSession` is set).\n * @see {@link UserManagerSettings.monitorSession}\n */\n addUserSignedIn(cb) {\n return this._userSignedIn.addHandler(cb);\n }\n /**\n * Remove callback: Raised when the user is signed in (when `monitorSession` is set).\n */\n removeUserSignedIn(cb) {\n this._userSignedIn.removeHandler(cb);\n }\n /**\n * @internal\n */\n async _raiseUserSignedIn() {\n await this._userSignedIn.raise();\n }\n /**\n * Add callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).\n * @see {@link UserManagerSettings.monitorSession}\n */\n addUserSignedOut(cb) {\n return this._userSignedOut.addHandler(cb);\n }\n /**\n * Remove callback: Raised when the user's sign-in status at the OP has changed (when `monitorSession` is set).\n */\n removeUserSignedOut(cb) {\n this._userSignedOut.removeHandler(cb);\n }\n /**\n * @internal\n */\n async _raiseUserSignedOut() {\n await this._userSignedOut.raise();\n }\n /**\n * Add callback: Raised when the user session changed (when `monitorSession` is set).\n * @see {@link UserManagerSettings.monitorSession}\n */\n addUserSessionChanged(cb) {\n return this._userSessionChanged.addHandler(cb);\n }\n /**\n * Remove callback: Raised when the user session changed (when `monitorSession` is set).\n */\n removeUserSessionChanged(cb) {\n this._userSessionChanged.removeHandler(cb);\n }\n /**\n * @internal\n */\n async _raiseUserSessionChanged() {\n await this._userSessionChanged.raise();\n }\n};\n\n// src/SilentRenewService.ts\nvar SilentRenewService = class {\n constructor(_userManager) {\n this._userManager = _userManager;\n this._logger = new Logger(\"SilentRenewService\");\n this._isStarted = false;\n this._retryTimer = new Timer(\"Retry Silent Renew\");\n this._tokenExpiring = async () => {\n const logger2 = this._logger.create(\"_tokenExpiring\");\n try {\n await this._userManager.signinSilent();\n logger2.debug(\"silent token renewal successful\");\n } catch (err) {\n if (err instanceof ErrorTimeout) {\n logger2.warn(\"ErrorTimeout from signinSilent:\", err, \"retry in 5s\");\n this._retryTimer.init(5);\n return;\n }\n logger2.error(\"Error from signinSilent:\", err);\n await this._userManager.events._raiseSilentRenewError(err);\n }\n };\n }\n async start() {\n const logger2 = this._logger.create(\"start\");\n if (!this._isStarted) {\n this._isStarted = true;\n this._userManager.events.addAccessTokenExpiring(this._tokenExpiring);\n this._retryTimer.addHandler(this._tokenExpiring);\n try {\n await this._userManager.getUser();\n } catch (err) {\n logger2.error(\"getUser error\", err);\n }\n }\n }\n stop() {\n if (this._isStarted) {\n this._retryTimer.cancel();\n this._retryTimer.removeHandler(this._tokenExpiring);\n this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring);\n this._isStarted = false;\n }\n }\n};\n\n// src/RefreshState.ts\nvar RefreshState = class {\n constructor(args) {\n this.refresh_token = args.refresh_token;\n this.id_token = args.id_token;\n this.session_state = args.session_state;\n this.scope = args.scope;\n this.profile = args.profile;\n this.data = args.state;\n }\n};\n\n// src/UserManager.ts\nvar UserManager = class {\n constructor(settings, redirectNavigator, popupNavigator, iframeNavigator) {\n this._logger = new Logger(\"UserManager\");\n this.settings = new UserManagerSettingsStore(settings);\n this._client = new OidcClient(settings);\n this._redirectNavigator = redirectNavigator != null ? redirectNavigator : new RedirectNavigator(this.settings);\n this._popupNavigator = popupNavigator != null ? popupNavigator : new PopupNavigator(this.settings);\n this._iframeNavigator = iframeNavigator != null ? iframeNavigator : new IFrameNavigator(this.settings);\n this._events = new UserManagerEvents(this.settings);\n this._silentRenewService = new SilentRenewService(this);\n if (this.settings.automaticSilentRenew) {\n this.startSilentRenew();\n }\n this._sessionMonitor = null;\n if (this.settings.monitorSession) {\n this._sessionMonitor = new SessionMonitor(this);\n }\n }\n /**\n * Get object used to register for events raised by the `UserManager`.\n */\n get events() {\n return this._events;\n }\n /**\n * Get object used to access the metadata configuration of the identity provider.\n */\n get metadataService() {\n return this._client.metadataService;\n }\n /**\n * Load the `User` object for the currently authenticated user.\n *\n * @returns A promise\n */\n async getUser() {\n const logger2 = this._logger.create(\"getUser\");\n const user = await this._loadUser();\n if (user) {\n logger2.info(\"user loaded\");\n await this._events.load(user, false);\n return user;\n }\n logger2.info(\"user not found in storage\");\n return null;\n }\n /**\n * Remove from any storage the currently authenticated user.\n *\n * @returns A promise\n */\n async removeUser() {\n const logger2 = this._logger.create(\"removeUser\");\n await this.storeUser(null);\n logger2.info(\"user removed from storage\");\n await this._events.unload();\n }\n /**\n * Trigger a redirect of the current window to the authorization endpoint.\n *\n * @returns A promise\n *\n * @throws `Error` In cases of wrong authentication.\n */\n async signinRedirect(args = {}) {\n this._logger.create(\"signinRedirect\");\n const {\n redirectMethod,\n ...requestArgs\n } = args;\n const handle = await this._redirectNavigator.prepare({ redirectMethod });\n await this._signinStart({\n request_type: \"si:r\",\n ...requestArgs\n }, handle);\n }\n /**\n * Process the response (callback) from the authorization endpoint.\n * It is recommend to use {@link UserManager.signinCallback} instead.\n *\n * @returns A promise containing the authenticated `User`.\n *\n * @see {@link UserManager.signinCallback}\n */\n async signinRedirectCallback(url = window.location.href) {\n const logger2 = this._logger.create(\"signinRedirectCallback\");\n const user = await this._signinEnd(url);\n if (user.profile && user.profile.sub) {\n logger2.info(\"success, signed in subject\", user.profile.sub);\n } else {\n logger2.info(\"no subject\");\n }\n return user;\n }\n /**\n * Trigger the signin with user/password.\n *\n * @returns A promise containing the authenticated `User`.\n * @throws {@link ErrorResponse} In cases of wrong authentication.\n */\n async signinResourceOwnerCredentials({\n username,\n password,\n skipUserInfo = false\n }) {\n const logger2 = this._logger.create(\"signinResourceOwnerCredential\");\n const signinResponse = await this._client.processResourceOwnerPasswordCredentials({ username, password, skipUserInfo, extraTokenParams: this.settings.extraTokenParams });\n logger2.debug(\"got signin response\");\n const user = await this._buildUser(signinResponse);\n if (user.profile && user.profile.sub) {\n logger2.info(\"success, signed in subject\", user.profile.sub);\n } else {\n logger2.info(\"no subject\");\n }\n return user;\n }\n /**\n * Trigger a request (via a popup window) to the authorization endpoint.\n *\n * @returns A promise containing the authenticated `User`.\n * @throws `Error` In cases of wrong authentication.\n */\n async signinPopup(args = {}) {\n const logger2 = this._logger.create(\"signinPopup\");\n const {\n popupWindowFeatures,\n popupWindowTarget,\n ...requestArgs\n } = args;\n const url = this.settings.popup_redirect_uri;\n if (!url) {\n logger2.throw(new Error(\"No popup_redirect_uri configured\"));\n }\n const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget });\n const user = await this._signin({\n request_type: \"si:p\",\n redirect_uri: url,\n display: \"popup\",\n ...requestArgs\n }, handle);\n if (user) {\n if (user.profile && user.profile.sub) {\n logger2.info(\"success, signed in subject\", user.profile.sub);\n } else {\n logger2.info(\"no subject\");\n }\n }\n return user;\n }\n /**\n * Notify the opening window of response (callback) from the authorization endpoint.\n * It is recommend to use {@link UserManager.signinCallback} instead.\n *\n * @returns A promise\n *\n * @see {@link UserManager.signinCallback}\n */\n async signinPopupCallback(url = window.location.href, keepOpen = false) {\n const logger2 = this._logger.create(\"signinPopupCallback\");\n await this._popupNavigator.callback(url, { keepOpen });\n logger2.info(\"success\");\n }\n /**\n * Trigger a silent request (via refresh token or an iframe) to the authorization endpoint.\n *\n * @returns A promise that contains the authenticated `User`.\n */\n async signinSilent(args = {}) {\n var _a;\n const logger2 = this._logger.create(\"signinSilent\");\n const {\n silentRequestTimeoutInSeconds,\n ...requestArgs\n } = args;\n let user = await this._loadUser();\n if (user == null ? void 0 : user.refresh_token) {\n logger2.debug(\"using refresh token\");\n const state = new RefreshState(user);\n return await this._useRefreshToken({\n state,\n redirect_uri: requestArgs.redirect_uri,\n resource: requestArgs.resource,\n extraTokenParams: requestArgs.extraTokenParams,\n timeoutInSeconds: silentRequestTimeoutInSeconds\n });\n }\n const url = this.settings.silent_redirect_uri;\n if (!url) {\n logger2.throw(new Error(\"No silent_redirect_uri configured\"));\n }\n let verifySub;\n if (user && this.settings.validateSubOnSilentRenew) {\n logger2.debug(\"subject prior to silent renew:\", user.profile.sub);\n verifySub = user.profile.sub;\n }\n const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n user = await this._signin({\n request_type: \"si:s\",\n redirect_uri: url,\n prompt: \"none\",\n id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0,\n ...requestArgs\n }, handle, verifySub);\n if (user) {\n if ((_a = user.profile) == null ? void 0 : _a.sub) {\n logger2.info(\"success, signed in subject\", user.profile.sub);\n } else {\n logger2.info(\"no subject\");\n }\n }\n return user;\n }\n async _useRefreshToken(args) {\n const response = await this._client.useRefreshToken({\n ...args,\n timeoutInSeconds: this.settings.silentRequestTimeoutInSeconds\n });\n const user = new User({ ...args.state, ...response });\n await this.storeUser(user);\n await this._events.load(user);\n return user;\n }\n /**\n *\n * Notify the parent window of response (callback) from the authorization endpoint.\n * It is recommend to use {@link UserManager.signinCallback} instead.\n *\n * @returns A promise\n *\n * @see {@link UserManager.signinCallback}\n */\n async signinSilentCallback(url = window.location.href) {\n const logger2 = this._logger.create(\"signinSilentCallback\");\n await this._iframeNavigator.callback(url);\n logger2.info(\"success\");\n }\n /**\n * Process any response (callback) from the authorization endpoint, by dispatching the request_type\n * and executing one of the following functions:\n * - {@link UserManager.signinRedirectCallback}\n * - {@link UserManager.signinPopupCallback}\n * - {@link UserManager.signinSilentCallback}\n *\n * @throws `Error` If request_type is unknown or signout can not processed.\n */\n async signinCallback(url = window.location.href) {\n const { state } = await this._client.readSigninResponseState(url);\n switch (state.request_type) {\n case \"si:r\":\n return await this.signinRedirectCallback(url);\n case \"si:p\":\n return await this.signinPopupCallback(url);\n case \"si:s\":\n return await this.signinSilentCallback(url);\n default:\n throw new Error(\"invalid response_type in state\");\n }\n }\n /**\n * Process any response (callback) from the end session endpoint, by dispatching the request_type\n * and executing one of the following functions:\n * - {@link UserManager.signoutRedirectCallback}\n * - {@link UserManager.signoutPopupCallback}\n * - {@link UserManager.signoutSilentCallback}\n *\n * @throws `Error` If request_type is unknown or signout can not processed.\n */\n async signoutCallback(url = window.location.href, keepOpen = false) {\n const { state } = await this._client.readSignoutResponseState(url);\n if (!state) {\n return;\n }\n switch (state.request_type) {\n case \"so:r\":\n await this.signoutRedirectCallback(url);\n break;\n case \"so:p\":\n await this.signoutPopupCallback(url, keepOpen);\n break;\n case \"so:s\":\n await this.signoutSilentCallback(url);\n break;\n default:\n throw new Error(\"invalid response_type in state\");\n }\n }\n /**\n * Query OP for user's current signin status.\n *\n * @returns A promise object with session_state and subject identifier.\n */\n async querySessionStatus(args = {}) {\n const logger2 = this._logger.create(\"querySessionStatus\");\n const {\n silentRequestTimeoutInSeconds,\n ...requestArgs\n } = args;\n const url = this.settings.silent_redirect_uri;\n if (!url) {\n logger2.throw(new Error(\"No silent_redirect_uri configured\"));\n }\n const user = await this._loadUser();\n const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n const navResponse = await this._signinStart({\n request_type: \"si:s\",\n // this acts like a signin silent\n redirect_uri: url,\n prompt: \"none\",\n id_token_hint: this.settings.includeIdTokenInSilentRenew ? user == null ? void 0 : user.id_token : void 0,\n response_type: this.settings.query_status_response_type,\n scope: \"openid\",\n skipUserInfo: true,\n ...requestArgs\n }, handle);\n try {\n const signinResponse = await this._client.processSigninResponse(navResponse.url);\n logger2.debug(\"got signin response\");\n if (signinResponse.session_state && signinResponse.profile.sub) {\n logger2.info(\"success for subject\", signinResponse.profile.sub);\n return {\n session_state: signinResponse.session_state,\n sub: signinResponse.profile.sub\n };\n }\n logger2.info(\"success, user not authenticated\");\n return null;\n } catch (err) {\n if (this.settings.monitorAnonymousSession && err instanceof ErrorResponse) {\n switch (err.error) {\n case \"login_required\":\n case \"consent_required\":\n case \"interaction_required\":\n case \"account_selection_required\":\n logger2.info(\"success for anonymous user\");\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n session_state: err.session_state\n };\n }\n }\n throw err;\n }\n }\n async _signin(args, handle, verifySub) {\n const navResponse = await this._signinStart(args, handle);\n return await this._signinEnd(navResponse.url, verifySub);\n }\n async _signinStart(args, handle) {\n const logger2 = this._logger.create(\"_signinStart\");\n try {\n const signinRequest = await this._client.createSigninRequest(args);\n logger2.debug(\"got signin request\");\n return await handle.navigate({\n url: signinRequest.url,\n state: signinRequest.state.id,\n response_mode: signinRequest.state.response_mode,\n scriptOrigin: this.settings.iframeScriptOrigin\n });\n } catch (err) {\n logger2.debug(\"error after preparing navigator, closing navigator window\");\n handle.close();\n throw err;\n }\n }\n async _signinEnd(url, verifySub) {\n const logger2 = this._logger.create(\"_signinEnd\");\n const signinResponse = await this._client.processSigninResponse(url);\n logger2.debug(\"got signin response\");\n const user = await this._buildUser(signinResponse, verifySub);\n return user;\n }\n async _buildUser(signinResponse, verifySub) {\n const logger2 = this._logger.create(\"_buildUser\");\n const user = new User(signinResponse);\n if (verifySub) {\n if (verifySub !== user.profile.sub) {\n logger2.debug(\"current user does not match user returned from signin. sub from signin:\", user.profile.sub);\n throw new ErrorResponse({ ...signinResponse, error: \"login_required\" });\n }\n logger2.debug(\"current user matches user returned from signin\");\n }\n await this.storeUser(user);\n logger2.debug(\"user stored\");\n await this._events.load(user);\n return user;\n }\n /**\n * Trigger a redirect of the current window to the end session endpoint.\n *\n * @returns A promise\n */\n async signoutRedirect(args = {}) {\n const logger2 = this._logger.create(\"signoutRedirect\");\n const {\n redirectMethod,\n ...requestArgs\n } = args;\n const handle = await this._redirectNavigator.prepare({ redirectMethod });\n await this._signoutStart({\n request_type: \"so:r\",\n post_logout_redirect_uri: this.settings.post_logout_redirect_uri,\n ...requestArgs\n }, handle);\n logger2.info(\"success\");\n }\n /**\n * Process response (callback) from the end session endpoint.\n * It is recommend to use {@link UserManager.signoutCallback} instead.\n *\n * @returns A promise containing signout response\n *\n * @see {@link UserManager.signoutCallback}\n */\n async signoutRedirectCallback(url = window.location.href) {\n const logger2 = this._logger.create(\"signoutRedirectCallback\");\n const response = await this._signoutEnd(url);\n logger2.info(\"success\");\n return response;\n }\n /**\n * Trigger a redirect of a popup window window to the end session endpoint.\n *\n * @returns A promise\n */\n async signoutPopup(args = {}) {\n const logger2 = this._logger.create(\"signoutPopup\");\n const {\n popupWindowFeatures,\n popupWindowTarget,\n ...requestArgs\n } = args;\n const url = this.settings.popup_post_logout_redirect_uri;\n const handle = await this._popupNavigator.prepare({ popupWindowFeatures, popupWindowTarget });\n await this._signout({\n request_type: \"so:p\",\n post_logout_redirect_uri: url,\n // we're putting a dummy entry in here because we\n // need a unique id from the state for notification\n // to the parent window, which is necessary if we\n // plan to return back to the client after signout\n // and so we can close the popup after signout\n state: url == null ? void 0 : {},\n ...requestArgs\n }, handle);\n logger2.info(\"success\");\n }\n /**\n * Process response (callback) from the end session endpoint from a popup window.\n * It is recommend to use {@link UserManager.signoutCallback} instead.\n *\n * @returns A promise\n *\n * @see {@link UserManager.signoutCallback}\n */\n async signoutPopupCallback(url = window.location.href, keepOpen = false) {\n const logger2 = this._logger.create(\"signoutPopupCallback\");\n await this._popupNavigator.callback(url, { keepOpen });\n logger2.info(\"success\");\n }\n async _signout(args, handle) {\n const navResponse = await this._signoutStart(args, handle);\n return await this._signoutEnd(navResponse.url);\n }\n async _signoutStart(args = {}, handle) {\n var _a;\n const logger2 = this._logger.create(\"_signoutStart\");\n try {\n const user = await this._loadUser();\n logger2.debug(\"loaded current user from storage\");\n if (this.settings.revokeTokensOnSignout) {\n await this._revokeInternal(user);\n }\n const id_token = args.id_token_hint || user && user.id_token;\n if (id_token) {\n logger2.debug(\"setting id_token_hint in signout request\");\n args.id_token_hint = id_token;\n }\n await this.removeUser();\n logger2.debug(\"user removed, creating signout request\");\n const signoutRequest = await this._client.createSignoutRequest(args);\n logger2.debug(\"got signout request\");\n return await handle.navigate({\n url: signoutRequest.url,\n state: (_a = signoutRequest.state) == null ? void 0 : _a.id,\n scriptOrigin: this.settings.iframeScriptOrigin\n });\n } catch (err) {\n logger2.debug(\"error after preparing navigator, closing navigator window\");\n handle.close();\n throw err;\n }\n }\n async _signoutEnd(url) {\n const logger2 = this._logger.create(\"_signoutEnd\");\n const signoutResponse = await this._client.processSignoutResponse(url);\n logger2.debug(\"got signout response\");\n return signoutResponse;\n }\n /**\n * Trigger a silent request (via an iframe) to the end session endpoint.\n *\n * @returns A promise\n */\n async signoutSilent(args = {}) {\n var _a;\n const logger2 = this._logger.create(\"signoutSilent\");\n const {\n silentRequestTimeoutInSeconds,\n ...requestArgs\n } = args;\n const id_token_hint = this.settings.includeIdTokenInSilentSignout ? (_a = await this._loadUser()) == null ? void 0 : _a.id_token : void 0;\n const url = this.settings.popup_post_logout_redirect_uri;\n const handle = await this._iframeNavigator.prepare({ silentRequestTimeoutInSeconds });\n await this._signout({\n request_type: \"so:s\",\n post_logout_redirect_uri: url,\n id_token_hint,\n ...requestArgs\n }, handle);\n logger2.info(\"success\");\n }\n /**\n * Notify the parent window of response (callback) from the end session endpoint.\n * It is recommend to use {@link UserManager.signoutCallback} instead.\n *\n * @returns A promise\n *\n * @see {@link UserManager.signoutCallback}\n */\n async signoutSilentCallback(url = window.location.href) {\n const logger2 = this._logger.create(\"signoutSilentCallback\");\n await this._iframeNavigator.callback(url);\n logger2.info(\"success\");\n }\n async revokeTokens(types) {\n const user = await this._loadUser();\n await this._revokeInternal(user, types);\n }\n async _revokeInternal(user, types = this.settings.revokeTokenTypes) {\n const logger2 = this._logger.create(\"_revokeInternal\");\n if (!user)\n return;\n const typesPresent = types.filter((type) => typeof user[type] === \"string\");\n if (!typesPresent.length) {\n logger2.debug(\"no need to revoke due to no token(s)\");\n return;\n }\n for (const type of typesPresent) {\n await this._client.revokeToken(\n user[type],\n // eslint-disable-line @typescript-eslint/no-non-null-assertion\n type\n );\n logger2.info(`${type} revoked successfully`);\n if (type !== \"access_token\") {\n user[type] = null;\n }\n }\n await this.storeUser(user);\n logger2.debug(\"user stored\");\n await this._events.load(user);\n }\n /**\n * Enables silent renew for the `UserManager`.\n */\n startSilentRenew() {\n this._logger.create(\"startSilentRenew\");\n void this._silentRenewService.start();\n }\n /**\n * Disables silent renew for the `UserManager`.\n */\n stopSilentRenew() {\n this._silentRenewService.stop();\n }\n get _userStoreKey() {\n return `user:${this.settings.authority}:${this.settings.client_id}`;\n }\n async _loadUser() {\n const logger2 = this._logger.create(\"_loadUser\");\n const storageString = await this.settings.userStore.get(this._userStoreKey);\n if (storageString) {\n logger2.debug(\"user storageString loaded\");\n return User.fromStorageString(storageString);\n }\n logger2.debug(\"no user storageString\");\n return null;\n }\n async storeUser(user) {\n const logger2 = this._logger.create(\"storeUser\");\n if (user) {\n logger2.debug(\"storing user\");\n const storageString = user.toStorageString();\n await this.settings.userStore.set(this._userStoreKey, storageString);\n } else {\n this._logger.debug(\"removing user\");\n await this.settings.userStore.remove(this._userStoreKey);\n }\n }\n /**\n * Removes stale state entries in storage for incomplete authorize requests.\n */\n async clearStaleState() {\n await this._client.clearStaleState();\n }\n};\n\n// package.json\nvar version = \"3.0.1\";\n\n// src/Version.ts\nvar Version = version;\nexport {\n AccessTokenEvents,\n CheckSessionIFrame,\n ErrorResponse,\n ErrorTimeout,\n InMemoryWebStorage,\n Log,\n Logger,\n MetadataService,\n OidcClient,\n OidcClientSettingsStore,\n SessionMonitor,\n SigninResponse,\n SigninState,\n SignoutResponse,\n State,\n User,\n UserManager,\n UserManagerSettingsStore,\n Version,\n WebStorageStateStore\n};\n//# sourceMappingURL=oidc-client-ts.js.map\n"],"names":["InvalidTokenError","Error","prototype","name","level","logger","Log2","nopLogger","debug","info","warn","error","Log","reset","setLevel","value","setLogger","Logger","_Logger","constructor","_name","this","args","_format","_method","err","create","method","methodLogger","Object","createStatic","staticMethod","staticLogger","prefix","toBase64","val","btoa","Uint8Array","map","chr","String","fromCharCode","join","CryptoUtils","_CryptoUtils","_randomWord","arr","Uint32Array","crypto","getRandomValues","generateUUIDv4","replace","c","toString","generateCodeVerifier","generateCodeChallenge","code_verifier","subtle","data","TextEncoder","encode","hashed","digest","generateBasicAuth","client_id","client_secret","Event","_logger","_callbacks","addHandler","cb","push","removeHandler","idx","lastIndexOf","splice","raise","ev","Timer","_Timer","super","arguments","_timerHandle","_expiration","_callback","diff","getEpochTime","cancel","Math","floor","Date","now","init","durationInSeconds","logger2","max","expiration","timerDurationInSeconds","min","setInterval","clearInterval","State","_State","id","created","request_type","url_state","toStorageString","JSON","stringify","fromStorageString","storageString","Promise","resolve","parse","clearStaleState","storage","age","cutoff","keys","getAllKeys","i","length","key","item","get","remove","state","SigninState","_SigninState","code_challenge","authority","redirect_uri","scope","extraTokenParams","response_mode","skipUserInfo","_SigninRequest","url","response_type","state_data","nonce","resource","extraQueryParams","disablePKCE","optionalParams","parsedUrl","URL","searchParams","append","stateParam","Array","isArray","forEach","r","entries","href"],"sourceRoot":""}