@schibsted/account-sdk-browser 6.0.0-alpha.2 → 6.0.0-alpha.4

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.
Files changed (60) hide show
  1. package/README.md +39 -39
  2. package/dist/account-sdk.d.ts +4 -0
  3. package/dist/account.d.ts +30 -0
  4. package/dist/global-registry.d.ts +1 -1
  5. package/dist/globals.d.ts +2 -0
  6. package/dist/has-access-response.d.ts +2 -0
  7. package/dist/identity.d.ts +37 -237
  8. package/dist/index.d.ts +8 -3
  9. package/dist/index.js +862 -4
  10. package/dist/index.js.map +1 -0
  11. package/dist/monetization.d.ts +7 -43
  12. package/dist/resolve-browser-window.d.ts +1 -0
  13. package/dist/{RESTClient.d.ts → rest-client.d.ts} +22 -11
  14. package/dist/rest-clients.d.ts +10 -0
  15. package/dist/session-response.d.ts +30 -0
  16. package/dist/types/account.d.ts +13 -0
  17. package/dist/types/common.d.ts +22 -0
  18. package/dist/types/identity.d.ts +41 -0
  19. package/dist/types/login.d.ts +120 -0
  20. package/dist/types/monetization-guards.d.ts +2 -0
  21. package/dist/types/monetization.d.ts +21 -0
  22. package/dist/types/session-guards.d.ts +36 -0
  23. package/dist/types/session.d.ts +124 -0
  24. package/dist/version.d.ts +1 -1
  25. package/package.json +1 -9
  26. package/src/account-sdk.ts +74 -0
  27. package/src/account.ts +153 -0
  28. package/src/cache.ts +1 -1
  29. package/src/global-registry.ts +1 -1
  30. package/src/globals.ts +2 -0
  31. package/src/has-access-response.ts +35 -0
  32. package/src/identity.ts +269 -423
  33. package/src/index.ts +28 -3
  34. package/src/monetization.ts +31 -68
  35. package/src/object.ts +1 -1
  36. package/src/resolve-browser-window.ts +11 -0
  37. package/src/{RESTClient.ts → rest-client.ts} +55 -28
  38. package/src/rest-clients.ts +30 -0
  39. package/src/session-response.ts +79 -0
  40. package/src/types/account.ts +27 -0
  41. package/src/types/common.ts +26 -0
  42. package/src/types/identity.ts +55 -0
  43. package/src/types/login.ts +145 -0
  44. package/src/types/monetization-guards.ts +35 -0
  45. package/src/types/monetization.ts +24 -0
  46. package/src/types/session-guards.ts +89 -0
  47. package/src/types/session.ts +147 -0
  48. package/src/validate.ts +1 -1
  49. package/src/version.ts +1 -1
  50. package/dist/identity-s4nofYmB.js +0 -370
  51. package/dist/identity-s4nofYmB.js.map +0 -1
  52. package/dist/identity.js +0 -2
  53. package/dist/monetization.js +0 -72
  54. package/dist/monetization.js.map +0 -1
  55. package/dist/version-spE-k97g.js +0 -289
  56. package/dist/version-spE-k97g.js.map +0 -1
  57. /package/dist/{SDKError.d.ts → sdk-error.d.ts} +0 -0
  58. /package/dist/{spidTalk.d.ts → spid-talk.d.ts} +0 -0
  59. /package/src/{SDKError.ts → sdk-error.ts} +0 -0
  60. /package/src/{spidTalk.ts → spid-talk.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,4 +1,862 @@
1
- import { v as e } from "./version-spE-k97g.js";
2
- import { t } from "./identity-s4nofYmB.js";
3
- import { Monetization as n } from "./monetization.js";
4
- export { t as Identity, n as Monetization, e as SDKError };
1
+ //#region \0rolldown/runtime.js
2
+ var e = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), t = (e, t, n) => {
3
+ e[t] || (e[t] = n), e.dispatchEvent(new CustomEvent(`${t}:ready`, { detail: { instance: e[t] } }));
4
+ }, n = (/* @__PURE__ */ e(((e, t) => {
5
+ function n() {}
6
+ n.prototype = {
7
+ on: function(e, t, n) {
8
+ var r = this.e ||= {};
9
+ return (r[e] || (r[e] = [])).push({
10
+ fn: t,
11
+ ctx: n
12
+ }), this;
13
+ },
14
+ once: function(e, t, n) {
15
+ var r = this;
16
+ function i() {
17
+ r.off(e, i), t.apply(n, arguments);
18
+ }
19
+ return i._ = t, this.on(e, i, n);
20
+ },
21
+ emit: function(e) {
22
+ for (var t = [].slice.call(arguments, 1), n = ((this.e ||= {})[e] || []).slice(), r = 0, i = n.length; r < i; r++) n[r].fn.apply(n[r].ctx, t);
23
+ return this;
24
+ },
25
+ off: function(e, t) {
26
+ var n = this.e ||= {}, r = n[e], i = [];
27
+ if (r && t) for (var a = 0, o = r.length; a < o; a++) r[a].fn !== t && r[a].fn._ !== t && i.push(r[a]);
28
+ return i.length ? n[e] = i : delete n[e], this;
29
+ }
30
+ }, t.exports = n, t.exports.TinyEmitter = n;
31
+ })))(), r = [
32
+ "boolean",
33
+ "number",
34
+ "string"
35
+ ], i = class extends Error {
36
+ code;
37
+ constructor(e, t) {
38
+ if (super(e), this.name = "SDKError", t) try {
39
+ Object.assign(this, t);
40
+ } catch {}
41
+ }
42
+ toString() {
43
+ let e = `${this.name}: ${this.message}`, t = Object.keys(this).filter((e) => e !== "name" && r.includes(typeof this[e])).map((e) => ` ${e}: ${this[e]}`).join("\n");
44
+ return t ? `${e}\n${t}` : e;
45
+ }
46
+ };
47
+ //#endregion
48
+ //#region src/cache.ts
49
+ function a(e) {
50
+ if (!e) return !1;
51
+ try {
52
+ let t = e(), n = "x-x-x-x".replace(/x/g, () => String(Math.random())), r = "TEST-VALUE";
53
+ t.setItem(n, r);
54
+ let i = t.getItem(n);
55
+ return t.removeItem(n), i === r;
56
+ } catch {
57
+ return !1;
58
+ }
59
+ }
60
+ var o = class {
61
+ store;
62
+ get;
63
+ set;
64
+ delete;
65
+ constructor(e) {
66
+ this.store = e, this.get = (e) => this.store.getItem(e), this.set = (e, t) => this.store.setItem(e, t), this.delete = (e) => this.store.removeItem(e);
67
+ }
68
+ }, s = class {
69
+ store;
70
+ get;
71
+ set;
72
+ delete;
73
+ constructor() {
74
+ this.store = {}, this.get = (e) => this.store[e], this.set = (e, t) => {
75
+ this.store[e] = t;
76
+ }, this.delete = (e) => {
77
+ delete this.store[e];
78
+ };
79
+ }
80
+ }, c = 2 ** 31 - 1, l = class {
81
+ cache;
82
+ type;
83
+ constructor(e) {
84
+ e && a(e) ? (this.cache = new o(e()), this.type = "WebStorage") : (this.cache = new s(), this.type = "ObjectLiteralStorage");
85
+ }
86
+ get(e) {
87
+ function t(e) {
88
+ if (e == null) return null;
89
+ try {
90
+ return JSON.parse(e);
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ try {
96
+ let n = t(this.cache.get(e));
97
+ return n && Number.isInteger(n.expiresOn) && n.expiresOn > Date.now() ? n.value : (this.delete(e), null);
98
+ } catch (e) {
99
+ throw new i(String(e));
100
+ }
101
+ }
102
+ set(e, t, n = 0) {
103
+ if (!(n <= 0)) {
104
+ n = Math.min(c, n);
105
+ try {
106
+ let r = Math.floor(Date.now() + n);
107
+ this.cache.set(e, JSON.stringify({
108
+ expiresOn: r,
109
+ value: t
110
+ })), setTimeout(() => this.delete(e), n);
111
+ } catch (e) {
112
+ throw new i(String(e));
113
+ }
114
+ }
115
+ }
116
+ delete(e) {
117
+ try {
118
+ this.cache.delete(e);
119
+ } catch (e) {
120
+ throw new i(String(e));
121
+ }
122
+ }
123
+ }, u = {
124
+ ENDPOINTS: {
125
+ SPiD: {
126
+ LOCAL: "http://id.localhost",
127
+ DEV: "https://identity-dev.schibsted.com",
128
+ PRE: "https://identity-pre.schibsted.com",
129
+ PRO: "https://login.schibsted.com",
130
+ PRO_NO: "https://payment.schibsted.no",
131
+ PRO_FI: "https://login.schibsted.fi",
132
+ PRO_DK: "https://login.schibsted.dk"
133
+ },
134
+ BFF: {
135
+ LOCAL: "http://id.localhost/authn/",
136
+ DEV: "https://identity-dev.schibsted.com/authn/",
137
+ PRE: "https://identity-pre.schibsted.com/authn/",
138
+ PRO: "https://login.schibsted.com/authn/",
139
+ PRO_NO: "https://payment.schibsted.no/authn/",
140
+ PRO_FI: "https://login.schibsted.fi/authn/",
141
+ PRO_DK: "https://login.schibsted.dk/authn/"
142
+ },
143
+ SESSION_SERVICE: {
144
+ LOCAL: "http://session-service.id.localhost",
145
+ DEV: "https://session-service.identity-dev.schibsted.com",
146
+ PRE: "https://session-service.identity-pre.schibsted.com",
147
+ PRO: "https://session-service.login.schibsted.com",
148
+ PRO_NO: "https://session-service.payment.schibsted.no",
149
+ PRO_FI: "https://session-service.login.schibsted.fi",
150
+ PRO_DK: "https://session-service.login.schibsted.dk"
151
+ }
152
+ },
153
+ NAMESPACE: {
154
+ LOCAL: "id.localhost",
155
+ DEV: "schibsted.com",
156
+ PRE: "schibsted.com",
157
+ PRO: "schibsted.com",
158
+ PRO_NO: "spid.no",
159
+ PRO_FI: "schibsted.fi",
160
+ PRO_DK: "schibsted.dk"
161
+ }
162
+ }, d = u.ENDPOINTS, f = u.NAMESPACE;
163
+ //#endregion
164
+ //#region src/validate.ts
165
+ function p(e, t = "Assertion failed") {
166
+ if (!e) throw new i(t);
167
+ }
168
+ function m(e) {
169
+ return typeof e == "string";
170
+ }
171
+ function h(e) {
172
+ return typeof e == "string" && e.length > 0;
173
+ }
174
+ function g(e) {
175
+ return typeof e == "object" && !!e;
176
+ }
177
+ function _(e) {
178
+ return g(e) && Object.keys(e).length > 0;
179
+ }
180
+ function v(e, ...t) {
181
+ try {
182
+ let n = new URL(e);
183
+ return t.every((e) => n[e]);
184
+ } catch {
185
+ return !1;
186
+ }
187
+ }
188
+ function y(e) {
189
+ return typeof e == "function";
190
+ }
191
+ function b(e, t, n = !1) {
192
+ return m(e) && Array.isArray(t) ? n ? t.indexOf(e) !== -1 : t.some((t) => m(t) && e.toUpperCase() === t.toUpperCase()) : !1;
193
+ }
194
+ //#endregion
195
+ //#region src/object.ts
196
+ function x(...e) {
197
+ let t = {};
198
+ if (!(e && e.length)) throw new i("No objects to clone");
199
+ return e.forEach((e) => {
200
+ p(g(e)), _(e) && Object.entries(e).forEach(([e, n]) => {
201
+ n !== void 0 && (t[e] = g(n) ? S(n) : n);
202
+ });
203
+ }), t;
204
+ }
205
+ function S(e) {
206
+ return p(typeof e == "object", `obj should be an object (even null) but it is ${e}`), JSON.parse(JSON.stringify(e)) || e;
207
+ }
208
+ //#endregion
209
+ //#region src/popup.ts
210
+ function ee(e) {
211
+ return p(g(e), `Object must be an object but it is '${e}'`), Object.keys(e).map((t) => `${t}=${e[t]}`).join(",");
212
+ }
213
+ var te = {
214
+ scrollbars: "yes",
215
+ location: "yes",
216
+ status: "no",
217
+ menubar: "no",
218
+ toolbar: "no",
219
+ resizable: "yes"
220
+ };
221
+ function ne(e, t, n = "", r = {}) {
222
+ p(g(e), `window was supposed to be an object but it is ${e}`), p(g(e.screen), "window should be a valid Window object but it lacks a 'screen' property"), p(y(e.open), "window should be a valid Window object but it lacks an 'open' function"), p(v(t), "Invalid URL for popup");
223
+ let { height: i, width: a } = e.screen, o = x(te, r), { width: s, height: c } = o;
224
+ typeof s == "number" && Number.isFinite(s) && Number.isFinite(a) && (o.left = (a - s) / 2), typeof c == "number" && Number.isFinite(c) && Number.isFinite(i) && (o.top = (i - c) / 2);
225
+ let l = ee(o);
226
+ return e.open(t, n, l);
227
+ }
228
+ //#endregion
229
+ //#region src/url.ts
230
+ function C(e, t) {
231
+ return p(h(e), `"url" param must be a non empty string: ${typeof e}`), _(t) && v(t[e]) ? t[e] : (p(v(e, "hostname"), `Bad URL given: '${e}'`), e);
232
+ }
233
+ //#endregion
234
+ //#region src/rest-client.ts
235
+ var w = (e) => e.map((e) => g(e) ? JSON.stringify(e, null, 2) : e).join(" "), T = (e, ...t) => {
236
+ e && e(w(t));
237
+ };
238
+ function E(e) {
239
+ let t = {
240
+ "!": "%21",
241
+ "'": "%27",
242
+ "(": "%28",
243
+ ")": "%29",
244
+ "~": "%7E",
245
+ "%20": "+",
246
+ "%00": "\0"
247
+ };
248
+ return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g, (e) => t[e]);
249
+ }
250
+ var re = () => window.fetch && window.fetch.bind(window), ie = () => {
251
+ throw new i("fetch is not available in this environment");
252
+ }, D = class e {
253
+ url;
254
+ defaultParams;
255
+ log;
256
+ fetch;
257
+ constructor({ serverUrl: e = "PRE", envDic: t, fetch: n = re() ?? ie, log: r, defaultParams: i = {} }) {
258
+ p(g(i), "defaultParams should be a non-null object");
259
+ let a = C(e, t ?? {}), o = a.endsWith("/") ? a : `${a}/`;
260
+ this.url = new URL(o), this.defaultParams = i, r && (p(y(r), `log must be a function but it is ${r}`), this.log = r), this.fetch = n;
261
+ }
262
+ async go(e) {
263
+ let { method: t, headers: n, pathname: r, data: a = {}, useDefaultParams: o = !0, fetchOptions: s = {
264
+ method: e.method,
265
+ credentials: "include"
266
+ }, parseResponse: c } = e;
267
+ p(h(t), `Method must be a non empty string but it is "${t}"`), p(h(r), `Pathname must be string but it is "${r}"`), p(g(a), "data must be a non-null object"), s.headers = g(n) ? n : {};
268
+ let l = this.makeUrl(r, a, o);
269
+ T(this.log, "Request:", t.toUpperCase(), l), T(this.log, "Request Headers:", s.headers), T(this.log, "Request Body:", s.body);
270
+ try {
271
+ let e = await this.fetch(l, s);
272
+ if (T(this.log, "Response Code:", e.status, e.statusText), !e.ok) throw new i(e.statusText, { code: e.status });
273
+ let t = await e.json();
274
+ return T(this.log, "Response Parsed:", t), c ? c(t) : t;
275
+ } catch (e) {
276
+ let n = m(e) ? e : "Unknown RESTClient error";
277
+ g(e) && m(e.message) && (n = e.message);
278
+ let r = g(e) ? e : void 0;
279
+ throw new i(`Failed to '${t}' '${l}': '${n}'`, r);
280
+ }
281
+ }
282
+ makeUrl(t = "", n = {}, r = !0) {
283
+ let i = t.startsWith("/") ? t.slice(1) : t, a = new URL(i, this.url);
284
+ return a.search = e.search(n, r, this.defaultParams), a.href;
285
+ }
286
+ get(e, t, n) {
287
+ return n ? this.go({
288
+ method: "GET",
289
+ pathname: e,
290
+ data: t,
291
+ parseResponse: n
292
+ }) : this.go({
293
+ method: "GET",
294
+ pathname: e,
295
+ data: t
296
+ });
297
+ }
298
+ static search(e, t, n) {
299
+ let r = t ? x(n, e) : x(e);
300
+ return Object.keys(r).filter((e) => r[e] !== "").map((e) => `${E(e)}=${E(String(r[e]))}`).join("&");
301
+ }
302
+ }, O = (e) => Object.hasOwn(f, e), k = (e, t) => (p(h(t), "clientId parameter is required"), p(O(e), `env parameter is invalid: ${e}`), `sdrn:${f[e]}:client:${t}`), A = ({ serverUrl: e, log: t, defaultParams: n }) => new D({
303
+ serverUrl: e,
304
+ log: t,
305
+ defaultParams: n
306
+ });
307
+ //#endregion
308
+ //#region src/session-response.ts
309
+ function j(e) {
310
+ return g(e) && typeof e.result == "boolean";
311
+ }
312
+ function M(e) {
313
+ return j(e) && e.result === !0;
314
+ }
315
+ function N(e) {
316
+ return g(e) && !!e.error;
317
+ }
318
+ function P(e) {
319
+ return g(e) && Object.keys(e).length === 1 && m(e.redirectURL);
320
+ }
321
+ function F(e) {
322
+ return M(e) && (typeof e.userId == "number" || typeof e.userId == "string");
323
+ }
324
+ function I(e) {
325
+ return P(e) || N(e) || j(e) || g(e) ? e : {};
326
+ }
327
+ //#endregion
328
+ //#region src/spid-talk.ts
329
+ function L(e) {
330
+ (!e.SPiD || typeof e.SPiD != "object") && (e.SPiD = {}), (!e.SPiD.Talk || typeof e.SPiD.Talk != "object") && (e.SPiD.Talk = {}), y(e.SPiD.Talk.response) || (e.SPiD.Talk.response = (t, n) => e[t](n));
331
+ }
332
+ //#endregion
333
+ //#region src/types/login.ts
334
+ var R = (e) => typeof e.openSimplifiedLoginWidget == "function", z = "6.0.0-alpha.4", B = "hasSession-cache", V = "sessionCallBlocked-cache", H = 1e3 * 60 * 5, U = "tab-id-cache", W = Math.floor(Math.random() * 1e5), G = 1e3 * 60 * 60 * 24 * 30, K = () => window, q = class extends n.TinyEmitter {
335
+ _sessionInitiatedSent;
336
+ window;
337
+ clientId;
338
+ sessionStorageCache;
339
+ localStorageCache;
340
+ redirectUri;
341
+ env;
342
+ log;
343
+ callbackBeforeRedirect;
344
+ _sessionDomain;
345
+ _enableSessionCaching;
346
+ _session;
347
+ _spid;
348
+ _oauthService;
349
+ _bffService;
350
+ _sessionService;
351
+ _globalSessionService;
352
+ _usedSessionServiceGetSessionEndpoint;
353
+ _hasSessionInProgress;
354
+ popup;
355
+ setVarnishCookie;
356
+ varnishExpiresIn;
357
+ varnishCookieDomain;
358
+ constructor({ clientId: e, redirectUri: n, sessionDomain: r, env: i = "PRE", log: a, window: o = K(), callbackBeforeRedirect: s = () => {} }) {
359
+ super(), p(h(e), "clientId parameter is required"), p(g(o), "The reference to window is missing"), p(!n || v(n), "redirectUri parameter is invalid"), p(h(r) && v(r), "sessionDomain parameter is not a valid URL"), p(m(i), `env parameter is invalid: ${i}`), L(o), this._sessionInitiatedSent = !1, this.window = o, this.clientId = e, this.sessionStorageCache = new l(() => this.window && this.window.sessionStorage), this.localStorageCache = new l(() => this.window && this.window.localStorage), this.redirectUri = n, this.env = i, this.log = a, this.callbackBeforeRedirect = s, this._sessionDomain = r, this._enableSessionCaching = !0, this._session = {};
360
+ let c = {
361
+ client_id: this.clientId,
362
+ redirect_uri: this.redirectUri
363
+ }, u = k(this.env, this.clientId);
364
+ this._sessionService = A({
365
+ serverUrl: r,
366
+ log: this.log,
367
+ defaultParams: {
368
+ client_sdrn: u,
369
+ redirect_uri: this.redirectUri,
370
+ sdk_version: z
371
+ }
372
+ }), this._usedSessionServiceGetSessionEndpoint = this._sessionService.url.pathname && this._sessionService.url.pathname.length <= 1 ? "v2/session" : "session", this._spid = A({
373
+ serverUrl: C(i, d.SPiD),
374
+ log: this.log,
375
+ defaultParams: c
376
+ }), this._bffService = A({
377
+ serverUrl: C(i, d.BFF),
378
+ log: this.log,
379
+ defaultParams: c
380
+ }), this._oauthService = A({
381
+ serverUrl: C(i, d.SPiD),
382
+ log: this.log,
383
+ defaultParams: c
384
+ }), this._globalSessionService = A({
385
+ serverUrl: C(i, d.SESSION_SERVICE),
386
+ log: this.log,
387
+ defaultParams: {
388
+ client_sdrn: u,
389
+ sdk_version: z
390
+ }
391
+ }), this._unblockSessionCall(), t(o, "schIdentity", this);
392
+ }
393
+ _getTabId() {
394
+ if (this._enableSessionCaching) {
395
+ let e = this.sessionStorageCache.get(U);
396
+ return typeof e == "number" ? e : (this.sessionStorageCache.set(U, W, G), W);
397
+ }
398
+ }
399
+ _isSessionCallBlocked() {
400
+ return !!this.localStorageCache.get(V);
401
+ }
402
+ _blockSessionCall() {
403
+ this.localStorageCache.set(V, !0, H);
404
+ }
405
+ _unblockSessionCall() {
406
+ this.localStorageCache.delete(V);
407
+ }
408
+ _emitSessionEvent(e, t) {
409
+ let n = j(e) ? e.userId : void 0, r = j(t) ? t.userId : void 0, i = j(e) ? e.userStatus : void 0, a = j(t) ? t.userStatus : void 0;
410
+ r && this.emit("login", t), n && !r && this.emit("logout", t), n && r && n !== r && this.emit("userChange", t), n || r ? this.emit("sessionChange", t) : this.emit("notLoggedin", t), r && !this._sessionInitiatedSent && (this._sessionInitiatedSent = !0, this.emit("sessionInit", t)), i !== a && this.emit("statusChange", t);
411
+ }
412
+ _closePopup() {
413
+ this.popup &&= (this.popup.closed || this.popup.close(), null);
414
+ }
415
+ enableVarnishCookie(e) {
416
+ if (typeof e != "object") throw new i("VarnishCookieOptions must be an object");
417
+ let { expiresIn: t = 0, domain: n } = e;
418
+ p(Number.isInteger(t), "'expiresIn' must be an integer"), p(t >= 0, "'expiresIn' cannot be negative"), this.setVarnishCookie = !0, this.varnishExpiresIn = t, this.varnishCookieDomain = n;
419
+ }
420
+ _maybeSetVarnishCookie(e) {
421
+ if (!this.setVarnishCookie || !j(e)) return;
422
+ let t = /* @__PURE__ */ new Date();
423
+ if (this.varnishExpiresIn || typeof e.expiresIn == "number" && e.expiresIn > 0) {
424
+ let n = this.varnishExpiresIn || e.expiresIn || 0;
425
+ t.setTime(t.getTime() + n * 1e3);
426
+ } else t.setTime(0);
427
+ let n = this.varnishCookieDomain || (typeof e.baseDomain == "string" ? e.baseDomain : this.window.location.hostname) || "", r = [
428
+ `SP_ID=${e.sp_id}`,
429
+ `expires=${t.toUTCString()}`,
430
+ "path=/",
431
+ `domain=.${n}`
432
+ ].join("; ");
433
+ document.cookie = r;
434
+ }
435
+ _maybeClearVarnishCookie() {
436
+ this.setVarnishCookie && this._clearVarnishCookie();
437
+ }
438
+ _clearVarnishCookie() {
439
+ let e = this._session && j(this._session) && typeof this._session.baseDomain == "string" ? this._session.baseDomain : this.window.location.hostname, t = this.varnishCookieDomain || e || "";
440
+ document.cookie = `SP_ID=nothing; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=.${t}`;
441
+ }
442
+ logSettings() {
443
+ if (!this.log && !window.console) throw new i("You have to provide log method in constructor");
444
+ let e = this.log || console.log, t = {
445
+ clientId: this.clientId,
446
+ redirectUri: this.redirectUri,
447
+ env: this.env,
448
+ sessionDomain: this._sessionDomain,
449
+ sdkVersion: z
450
+ };
451
+ e(`Schibsted account SDK for browsers settings: \n${JSON.stringify(t, null, 2)}`);
452
+ }
453
+ hasSession() {
454
+ if (this._isSessionCallBlocked()) {
455
+ let e = I(this._session);
456
+ return Promise.resolve(P(e) ? {} : e);
457
+ }
458
+ if (this._hasSessionInProgress) return this._hasSessionInProgress;
459
+ let e = (e) => {
460
+ if (N(e)) throw new i("HasSession failed", g(e.error) ? e.error : { description: String(e.error) });
461
+ return this._maybeSetVarnishCookie(e), this._emitSessionEvent(this._session, e), this._session = e, e;
462
+ }, t = () => {
463
+ let e = this.sessionStorageCache.get(B);
464
+ return e ? I(e) : null;
465
+ }, n = async () => {
466
+ if (this._enableSessionCaching) {
467
+ let n = t();
468
+ if (n) return P(n) ? {} : e(n);
469
+ }
470
+ let n = null;
471
+ try {
472
+ n = await this._sessionService.get(this._usedSessionServiceGetSessionEndpoint, { tabId: this._getTabId() }, I);
473
+ } catch (e) {
474
+ let t = g(e) ? e : void 0;
475
+ if (t?.code === 400 && this._enableSessionCaching) {
476
+ let n = 1e3 * (typeof t.expiresIn == "number" ? t.expiresIn : 300);
477
+ this.sessionStorageCache.set(B, { error: e }, n);
478
+ } else t && typeof t.code == "number" && t.code >= 500 && t.code < 600 && this._enableSessionCaching && this.sessionStorageCache.set(B, { error: e }, 30 * 1e3);
479
+ throw e;
480
+ }
481
+ if (n) {
482
+ if (P(n)) return this._blockSessionCall(), await this.callbackBeforeRedirect(), this._sessionService.makeUrl(n.redirectURL, { tabId: this._getTabId() });
483
+ if (this._enableSessionCaching) {
484
+ let e = 1e3 * (j(n) && n.expiresIn || 300);
485
+ this.sessionStorageCache.set(B, n, e);
486
+ }
487
+ }
488
+ return e(n ?? {});
489
+ };
490
+ return this._hasSessionInProgress = n().then((e) => (this._hasSessionInProgress = !1, typeof e == "string" && (this.window.location.href = e), e), (e) => {
491
+ throw this.emit("error", e), this._hasSessionInProgress = !1, new i("HasSession failed", e);
492
+ }), this._hasSessionInProgress;
493
+ }
494
+ async isLoggedIn() {
495
+ try {
496
+ return j(await this.hasSession());
497
+ } catch {
498
+ return !1;
499
+ }
500
+ }
501
+ clearCachedUserSession() {
502
+ this.sessionStorageCache.delete(B);
503
+ }
504
+ async isConnected() {
505
+ try {
506
+ return M(await this.hasSession());
507
+ } catch {
508
+ return !1;
509
+ }
510
+ }
511
+ async getUser() {
512
+ let e = await this.hasSession();
513
+ if (!M(e)) throw new i("The user is not connected to this merchant");
514
+ return S(e);
515
+ }
516
+ async getUserId() {
517
+ let e = await this.hasSession();
518
+ if (F(e)) return String(e.userId);
519
+ throw new i("The user is not connected to this merchant");
520
+ }
521
+ async getExternalId(e, t = "") {
522
+ let n = await this.hasSession(), r = j(n) ? n.pairId : void 0;
523
+ if (!r) throw new i("pairId missing in user session!");
524
+ if (!e || e.length === 0) throw new i("externalParty cannot be empty");
525
+ let a = (e) => Array.from(new Uint8Array(e)).map((e) => e.toString(16).padStart(2, "0")).join(""), o = (e) => crypto.subtle.digest("SHA-256", e);
526
+ return (async (e) => o(new TextEncoder().encode(e)).then((e) => a(e)))(((e, t, n) => n ? `${e}:${t}:${n}` : `${e}:${t}`)(r, e, t));
527
+ }
528
+ async getUserSDRN() {
529
+ let e = await this.hasSession();
530
+ if (j(e) && e.sdrn) return e.sdrn;
531
+ throw new i("Failed to get SDRN from user session");
532
+ }
533
+ async getUserUuid() {
534
+ let e = await this.hasSession();
535
+ if (j(e) && e.uuid && e.result) return e.uuid;
536
+ throw new i("The user is not connected to this merchant");
537
+ }
538
+ async getUserContextData() {
539
+ try {
540
+ return await this._globalSessionService.get("user-context", void 0, (e) => g(e) && m(e.identifier) ? {
541
+ identifier: e.identifier,
542
+ display_text: m(e.display_text) ? e.display_text : "",
543
+ client_name: m(e.client_name) ? e.client_name : "",
544
+ provider_id: m(e.provider_id) ? e.provider_id : void 0
545
+ } : null);
546
+ } catch {
547
+ return null;
548
+ }
549
+ }
550
+ login({ state: e, acrValues: t, scope: n = "openid", redirectUri: r = this.redirectUri, preferPopup: i = !1, loginHint: a = "", tag: o = "", teaser: s = "", maxAge: c = "", locale: l, oneStepLogin: u = !1, prompt: d = "select_account", xDomainId: f = "", xEnvironmentId: p = "", originCampaign: m = "" }) {
551
+ this._closePopup(), this.sessionStorageCache.delete(B);
552
+ let h = this.loginUrl({
553
+ state: e,
554
+ acrValues: t,
555
+ scope: n,
556
+ redirectUri: r,
557
+ loginHint: a,
558
+ tag: o,
559
+ teaser: s,
560
+ maxAge: c,
561
+ locale: l,
562
+ oneStepLogin: u,
563
+ prompt: d,
564
+ xDomainId: f,
565
+ xEnvironmentId: p,
566
+ originCampaign: m
567
+ });
568
+ return i && (this.popup = ne(this.window, h, "Schibsted account", {
569
+ width: 360,
570
+ height: 570
571
+ }), this.popup) ? this.popup : (this.window.location.href = h, null);
572
+ }
573
+ async getSpId() {
574
+ try {
575
+ let e = await this.hasSession();
576
+ if (j(e)) return e.sp_id || null;
577
+ let t = g(e) && "sp_id" in e ? e.sp_id : void 0;
578
+ return m(t) ? t : null;
579
+ } catch {
580
+ return null;
581
+ }
582
+ }
583
+ logout(e = this.redirectUri) {
584
+ this.sessionStorageCache.delete(B), this._maybeClearVarnishCookie(), this.emit("logout"), this.window.location.href = this.logoutUrl(e);
585
+ }
586
+ loginUrl({ state: e, acrValues: t = "", scope: n = "openid", redirectUri: r = this.redirectUri, loginHint: i = "", tag: a = "", teaser: o = "", maxAge: s = "", locale: c, oneStepLogin: l = !1, prompt: u = "select_account", xDomainId: d = "", xEnvironmentId: f = "", originCampaign: m = "" }) {
587
+ return p(!t || b(t, ["", "otp-email"], !0) || t.split(" ").every((e) => b(e, [
588
+ "password",
589
+ "otp",
590
+ "sms",
591
+ "eid-dk",
592
+ "eid-no",
593
+ "eid-se",
594
+ "eid-fi",
595
+ "eid"
596
+ ], !0)), `The acrValues parameter is not acceptable: ${t}`), p(v(r), `loginUrl(): redirectUri must be a valid url but is ${r}`), p(h(e), `the state parameter should be a non empty string but it is ${e}`), this._oauthService.makeUrl("oauth/authorize", {
597
+ response_type: "code",
598
+ redirect_uri: r,
599
+ scope: n,
600
+ state: e,
601
+ acr_values: t,
602
+ login_hint: i,
603
+ tag: a,
604
+ teaser: o,
605
+ max_age: s,
606
+ locale: c,
607
+ one_step_login: l || "",
608
+ prompt: t ? "" : u,
609
+ x_domain_id: d,
610
+ x_env_id: f,
611
+ utm_campaign: m
612
+ });
613
+ }
614
+ logoutUrl(e = this.redirectUri) {
615
+ p(v(e), "logoutUrl(): redirectUri is invalid");
616
+ let t = { redirect_uri: e };
617
+ return this._sessionService.makeUrl("logout", t);
618
+ }
619
+ accountUrl(e = this.redirectUri) {
620
+ return this._spid.makeUrl("profile-pages", {
621
+ response_type: "code",
622
+ redirect_uri: e
623
+ });
624
+ }
625
+ phonesUrl(e = this.redirectUri) {
626
+ return this._spid.makeUrl("profile-pages/about-you/phone", {
627
+ response_type: "code",
628
+ redirect_uri: e
629
+ });
630
+ }
631
+ async showSimplifiedLoginWidget(e, t) {
632
+ let n = await this.getUserContextData(), r = { client_id: this.clientId };
633
+ t && t.encoding && (r.encoding = t.encoding);
634
+ let a = this._bffService.makeUrl("simplified-login-widget", r, !1), o = async (e) => {
635
+ let t = typeof e.state == "function" ? await e.state() : e.state;
636
+ return {
637
+ ...e,
638
+ state: t
639
+ };
640
+ };
641
+ return new Promise((r, s) => {
642
+ if (!n?.display_text || !n.identifier) {
643
+ s(new i("Missing user data"));
644
+ return;
645
+ }
646
+ let c = {
647
+ displayText: n.display_text,
648
+ env: this.env,
649
+ clientName: n.client_name || "",
650
+ clientId: this.clientId,
651
+ providerId: n.provider_id,
652
+ windowWidth: () => window.innerWidth,
653
+ windowOnResize: (e) => {
654
+ window.onresize = e;
655
+ }
656
+ };
657
+ t && t.locale && (c.locale = t.locale);
658
+ let l = async () => {
659
+ this.login(Object.assign(await o(e), { loginHint: n.identifier }));
660
+ }, u = async () => {
661
+ this.login(Object.assign(await o(e), {
662
+ loginHint: n.identifier,
663
+ prompt: "login"
664
+ }));
665
+ }, d = () => {
666
+ this.emit("simplifiedLoginOpened");
667
+ }, f = () => {
668
+ this.emit("simplifiedLoginCancelled");
669
+ };
670
+ if (R(window)) return window.openSimplifiedLoginWidget(c, l, u, d, f), r(!0);
671
+ let p = document.createElement("script");
672
+ p.type = "text/javascript", p.src = a, p.onload = () => {
673
+ if (!R(window)) {
674
+ s(new i("Error when loading simplified login widget content"));
675
+ return;
676
+ }
677
+ window.openSimplifiedLoginWidget(c, l, u, d, f), r(!0);
678
+ }, p.onerror = () => {
679
+ s(new i("Error when loading simplified login widget content"));
680
+ }, document.getElementsByTagName("body")[0].appendChild(p);
681
+ });
682
+ }
683
+ };
684
+ //#endregion
685
+ //#region src/has-access-response.ts
686
+ function J(e) {
687
+ if (!g(e)) throw new i("Invalid hasAccess response");
688
+ let { entitled: t, ttl: n, allowedFeatures: r, userId: a, uuid: o, sig: s } = e;
689
+ if (typeof t != "boolean" || typeof n != "number" || !Array.isArray(r) || typeof a != "number" && typeof a != "string" || !m(o) || !m(s)) throw new i("Invalid hasAccess response");
690
+ return {
691
+ entitled: t,
692
+ ttl: n,
693
+ allowedFeatures: r.filter(m),
694
+ userId: a,
695
+ uuid: o,
696
+ sig: s
697
+ };
698
+ }
699
+ //#endregion
700
+ //#region src/monetization.ts
701
+ var ae = () => window, oe = class extends n.TinyEmitter {
702
+ cache;
703
+ clientId;
704
+ env;
705
+ redirectUri;
706
+ _spid;
707
+ _sessionService;
708
+ pendingHasAccessRequests;
709
+ constructor({ clientId: e, redirectUri: n, env: r = "PRE", sessionDomain: i, window: a = ae() }) {
710
+ super(), L(a), p(h(e), "clientId parameter is required"), p(m(r), `env parameter is invalid: ${r}`), this.cache = new l(() => a && a.sessionStorage), this.clientId = e, this.env = r, this.redirectUri = n, this.pendingHasAccessRequests = {}, this._spid = A({
711
+ serverUrl: C(r, d.SPiD),
712
+ defaultParams: {
713
+ client_id: this.clientId,
714
+ redirect_uri: this.redirectUri
715
+ }
716
+ }), i && (p(v(i), "sessionDomain parameter is not a valid URL"), this._sessionService = A({
717
+ serverUrl: i,
718
+ defaultParams: {
719
+ client_sdrn: k(this.env, this.clientId),
720
+ redirect_uri: this.redirectUri,
721
+ sdk_version: z
722
+ }
723
+ })), t(a, "schMonetization", this);
724
+ }
725
+ async hasAccess(e, t) {
726
+ if (!this._sessionService) throw new i("hasAccess can only be called if 'sessionDomain' is configured");
727
+ if (!t) throw new i("'userId' must be specified");
728
+ if (!Array.isArray(e)) throw new i("'productIds' must be an array");
729
+ let n = [...e].sort(), r = this._accessCacheKey(n, t), a = this.cache.get(r);
730
+ if (!a) {
731
+ this.pendingHasAccessRequests[r] || (this.pendingHasAccessRequests[r] = this._sessionService.get(`/hasAccess/${n.join(",")}`, void 0, J));
732
+ let e = this.pendingHasAccessRequests[r];
733
+ try {
734
+ a = await e;
735
+ let t = a.ttl;
736
+ this.cache.set(r, a, t * 1e3);
737
+ } finally {
738
+ this.pendingHasAccessRequests[r] === e && delete this.pendingHasAccessRequests[r];
739
+ }
740
+ }
741
+ return a.entitled ? (this.emit("hasAccess", {
742
+ ids: n,
743
+ data: a
744
+ }), a) : null;
745
+ }
746
+ clearCachedAccessResult(e, t) {
747
+ this.cache.delete(this._accessCacheKey(e, t));
748
+ }
749
+ _accessCacheKey(e, t) {
750
+ return `prd_${[...e].sort()}_${t}`;
751
+ }
752
+ subscriptionsUrl(e = this.redirectUri ?? "") {
753
+ return p(v(e), "subscriptionsUrl(): redirectUri is invalid"), this._spid.makeUrl("account/subscriptions", { redirect_uri: e });
754
+ }
755
+ productsUrl(e = this.redirectUri ?? "") {
756
+ return p(v(e), "productsUrl(): redirectUri is invalid"), this._spid.makeUrl("account/products", { redirect_uri: e });
757
+ }
758
+ }, Y = (e) => e || (typeof window > "u" ? void 0 : window), X = class {
759
+ #e;
760
+ #t;
761
+ constructor(e) {
762
+ let n = Y(e.window);
763
+ if (!n) throw new i("Schibsted Account SDK is not available in this browser context");
764
+ if (n.schAccount) throw new i("Schibsted Account SDK has already been initialized");
765
+ let { log: r, callbackBeforeRedirect: a, varnish: o } = e, s = {
766
+ clientId: e.clientId,
767
+ redirectUri: e.redirectUri,
768
+ sessionDomain: e.sessionDomain,
769
+ env: e.env,
770
+ window: n
771
+ };
772
+ if (this.#e = new q({
773
+ ...s,
774
+ log: r,
775
+ callbackBeforeRedirect: a
776
+ }), o) {
777
+ if (typeof o != "object" || Array.isArray(o)) throw new i("Account varnish config must be an object");
778
+ this.#e.enableVarnishCookie(o);
779
+ }
780
+ this.#t = new oe(s), t(n, "schAccount", this);
781
+ }
782
+ hasSession() {
783
+ return this.#e.hasSession();
784
+ }
785
+ isLoggedIn() {
786
+ return this.#e.isLoggedIn();
787
+ }
788
+ isConnected() {
789
+ return this.#e.isConnected();
790
+ }
791
+ getUser() {
792
+ return this.#e.getUser();
793
+ }
794
+ getUserId() {
795
+ return this.#e.getUserId();
796
+ }
797
+ getUserSDRN() {
798
+ return this.#e.getUserSDRN();
799
+ }
800
+ getUserContextData() {
801
+ return this.#e.getUserContextData();
802
+ }
803
+ getSpId() {
804
+ return this.#e.getSpId();
805
+ }
806
+ login(e) {
807
+ return this.#e.login(e);
808
+ }
809
+ logout(e) {
810
+ this.#e.logout(e);
811
+ }
812
+ loginUrl(e) {
813
+ return this.#e.loginUrl(e);
814
+ }
815
+ accountUrl(e) {
816
+ return this.#e.accountUrl(e);
817
+ }
818
+ showSimplifiedLoginWidget(e, t) {
819
+ return this.#e.showSimplifiedLoginWidget(e, t);
820
+ }
821
+ clearCachedUserSession() {
822
+ this.#e.clearCachedUserSession();
823
+ }
824
+ hasAccess(e, t) {
825
+ return this.#t.hasAccess(e, t);
826
+ }
827
+ clearCachedAccessResult(e, t) {
828
+ this.#t.clearCachedAccessResult(e, t);
829
+ }
830
+ on(e, t, n) {
831
+ return e === "hasAccess" ? this.#t.on(e, t, n) : this.#e.on(e, t, n), this;
832
+ }
833
+ off(e, t) {
834
+ return e === "hasAccess" ? this.#t.off(e, t) : this.#e.off(e, t), this;
835
+ }
836
+ }, Z = "schAccount:ready", Q = 4e3, $, se = () => /* @__PURE__ */ Error("Schibsted Account SDK is not available in this browser context"), ce = () => /* @__PURE__ */ Error(`Schibsted Account SDK was not initialized within ${Q} ms`);
837
+ function le(e) {
838
+ return new X(e);
839
+ }
840
+ function ue() {
841
+ let e = Y();
842
+ if (!e) {
843
+ let e = se();
844
+ return console.error(e.message), Promise.reject(e);
845
+ }
846
+ return e.schAccount ? Promise.resolve(e.schAccount) : $ || ($ = new Promise((t, n) => {
847
+ let r, i = () => {
848
+ e.removeEventListener(Z, a), r !== void 0 && e.clearTimeout(r), $ = void 0;
849
+ }, a = () => {
850
+ let n = e.schAccount;
851
+ n && (i(), t(n));
852
+ };
853
+ e.addEventListener(Z, a), r = e.setTimeout(() => {
854
+ let e = ce();
855
+ console.error(e.message), i(), n(e);
856
+ }, Q), a();
857
+ }), $);
858
+ }
859
+ //#endregion
860
+ export { X as Account, i as SDKError, le as createAccountSdk, ue as getAccountSdk };
861
+
862
+ //# sourceMappingURL=index.js.map