@schibsted/account-sdk-browser 6.0.0-alpha.3 → 6.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,36 +0,0 @@
1
- import { ConnectedSessionResponse, ConnectedSessionWithUserIdResponse, SessionFailureResponse, SessionResponse, SessionSuccessResponse, UnrecognizedSessionResponse } from './session.js';
2
- type SessionObjectResponse = SessionSuccessResponse | SessionFailureResponse | UnrecognizedSessionResponse;
3
- type RedirectSessionPayload = {
4
- redirectURL: string;
5
- };
6
- export type NormalizedSessionPayload = SessionObjectResponse | RedirectSessionPayload;
7
- export declare function isSessionSuccessResponse(value: unknown): value is SessionSuccessResponse;
8
- export declare function isConnectedSessionResponse(value: unknown): value is ConnectedSessionResponse;
9
- export declare function isSessionFailureResponse(value: unknown): value is SessionFailureResponse;
10
- export declare function isRedirectSessionPayload(value: unknown): value is RedirectSessionPayload;
11
- export declare function isConnectedSessionWithUserIdResponse(value: SessionResponse): value is ConnectedSessionWithUserIdResponse;
12
- /**
13
- * Converts an unknown Session Service `hasSession` payload into one of the shapes the SDK knows how
14
- * to handle.
15
- *
16
- * This function is intentionally tolerant because `hasSession()` historically resolved unknown
17
- * object payloads instead of rejecting them. The SDK relies on that behavior for backwards
18
- * compatibility with clients that check the raw response themselves.
19
- *
20
- * The normal cases are:
21
- * - regular success payloads with a boolean `result`;
22
- * - failure payloads wrapped as `{ error, response? }`;
23
- * - Safari/session-refresh redirect payloads shaped as `{ redirectURL }`.
24
- *
25
- * Any other object is preserved as an unrecognized response so callers can still receive it.
26
- * Non-object values are normalized to `{}`, matching the old "empty response" fallback used by
27
- * `hasSession()` and cached-session reads.
28
- *
29
- * This is used both for network responses parsed by `RESTClient` and for values restored from the
30
- * session cache, so the rest of the Identity flow can switch on typed guards instead of repeatedly
31
- * re-validating unknown data.
32
- *
33
- * @internal
34
- */
35
- export declare function normalizeSessionResponse(value: unknown): NormalizedSessionPayload;
36
- export {};
@@ -1,94 +0,0 @@
1
- /* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.
2
- * See LICENSE.md in the project root.
3
- */
4
-
5
- import { Account } from './account.js';
6
- import { resolveBrowserWindow } from './resolve-browser-window.js';
7
- import type { AccountConfig } from './types/account.js';
8
-
9
- const ACCOUNT_READY_EVENT = 'schAccount:ready';
10
- const GET_ACCOUNT_SDK_TIMEOUT_MS = 4000;
11
- const IGNORED_CONFIG_WARNING =
12
- 'Schibsted Account SDK has already been initialized. The config passed to getAccountSdk() was ignored.';
13
-
14
- let pendingAccountPromise: Promise<Account> | undefined;
15
- let ignoredConfigWarningSent = false;
16
-
17
- const createUnavailableError = (): Error =>
18
- new Error('Schibsted Account SDK is not available in this browser context');
19
-
20
- const createTimeoutError = (): Error =>
21
- new Error(`Schibsted Account SDK was not initialized within ${GET_ACCOUNT_SDK_TIMEOUT_MS} ms`);
22
-
23
- const warnIgnoredConfigOnce = (): void => {
24
- if (ignoredConfigWarningSent) {
25
- return;
26
- }
27
-
28
- console.warn(IGNORED_CONFIG_WARNING);
29
- ignoredConfigWarningSent = true;
30
- };
31
-
32
- export function getAccountSdk(config?: AccountConfig): Promise<Account> {
33
- const browserWindow = resolveBrowserWindow(config?.window);
34
-
35
- if (!browserWindow) {
36
- const error = createUnavailableError();
37
- console.error(error.message);
38
- return Promise.reject(error);
39
- }
40
-
41
- if (browserWindow.schAccount) {
42
- if (config) {
43
- warnIgnoredConfigOnce();
44
- }
45
-
46
- return Promise.resolve(browserWindow.schAccount);
47
- }
48
-
49
- if (config) {
50
- return Promise.resolve(new Account(config));
51
- }
52
-
53
- if (pendingAccountPromise) {
54
- return pendingAccountPromise;
55
- }
56
-
57
- pendingAccountPromise = new Promise<Account>((resolve, reject) => {
58
- let timeoutId: number | undefined;
59
-
60
- const cleanup = () => {
61
- browserWindow.removeEventListener(ACCOUNT_READY_EVENT, handleReady);
62
- if (timeoutId !== undefined) {
63
- browserWindow.clearTimeout(timeoutId);
64
- }
65
- pendingAccountPromise = undefined;
66
- };
67
-
68
- const resolveRegisteredAccount = () => {
69
- const account = browserWindow.schAccount;
70
- if (!account) {
71
- return;
72
- }
73
-
74
- cleanup();
75
- resolve(account);
76
- };
77
-
78
- const handleReady = () => {
79
- resolveRegisteredAccount();
80
- };
81
-
82
- browserWindow.addEventListener(ACCOUNT_READY_EVENT, handleReady);
83
- timeoutId = browserWindow.setTimeout(() => {
84
- const error = createTimeoutError();
85
- console.error(error.message);
86
- cleanup();
87
- reject(error);
88
- }, GET_ACCOUNT_SDK_TIMEOUT_MS);
89
-
90
- resolveRegisteredAccount();
91
- });
92
-
93
- return pendingAccountPromise;
94
- }
@@ -1,39 +0,0 @@
1
- import './globals.js';
2
-
3
- /**
4
- * Names of the SDK instance properties that can be registered on the global {@link Window} object.
5
- */
6
- type Property = 'schAccount' | 'schIdentity' | 'schMonetization';
7
-
8
- /**
9
- * Registers an SDK instance on the global {@link Window} object's given property and dispatches a ready event.
10
- *
11
- * The dispatched event is a {@link CustomEvent} fired on `global` (i.e. `window`) with:
12
- * - name: `${property}:ready` (e.g. `"schIdentity:ready"` or `"schMonetization:ready"`)
13
- * - `detail.instance`: the registered SDK instance
14
- *
15
- * @typeParam T - Constrained to {@link Property}; inferred from the `property` argument.
16
- * @param global - The `Window` object to register on.
17
- * @param property - The window property name to assign the instance to, 'schIdentity' or 'schMonetization'.
18
- * @param instance - The SDK instance to register. Must be non-nullable.
19
- *
20
- * @example
21
- * registerAndDispatchInGlobal(window, 'schIdentity', identityInstance);
22
- * / window.schIdentity === identityInstance
23
- * / CustomEvent 'schIdentity:ready' has been dispatched on window
24
- */
25
-
26
- export const registerAndDispatchInGlobal = <T extends Property>(
27
- global: Window,
28
- property: T,
29
- instance: NonNullable<Window[T]>,
30
- ): void => {
31
- if (!global[property]) {
32
- global[property] = instance;
33
- }
34
-
35
- global.dispatchEvent(
36
- //TODO -> https://schibsted.ghe.com/connect/team/issues/645
37
- new CustomEvent(`${property}:ready`, { detail: { instance: global[property] } }),
38
- );
39
- };
@@ -1,35 +0,0 @@
1
- /* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.
2
- * See LICENSE.md in the project root.
3
- */
4
-
5
- import SDKError from '../sdk-error.js';
6
- import { isObject, isStr } from '../validate.js';
7
- import type { HasAccessResult } from './monetization.js';
8
-
9
- export function parseHasAccessResult(value: unknown): HasAccessResult {
10
- if (!isObject(value)) {
11
- throw new SDKError('Invalid hasAccess response');
12
- }
13
-
14
- const { entitled, ttl, allowedFeatures, userId, uuid, sig } = value;
15
-
16
- if (
17
- typeof entitled !== 'boolean' ||
18
- typeof ttl !== 'number' ||
19
- !Array.isArray(allowedFeatures) ||
20
- (typeof userId !== 'number' && typeof userId !== 'string') ||
21
- !isStr(uuid) ||
22
- !isStr(sig)
23
- ) {
24
- throw new SDKError('Invalid hasAccess response');
25
- }
26
-
27
- return {
28
- entitled,
29
- ttl,
30
- allowedFeatures: allowedFeatures.filter(isStr),
31
- userId,
32
- uuid,
33
- sig,
34
- };
35
- }
@@ -1,89 +0,0 @@
1
- /* Copyright 2026 Schibsted Products & Technology AS. Licensed under the terms of the MIT license.
2
- * See LICENSE.md in the project root.
3
- */
4
-
5
- import { isObject, isStr } from '../validate.js';
6
- import type {
7
- ConnectedSessionResponse,
8
- ConnectedSessionWithUserIdResponse,
9
- SessionFailureResponse,
10
- SessionResponse,
11
- SessionSuccessResponse,
12
- UnrecognizedSessionResponse,
13
- } from './session.js';
14
-
15
- type SessionObjectResponse =
16
- | SessionSuccessResponse
17
- | SessionFailureResponse
18
- | UnrecognizedSessionResponse;
19
-
20
- type RedirectSessionPayload = {
21
- redirectURL: string;
22
- };
23
-
24
- export type NormalizedSessionPayload = SessionObjectResponse | RedirectSessionPayload;
25
-
26
- export function isSessionSuccessResponse(value: unknown): value is SessionSuccessResponse {
27
- return isObject(value) && typeof value.result === 'boolean';
28
- }
29
-
30
- export function isConnectedSessionResponse(value: unknown): value is ConnectedSessionResponse {
31
- return isSessionSuccessResponse(value) && value.result === true;
32
- }
33
-
34
- export function isSessionFailureResponse(value: unknown): value is SessionFailureResponse {
35
- return isObject(value) && Boolean(value.error);
36
- }
37
-
38
- export function isRedirectSessionPayload(value: unknown): value is RedirectSessionPayload {
39
- return isObject(value) && Object.keys(value).length === 1 && isStr(value.redirectURL);
40
- }
41
-
42
- export function isConnectedSessionWithUserIdResponse(
43
- value: SessionResponse,
44
- ): value is ConnectedSessionWithUserIdResponse {
45
- return (
46
- isConnectedSessionResponse(value) &&
47
- (typeof value.userId === 'number' || typeof value.userId === 'string')
48
- );
49
- }
50
-
51
- /**
52
- * Converts an unknown Session Service `hasSession` payload into one of the shapes the SDK knows how
53
- * to handle.
54
- *
55
- * This function is intentionally tolerant because `hasSession()` historically resolved unknown
56
- * object payloads instead of rejecting them. The SDK relies on that behavior for backwards
57
- * compatibility with clients that check the raw response themselves.
58
- *
59
- * The normal cases are:
60
- * - regular success payloads with a boolean `result`;
61
- * - failure payloads wrapped as `{ error, response? }`;
62
- * - Safari/session-refresh redirect payloads shaped as `{ redirectURL }`.
63
- *
64
- * Any other object is preserved as an unrecognized response so callers can still receive it.
65
- * Non-object values are normalized to `{}`, matching the old "empty response" fallback used by
66
- * `hasSession()` and cached-session reads.
67
- *
68
- * This is used both for network responses parsed by `RESTClient` and for values restored from the
69
- * session cache, so the rest of the Identity flow can switch on typed guards instead of repeatedly
70
- * re-validating unknown data.
71
- *
72
- * @internal
73
- */
74
- export function normalizeSessionResponse(value: unknown): NormalizedSessionPayload {
75
- if (isRedirectSessionPayload(value)) {
76
- return value;
77
- }
78
- if (isSessionFailureResponse(value)) {
79
- return value;
80
- }
81
- if (isSessionSuccessResponse(value)) {
82
- return value;
83
- }
84
- if (isObject(value)) {
85
- return value;
86
- }
87
-
88
- return {};
89
- }