@financial-times/cmp-client 2.0.2 → 2.0.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/dist/client.js ADDED
@@ -0,0 +1,2657 @@
1
+ import { FT_DOTCOM_PROD } from "./properties.js";
2
+ const request = (url, { credentials = "omit" } = {}) => {
3
+ return fetch(`https://session-next.ft.com${url}`, {
4
+ credentials,
5
+ useCorsProxy: true
6
+ }).then((response) => {
7
+ if (response.ok) {
8
+ return response.json();
9
+ } else {
10
+ return response.text().then((text) => {
11
+ throw new Error(`Next session responded with "${text}" (${response.status})`);
12
+ });
13
+ }
14
+ }).catch((err) => {
15
+ document.body.dispatchEvent(new CustomEvent("oErrors.log", {
16
+ bubbles: true,
17
+ detail: {
18
+ error: err,
19
+ info: {
20
+ component: "next-session-client"
21
+ }
22
+ }
23
+ }));
24
+ });
25
+ };
26
+ let detailsCache = {};
27
+ const cache = (name, value) => {
28
+ if (typeof name === "object") {
29
+ detailsCache = name;
30
+ return;
31
+ }
32
+ if (typeof name === "string" && typeof value === "string") {
33
+ detailsCache[name] = value;
34
+ return;
35
+ }
36
+ if (typeof name === "string" && typeof value === "undefined") {
37
+ return detailsCache[name] || null;
38
+ }
39
+ if (typeof name === "undefined" && typeof value === "undefined") {
40
+ return detailsCache;
41
+ }
42
+ throw new Error("Invalid arguments");
43
+ };
44
+ cache.clear = () => {
45
+ detailsCache = {};
46
+ };
47
+ const requests = {};
48
+ const getSessionId = () => {
49
+ const [, sessionId] = /FTSession_s=([^;]+)/.exec(document.cookie) || [];
50
+ return sessionId;
51
+ };
52
+ const getUuid = () => {
53
+ const cachedUUID = cache("uuid");
54
+ if (cachedUUID) {
55
+ return Promise.resolve({ uuid: cachedUUID });
56
+ }
57
+ const sessionId = getSessionId();
58
+ if (!sessionId) {
59
+ return Promise.resolve({ uuid: void 0 });
60
+ }
61
+ if (!requests.uuid) {
62
+ requests.uuid = request(`/sessions/s/${sessionId}`).then(({ uuid } = {}) => {
63
+ delete requests.uuid;
64
+ if (uuid) {
65
+ cache("uuid", uuid);
66
+ }
67
+ return { uuid };
68
+ });
69
+ }
70
+ return requests.uuid;
71
+ };
72
+ function encodeConfig(obj) {
73
+ let str = "";
74
+ for (const [key, val] of Object.entries(obj)) {
75
+ switch (typeof obj[key]) {
76
+ case "function":
77
+ str += `${key}:${val.toString().replace(/"/g, "'").replace(/\s/g, "")},`;
78
+ break;
79
+ case "string":
80
+ str += `${key}:"${val.replace(/"/g, "'").replace(/\s/g, "")}",`;
81
+ break;
82
+ case "object":
83
+ str += `${key}:{${encodeConfig(val)}},`;
84
+ break;
85
+ default:
86
+ str += `${key}:${val},`;
87
+ break;
88
+ }
89
+ }
90
+ return str.slice(0, -1);
91
+ }
92
+ function getSPConfig(config) {
93
+ return `window._sp_queue=[];window._sp_={config:{${encodeConfig(config)}}}`;
94
+ }
95
+ const scriptSources = {
96
+ cmpFrames: "https://cdn.privacy-mgmt.com/unified/wrapperMessagingWithoutDetection.js"
97
+ };
98
+ const scriptContent = {
99
+ getSPConfig,
100
+ tcfStub: `"use strict";function _typeof(t){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}!function(){var t=function(){var t,e,o=[],n=window,r=n;for(;r;){try{if(r.frames.__tcfapiLocator){t=r;break}}catch(t){}if(r===n.top)break;r=r.parent}t||(!function t(){var e=n.document,o=!!n.frames.__tcfapiLocator;if(!o)if(e.body){var r=e.createElement("iframe");r.style.cssText="display:none",r.name="__tcfapiLocator",e.body.appendChild(r)}else setTimeout(t,5);return!o}(),n.__tcfapi=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(!n.length)return o;"setGdprApplies"===n[0]?n.length>3&&2===parseInt(n[1],10)&&"boolean"==typeof n[3]&&(e=n[3],"function"==typeof n[2]&&n[2]("set",!0)):"ping"===n[0]?"function"==typeof n[2]&&n[2]({gdprApplies:e,cmpLoaded:!1,cmpStatus:"stub"}):o.push(n)},n.addEventListener("message",(function(t){var e="string"==typeof t.data,o={};if(e)try{o=JSON.parse(t.data)}catch(t){}else o=t.data;var n="object"===_typeof(o)&&null!==o?o.__tcfapiCall:null;n&&window.__tcfapi(n.command,n.version,(function(o,r){var a={__tcfapiReturn:{returnValue:o,success:r,callId:n.callId}};t&&t.source&&t.source.postMessage&&t.source.postMessage(e?JSON.stringify(a):a,"*")}),n.parameter)}),!1))};"undefined"!=typeof module?module.exports=t:t()}();`,
101
+ uspStub: `"use strict";(function () { var e = false; var c = window; var t = document; function r() { if (!c.frames["__uspapiLocator"]) { if (t.body) { var a = t.body; var e = t.createElement("iframe"); e.style.cssText = "display:none"; e.name = "__uspapiLocator"; a.appendChild(e) } else { setTimeout(r, 5) } } } r(); function p() { var a = arguments; __uspapi.a = __uspapi.a || []; if (!a.length) { return __uspapi.a } else if (a[0] === "ping") { a[2]({ gdprAppliesGlobally: e, cmpLoaded: false }, true) } else { __uspapi.a.push([].slice.apply(a)) } } function l(t) { var r = typeof t.data === "string"; try { var a = r ? JSON.parse(t.data) : t.data; if (a.__cmpCall) { var n = a.__cmpCall; c.__uspapi(n.command, n.parameter, function (a, e) { var c = { __cmpReturn: { returnValue: a, success: e, callId: n.callId } }; t.source.postMessage(r ? JSON.stringify(c) : c, "*") }) } } catch (a) { } } if (typeof __uspapi !== "function") { c.__uspapi = p; __uspapi.msgHandler = l; c.addEventListener("message", l, false) } })();`
102
+ };
103
+ var __defProp = Object.defineProperty;
104
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
105
+ var __publicField = (obj, key, value) => {
106
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
107
+ return value;
108
+ };
109
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
110
+ class DecodingError extends Error {
111
+ /**
112
+ * constructor - constructs an DecodingError
113
+ *
114
+ * @param {string} msg - Decoding Error Message
115
+ * @return {undefined}
116
+ */
117
+ constructor(msg) {
118
+ super(msg);
119
+ this.name = "DecodingError";
120
+ }
121
+ }
122
+ class EncodingError extends Error {
123
+ /**
124
+ * constructor - constructs an EncodingError
125
+ *
126
+ * @param {string} msg - Encoding Error Message
127
+ * @return {undefined}
128
+ */
129
+ constructor(msg) {
130
+ super(msg);
131
+ this.name = "EncodingError";
132
+ }
133
+ }
134
+ class GVLError extends Error {
135
+ /**
136
+ * constructor - constructs a GVLError
137
+ *
138
+ * @param {string} msg - Error message to display
139
+ * @return {undefined}
140
+ */
141
+ constructor(msg) {
142
+ super(msg);
143
+ this.name = "GVLError";
144
+ }
145
+ }
146
+ class TCModelError extends Error {
147
+ /**
148
+ * constructor - constructs an TCModelError
149
+ *
150
+ * @param {string} fieldName - the errored field
151
+ * @param {string} passedValue - what was passed
152
+ * @return {undefined}
153
+ */
154
+ constructor(fieldName, passedValue, msg = "") {
155
+ super(`invalid value ${passedValue} passed for ${fieldName} ${msg}`);
156
+ this.name = "TCModelError";
157
+ }
158
+ }
159
+ class Base64Url {
160
+ /**
161
+ * encodes an arbitrary-length bitfield string into base64url
162
+ *
163
+ * @static
164
+ * @param {string} str - arbitrary-length bitfield string to be encoded to base64url
165
+ * @return {string} - base64url encoded result
166
+ */
167
+ static encode(str) {
168
+ if (!/^[0-1]+$/.test(str)) {
169
+ throw new EncodingError("Invalid bitField");
170
+ }
171
+ const padding = str.length % this.LCM;
172
+ str += padding ? "0".repeat(this.LCM - padding) : "";
173
+ let result = "";
174
+ for (let i = 0; i < str.length; i += this.BASIS) {
175
+ result += this.DICT[parseInt(str.substr(i, this.BASIS), 2)];
176
+ }
177
+ return result;
178
+ }
179
+ /**
180
+ * decodes a base64url encoded bitfield string
181
+ *
182
+ * @static
183
+ * @param {string} str - base64url encoded bitfield string to be decoded
184
+ * @return {string} - bitfield string
185
+ */
186
+ static decode(str) {
187
+ if (!/^[A-Za-z0-9\-_]+$/.test(str)) {
188
+ throw new DecodingError("Invalidly encoded Base64URL string");
189
+ }
190
+ let result = "";
191
+ for (let i = 0; i < str.length; i++) {
192
+ const strBits = this.REVERSE_DICT.get(str[i]).toString(2);
193
+ result += "0".repeat(this.BASIS - strBits.length) + strBits;
194
+ }
195
+ return result;
196
+ }
197
+ }
198
+ __publicField(Base64Url, "DICT", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
199
+ __publicField(Base64Url, "REVERSE_DICT", /* @__PURE__ */ new Map([
200
+ ["A", 0],
201
+ ["B", 1],
202
+ ["C", 2],
203
+ ["D", 3],
204
+ ["E", 4],
205
+ ["F", 5],
206
+ ["G", 6],
207
+ ["H", 7],
208
+ ["I", 8],
209
+ ["J", 9],
210
+ ["K", 10],
211
+ ["L", 11],
212
+ ["M", 12],
213
+ ["N", 13],
214
+ ["O", 14],
215
+ ["P", 15],
216
+ ["Q", 16],
217
+ ["R", 17],
218
+ ["S", 18],
219
+ ["T", 19],
220
+ ["U", 20],
221
+ ["V", 21],
222
+ ["W", 22],
223
+ ["X", 23],
224
+ ["Y", 24],
225
+ ["Z", 25],
226
+ ["a", 26],
227
+ ["b", 27],
228
+ ["c", 28],
229
+ ["d", 29],
230
+ ["e", 30],
231
+ ["f", 31],
232
+ ["g", 32],
233
+ ["h", 33],
234
+ ["i", 34],
235
+ ["j", 35],
236
+ ["k", 36],
237
+ ["l", 37],
238
+ ["m", 38],
239
+ ["n", 39],
240
+ ["o", 40],
241
+ ["p", 41],
242
+ ["q", 42],
243
+ ["r", 43],
244
+ ["s", 44],
245
+ ["t", 45],
246
+ ["u", 46],
247
+ ["v", 47],
248
+ ["w", 48],
249
+ ["x", 49],
250
+ ["y", 50],
251
+ ["z", 51],
252
+ ["0", 52],
253
+ ["1", 53],
254
+ ["2", 54],
255
+ ["3", 55],
256
+ ["4", 56],
257
+ ["5", 57],
258
+ ["6", 58],
259
+ ["7", 59],
260
+ ["8", 60],
261
+ ["9", 61],
262
+ ["-", 62],
263
+ ["_", 63]
264
+ ]));
265
+ __publicField(Base64Url, "BASIS", 6);
266
+ __publicField(Base64Url, "LCM", 24);
267
+ const _ConsentLanguages = class _ConsentLanguages2 {
268
+ has(key) {
269
+ return _ConsentLanguages2.langSet.has(key);
270
+ }
271
+ parseLanguage(lang) {
272
+ lang = lang.toUpperCase();
273
+ const primaryLanguage = lang.split("-")[0];
274
+ if (lang.length >= 2 && primaryLanguage.length == 2) {
275
+ if (_ConsentLanguages2.langSet.has(lang)) {
276
+ return lang;
277
+ } else if (_ConsentLanguages2.langSet.has(primaryLanguage)) {
278
+ return primaryLanguage;
279
+ }
280
+ const fullPrimaryLang = primaryLanguage + "-" + primaryLanguage;
281
+ if (_ConsentLanguages2.langSet.has(fullPrimaryLang)) {
282
+ return fullPrimaryLang;
283
+ }
284
+ for (const supportedLang of _ConsentLanguages2.langSet) {
285
+ if (supportedLang.indexOf(lang) !== -1 || supportedLang.indexOf(primaryLanguage) !== -1) {
286
+ return supportedLang;
287
+ }
288
+ }
289
+ }
290
+ throw new Error(`unsupported language ${lang}`);
291
+ }
292
+ forEach(callback) {
293
+ _ConsentLanguages2.langSet.forEach(callback);
294
+ }
295
+ get size() {
296
+ return _ConsentLanguages2.langSet.size;
297
+ }
298
+ };
299
+ __publicField(_ConsentLanguages, "langSet", /* @__PURE__ */ new Set([
300
+ "AR",
301
+ "BG",
302
+ "BS",
303
+ "CA",
304
+ "CS",
305
+ "DA",
306
+ "DE",
307
+ "EL",
308
+ "EN",
309
+ "ES",
310
+ "ET",
311
+ "EU",
312
+ "FI",
313
+ "FR",
314
+ "GL",
315
+ "HR",
316
+ "HU",
317
+ "IT",
318
+ "JA",
319
+ "LT",
320
+ "LV",
321
+ "MT",
322
+ "NL",
323
+ "NO",
324
+ "PL",
325
+ "PT-BR",
326
+ "PT-PT",
327
+ "RO",
328
+ "RU",
329
+ "SK",
330
+ "SL",
331
+ "SR-LATN",
332
+ "SR-CYRL",
333
+ "SV",
334
+ "TR",
335
+ "ZH"
336
+ ]));
337
+ let ConsentLanguages = _ConsentLanguages;
338
+ class Fields {
339
+ }
340
+ __publicField(Fields, "cmpId", "cmpId");
341
+ __publicField(Fields, "cmpVersion", "cmpVersion");
342
+ __publicField(Fields, "consentLanguage", "consentLanguage");
343
+ __publicField(Fields, "consentScreen", "consentScreen");
344
+ __publicField(Fields, "created", "created");
345
+ __publicField(Fields, "supportOOB", "supportOOB");
346
+ __publicField(Fields, "isServiceSpecific", "isServiceSpecific");
347
+ __publicField(Fields, "lastUpdated", "lastUpdated");
348
+ __publicField(Fields, "numCustomPurposes", "numCustomPurposes");
349
+ __publicField(Fields, "policyVersion", "policyVersion");
350
+ __publicField(Fields, "publisherCountryCode", "publisherCountryCode");
351
+ __publicField(Fields, "publisherCustomConsents", "publisherCustomConsents");
352
+ __publicField(Fields, "publisherCustomLegitimateInterests", "publisherCustomLegitimateInterests");
353
+ __publicField(Fields, "publisherLegitimateInterests", "publisherLegitimateInterests");
354
+ __publicField(Fields, "publisherConsents", "publisherConsents");
355
+ __publicField(Fields, "publisherRestrictions", "publisherRestrictions");
356
+ __publicField(Fields, "purposeConsents", "purposeConsents");
357
+ __publicField(Fields, "purposeLegitimateInterests", "purposeLegitimateInterests");
358
+ __publicField(Fields, "purposeOneTreatment", "purposeOneTreatment");
359
+ __publicField(Fields, "specialFeatureOptins", "specialFeatureOptins");
360
+ __publicField(Fields, "useNonStandardTexts", "useNonStandardTexts");
361
+ __publicField(Fields, "vendorConsents", "vendorConsents");
362
+ __publicField(Fields, "vendorLegitimateInterests", "vendorLegitimateInterests");
363
+ __publicField(Fields, "vendorListVersion", "vendorListVersion");
364
+ __publicField(Fields, "vendorsAllowed", "vendorsAllowed");
365
+ __publicField(Fields, "vendorsDisclosed", "vendorsDisclosed");
366
+ __publicField(Fields, "version", "version");
367
+ class Cloneable {
368
+ /**
369
+ * clone - returns a copy of the classes with new values and not references
370
+ *
371
+ * @return {T}
372
+ */
373
+ clone() {
374
+ const myClone = new this.constructor();
375
+ const keys = Object.keys(this);
376
+ keys.forEach((key) => {
377
+ const value = this.deepClone(this[key]);
378
+ if (value !== void 0) {
379
+ myClone[key] = value;
380
+ }
381
+ });
382
+ return myClone;
383
+ }
384
+ /**
385
+ * deepClone - recursive function that makes copies of reference values
386
+ *
387
+ * @param {unknown} item
388
+ * @return {unknown}
389
+ */
390
+ deepClone(item) {
391
+ const itsType = typeof item;
392
+ if (itsType === "number" || itsType === "string" || itsType === "boolean") {
393
+ return item;
394
+ } else if (item !== null && itsType === "object") {
395
+ if (typeof item.clone === "function") {
396
+ return item.clone();
397
+ } else if (item instanceof Date) {
398
+ return new Date(item.getTime());
399
+ } else if (item[Symbol.iterator] !== void 0) {
400
+ const ar = [];
401
+ for (const subItem of item) {
402
+ ar.push(this.deepClone(subItem));
403
+ }
404
+ if (item instanceof Array) {
405
+ return ar;
406
+ } else {
407
+ return new item.constructor(ar);
408
+ }
409
+ } else {
410
+ const retr = {};
411
+ for (const prop in item) {
412
+ if (item.hasOwnProperty(prop)) {
413
+ retr[prop] = this.deepClone(item[prop]);
414
+ }
415
+ }
416
+ return retr;
417
+ }
418
+ }
419
+ }
420
+ }
421
+ var RestrictionType;
422
+ (function(RestrictionType2) {
423
+ RestrictionType2[RestrictionType2["NOT_ALLOWED"] = 0] = "NOT_ALLOWED";
424
+ RestrictionType2[RestrictionType2["REQUIRE_CONSENT"] = 1] = "REQUIRE_CONSENT";
425
+ RestrictionType2[RestrictionType2["REQUIRE_LI"] = 2] = "REQUIRE_LI";
426
+ })(RestrictionType || (RestrictionType = {}));
427
+ const _PurposeRestriction = class _PurposeRestriction2 extends Cloneable {
428
+ /**
429
+ * constructor
430
+ *
431
+ * @param {number} purposeId? - may optionally pass the purposeId into the
432
+ * constructor
433
+ * @param {RestrictionType} restrictionType? - may
434
+ * optionally pass the restrictionType into the constructor
435
+ * @return {undefined}
436
+ */
437
+ constructor(purposeId, restrictionType) {
438
+ super();
439
+ __publicField(this, "purposeId_");
440
+ __publicField(this, "restrictionType");
441
+ if (purposeId !== void 0) {
442
+ this.purposeId = purposeId;
443
+ }
444
+ if (restrictionType !== void 0) {
445
+ this.restrictionType = restrictionType;
446
+ }
447
+ }
448
+ static unHash(hash) {
449
+ const splitUp = hash.split(this.hashSeparator);
450
+ const purpRestriction = new _PurposeRestriction2();
451
+ if (splitUp.length !== 2) {
452
+ throw new TCModelError("hash", hash);
453
+ }
454
+ purpRestriction.purposeId = parseInt(splitUp[0], 10);
455
+ purpRestriction.restrictionType = parseInt(splitUp[1], 10);
456
+ return purpRestriction;
457
+ }
458
+ get hash() {
459
+ if (!this.isValid()) {
460
+ throw new Error("cannot hash invalid PurposeRestriction");
461
+ }
462
+ return `${this.purposeId}${_PurposeRestriction2.hashSeparator}${this.restrictionType}`;
463
+ }
464
+ /**
465
+ * @return {number} The purpose Id associated with a publisher
466
+ * purpose-by-vendor restriction that resulted in a different consent or LI
467
+ * status than the consent or LI purposes allowed lists.
468
+ */
469
+ get purposeId() {
470
+ return this.purposeId_;
471
+ }
472
+ /**
473
+ * @param {number} idNum - The purpose Id associated with a publisher
474
+ * purpose-by-vendor restriction that resulted in a different consent or LI
475
+ * status than the consent or LI purposes allowed lists.
476
+ */
477
+ set purposeId(idNum) {
478
+ this.purposeId_ = idNum;
479
+ }
480
+ isValid() {
481
+ return Number.isInteger(this.purposeId) && this.purposeId > 0 && (this.restrictionType === RestrictionType.NOT_ALLOWED || this.restrictionType === RestrictionType.REQUIRE_CONSENT || this.restrictionType === RestrictionType.REQUIRE_LI);
482
+ }
483
+ isSameAs(otherPR) {
484
+ return this.purposeId === otherPR.purposeId && this.restrictionType === otherPR.restrictionType;
485
+ }
486
+ };
487
+ __publicField(_PurposeRestriction, "hashSeparator", "-");
488
+ let PurposeRestriction = _PurposeRestriction;
489
+ class PurposeRestrictionVector extends Cloneable {
490
+ constructor() {
491
+ super(...arguments);
492
+ __publicField(this, "bitLength", 0);
493
+ __publicField(this, "map", /* @__PURE__ */ new Map());
494
+ __publicField(this, "gvl_");
495
+ }
496
+ has(hash) {
497
+ return this.map.has(hash);
498
+ }
499
+ isOkToHave(restrictionType, purposeId, vendorId) {
500
+ var _a2;
501
+ let result = true;
502
+ if ((_a2 = this.gvl) == null ? void 0 : _a2.vendors) {
503
+ const vendor = this.gvl.vendors[vendorId];
504
+ if (vendor) {
505
+ if (restrictionType === RestrictionType.NOT_ALLOWED) {
506
+ result = vendor.legIntPurposes.includes(purposeId) || vendor.purposes.includes(purposeId);
507
+ } else if (vendor.flexiblePurposes.length) {
508
+ switch (restrictionType) {
509
+ case RestrictionType.REQUIRE_CONSENT:
510
+ result = vendor.flexiblePurposes.includes(purposeId) && vendor.legIntPurposes.includes(purposeId);
511
+ break;
512
+ case RestrictionType.REQUIRE_LI:
513
+ result = vendor.flexiblePurposes.includes(purposeId) && vendor.purposes.includes(purposeId);
514
+ break;
515
+ }
516
+ } else {
517
+ result = false;
518
+ }
519
+ } else {
520
+ result = false;
521
+ }
522
+ }
523
+ return result;
524
+ }
525
+ /**
526
+ * add - adds a given Vendor ID under a given Purpose Restriction
527
+ *
528
+ * @param {number} vendorId
529
+ * @param {PurposeRestriction} purposeRestriction
530
+ * @return {void}
531
+ */
532
+ add(vendorId, purposeRestriction) {
533
+ if (this.isOkToHave(purposeRestriction.restrictionType, purposeRestriction.purposeId, vendorId)) {
534
+ const hash = purposeRestriction.hash;
535
+ if (!this.has(hash)) {
536
+ this.map.set(hash, /* @__PURE__ */ new Set());
537
+ this.bitLength = 0;
538
+ }
539
+ this.map.get(hash).add(vendorId);
540
+ }
541
+ }
542
+ /**
543
+ * restrictPurposeToLegalBasis - adds all Vendors under a given Purpose Restriction
544
+ *
545
+ * @param {PurposeRestriction} purposeRestriction
546
+ * @return {void}
547
+ */
548
+ restrictPurposeToLegalBasis(purposeRestriction) {
549
+ const vendors = Array.from(this.gvl.vendorIds);
550
+ const hash = purposeRestriction.hash;
551
+ const lastEntry = vendors[vendors.length - 1];
552
+ const values = [...Array(lastEntry).keys()].map((i) => i + 1);
553
+ if (!this.has(hash)) {
554
+ this.map.set(hash, new Set(values));
555
+ this.bitLength = 0;
556
+ } else {
557
+ for (let i = 1; i <= lastEntry; i++) {
558
+ this.map.get(hash).add(i);
559
+ }
560
+ }
561
+ }
562
+ /**
563
+ * getVendors - returns array of vendor ids optionally narrowed by a given
564
+ * Purpose Restriction. If no purpose restriction is passed then all vendor
565
+ * ids will be returned. One can expect this result to be a unique set of
566
+ * ids no duplicates.
567
+ *
568
+ * @param {PurposeRestriction} [purposeRestriction] - optionally passed to
569
+ * get only Vendor IDs restricted under the given Purpose Restriction
570
+ * @return {number[]} - Unique ID set of vendors
571
+ */
572
+ getVendors(purposeRestriction) {
573
+ let vendorIds = [];
574
+ if (purposeRestriction) {
575
+ const hash = purposeRestriction.hash;
576
+ if (this.has(hash)) {
577
+ vendorIds = Array.from(this.map.get(hash));
578
+ }
579
+ } else {
580
+ const vendorSet = /* @__PURE__ */ new Set();
581
+ this.map.forEach((set) => {
582
+ set.forEach((vendorId) => {
583
+ vendorSet.add(vendorId);
584
+ });
585
+ });
586
+ vendorIds = Array.from(vendorSet);
587
+ }
588
+ return vendorIds.sort((a, b) => a - b);
589
+ }
590
+ getRestrictionType(vendorId, purposeId) {
591
+ let rType;
592
+ this.getRestrictions(vendorId).forEach((purposeRestriction) => {
593
+ if (purposeRestriction.purposeId === purposeId) {
594
+ if (rType === void 0 || rType > purposeRestriction.restrictionType) {
595
+ rType = purposeRestriction.restrictionType;
596
+ }
597
+ }
598
+ });
599
+ return rType;
600
+ }
601
+ /**
602
+ * vendorHasRestriction - determines whether a given Vendor ID is under a
603
+ * given Purpose Restriction
604
+ *
605
+ * @param {number} vendorId
606
+ * @param {PurposeRestriction} purposeRestriction
607
+ * @return {boolean} - true if the give Vendor ID is under the given Purpose
608
+ * Restriction
609
+ */
610
+ vendorHasRestriction(vendorId, purposeRestriction) {
611
+ let has = false;
612
+ const restrictions = this.getRestrictions(vendorId);
613
+ for (let i = 0; i < restrictions.length && !has; i++) {
614
+ has = purposeRestriction.isSameAs(restrictions[i]);
615
+ }
616
+ return has;
617
+ }
618
+ /**
619
+ * getMaxVendorId - gets the Maximum Vendor ID regardless of Purpose
620
+ * Restriction
621
+ *
622
+ * @return {number} - maximum Vendor ID
623
+ */
624
+ getMaxVendorId() {
625
+ let retr = 0;
626
+ this.map.forEach((set) => {
627
+ retr = Math.max(Array.from(set)[set.size - 1], retr);
628
+ });
629
+ return retr;
630
+ }
631
+ getRestrictions(vendorId) {
632
+ const retr = [];
633
+ this.map.forEach((set, hash) => {
634
+ if (vendorId) {
635
+ if (set.has(vendorId)) {
636
+ retr.push(PurposeRestriction.unHash(hash));
637
+ }
638
+ } else {
639
+ retr.push(PurposeRestriction.unHash(hash));
640
+ }
641
+ });
642
+ return retr;
643
+ }
644
+ getPurposes() {
645
+ const purposeIds = /* @__PURE__ */ new Set();
646
+ this.map.forEach((set, hash) => {
647
+ purposeIds.add(PurposeRestriction.unHash(hash).purposeId);
648
+ });
649
+ return Array.from(purposeIds);
650
+ }
651
+ /**
652
+ * remove - removes Vendor ID from a Purpose Restriction
653
+ *
654
+ * @param {number} vendorId
655
+ * @param {PurposeRestriction} purposeRestriction
656
+ * @return {void}
657
+ */
658
+ remove(vendorId, purposeRestriction) {
659
+ const hash = purposeRestriction.hash;
660
+ const set = this.map.get(hash);
661
+ if (set) {
662
+ set.delete(vendorId);
663
+ if (set.size == 0) {
664
+ this.map.delete(hash);
665
+ this.bitLength = 0;
666
+ }
667
+ }
668
+ }
669
+ /**
670
+ * Essential for being able to determine whether we can actually set a
671
+ * purpose restriction since they have to have a flexible legal basis
672
+ *
673
+ * @param {GVL} value - the GVL instance
674
+ */
675
+ set gvl(value) {
676
+ if (!this.gvl_) {
677
+ this.gvl_ = value;
678
+ this.map.forEach((set, hash) => {
679
+ const purposeRestriction = PurposeRestriction.unHash(hash);
680
+ const vendors = Array.from(set);
681
+ vendors.forEach((vendorId) => {
682
+ if (!this.isOkToHave(purposeRestriction.restrictionType, purposeRestriction.purposeId, vendorId)) {
683
+ set.delete(vendorId);
684
+ }
685
+ });
686
+ });
687
+ }
688
+ }
689
+ /**
690
+ * gvl returns local copy of the GVL these restrictions apply to
691
+ *
692
+ * @return {GVL}
693
+ */
694
+ get gvl() {
695
+ return this.gvl_;
696
+ }
697
+ /**
698
+ * isEmpty - whether or not this vector has any restrictions in it
699
+ *
700
+ * @return {boolean}
701
+ */
702
+ isEmpty() {
703
+ return this.map.size === 0;
704
+ }
705
+ /**
706
+ * numRestrictions - returns the number of Purpose Restrictions.
707
+ *
708
+ * @return {number}
709
+ */
710
+ get numRestrictions() {
711
+ return this.map.size;
712
+ }
713
+ }
714
+ var DeviceDisclosureStorageAccessType;
715
+ (function(DeviceDisclosureStorageAccessType2) {
716
+ DeviceDisclosureStorageAccessType2["COOKIE"] = "cookie";
717
+ DeviceDisclosureStorageAccessType2["WEB"] = "web";
718
+ DeviceDisclosureStorageAccessType2["APP"] = "app";
719
+ })(DeviceDisclosureStorageAccessType || (DeviceDisclosureStorageAccessType = {}));
720
+ var Segment;
721
+ (function(Segment2) {
722
+ Segment2["CORE"] = "core";
723
+ Segment2["VENDORS_DISCLOSED"] = "vendorsDisclosed";
724
+ Segment2["VENDORS_ALLOWED"] = "vendorsAllowed";
725
+ Segment2["PUBLISHER_TC"] = "publisherTC";
726
+ })(Segment || (Segment = {}));
727
+ class SegmentIDs {
728
+ }
729
+ __publicField(SegmentIDs, "ID_TO_KEY", [
730
+ Segment.CORE,
731
+ Segment.VENDORS_DISCLOSED,
732
+ Segment.VENDORS_ALLOWED,
733
+ Segment.PUBLISHER_TC
734
+ ]);
735
+ __publicField(SegmentIDs, "KEY_TO_ID", {
736
+ [Segment.CORE]: 0,
737
+ [Segment.VENDORS_DISCLOSED]: 1,
738
+ [Segment.VENDORS_ALLOWED]: 2,
739
+ [Segment.PUBLISHER_TC]: 3
740
+ });
741
+ class Vector extends Cloneable {
742
+ constructor() {
743
+ super(...arguments);
744
+ __publicField(this, "bitLength", 0);
745
+ __publicField(this, "maxId_", 0);
746
+ __publicField(this, "set_", /* @__PURE__ */ new Set());
747
+ }
748
+ *[Symbol.iterator]() {
749
+ for (let i = 1; i <= this.maxId; i++) {
750
+ yield [i, this.has(i)];
751
+ }
752
+ }
753
+ /**
754
+ * values()
755
+ *
756
+ * @return {IterableIterator<number>} - returns an iterator of the positive
757
+ * values in the set
758
+ */
759
+ values() {
760
+ return this.set_.values();
761
+ }
762
+ /**
763
+ * maxId
764
+ *
765
+ * @return {number} - the highest id in this Vector
766
+ */
767
+ get maxId() {
768
+ return this.maxId_;
769
+ }
770
+ /**
771
+ * get
772
+ *
773
+ * @param {number} id - key for value to check
774
+ * @return {boolean} - value of that key, if never set it will be false
775
+ */
776
+ has(id) {
777
+ return this.set_.has(id);
778
+ }
779
+ /**
780
+ * unset
781
+ *
782
+ * @param {SingleIDOrCollection} id - id or ids to unset
783
+ * @return {void}
784
+ */
785
+ unset(id) {
786
+ if (Array.isArray(id)) {
787
+ id.forEach((id2) => this.unset(id2));
788
+ } else if (typeof id === "object") {
789
+ this.unset(Object.keys(id).map((strId) => Number(strId)));
790
+ } else {
791
+ this.set_.delete(Number(id));
792
+ this.bitLength = 0;
793
+ if (id === this.maxId) {
794
+ this.maxId_ = 0;
795
+ this.set_.forEach((id2) => {
796
+ this.maxId_ = Math.max(this.maxId, id2);
797
+ });
798
+ }
799
+ }
800
+ }
801
+ isIntMap(item) {
802
+ let result = typeof item === "object";
803
+ result = result && Object.keys(item).every((key) => {
804
+ let itemResult = Number.isInteger(parseInt(key, 10));
805
+ itemResult = itemResult && this.isValidNumber(item[key].id);
806
+ itemResult = itemResult && item[key].name !== void 0;
807
+ return itemResult;
808
+ });
809
+ return result;
810
+ }
811
+ isValidNumber(item) {
812
+ return parseInt(item, 10) > 0;
813
+ }
814
+ isSet(item) {
815
+ let result = false;
816
+ if (item instanceof Set) {
817
+ result = Array.from(item).every(this.isValidNumber);
818
+ }
819
+ return result;
820
+ }
821
+ /**
822
+ * set - sets an item assumed to be a truthy value by its presence
823
+ *
824
+ * @param {SingleIDOrCollection} item - May be a single id (positive integer)
825
+ * or collection of ids in a set, GVL Int Map, or Array.
826
+ *
827
+ * @return {void}
828
+ */
829
+ set(item) {
830
+ if (Array.isArray(item)) {
831
+ item.forEach((item2) => this.set(item2));
832
+ } else if (this.isSet(item)) {
833
+ this.set(Array.from(item));
834
+ } else if (this.isIntMap(item)) {
835
+ this.set(Object.keys(item).map((strId) => Number(strId)));
836
+ } else if (this.isValidNumber(item)) {
837
+ this.set_.add(item);
838
+ this.maxId_ = Math.max(this.maxId, item);
839
+ this.bitLength = 0;
840
+ } else {
841
+ throw new TCModelError("set()", item, "must be positive integer array, positive integer, Set<number>, or IntMap");
842
+ }
843
+ }
844
+ empty() {
845
+ this.set_ = /* @__PURE__ */ new Set();
846
+ }
847
+ /**
848
+ * forEach - to traverse from id=1 to id=maxId in a sequential non-sparse manner
849
+ *
850
+ *
851
+ * @param {forEachCallback} callback - callback to execute
852
+ * @return {void}
853
+ *
854
+ * @callback forEachCallback
855
+ * @param {boolean} value - whether or not this id exists in the vector
856
+ * @param {number} id - the id number of the current iteration
857
+ */
858
+ forEach(callback) {
859
+ for (let i = 1; i <= this.maxId; i++) {
860
+ callback(this.has(i), i);
861
+ }
862
+ }
863
+ get size() {
864
+ return this.set_.size;
865
+ }
866
+ setAll(intMap) {
867
+ this.set(intMap);
868
+ }
869
+ }
870
+ class BitLength {
871
+ }
872
+ _a = Fields.cmpId, _b = Fields.cmpVersion, _c = Fields.consentLanguage, _d = Fields.consentScreen, _e = Fields.created, _f = Fields.isServiceSpecific, _g = Fields.lastUpdated, _h = Fields.policyVersion, _i = Fields.publisherCountryCode, _j = Fields.publisherLegitimateInterests, _k = Fields.publisherConsents, _l = Fields.purposeConsents, _m = Fields.purposeLegitimateInterests, _n = Fields.purposeOneTreatment, _o = Fields.specialFeatureOptins, _p = Fields.useNonStandardTexts, _q = Fields.vendorListVersion, _r = Fields.version;
873
+ __publicField(BitLength, _a, 12);
874
+ __publicField(BitLength, _b, 12);
875
+ __publicField(BitLength, _c, 12);
876
+ __publicField(BitLength, _d, 6);
877
+ __publicField(BitLength, _e, 36);
878
+ __publicField(BitLength, _f, 1);
879
+ __publicField(BitLength, _g, 36);
880
+ __publicField(BitLength, _h, 6);
881
+ __publicField(BitLength, _i, 12);
882
+ __publicField(BitLength, _j, 24);
883
+ __publicField(BitLength, _k, 24);
884
+ __publicField(BitLength, _l, 24);
885
+ __publicField(BitLength, _m, 24);
886
+ __publicField(BitLength, _n, 1);
887
+ __publicField(BitLength, _o, 12);
888
+ __publicField(BitLength, _p, 1);
889
+ __publicField(BitLength, _q, 12);
890
+ __publicField(BitLength, _r, 6);
891
+ __publicField(BitLength, "anyBoolean", 1);
892
+ __publicField(BitLength, "encodingType", 1);
893
+ __publicField(BitLength, "maxId", 16);
894
+ __publicField(BitLength, "numCustomPurposes", 6);
895
+ __publicField(BitLength, "numEntries", 12);
896
+ __publicField(BitLength, "numRestrictions", 12);
897
+ __publicField(BitLength, "purposeId", 6);
898
+ __publicField(BitLength, "restrictionType", 2);
899
+ __publicField(BitLength, "segmentType", 3);
900
+ __publicField(BitLength, "singleOrRange", 1);
901
+ __publicField(BitLength, "vendorId", 16);
902
+ class BooleanEncoder {
903
+ static encode(value) {
904
+ return String(Number(value));
905
+ }
906
+ static decode(value) {
907
+ return value === "1";
908
+ }
909
+ }
910
+ class IntEncoder {
911
+ static encode(value, numBits) {
912
+ let bitString;
913
+ if (typeof value === "string") {
914
+ value = parseInt(value, 10);
915
+ }
916
+ bitString = value.toString(2);
917
+ if (bitString.length > numBits || value < 0) {
918
+ throw new EncodingError(`${value} too large to encode into ${numBits}`);
919
+ }
920
+ if (bitString.length < numBits) {
921
+ bitString = "0".repeat(numBits - bitString.length) + bitString;
922
+ }
923
+ return bitString;
924
+ }
925
+ static decode(value, numBits) {
926
+ if (numBits !== value.length) {
927
+ throw new DecodingError("invalid bit length");
928
+ }
929
+ return parseInt(value, 2);
930
+ }
931
+ }
932
+ class DateEncoder {
933
+ static encode(value, numBits) {
934
+ return IntEncoder.encode(Math.round(value.getTime() / 100), numBits);
935
+ }
936
+ static decode(value, numBits) {
937
+ if (numBits !== value.length) {
938
+ throw new DecodingError("invalid bit length");
939
+ }
940
+ const date = /* @__PURE__ */ new Date();
941
+ date.setTime(IntEncoder.decode(value, numBits) * 100);
942
+ return date;
943
+ }
944
+ }
945
+ class FixedVectorEncoder {
946
+ static encode(value, numBits) {
947
+ let bitString = "";
948
+ for (let i = 1; i <= numBits; i++) {
949
+ bitString += BooleanEncoder.encode(value.has(i));
950
+ }
951
+ return bitString;
952
+ }
953
+ static decode(value, numBits) {
954
+ if (value.length !== numBits) {
955
+ throw new DecodingError("bitfield encoding length mismatch");
956
+ }
957
+ const vector = new Vector();
958
+ for (let i = 1; i <= numBits; i++) {
959
+ if (BooleanEncoder.decode(value[i - 1])) {
960
+ vector.set(i);
961
+ }
962
+ }
963
+ vector.bitLength = value.length;
964
+ return vector;
965
+ }
966
+ }
967
+ class LangEncoder {
968
+ static encode(value, numBits) {
969
+ value = value.toUpperCase();
970
+ const ASCII_START = 65;
971
+ const firstLetter = value.charCodeAt(0) - ASCII_START;
972
+ const secondLetter = value.charCodeAt(1) - ASCII_START;
973
+ if (firstLetter < 0 || firstLetter > 25 || secondLetter < 0 || secondLetter > 25) {
974
+ throw new EncodingError(`invalid language code: ${value}`);
975
+ }
976
+ if (numBits % 2 === 1) {
977
+ throw new EncodingError(`numBits must be even, ${numBits} is not valid`);
978
+ }
979
+ numBits = numBits / 2;
980
+ const firstLetterBString = IntEncoder.encode(firstLetter, numBits);
981
+ const secondLetterBString = IntEncoder.encode(secondLetter, numBits);
982
+ return firstLetterBString + secondLetterBString;
983
+ }
984
+ static decode(value, numBits) {
985
+ let retr;
986
+ if (numBits === value.length && !(value.length % 2)) {
987
+ const ASCII_START = 65;
988
+ const mid = value.length / 2;
989
+ const firstLetter = IntEncoder.decode(value.slice(0, mid), mid) + ASCII_START;
990
+ const secondLetter = IntEncoder.decode(value.slice(mid), mid) + ASCII_START;
991
+ retr = String.fromCharCode(firstLetter) + String.fromCharCode(secondLetter);
992
+ } else {
993
+ throw new DecodingError("invalid bit length for language");
994
+ }
995
+ return retr;
996
+ }
997
+ }
998
+ class PurposeRestrictionVectorEncoder {
999
+ static encode(prVector) {
1000
+ let bitString = IntEncoder.encode(prVector.numRestrictions, BitLength.numRestrictions);
1001
+ if (!prVector.isEmpty()) {
1002
+ const nextGvlVendor = (vendorId, lastVendorId) => {
1003
+ for (let nextId = vendorId + 1; nextId <= lastVendorId; nextId++) {
1004
+ if (prVector.gvl.vendorIds.has(nextId)) {
1005
+ return nextId;
1006
+ }
1007
+ }
1008
+ return vendorId;
1009
+ };
1010
+ prVector.getRestrictions().forEach((purpRestriction) => {
1011
+ bitString += IntEncoder.encode(purpRestriction.purposeId, BitLength.purposeId);
1012
+ bitString += IntEncoder.encode(purpRestriction.restrictionType, BitLength.restrictionType);
1013
+ const vendors = prVector.getVendors(purpRestriction);
1014
+ const len = vendors.length;
1015
+ let numEntries = 0;
1016
+ let startId = 0;
1017
+ let rangeField = "";
1018
+ for (let i = 0; i < len; i++) {
1019
+ const vendorId = vendors[i];
1020
+ if (startId === 0) {
1021
+ numEntries++;
1022
+ startId = vendorId;
1023
+ }
1024
+ if (i === len - 1 || vendors[i + 1] > nextGvlVendor(vendorId, vendors[len - 1])) {
1025
+ const isRange = !(vendorId === startId);
1026
+ rangeField += BooleanEncoder.encode(isRange);
1027
+ rangeField += IntEncoder.encode(startId, BitLength.vendorId);
1028
+ if (isRange) {
1029
+ rangeField += IntEncoder.encode(vendorId, BitLength.vendorId);
1030
+ }
1031
+ startId = 0;
1032
+ }
1033
+ }
1034
+ bitString += IntEncoder.encode(numEntries, BitLength.numEntries);
1035
+ bitString += rangeField;
1036
+ });
1037
+ }
1038
+ return bitString;
1039
+ }
1040
+ static decode(encodedString) {
1041
+ let index = 0;
1042
+ const vector = new PurposeRestrictionVector();
1043
+ const numRestrictions = IntEncoder.decode(encodedString.substr(index, BitLength.numRestrictions), BitLength.numRestrictions);
1044
+ index += BitLength.numRestrictions;
1045
+ for (let i = 0; i < numRestrictions; i++) {
1046
+ const purposeId = IntEncoder.decode(encodedString.substr(index, BitLength.purposeId), BitLength.purposeId);
1047
+ index += BitLength.purposeId;
1048
+ const restrictionType = IntEncoder.decode(encodedString.substr(index, BitLength.restrictionType), BitLength.restrictionType);
1049
+ index += BitLength.restrictionType;
1050
+ const purposeRestriction = new PurposeRestriction(purposeId, restrictionType);
1051
+ const numEntries = IntEncoder.decode(encodedString.substr(index, BitLength.numEntries), BitLength.numEntries);
1052
+ index += BitLength.numEntries;
1053
+ for (let j = 0; j < numEntries; j++) {
1054
+ const isARange = BooleanEncoder.decode(encodedString.substr(index, BitLength.anyBoolean));
1055
+ index += BitLength.anyBoolean;
1056
+ const startOrOnlyVendorId = IntEncoder.decode(encodedString.substr(index, BitLength.vendorId), BitLength.vendorId);
1057
+ index += BitLength.vendorId;
1058
+ if (isARange) {
1059
+ const endVendorId = IntEncoder.decode(encodedString.substr(index, BitLength.vendorId), BitLength.vendorId);
1060
+ index += BitLength.vendorId;
1061
+ if (endVendorId < startOrOnlyVendorId) {
1062
+ throw new DecodingError(`Invalid RangeEntry: endVendorId ${endVendorId} is less than ${startOrOnlyVendorId}`);
1063
+ }
1064
+ for (let k = startOrOnlyVendorId; k <= endVendorId; k++) {
1065
+ vector.add(k, purposeRestriction);
1066
+ }
1067
+ } else {
1068
+ vector.add(startOrOnlyVendorId, purposeRestriction);
1069
+ }
1070
+ }
1071
+ }
1072
+ vector.bitLength = index;
1073
+ return vector;
1074
+ }
1075
+ }
1076
+ var VectorEncodingType;
1077
+ (function(VectorEncodingType2) {
1078
+ VectorEncodingType2[VectorEncodingType2["FIELD"] = 0] = "FIELD";
1079
+ VectorEncodingType2[VectorEncodingType2["RANGE"] = 1] = "RANGE";
1080
+ })(VectorEncodingType || (VectorEncodingType = {}));
1081
+ class VendorVectorEncoder {
1082
+ static encode(value) {
1083
+ const ranges = [];
1084
+ let range = [];
1085
+ let retrString = IntEncoder.encode(value.maxId, BitLength.maxId);
1086
+ let bitField = "";
1087
+ let rangeIsSmaller;
1088
+ const headerLength = BitLength.maxId + BitLength.encodingType;
1089
+ const bitFieldLength = headerLength + value.maxId;
1090
+ const minRangeLength = BitLength.vendorId * 2 + BitLength.singleOrRange + BitLength.numEntries;
1091
+ let rangeLength = headerLength + BitLength.numEntries;
1092
+ value.forEach((curValue, i) => {
1093
+ bitField += BooleanEncoder.encode(curValue);
1094
+ rangeIsSmaller = value.maxId > minRangeLength && rangeLength < bitFieldLength;
1095
+ if (rangeIsSmaller && curValue) {
1096
+ const nextValue = value.has(i + 1);
1097
+ if (!nextValue) {
1098
+ range.push(i);
1099
+ rangeLength += BitLength.vendorId;
1100
+ ranges.push(range);
1101
+ range = [];
1102
+ } else if (range.length === 0) {
1103
+ range.push(i);
1104
+ rangeLength += BitLength.singleOrRange;
1105
+ rangeLength += BitLength.vendorId;
1106
+ }
1107
+ }
1108
+ });
1109
+ if (rangeIsSmaller) {
1110
+ retrString += String(VectorEncodingType.RANGE);
1111
+ retrString += this.buildRangeEncoding(ranges);
1112
+ } else {
1113
+ retrString += String(VectorEncodingType.FIELD);
1114
+ retrString += bitField;
1115
+ }
1116
+ return retrString;
1117
+ }
1118
+ static decode(value, version) {
1119
+ let vector;
1120
+ let index = 0;
1121
+ const maxId = IntEncoder.decode(value.substr(index, BitLength.maxId), BitLength.maxId);
1122
+ index += BitLength.maxId;
1123
+ const encodingType = IntEncoder.decode(value.charAt(index), BitLength.encodingType);
1124
+ index += BitLength.encodingType;
1125
+ if (encodingType === VectorEncodingType.RANGE) {
1126
+ vector = new Vector();
1127
+ if (version === 1) {
1128
+ if (value.substr(index, 1) === "1") {
1129
+ throw new DecodingError("Unable to decode default consent=1");
1130
+ }
1131
+ index++;
1132
+ }
1133
+ const numEntries = IntEncoder.decode(value.substr(index, BitLength.numEntries), BitLength.numEntries);
1134
+ index += BitLength.numEntries;
1135
+ for (let i = 0; i < numEntries; i++) {
1136
+ const isIdRange = BooleanEncoder.decode(value.charAt(index));
1137
+ index += BitLength.singleOrRange;
1138
+ const firstId = IntEncoder.decode(value.substr(index, BitLength.vendorId), BitLength.vendorId);
1139
+ index += BitLength.vendorId;
1140
+ if (isIdRange) {
1141
+ const secondId = IntEncoder.decode(value.substr(index, BitLength.vendorId), BitLength.vendorId);
1142
+ index += BitLength.vendorId;
1143
+ for (let j = firstId; j <= secondId; j++) {
1144
+ vector.set(j);
1145
+ }
1146
+ } else {
1147
+ vector.set(firstId);
1148
+ }
1149
+ }
1150
+ } else {
1151
+ const bitField = value.substr(index, maxId);
1152
+ index += maxId;
1153
+ vector = FixedVectorEncoder.decode(bitField, maxId);
1154
+ }
1155
+ vector.bitLength = index;
1156
+ return vector;
1157
+ }
1158
+ static buildRangeEncoding(ranges) {
1159
+ const numEntries = ranges.length;
1160
+ let rangeString = IntEncoder.encode(numEntries, BitLength.numEntries);
1161
+ ranges.forEach((range) => {
1162
+ const single = range.length === 1;
1163
+ rangeString += BooleanEncoder.encode(!single);
1164
+ rangeString += IntEncoder.encode(range[0], BitLength.vendorId);
1165
+ if (!single) {
1166
+ rangeString += IntEncoder.encode(range[1], BitLength.vendorId);
1167
+ }
1168
+ });
1169
+ return rangeString;
1170
+ }
1171
+ }
1172
+ function FieldEncoderMap() {
1173
+ return {
1174
+ [Fields.version]: IntEncoder,
1175
+ [Fields.created]: DateEncoder,
1176
+ [Fields.lastUpdated]: DateEncoder,
1177
+ [Fields.cmpId]: IntEncoder,
1178
+ [Fields.cmpVersion]: IntEncoder,
1179
+ [Fields.consentScreen]: IntEncoder,
1180
+ [Fields.consentLanguage]: LangEncoder,
1181
+ [Fields.vendorListVersion]: IntEncoder,
1182
+ [Fields.policyVersion]: IntEncoder,
1183
+ [Fields.isServiceSpecific]: BooleanEncoder,
1184
+ [Fields.useNonStandardTexts]: BooleanEncoder,
1185
+ [Fields.specialFeatureOptins]: FixedVectorEncoder,
1186
+ [Fields.purposeConsents]: FixedVectorEncoder,
1187
+ [Fields.purposeLegitimateInterests]: FixedVectorEncoder,
1188
+ [Fields.purposeOneTreatment]: BooleanEncoder,
1189
+ [Fields.publisherCountryCode]: LangEncoder,
1190
+ [Fields.vendorConsents]: VendorVectorEncoder,
1191
+ [Fields.vendorLegitimateInterests]: VendorVectorEncoder,
1192
+ [Fields.publisherRestrictions]: PurposeRestrictionVectorEncoder,
1193
+ segmentType: IntEncoder,
1194
+ [Fields.vendorsDisclosed]: VendorVectorEncoder,
1195
+ [Fields.vendorsAllowed]: VendorVectorEncoder,
1196
+ [Fields.publisherConsents]: FixedVectorEncoder,
1197
+ [Fields.publisherLegitimateInterests]: FixedVectorEncoder,
1198
+ [Fields.numCustomPurposes]: IntEncoder,
1199
+ [Fields.publisherCustomConsents]: FixedVectorEncoder,
1200
+ [Fields.publisherCustomLegitimateInterests]: FixedVectorEncoder
1201
+ };
1202
+ }
1203
+ class FieldSequence {
1204
+ constructor() {
1205
+ __publicField(this, "1", {
1206
+ [Segment.CORE]: [
1207
+ Fields.version,
1208
+ Fields.created,
1209
+ Fields.lastUpdated,
1210
+ Fields.cmpId,
1211
+ Fields.cmpVersion,
1212
+ Fields.consentScreen,
1213
+ Fields.consentLanguage,
1214
+ Fields.vendorListVersion,
1215
+ Fields.purposeConsents,
1216
+ Fields.vendorConsents
1217
+ ]
1218
+ });
1219
+ __publicField(this, "2", {
1220
+ [Segment.CORE]: [
1221
+ Fields.version,
1222
+ Fields.created,
1223
+ Fields.lastUpdated,
1224
+ Fields.cmpId,
1225
+ Fields.cmpVersion,
1226
+ Fields.consentScreen,
1227
+ Fields.consentLanguage,
1228
+ Fields.vendorListVersion,
1229
+ Fields.policyVersion,
1230
+ Fields.isServiceSpecific,
1231
+ Fields.useNonStandardTexts,
1232
+ Fields.specialFeatureOptins,
1233
+ Fields.purposeConsents,
1234
+ Fields.purposeLegitimateInterests,
1235
+ Fields.purposeOneTreatment,
1236
+ Fields.publisherCountryCode,
1237
+ Fields.vendorConsents,
1238
+ Fields.vendorLegitimateInterests,
1239
+ Fields.publisherRestrictions
1240
+ ],
1241
+ [Segment.PUBLISHER_TC]: [
1242
+ Fields.publisherConsents,
1243
+ Fields.publisherLegitimateInterests,
1244
+ Fields.numCustomPurposes,
1245
+ Fields.publisherCustomConsents,
1246
+ Fields.publisherCustomLegitimateInterests
1247
+ ],
1248
+ [Segment.VENDORS_ALLOWED]: [
1249
+ Fields.vendorsAllowed
1250
+ ],
1251
+ [Segment.VENDORS_DISCLOSED]: [
1252
+ Fields.vendorsDisclosed
1253
+ ]
1254
+ });
1255
+ }
1256
+ }
1257
+ class SegmentSequence {
1258
+ constructor(tcModel, options) {
1259
+ __publicField(this, "1", [
1260
+ Segment.CORE
1261
+ ]);
1262
+ __publicField(this, "2", [
1263
+ Segment.CORE
1264
+ ]);
1265
+ if (tcModel.version === 2) {
1266
+ if (tcModel.isServiceSpecific) {
1267
+ this["2"].push(Segment.PUBLISHER_TC);
1268
+ } else {
1269
+ const isForVendors = !!(options && options.isForVendors);
1270
+ if (!isForVendors || tcModel[Fields.supportOOB] === true) {
1271
+ this["2"].push(Segment.VENDORS_DISCLOSED);
1272
+ }
1273
+ if (isForVendors) {
1274
+ if (tcModel[Fields.supportOOB] && tcModel[Fields.vendorsAllowed].size > 0) {
1275
+ this["2"].push(Segment.VENDORS_ALLOWED);
1276
+ }
1277
+ this["2"].push(Segment.PUBLISHER_TC);
1278
+ }
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ class SegmentEncoder {
1284
+ static encode(tcModel, segment) {
1285
+ let sequence;
1286
+ try {
1287
+ sequence = this.fieldSequence[String(tcModel.version)][segment];
1288
+ } catch (err) {
1289
+ throw new EncodingError(`Unable to encode version: ${tcModel.version}, segment: ${segment}`);
1290
+ }
1291
+ let bitField = "";
1292
+ if (segment !== Segment.CORE) {
1293
+ bitField = IntEncoder.encode(SegmentIDs.KEY_TO_ID[segment], BitLength.segmentType);
1294
+ }
1295
+ const fieldEncoderMap = FieldEncoderMap();
1296
+ sequence.forEach((key) => {
1297
+ const value = tcModel[key];
1298
+ const encoder = fieldEncoderMap[key];
1299
+ let numBits = BitLength[key];
1300
+ if (numBits === void 0) {
1301
+ if (this.isPublisherCustom(key)) {
1302
+ numBits = Number(tcModel[Fields.numCustomPurposes]);
1303
+ }
1304
+ }
1305
+ try {
1306
+ bitField += encoder.encode(value, numBits);
1307
+ } catch (err) {
1308
+ throw new EncodingError(`Error encoding ${segment}->${key}: ${err.message}`);
1309
+ }
1310
+ });
1311
+ return Base64Url.encode(bitField);
1312
+ }
1313
+ static decode(encodedString, tcModel, segment) {
1314
+ const bitField = Base64Url.decode(encodedString);
1315
+ let bStringIdx = 0;
1316
+ if (segment === Segment.CORE) {
1317
+ tcModel.version = IntEncoder.decode(bitField.substr(bStringIdx, BitLength[Fields.version]), BitLength[Fields.version]);
1318
+ }
1319
+ if (segment !== Segment.CORE) {
1320
+ bStringIdx += BitLength.segmentType;
1321
+ }
1322
+ const sequence = this.fieldSequence[String(tcModel.version)][segment];
1323
+ const fieldEncoderMap = FieldEncoderMap();
1324
+ sequence.forEach((key) => {
1325
+ const encoder = fieldEncoderMap[key];
1326
+ let numBits = BitLength[key];
1327
+ if (numBits === void 0) {
1328
+ if (this.isPublisherCustom(key)) {
1329
+ numBits = Number(tcModel[Fields.numCustomPurposes]);
1330
+ }
1331
+ }
1332
+ if (numBits !== 0) {
1333
+ const bits = bitField.substr(bStringIdx, numBits);
1334
+ if (encoder === VendorVectorEncoder) {
1335
+ tcModel[key] = encoder.decode(bits, tcModel.version);
1336
+ } else {
1337
+ tcModel[key] = encoder.decode(bits, numBits);
1338
+ }
1339
+ if (Number.isInteger(numBits)) {
1340
+ bStringIdx += numBits;
1341
+ } else if (Number.isInteger(tcModel[key].bitLength)) {
1342
+ bStringIdx += tcModel[key].bitLength;
1343
+ } else {
1344
+ throw new DecodingError(key);
1345
+ }
1346
+ }
1347
+ });
1348
+ return tcModel;
1349
+ }
1350
+ static isPublisherCustom(key) {
1351
+ return key.indexOf("publisherCustom") === 0;
1352
+ }
1353
+ }
1354
+ __publicField(SegmentEncoder, "fieldSequence", new FieldSequence());
1355
+ class SemanticPreEncoder {
1356
+ static process(tcModel, options) {
1357
+ const gvl = tcModel.gvl;
1358
+ if (!gvl) {
1359
+ throw new EncodingError("Unable to encode TCModel without a GVL");
1360
+ }
1361
+ if (!gvl.isReady) {
1362
+ throw new EncodingError("Unable to encode TCModel tcModel.gvl.readyPromise is not resolved");
1363
+ }
1364
+ tcModel = tcModel.clone();
1365
+ tcModel.consentLanguage = gvl.language.slice(0, 2).toUpperCase();
1366
+ if ((options == null ? void 0 : options.version) > 0 && (options == null ? void 0 : options.version) <= this.processor.length) {
1367
+ tcModel.version = options.version;
1368
+ } else {
1369
+ tcModel.version = this.processor.length;
1370
+ }
1371
+ const processorFunctionIndex = tcModel.version - 1;
1372
+ if (!this.processor[processorFunctionIndex]) {
1373
+ throw new EncodingError(`Invalid version: ${tcModel.version}`);
1374
+ }
1375
+ return this.processor[processorFunctionIndex](tcModel, gvl);
1376
+ }
1377
+ }
1378
+ __publicField(SemanticPreEncoder, "processor", [
1379
+ (tcModel) => tcModel,
1380
+ (tcModel, gvl) => {
1381
+ tcModel.publisherRestrictions.gvl = gvl;
1382
+ tcModel.purposeLegitimateInterests.unset([1, 3, 4, 5, 6]);
1383
+ const vectorToIntMap = /* @__PURE__ */ new Map();
1384
+ vectorToIntMap.set("legIntPurposes", tcModel.vendorLegitimateInterests);
1385
+ vectorToIntMap.set("purposes", tcModel.vendorConsents);
1386
+ vectorToIntMap.forEach((vector, gvlVendorKey) => {
1387
+ vector.forEach((value, vendorId) => {
1388
+ if (value) {
1389
+ const vendor = gvl.vendors[vendorId];
1390
+ if (!vendor || vendor.deletedDate) {
1391
+ vector.unset(vendorId);
1392
+ } else if (vendor[gvlVendorKey].length === 0) {
1393
+ if (gvlVendorKey === "legIntPurposes" && vendor["purposes"].length === 0 && vendor["legIntPurposes"].length === 0 && vendor["specialPurposes"].length > 0)
1394
+ ;
1395
+ else {
1396
+ if (tcModel.isServiceSpecific) {
1397
+ if (vendor.flexiblePurposes.length === 0) {
1398
+ vector.unset(vendorId);
1399
+ } else {
1400
+ const restrictions = tcModel.publisherRestrictions.getRestrictions(vendorId);
1401
+ let isValid = false;
1402
+ for (let i = 0, len = restrictions.length; i < len && !isValid; i++) {
1403
+ isValid = restrictions[i].restrictionType === RestrictionType.REQUIRE_CONSENT && gvlVendorKey === "purposes" || restrictions[i].restrictionType === RestrictionType.REQUIRE_LI && gvlVendorKey === "legIntPurposes";
1404
+ }
1405
+ if (!isValid) {
1406
+ vector.unset(vendorId);
1407
+ }
1408
+ }
1409
+ } else {
1410
+ vector.unset(vendorId);
1411
+ }
1412
+ }
1413
+ }
1414
+ }
1415
+ });
1416
+ });
1417
+ tcModel.vendorsDisclosed.set(gvl.vendors);
1418
+ return tcModel;
1419
+ }
1420
+ ]);
1421
+ class Json {
1422
+ static absCall(url, body, sendCookies, timeout) {
1423
+ return new Promise((resolve, reject) => {
1424
+ const req = new XMLHttpRequest();
1425
+ const onLoad = () => {
1426
+ if (req.readyState == XMLHttpRequest.DONE) {
1427
+ if (req.status >= 200 && req.status < 300) {
1428
+ let response = req.response;
1429
+ if (typeof response === "string") {
1430
+ try {
1431
+ response = JSON.parse(response);
1432
+ } catch (e) {
1433
+ }
1434
+ }
1435
+ resolve(response);
1436
+ } else {
1437
+ reject(new Error(`HTTP Status: ${req.status} response type: ${req.responseType}`));
1438
+ }
1439
+ }
1440
+ };
1441
+ const onError = () => {
1442
+ reject(new Error("error"));
1443
+ };
1444
+ const onAbort = () => {
1445
+ reject(new Error("aborted"));
1446
+ };
1447
+ const onTimeout = () => {
1448
+ reject(new Error("Timeout " + timeout + "ms " + url));
1449
+ };
1450
+ req.withCredentials = sendCookies;
1451
+ req.addEventListener("load", onLoad);
1452
+ req.addEventListener("error", onError);
1453
+ req.addEventListener("abort", onAbort);
1454
+ if (body === null) {
1455
+ req.open("GET", url, true);
1456
+ } else {
1457
+ req.open("POST", url, true);
1458
+ }
1459
+ req.responseType = "json";
1460
+ req.timeout = timeout;
1461
+ req.ontimeout = onTimeout;
1462
+ req.send(body);
1463
+ });
1464
+ }
1465
+ /**
1466
+ * @static
1467
+ * @param {string} url - full path to POST to
1468
+ * @param {object} body - JSON object to post
1469
+ * @param {boolean} sendCookies - Whether or not to send the XMLHttpRequest with credentials or not
1470
+ * @param {number} [timeout] - optional timeout in milliseconds
1471
+ * @return {Promise<object>} - if the server responds the response will be returned here
1472
+ */
1473
+ static post(url, body, sendCookies = false, timeout = 0) {
1474
+ return this.absCall(url, JSON.stringify(body), sendCookies, timeout);
1475
+ }
1476
+ /**
1477
+ * @static
1478
+ * @param {string} url - full path to the json
1479
+ * @param {boolean} sendCookies - Whether or not to send the XMLHttpRequest with credentials or not
1480
+ * @param {number} [timeout] - optional timeout in milliseconds
1481
+ * @return {Promise<object>} - resolves with parsed JSON
1482
+ */
1483
+ static fetch(url, sendCookies = false, timeout = 0) {
1484
+ return this.absCall(url, null, sendCookies, timeout);
1485
+ }
1486
+ }
1487
+ const _GVL = class _GVL2 extends Cloneable {
1488
+ /**
1489
+ * @param {VersionOrVendorList} [versionOrVendorList] - can be either a
1490
+ * [[VendorList]] object or a version number represented as a string or
1491
+ * number to download. If nothing is passed the latest version of the GVL
1492
+ * will be loaded
1493
+ */
1494
+ constructor(versionOrVendorList) {
1495
+ super();
1496
+ __publicField(this, "readyPromise");
1497
+ __publicField(this, "gvlSpecificationVersion");
1498
+ __publicField(this, "vendorListVersion");
1499
+ __publicField(this, "tcfPolicyVersion");
1500
+ __publicField(this, "lastUpdated");
1501
+ __publicField(this, "purposes");
1502
+ __publicField(this, "specialPurposes");
1503
+ __publicField(this, "features");
1504
+ __publicField(this, "specialFeatures");
1505
+ __publicField(this, "isReady_", false);
1506
+ __publicField(this, "vendors_");
1507
+ __publicField(this, "vendorIds");
1508
+ __publicField(this, "fullVendorList");
1509
+ __publicField(this, "byPurposeVendorMap");
1510
+ __publicField(this, "bySpecialPurposeVendorMap");
1511
+ __publicField(this, "byFeatureVendorMap");
1512
+ __publicField(this, "bySpecialFeatureVendorMap");
1513
+ __publicField(this, "stacks");
1514
+ __publicField(this, "dataCategories");
1515
+ __publicField(this, "lang_");
1516
+ __publicField(this, "cacheLang_");
1517
+ __publicField(this, "isLatest", false);
1518
+ let url = _GVL2.baseUrl;
1519
+ this.lang_ = _GVL2.DEFAULT_LANGUAGE;
1520
+ this.cacheLang_ = _GVL2.DEFAULT_LANGUAGE;
1521
+ if (this.isVendorList(versionOrVendorList)) {
1522
+ this.populate(versionOrVendorList);
1523
+ this.readyPromise = Promise.resolve();
1524
+ } else {
1525
+ if (!url) {
1526
+ throw new GVLError("must specify GVL.baseUrl before loading GVL json");
1527
+ }
1528
+ if (versionOrVendorList > 0) {
1529
+ const version = versionOrVendorList;
1530
+ if (_GVL2.CACHE.has(version)) {
1531
+ this.populate(_GVL2.CACHE.get(version));
1532
+ this.readyPromise = Promise.resolve();
1533
+ } else {
1534
+ url += _GVL2.versionedFilename.replace("[VERSION]", String(version));
1535
+ this.readyPromise = this.fetchJson(url);
1536
+ }
1537
+ } else {
1538
+ if (_GVL2.CACHE.has(_GVL2.LATEST_CACHE_KEY)) {
1539
+ this.populate(_GVL2.CACHE.get(_GVL2.LATEST_CACHE_KEY));
1540
+ this.readyPromise = Promise.resolve();
1541
+ } else {
1542
+ this.isLatest = true;
1543
+ this.readyPromise = this.fetchJson(url + _GVL2.latestFilename);
1544
+ }
1545
+ }
1546
+ }
1547
+ }
1548
+ /**
1549
+ * baseUrl - Entities using the vendor-list.json are required by the iab to
1550
+ * host their own copy of it to reduce the load on the iab's infrastructure
1551
+ * so a 'base' url must be set to be put together with the versioning scheme
1552
+ * of the filenames.
1553
+ *
1554
+ * @static
1555
+ * @param {string} url - the base url to load the vendor-list.json from. This is
1556
+ * broken out from the filename because it follows a different scheme for
1557
+ * latest file vs versioned files.
1558
+ *
1559
+ * @throws {GVLError} - If the url is http[s]://vendorlist.consensu.org/...
1560
+ * this will throw an error. IAB Europe requires that that CMPs and Vendors
1561
+ * cache their own copies of the GVL to minimize load on their
1562
+ * infrastructure. For more information regarding caching of the
1563
+ * vendor-list.json, please see [the TCF documentation on 'Caching the Global
1564
+ * Vendor List'
1565
+ * ](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20Consent%20string%20and%20vendor%20list%20formats%20v2.md#caching-the-global-vendor-list)
1566
+ */
1567
+ static set baseUrl(url) {
1568
+ const notValid = /^https?:\/\/vendorlist\.consensu\.org\//;
1569
+ if (notValid.test(url)) {
1570
+ throw new GVLError("Invalid baseUrl! You may not pull directly from vendorlist.consensu.org and must provide your own cache");
1571
+ }
1572
+ if (url.length > 0 && url[url.length - 1] !== "/") {
1573
+ url += "/";
1574
+ }
1575
+ this.baseUrl_ = url;
1576
+ }
1577
+ /**
1578
+ * baseUrl - Entities using the vendor-list.json are required by the iab to
1579
+ * host their own copy of it to reduce the load on the iab's infrastructure
1580
+ * so a 'base' url must be set to be put together with the versioning scheme
1581
+ * of the filenames.
1582
+ *
1583
+ * @static
1584
+ * @return {string} - returns the previously set baseUrl, the default is
1585
+ * `undefined`
1586
+ */
1587
+ static get baseUrl() {
1588
+ return this.baseUrl_;
1589
+ }
1590
+ /**
1591
+ * emptyLanguageCache
1592
+ *
1593
+ * @param {string} [lang] - Optional language code to remove from
1594
+ * the cache. Should be one of the languages in GVL.consentLanguages set.
1595
+ * If not then the whole cache will be deleted.
1596
+ * @return {boolean} - true if anything was deleted from the cache
1597
+ */
1598
+ static emptyLanguageCache(lang) {
1599
+ let result = false;
1600
+ if (lang == null && _GVL2.LANGUAGE_CACHE.size > 0) {
1601
+ _GVL2.LANGUAGE_CACHE = /* @__PURE__ */ new Map();
1602
+ result = true;
1603
+ } else if (typeof lang === "string" && this.consentLanguages.has(lang.toUpperCase())) {
1604
+ _GVL2.LANGUAGE_CACHE.delete(lang.toUpperCase());
1605
+ result = true;
1606
+ }
1607
+ return result;
1608
+ }
1609
+ /**
1610
+ * emptyCache
1611
+ *
1612
+ * @param {number} [vendorListVersion] - version of the vendor list to delete
1613
+ * from the cache. If none is specified then the whole cache is deleted.
1614
+ * @return {boolean} - true if anything was deleted from the cache
1615
+ */
1616
+ static emptyCache(vendorListVersion) {
1617
+ let retr = false;
1618
+ if (Number.isInteger(vendorListVersion) && vendorListVersion >= 0) {
1619
+ _GVL2.CACHE.delete(vendorListVersion);
1620
+ retr = true;
1621
+ } else if (vendorListVersion === void 0) {
1622
+ _GVL2.CACHE = /* @__PURE__ */ new Map();
1623
+ retr = true;
1624
+ }
1625
+ return retr;
1626
+ }
1627
+ cacheLanguage() {
1628
+ if (!_GVL2.LANGUAGE_CACHE.has(this.cacheLang_)) {
1629
+ _GVL2.LANGUAGE_CACHE.set(this.cacheLang_, {
1630
+ purposes: this.purposes,
1631
+ specialPurposes: this.specialPurposes,
1632
+ features: this.features,
1633
+ specialFeatures: this.specialFeatures,
1634
+ stacks: this.stacks,
1635
+ dataCategories: this.dataCategories
1636
+ });
1637
+ }
1638
+ }
1639
+ async fetchJson(url) {
1640
+ try {
1641
+ this.populate(await Json.fetch(url));
1642
+ } catch (err) {
1643
+ throw new GVLError(err.message);
1644
+ }
1645
+ }
1646
+ /**
1647
+ * getJson - Method for getting the JSON that was downloaded to created this
1648
+ * `GVL` object
1649
+ *
1650
+ * @return {VendorList} - The basic JSON structure without the extra
1651
+ * functionality and methods of this class.
1652
+ */
1653
+ getJson() {
1654
+ return JSON.parse(JSON.stringify({
1655
+ gvlSpecificationVersion: this.gvlSpecificationVersion,
1656
+ vendorListVersion: this.vendorListVersion,
1657
+ tcfPolicyVersion: this.tcfPolicyVersion,
1658
+ lastUpdated: this.lastUpdated,
1659
+ purposes: this.purposes,
1660
+ specialPurposes: this.specialPurposes,
1661
+ features: this.features,
1662
+ specialFeatures: this.specialFeatures,
1663
+ stacks: this.stacks,
1664
+ dataCategories: this.dataCategories,
1665
+ vendors: this.fullVendorList
1666
+ }));
1667
+ }
1668
+ /**
1669
+ * changeLanguage - retrieves the purpose language translation and sets the
1670
+ * internal language variable
1671
+ *
1672
+ * @param {string} lang - language code to change language to
1673
+ * @return {Promise<void | GVLError>} - returns the `readyPromise` and
1674
+ * resolves when this GVL is populated with the data from the language file.
1675
+ */
1676
+ async changeLanguage(lang) {
1677
+ let parsedLanguage = lang;
1678
+ try {
1679
+ parsedLanguage = _GVL2.consentLanguages.parseLanguage(lang);
1680
+ } catch (e) {
1681
+ throw new GVLError("Error during parsing the language: " + e.message);
1682
+ }
1683
+ const cacheLang = lang.toUpperCase();
1684
+ if (parsedLanguage.toLowerCase() === _GVL2.DEFAULT_LANGUAGE.toLowerCase() && !_GVL2.LANGUAGE_CACHE.has(cacheLang)) {
1685
+ return;
1686
+ }
1687
+ if (parsedLanguage !== this.lang_) {
1688
+ this.lang_ = parsedLanguage;
1689
+ if (_GVL2.LANGUAGE_CACHE.has(cacheLang)) {
1690
+ const cached = _GVL2.LANGUAGE_CACHE.get(cacheLang);
1691
+ for (const prop in cached) {
1692
+ if (cached.hasOwnProperty(prop)) {
1693
+ this[prop] = cached[prop];
1694
+ }
1695
+ }
1696
+ } else {
1697
+ const url = _GVL2.baseUrl + _GVL2.languageFilename.replace("[LANG]", this.lang_.toLowerCase());
1698
+ try {
1699
+ await this.fetchJson(url);
1700
+ this.cacheLang_ = cacheLang;
1701
+ this.cacheLanguage();
1702
+ } catch (err) {
1703
+ throw new GVLError("unable to load language: " + err.message);
1704
+ }
1705
+ }
1706
+ }
1707
+ }
1708
+ get language() {
1709
+ return this.lang_;
1710
+ }
1711
+ isVendorList(gvlObject) {
1712
+ return gvlObject !== void 0 && gvlObject.vendors !== void 0;
1713
+ }
1714
+ populate(gvlObject) {
1715
+ this.purposes = gvlObject.purposes;
1716
+ this.specialPurposes = gvlObject.specialPurposes;
1717
+ this.features = gvlObject.features;
1718
+ this.specialFeatures = gvlObject.specialFeatures;
1719
+ this.stacks = gvlObject.stacks;
1720
+ this.dataCategories = gvlObject.dataCategories;
1721
+ if (this.isVendorList(gvlObject)) {
1722
+ this.gvlSpecificationVersion = gvlObject.gvlSpecificationVersion;
1723
+ this.tcfPolicyVersion = gvlObject.tcfPolicyVersion;
1724
+ this.vendorListVersion = gvlObject.vendorListVersion;
1725
+ this.lastUpdated = gvlObject.lastUpdated;
1726
+ if (typeof this.lastUpdated === "string") {
1727
+ this.lastUpdated = new Date(this.lastUpdated);
1728
+ }
1729
+ this.vendors_ = gvlObject.vendors;
1730
+ this.fullVendorList = gvlObject.vendors;
1731
+ this.mapVendors();
1732
+ this.isReady_ = true;
1733
+ if (this.isLatest) {
1734
+ _GVL2.CACHE.set(_GVL2.LATEST_CACHE_KEY, this.getJson());
1735
+ }
1736
+ if (!_GVL2.CACHE.has(this.vendorListVersion)) {
1737
+ _GVL2.CACHE.set(this.vendorListVersion, this.getJson());
1738
+ }
1739
+ }
1740
+ this.cacheLanguage();
1741
+ }
1742
+ mapVendors(vendorIds) {
1743
+ this.byPurposeVendorMap = {};
1744
+ this.bySpecialPurposeVendorMap = {};
1745
+ this.byFeatureVendorMap = {};
1746
+ this.bySpecialFeatureVendorMap = {};
1747
+ Object.keys(this.purposes).forEach((purposeId) => {
1748
+ this.byPurposeVendorMap[purposeId] = {
1749
+ legInt: /* @__PURE__ */ new Set(),
1750
+ consent: /* @__PURE__ */ new Set(),
1751
+ flexible: /* @__PURE__ */ new Set()
1752
+ };
1753
+ });
1754
+ Object.keys(this.specialPurposes).forEach((purposeId) => {
1755
+ this.bySpecialPurposeVendorMap[purposeId] = /* @__PURE__ */ new Set();
1756
+ });
1757
+ Object.keys(this.features).forEach((featureId) => {
1758
+ this.byFeatureVendorMap[featureId] = /* @__PURE__ */ new Set();
1759
+ });
1760
+ Object.keys(this.specialFeatures).forEach((featureId) => {
1761
+ this.bySpecialFeatureVendorMap[featureId] = /* @__PURE__ */ new Set();
1762
+ });
1763
+ if (!Array.isArray(vendorIds)) {
1764
+ vendorIds = Object.keys(this.fullVendorList).map((vId) => +vId);
1765
+ }
1766
+ this.vendorIds = new Set(vendorIds);
1767
+ this.vendors_ = vendorIds.reduce((vendors, vendorId) => {
1768
+ const vendor = this.vendors_[String(vendorId)];
1769
+ if (vendor && vendor.deletedDate === void 0) {
1770
+ vendor.purposes.forEach((purposeId) => {
1771
+ const purpGroup = this.byPurposeVendorMap[String(purposeId)];
1772
+ purpGroup.consent.add(vendorId);
1773
+ });
1774
+ vendor.specialPurposes.forEach((purposeId) => {
1775
+ this.bySpecialPurposeVendorMap[String(purposeId)].add(vendorId);
1776
+ });
1777
+ vendor.legIntPurposes.forEach((purposeId) => {
1778
+ this.byPurposeVendorMap[String(purposeId)].legInt.add(vendorId);
1779
+ });
1780
+ if (vendor.flexiblePurposes) {
1781
+ vendor.flexiblePurposes.forEach((purposeId) => {
1782
+ this.byPurposeVendorMap[String(purposeId)].flexible.add(vendorId);
1783
+ });
1784
+ }
1785
+ vendor.features.forEach((featureId) => {
1786
+ this.byFeatureVendorMap[String(featureId)].add(vendorId);
1787
+ });
1788
+ vendor.specialFeatures.forEach((featureId) => {
1789
+ this.bySpecialFeatureVendorMap[String(featureId)].add(vendorId);
1790
+ });
1791
+ vendors[vendorId] = vendor;
1792
+ }
1793
+ return vendors;
1794
+ }, {});
1795
+ }
1796
+ getFilteredVendors(purposeOrFeature, id, subType, special) {
1797
+ const properPurposeOrFeature = purposeOrFeature.charAt(0).toUpperCase() + purposeOrFeature.slice(1);
1798
+ let vendorSet;
1799
+ const retr = {};
1800
+ if (purposeOrFeature === "purpose" && subType) {
1801
+ vendorSet = this["by" + properPurposeOrFeature + "VendorMap"][String(id)][subType];
1802
+ } else {
1803
+ vendorSet = this["by" + (special ? "Special" : "") + properPurposeOrFeature + "VendorMap"][String(id)];
1804
+ }
1805
+ vendorSet.forEach((vendorId) => {
1806
+ retr[String(vendorId)] = this.vendors[String(vendorId)];
1807
+ });
1808
+ return retr;
1809
+ }
1810
+ /**
1811
+ * getVendorsWithConsentPurpose
1812
+ *
1813
+ * @param {number} purposeId
1814
+ * @return {IntMap<Vendor>} - list of vendors that have declared the consent purpose id
1815
+ */
1816
+ getVendorsWithConsentPurpose(purposeId) {
1817
+ return this.getFilteredVendors("purpose", purposeId, "consent");
1818
+ }
1819
+ /**
1820
+ * getVendorsWithLegIntPurpose
1821
+ *
1822
+ * @param {number} purposeId
1823
+ * @return {IntMap<Vendor>} - list of vendors that have declared the legInt (Legitimate Interest) purpose id
1824
+ */
1825
+ getVendorsWithLegIntPurpose(purposeId) {
1826
+ return this.getFilteredVendors("purpose", purposeId, "legInt");
1827
+ }
1828
+ /**
1829
+ * getVendorsWithFlexiblePurpose
1830
+ *
1831
+ * @param {number} purposeId
1832
+ * @return {IntMap<Vendor>} - list of vendors that have declared the flexible purpose id
1833
+ */
1834
+ getVendorsWithFlexiblePurpose(purposeId) {
1835
+ return this.getFilteredVendors("purpose", purposeId, "flexible");
1836
+ }
1837
+ /**
1838
+ * getVendorsWithSpecialPurpose
1839
+ *
1840
+ * @param {number} specialPurposeId
1841
+ * @return {IntMap<Vendor>} - list of vendors that have declared the special purpose id
1842
+ */
1843
+ getVendorsWithSpecialPurpose(specialPurposeId) {
1844
+ return this.getFilteredVendors("purpose", specialPurposeId, void 0, true);
1845
+ }
1846
+ /**
1847
+ * getVendorsWithFeature
1848
+ *
1849
+ * @param {number} featureId
1850
+ * @return {IntMap<Vendor>} - list of vendors that have declared the feature id
1851
+ */
1852
+ getVendorsWithFeature(featureId) {
1853
+ return this.getFilteredVendors("feature", featureId);
1854
+ }
1855
+ /**
1856
+ * getVendorsWithSpecialFeature
1857
+ *
1858
+ * @param {number} specialFeatureId
1859
+ * @return {IntMap<Vendor>} - list of vendors that have declared the special feature id
1860
+ */
1861
+ getVendorsWithSpecialFeature(specialFeatureId) {
1862
+ return this.getFilteredVendors("feature", specialFeatureId, void 0, true);
1863
+ }
1864
+ /**
1865
+ * vendors
1866
+ *
1867
+ * @return {IntMap<Vendor>} - the list of vendors as it would on the JSON file
1868
+ * except if `narrowVendorsTo` was called, it would be that narrowed list
1869
+ */
1870
+ get vendors() {
1871
+ return this.vendors_;
1872
+ }
1873
+ /**
1874
+ * narrowVendorsTo - narrows vendors represented in this GVL to the list of ids passed in
1875
+ *
1876
+ * @param {number[]} vendorIds - list of ids to narrow this GVL to
1877
+ * @return {void}
1878
+ */
1879
+ narrowVendorsTo(vendorIds) {
1880
+ this.mapVendors(vendorIds);
1881
+ }
1882
+ /**
1883
+ * isReady - Whether or not this instance is ready to be used. This will be
1884
+ * immediately and synchronously true if a vendorlist object is passed into
1885
+ * the constructor or once the JSON vendorllist is retrieved.
1886
+ *
1887
+ * @return {boolean} whether or not the instance is ready to be interacted
1888
+ * with and all the data is populated
1889
+ */
1890
+ get isReady() {
1891
+ return this.isReady_;
1892
+ }
1893
+ /**
1894
+ * clone - overrides base `clone()` method since GVL is a special class that
1895
+ * represents a JSON structure with some additional functionality.
1896
+ *
1897
+ * @return {GVL}
1898
+ */
1899
+ clone() {
1900
+ const result = new _GVL2(this.getJson());
1901
+ if (this.lang_ !== _GVL2.DEFAULT_LANGUAGE) {
1902
+ result.changeLanguage(this.lang_);
1903
+ }
1904
+ return result;
1905
+ }
1906
+ static isInstanceOf(questionableInstance) {
1907
+ const isSo = typeof questionableInstance === "object";
1908
+ return isSo && typeof questionableInstance.narrowVendorsTo === "function";
1909
+ }
1910
+ };
1911
+ __publicField(_GVL, "LANGUAGE_CACHE", /* @__PURE__ */ new Map());
1912
+ __publicField(_GVL, "CACHE", /* @__PURE__ */ new Map());
1913
+ __publicField(_GVL, "LATEST_CACHE_KEY", 0);
1914
+ __publicField(_GVL, "DEFAULT_LANGUAGE", "EN");
1915
+ __publicField(_GVL, "consentLanguages", new ConsentLanguages());
1916
+ __publicField(_GVL, "baseUrl_");
1917
+ __publicField(_GVL, "latestFilename", "vendor-list.json");
1918
+ __publicField(_GVL, "versionedFilename", "archives/vendor-list-v[VERSION].json");
1919
+ __publicField(_GVL, "languageFilename", "purposes-[LANG].json");
1920
+ let GVL = _GVL;
1921
+ class TCModel extends Cloneable {
1922
+ /**
1923
+ * Constructs the TCModel. Passing a [[GVL]] is optional when constructing
1924
+ * as this TCModel may be constructed from decoding an existing encoded
1925
+ * TCString.
1926
+ *
1927
+ * @param {GVL} [gvl]
1928
+ */
1929
+ constructor(gvl) {
1930
+ super();
1931
+ __publicField(this, "isServiceSpecific_", false);
1932
+ __publicField(this, "supportOOB_", true);
1933
+ __publicField(this, "useNonStandardTexts_", false);
1934
+ __publicField(this, "purposeOneTreatment_", false);
1935
+ __publicField(this, "publisherCountryCode_", "AA");
1936
+ __publicField(this, "version_", 2);
1937
+ __publicField(this, "consentScreen_", 0);
1938
+ __publicField(this, "policyVersion_", 4);
1939
+ __publicField(this, "consentLanguage_", "EN");
1940
+ __publicField(this, "cmpId_", 0);
1941
+ __publicField(this, "cmpVersion_", 0);
1942
+ __publicField(this, "vendorListVersion_", 0);
1943
+ __publicField(this, "numCustomPurposes_", 0);
1944
+ __publicField(this, "gvl_");
1945
+ __publicField(this, "created");
1946
+ __publicField(this, "lastUpdated");
1947
+ __publicField(this, "specialFeatureOptins", new Vector());
1948
+ __publicField(this, "purposeConsents", new Vector());
1949
+ __publicField(this, "purposeLegitimateInterests", new Vector());
1950
+ __publicField(this, "publisherConsents", new Vector());
1951
+ __publicField(this, "publisherLegitimateInterests", new Vector());
1952
+ __publicField(this, "publisherCustomConsents", new Vector());
1953
+ __publicField(this, "publisherCustomLegitimateInterests", new Vector());
1954
+ __publicField(this, "customPurposes");
1955
+ __publicField(this, "vendorConsents", new Vector());
1956
+ __publicField(this, "vendorLegitimateInterests", new Vector());
1957
+ __publicField(this, "vendorsDisclosed", new Vector());
1958
+ __publicField(this, "vendorsAllowed", new Vector());
1959
+ __publicField(this, "publisherRestrictions", new PurposeRestrictionVector());
1960
+ if (gvl) {
1961
+ this.gvl = gvl;
1962
+ }
1963
+ this.updated();
1964
+ }
1965
+ /**
1966
+ * sets the [[GVL]] with side effects of also setting the `vendorListVersion`, `policyVersion`, and `consentLanguage`
1967
+ * @param {GVL} gvl
1968
+ */
1969
+ set gvl(gvl) {
1970
+ if (!GVL.isInstanceOf(gvl)) {
1971
+ gvl = new GVL(gvl);
1972
+ }
1973
+ this.gvl_ = gvl;
1974
+ this.publisherRestrictions.gvl = gvl;
1975
+ }
1976
+ /**
1977
+ * @return {GVL} the gvl instance set on this TCModel instance
1978
+ */
1979
+ get gvl() {
1980
+ return this.gvl_;
1981
+ }
1982
+ /**
1983
+ * @param {number} integer - A unique ID will be assigned to each Consent
1984
+ * Manager Provider (CMP) from the iab.
1985
+ *
1986
+ * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid.
1987
+ */
1988
+ set cmpId(integer) {
1989
+ integer = Number(integer);
1990
+ if (Number.isInteger(integer) && integer > 1) {
1991
+ this.cmpId_ = integer;
1992
+ } else {
1993
+ throw new TCModelError("cmpId", integer);
1994
+ }
1995
+ }
1996
+ get cmpId() {
1997
+ return this.cmpId_;
1998
+ }
1999
+ /**
2000
+ * Each change to an operating CMP should receive a
2001
+ * new version number, for logging proof of consent. CmpVersion defined by
2002
+ * each CMP.
2003
+ *
2004
+ * @param {number} integer
2005
+ *
2006
+ * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid.
2007
+ */
2008
+ set cmpVersion(integer) {
2009
+ integer = Number(integer);
2010
+ if (Number.isInteger(integer) && integer > -1) {
2011
+ this.cmpVersion_ = integer;
2012
+ } else {
2013
+ throw new TCModelError("cmpVersion", integer);
2014
+ }
2015
+ }
2016
+ get cmpVersion() {
2017
+ return this.cmpVersion_;
2018
+ }
2019
+ /**
2020
+ * The screen number is CMP and CmpVersion
2021
+ * specific, and is for logging proof of consent.(For example, a CMP could
2022
+ * keep records so that a publisher can request information about the context
2023
+ * in which consent was gathered.)
2024
+ *
2025
+ * @param {number} integer
2026
+ *
2027
+ * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid.
2028
+ */
2029
+ set consentScreen(integer) {
2030
+ integer = Number(integer);
2031
+ if (Number.isInteger(integer) && integer > -1) {
2032
+ this.consentScreen_ = integer;
2033
+ } else {
2034
+ throw new TCModelError("consentScreen", integer);
2035
+ }
2036
+ }
2037
+ get consentScreen() {
2038
+ return this.consentScreen_;
2039
+ }
2040
+ /**
2041
+ * @param {string} lang - [two-letter ISO 639-1 language
2042
+ * code](http://www.loc.gov/standards/iso639-2/php/code_list.php) in which
2043
+ * the CMP UI was presented
2044
+ *
2045
+ * @throws {TCModelError} if the value is not a length-2 string of alpha characters
2046
+ */
2047
+ set consentLanguage(lang) {
2048
+ this.consentLanguage_ = lang;
2049
+ }
2050
+ get consentLanguage() {
2051
+ return this.consentLanguage_;
2052
+ }
2053
+ /**
2054
+ * @param {string} countryCode - [two-letter ISO 3166-1 alpha-2 country
2055
+ * code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the publisher,
2056
+ * determined by the CMP-settings of the publisher.
2057
+ *
2058
+ * @throws {TCModelError} if the value is not a length-2 string of alpha characters
2059
+ */
2060
+ set publisherCountryCode(countryCode) {
2061
+ if (/^([A-z]){2}$/.test(countryCode)) {
2062
+ this.publisherCountryCode_ = countryCode.toUpperCase();
2063
+ } else {
2064
+ throw new TCModelError("publisherCountryCode", countryCode);
2065
+ }
2066
+ }
2067
+ get publisherCountryCode() {
2068
+ return this.publisherCountryCode_;
2069
+ }
2070
+ /**
2071
+ * Version of the GVL used to create this TCModel. Global
2072
+ * Vendor List versions will be released periodically.
2073
+ *
2074
+ * @param {number} integer
2075
+ *
2076
+ * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid.
2077
+ */
2078
+ set vendorListVersion(integer) {
2079
+ integer = Number(integer) >> 0;
2080
+ if (integer < 0) {
2081
+ throw new TCModelError("vendorListVersion", integer);
2082
+ } else {
2083
+ this.vendorListVersion_ = integer;
2084
+ }
2085
+ }
2086
+ get vendorListVersion() {
2087
+ if (this.gvl) {
2088
+ return this.gvl.vendorListVersion;
2089
+ } else {
2090
+ return this.vendorListVersion_;
2091
+ }
2092
+ }
2093
+ /**
2094
+ * From the corresponding field in the GVL that was
2095
+ * used for obtaining consent. A new policy version invalidates existing
2096
+ * strings and requires CMPs to re-establish transparency and consent from
2097
+ * users.
2098
+ *
2099
+ * If a TCF policy version number is different from the one from the latest
2100
+ * GVL, the CMP must re-establish transparency and consent.
2101
+ *
2102
+ * @param {number} num - You do not need to set this. This comes
2103
+ * directly from the [[GVL]].
2104
+ *
2105
+ */
2106
+ set policyVersion(num) {
2107
+ this.policyVersion_ = parseInt(num, 10);
2108
+ if (this.policyVersion_ < 0) {
2109
+ throw new TCModelError("policyVersion", num);
2110
+ }
2111
+ }
2112
+ get policyVersion() {
2113
+ if (this.gvl) {
2114
+ return this.gvl.tcfPolicyVersion;
2115
+ } else {
2116
+ return this.policyVersion_;
2117
+ }
2118
+ }
2119
+ set version(num) {
2120
+ this.version_ = parseInt(num, 10);
2121
+ }
2122
+ get version() {
2123
+ return this.version_;
2124
+ }
2125
+ /**
2126
+ * Whether the signals encoded in this TC String were from site-specific
2127
+ * storage `true` versus ‘global’ consensu.org shared storage `false`. A
2128
+ * string intended to be stored in global/shared scope but the CMP is unable
2129
+ * to store due to a user agent not accepting third-party cookies would be
2130
+ * considered site-specific `true`.
2131
+ *
2132
+ * @param {boolean} bool - value to set. Some changes to other fields in this
2133
+ * model will automatically change this value like adding publisher
2134
+ * restrictions.
2135
+ */
2136
+ set isServiceSpecific(bool) {
2137
+ this.isServiceSpecific_ = bool;
2138
+ }
2139
+ get isServiceSpecific() {
2140
+ return this.isServiceSpecific_;
2141
+ }
2142
+ /**
2143
+ * Non-standard stacks means that a CMP is using publisher-customized stack
2144
+ * descriptions. Stacks (in terms of purposes in a stack) are pre-set by the
2145
+ * IAB. As are titles. Descriptions are pre-set, but publishers can customize
2146
+ * them. If they do, they need to set this bit to indicate that they've
2147
+ * customized descriptions.
2148
+ *
2149
+ * @param {boolean} bool - value to set
2150
+ */
2151
+ set useNonStandardTexts(bool) {
2152
+ this.useNonStandardTexts_ = bool;
2153
+ }
2154
+ get useNonStandardTexts() {
2155
+ return this.useNonStandardTexts_;
2156
+ }
2157
+ /**
2158
+ * Whether or not this publisher supports OOB signaling. On Global TC String
2159
+ * OOB Vendors Disclosed will be included if the publish wishes to no allow
2160
+ * these vendors they should set this to false.
2161
+ * @param {boolean} bool - value to set
2162
+ */
2163
+ set supportOOB(bool) {
2164
+ this.supportOOB_ = bool;
2165
+ }
2166
+ get supportOOB() {
2167
+ return this.supportOOB_;
2168
+ }
2169
+ /**
2170
+ * `false` There is no special Purpose 1 status.
2171
+ * Purpose 1 was disclosed normally (consent) as expected by Policy. `true`
2172
+ * Purpose 1 not disclosed at all. CMPs use PublisherCC to indicate the
2173
+ * publisher’s country of establishment to help Vendors determine whether the
2174
+ * vendor requires Purpose 1 consent. In global scope TC strings, this field
2175
+ * must always have a value of `false`. When a CMP encounters a global scope
2176
+ * string with `purposeOneTreatment=true` then that string should be
2177
+ * considered invalid and the CMP must re-establish transparency and consent.
2178
+ *
2179
+ * @param {boolean} bool
2180
+ */
2181
+ set purposeOneTreatment(bool) {
2182
+ this.purposeOneTreatment_ = bool;
2183
+ }
2184
+ get purposeOneTreatment() {
2185
+ return this.purposeOneTreatment_;
2186
+ }
2187
+ /**
2188
+ * setAllVendorConsents - sets all vendors on the GVL Consent (true)
2189
+ *
2190
+ * @return {void}
2191
+ */
2192
+ setAllVendorConsents() {
2193
+ this.vendorConsents.set(this.gvl.vendors);
2194
+ }
2195
+ /**
2196
+ * unsetAllVendorConsents - unsets all vendors on the GVL Consent (false)
2197
+ *
2198
+ * @return {void}
2199
+ */
2200
+ unsetAllVendorConsents() {
2201
+ this.vendorConsents.empty();
2202
+ }
2203
+ /**
2204
+ * setAllVendorsDisclosed - sets all vendors on the GVL Vendors Disclosed (true)
2205
+ *
2206
+ * @return {void}
2207
+ */
2208
+ setAllVendorsDisclosed() {
2209
+ this.vendorsDisclosed.set(this.gvl.vendors);
2210
+ }
2211
+ /**
2212
+ * unsetAllVendorsDisclosed - unsets all vendors on the GVL Consent (false)
2213
+ *
2214
+ * @return {void}
2215
+ */
2216
+ unsetAllVendorsDisclosed() {
2217
+ this.vendorsDisclosed.empty();
2218
+ }
2219
+ /**
2220
+ * setAllVendorsAllowed - sets all vendors on the GVL Consent (true)
2221
+ *
2222
+ * @return {void}
2223
+ */
2224
+ setAllVendorsAllowed() {
2225
+ this.vendorsAllowed.set(this.gvl.vendors);
2226
+ }
2227
+ /**
2228
+ * unsetAllVendorsAllowed - unsets all vendors on the GVL Consent (false)
2229
+ *
2230
+ * @return {void}
2231
+ */
2232
+ unsetAllVendorsAllowed() {
2233
+ this.vendorsAllowed.empty();
2234
+ }
2235
+ /**
2236
+ * setAllVendorLegitimateInterests - sets all vendors on the GVL LegitimateInterests (true)
2237
+ *
2238
+ * @return {void}
2239
+ */
2240
+ setAllVendorLegitimateInterests() {
2241
+ this.vendorLegitimateInterests.set(this.gvl.vendors);
2242
+ }
2243
+ /**
2244
+ * unsetAllVendorLegitimateInterests - unsets all vendors on the GVL LegitimateInterests (false)
2245
+ *
2246
+ * @return {void}
2247
+ */
2248
+ unsetAllVendorLegitimateInterests() {
2249
+ this.vendorLegitimateInterests.empty();
2250
+ }
2251
+ /**
2252
+ * setAllPurposeConsents - sets all purposes on the GVL Consent (true)
2253
+ *
2254
+ * @return {void}
2255
+ */
2256
+ setAllPurposeConsents() {
2257
+ this.purposeConsents.set(this.gvl.purposes);
2258
+ }
2259
+ /**
2260
+ * unsetAllPurposeConsents - unsets all purposes on the GVL Consent (false)
2261
+ *
2262
+ * @return {void}
2263
+ */
2264
+ unsetAllPurposeConsents() {
2265
+ this.purposeConsents.empty();
2266
+ }
2267
+ /**
2268
+ * setAllPurposeLegitimateInterests - sets all purposes on the GVL LI Transparency (true)
2269
+ *
2270
+ * @return {void}
2271
+ */
2272
+ setAllPurposeLegitimateInterests() {
2273
+ this.purposeLegitimateInterests.set(this.gvl.purposes);
2274
+ }
2275
+ /**
2276
+ * unsetAllPurposeLegitimateInterests - unsets all purposes on the GVL LI Transparency (false)
2277
+ *
2278
+ * @return {void}
2279
+ */
2280
+ unsetAllPurposeLegitimateInterests() {
2281
+ this.purposeLegitimateInterests.empty();
2282
+ }
2283
+ /**
2284
+ * setAllSpecialFeatureOptins - sets all special featuresOptins on the GVL (true)
2285
+ *
2286
+ * @return {void}
2287
+ */
2288
+ setAllSpecialFeatureOptins() {
2289
+ this.specialFeatureOptins.set(this.gvl.specialFeatures);
2290
+ }
2291
+ /**
2292
+ * unsetAllSpecialFeatureOptins - unsets all special featuresOptins on the GVL (true)
2293
+ *
2294
+ * @return {void}
2295
+ */
2296
+ unsetAllSpecialFeatureOptins() {
2297
+ this.specialFeatureOptins.empty();
2298
+ }
2299
+ setAll() {
2300
+ this.setAllVendorConsents();
2301
+ this.setAllPurposeLegitimateInterests();
2302
+ this.setAllSpecialFeatureOptins();
2303
+ this.setAllPurposeConsents();
2304
+ this.setAllVendorLegitimateInterests();
2305
+ }
2306
+ unsetAll() {
2307
+ this.unsetAllVendorConsents();
2308
+ this.unsetAllPurposeLegitimateInterests();
2309
+ this.unsetAllSpecialFeatureOptins();
2310
+ this.unsetAllPurposeConsents();
2311
+ this.unsetAllVendorLegitimateInterests();
2312
+ }
2313
+ get numCustomPurposes() {
2314
+ let len = this.numCustomPurposes_;
2315
+ if (typeof this.customPurposes === "object") {
2316
+ const purposeIds = Object.keys(this.customPurposes).sort((a, b) => Number(a) - Number(b));
2317
+ len = parseInt(purposeIds.pop(), 10);
2318
+ }
2319
+ return len;
2320
+ }
2321
+ set numCustomPurposes(num) {
2322
+ this.numCustomPurposes_ = parseInt(num, 10);
2323
+ if (this.numCustomPurposes_ < 0) {
2324
+ throw new TCModelError("numCustomPurposes", num);
2325
+ }
2326
+ }
2327
+ /**
2328
+ * updated - updates the created and lastUpdated dates with a 'now' day-level UTC timestamp
2329
+ *
2330
+ * @return {void}
2331
+ */
2332
+ updated() {
2333
+ const date = /* @__PURE__ */ new Date();
2334
+ const utcDate = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
2335
+ this.created = utcDate;
2336
+ this.lastUpdated = utcDate;
2337
+ }
2338
+ }
2339
+ __publicField(TCModel, "consentLanguages", GVL.consentLanguages);
2340
+ class TCString {
2341
+ /**
2342
+ * encodes a model into a TCString
2343
+ *
2344
+ * @param {TCModel} tcModel - model to convert into encoded string
2345
+ * @param {EncodingOptions} options - for encoding options other than default
2346
+ * @return {string} - base64url encoded Transparency and Consent String
2347
+ */
2348
+ static encode(tcModel, options) {
2349
+ let out = "";
2350
+ let sequence;
2351
+ tcModel = SemanticPreEncoder.process(tcModel, options);
2352
+ if (Array.isArray(options == null ? void 0 : options.segments)) {
2353
+ sequence = options.segments;
2354
+ } else {
2355
+ sequence = new SegmentSequence(tcModel, options)["" + tcModel.version];
2356
+ }
2357
+ sequence.forEach((segment, idx) => {
2358
+ let dotMaybe = "";
2359
+ if (idx < sequence.length - 1) {
2360
+ dotMaybe = ".";
2361
+ }
2362
+ out += SegmentEncoder.encode(tcModel, segment) + dotMaybe;
2363
+ });
2364
+ return out;
2365
+ }
2366
+ /**
2367
+ * Decodes a string into a TCModel
2368
+ *
2369
+ * @param {string} encodedTCString - base64url encoded Transparency and
2370
+ * Consent String to decode - can also be a single or group of segments of
2371
+ * the string
2372
+ * @param {string} [tcModel] - model to enhance with the information. If
2373
+ * none is passed a new instance of TCModel will be created.
2374
+ * @return {TCModel} - Returns populated TCModel
2375
+ */
2376
+ static decode(encodedTCString, tcModel) {
2377
+ const segments = encodedTCString.split(".");
2378
+ const len = segments.length;
2379
+ if (!tcModel) {
2380
+ tcModel = new TCModel();
2381
+ }
2382
+ for (let i = 0; i < len; i++) {
2383
+ const segString = segments[i];
2384
+ const firstChar = Base64Url.decode(segString.charAt(0));
2385
+ const segTypeBits = firstChar.substr(0, BitLength.segmentType);
2386
+ const segment = SegmentIDs.ID_TO_KEY[IntEncoder.decode(segTypeBits, BitLength.segmentType).toString()];
2387
+ SegmentEncoder.decode(segString, tcModel, segment);
2388
+ }
2389
+ return tcModel;
2390
+ }
2391
+ }
2392
+ const iabCustomCategories = {
2393
+ permutiveAds: {
2394
+ purposes: [2, 4, 8, 9],
2395
+ iabVendors: [361],
2396
+ customVendors: [],
2397
+ specialFeatures: []
2398
+ },
2399
+ demographicAds: {
2400
+ purposes: [3, 4, 7, 9, 10],
2401
+ iabVendors: [],
2402
+ customVendors: [],
2403
+ specialFeatures: []
2404
+ }
2405
+ };
2406
+ function isValidGdprValue(val) {
2407
+ if (val === null) {
2408
+ return true;
2409
+ }
2410
+ try {
2411
+ TCString.decode(val);
2412
+ return true;
2413
+ } catch (error) {
2414
+ return false;
2415
+ }
2416
+ }
2417
+ function isValidUspString(val) {
2418
+ if (val === null) {
2419
+ return true;
2420
+ }
2421
+ const regex = /^[1-9][YN-][YN-][YN-]$/;
2422
+ return regex.test(val);
2423
+ }
2424
+ function validateRawConsentState(input) {
2425
+ if (typeof input !== "object" || input === null) {
2426
+ throw new Error("Invalid consent state object");
2427
+ }
2428
+ if (!isValidGdprValue(input.gdpr)) {
2429
+ throw new Error("Invalid TC string provided");
2430
+ }
2431
+ if (!isValidUspString(input.ccpa)) {
2432
+ throw new Error("Invalid USP string provided");
2433
+ }
2434
+ if (!["ccpa", "gdpr"].includes(input.activeLegislation)) {
2435
+ throw new Error("Active legislation is required");
2436
+ }
2437
+ if (input.gdpr === void 0 && input.ccpa === void 0) {
2438
+ throw new Error("Either GDPR or CCPA consent must be provided");
2439
+ }
2440
+ return true;
2441
+ }
2442
+ function validateIabConsentCategory(categoryName) {
2443
+ if (!categoryName || categoryName in iabCustomCategories === false) {
2444
+ throw new Error("Provided custom category identifier does not exist. Please check");
2445
+ }
2446
+ }
2447
+ const legislation = {
2448
+ CCPA: "ccpa",
2449
+ GDPR: "gdpr"
2450
+ };
2451
+ function checkConsentFor(categoryName, consentState) {
2452
+ validateIabConsentCategory(categoryName);
2453
+ validateRawConsentState(consentState);
2454
+ const { gdpr, ccpa, activeLegislation } = consentState;
2455
+ const customCategory = iabCustomCategories[categoryName];
2456
+ if (activeLegislation === legislation.CCPA) {
2457
+ const userHasNotOptedOut = (ccpa == null ? void 0 : ccpa[2]) === "N";
2458
+ return userHasNotOptedOut;
2459
+ }
2460
+ const decodedGdprConsent = TCString.decode(gdpr);
2461
+ const { purposeConsents, vendorConsents, specialFeatureOptins } = decodedGdprConsent;
2462
+ const requiredPurposesConsented = customCategory.purposes.every(
2463
+ (requiredPurpose) => purposeConsents.has(requiredPurpose)
2464
+ );
2465
+ const requiredIabVendorsConsented = customCategory.iabVendors.every(
2466
+ (requiredVendor) => vendorConsents.has(requiredVendor)
2467
+ );
2468
+ const requiredSpecialFeaturesConsented = customCategory.specialFeatures.every(
2469
+ (requiredFeature) => specialFeatureOptins.has(requiredFeature)
2470
+ );
2471
+ return requiredPurposesConsented && requiredIabVendorsConsented && requiredSpecialFeaturesConsented;
2472
+ }
2473
+ function getParsedConsent(rawConsentState) {
2474
+ const categoryNames = Object.keys(iabCustomCategories);
2475
+ return categoryNames.reduce((parsedConsent, categoryName) => {
2476
+ parsedConsent[categoryName] = checkConsentFor(categoryName, rawConsentState);
2477
+ return parsedConsent;
2478
+ }, {});
2479
+ }
2480
+ function updateFooterLinkCMP() {
2481
+ const cookieLink = document.querySelector(
2482
+ "[href='https://www.ft.com/preferences/manage-cookies']"
2483
+ );
2484
+ if (cookieLink) {
2485
+ cookieLink.href = "#";
2486
+ cookieLink.setAttribute("onclick", "window._sp_.gdpr.loadPrivacyManagerModal(827767);");
2487
+ cookieLink.dataset.cmpLink = "updated";
2488
+ return true;
2489
+ } else {
2490
+ console.warn("CMP Footer Link was not found and not updated");
2491
+ return false;
2492
+ }
2493
+ }
2494
+ const SOURCEPOINT_CONSENT_SOURCE = "sourcepoint-cmp";
2495
+ const SOURCEPOINT_FOW_SCOPE = "FTPINK";
2496
+ const CONSENT_COOKIE_NAME = "FTConsent";
2497
+ function getPayload(parsedConsent, { shouldUpdateConsentStore, formOfWordsId, cookieDomain }) {
2498
+ const categoryNames = Object.keys(parsedConsent);
2499
+ const data = categoryNames.reduce((payload, categoryName) => {
2500
+ payload[categoryName] = {
2501
+ onsite: {
2502
+ status: parsedConsent[categoryName],
2503
+ lbi: false,
2504
+ source: SOURCEPOINT_CONSENT_SOURCE,
2505
+ fow: formOfWordsId
2506
+ }
2507
+ };
2508
+ return payload;
2509
+ }, {});
2510
+ if (!shouldUpdateConsentStore) {
2511
+ return { data };
2512
+ } else {
2513
+ return {
2514
+ setConsentCookie: true,
2515
+ formOfWordsId,
2516
+ consentSource: SOURCEPOINT_CONSENT_SOURCE,
2517
+ cookieDomain,
2518
+ data
2519
+ };
2520
+ }
2521
+ }
2522
+ async function saveConsent(consentEndpoint, payload) {
2523
+ try {
2524
+ const response = await fetch(consentEndpoint, {
2525
+ method: "POST",
2526
+ headers: {
2527
+ "Content-Type": "application/json"
2528
+ },
2529
+ body: JSON.stringify(payload),
2530
+ credentials: "include"
2531
+ });
2532
+ if (!response.ok) {
2533
+ console.error("Unable to save consent preferences", response.status);
2534
+ }
2535
+ } catch (error) {
2536
+ console.error("An error occurred while saving consent", error);
2537
+ }
2538
+ }
2539
+ function consentReadyHandlerFn(props) {
2540
+ const { userId, consentProxyHost, cookieDomain, formOfWordsId, useConsentStore } = props;
2541
+ return async (legislation2, _, consentString, consentMeta) => {
2542
+ const activeLegislation = consentMeta.applies ? legislation2 : "gdpr";
2543
+ if (activeLegislation !== legislation2 || !consentString) {
2544
+ return;
2545
+ }
2546
+ const parsedConsent = getParsedConsent({
2547
+ activeLegislation,
2548
+ gdpr: activeLegislation === "gdpr" ? consentString : null,
2549
+ ccpa: activeLegislation === "ccpa" ? consentString : null
2550
+ });
2551
+ const consentHasChanged = hasConsentChanged(parsedConsent);
2552
+ if (!consentHasChanged) {
2553
+ return;
2554
+ }
2555
+ let consentEndpoint = `${consentProxyHost}/__consent/consent-record-cookie?cookieDomain=${cookieDomain}`;
2556
+ const shouldUpdateConsentStore = !!userId && useConsentStore;
2557
+ if (shouldUpdateConsentStore) {
2558
+ consentEndpoint = `${consentProxyHost}/__consent/consent-record/${SOURCEPOINT_FOW_SCOPE}/${userId}`;
2559
+ }
2560
+ const payload = getPayload(parsedConsent, {
2561
+ formOfWordsId,
2562
+ cookieDomain,
2563
+ shouldUpdateConsentStore
2564
+ });
2565
+ await saveConsent(consentEndpoint, payload);
2566
+ document.dispatchEvent(new CustomEvent("oCookieMessage.act", { bubbles: true }));
2567
+ };
2568
+ }
2569
+ function hasConsentChanged(parsedConsent) {
2570
+ const categories = Object.keys(parsedConsent);
2571
+ const previousConsent = getConsentCookieValue();
2572
+ return categories.some((category) => {
2573
+ const adaptedCategoryName = `${category.toLowerCase()}Onsite`;
2574
+ return parsedConsent[category] !== previousConsent[adaptedCategoryName];
2575
+ });
2576
+ }
2577
+ function getConsentCookieValue() {
2578
+ const cookies = Object.fromEntries(
2579
+ document.cookie.split("; ").map((cookie) => cookie.split("="))
2580
+ );
2581
+ const encodedValue = cookies[CONSENT_COOKIE_NAME];
2582
+ if (!encodedValue)
2583
+ return {};
2584
+ const decodedValue = decodeURIComponent(encodedValue);
2585
+ return Object.fromEntries(
2586
+ decodedValue.split(",").map((consent) => {
2587
+ const [category, value] = consent.split(":");
2588
+ const booleanConsent = [category, value === "on" ? true : false];
2589
+ return booleanConsent;
2590
+ })
2591
+ );
2592
+ }
2593
+ const SOURCEPOINT_FOW_ID = "sourcepointCmp/VngD.XycZut.595cp9fWdp5XYP9vlFvk";
2594
+ const FT_COOKIE_DOMAIN = ".ft.com";
2595
+ const FT_CONSENT_PROXY_HOST = "https://consent.ft.com";
2596
+ function createContentScript(content) {
2597
+ const s = document.createElement("script");
2598
+ s.innerHTML = content;
2599
+ return s;
2600
+ }
2601
+ function createSourceScript(src) {
2602
+ const s = document.createElement("script");
2603
+ s.src = src;
2604
+ return s;
2605
+ }
2606
+ function getCmpScripts(config) {
2607
+ const fragment = document.createDocumentFragment();
2608
+ fragment.appendChild(createContentScript(scriptContent.tcfStub));
2609
+ fragment.appendChild(createContentScript(scriptContent.uspStub));
2610
+ fragment.appendChild(createContentScript(scriptContent.getSPConfig(config)));
2611
+ fragment.appendChild(createSourceScript(scriptSources.cmpFrames));
2612
+ return fragment;
2613
+ }
2614
+ async function initSourcepointCmp({
2615
+ propertyConfig = FT_DOTCOM_PROD,
2616
+ userId,
2617
+ useFTSession = true,
2618
+ consentProxyHost = FT_CONSENT_PROXY_HOST,
2619
+ cookieDomain = FT_COOKIE_DOMAIN,
2620
+ formOfWordsId = SOURCEPOINT_FOW_ID,
2621
+ useConsentStore = true
2622
+ }) {
2623
+ let maybeUserId = userId;
2624
+ if (!maybeUserId && useFTSession) {
2625
+ try {
2626
+ const response = await getUuid();
2627
+ maybeUserId = response == null ? void 0 : response.uuid;
2628
+ } catch (error) {
2629
+ console.error(error);
2630
+ }
2631
+ }
2632
+ if (!(propertyConfig == null ? void 0 : propertyConfig.accountId)) {
2633
+ throw new Error("Please pass a valid property config");
2634
+ }
2635
+ if (maybeUserId) {
2636
+ propertyConfig.authId = maybeUserId;
2637
+ }
2638
+ const scripts = getCmpScripts(propertyConfig);
2639
+ document.head.appendChild(scripts);
2640
+ window._sp_queue.push(() => {
2641
+ window._sp_.addEventListener(
2642
+ "onConsentReady",
2643
+ consentReadyHandlerFn({
2644
+ userId: maybeUserId,
2645
+ consentProxyHost,
2646
+ cookieDomain,
2647
+ formOfWordsId,
2648
+ useConsentStore
2649
+ })
2650
+ );
2651
+ });
2652
+ }
2653
+ export {
2654
+ getCmpScripts,
2655
+ initSourcepointCmp,
2656
+ updateFooterLinkCMP
2657
+ };