@schibsted/account-sdk-browser 6.0.0-alpha.2 → 6.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -39
- package/dist/account-sdk.d.ts +4 -0
- package/dist/account.d.ts +29 -0
- package/dist/get-account-sdk.d.ts +3 -0
- package/dist/global-registry.d.ts +1 -1
- package/dist/globals.d.ts +2 -0
- package/dist/has-access-response.d.ts +2 -0
- package/dist/identity.d.ts +37 -237
- package/dist/index.d.ts +8 -3
- package/dist/index.js +859 -4
- package/dist/index.js.map +1 -0
- package/dist/monetization.d.ts +7 -43
- package/dist/resolve-browser-window.d.ts +1 -0
- package/dist/{RESTClient.d.ts → rest-client.d.ts} +22 -11
- package/dist/rest-clients.d.ts +10 -0
- package/dist/session-response.d.ts +30 -0
- package/dist/types/account.d.ts +13 -0
- package/dist/types/common.d.ts +22 -0
- package/dist/types/identity.d.ts +41 -0
- package/dist/types/login.d.ts +120 -0
- package/dist/types/monetization-guards.d.ts +2 -0
- package/dist/types/monetization.d.ts +21 -0
- package/dist/types/session-guards.d.ts +36 -0
- package/dist/types/session.d.ts +124 -0
- package/dist/version.d.ts +1 -1
- package/package.json +1 -9
- package/src/account-sdk.ts +74 -0
- package/src/account.ts +149 -0
- package/src/cache.ts +1 -1
- package/src/get-account-sdk.ts +94 -0
- package/src/global-registry.ts +1 -1
- package/src/globals.ts +2 -0
- package/src/has-access-response.ts +35 -0
- package/src/identity.ts +269 -423
- package/src/index.ts +28 -3
- package/src/monetization.ts +31 -68
- package/src/object.ts +1 -1
- package/src/resolve-browser-window.ts +11 -0
- package/src/{RESTClient.ts → rest-client.ts} +55 -28
- package/src/rest-clients.ts +30 -0
- package/src/session-response.ts +85 -0
- package/src/types/account.ts +27 -0
- package/src/types/common.ts +26 -0
- package/src/types/identity.ts +55 -0
- package/src/types/login.ts +145 -0
- package/src/types/monetization-guards.ts +35 -0
- package/src/types/monetization.ts +24 -0
- package/src/types/session-guards.ts +89 -0
- package/src/types/session.ts +147 -0
- package/src/validate.ts +1 -1
- package/src/version.ts +1 -1
- package/dist/identity-s4nofYmB.js +0 -370
- package/dist/identity-s4nofYmB.js.map +0 -1
- package/dist/identity.js +0 -2
- package/dist/monetization.js +0 -72
- package/dist/monetization.js.map +0 -1
- package/dist/version-spE-k97g.js +0 -289
- package/dist/version-spE-k97g.js.map +0 -1
- /package/dist/{SDKError.d.ts → sdk-error.d.ts} +0 -0
- /package/dist/{spidTalk.d.ts → spid-talk.d.ts} +0 -0
- /package/src/{SDKError.ts → sdk-error.ts} +0 -0
- /package/src/{spidTalk.ts → spid-talk.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["#identity","#monetization"],"sources":["../src/global-registry.ts","../node_modules/tiny-emitter/index.js","../src/sdk-error.ts","../src/cache.ts","../src/config.ts","../src/validate.ts","../src/object.ts","../src/popup.ts","../src/url.ts","../src/rest-client.ts","../src/rest-clients.ts","../src/session-response.ts","../src/spid-talk.ts","../src/types/login.ts","../src/version.ts","../src/identity.ts","../src/has-access-response.ts","../src/monetization.ts","../src/resolve-browser-window.ts","../src/account.ts","../src/account-sdk.ts"],"sourcesContent":["import './globals.js';\n\n/**\n * Names of the SDK instance properties that can be registered on the global {@link Window} object.\n */\ntype Property = 'schAccount' | 'schIdentity' | 'schMonetization';\n\n/**\n * Registers an SDK instance on the global {@link Window} object's given property and dispatches a ready event.\n *\n * The dispatched event is a {@link CustomEvent} fired on `global` (i.e. `window`) with:\n * - name: `${property}:ready` (e.g. `\"schIdentity:ready\"` or `\"schMonetization:ready\"`)\n * - `detail.instance`: the registered SDK instance\n *\n * @typeParam T - Constrained to {@link Property}; inferred from the `property` argument.\n * @param global - The `Window` object to register on.\n * @param property - The window property name to assign the instance to, 'schIdentity' or 'schMonetization'.\n * @param instance - The SDK instance to register. Must be non-nullable.\n *\n * @example\n * registerAndDispatchInGlobal(window, 'schIdentity', identityInstance);\n * / window.schIdentity === identityInstance\n * / CustomEvent 'schIdentity:ready' has been dispatched on window\n */\n\nexport const registerAndDispatchInGlobal = <T extends Property>(\n global: Window,\n property: T,\n instance: NonNullable<Window[T]>,\n): void => {\n if (!global[property]) {\n global[property] = instance;\n }\n\n global.dispatchEvent(\n //TODO -> https://schibsted.ghe.com/connect/team/issues/645\n new CustomEvent(`${property}:ready`, { detail: { instance: global[property] } }),\n );\n};\n","function E () {\n // Keep this empty so it's easier to inherit from\n // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)\n}\n\nE.prototype = {\n on: function (name, callback, ctx) {\n var e = this.e || (this.e = {});\n\n (e[name] || (e[name] = [])).push({\n fn: callback,\n ctx: ctx\n });\n\n return this;\n },\n\n once: function (name, callback, ctx) {\n var self = this;\n function listener () {\n self.off(name, listener);\n callback.apply(ctx, arguments);\n };\n\n listener._ = callback\n return this.on(name, listener, ctx);\n },\n\n emit: function (name) {\n var data = [].slice.call(arguments, 1);\n var evtArr = ((this.e || (this.e = {}))[name] || []).slice();\n var i = 0;\n var len = evtArr.length;\n\n for (i; i < len; i++) {\n evtArr[i].fn.apply(evtArr[i].ctx, data);\n }\n\n return this;\n },\n\n off: function (name, callback) {\n var e = this.e || (this.e = {});\n var evts = e[name];\n var liveEvents = [];\n\n if (evts && callback) {\n for (var i = 0, len = evts.length; i < len; i++) {\n if (evts[i].fn !== callback && evts[i].fn._ !== callback)\n liveEvents.push(evts[i]);\n }\n }\n\n // Remove event from queue to prevent memory leak\n // Suggested by https://github.com/lazd\n // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910\n\n (liveEvents.length)\n ? e[name] = liveEvents\n : delete e[name];\n\n return this;\n }\n};\n\nmodule.exports = E;\nmodule.exports.TinyEmitter = E;\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\n/*\n * Note: this module can't have any internal dependencies because it's used in ./validate which\n * in turn is used as a dependency to a lot of other modules. Doing so may create a circular\n * dependency that's hard to debug in Node.\n */\n\nconst STRINGIFY_TYPES = ['boolean', 'number', 'string'];\n\n/**\n * Custom error class thrown by all SDK methods on failure.\n *\n * All rejected promises from API calls reject with an instance of this class.\n */\nexport default class SDKError extends Error {\n /** HTTP status code from the server error payload;\n * declared explicitly to allow numeric comparisons without type-casting.\n */\n code?: number;\n /**\n * Properties copied from the server error object.\n * @internal\n */\n [key: string]: unknown;\n\n /**\n * @param message - Human-readable error message\n * @param errorObject - Optional server error payload. All enumerable properties are\n * shallow-copied onto this instance.\n */\n constructor(message: string, errorObject?: Record<string, unknown>) {\n super(message);\n this.name = 'SDKError';\n\n if (errorObject) {\n try {\n Object.assign(this, errorObject);\n } catch {\n // silent\n }\n }\n }\n\n /**\n * Returns a multi-line string with the error name, message, and any other properties copied\n * from the server error payload.\n */\n toString(): string {\n const ret = `${this.name}: ${this.message}`;\n const additionalInfo = Object.keys(this)\n .filter((key) => key !== 'name' && STRINGIFY_TYPES.includes(typeof this[key]))\n .map((key) => ` ${key}: ${this[key]}`)\n .join('\\n');\n return additionalInfo ? `${ret}\\n${additionalInfo}` : ret;\n }\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport SDKError from './sdk-error.js';\n\n/**\n * Check whether we are able to use web storage\n * @param storeProvider - A function to return a WebStorage instance (either\n * `sessionStorage` or `localStorage` from a `Window` object)\n * @private\n */\nfunction webStorageWorks(storeProvider: (() => Storage) | undefined): boolean {\n if (!storeProvider) {\n return false;\n }\n try {\n const store = storeProvider();\n const randomKey = 'x-x-x-x'.replace(/x/g, () => String(Math.random()));\n const testValue = 'TEST-VALUE';\n store.setItem(randomKey, testValue);\n const val = store.getItem(randomKey);\n store.removeItem(randomKey);\n return val === testValue;\n } catch {\n return false;\n }\n}\n\n/**\n * Cache implementation used when web storage is available. Wraps a `Storage` instance.\n * @private\n */\nclass WebStorageCache {\n store: Storage;\n get: (key: string) => string | null;\n set: (key: string, value: string) => void;\n delete: (key: string) => void;\n\n /**\n * Create web storage cache object\n * @param store - A reference to either `sessionStorage` or `localStorage` from a\n * `Window` object\n */\n constructor(store: Storage) {\n this.store = store;\n this.get = (key) => this.store.getItem(key);\n this.set = (key, value) => this.store.setItem(key, value);\n this.delete = (key) => this.store.removeItem(key);\n }\n}\n\n/**\n * Cache implementation used when web storage is not available. Stores entries in an in-memory object.\n * @private\n */\nclass LiteralCache {\n store: Record<string, string>;\n get: (key: string) => string | undefined;\n set: (key: string, value: string) => void;\n delete: (key: string) => void;\n\n /**\n * Create JS object literal cache object\n */\n constructor() {\n this.store = {};\n this.get = (key) => this.store[key];\n this.set = (key, value) => {\n this.store[key] = value;\n };\n this.delete = (key) => {\n delete this.store[key];\n };\n }\n}\n\ntype CacheEntry = { expiresOn: number; value: unknown };\n\nconst maxExpiresIn = 2 ** 31 - 1;\n\n/**\n * Cache class that attempts WebStorage (session/local storage), and falls back to JS object literal\n * @private\n */\nexport default class Cache {\n cache: WebStorageCache | LiteralCache;\n type: string;\n\n /**\n * @param storeProvider - A function to return a WebStorage instance (either\n * `sessionStorage` or `localStorage` from a `Window` object)\n * @throws {SDKError} - If sessionStorage or localStorage are not accessible\n */\n constructor(storeProvider?: () => Storage) {\n if (storeProvider && webStorageWorks(storeProvider)) {\n this.cache = new WebStorageCache(storeProvider());\n this.type = 'WebStorage';\n } else {\n this.cache = new LiteralCache();\n this.type = 'ObjectLiteralStorage';\n }\n }\n\n /**\n * Get a value from cache (checks that the object has not expired)\n * @param key\n * @private\n */\n get(key: string): unknown {\n /**\n * JSON.parse safe wrapper\n * @param raw\n */\n function getObj(raw: string | null | undefined): CacheEntry | null {\n if (raw == null) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n }\n\n try {\n const raw = this.cache.get(key);\n const obj = getObj(raw);\n if (obj && Number.isInteger(obj.expiresOn) && obj.expiresOn > Date.now()) {\n return obj.value;\n }\n this.delete(key);\n return null;\n } catch (e) {\n throw new SDKError(String(e));\n }\n }\n\n /**\n * Set a cache entry\n * @param key\n * @param value\n * @param expiresIn - Value in milliseconds until the entry expires\n * @private\n */\n set(key: string, value: unknown, expiresIn = 0): void {\n if (expiresIn <= 0) {\n return;\n }\n expiresIn = Math.min(maxExpiresIn, expiresIn);\n\n try {\n const expiresOn = Math.floor(Date.now() + expiresIn);\n this.cache.set(key, JSON.stringify({ expiresOn, value }));\n setTimeout(() => this.delete(key), expiresIn);\n } catch (e) {\n throw new SDKError(String(e));\n }\n }\n\n /**\n * Delete a cache entry\n * @param key\n * @private\n */\n delete(key: string): void {\n try {\n this.cache.delete(key);\n } catch (e) {\n throw new SDKError(String(e));\n }\n }\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\n/*\n * This file declares configs that are essentially part of how the SDK works and interacts with our\n * backend servers.\n *\n * What goes here?\n * - The configurations that are likely to change over time\n * - Constants that are otherwise obscure (for example 7000 for a TIMEOUT)\n *\n * What doesn't go here?\n * - options that the users of the SDK are supposed to set or provide as a parameter to functions\n * and classes.\n */\n\n/**\n * Core configuration used by the SDK.\n * - `ENDPOINTS.SPiD` — SPiD endpoints per environment\n * - `ENDPOINTS.BFF` — Endpoints used with new GDPR-compliant web flows\n * - `ENDPOINTS.SESSION_SERVICE` — Endpoints to check global user session data\n *\n */\nconst config = {\n ENDPOINTS: {\n SPiD: {\n LOCAL: 'http://id.localhost',\n DEV: 'https://identity-dev.schibsted.com',\n PRE: 'https://identity-pre.schibsted.com',\n PRO: 'https://login.schibsted.com',\n PRO_NO: 'https://payment.schibsted.no',\n PRO_FI: 'https://login.schibsted.fi',\n PRO_DK: 'https://login.schibsted.dk',\n },\n BFF: {\n LOCAL: 'http://id.localhost/authn/',\n DEV: 'https://identity-dev.schibsted.com/authn/',\n PRE: 'https://identity-pre.schibsted.com/authn/',\n PRO: 'https://login.schibsted.com/authn/',\n PRO_NO: 'https://payment.schibsted.no/authn/',\n PRO_FI: 'https://login.schibsted.fi/authn/',\n PRO_DK: 'https://login.schibsted.dk/authn/',\n },\n SESSION_SERVICE: {\n LOCAL: 'http://session-service.id.localhost',\n DEV: 'https://session-service.identity-dev.schibsted.com',\n PRE: 'https://session-service.identity-pre.schibsted.com',\n PRO: 'https://session-service.login.schibsted.com',\n PRO_NO: 'https://session-service.payment.schibsted.no',\n PRO_FI: 'https://session-service.login.schibsted.fi',\n PRO_DK: 'https://session-service.login.schibsted.dk',\n },\n },\n NAMESPACE: {\n LOCAL: 'id.localhost',\n DEV: 'schibsted.com',\n PRE: 'schibsted.com',\n PRO: 'schibsted.com',\n PRO_NO: 'spid.no',\n PRO_FI: 'schibsted.fi',\n PRO_DK: 'schibsted.dk',\n },\n} as const;\n\nexport default config;\nexport const ENDPOINTS = config.ENDPOINTS;\nexport const NAMESPACE = config.NAMESPACE;\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport SDKError from './sdk-error.js';\n\n/*\n * This module defines a set of validation functions which are used in the rest of the SDK.\n * Why make our own validation module?\n * 1. To implement the validations that we specifically need for the SDK\n * 2. To have one less dependency\n */\n\n/**\n * A utility function that throws an SDKError if an assertion fails. It's mostly useful for\n * validating function inputs.\n *\n * Narrows `condition` for the rest of the enclosing scope (TypeScript assertion signature).\n * @param condition - The condition that we're asserting\n * @param message - The error message\n * @throws {SDKError} - If the condition is falsy it throws the appropriate error\n */\nexport function assert(condition: boolean, message = 'Assertion failed'): asserts condition {\n if (!condition) {\n throw new SDKError(message);\n }\n}\n\n/**\n * Checks if a value is a string or not\n * @param value - The value to check\n */\nexport function isStr(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n/**\n * Checks if a value is a non-empty string\n * @param value - The value to check\n */\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * checks if a given value is an object (but not null)\n * @param value - The value to check\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Checks if a given value is an object with at least one own key\n * @param value - The value to check\n */\nexport function isNonEmptyObj(value: unknown): value is Record<string, unknown> {\n return isObject(value) && Object.keys(value).length > 0;\n}\n\n/**\n * Checks if a given string is a valid URL\n * @param value - The string to be tested\n * @param mandatoryFields - A list of mandatory fields that should exist in the parsed\n * `URL` object\n */\nexport function isUrl(value: string, ...mandatoryFields: (keyof URL)[]): boolean {\n try {\n const parsedUrl = new URL(value);\n return mandatoryFields.every((f) => parsedUrl[f]);\n } catch {\n return false;\n }\n}\n\n/**\n * Checks if a given value is a function\n * @param value - The value to check\n */\nexport function isFunction(value: unknown): value is (...args: unknown[]) => unknown {\n return typeof value === 'function';\n}\n\n/**\n * Checks if a string matches any of the strings in a set of possibilities\n * @param value\n * @param possibilities - An array of strings that'll be used to check the string\n * inclusion. Note that for performance reasons, we don't validate this parameter.\n * @param caseSensitive - Should the check be case sensitive\n */\nexport function isStrIn(value: string, possibilities: string[], caseSensitive = false): boolean {\n const _isSameStrCaseInsensitive = (str: string) =>\n isStr(str) && value.toUpperCase() === str.toUpperCase();\n if (!(isStr(value) && Array.isArray(possibilities))) {\n return false;\n }\n if (caseSensitive) {\n return possibilities.indexOf(value) !== -1;\n }\n return possibilities.some(_isSameStrCaseInsensitive);\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\n/**\n * @summary Some routines that work on javascript objects\n * @private\n */\n\nimport SDKError from './sdk-error.js';\nimport { assert, isNonEmptyObj, isObject } from './validate.js';\n\n/**\n * Similar to Object.assign({}, src) but only clones the keys of an object that have non-undefined\n * values.\n * Please note that the values in the rightmost parameters can overwrite the values of the earlier\n * parameters so the order of the parameters matters.\n * @example\n * cloneDefined({foo: 1, bar: 2}, {foo: 2}) // returns {foo: 2, bar: 2}\n *\n * @param sources - one or more sources. Their defined properties will override the ones\n * that came before it. For example if `source1.foo = 'bar'` and `source2.foo = 'baz'`, the\n * result will include `{ foo: 'baz' }`\n */\nexport function cloneDefined(...sources: object[]): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n if (!(sources && sources.length)) {\n throw new SDKError('No objects to clone');\n }\n sources.forEach((source) => {\n assert(isObject(source));\n if (isNonEmptyObj(source)) {\n Object.entries(source).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n result[key] = isObject(value) ? cloneDeep(value) : value;\n }\n });\n }\n });\n return result;\n}\n\n/**\n * Deep copies an object. This is handy for immutability.\n * @param obj - An object, array or null.\n * @throws {SDKError} - if the obj is not an accepted type or is not\n * stringifiable by JSON for example if it has loops\n */\nexport function cloneDeep<T extends object | null>(obj: T): T {\n assert(typeof obj === 'object', `obj should be an object (even null) but it is ${obj}`);\n return JSON.parse(JSON.stringify(obj)) || obj;\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { cloneDefined } from './object.js';\nimport { assert, isFunction, isObject, isUrl } from './validate.js';\n\n/**\n * Serializes an object to string.\n * @private\n * @param obj - for example {a: 'b', c: 1}\n */\nfunction serialize(obj: Record<string, unknown>): string {\n assert(isObject(obj), `Object must be an object but it is '${obj}'`);\n return Object.keys(obj)\n .map((key) => `${key}=${obj[key]}`)\n .join(',');\n}\n\nconst defaultWindowFeatures = {\n scrollbars: 'yes',\n location: 'yes',\n status: 'no',\n menubar: 'no',\n toolbar: 'no',\n resizable: 'yes',\n};\n\n/**\n * Opens a popup\n * @param parentWindow - A reference to the window that will open the popup\n * @param url - The URL that the popup will open\n * @param windowName - A name for the window\n * @param windowFeatures - Window features for the popup (default ones are usually ok)\n * @private\n */\nexport function open(\n parentWindow: Window,\n url: string,\n windowName = '',\n windowFeatures: Record<string, string | number> = {},\n): Window | null {\n assert(isObject(parentWindow), `window was supposed to be an object but it is ${parentWindow}`);\n assert(\n isObject(parentWindow.screen),\n `window should be a valid Window object but it lacks a 'screen' property`,\n );\n assert(\n isFunction(parentWindow.open),\n `window should be a valid Window object but it lacks an 'open' function`,\n );\n assert(isUrl(url), 'Invalid URL for popup');\n\n const { height, width } = parentWindow.screen;\n\n const mergedFeatures = cloneDefined(defaultWindowFeatures, windowFeatures);\n const { width: featureWidth, height: featureHeight } = mergedFeatures;\n if (\n typeof featureWidth === 'number' &&\n Number.isFinite(featureWidth) &&\n Number.isFinite(width)\n ) {\n mergedFeatures.left = (width - featureWidth) / 2;\n }\n if (\n typeof featureHeight === 'number' &&\n Number.isFinite(featureHeight) &&\n Number.isFinite(height)\n ) {\n mergedFeatures.top = (height - featureHeight) / 2;\n }\n const features = serialize(mergedFeatures);\n return parentWindow.open(url, windowName, features);\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { assert, isNonEmptyObj, isNonEmptyString, isUrl } from './validate.js';\n\n/**\n * A simple utility function that allows looking up URLs from a dictionary\n * @param url - A url like http://example.com, or a key used for lookup\n * @param urlMap - A map of URLs like `{ DEV: 'http://dev.example.com' }`\n * @returns The resolved URL: the mapped value when `url` is a known key, otherwise `url` itself\n * @throws {SDKError} - If the url is not a string or is an empty string\n */\nexport function urlMapper(url: string, urlMap: Record<string, string>): string {\n assert(isNonEmptyString(url), `\"url\" param must be a non empty string: ${typeof url}`);\n if (isNonEmptyObj(urlMap) && isUrl(urlMap[url])) {\n return urlMap[url];\n }\n assert(isUrl(url, 'hostname'), `Bad URL given: '${url}'`);\n return url;\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { cloneDefined } from './object.js';\nimport SDKError from './sdk-error.js';\nimport type { LogFunction } from './types/common.js';\nimport { urlMapper } from './url.js';\nimport { assert, isFunction, isNonEmptyString, isObject, isStr } from './validate.js';\n\n/**\n * Converts a series of parameters of various types to a string that's suitable for logging.\n * @private\n * @param msg - The values to format; objects are stringified to JSON\n */\nconst logString = (msg: unknown[]): string =>\n msg.map((m) => (isObject(m) ? JSON.stringify(m, null, 2) : m)).join(' ');\n\nconst logFn = (fn: LogFunction | undefined, ...msg: unknown[]): void => {\n if (fn) {\n fn(logString(msg));\n }\n};\n\n/**\n * Encode a string like URLSearchParams would do\n * @private\n * @param str - The input\n */\nfunction encode(str: string): string {\n const replace: Record<string, string> = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00',\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, (match) => replace[match]);\n}\ntype FetchFunction = (input: RequestInfo, init?: RequestInit) => Promise<Response>;\nconst globalFetch = () => window.fetch && window.fetch.bind(window);\nconst noFetch: FetchFunction = () => {\n throw new SDKError('fetch is not available in this environment');\n};\n\n/**\n * The value of a single query parameter; `undefined` entries are skipped.\n */\ntype QueryValue = string | number | boolean | undefined;\n\n/**\n * Query parameters appended to a request URL.\n */\ntype QueryParams = Record<string, QueryValue>;\n\n/**\n * HTTP method used for a request.\n */\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\ntype ResponseParser<T> = (value: JsonValue) => T;\n\ntype RESTRequestOptions<T = JsonValue> = {\n method: HttpMethod;\n pathname: string;\n data?: QueryParams;\n headers?: Record<string, string>;\n useDefaultParams?: boolean;\n fetchOptions?: RequestInit;\n parseResponse?: ResponseParser<T>;\n};\n\n/**\n * This class can be used for creating a wrapper around a server and all its endpoints.\n * Its functionality is extended by {@link JSONPClient}\n * Creates a client to a REST server. While useful stand-alone, it's also used for some other\n * types of client that change some functionalities.\n * @throws {SDKError} - If any of options are invalid\n * @summary The simplest way to communicate to a REST endpoint without any\n * special authentication\n * @private\n */\nexport class RESTClient {\n url: URL;\n defaultParams: QueryParams;\n log?: LogFunction;\n fetch: FetchFunction;\n\n /**\n * @param options\n * @param options.serverUrl - The URL to the server eg.\n * https://login.schibsted.com or a URL key like 'DEV' in combination with {@link envDic}.\n * @param options.envDic - A dictionary that will be used for looking up\n * {@link serverUrl} keys. If serverUrl is always a URL, you don't need this.\n * @param options.fetch - The fetch function to use. It can be native\n * or a polyfill\n * @param options.log - A function that will be called with log messages about\n * request and response\n * @param options.defaultParams - Query parameters added to every request\n */\n constructor({\n serverUrl = 'PRE',\n envDic,\n fetch = globalFetch() ?? noFetch,\n log,\n defaultParams = {},\n }: {\n serverUrl?: string;\n envDic?: Record<string, string>;\n fetch?: FetchFunction;\n log?: LogFunction;\n defaultParams?: QueryParams;\n }) {\n assert(isObject(defaultParams), `defaultParams should be a non-null object`);\n\n const mappedUrl = urlMapper(serverUrl, envDic ?? {});\n const handledServerUrl = mappedUrl.endsWith('/') ? mappedUrl : `${mappedUrl}/`;\n this.url = new URL(handledServerUrl);\n\n this.defaultParams = defaultParams;\n\n if (log) {\n assert(isFunction(log), `log must be a function but it is ${log}`);\n this.log = log;\n }\n\n this.fetch = fetch;\n }\n\n /**\n * Makes the actual call to the server and deals with headers, data objects and the edge cases.\n * Please note that this method expects the response to be in JSON format. However, it'll not\n * parse the response if its code is not in the 200 range.\n * @param options - An obligatory options object\n * @param options.method - The HTTP request method, e.g. 'GET' or 'POST'\n * @param options.pathname - The path to the endpoint like 'api/2/endpoint-name'\n * @param options.data - Query parameters added to the request URL\n * @param options.headers - Request headers as a plain key/value map\n * @param options.useDefaultParams - Should we add the defaultParams to the query?\n * @param options.fetchOptions - Additional fetch options\n * @throws {SDKError} - If the call can't be made for whatever reason.\n */\n // Overloads describe the two supported modes:\n // - without a parser: return the parsed JSON response as-is;\n // - with a parser: return the parser's typed result.\n async go(options: RESTRequestOptions): Promise<JsonValue>;\n async go<T>(options: RESTRequestOptions<T> & { parseResponse: ResponseParser<T> }): Promise<T>;\n\n // TypeScript requires one implementation signature for the overloads above.\n async go<T = JsonValue>(options: RESTRequestOptions<T>): Promise<JsonValue | T> {\n const {\n method,\n headers,\n pathname,\n data = {},\n useDefaultParams = true,\n fetchOptions = { method: options.method, credentials: 'include' },\n parseResponse,\n } = options;\n assert(isNonEmptyString(method), `Method must be a non empty string but it is \"${method}\"`);\n assert(isNonEmptyString(pathname), `Pathname must be string but it is \"${pathname}\"`);\n assert(isObject(data), `data must be a non-null object`);\n\n fetchOptions.headers = isObject(headers) ? headers : {};\n const fullUrl = this.makeUrl(pathname, data, useDefaultParams);\n\n logFn(this.log, 'Request:', method.toUpperCase(), fullUrl);\n logFn(this.log, 'Request Headers:', fetchOptions.headers);\n logFn(this.log, 'Request Body:', fetchOptions.body);\n try {\n const response = await this.fetch(fullUrl, fetchOptions);\n logFn(this.log, 'Response Code:', response.status, response.statusText);\n if (!response.ok) {\n // status code not in range 200-299\n throw new SDKError(response.statusText, { code: response.status });\n }\n const responseObject: JsonValue = await response.json();\n logFn(this.log, 'Response Parsed:', responseObject);\n return parseResponse ? parseResponse(responseObject) : responseObject;\n } catch (err: unknown) {\n let msg = isStr(err) ? err : 'Unknown RESTClient error';\n if (isObject(err) && isStr(err.message)) {\n msg = err.message;\n }\n const errorObject = isObject(err) ? err : undefined;\n throw new SDKError(`Failed to '${method}' '${fullUrl}': '${msg}'`, errorObject);\n }\n }\n\n /**\n * Creates a url that points to an endpoint in the server\n * @param pathname - WHATWG pathname ie. 'api/2/endpoint-name'\n * @param query - Query parameters to serialize into the query string\n * @param useDefaultParams - Should we add the defaultParams to the query?\n */\n makeUrl(pathname = '', query: QueryParams = {}, useDefaultParams = true): string {\n const handledPathname = pathname.startsWith('/') ? pathname.slice(1) : pathname;\n\n const url = new URL(handledPathname, this.url);\n url.search = RESTClient.search(query, useDefaultParams, this.defaultParams);\n return url.href;\n }\n\n /**\n * Make a GET request\n * @param pathname - WHATWG pathname ie. 'api/2/endpoint-name'\n * @param data - Query parameters\n */\n // Mirrors `go()` overloads for the common GET helper.\n get(pathname: string, data?: QueryParams): Promise<JsonValue>;\n get<T>(\n pathname: string,\n data: QueryParams | undefined,\n parseResponse: ResponseParser<T>,\n ): Promise<T>;\n\n // TypeScript requires one implementation signature for the overloads above.\n get<T>(\n pathname: string,\n data?: QueryParams,\n parseResponse?: ResponseParser<T>,\n ): Promise<JsonValue | T> {\n if (parseResponse) {\n return this.go({ method: 'GET', pathname, data, parseResponse });\n }\n return this.go({ method: 'GET', pathname, data });\n }\n\n /**\n * Construct query string for WHATWG urls\n * @private\n * @param query - Query parameters to generate the query string from\n * @param useDefaultParams - Use defaultParams or not\n * @param defaultParams - Default params\n */\n private static search(\n query: QueryParams,\n useDefaultParams: boolean,\n defaultParams: QueryParams,\n ): string {\n const params = useDefaultParams ? cloneDefined(defaultParams, query) : cloneDefined(query);\n return Object.keys(params)\n .filter((p) => params[p] !== '')\n .map((p) => `${encode(p)}=${encode(String(params[p]))}`)\n .join('&');\n }\n}\n\nexport default RESTClient;\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { NAMESPACE } from './config.js';\nimport RESTClient from './rest-client.js';\nimport type { LogFunction } from './types/common.js';\nimport { assert, isNonEmptyString } from './validate.js';\n\ntype AccountRestClientOptions = {\n serverUrl: string;\n log?: LogFunction;\n defaultParams: Record<string, string | number | boolean | undefined>;\n};\n\nconst isKnownNamespace = (env: string): env is keyof typeof NAMESPACE =>\n Object.hasOwn(NAMESPACE, env);\n\nexport const buildClientSdrn = (env: string, clientId: string): string => {\n assert(isNonEmptyString(clientId), 'clientId parameter is required');\n assert(isKnownNamespace(env), `env parameter is invalid: ${env}`);\n\n return `sdrn:${NAMESPACE[env]}:client:${clientId}`;\n};\n\nexport const createAccountRestClient = ({\n serverUrl,\n log,\n defaultParams,\n}: AccountRestClientOptions): RESTClient => new RESTClient({ serverUrl, log, defaultParams });\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport type {\n ConnectedSessionResponse,\n ConnectedSessionWithUserIdResponse,\n NormalizedSessionPayload,\n RedirectSessionPayload,\n SessionFailureResponse,\n SessionResponse,\n SessionSuccessResponse,\n} from './types/session.js';\nimport { isObject, isStr } from './validate.js';\n\nexport function isSessionSuccessResponse(value: unknown): value is SessionSuccessResponse {\n return (\n isObject(value) &&\n typeof value.code === 'number' &&\n isStr(value.type) &&\n isStr(value.description) &&\n typeof value.result === 'boolean'\n );\n}\n\nexport function isConnectedSessionResponse(value: unknown): value is ConnectedSessionResponse {\n return isSessionSuccessResponse(value) && value.result === true;\n}\n\nexport function isSessionFailureResponse(value: unknown): value is SessionFailureResponse {\n return isObject(value) && Boolean(value.error);\n}\n\nexport function isRedirectSessionPayload(value: unknown): value is RedirectSessionPayload {\n return isObject(value) && Object.keys(value).length === 1 && isStr(value.redirectURL);\n}\n\nexport function isConnectedSessionWithUserIdResponse(\n value: SessionResponse,\n): value is ConnectedSessionWithUserIdResponse {\n return (\n isConnectedSessionResponse(value) &&\n (typeof value.userId === 'number' || typeof value.userId === 'string')\n );\n}\n\n/**\n * Converts an unknown Session Service `hasSession` payload into one of the shapes the SDK knows how\n * to handle.\n *\n * This function is intentionally tolerant because `hasSession()` historically resolved unknown\n * object payloads instead of rejecting them. The SDK relies on that behavior for backwards\n * compatibility with clients that check the raw response themselves.\n *\n * The normal cases are:\n * - regular success payloads with a boolean `result`;\n * - failure payloads wrapped as `{ error, response? }`;\n * - Safari/session-refresh redirect payloads shaped as `{ redirectURL }`.\n *\n * Any other object is preserved as an unrecognized response so callers can still receive it.\n * Non-object values are normalized to `{}`, matching the old \"empty response\" fallback used by\n * `hasSession()` and cached-session reads.\n *\n * This is used both for network responses parsed by `RESTClient` and for values restored from the\n * session cache, so the rest of the Identity flow can switch on typed guards instead of repeatedly\n * re-validating unknown data.\n *\n * @internal\n */\nexport function normalizeSessionResponse(value: unknown): NormalizedSessionPayload {\n if (isRedirectSessionPayload(value)) {\n return value;\n }\n if (isSessionFailureResponse(value)) {\n return value;\n }\n if (isSessionSuccessResponse(value)) {\n return value;\n }\n if (isObject(value)) {\n return value;\n }\n\n return {};\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\n/**\n * A workaround for how Schibsted account handles JSONP calls in the browser\n * @private\n */\n\nimport './globals.js';\nimport { isFunction } from './validate.js';\n\n/**\n * This is a workaround for making the old SPiD/hassession on JSONP APIs compatible with more common\n * JSONP convention where the callback function is expected to exist in the global object.\n *\n * How does it work?\n * =================\n * The old SPiD JSONP APIs relied on SPiD.Talk.response(callbackName, data) but fetch-jsonp merely\n * calls window[callbackName](data) which is more common practice. This module simply acts as an\n * adapter to modernize the old mechanism until we support CORS. To see how the SPiD solution works,\n * try to run a simple JSONP request or debug it in the network tab. This module will be removed\n * when CORS is supported.\n * @param global - A reference to the global object, typically the `Window`.\n */\nexport function emulate(global: Window): void {\n if (!global.SPiD || typeof global.SPiD !== 'object') {\n global.SPiD = {};\n }\n if (!global.SPiD.Talk || typeof global.SPiD.Talk !== 'object') {\n global.SPiD.Talk = {};\n }\n if (!isFunction(global.SPiD.Talk.response)) {\n global.SPiD.Talk.response = (callbackName: string, data: unknown) =>\n (global as any)[callbackName](data);\n }\n}\n","/**\n * Options accepted by {@link Identity#login} and related login URL helpers.\n */\nexport type LoginOptions = {\n /**\n * An opaque value used by the client to maintain state between the request and callback.\n * It's also recommended to prevent CSRF {@link https://tools.ietf.org/html/rfc6749#section-10.12}\n */\n state: string;\n /**\n * Authentication Context Class Reference Values. If omitted, the user will be asked to\n * authenticate using username+password. For 2FA (Two-Factor Authentication) possible values\n * are `sms`, `otp` (one time password), `password` (will force password confirmation, even if\n * user is already logged in), `eid`. Those values might be mixed as space-separated string.\n * To make sure that user has authenticated with 2FA you need to verify AMR (Authentication\n * Methods References) claim in ID token. Might also be used to ensure additional acr\n * (sms, otp, eid) for already logged in users. Supported value is also 'otp-email' means one\n * time password using email.\n */\n acrValues?:\n | 'password'\n | 'otp'\n | 'sms'\n | 'eid-dk'\n | 'eid-no'\n | 'eid-se'\n | 'eid-fi'\n | 'eid'\n | 'otp-email'\n | (string & {});\n /**\n * The OAuth scopes for the tokens. This is a list of scopes, separated by space. If the list\n * of scopes contains `openid`, the generated tokens includes the id token which can be useful\n * for getting information about the user. Omitting scope is allowed, while `invalid_scope` is\n * returned when the client asks for a scope you aren't allowed to request.\n * {@link https://tools.ietf.org/html/rfc6749#section-3.3}\n * Defaults to `openid`.\n */\n scope?: 'openid' | (string & {});\n /**\n * Redirect uri that will receive the code. Must exactly match a redirectUri from your client\n * in self-service\n */\n redirectUri?: string;\n /** Should we try to open a popup window? Defaults to `false`. */\n preferPopup?: boolean;\n /** user email or UUID hint */\n loginHint?: string;\n /** Pulse tag */\n tag?: string;\n /** Teaser slug. Teaser with given slug will be displayed in place of default teaser */\n teaser?: string;\n /**\n * Specifies the allowable elapsed time in seconds since the last time the End-User was actively\n * authenticated. If last authentication time is more than maxAge seconds in the past,\n * re-authentication will be required. See the OpenID Connect spec section 3.1.2.1 for more\n * information. Prefer a number of seconds; strings remain accepted for legacy callers.\n */\n maxAge?: number | string;\n /**\n * Optional parameter to overwrite client locale setting.\n * New flows supports nb_NO, fi_FI, sv_SE, en_US\n */\n locale?: 'nb_NO' | 'fi_FI' | 'sv_SE' | 'en_US';\n /** display username and password on one screen. Defaults to `false`. */\n oneStepLogin?: boolean;\n /**\n * String that specifies whether the Authorization Server prompts the End-User for\n * reauthentication or confirm account screen. Supported values: `select_account` or `login`.\n * Defaults to `select_account`.\n */\n prompt?: 'select_account' | 'login';\n /** Identifier for cross-domain tracking in Pulse */\n xDomainId?: string;\n /** Environment for cross-domain tracking in Pulse */\n xEnvironmentId?: string;\n /** Campaign identifier for tracking in Pulse */\n originCampaign?: string;\n};\n\n/**\n * Identical to {@link LoginOptions} except that `state` may also be a (possibly async) function;\n * all other fields reuse the `LoginOptions` documentation.\n */\nexport type SimplifiedLoginWidgetLoginOptions = Omit<LoginOptions, 'state'> & {\n /**\n * An opaque value used by the client to maintain state between the request and callback.\n * It's also recommended to prevent CSRF {@link https://tools.ietf.org/html/rfc6749#section-10.12}\n */\n state: string | (() => string | Promise<string>);\n};\n\n/**\n * Minimal user information used by the simplified login widget flow.\n */\nexport type SimplifiedLoginData = {\n /** Deprecated: User UUID, to be be used as `loginHint` for {@link Identity#login} */\n identifier: string;\n /** Human-readable user identifier */\n display_text: string;\n /** Client name */\n client_name: string;\n /** Provider id used by the simplified login widget when supplied by the backend. */\n provider_id?: string;\n};\n\n/**\n * Configuration options for {@link Identity#showSimplifiedLoginWidget}.\n */\nexport type SimplifiedLoginWidgetOptions = {\n /** expected encoding of simplified login widget. Could be utf-8 (default), iso-8859-1 or iso-8859-15 */\n encoding?: string;\n /**\n * expected locale of simplified login widget. Should be provided in a short format like 'nb',\n * 'sv'. If not set, a value from the env variable is used.\n */\n locale?: 'nb' | 'sv' | 'fi' | 'da' | 'en';\n};\n\nexport type SimplifiedLoginWidgetInitialParams = {\n displayText: string;\n env: string;\n clientName: string;\n clientId: string;\n providerId?: string;\n locale?: SimplifiedLoginWidgetOptions['locale'];\n windowWidth: () => number;\n windowOnResize: (handler: () => void) => void;\n};\n\nexport type SimplifiedLoginWidgetHandler = () => void | Promise<void>;\n\nexport type OpenSimplifiedLoginWidget = (\n initialParams: SimplifiedLoginWidgetInitialParams,\n loginHandler: SimplifiedLoginWidgetHandler,\n loginNotYouHandler: SimplifiedLoginWidgetHandler,\n initHandler: SimplifiedLoginWidgetHandler,\n cancelLoginHandler: SimplifiedLoginWidgetHandler,\n) => unknown;\n\nexport const hasOpenSimplifiedLoginWidget = (\n targetWindow: Window,\n): targetWindow is Window & { openSimplifiedLoginWidget: OpenSimplifiedLoginWidget } => {\n return typeof targetWindow.openSimplifiedLoginWidget === 'function';\n};\n","// Version is bumped automatically by release-please. See release-please-config.json.\n\nconst version = '6.0.0-alpha.3'; // x-release-please-version\nexport default version;\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { TinyEmitter } from 'tiny-emitter';\nimport Cache from './cache.js';\nimport { ENDPOINTS } from './config.js';\nimport { registerAndDispatchInGlobal } from './global-registry.js';\nimport { cloneDeep } from './object.js';\nimport * as popup from './popup.js';\nimport type RESTClient from './rest-client.js';\nimport { buildClientSdrn, createAccountRestClient } from './rest-clients.js';\nimport SDKError from './sdk-error.js';\nimport {\n isConnectedSessionResponse,\n isConnectedSessionWithUserIdResponse,\n isRedirectSessionPayload,\n isSessionFailureResponse,\n isSessionSuccessResponse,\n normalizeSessionResponse,\n} from './session-response.js';\nimport * as spidTalk from './spid-talk.js';\nimport type { LogFunction } from './types/common.js';\nimport type {\n IdentityBeforeRedirectCallback,\n IdentityOptions,\n VarnishCookieOptions,\n} from './types/identity.js';\nimport {\n hasOpenSimplifiedLoginWidget,\n type LoginOptions,\n type OpenSimplifiedLoginWidget,\n type SimplifiedLoginData,\n type SimplifiedLoginWidgetInitialParams,\n type SimplifiedLoginWidgetLoginOptions,\n type SimplifiedLoginWidgetOptions,\n} from './types/login.js';\nimport type {\n ConnectedSessionResponse,\n NormalizedSessionPayload,\n SessionObjectResponse,\n SessionResponse,\n} from './types/session.js';\nimport { urlMapper } from './url.js';\nimport { assert, isNonEmptyString, isObject, isStr, isStrIn, isUrl } from './validate.js';\nimport version from './version.js';\n\nexport { isConnectedSessionResponse, isSessionSuccessResponse } from './session-response.js';\nexport type {\n ConnectedSessionResponse,\n SessionFailureResponse,\n SessionObjectResponse,\n SessionResponse,\n SessionSuccessResponse,\n SessionUserId,\n} from './types/session.js';\n\ndeclare global {\n interface Window {\n openSimplifiedLoginWidget?: OpenSimplifiedLoginWidget;\n }\n}\n\nconst HAS_SESSION_CACHE_KEY = 'hasSession-cache';\nconst SESSION_CALL_BLOCKED_CACHE_KEY = 'sessionCallBlocked-cache';\nconst SESSION_CALL_BLOCKED_TTL = 1000 * 60 * 5;\n\nconst TAB_ID_KEY = 'tab-id-cache';\nconst TAB_ID = Math.floor(Math.random() * 100000);\nconst TAB_ID_TTL = 1000 * 60 * 60 * 24 * 30;\n\nconst globalWindow = () => window;\n\n/**\n * Provides Identity functionalty to a web page\n */\nexport class Identity extends TinyEmitter {\n _sessionInitiatedSent: boolean;\n window: Window;\n clientId: string;\n sessionStorageCache: Cache;\n localStorageCache: Cache;\n redirectUri: string;\n env: string;\n log?: LogFunction;\n callbackBeforeRedirect: IdentityBeforeRedirectCallback;\n _sessionDomain: string;\n _enableSessionCaching: boolean;\n /**\n * @internal Starts as `{}` before the first `hasSession()` call, then stores the latest\n * object response from hasSession().\n */\n _session: SessionObjectResponse;\n _spid: RESTClient;\n _oauthService: RESTClient;\n _bffService: RESTClient;\n _sessionService: RESTClient;\n _globalSessionService: RESTClient;\n _usedSessionServiceGetSessionEndpoint: 'v2/session' | 'session';\n _hasSessionInProgress?: false | Promise<SessionResponse>;\n popup?: Window | null;\n setVarnishCookie?: boolean;\n varnishExpiresIn?: number;\n varnishCookieDomain?: string;\n\n /**\n * @param options\n * @param options.clientId - Example: \"1234567890abcdef12345678\"\n * @param options.sessionDomain - Example: \"https://id.site.com\"\n * @param options.redirectUri - Example: \"https://site.com\"\n * @param options.env - Schibsted account environment: `PRE` (default), `PRO`, `PRO_NO`, `PRO_FI` or `PRO_DK`\n * @param options.log - A function that receives debug log information. If not set,\n * no logging will be done\n * @param options.window - window object\n * @param options.callbackBeforeRedirect - callback triggered before session refresh redirect happen\n * @throws {SDKError} - If any of options are invalid\n */\n constructor({\n clientId,\n redirectUri,\n sessionDomain,\n env = 'PRE',\n log,\n window = globalWindow(),\n callbackBeforeRedirect = () => {},\n }: IdentityOptions) {\n super();\n assert(isNonEmptyString(clientId), 'clientId parameter is required');\n assert(isObject(window), 'The reference to window is missing');\n assert(!redirectUri || isUrl(redirectUri), 'redirectUri parameter is invalid');\n assert(\n isNonEmptyString(sessionDomain) && isUrl(sessionDomain),\n 'sessionDomain parameter is not a valid URL',\n );\n assert(isStr(env), `env parameter is invalid: ${env}`);\n\n spidTalk.emulate(window);\n this._sessionInitiatedSent = false;\n this.window = window;\n this.clientId = clientId;\n this.sessionStorageCache = new Cache(() => this.window && this.window.sessionStorage);\n this.localStorageCache = new Cache(() => this.window && this.window.localStorage);\n this.redirectUri = redirectUri;\n this.env = env;\n this.log = log;\n this.callbackBeforeRedirect = callbackBeforeRedirect;\n this._sessionDomain = sessionDomain;\n\n // Internal hack: set to false to always refresh from hassession\n this._enableSessionCaching = true;\n\n // Old session\n this._session = {};\n\n const accountClientParams = { client_id: this.clientId, redirect_uri: this.redirectUri };\n const clientSdrn = buildClientSdrn(this.env, this.clientId);\n\n this._sessionService = createAccountRestClient({\n serverUrl: sessionDomain,\n log: this.log,\n defaultParams: {\n client_sdrn: clientSdrn,\n redirect_uri: this.redirectUri,\n sdk_version: version,\n },\n });\n this._usedSessionServiceGetSessionEndpoint =\n this._sessionService.url.pathname && this._sessionService.url.pathname.length <= 1\n ? 'v2/session'\n : 'session';\n\n this._spid = createAccountRestClient({\n serverUrl: urlMapper(env, ENDPOINTS.SPiD),\n log: this.log,\n defaultParams: accountClientParams,\n });\n this._bffService = createAccountRestClient({\n serverUrl: urlMapper(env, ENDPOINTS.BFF),\n log: this.log,\n defaultParams: accountClientParams,\n });\n this._oauthService = createAccountRestClient({\n serverUrl: urlMapper(env, ENDPOINTS.SPiD),\n log: this.log,\n defaultParams: accountClientParams,\n });\n this._globalSessionService = createAccountRestClient({\n serverUrl: urlMapper(env, ENDPOINTS.SESSION_SERVICE),\n log: this.log,\n defaultParams: { client_sdrn: clientSdrn, sdk_version: version },\n });\n\n this._unblockSessionCall();\n\n registerAndDispatchInGlobal(window, 'schIdentity', this);\n }\n\n /**\n * Read tabId from session storage\n * @private\n */\n _getTabId(): number | undefined {\n if (this._enableSessionCaching) {\n const tabId = this.sessionStorageCache.get(TAB_ID_KEY);\n if (typeof tabId !== 'number') {\n this.sessionStorageCache.set(TAB_ID_KEY, TAB_ID, TAB_ID_TTL);\n return TAB_ID;\n }\n\n return tabId;\n }\n }\n\n /**\n * Checks if getting session is blocked\n * @private\n *\n */\n _isSessionCallBlocked(): boolean {\n return Boolean(this.localStorageCache.get(SESSION_CALL_BLOCKED_CACHE_KEY));\n }\n\n /**\n * Block calls to get session\n * @private\n *\n */\n _blockSessionCall(): void {\n const SESSION_CALL_BLOCKED = true;\n\n this.localStorageCache.set(\n SESSION_CALL_BLOCKED_CACHE_KEY,\n SESSION_CALL_BLOCKED,\n SESSION_CALL_BLOCKED_TTL,\n );\n }\n\n /**\n * Unblocks calls to get session\n * @private\n *\n */\n _unblockSessionCall(): void {\n this.localStorageCache.delete(SESSION_CALL_BLOCKED_CACHE_KEY);\n }\n\n /**\n * Emits the relevant events based on the previous and new reply from hasSession\n * @private\n * @param previous\n * @param current\n */\n _emitSessionEvent(previous: object, current: object): void {\n const previousUserId = isSessionSuccessResponse(previous) ? previous.userId : undefined;\n const currentUserId = isSessionSuccessResponse(current) ? current.userId : undefined;\n const previousUserStatus = isSessionSuccessResponse(previous)\n ? previous.userStatus\n : undefined;\n const currentUserStatus = isSessionSuccessResponse(current)\n ? current.userStatus\n : undefined;\n\n /**\n * Emitted when the user is logged in (This happens as a result of calling\n * {@link Identity#hasSession}, so it is also emitted if the user was previously logged in)\n * @event Identity#login\n */\n if (currentUserId) {\n this.emit('login', current);\n }\n /**\n * Emitted when the user logged out\n * @event Identity#logout\n */\n if (previousUserId && !currentUserId) {\n this.emit('logout', current);\n }\n /**\n * Emitted when the user is changed. This happens as a result of calling\n * {@link Identity#hasSession}, and is emitted if there was a user both before and after\n * this invocation, and the userId has now changed\n * @event Identity#userChange\n */\n if (previousUserId && currentUserId && previousUserId !== currentUserId) {\n this.emit('userChange', current);\n }\n if (previousUserId || currentUserId) {\n /**\n * Emitted when the session is changed. More accurately, this event is emitted if there\n * was a logged-in user either before or after {@link Identity#hasSession} was called.\n * In practice, this means the event is emitted a lot\n * @event Identity#sessionChange\n */\n this.emit('sessionChange', current);\n } else {\n /**\n * Emitted when there is no logged-in user. More specifically, it means that there was\n * no logged-in user neither before nor after {@link Identity#hasSession} was called\n * @event Identity#notLoggedin\n */\n this.emit('notLoggedin', current);\n }\n /**\n * Emitted when the session is first created\n * @event Identity#sessionInit\n */\n if (currentUserId && !this._sessionInitiatedSent) {\n this._sessionInitiatedSent = true;\n this.emit('sessionInit', current);\n }\n /**\n * Emitted when the user status changes. This happens as a result of calling\n * {@link Identity#hasSession}\n * @event Identity#statusChange\n */\n if (previousUserStatus !== currentUserStatus) {\n this.emit('statusChange', current);\n }\n }\n\n /**\n * Close this.popup if it exists and is open\n * @private\n */\n _closePopup(): void {\n if (this.popup) {\n if (!this.popup.closed) {\n this.popup.close();\n }\n this.popup = null;\n }\n }\n\n /**\n * Set the Varnish cookie (`SP_ID`) when hasSession() is called. Note that most browsers require\n * that you are on a \"real domain\" for this to work — so, **not** `localhost`\n * @param options\n * @param options.expiresIn Override this to set number of seconds before the varnish\n * cookie expires. The default is to use the same time that hasSession responses are cached for\n * @param options.domain Override cookie domain. E.g. «vg.no» instead of «www.vg.no»\n */\n enableVarnishCookie(options: VarnishCookieOptions): void {\n if (typeof options !== 'object') {\n throw new SDKError('VarnishCookieOptions must be an object');\n }\n\n const { expiresIn = 0, domain } = options;\n\n assert(Number.isInteger(expiresIn), `'expiresIn' must be an integer`);\n assert(expiresIn >= 0, `'expiresIn' cannot be negative`);\n this.setVarnishCookie = true;\n this.varnishExpiresIn = expiresIn;\n this.varnishCookieDomain = domain;\n }\n\n /**\n * Set the Varnish cookie if configured\n * @private\n * @param sessionData\n */\n _maybeSetVarnishCookie(sessionData: object): void {\n if (!this.setVarnishCookie || !isSessionSuccessResponse(sessionData)) {\n return;\n }\n const date = new Date();\n const validExpires =\n this.varnishExpiresIn ||\n (typeof sessionData.expiresIn === 'number' && sessionData.expiresIn > 0);\n if (validExpires) {\n const expires = this.varnishExpiresIn || sessionData.expiresIn || 0;\n date.setTime(date.getTime() + expires * 1000);\n } else {\n date.setTime(0);\n }\n\n // If the domain is missing or of the wrong type, we'll use document.domain\n const domain =\n this.varnishCookieDomain ||\n (typeof sessionData.baseDomain === 'string'\n ? sessionData.baseDomain\n : this.window.location.hostname) ||\n '';\n\n const cookie = [\n `SP_ID=${sessionData.sp_id}`,\n `expires=${date.toUTCString()}`,\n `path=/`,\n `domain=.${domain}`,\n ].join('; ');\n document.cookie = cookie;\n }\n\n /**\n * Clear the Varnish cookie if configured\n * @private\n */\n _maybeClearVarnishCookie(): void {\n if (this.setVarnishCookie) {\n this._clearVarnishCookie();\n }\n }\n\n /**\n * Clear the Varnish cookie\n * @private\n */\n _clearVarnishCookie(): void {\n const baseDomain =\n this._session &&\n isSessionSuccessResponse(this._session) &&\n typeof this._session.baseDomain === 'string'\n ? this._session.baseDomain\n : this.window.location.hostname;\n\n const domain = this.varnishCookieDomain || baseDomain || '';\n\n document.cookie = `SP_ID=nothing; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.${domain}`;\n }\n\n /**\n * Log used settings and version\n * @throws {SDKError} - If log method is not provided\n */\n logSettings(): void {\n if (!this.log && !window.console) {\n throw new SDKError('You have to provide log method in constructor');\n }\n\n const log = this.log || console.log;\n\n const settings = {\n clientId: this.clientId,\n redirectUri: this.redirectUri,\n env: this.env,\n sessionDomain: this._sessionDomain,\n sdkVersion: version,\n };\n\n log(`Schibsted account SDK for browsers settings: \\n${JSON.stringify(settings, null, 2)}`);\n }\n\n /**\n * @summary Queries the hassession endpoint and returns information about the status of the user\n * @remarks When we send a request to this endpoint, cookies sent along with the request\n * determines the status of the user.\n * @throws {SDKError} - If the call to the hasSession service fails in any way (this will happen\n * if, say, the user is not logged in)\n * @fires Identity#login\n * @fires Identity#logout\n * @fires Identity#userChange\n * @fires Identity#sessionChange\n * @fires Identity#notLoggedin\n * @fires Identity#sessionInit\n * @fires Identity#statusChange\n * @fires Identity#error\n */\n hasSession(): Promise<SessionResponse> {\n const isSessionCallBlocked = this._isSessionCallBlocked();\n\n if (isSessionCallBlocked) {\n const sessionData = normalizeSessionResponse(this._session);\n return Promise.resolve(isRedirectSessionPayload(sessionData) ? {} : sessionData);\n }\n\n if (this._hasSessionInProgress) {\n return this._hasSessionInProgress;\n }\n\n const _postProcess = (sessionData: SessionObjectResponse): SessionObjectResponse => {\n if (isSessionFailureResponse(sessionData)) {\n const errorObject = isObject(sessionData.error)\n ? sessionData.error\n : { description: String(sessionData.error) };\n throw new SDKError('HasSession failed', errorObject);\n }\n this._maybeSetVarnishCookie(sessionData);\n this._emitSessionEvent(this._session, sessionData);\n this._session = sessionData;\n return sessionData;\n };\n\n const _getCachedSession = (): NormalizedSessionPayload | null => {\n const cachedSession = this.sessionStorageCache.get(HAS_SESSION_CACHE_KEY);\n return cachedSession ? normalizeSessionResponse(cachedSession) : null;\n };\n\n const _getSession = async (): Promise<SessionResponse> => {\n if (this._enableSessionCaching) {\n // Try to resolve from cache (it has a TTL)\n const cachedSession = _getCachedSession();\n if (cachedSession) {\n if (isRedirectSessionPayload(cachedSession)) {\n return {};\n }\n return _postProcess(cachedSession);\n }\n }\n let sessionData: NormalizedSessionPayload | null = null;\n try {\n sessionData = await this._sessionService.get(\n this._usedSessionServiceGetSessionEndpoint,\n { tabId: this._getTabId() },\n normalizeSessionResponse,\n );\n } catch (err: unknown) {\n const cacheableError = isObject(err) ? err : undefined;\n if (cacheableError?.code === 400 && this._enableSessionCaching) {\n const errorExpiresIn =\n typeof cacheableError.expiresIn === 'number'\n ? cacheableError.expiresIn\n : 300;\n const expiresIn = 1000 * errorExpiresIn;\n this.sessionStorageCache.set(HAS_SESSION_CACHE_KEY, { error: err }, expiresIn);\n } else if (\n cacheableError &&\n typeof cacheableError.code === 'number' &&\n cacheableError.code >= 500 &&\n cacheableError.code < 600 &&\n this._enableSessionCaching\n ) {\n // Temporary fix: 30 seconds cache to limit number of calls when service is unavailable\n this.sessionStorageCache.set(HAS_SESSION_CACHE_KEY, { error: err }, 30 * 1000);\n }\n throw err;\n }\n\n if (sessionData) {\n // for expiring session and safari browser do full page redirect to gain new session\n if (isRedirectSessionPayload(sessionData)) {\n this._blockSessionCall();\n\n await this.callbackBeforeRedirect();\n\n const redirectUrl = this._sessionService.makeUrl(sessionData.redirectURL, {\n tabId: this._getTabId(),\n });\n return redirectUrl;\n }\n\n if (this._enableSessionCaching) {\n const expiresIn =\n 1000 *\n (isSessionSuccessResponse(sessionData)\n ? sessionData.expiresIn || 300\n : 300);\n this.sessionStorageCache.set(HAS_SESSION_CACHE_KEY, sessionData, expiresIn);\n }\n }\n\n return _postProcess(sessionData ?? {});\n };\n this._hasSessionInProgress = _getSession().then(\n (sessionData) => {\n this._hasSessionInProgress = false;\n if (typeof sessionData === 'string') {\n this.window.location.href = sessionData;\n }\n return sessionData;\n },\n (err) => {\n this.emit('error', err);\n this._hasSessionInProgress = false;\n throw new SDKError('HasSession failed', err);\n },\n );\n\n return this._hasSessionInProgress;\n }\n\n /**\n * @summary Allows the client app to check if the user is logged in to Schibsted account\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n */\n async isLoggedIn(): Promise<boolean> {\n try {\n const data = await this.hasSession();\n return isSessionSuccessResponse(data);\n } catch (_) {\n return false;\n }\n }\n\n /**\n * Removes the cached user session.\n */\n clearCachedUserSession(): void {\n this.sessionStorageCache.delete(HAS_SESSION_CACHE_KEY);\n }\n\n /**\n * @summary Allows the caller to check if the current user is connected to the client_id in\n * Schibsted account. Being connected means that the user has agreed for their account to be\n * used by your web app and have accepted the required terms\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @summary Check if the user is connected to the client_id\n */\n async isConnected(): Promise<boolean> {\n try {\n return isConnectedSessionResponse(await this.hasSession());\n } catch (_) {\n return false;\n }\n }\n\n /**\n * @summary Returns information about the user\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @throws {SDKError} If the user isn't connected to the merchant\n * @throws {SDKError} If we couldn't get the user\n */\n async getUser(): Promise<ConnectedSessionResponse> {\n const user = await this.hasSession();\n if (!isConnectedSessionResponse(user)) {\n throw new SDKError('The user is not connected to this merchant');\n }\n return cloneDeep(user);\n }\n\n /**\n * @summary\n * In Schibsted account, there are multiple ways of identifying a user; the `userId`,\n * `uuid` and `externalId` used for identifying a user-merchant pair (see {@link Identity#getExternalId}).\n * There are reasons for them all to exist. The `userId` is a numeric identifier, but\n * since Schibsted account is deployed separately in Norway and Sweden, there are a lot of\n * duplicates. The `userId` was introduced early, so many sites still need to use them for\n * legacy reasons. The `uuid` is universally unique, and so — if we could disregard a lot of\n * Schibsted components depending on the numeric `userId` — it would be a good identifier to use\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @throws {SDKError} If the user isn't connected to the merchant\n * @return The `userId` field (not to be confused with the `uuid`)\n */\n async getUserId(): Promise<string> {\n const user = await this.hasSession();\n if (isConnectedSessionWithUserIdResponse(user)) {\n return String(user.userId);\n }\n throw new SDKError('The user is not connected to this merchant');\n }\n\n /**\n * @function\n * @summary\n * Retrieves the external identifier (`externalId`) for the authenticated user.\n *\n * In Schibsted Account there are multiple ways of identifying users, however for integrations with\n * third-parties it's recommended to use `externalId` as it does not disclose\n * any critical data whilst allowing for user identification.\n *\n * `externalId` is merchant-scoped using a pairwise identifier (`pairId`),\n * meaning the same user's ID will differ between merchants.\n * Additionally, this identifier is bound to the external party provided as argument.\n *\n * @param externalParty\n * @param optionalSuffix\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @throws {SDKError} If the `pairId` is missing in user session.\n * @throws {SDKError} If the `externalParty` is not defined\n * @return The merchant- and 3rd-party-specific `externalId`\n */\n async getExternalId(externalParty: string, optionalSuffix: string = ''): Promise<string> {\n const user = await this.hasSession();\n const pairId = isSessionSuccessResponse(user) ? user.pairId : undefined;\n\n if (!pairId) throw new SDKError('pairId missing in user session!');\n\n if (!externalParty || externalParty.length === 0) {\n throw new SDKError('externalParty cannot be empty');\n }\n const _toHexDigest = (hashBuffer: ArrayBuffer) => {\n // convert buffer to byte array\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n // convert bytes to hex string\n return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n };\n\n const _getSha256Digest = (data: BufferSource) => {\n return crypto.subtle.digest('SHA-256', data);\n };\n\n const _hashMessage = async (message: string) => {\n const msgUint8 = new TextEncoder().encode(message);\n return _getSha256Digest(msgUint8).then((it) => _toHexDigest(it));\n };\n\n const _constructMessage = (\n pairId: string,\n externalParty: string,\n optionalSuffix: string,\n ) => {\n return optionalSuffix\n ? `${pairId}:${externalParty}:${optionalSuffix}`\n : `${pairId}:${externalParty}`;\n };\n\n return _hashMessage(_constructMessage(pairId, externalParty, optionalSuffix));\n }\n\n /**\n * @summary Enables brands to programmatically get the current the SDRN based on the user's session.\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @throws {SDKError} If the SDRN is missing in user session object.\n */\n async getUserSDRN(): Promise<string> {\n const user = await this.hasSession();\n if (isSessionSuccessResponse(user) && user.sdrn) {\n return user.sdrn;\n }\n throw new SDKError('Failed to get SDRN from user session');\n }\n\n /**\n * @summary In Schibsted account, there are two ways of identifying a user; the `userId` and the\n * `uuid`. There are reasons for them both existing. The `userId` is a numeric identifier, but\n * since Schibsted account is deployed separately in Norway and Sweden, there are a lot of\n * duplicates. The `userId` was introduced early, so many sites still need to use them for\n * legacy reasons. The `uuid` is universally unique, and so — if we could disregard a lot of\n * Schibsted components depending on the numeric `userId` — it would be a good identifier to use\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @throws {SDKError} If the user isn't connected to the merchant\n * @return The `uuid` field (not to be confused with the `userId`)\n */\n async getUserUuid(): Promise<string> {\n const user = await this.hasSession();\n if (isSessionSuccessResponse(user) && user.uuid && user.result) {\n return user.uuid;\n }\n throw new SDKError('The user is not connected to this merchant');\n }\n\n /**\n * @summary Get basic information about any user currently logged-in to their Schibsted account\n * in this browser. Can be used to provide context in a continue-as prompt.\n * @remarks This function relies on the global Schibsted account user session cookie, which\n * is a third-party cookie and hence might be blocked by the browser (for example due to ITP in\n * Safari). So there's no guarantee any data is returned, even though a user is logged-in in\n * the current browser.\n */\n async getUserContextData(): Promise<SimplifiedLoginData | null> {\n try {\n return await this._globalSessionService.get('user-context', undefined, (value) =>\n isObject(value) && isStr(value.identifier)\n ? {\n identifier: value.identifier,\n display_text: isStr(value.display_text) ? value.display_text : '',\n client_name: isStr(value.client_name) ? value.client_name : '',\n provider_id: isStr(value.provider_id) ? value.provider_id : undefined,\n }\n : null,\n );\n } catch (_) {\n return null;\n }\n }\n\n /**\n * If a popup is desired, this function needs to be called in response to a user event (like\n * click or tap) in order to work correctly. Otherwise the popup will be blocked by the\n * browser's popup blockers and has to be explicitly authorized to be shown.\n * @summary Perform a login, either using a full-page redirect or a popup\n * @see https://tools.ietf.org/html/rfc6749#section-4.1.1\n *\n * @param options\n * @param options.state\n * @param options.acrValues\n * @param options.scope\n * @param options.redirectUri\n * @param options.preferPopup\n * @param options.loginHint\n * @param options.tag\n * @param options.teaser\n * @param options.maxAge\n * @param options.locale\n * @param options.oneStepLogin\n * @param options.prompt\n * @param options.xDomainId\n * @param options.xEnvironmentId\n * @param options.originCampaign\n * @return - Reference to popup window if created (or `null` otherwise)\n */\n login({\n state,\n acrValues,\n scope = 'openid',\n redirectUri = this.redirectUri,\n preferPopup = false,\n loginHint = '',\n tag = '',\n teaser = '',\n maxAge = '',\n locale,\n oneStepLogin = false,\n prompt = 'select_account',\n xDomainId = '',\n xEnvironmentId = '',\n originCampaign = '',\n }: LoginOptions): Window | null {\n this._closePopup();\n this.sessionStorageCache.delete(HAS_SESSION_CACHE_KEY);\n const url = this.loginUrl({\n state,\n acrValues,\n scope,\n redirectUri,\n loginHint,\n tag,\n teaser,\n maxAge,\n locale,\n oneStepLogin,\n prompt,\n xDomainId,\n xEnvironmentId,\n originCampaign,\n });\n\n if (preferPopup) {\n this.popup = popup.open(this.window, url, 'Schibsted account', {\n width: 360,\n height: 570,\n });\n if (this.popup) {\n return this.popup;\n }\n }\n this.window.location.href = url;\n return null;\n }\n\n /**\n * @summary Retrieve the sp_id (Varnish ID)\n * @remarks This function calls {@link Identity#hasSession} internally and thus has the side\n * effect that it might perform an auto-login on the user\n * @return - The sp_id string or null (if the server didn't return it)\n */\n async getSpId(): Promise<string | null> {\n try {\n const user = await this.hasSession();\n if (isSessionSuccessResponse(user)) {\n return user.sp_id || null;\n }\n const spId = isObject(user) && 'sp_id' in user ? user.sp_id : undefined;\n return isStr(spId) ? spId : null;\n } catch (_) {\n return null;\n }\n }\n\n /**\n * @summary Logs the user out from the Identity platform\n * @param redirectUri - Where to redirect the browser after logging out of Schibsted\n * account\n */\n logout(redirectUri: string = this.redirectUri): void {\n this.sessionStorageCache.delete(HAS_SESSION_CACHE_KEY);\n this._maybeClearVarnishCookie();\n this.emit('logout');\n this.window.location.href = this.logoutUrl(redirectUri);\n }\n\n /**\n * Generates the link to the new login page that'll be used in the popup or redirect flow\n * @param options\n * @param options.state\n * @param options.acrValues\n * @param options.scope\n * @param options.redirectUri\n * @param options.loginHint\n * @param options.tag\n * @param options.teaser\n * @param options.maxAge\n * @param options.locale\n * @param options.oneStepLogin\n * @param options.prompt\n * @param options.xDomainId\n * @param options.xEnvironmentId\n * @param options.originCampaign\n * @return - The url\n */\n loginUrl({\n state,\n acrValues = '',\n scope = 'openid',\n redirectUri = this.redirectUri,\n loginHint = '',\n tag = '',\n teaser = '',\n maxAge = '',\n locale,\n oneStepLogin = false,\n prompt = 'select_account',\n xDomainId = '',\n xEnvironmentId = '',\n originCampaign = '',\n }: LoginOptions): string {\n const isValidAcrValue = (acrValue: string) =>\n isStrIn(\n acrValue,\n ['password', 'otp', 'sms', 'eid-dk', 'eid-no', 'eid-se', 'eid-fi', 'eid'],\n true,\n );\n assert(\n !acrValues ||\n isStrIn(acrValues, ['', 'otp-email'], true) ||\n acrValues.split(' ').every(isValidAcrValue),\n `The acrValues parameter is not acceptable: ${acrValues}`,\n );\n assert(\n isUrl(redirectUri),\n `loginUrl(): redirectUri must be a valid url but is ${redirectUri}`,\n );\n assert(\n isNonEmptyString(state),\n `the state parameter should be a non empty string but it is ${state}`,\n );\n\n return this._oauthService.makeUrl('oauth/authorize', {\n response_type: 'code',\n redirect_uri: redirectUri,\n scope,\n state,\n acr_values: acrValues,\n login_hint: loginHint,\n tag,\n teaser,\n max_age: maxAge,\n locale,\n one_step_login: oneStepLogin || '',\n prompt: acrValues ? '' : prompt,\n x_domain_id: xDomainId,\n x_env_id: xEnvironmentId,\n utm_campaign: originCampaign,\n });\n }\n\n /**\n * The url for logging the user out\n * @param redirectUri\n * @return url\n */\n logoutUrl(redirectUri: string = this.redirectUri): string {\n assert(isUrl(redirectUri), `logoutUrl(): redirectUri is invalid`);\n const params = { redirect_uri: redirectUri };\n return this._sessionService.makeUrl('logout', params);\n }\n\n /**\n * The account summary page url\n * @param redirectUri\n */\n accountUrl(redirectUri: string = this.redirectUri): string {\n return this._spid.makeUrl('profile-pages', {\n response_type: 'code',\n redirect_uri: redirectUri,\n });\n }\n\n /**\n * The phone editing page url\n * @param redirectUri\n */\n phonesUrl(redirectUri: string = this.redirectUri): string {\n return this._spid.makeUrl('profile-pages/about-you/phone', {\n response_type: 'code',\n redirect_uri: redirectUri,\n });\n }\n\n /**\n * Function responsible for loading and displaying simplified login widget. How often\n * widget will be display is up to you. Preferred way would be to show it once per user,\n * and store that info in localStorage. Widget will be display only if user is logged in to SSO.\n *\n * @param loginParams - the same as `options` param for login function. Login will be called on user\n * continue action. `state` might be string or async function.\n * @param options - additional configuration of Simplified Login Widget\n * @fires Identity#simplifiedLoginOpened\n * @fires Identity#simplifiedLoginCancelled\n * @throws {SDKError} - If user context data is missing or the widget script cannot be loaded\n * @return - will resolve to true if widget will be displayed\n */\n async showSimplifiedLoginWidget(\n loginParams: SimplifiedLoginWidgetLoginOptions,\n options?: SimplifiedLoginWidgetOptions,\n ): Promise<boolean> {\n // getUserContextData doesn't throw exception\n const userData = await this.getUserContextData();\n\n const queryParams: Record<string, string> = { client_id: this.clientId };\n if (options && options.encoding) {\n queryParams.encoding = options.encoding;\n }\n const widgetUrl = this._bffService.makeUrl('simplified-login-widget', queryParams, false);\n\n const prepareLoginParams = async (\n loginParams: SimplifiedLoginWidgetLoginOptions,\n ): Promise<LoginOptions> => {\n const state =\n typeof loginParams.state === 'function'\n ? await loginParams.state()\n : loginParams.state;\n\n return {\n ...loginParams,\n state,\n };\n };\n\n return new Promise<boolean>((resolve, reject) => {\n if (!userData?.display_text || !userData.identifier) {\n reject(new SDKError('Missing user data'));\n return;\n }\n\n const initialParams: SimplifiedLoginWidgetInitialParams = {\n displayText: userData.display_text,\n env: this.env,\n clientName: userData.client_name || '',\n clientId: this.clientId,\n providerId: userData.provider_id,\n windowWidth: () => window.innerWidth,\n windowOnResize: (f: () => void) => {\n window.onresize = f;\n },\n };\n\n if (options && options.locale) {\n initialParams.locale = options.locale;\n }\n\n const loginHandler = async () => {\n this.login(\n Object.assign(await prepareLoginParams(loginParams), {\n loginHint: userData.identifier,\n }) as LoginOptions,\n );\n };\n\n const loginNotYouHandler = async () => {\n this.login(\n Object.assign(await prepareLoginParams(loginParams), {\n loginHint: userData.identifier,\n prompt: 'login',\n }) as LoginOptions,\n );\n };\n\n const initHandler = () => {\n /**\n * Emitted when the simplified login widget is displayed on the screen\n * @event Identity#simplifiedLoginOpened\n */\n this.emit('simplifiedLoginOpened');\n };\n\n const cancelLoginHandler = () => {\n this.emit('simplifiedLoginCancelled');\n };\n\n if (hasOpenSimplifiedLoginWidget(window)) {\n window.openSimplifiedLoginWidget(\n initialParams,\n loginHandler,\n loginNotYouHandler,\n initHandler,\n cancelLoginHandler,\n );\n return resolve(true);\n }\n\n const simplifiedLoginWidget = document.createElement('script');\n simplifiedLoginWidget.type = 'text/javascript';\n simplifiedLoginWidget.src = widgetUrl;\n simplifiedLoginWidget.onload = () => {\n if (!hasOpenSimplifiedLoginWidget(window)) {\n reject(new SDKError('Error when loading simplified login widget content'));\n return;\n }\n window.openSimplifiedLoginWidget(\n initialParams,\n loginHandler,\n loginNotYouHandler,\n initHandler,\n cancelLoginHandler,\n );\n resolve(true);\n };\n simplifiedLoginWidget.onerror = () => {\n reject(new SDKError('Error when loading simplified login widget content'));\n };\n document.getElementsByTagName('body')[0].appendChild(simplifiedLoginWidget);\n });\n }\n}\n\nexport default Identity;\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport SDKError from './sdk-error.js';\nimport type { HasAccessResult } from './types/monetization.js';\nimport { isObject, isStr } from './validate.js';\n\nexport function parseHasAccessResult(value: unknown): HasAccessResult {\n if (!isObject(value)) {\n throw new SDKError('Invalid hasAccess response');\n }\n\n const { entitled, ttl, allowedFeatures, userId, uuid, sig } = value;\n\n if (\n typeof entitled !== 'boolean' ||\n typeof ttl !== 'number' ||\n !Array.isArray(allowedFeatures) ||\n (typeof userId !== 'number' && typeof userId !== 'string') ||\n !isStr(uuid) ||\n !isStr(sig)\n ) {\n throw new SDKError('Invalid hasAccess response');\n }\n\n return {\n entitled,\n ttl,\n allowedFeatures: allowedFeatures.filter(isStr),\n userId,\n uuid,\n sig,\n };\n}\n","/* Copyright 2024 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { TinyEmitter } from 'tiny-emitter';\nimport Cache from './cache.js';\nimport { ENDPOINTS } from './config.js';\nimport { registerAndDispatchInGlobal } from './global-registry.js';\nimport { parseHasAccessResult } from './has-access-response.js';\nimport type { SessionUserId } from './identity.js';\nimport type RESTClient from './rest-client.js';\nimport { buildClientSdrn, createAccountRestClient } from './rest-clients.js';\nimport SDKError from './sdk-error.js';\nimport * as spidTalk from './spid-talk.js';\nimport type { HasAccessResult, MonetizationOptions } from './types/monetization.js';\nimport { urlMapper } from './url.js';\nimport { assert, isNonEmptyString, isStr, isUrl } from './validate.js';\nimport version from './version.js';\n\nconst globalWindow = () => window;\n\n/**\n * Provides features related to monetization\n */\nexport class Monetization extends TinyEmitter {\n cache: Cache;\n clientId: string;\n env: string;\n redirectUri?: string;\n _spid: RESTClient;\n _sessionService?: RESTClient;\n private pendingHasAccessRequests: Record<string, Promise<HasAccessResult>>;\n\n /**\n * @param options - Monetization configuration\n * @throws {SDKError} - If any of options are invalid\n */\n constructor({\n clientId,\n redirectUri,\n env = 'PRE',\n sessionDomain,\n window = globalWindow(),\n }: MonetizationOptions) {\n super();\n spidTalk.emulate(window);\n assert(isNonEmptyString(clientId), 'clientId parameter is required');\n assert(isStr(env), `env parameter is invalid: ${env}`);\n\n this.cache = new Cache(() => window && window.sessionStorage);\n this.clientId = clientId;\n this.env = env;\n this.redirectUri = redirectUri;\n this.pendingHasAccessRequests = {};\n this._spid = createAccountRestClient({\n serverUrl: urlMapper(env, ENDPOINTS.SPiD),\n defaultParams: { client_id: this.clientId, redirect_uri: this.redirectUri },\n });\n\n if (sessionDomain) {\n assert(isUrl(sessionDomain), 'sessionDomain parameter is not a valid URL');\n this._sessionService = createAccountRestClient({\n serverUrl: sessionDomain,\n defaultParams: {\n client_sdrn: buildClientSdrn(this.env, this.clientId),\n redirect_uri: this.redirectUri,\n sdk_version: version,\n },\n });\n }\n registerAndDispatchInGlobal(window, 'schMonetization', this);\n }\n\n /**\n * Checks if the user has access to a set of products or features.\n * @param productIds - which products/features to check\n * @param userId - id of currently logged in user\n * @throws {SDKError} - If the input is incorrect, or a network call fails in any way\n * (this will happen if, say, the user is not logged in)\n * @returns The data object returned from Schibsted account (or `null` if the user\n * doesn't have access to any of the given products/features)\n */\n async hasAccess(productIds: string[], userId: SessionUserId): Promise<HasAccessResult | null> {\n if (!this._sessionService) {\n throw new SDKError(`hasAccess can only be called if 'sessionDomain' is configured`);\n }\n if (!userId) {\n throw new SDKError(`'userId' must be specified`);\n }\n if (!Array.isArray(productIds)) {\n throw new SDKError(`'productIds' must be an array`);\n }\n\n const sortedIds = [...productIds].sort();\n const cacheKey = this._accessCacheKey(sortedIds, userId);\n let data = this.cache.get(cacheKey) as HasAccessResult | null;\n if (!data) {\n if (!this.pendingHasAccessRequests[cacheKey]) {\n this.pendingHasAccessRequests[cacheKey] = this._sessionService.get(\n `/hasAccess/${sortedIds.join(',')}`,\n undefined,\n parseHasAccessResult,\n );\n }\n const promise = this.pendingHasAccessRequests[cacheKey];\n try {\n data = await promise;\n const expiresSeconds = data.ttl;\n this.cache.set(cacheKey, data, expiresSeconds * 1000);\n } finally {\n if (this.pendingHasAccessRequests[cacheKey] === promise) {\n delete this.pendingHasAccessRequests[cacheKey];\n }\n }\n }\n\n if (!data.entitled) {\n return null;\n }\n this.emit('hasAccess', { ids: sortedIds, data });\n return data;\n }\n\n /**\n * Removes the cached access result.\n * @param productIds - which products/features to check\n * @param userId - id of currently logged in user\n */\n clearCachedAccessResult(productIds: string[], userId: SessionUserId): void {\n this.cache.delete(this._accessCacheKey(productIds, userId));\n }\n\n /**\n * Compute \"has access\" cache key for the given product ids and user id.\n * @private\n * @param productIds - which products/features to check\n * @param userId - id of currently logged in user\n */\n private _accessCacheKey(productIds: string[], userId: SessionUserId): string {\n return `prd_${[...productIds].sort()}_${userId}`;\n }\n\n /**\n * Get the url for the end user to review the subscriptions\n * @param redirectUri\n * @returns - The url to the subscriptions review page\n */\n subscriptionsUrl(redirectUri: string = this.redirectUri ?? ''): string {\n assert(isUrl(redirectUri), `subscriptionsUrl(): redirectUri is invalid`);\n return this._spid.makeUrl('account/subscriptions', { redirect_uri: redirectUri });\n }\n\n /**\n * Get the url for the end user to review the products\n * @param redirectUri\n * @returns - The url to the products review page\n */\n productsUrl(redirectUri: string = this.redirectUri ?? ''): string {\n assert(isUrl(redirectUri), `productsUrl(): redirectUri is invalid`);\n return this._spid.makeUrl('account/products', { redirect_uri: redirectUri });\n }\n}\n\nexport default Monetization;\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nexport const resolveBrowserWindow = (providedWindow?: Window): Window | undefined => {\n if (providedWindow) {\n return providedWindow;\n }\n\n return typeof window === 'undefined' ? undefined : window;\n};\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { registerAndDispatchInGlobal } from './global-registry.js';\nimport Identity from './identity.js';\nimport Monetization from './monetization.js';\nimport { resolveBrowserWindow } from './resolve-browser-window.js';\nimport SDKError from './sdk-error.js';\nimport type { AccountConfig, AccountEventHandler, AccountEventName } from './types/account.js';\nimport type {\n LoginOptions,\n SimplifiedLoginData,\n SimplifiedLoginWidgetLoginOptions,\n SimplifiedLoginWidgetOptions,\n} from './types/login.js';\nimport type { HasAccessResult } from './types/monetization.js';\nimport type { ConnectedSessionResponse, SessionResponse, SessionUserId } from './types/session.js';\n\n/**\n * Unified client-side interface for a configured Schibsted Account integration.\n */\nexport class Account {\n #identity: Identity;\n #monetization: Monetization;\n\n constructor(config: AccountConfig) {\n const browserWindow = resolveBrowserWindow(config.window);\n\n if (!browserWindow) {\n throw new SDKError('Schibsted Account SDK is not available in this browser context');\n }\n\n if (browserWindow.schAccount) {\n throw new SDKError('Schibsted Account SDK has already been initialized');\n }\n\n const { log, callbackBeforeRedirect, varnish } = config;\n const sharedConfig = {\n clientId: config.clientId,\n redirectUri: config.redirectUri,\n sessionDomain: config.sessionDomain,\n env: config.env,\n window: browserWindow,\n };\n\n this.#identity = new Identity({\n ...sharedConfig,\n log,\n callbackBeforeRedirect,\n });\n\n if (varnish) {\n if (typeof varnish !== 'object' || Array.isArray(varnish)) {\n throw new SDKError('Account varnish config must be an object');\n }\n this.#identity.enableVarnishCookie(varnish);\n }\n\n this.#monetization = new Monetization(sharedConfig);\n\n registerAndDispatchInGlobal(browserWindow, 'schAccount', this);\n }\n\n hasSession(): Promise<SessionResponse> {\n return this.#identity.hasSession();\n }\n\n isLoggedIn(): Promise<boolean> {\n return this.#identity.isLoggedIn();\n }\n\n isConnected(): Promise<boolean> {\n return this.#identity.isConnected();\n }\n\n getUser(): Promise<ConnectedSessionResponse> {\n return this.#identity.getUser();\n }\n\n getUserId(): Promise<string> {\n return this.#identity.getUserId();\n }\n\n getUserSDRN(): Promise<string> {\n return this.#identity.getUserSDRN();\n }\n\n getUserContextData(): Promise<SimplifiedLoginData | null> {\n return this.#identity.getUserContextData();\n }\n\n getSpId(): Promise<string | null> {\n return this.#identity.getSpId();\n }\n\n login(options: LoginOptions): Window | null {\n return this.#identity.login(options);\n }\n\n logout(redirectUri?: string): void {\n this.#identity.logout(redirectUri);\n }\n\n loginUrl(options: LoginOptions): string {\n return this.#identity.loginUrl(options);\n }\n\n showSimplifiedLoginWidget(\n loginParams: SimplifiedLoginWidgetLoginOptions,\n options?: SimplifiedLoginWidgetOptions,\n ): Promise<boolean> {\n return this.#identity.showSimplifiedLoginWidget(loginParams, options);\n }\n\n clearCachedUserSession(): void {\n this.#identity.clearCachedUserSession();\n }\n\n hasAccess(productIds: string[], userId: SessionUserId): Promise<HasAccessResult | null> {\n return this.#monetization.hasAccess(productIds, userId);\n }\n\n clearCachedAccessResult(productIds: string[], userId: SessionUserId): void {\n this.#monetization.clearCachedAccessResult(productIds, userId);\n }\n\n on(event: AccountEventName, callback: AccountEventHandler, ctx?: unknown): this {\n if (event === 'hasAccess') {\n this.#monetization.on(event, callback, ctx);\n } else {\n this.#identity.on(event, callback, ctx);\n }\n\n return this;\n }\n\n off(event: AccountEventName, callback?: AccountEventHandler): this {\n if (event === 'hasAccess') {\n this.#monetization.off(event, callback);\n } else {\n this.#identity.off(event, callback);\n }\n\n return this;\n }\n}\n\nexport default Account;\n","/* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.\n * See LICENSE.md in the project root.\n */\n\nimport { Account } from './account.js';\nimport { resolveBrowserWindow } from './resolve-browser-window.js';\nimport type { AccountConfig } from './types/account.js';\n\nconst ACCOUNT_READY_EVENT = 'schAccount:ready';\nconst GET_ACCOUNT_SDK_TIMEOUT_MS = 4000;\n\nlet pendingAccountPromise: Promise<Account> | undefined;\n\nconst createUnavailableError = (): Error =>\n new Error('Schibsted Account SDK is not available in this browser context');\n\nconst createTimeoutError = (): Error =>\n new Error(`Schibsted Account SDK was not initialized within ${GET_ACCOUNT_SDK_TIMEOUT_MS} ms`);\n\nexport function createAccountSdk(config: AccountConfig): Account {\n return new Account(config);\n}\n\nexport function getAccountSdk(): Promise<Account> {\n const browserWindow = resolveBrowserWindow();\n\n if (!browserWindow) {\n const error = createUnavailableError();\n console.error(error.message);\n return Promise.reject(error);\n }\n\n if (browserWindow.schAccount) {\n return Promise.resolve(browserWindow.schAccount);\n }\n\n if (pendingAccountPromise) {\n return pendingAccountPromise;\n }\n\n pendingAccountPromise = new Promise<Account>((resolve, reject) => {\n let timeoutId: number | undefined;\n\n const cleanup = () => {\n browserWindow.removeEventListener(ACCOUNT_READY_EVENT, resolveRegisteredAccount);\n if (timeoutId !== undefined) {\n browserWindow.clearTimeout(timeoutId);\n }\n pendingAccountPromise = undefined;\n };\n\n const resolveRegisteredAccount = () => {\n const account = browserWindow.schAccount;\n if (!account) {\n return;\n }\n\n cleanup();\n resolve(account);\n };\n\n browserWindow.addEventListener(ACCOUNT_READY_EVENT, resolveRegisteredAccount);\n timeoutId = browserWindow.setTimeout(() => {\n const error = createTimeoutError();\n console.error(error.message);\n cleanup();\n reject(error);\n }, GET_ACCOUNT_SDK_TIMEOUT_MS);\n\n resolveRegisteredAccount();\n });\n\n return pendingAccountPromise;\n}\n"],"x_google_ignoreList":[1],"mappings":";2FAyBa,KACT,GACA,GACA,MACO;CAKP,AAJK,EAAO,OACR,EAAO,KAAY,IAGvB,EAAO,cAEH,IAAI,YAAY,GAAG,EAAS,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAO,GAAU,EAAE,CAAC,CACn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
|
-
|
|
5
|
-
|
|
6
|
-
* is entitled to a requested set of products/features.
|
|
7
|
-
* @internal
|
|
8
|
-
*/
|
|
9
|
-
export interface HasAccessResult {
|
|
10
|
-
/** Whether the user is entitled to at least one of the requested products/features. */
|
|
11
|
-
entitled: boolean;
|
|
12
|
-
/** How long this result stays valid, in seconds, before the cache entry expires. */
|
|
13
|
-
ttl: number;
|
|
14
|
-
allowedFeatures: string[];
|
|
15
|
-
userId: number;
|
|
16
|
-
uuid: string;
|
|
17
|
-
sig: string;
|
|
18
|
-
}
|
|
3
|
+
import { SessionUserId } from './identity.js';
|
|
4
|
+
import { default as RESTClient } from './rest-client.js';
|
|
5
|
+
import { HasAccessResult, MonetizationOptions } from './types/monetization.js';
|
|
19
6
|
/**
|
|
20
7
|
* Provides features related to monetization
|
|
21
8
|
*/
|
|
@@ -23,7 +10,7 @@ export declare class Monetization extends TinyEmitter {
|
|
|
23
10
|
cache: Cache;
|
|
24
11
|
clientId: string;
|
|
25
12
|
env: string;
|
|
26
|
-
redirectUri
|
|
13
|
+
redirectUri?: string;
|
|
27
14
|
_spid: RESTClient;
|
|
28
15
|
_sessionService?: RESTClient;
|
|
29
16
|
private pendingHasAccessRequests;
|
|
@@ -31,30 +18,7 @@ export declare class Monetization extends TinyEmitter {
|
|
|
31
18
|
* @param options - Monetization configuration
|
|
32
19
|
* @throws {SDKError} - If any of options are invalid
|
|
33
20
|
*/
|
|
34
|
-
constructor({ clientId, redirectUri, env, sessionDomain, window, }:
|
|
35
|
-
/** Mandatory client id */
|
|
36
|
-
clientId: string;
|
|
37
|
-
/** Redirect uri */
|
|
38
|
-
redirectUri: string;
|
|
39
|
-
/** Example: `"https://id.site.com"` */
|
|
40
|
-
sessionDomain: string;
|
|
41
|
-
/** Schibsted account environment: `PRE` (default), `PRO`, `PRO_NO` */
|
|
42
|
-
env?: string;
|
|
43
|
-
/** Window object to use (defaults to the global `window`). */
|
|
44
|
-
window?: Window;
|
|
45
|
-
});
|
|
46
|
-
/**
|
|
47
|
-
* Set SPiD server URL
|
|
48
|
-
* @private
|
|
49
|
-
* @param url
|
|
50
|
-
*/
|
|
51
|
-
private _setSpidServerUrl;
|
|
52
|
-
/**
|
|
53
|
-
* Set session-service domain
|
|
54
|
-
* @private
|
|
55
|
-
* @param domain - real URL — (**not** 'PRE' style env key)
|
|
56
|
-
*/
|
|
57
|
-
private _setSessionServiceUrl;
|
|
21
|
+
constructor({ clientId, redirectUri, env, sessionDomain, window, }: MonetizationOptions);
|
|
58
22
|
/**
|
|
59
23
|
* Checks if the user has access to a set of products or features.
|
|
60
24
|
* @param productIds - which products/features to check
|
|
@@ -64,13 +28,13 @@ export declare class Monetization extends TinyEmitter {
|
|
|
64
28
|
* @returns The data object returned from Schibsted account (or `null` if the user
|
|
65
29
|
* doesn't have access to any of the given products/features)
|
|
66
30
|
*/
|
|
67
|
-
hasAccess(productIds: string[], userId:
|
|
31
|
+
hasAccess(productIds: string[], userId: SessionUserId): Promise<HasAccessResult | null>;
|
|
68
32
|
/**
|
|
69
33
|
* Removes the cached access result.
|
|
70
34
|
* @param productIds - which products/features to check
|
|
71
35
|
* @param userId - id of currently logged in user
|
|
72
36
|
*/
|
|
73
|
-
clearCachedAccessResult(productIds: string[], userId:
|
|
37
|
+
clearCachedAccessResult(productIds: string[], userId: SessionUserId): void;
|
|
74
38
|
/**
|
|
75
39
|
* Compute "has access" cache key for the given product ids and user id.
|
|
76
40
|
* @private
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const resolveBrowserWindow: (providedWindow?: Window) => Window | undefined;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { LogFunction } from './types/common.js';
|
|
1
2
|
type FetchFunction = (input: RequestInfo, init?: RequestInit) => Promise<Response>;
|
|
2
3
|
/**
|
|
3
4
|
* The value of a single query parameter; `undefined` entries are skipped.
|
|
@@ -11,6 +12,19 @@ type QueryParams = Record<string, QueryValue>;
|
|
|
11
12
|
* HTTP method used for a request.
|
|
12
13
|
*/
|
|
13
14
|
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
15
|
+
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
16
|
+
[key: string]: JsonValue;
|
|
17
|
+
};
|
|
18
|
+
type ResponseParser<T> = (value: JsonValue) => T;
|
|
19
|
+
type RESTRequestOptions<T = JsonValue> = {
|
|
20
|
+
method: HttpMethod;
|
|
21
|
+
pathname: string;
|
|
22
|
+
data?: QueryParams;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
useDefaultParams?: boolean;
|
|
25
|
+
fetchOptions?: RequestInit;
|
|
26
|
+
parseResponse?: ResponseParser<T>;
|
|
27
|
+
};
|
|
14
28
|
/**
|
|
15
29
|
* This class can be used for creating a wrapper around a server and all its endpoints.
|
|
16
30
|
* Its functionality is extended by {@link JSONPClient}
|
|
@@ -24,7 +38,7 @@ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
|
24
38
|
export declare class RESTClient {
|
|
25
39
|
url: URL;
|
|
26
40
|
defaultParams: QueryParams;
|
|
27
|
-
log?:
|
|
41
|
+
log?: LogFunction;
|
|
28
42
|
fetch: FetchFunction;
|
|
29
43
|
/**
|
|
30
44
|
* @param options
|
|
@@ -42,7 +56,7 @@ export declare class RESTClient {
|
|
|
42
56
|
serverUrl?: string;
|
|
43
57
|
envDic?: Record<string, string>;
|
|
44
58
|
fetch?: FetchFunction;
|
|
45
|
-
log?:
|
|
59
|
+
log?: LogFunction;
|
|
46
60
|
defaultParams?: QueryParams;
|
|
47
61
|
});
|
|
48
62
|
/**
|
|
@@ -58,14 +72,10 @@ export declare class RESTClient {
|
|
|
58
72
|
* @param options.fetchOptions - Additional fetch options
|
|
59
73
|
* @throws {SDKError} - If the call can't be made for whatever reason.
|
|
60
74
|
*/
|
|
61
|
-
go(
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
headers?: Record<string, string>;
|
|
66
|
-
useDefaultParams?: boolean;
|
|
67
|
-
fetchOptions?: RequestInit;
|
|
68
|
-
}): Promise<any>;
|
|
75
|
+
go(options: RESTRequestOptions): Promise<JsonValue>;
|
|
76
|
+
go<T>(options: RESTRequestOptions<T> & {
|
|
77
|
+
parseResponse: ResponseParser<T>;
|
|
78
|
+
}): Promise<T>;
|
|
69
79
|
/**
|
|
70
80
|
* Creates a url that points to an endpoint in the server
|
|
71
81
|
* @param pathname - WHATWG pathname ie. 'api/2/endpoint-name'
|
|
@@ -78,7 +88,8 @@ export declare class RESTClient {
|
|
|
78
88
|
* @param pathname - WHATWG pathname ie. 'api/2/endpoint-name'
|
|
79
89
|
* @param data - Query parameters
|
|
80
90
|
*/
|
|
81
|
-
get(pathname: string, data?: QueryParams): Promise<
|
|
91
|
+
get(pathname: string, data?: QueryParams): Promise<JsonValue>;
|
|
92
|
+
get<T>(pathname: string, data: QueryParams | undefined, parseResponse: ResponseParser<T>): Promise<T>;
|
|
82
93
|
/**
|
|
83
94
|
* Construct query string for WHATWG urls
|
|
84
95
|
* @private
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { default as RESTClient } from './rest-client.js';
|
|
2
|
+
import { LogFunction } from './types/common.js';
|
|
3
|
+
type AccountRestClientOptions = {
|
|
4
|
+
serverUrl: string;
|
|
5
|
+
log?: LogFunction;
|
|
6
|
+
defaultParams: Record<string, string | number | boolean | undefined>;
|
|
7
|
+
};
|
|
8
|
+
export declare const buildClientSdrn: (env: string, clientId: string) => string;
|
|
9
|
+
export declare const createAccountRestClient: ({ serverUrl, log, defaultParams, }: AccountRestClientOptions) => RESTClient;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ConnectedSessionResponse, ConnectedSessionWithUserIdResponse, NormalizedSessionPayload, RedirectSessionPayload, SessionFailureResponse, SessionResponse, SessionSuccessResponse } from './types/session.js';
|
|
2
|
+
export declare function isSessionSuccessResponse(value: unknown): value is SessionSuccessResponse;
|
|
3
|
+
export declare function isConnectedSessionResponse(value: unknown): value is ConnectedSessionResponse;
|
|
4
|
+
export declare function isSessionFailureResponse(value: unknown): value is SessionFailureResponse;
|
|
5
|
+
export declare function isRedirectSessionPayload(value: unknown): value is RedirectSessionPayload;
|
|
6
|
+
export declare function isConnectedSessionWithUserIdResponse(value: SessionResponse): value is ConnectedSessionWithUserIdResponse;
|
|
7
|
+
/**
|
|
8
|
+
* Converts an unknown Session Service `hasSession` payload into one of the shapes the SDK knows how
|
|
9
|
+
* to handle.
|
|
10
|
+
*
|
|
11
|
+
* This function is intentionally tolerant because `hasSession()` historically resolved unknown
|
|
12
|
+
* object payloads instead of rejecting them. The SDK relies on that behavior for backwards
|
|
13
|
+
* compatibility with clients that check the raw response themselves.
|
|
14
|
+
*
|
|
15
|
+
* The normal cases are:
|
|
16
|
+
* - regular success payloads with a boolean `result`;
|
|
17
|
+
* - failure payloads wrapped as `{ error, response? }`;
|
|
18
|
+
* - Safari/session-refresh redirect payloads shaped as `{ redirectURL }`.
|
|
19
|
+
*
|
|
20
|
+
* Any other object is preserved as an unrecognized response so callers can still receive it.
|
|
21
|
+
* Non-object values are normalized to `{}`, matching the old "empty response" fallback used by
|
|
22
|
+
* `hasSession()` and cached-session reads.
|
|
23
|
+
*
|
|
24
|
+
* This is used both for network responses parsed by `RESTClient` and for values restored from the
|
|
25
|
+
* session cache, so the rest of the Identity flow can switch on typed guards instead of repeatedly
|
|
26
|
+
* re-validating unknown data.
|
|
27
|
+
*
|
|
28
|
+
* @internal
|
|
29
|
+
*/
|
|
30
|
+
export declare function normalizeSessionResponse(value: unknown): NormalizedSessionPayload;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { AccountBaseConfig, LogFunction } from './common';
|
|
2
|
+
import { IdentityBeforeRedirectCallback, VarnishCookieOptions } from './identity';
|
|
3
|
+
export type AccountConfig = AccountBaseConfig & {
|
|
4
|
+
/** Receives debug log information. If not set, no logging will be done. */
|
|
5
|
+
log?: LogFunction;
|
|
6
|
+
/** Callback triggered before a session refresh redirect happens. */
|
|
7
|
+
callbackBeforeRedirect?: IdentityBeforeRedirectCallback;
|
|
8
|
+
/** Optional Varnish cookie setup applied during Account initialization. */
|
|
9
|
+
varnish?: VarnishCookieOptions;
|
|
10
|
+
};
|
|
11
|
+
export type AccountSessionEventName = 'login' | 'logout' | 'userChange' | 'sessionChange' | 'notLoggedin' | 'sessionInit' | 'statusChange' | 'error' | 'simplifiedLoginOpened' | 'simplifiedLoginCancelled';
|
|
12
|
+
export type AccountEventName = AccountSessionEventName | 'hasAccess';
|
|
13
|
+
export type AccountEventHandler = (...args: unknown[]) => void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Log callback used by the SDK for debug output.
|
|
3
|
+
* Receives a pre-formatted log line.
|
|
4
|
+
* @internal
|
|
5
|
+
*/
|
|
6
|
+
export type LogFunction = (message: string) => void;
|
|
7
|
+
/**
|
|
8
|
+
* Supported Schibsted account environment keys.
|
|
9
|
+
*/
|
|
10
|
+
export type AccountEnvironment = 'LOCAL' | 'DEV' | 'PRE' | 'PRO' | 'PRO_NO' | 'PRO_FI' | 'PRO_DK';
|
|
11
|
+
export type AccountBaseConfig = {
|
|
12
|
+
/** Mandatory client id. Example: "1234567890abcdef12345678" */
|
|
13
|
+
clientId: string;
|
|
14
|
+
/** Redirect uri. Example: "https://site.com" */
|
|
15
|
+
redirectUri: string;
|
|
16
|
+
/** Session Service domain. Example: "https://id.site.com" */
|
|
17
|
+
sessionDomain: string;
|
|
18
|
+
/** Schibsted account environment. Defaults to PRE. */
|
|
19
|
+
env?: AccountEnvironment;
|
|
20
|
+
/** Window object to use. Defaults to the global `window`. */
|
|
21
|
+
window?: Window;
|
|
22
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AccountBaseConfig, LogFunction } from './common';
|
|
2
|
+
/**
|
|
3
|
+
* Callback invoked before the SDK performs a full-page session refresh redirect.
|
|
4
|
+
*/
|
|
5
|
+
export type IdentityBeforeRedirectCallback = () => void | Promise<void>;
|
|
6
|
+
/**
|
|
7
|
+
* Options accepted by the {@link Identity} constructor.
|
|
8
|
+
*/
|
|
9
|
+
export type IdentityOptions = AccountBaseConfig & {
|
|
10
|
+
/** Receives debug log information. If not set, no logging will be done. */
|
|
11
|
+
log?: LogFunction;
|
|
12
|
+
/** Callback triggered before a session refresh redirect happens. */
|
|
13
|
+
callbackBeforeRedirect?: IdentityBeforeRedirectCallback;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Identity events emitted by the SDK.
|
|
17
|
+
*
|
|
18
|
+
* - `login`: emitted when `hasSession()` resolves with a logged-in user payload.
|
|
19
|
+
* - `logout`: emitted when a previously logged-in user is no longer logged in, or when
|
|
20
|
+
* `logout()` is called.
|
|
21
|
+
* - `userChange`: emitted when the current session user id changes.
|
|
22
|
+
* - `sessionChange`: emitted when either the previous or current `hasSession()` payload contains
|
|
23
|
+
* a logged-in user.
|
|
24
|
+
* - `notLoggedin`: emitted when neither the previous nor current `hasSession()` payload contains
|
|
25
|
+
* a logged-in user.
|
|
26
|
+
* - `sessionInit`: emitted once for the first logged-in session payload.
|
|
27
|
+
* - `statusChange`: emitted when the session `userStatus` changes.
|
|
28
|
+
* - `error`: emitted when `hasSession()` fails.
|
|
29
|
+
* - `simplifiedLoginOpened`: emitted when the simplified login widget is displayed.
|
|
30
|
+
* - `simplifiedLoginCancelled`: emitted when the simplified login widget is closed.
|
|
31
|
+
*/
|
|
32
|
+
export type IdentityEventName = 'login' | 'logout' | 'userChange' | 'sessionChange' | 'notLoggedin' | 'sessionInit' | 'statusChange' | 'error' | 'simplifiedLoginOpened' | 'simplifiedLoginCancelled';
|
|
33
|
+
/**
|
|
34
|
+
* Options for {@link Identity#enableVarnishCookie}.
|
|
35
|
+
*/
|
|
36
|
+
export type VarnishCookieOptions = {
|
|
37
|
+
/** Override number of seconds before the Varnish cookie expires. */
|
|
38
|
+
expiresIn?: number;
|
|
39
|
+
/** Override cookie domain. E.g. "vg.no" instead of "www.vg.no". */
|
|
40
|
+
domain?: string;
|
|
41
|
+
};
|