@blotoutio/edgetag-sdk-js 0.51.1 → 0.52.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs.js +545 -408
  2. package/index.d.ts +29 -6
  3. package/index.mjs +545 -408
  4. package/package.json +1 -1
package/index.cjs.js CHANGED
@@ -15,11 +15,174 @@ var api = /*#__PURE__*/Object.freeze({
15
15
  get user () { return user; }
16
16
  });
17
17
 
18
- const _config = {};
19
- const setConfig$1 = (config) => {
20
- Object.assign(_config, config);
18
+ const isBool = (v) => typeof v == 'boolean';
19
+ const isRecord = (v) => !!v && typeof v == 'object' && !Array.isArray(v);
20
+ /**
21
+ * This function validates user consent for a given provider and tag name.
22
+ * It should be used in conjunction with `UserConsent`, not `ProvidersConfig`.
23
+ */
24
+ const hasUserConsent = (consent, provider, tagName) => {
25
+ if (!isRecord(consent)) {
26
+ return false;
27
+ }
28
+ let allowed = isBool(consent.all) ? consent.all : false;
29
+ if (provider in consent) {
30
+ const providerSpecific = consent[provider];
31
+ if (isBool(providerSpecific)) {
32
+ allowed = providerSpecific;
33
+ }
34
+ else if (isRecord(providerSpecific)) {
35
+ if ('all' in providerSpecific && isBool(providerSpecific.all)) {
36
+ allowed = providerSpecific.all;
37
+ }
38
+ if (tagName in providerSpecific && isBool(providerSpecific[tagName])) {
39
+ allowed = providerSpecific[tagName];
40
+ }
41
+ }
42
+ }
43
+ return allowed;
44
+ };
45
+ /**
46
+ * This function validates user consent for a given provider type, not based on tagName.
47
+ */
48
+ const hasUserConsentForProvider = (consent, provider) => {
49
+ if (!isRecord(consent)) {
50
+ return false;
51
+ }
52
+ let allowed = isBool(consent.all) ? consent.all : false;
53
+ if (provider in consent) {
54
+ const providerSpecific = consent[provider];
55
+ if (isBool(providerSpecific)) {
56
+ allowed = providerSpecific;
57
+ }
58
+ else if (isRecord(providerSpecific)) {
59
+ return Object.keys(providerSpecific).some((instance) => providerSpecific[instance] === true);
60
+ }
61
+ }
62
+ return allowed;
63
+ };
64
+ /**
65
+ * This function validates provider allowance for a given provider and tag name.
66
+ * It should not be used to validate `UserConsent`.
67
+ */
68
+ const isProviderInstanceAllowed = (providersConfig, provider, tagName) => {
69
+ if (!isRecord(providersConfig)) {
70
+ return true;
71
+ }
72
+ if (provider in providersConfig) {
73
+ const providerSpecific = providersConfig[provider];
74
+ if (isBool(providerSpecific)) {
75
+ return providerSpecific;
76
+ }
77
+ if (isRecord(providerSpecific)) {
78
+ const tagKeys = Object.keys(providerSpecific).filter((k) => k != 'all');
79
+ if (tagName in providerSpecific && isBool(providerSpecific[tagName])) {
80
+ return providerSpecific[tagName];
81
+ }
82
+ return isBool(providerSpecific.all)
83
+ ? providerSpecific.all
84
+ : tagKeys.length == 0;
85
+ }
86
+ }
87
+ const providerKeys = Object.keys(providersConfig).filter((k) => k != 'all');
88
+ return isBool(providersConfig.all)
89
+ ? providersConfig.all
90
+ : providerKeys.length == 0;
91
+ };
92
+
93
+ const upsert = (map, key, update, createDefault) => {
94
+ const currentValue = map.has(key)
95
+ ? map.get(key)
96
+ : createDefault();
97
+ return map.set(key, update(currentValue));
98
+ };
99
+
100
+ const expand = (str) => str.split(',').flatMap((entry) => {
101
+ if (!entry.includes('-')) {
102
+ return entry;
103
+ }
104
+ const result = [];
105
+ const [start, end] = entry.split('-').map(Number);
106
+ for (let i = start; i <= end; i++) {
107
+ result.push(i.toString());
108
+ }
109
+ return result;
110
+ });
111
+ /**
112
+ * Exported from https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes
113
+ *
114
+ * In Dev Tools, select the `tbody` element containing the area codes and run the following code,
115
+ * replacing the emdash character with a simple endash:
116
+ *
117
+ * ```ts
118
+ * [...$0.querySelectorAll('td:first-child')]
119
+ * .filter(cell => cell.firstChild.nodeName != 'A')
120
+ * .map(cell => cell.textContent.trim()).join(',')
121
+ * ```
122
+ */
123
+ new Set([
124
+ ...expand('200,211,221,222,230,232,233,235,237-238,241,243,244,245,247,255,257,258-259,261,265,266,271,273,274,275,277,278,280,282,283,285-287,288,290-299'),
125
+ ...expand('300,311,322,324,327,328,333,335,338,342,344,348-349,353,355,356,357-359,362,366,369,370-379,381,382,383-384,387,388,389,390-399'),
126
+ ...expand('400,411,420,421-422,426-427,428,429,433,439,444,446,449,451-454,455,456,457,459,460,461-462,465,466,467,471,476,477,481-483,485-486,487,488,489,490-499'),
127
+ ...expand('511,532,535,536,537,538,542-543,545-547,549-550,552-554,555,556,558,560,565,568,569,576,578,583,589,590-599'),
128
+ ...expand('611,621,624,625,627,632,633,634-635,637-638,642-643,644,648,652-654,655,663,665,666,668,673-676,677,679,685,686,687,688,690-699'),
129
+ ...expand('711,722,723,729,733,735-736,739,741,744,745-746,748,749-751,752,755,756,759,761,764,766,768,776,777,783,788,789,790-799'),
130
+ ...expand('811,821,822,823-824,827,834,836,841-842,846,851,852-853,871,874-875,879,880-887,889,890-899'),
131
+ ...expand('911,921,922,923,924,926,927,932,933,935,942,944,946,950,953,955,957-958,960-969,974,975,976,977,981-982,987,988,990-999'),
132
+ ]);
133
+
134
+ // eslint-disable-next-line @nx/enforce-module-boundaries
135
+ let edgeTagSettings;
136
+ const initSettings = (destination, options) => {
137
+ if (!edgeTagSettings) {
138
+ edgeTagSettings = {};
139
+ }
140
+ edgeTagSettings[destination] = {
141
+ destination,
142
+ initialized: false,
143
+ stubs: [],
144
+ channels: new Map(),
145
+ ...options,
146
+ };
147
+ };
148
+ const setSetting = (options, destination) => {
149
+ if (!edgeTagSettings) {
150
+ return;
151
+ }
152
+ if (!destination) {
153
+ Object.keys(edgeTagSettings).forEach((key) => {
154
+ edgeTagSettings[key] = {
155
+ ...edgeTagSettings[key],
156
+ ...options,
157
+ };
158
+ });
159
+ return;
160
+ }
161
+ edgeTagSettings[destination] = {
162
+ ...edgeTagSettings[destination],
163
+ ...options,
164
+ };
165
+ };
166
+ const getSetting = (destination, key) => {
167
+ var _a;
168
+ return (_a = edgeTagSettings === null || edgeTagSettings === void 0 ? void 0 : edgeTagSettings[destination]) === null || _a === void 0 ? void 0 : _a[key];
169
+ };
170
+ const getInstances = () => {
171
+ return Object.keys(edgeTagSettings || {});
172
+ };
173
+ const addChannel = (destination, pkg, tagName) => upsert(getSetting(destination, 'channels'), pkg, (names) => names.add(tagName), () => new Set());
174
+ const getProviderVariables = (destination, packageId) => {
175
+ const setting = getSetting(destination, 'packages');
176
+ if (!setting) {
177
+ return [];
178
+ }
179
+ return (setting
180
+ .filter((pkg) => pkg.package === packageId)
181
+ .map((pkg) => ({
182
+ tagName: pkg.tagName,
183
+ variableSet: pkg.variables || {},
184
+ })) || []);
21
185
  };
22
- const getConfig = () => _config;
23
186
 
24
187
  const getUserAgent = () => {
25
188
  try {
@@ -30,11 +193,11 @@ const getUserAgent = () => {
30
193
  return '';
31
194
  }
32
195
  };
33
- const getReferrer = () => {
196
+ const getReferrer = (destination) => {
34
197
  let referrer = '';
35
198
  try {
36
199
  const referrerUrl = new URL(document.referrer);
37
- const pageUrl = new URL(getPageUrl());
200
+ const pageUrl = new URL(getPageUrl(destination));
38
201
  if (referrerUrl.host !== pageUrl.host) {
39
202
  referrer = referrerUrl.href;
40
203
  }
@@ -44,22 +207,22 @@ const getReferrer = () => {
44
207
  return referrer;
45
208
  }
46
209
  };
47
- const getPageUrl = () => {
210
+ const getPageUrl = (destination) => {
48
211
  try {
49
212
  // we need to leave this one in for existing Custom pixel customers
50
213
  if (window.edgetagData && window.edgetagData['pageUrl']) {
51
214
  return window.edgetagData['pageUrl'];
52
215
  }
53
- const { pageUrl } = getConfig();
54
- return pageUrl || window.location.href;
216
+ const config = getSetting(destination, 'config');
217
+ return (config === null || config === void 0 ? void 0 : config.pageUrl) || window.location.href;
55
218
  }
56
219
  catch {
57
220
  return '';
58
221
  }
59
222
  };
60
- const getSearch = () => {
223
+ const getSearch = (destination) => {
61
224
  try {
62
- return new URL(getPageUrl()).search;
225
+ return new URL(getPageUrl(destination)).search;
63
226
  }
64
227
  catch {
65
228
  return '';
@@ -146,9 +309,9 @@ const error = (data) => {
146
309
  console.error('[EdgeTag]', getMessage(data));
147
310
  };
148
311
 
149
- const initKey = `${keyPrefix}Store`;
150
- const saveDataPerKey = (persistType, provider, value, key) => {
151
- const storage = getData$1(persistType);
312
+ const initKey = `${keyPrefix}StoreMultiple`;
313
+ const saveDataPerKey = (destination, persistType, provider, value, key) => {
314
+ const storage = getData$1(destination, persistType);
152
315
  if (!storage['data']) {
153
316
  storage['data'] = {};
154
317
  }
@@ -156,49 +319,54 @@ const saveDataPerKey = (persistType, provider, value, key) => {
156
319
  storage['data'][provider] = {};
157
320
  }
158
321
  storage['data'][provider][key] = value;
159
- saveData(persistType, storage);
322
+ saveData(destination, persistType, storage);
160
323
  };
161
- const savePerKey = (persistType, provider, value, key) => {
162
- const storage = getData$1(persistType);
324
+ const saveKV = (destination, data) => {
325
+ const currentSession = getData$1(destination, 'session');
326
+ if (!currentSession['kv']) {
327
+ currentSession['kv'] = {};
328
+ }
329
+ currentSession['kv'] = {
330
+ ...currentSession['kv'],
331
+ ...data,
332
+ };
333
+ saveData(destination, 'session', currentSession);
334
+ };
335
+ const savePerKey = (destination, persistType, provider, value, key) => {
336
+ const storage = getData$1(destination, persistType);
163
337
  if (!storage[provider]) {
164
338
  storage[provider] = {};
165
339
  }
166
340
  storage[provider][key] = value;
167
- saveData(persistType, storage);
341
+ saveData(destination, persistType, storage);
168
342
  };
169
- const getDataPerKey = (persistType, provider, key) => {
170
- const storage = getData$1(persistType);
343
+ const getDataPerKey = (destination, persistType, provider, key) => {
344
+ const storage = getData$1(destination, persistType);
171
345
  if (!storage[provider]) {
172
346
  return undefined;
173
347
  }
174
348
  return storage[provider][key];
175
349
  };
176
- const saveData = (persistType, value, key = initKey) => {
350
+ const saveData = (destination, persistType, value, key = initKey) => {
177
351
  if (persistType === 'session') {
178
- saveSession(value, key);
352
+ const data = getSession(key);
353
+ data[destination] = value;
354
+ saveSession(data, key);
179
355
  return;
180
356
  }
181
- saveLocal(value, key);
357
+ const data = getLocal(key);
358
+ data[destination] = value;
359
+ saveLocal(data, key);
182
360
  };
183
- const getData$1 = (persistType, key = initKey) => {
361
+ const getData$1 = (destination, persistType, key = initKey) => {
362
+ let data;
184
363
  if (persistType === 'session') {
185
- return getSession(key);
364
+ data = getSession(key);
186
365
  }
187
- return getLocal(key);
188
- };
189
- const saveKV = (data) => {
190
- let currentSession = getData$1('session');
191
- if (!currentSession) {
192
- currentSession = {};
193
- }
194
- if (!currentSession['kv']) {
195
- currentSession['kv'] = {};
366
+ else {
367
+ data = getLocal(key);
196
368
  }
197
- currentSession['kv'] = {
198
- ...currentSession['kv'],
199
- ...data,
200
- };
201
- saveData('session', currentSession);
369
+ return (data === null || data === void 0 ? void 0 : data[destination]) || {};
202
370
  };
203
371
  const saveLocal = (value, key) => {
204
372
  try {
@@ -321,17 +489,23 @@ const getCookieValue = (key) => {
321
489
  }
322
490
  };
323
491
 
324
- let initUserId = '';
325
- const handleGetUserId = () => {
326
- if (initUserId) {
327
- return initUserId;
492
+ const getUserId$1 = (destination) => {
493
+ const userId = getSetting(destination, 'userId');
494
+ if (userId) {
495
+ return userId;
328
496
  }
329
- // leaving this for backward compatibility as worker was maybe not updated yet
330
- // reference https://github.com/blotoutio/solutions/issues/1960
331
497
  return getCookieValue(cookieKey);
332
498
  };
333
- const setUserId = (userId) => {
334
- initUserId = userId;
499
+ const handleGetUserId = (options) => {
500
+ if (options === null || options === void 0 ? void 0 : options.destination) {
501
+ return getUserId$1(options.destination);
502
+ }
503
+ const instances = getInstances();
504
+ if (instances.length > 1) {
505
+ error('Multiple instances detected! Please provide a destination.');
506
+ return '';
507
+ }
508
+ return getUserId$1(instances[0]);
335
509
  };
336
510
 
337
511
  const beacon = (url, payload) => {
@@ -346,12 +520,12 @@ const beacon = (url, payload) => {
346
520
  return Promise.reject(new Error('Beacon not supported.'));
347
521
  }
348
522
  };
349
- const ajax = (method, url, payload) => fetch(url, {
523
+ const ajax = (destination, method, url, payload) => fetch(url, {
350
524
  method,
351
525
  headers: {
352
526
  'Content-type': 'application/json; charset=utf-8',
353
527
  Accept: 'application/json; charset=utf-8',
354
- EdgeTagUserId: handleGetUserId(),
528
+ EdgeTagUserId: getUserId$1(destination),
355
529
  },
356
530
  body: JSON.stringify(payload),
357
531
  credentials: 'include',
@@ -365,26 +539,26 @@ const ajax = (method, url, payload) => fetch(url, {
365
539
  }
366
540
  return Promise.resolve(body);
367
541
  });
368
- const getStandardPayload = (payload) => {
542
+ const getStandardPayload = (destination, payload) => {
369
543
  const data = {
370
- pageUrl: getPageUrl(),
544
+ pageUrl: getPageUrl(destination),
371
545
  pageTitle: getPageTitle(),
372
546
  userAgent: getUserAgent(),
373
- referrer: getReferrer(),
374
- search: getSearch(),
547
+ referrer: getReferrer(destination),
548
+ search: getSearch(destination),
375
549
  locale: getLocale(),
376
- sdkVersion: "0.51.1" ,
550
+ sdkVersion: "0.52.1" ,
377
551
  ...(payload || {}),
378
552
  };
379
553
  let storage = {};
380
- const session = getData$1('session');
554
+ const session = getData$1(destination, 'session');
381
555
  if (session) {
382
556
  storage = {
383
557
  ...storage,
384
558
  ...session,
385
559
  };
386
560
  }
387
- const local = getData$1('local');
561
+ const local = getData$1(destination, 'local');
388
562
  if (local) {
389
563
  storage = {
390
564
  ...storage,
@@ -398,11 +572,13 @@ async function postRequest(url, data, options) {
398
572
  if (!url) {
399
573
  return Promise.reject(new Error('URL is empty.'));
400
574
  }
401
- const payload = getStandardPayload(data);
575
+ const parsedUrl = new URL(url);
576
+ const destination = parsedUrl.origin;
577
+ const payload = getStandardPayload(destination, data);
402
578
  if (options && options.method === 'beacon') {
403
579
  return Promise.resolve(beacon(url, payload));
404
580
  }
405
- return await ajax('POST', url, payload);
581
+ return await ajax(destination, 'POST', url, payload);
406
582
  }
407
583
  async function getRequest(url, options) {
408
584
  if (!url) {
@@ -413,170 +589,44 @@ async function getRequest(url, options) {
413
589
  result: Promise.resolve(beacon(url)),
414
590
  };
415
591
  }
416
- return await ajax('GET', url);
592
+ const parsedUrl = new URL(url);
593
+ const destination = parsedUrl.origin;
594
+ return await ajax(destination, 'GET', url);
417
595
  }
418
596
 
419
- let endpointUrl = '';
420
- const generateUrl = (path) => {
421
- const endpoint = getUrl();
422
- if (!endpoint) {
597
+ const generateUrl = (destination, path) => {
598
+ if (!destination) {
423
599
  log('URL is not valid');
424
600
  return '';
425
601
  }
426
- return `${endpoint}${path}`;
602
+ return `${destination}${path}`;
427
603
  };
428
- const getUrl = () => {
429
- return endpointUrl;
430
- };
431
- const setUrl = (url) => {
432
- if (url == null) {
433
- return;
434
- }
435
- endpointUrl = url;
436
- };
437
- const getTagURL = (options) => {
438
- const url = new URL(generateUrl('/tag'));
604
+ const getTagURL = (destination, options) => {
605
+ const parsedUrl = new URL(generateUrl(destination, '/tag'));
439
606
  if (options === null || options === void 0 ? void 0 : options.sync) {
440
- url.searchParams.set('sync', 'true');
607
+ parsedUrl.searchParams.set('sync', 'true');
441
608
  }
442
- return url.toString();
609
+ return parsedUrl.toString();
443
610
  };
444
- const getInitURL = () => {
445
- return generateUrl('/init');
611
+ const getInitURL = (destination) => {
612
+ return generateUrl(destination, '/init');
446
613
  };
447
- const getConsentURL = () => {
448
- return generateUrl('/consent');
614
+ const getConsentURL = (destination) => {
615
+ return generateUrl(destination, '/consent');
449
616
  };
450
- const getUserURL = () => {
451
- return generateUrl('/user');
617
+ const getUserURL = (destination) => {
618
+ return generateUrl(destination, '/user');
452
619
  };
453
- const getDataURL = () => {
454
- return generateUrl(`/data`);
620
+ const getDataURL = (destination) => {
621
+ return generateUrl(destination, `/data`);
455
622
  };
456
- const getGetDataURL = (keys) => {
457
- return generateUrl(`/data?keys=${encodeURIComponent(keys.join(','))}`);
623
+ const getGetDataURL = (destination, keys) => {
624
+ return generateUrl(destination, `/data?keys=${encodeURIComponent(keys.join(','))}`);
458
625
  };
459
- const getKeysURL = () => {
460
- return generateUrl(`/keys`);
626
+ const getKeysURL = (destination) => {
627
+ return generateUrl(destination, `/keys`);
461
628
  };
462
629
 
463
- const isBool = (v) => typeof v == 'boolean';
464
- const isRecord = (v) => !!v && typeof v == 'object' && !Array.isArray(v);
465
- /**
466
- * This function validates user consent for a given provider and tag name.
467
- * It should be used in conjunction with `UserConsent`, not `ProvidersConfig`.
468
- */
469
- const hasUserConsent = (consent, provider, tagName) => {
470
- if (!isRecord(consent)) {
471
- return false;
472
- }
473
- let allowed = isBool(consent.all) ? consent.all : false;
474
- if (provider in consent) {
475
- const providerSpecific = consent[provider];
476
- if (isBool(providerSpecific)) {
477
- allowed = providerSpecific;
478
- }
479
- else if (isRecord(providerSpecific)) {
480
- if ('all' in providerSpecific && isBool(providerSpecific.all)) {
481
- allowed = providerSpecific.all;
482
- }
483
- if (tagName in providerSpecific && isBool(providerSpecific[tagName])) {
484
- allowed = providerSpecific[tagName];
485
- }
486
- }
487
- }
488
- return allowed;
489
- };
490
- /**
491
- * This function validates user consent for a given provider type, not based on tagName.
492
- */
493
- const hasUserConsentForProvider = (consent, provider) => {
494
- if (!isRecord(consent)) {
495
- return false;
496
- }
497
- let allowed = isBool(consent.all) ? consent.all : false;
498
- if (provider in consent) {
499
- const providerSpecific = consent[provider];
500
- if (isBool(providerSpecific)) {
501
- allowed = providerSpecific;
502
- }
503
- else if (isRecord(providerSpecific)) {
504
- return Object.keys(providerSpecific).some((instance) => providerSpecific[instance] === true);
505
- }
506
- }
507
- return allowed;
508
- };
509
- /**
510
- * This function validates provider allowance for a given provider and tag name.
511
- * It should not be used to validate `UserConsent`.
512
- */
513
- const isProviderInstanceAllowed = (providersConfig, provider, tagName) => {
514
- if (!isRecord(providersConfig)) {
515
- return true;
516
- }
517
- if (provider in providersConfig) {
518
- const providerSpecific = providersConfig[provider];
519
- if (isBool(providerSpecific)) {
520
- return providerSpecific;
521
- }
522
- if (isRecord(providerSpecific)) {
523
- const tagKeys = Object.keys(providerSpecific).filter((k) => k != 'all');
524
- if (tagName in providerSpecific && isBool(providerSpecific[tagName])) {
525
- return providerSpecific[tagName];
526
- }
527
- return isBool(providerSpecific.all)
528
- ? providerSpecific.all
529
- : tagKeys.length == 0;
530
- }
531
- }
532
- const providerKeys = Object.keys(providersConfig).filter((k) => k != 'all');
533
- return isBool(providersConfig.all)
534
- ? providersConfig.all
535
- : providerKeys.length == 0;
536
- };
537
-
538
- const upsert = (map, key, update, createDefault) => {
539
- const currentValue = map.has(key)
540
- ? map.get(key)
541
- : createDefault();
542
- return map.set(key, update(currentValue));
543
- };
544
-
545
- const expand = (str) => str.split(',').flatMap((entry) => {
546
- if (!entry.includes('-')) {
547
- return entry;
548
- }
549
- const result = [];
550
- const [start, end] = entry.split('-').map(Number);
551
- for (let i = start; i <= end; i++) {
552
- result.push(i.toString());
553
- }
554
- return result;
555
- });
556
- /**
557
- * Exported from https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes
558
- *
559
- * In Dev Tools, select the `tbody` element containing the area codes and run the following code,
560
- * replacing the emdash character with a simple endash:
561
- *
562
- * ```ts
563
- * [...$0.querySelectorAll('td:first-child')]
564
- * .filter(cell => cell.firstChild.nodeName != 'A')
565
- * .map(cell => cell.textContent.trim()).join(',')
566
- * ```
567
- */
568
- new Set([
569
- ...expand('200,211,221,222,230,232,233,235,237-238,241,243,244,245,247,255,257,258-259,261,265,266,271,273,274,275,277,278,280,282,283,285-287,288,290-299'),
570
- ...expand('300,311,322,324,327,328,333,335,338,342,344,348-349,353,355,356,357-359,362,366,369,370-379,381,382,383-384,387,388,389,390-399'),
571
- ...expand('400,411,420,421-422,426-427,428,429,433,439,444,446,449,451-454,455,456,457,459,460,461-462,465,466,467,471,476,477,481-483,485-486,487,488,489,490-499'),
572
- ...expand('511,532,535,536,537,538,542-543,545-547,549-550,552-554,555,556,558,560,565,568,569,576,578,583,589,590-599'),
573
- ...expand('611,621,624,625,627,632,633,634-635,637-638,642-643,644,648,652-654,655,663,665,666,668,673-676,677,679,685,686,687,688,690-699'),
574
- ...expand('711,722,723,729,733,735-736,739,741,744,745-746,748,749-751,752,755,756,759,761,764,766,768,776,777,783,788,789,790-799'),
575
- ...expand('811,821,822,823-824,827,834,836,841-842,846,851,852-853,871,874-875,879,880-887,889,890-899'),
576
- ...expand('911,921,922,923,924,926,927,932,933,935,942,944,946,950,953,955,957-958,960-969,974,975,976,977,981-982,987,988,990-999'),
577
- ]);
578
-
579
- let initialized = false;
580
630
  const providersPackages = {};
581
631
  const setPreferences = (preferences) => {
582
632
  var _a;
@@ -587,7 +637,6 @@ const setPreferences = (preferences) => {
587
637
  error('Please provide URL for EdgeTag');
588
638
  return false;
589
639
  }
590
- !!preferences.disableConsentCheck;
591
640
  (_a = preferences.providers) === null || _a === void 0 ? void 0 : _a.forEach((provider) => {
592
641
  if (!provider.name) {
593
642
  return;
@@ -607,52 +656,54 @@ const setPreferences = (preferences) => {
607
656
  catch {
608
657
  // do nothing
609
658
  }
610
- setUrl(preferences.edgeURL);
659
+ initSettings(preferences.edgeURL, {
660
+ disableConsent: !!preferences.disableConsentCheck,
661
+ });
611
662
  return true;
612
663
  };
613
- const getProvidersPackage = () => providersPackages;
614
- const isInitialized = () => initialized;
615
- const setInitialized = () => {
616
- initialized = true;
664
+ const getProvidersPackage = (destination) => {
665
+ const packages = getSetting(destination, 'packages');
666
+ const providers = [];
667
+ packages === null || packages === void 0 ? void 0 : packages.forEach((pkg) => {
668
+ const provider = providersPackages[pkg.package];
669
+ if (!provider) {
670
+ return;
671
+ }
672
+ providers.push(provider);
673
+ });
674
+ return providers;
617
675
  };
618
- const configuredTags = new Map();
619
- const addConfiguredTag = (pkg, tagName) => upsert(configuredTags, pkg, (names) => names.add(tagName), () => new Set());
620
- const getConfiguredTags = () => configuredTags;
621
676
 
622
- const manifestVariables = {};
623
- const addProviderVariable = (name, variables, tagName) => {
624
- manifestVariables[name] = {
625
- ...manifestVariables[name],
626
- [tagName]: variables || {},
627
- };
628
- };
629
- const getProviderVariables = (name) => {
630
- if (!name) {
631
- return {};
677
+ const getConsent$1 = (destination) => {
678
+ const storageConsent = getDataPerKey(destination, 'local', tagStorage, consentKey);
679
+ if (storageConsent) {
680
+ return storageConsent;
632
681
  }
633
- return manifestVariables[name] || {};
682
+ return getSetting(destination, 'consent');
634
683
  };
635
684
 
636
- let stubs = [];
637
- const addStubs = (newStubs) => {
638
- stubs = [...stubs, ...newStubs];
639
- };
640
- const addStub = (stub) => {
641
- stubs.push(stub);
642
- };
643
- const processStubs = () => {
685
+ const processStubs = (destination) => {
644
686
  try {
687
+ const stubs = getSetting(destination, 'stubs');
645
688
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
646
689
  // @ts-ignore
647
690
  stubs.forEach((stub) => api[stub.name](...(stub.arguments || [])));
648
- stubs = [];
691
+ setSetting({
692
+ stubs: [],
693
+ }, destination);
649
694
  }
650
695
  catch (e) {
651
696
  error(e);
652
697
  }
653
698
  };
699
+ const addStub = (destination, stub) => {
700
+ const otherStubs = getSetting(destination, 'stubs') || [];
701
+ setSetting({
702
+ stubs: [...otherStubs, stub],
703
+ }, destination);
704
+ };
654
705
 
655
- const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
706
+ const sendTag = (destination, { eventName, eventId, data, providerData, providers, options }) => {
656
707
  const payload = {
657
708
  eventName,
658
709
  eventId,
@@ -663,11 +714,11 @@ const sendTag = ({ eventName, eventId, data, providerData, providers, options, }
663
714
  if (providers) {
664
715
  payload.providers = providers;
665
716
  }
666
- postRequest(getTagURL(options), payload, options).catch(error);
717
+ postRequest(getTagURL(destination, options), payload, options).catch(error);
667
718
  };
668
- const handleTag = (eventName, data = {}, providers, options) => {
669
- if (!isInitialized()) {
670
- addStub({
719
+ const processTag = (destination, eventName, data = {}, providers, options) => {
720
+ if (!getSetting(destination, 'initialized')) {
721
+ addStub(destination, {
671
722
  name: 'tag',
672
723
  arguments: [eventName, data, providers, options],
673
724
  });
@@ -677,12 +728,12 @@ const handleTag = (eventName, data = {}, providers, options) => {
677
728
  if (!eventId) {
678
729
  eventId = generateEventId(eventName);
679
730
  }
680
- const providerPackages = getProvidersPackage();
681
- const configuredTags = getConfiguredTags();
682
- const userId = handleGetUserId();
731
+ const providerPackages = getProvidersPackage(destination);
732
+ const configuredTags = getSetting(destination, 'channels');
733
+ const userId = getUserId$1(destination);
683
734
  const providerData = {};
684
- const consent = getConsent$1();
685
- for (const pkg of Object.values(providerPackages)) {
735
+ const consent = getConsent$1(destination);
736
+ for (const pkg of providerPackages) {
686
737
  if (!pkg || !pkg.name || !pkg.tag) {
687
738
  continue;
688
739
  }
@@ -690,26 +741,25 @@ const handleTag = (eventName, data = {}, providers, options) => {
690
741
  log(`Provider ${pkg.name} is not in allow list`);
691
742
  continue;
692
743
  }
693
- const variables = getProviderVariables(pkg.name);
744
+ const variables = getProviderVariables(destination, pkg.name);
694
745
  const result = {};
695
- const providerVariables = Object.entries(variables);
696
746
  const executionContext = new Map();
697
- for (const [tagName, variableSet] of providerVariables) {
698
- if (!isProviderInstanceAllowed(providers, pkg.name, tagName)) {
699
- log(`Provider instance is not allowed (${pkg.name}: ${tagName})`);
747
+ for (const variable of variables) {
748
+ if (!isProviderInstanceAllowed(providers, pkg.name, variable.tagName)) {
749
+ log(`Provider instance is not allowed (${pkg.name}: ${variable.tagName})`);
700
750
  continue;
701
751
  }
702
- if (!hasUserConsent(consent, pkg.name, tagName)) {
703
- log(`Consent is missing (${pkg.name}: ${tagName})`);
752
+ if (!hasUserConsent(consent, pkg.name, variable.tagName)) {
753
+ log(`Consent is missing (${pkg.name}: ${variable.tagName})`);
704
754
  continue;
705
755
  }
706
- result[tagName] = pkg.tag({
756
+ result[variable.tagName] = pkg.tag({
707
757
  userId,
708
758
  eventName,
709
759
  eventId,
710
760
  data: JSON.parse(JSON.stringify(data)),
711
- sendTag,
712
- manifestVariables: variableSet,
761
+ sendTag: sendTag.bind(null, destination),
762
+ manifestVariables: variable.variableSet,
713
763
  executionContext,
714
764
  });
715
765
  }
@@ -718,7 +768,7 @@ const handleTag = (eventName, data = {}, providers, options) => {
718
768
  if (!hasAllowedManifestTags(configuredTags, consent, providers)) {
719
769
  return;
720
770
  }
721
- sendTag({
771
+ sendTag(destination, {
722
772
  eventName,
723
773
  eventId,
724
774
  data,
@@ -727,6 +777,15 @@ const handleTag = (eventName, data = {}, providers, options) => {
727
777
  options,
728
778
  });
729
779
  };
780
+ const handleTag = (eventName, data = {}, providers, options) => {
781
+ if (options === null || options === void 0 ? void 0 : options.destination) {
782
+ processTag(options.destination, eventName, data, providers, options);
783
+ return;
784
+ }
785
+ getInstances().forEach((instance) => {
786
+ processTag(instance, eventName, data, providers, options);
787
+ });
788
+ };
730
789
  const hasAllowedManifestTags = (tags, consent, providersConfig) => {
731
790
  for (const [pkg, tagNames] of tags) {
732
791
  for (const tagName of tagNames) {
@@ -739,29 +798,38 @@ const hasAllowedManifestTags = (tags, consent, providersConfig) => {
739
798
  return false;
740
799
  };
741
800
 
742
- const handleGetData = (keys, callback) => {
743
- if (!keys || keys.length === 0) {
744
- error('Provide keys for get data API.');
745
- return;
746
- }
747
- getRequest(getGetDataURL(keys))
801
+ const processGetData = (destination, keys, callback) => {
802
+ getRequest(getGetDataURL(destination, keys))
748
803
  .then((result) => {
749
804
  callback((result === null || result === void 0 ? void 0 : result.result) || {});
750
805
  })
751
806
  .catch(error);
752
807
  };
753
-
754
- const handleData = (data, providers, options) => {
755
- if (!data || Object.keys(data).length === 0) {
756
- error('Provide data for data API.');
808
+ const handleGetData = (keys, callback, options) => {
809
+ if (!keys || keys.length === 0) {
810
+ error('Provide keys for get data API.');
757
811
  return;
758
812
  }
759
- saveKV(data);
760
- const providerPackages = getProvidersPackage();
761
- const configuredTags = getConfiguredTags();
762
- const userId = handleGetUserId();
763
- const consent = getConsent$1();
764
- for (const pkg of Object.values(providerPackages)) {
813
+ if (options === null || options === void 0 ? void 0 : options.destination) {
814
+ processGetData(options.destination, keys, callback);
815
+ return;
816
+ }
817
+ const instances = getInstances();
818
+ if (instances.length > 1) {
819
+ error('Multiple instances found! Please provide destination.');
820
+ callback({});
821
+ return;
822
+ }
823
+ processGetData(instances[0], keys, callback);
824
+ };
825
+
826
+ const processData = (destination, data, providers, options) => {
827
+ saveKV(destination, data);
828
+ const providerPackages = getProvidersPackage(destination);
829
+ const configuredTags = getSetting(destination, 'channels');
830
+ const userId = getUserId$1(destination);
831
+ const consent = getConsent$1(destination);
832
+ for (const pkg of providerPackages) {
765
833
  if (!pkg || !pkg.user || !pkg.name) {
766
834
  continue;
767
835
  }
@@ -769,70 +837,92 @@ const handleData = (data, providers, options) => {
769
837
  log(`Provider ${pkg.name} is not in allow list`);
770
838
  continue;
771
839
  }
772
- const variables = getProviderVariables(pkg.name);
773
- for (const [tagName, variableSet] of Object.entries(variables)) {
774
- if (!isProviderInstanceAllowed(providers, pkg.name, tagName)) {
775
- log(`Data not allowed for ${pkg.name} (${tagName})`);
840
+ const variables = getProviderVariables(destination, pkg.name);
841
+ for (const variable of variables) {
842
+ if (!isProviderInstanceAllowed(providers, pkg.name, variable.tagName)) {
843
+ log(`Data not allowed for ${pkg.name} (${variable.tagName})`);
776
844
  continue;
777
845
  }
778
- if (!hasUserConsent(consent, pkg.name, tagName)) {
779
- log(`Consent is missing for ${pkg.name} (${tagName})`);
846
+ if (!hasUserConsent(consent, pkg.name, variable.tagName)) {
847
+ log(`Consent is missing for ${pkg.name} (${variable.tagName})`);
780
848
  continue;
781
849
  }
782
850
  pkg.user({
783
851
  userId,
784
852
  data,
785
- manifestVariables: variableSet,
853
+ manifestVariables: variable.variableSet,
786
854
  });
787
855
  }
788
856
  }
789
- postRequest(getDataURL(), { data, providers }, options).catch(error);
857
+ postRequest(getDataURL(destination), { data, providers }, options).catch(error);
790
858
  };
791
-
792
- let memoryConsent;
793
- const saveConsent = (consent) => {
794
- setConsent(consent);
795
- savePerKey('local', tagStorage, consent, consentKey);
859
+ const handleData = (data, providers, options) => {
860
+ if (!data || Object.keys(data).length === 0) {
861
+ error('Provide data for data API.');
862
+ return;
863
+ }
864
+ if (options === null || options === void 0 ? void 0 : options.destination) {
865
+ processData(options.destination, data, providers, options);
866
+ return;
867
+ }
868
+ getInstances().forEach((destination) => {
869
+ processData(destination, data, providers, options);
870
+ });
796
871
  };
872
+
797
873
  const handleConsent = (consent, options) => {
798
- const existingConsent = getConsent$1();
874
+ if (options === null || options === void 0 ? void 0 : options.destination) {
875
+ processConsent(options.destination, consent, options === null || options === void 0 ? void 0 : options.localSave);
876
+ return;
877
+ }
878
+ getInstances().forEach((destination) => {
879
+ processConsent(destination, consent, options === null || options === void 0 ? void 0 : options.localSave);
880
+ });
881
+ };
882
+ const saveConsent = (destination, consent) => {
883
+ setSetting({
884
+ consent,
885
+ }, destination);
886
+ savePerKey(destination, 'local', tagStorage, consent, consentKey);
887
+ };
888
+ const processConsent = (destination, consent, localSave) => {
889
+ const existingConsent = getConsent$1(destination);
799
890
  if (areEqual(existingConsent, consent)) {
800
891
  return;
801
892
  }
802
893
  const payload = {
803
894
  consentString: consent,
804
895
  };
805
- saveConsent(consent);
806
- if (!(options === null || options === void 0 ? void 0 : options.localSave)) {
807
- postRequest(getConsentURL(), payload).catch(error);
896
+ saveConsent(destination, consent);
897
+ if (!localSave) {
898
+ postRequest(getConsentURL(destination), payload).catch(error);
808
899
  }
809
- const userId = handleGetUserId();
810
- const providerPackages = getProvidersPackage();
900
+ const userId = getUserId$1(destination);
901
+ const providerPackages = getProvidersPackage(destination);
811
902
  const executionContext = new Map();
812
903
  /* Calling Init for all provider instances based on consent check */
813
- for (const pkg of Object.values(providerPackages)) {
904
+ for (const pkg of providerPackages) {
814
905
  if (!pkg || !pkg.name || !pkg.init) {
815
906
  continue;
816
907
  }
817
- const variables = getProviderVariables(pkg.name);
818
- const providerVariables = Object.entries(variables);
819
- for (const [tagName, variablesSet] of providerVariables) {
820
- const hasConsent = hasUserConsent(consent, pkg.name, tagName);
908
+ const variables = getProviderVariables(destination, pkg.name);
909
+ for (const variable of variables) {
910
+ const hasConsent = hasUserConsent(consent, pkg.name, variable.tagName);
821
911
  if (!hasConsent) {
822
912
  continue;
823
913
  }
824
914
  pkg.init({
825
915
  userId,
826
916
  isNewUser: false,
827
- baseUrl: getUrl(),
917
+ baseUrl: destination,
828
918
  manifest: {
829
- tagName,
830
- variables: variablesSet,
919
+ tagName: variable.tagName,
920
+ variables: variable.variableSet,
831
921
  package: pkg.name,
832
922
  },
833
- sendTag,
834
- sendEdgeData: handleData,
835
- getEdgeData: handleGetData,
923
+ sendTag: sendTag.bind(null, destination),
924
+ sendEdgeData: processData.bind(null, destination),
925
+ getEdgeData: processGetData.bind(null, destination),
836
926
  keyName: `${keyPrefix}Store`,
837
927
  executionContext,
838
928
  session: null,
@@ -842,6 +932,7 @@ const handleConsent = (consent, options) => {
842
932
  try {
843
933
  window.dispatchEvent(new CustomEvent('edgetag-consent', {
844
934
  detail: {
935
+ destination,
845
936
  oldConsent: existingConsent,
846
937
  newConsent: consent,
847
938
  },
@@ -860,20 +951,10 @@ const handleConsent = (consent, options) => {
860
951
  pkg.consent({ hasConsent });
861
952
  }
862
953
  };
863
- const setConsent = (newConsent) => {
864
- memoryConsent = newConsent;
865
- };
866
- const getConsent$1 = () => {
867
- const storageConsent = getDataPerKey('local', tagStorage, consentKey);
868
- if (storageConsent) {
869
- return storageConsent;
870
- }
871
- return memoryConsent;
872
- };
873
954
 
874
955
  const cacheKey = `${keyPrefix}Cache`;
875
956
  const identity = (v) => v;
876
- const saveDataToEdge = (key, value, provider) => {
957
+ const saveDataToEdge = (destination, key, value, provider) => {
877
958
  if (!value) {
878
959
  return;
879
960
  }
@@ -887,9 +968,11 @@ const saveDataToEdge = (key, value, provider) => {
887
968
  return;
888
969
  }
889
970
  }
890
- handleData({ [`${provider}::${key}`]: updatedValue });
971
+ handleData({ [`${provider}::${key}`]: updatedValue }, undefined, {
972
+ destination,
973
+ });
891
974
  };
892
- const handleCaptureQuery = (provider, key, persistType, map) => {
975
+ const handleCaptureQuery = (destination, provider, key, persistType, map) => {
893
976
  try {
894
977
  if (!window) {
895
978
  return;
@@ -898,7 +981,7 @@ const handleCaptureQuery = (provider, key, persistType, map) => {
898
981
  catch {
899
982
  return;
900
983
  }
901
- const params = new URLSearchParams(getSearch());
984
+ const params = new URLSearchParams(getSearch(destination));
902
985
  if (!params || !params.get(key)) {
903
986
  return;
904
987
  }
@@ -907,27 +990,29 @@ const handleCaptureQuery = (provider, key, persistType, map) => {
907
990
  return;
908
991
  }
909
992
  if (persistType === 'edge') {
910
- saveDataToEdge(key, data, provider);
993
+ saveDataToEdge(destination, key, data, provider);
911
994
  return;
912
995
  }
913
- saveDataPerKey(persistType, provider, data, key);
996
+ saveDataPerKey(destination, persistType, provider, data, key);
914
997
  };
915
- const getFromCache = (persistType, provider, key) => {
998
+ const getFromCache = (destination, persistType, provider, key) => {
916
999
  var _a;
917
- const cache = getData$1(persistType === 'edge' ? 'local' : persistType, cacheKey);
1000
+ const type = persistType === 'edge' ? 'local' : persistType;
1001
+ const cache = getData$1(destination, type, cacheKey);
918
1002
  return (_a = cache[provider]) === null || _a === void 0 ? void 0 : _a[key];
919
1003
  };
920
- const saveToCache = (persistType, provider, key, value) => {
921
- const cache = getData$1(persistType === 'edge' ? 'local' : persistType, cacheKey);
1004
+ const saveToCache = (destination, persistType, provider, key, value) => {
1005
+ const type = persistType === 'edge' ? 'local' : persistType;
1006
+ const cache = getData$1(destination, type, cacheKey);
922
1007
  if (!cache[provider]) {
923
1008
  cache[provider] = { [key]: value };
924
1009
  }
925
1010
  else {
926
1011
  cache[provider][key] = value;
927
1012
  }
928
- saveData(persistType === 'edge' ? 'local' : persistType, cache, cacheKey);
1013
+ saveData(destination, type, cache, cacheKey);
929
1014
  };
930
- const handleCaptureStorage = (provider, key, persistType, location, map) => {
1015
+ const handleCaptureStorage = (destination, provider, key, persistType, location, map) => {
931
1016
  let data;
932
1017
  try {
933
1018
  switch (location) {
@@ -950,44 +1035,43 @@ const handleCaptureStorage = (provider, key, persistType, location, map) => {
950
1035
  if (!data) {
951
1036
  return;
952
1037
  }
953
- const cachedKey = `${handleGetUserId()}/${key}`;
954
- const cachedValue = getFromCache(persistType, provider, cachedKey);
1038
+ const cachedKey = `${getUserId$1(destination)}/${key}`;
1039
+ const cachedValue = getFromCache(destination, persistType, provider, cachedKey);
955
1040
  if (persistType === 'edge' && cachedValue !== data) {
956
- saveDataToEdge(key, data, provider);
957
- saveToCache(persistType, provider, cachedKey, data);
1041
+ saveDataToEdge(destination, key, data, provider);
1042
+ saveToCache(destination, persistType, provider, cachedKey, data);
958
1043
  return;
959
1044
  }
960
- saveDataPerKey(persistType, provider, data, key);
1045
+ saveDataPerKey(destination, persistType, provider, data, key);
961
1046
  };
962
- const handleCapture = (provider, params, capture) => {
1047
+ const handleCapture = (destination, provider, params, capture) => {
963
1048
  params.forEach((param) => {
964
1049
  switch (param.type) {
965
1050
  case 'query': {
966
- handleCaptureQuery(provider, param.key, param.persist, capture === null || capture === void 0 ? void 0 : capture.bind(null, param));
1051
+ handleCaptureQuery(destination, provider, param.key, param.persist, capture === null || capture === void 0 ? void 0 : capture.bind(null, param));
967
1052
  break;
968
1053
  }
969
1054
  case 'storage': {
970
- handleCaptureStorage(provider, param.key, param.persist, param.location, capture === null || capture === void 0 ? void 0 : capture.bind(null, param));
1055
+ handleCaptureStorage(destination, provider, param.key, param.persist, param.location, capture === null || capture === void 0 ? void 0 : capture.bind(null, param));
971
1056
  break;
972
1057
  }
973
1058
  }
974
1059
  });
975
1060
  };
976
1061
 
977
- const handleManifest = (response, consent) => {
978
- const providerPackages = getProvidersPackage();
979
- const userId = handleGetUserId();
1062
+ const handleManifest = (destination, response) => {
1063
+ const providerPackages = getProvidersPackage(destination);
1064
+ const userId = getUserId$1(destination);
980
1065
  const executionContext = new Map();
981
1066
  const manifest = response.result;
982
1067
  manifest.forEach((provider) => {
983
- addConfiguredTag(provider.package, provider.tagName);
984
- addProviderVariable(provider.package, provider.variables, provider.tagName);
985
- const pkg = providerPackages[provider.package];
1068
+ addChannel(destination, provider.package, provider.tagName);
1069
+ const pkg = providerPackages.find((pkg) => pkg.name === provider.package);
986
1070
  if (provider.rules) {
987
1071
  Object.entries(provider.rules).forEach(([name, recipe]) => {
988
1072
  switch (name) {
989
1073
  case 'capture': {
990
- handleCapture(provider.package, recipe, pkg === null || pkg === void 0 ? void 0 : pkg.capture);
1074
+ handleCapture(destination, provider.package, recipe, pkg === null || pkg === void 0 ? void 0 : pkg.capture);
991
1075
  return;
992
1076
  }
993
1077
  }
@@ -995,36 +1079,27 @@ const handleManifest = (response, consent) => {
995
1079
  }
996
1080
  if (pkg && pkg.name && pkg.init) {
997
1081
  /* this defines if the consent is given for a specific instance of a provider */
998
- const hasConsent = hasUserConsent(consent, pkg.name, provider.tagName);
1082
+ const hasConsent = hasUserConsent(getSetting(destination, 'consent'), pkg.name, provider.tagName);
999
1083
  if (hasConsent) {
1000
1084
  pkg.init({
1001
1085
  userId,
1002
1086
  isNewUser: !!response.isNewUser,
1003
1087
  session: response.session,
1004
- baseUrl: getUrl(),
1088
+ baseUrl: destination,
1005
1089
  manifest: provider,
1006
- sendTag,
1007
- sendEdgeData: handleData,
1008
- getEdgeData: handleGetData,
1090
+ sendTag: sendTag.bind(null, destination),
1091
+ sendEdgeData: processData.bind(null, destination),
1092
+ getEdgeData: processGetData.bind(null, destination),
1009
1093
  keyName: `${keyPrefix}Store`,
1010
1094
  executionContext,
1011
1095
  });
1012
1096
  }
1013
1097
  }
1014
1098
  });
1015
- setInitialized();
1016
- processStubs();
1017
- };
1018
-
1019
- let initIsNewUser = undefined;
1020
- const handleIsNewUser = () => {
1021
- if (initIsNewUser !== undefined) {
1022
- return initIsNewUser;
1023
- }
1024
- return undefined;
1025
- };
1026
- const setIsNewUSer = (isNewUser) => {
1027
- initIsNewUser = isNewUser;
1099
+ setSetting({
1100
+ initialized: true,
1101
+ }, destination);
1102
+ processStubs(destination);
1028
1103
  };
1029
1104
 
1030
1105
  const handleInit = (preferences) => {
@@ -1033,15 +1108,17 @@ const handleInit = (preferences) => {
1033
1108
  return;
1034
1109
  }
1035
1110
  if (preferences.afterManifestEvents) {
1036
- addStubs(preferences.afterManifestEvents);
1111
+ setSetting({
1112
+ stubs: preferences.afterManifestEvents,
1113
+ }, preferences.edgeURL);
1037
1114
  }
1038
- const url = new URL(getInitURL());
1115
+ const url = new URL(getInitURL(preferences.edgeURL));
1039
1116
  if (preferences.disableConsentCheck) {
1040
1117
  url.searchParams.set('consentDisabled', 'true');
1041
- saveConsent({ all: true });
1118
+ saveConsent(preferences.edgeURL, { all: true });
1042
1119
  }
1043
1120
  if (preferences.userId) {
1044
- setUserId(preferences.userId);
1121
+ setSetting({ userId: preferences.userId }, preferences.edgeURL);
1045
1122
  url.searchParams.set('userId', preferences.userId);
1046
1123
  }
1047
1124
  getRequest(url.href)
@@ -1050,18 +1127,17 @@ const handleInit = (preferences) => {
1050
1127
  error('Initialization failed');
1051
1128
  return;
1052
1129
  }
1053
- if (result.userId) {
1054
- setUserId(result.userId);
1055
- }
1056
- const consent = getConsent$1();
1057
- if (result.consent && !consent) {
1058
- saveConsent(result.consent);
1059
- }
1060
- setIsNewUSer(result.isNewUser);
1061
- handleManifest(result, consent || result.consent);
1130
+ setSetting({
1131
+ isNewUser: result.isNewUser,
1132
+ consent: getConsent$1(preferences.edgeURL) || result.consent,
1133
+ userId: result.userId,
1134
+ packages: result.result,
1135
+ }, preferences.edgeURL);
1136
+ handleManifest(preferences.edgeURL, result);
1062
1137
  try {
1063
1138
  window.dispatchEvent(new CustomEvent('edgetag-initialized', {
1064
1139
  detail: {
1140
+ destination: preferences.edgeURL,
1065
1141
  userId: result.userId,
1066
1142
  isNewUser: result.isNewUser,
1067
1143
  consent: result.consent,
@@ -1077,19 +1153,15 @@ const handleInit = (preferences) => {
1077
1153
  .catch(error);
1078
1154
  };
1079
1155
 
1080
- const handleUser = (key, value, providers, options) => {
1081
- if (!key || !value) {
1082
- error('Key or Value is missing in user API.');
1083
- return;
1084
- }
1085
- saveKV({
1156
+ const processUser = (destination, key, value, providers, options) => {
1157
+ saveKV(destination, {
1086
1158
  [key]: value,
1087
1159
  });
1088
- const providerPackages = getProvidersPackage();
1089
- const configuredTags = getConfiguredTags();
1090
- const consent = getConsent$1();
1091
- const userId = handleGetUserId();
1092
- for (const pkg of Object.values(providerPackages)) {
1160
+ const providerPackages = getProvidersPackage(destination);
1161
+ const configuredTags = getSetting(destination, 'channels');
1162
+ const consent = getConsent$1(destination);
1163
+ const userId = getUserId$1(destination);
1164
+ for (const pkg of providerPackages) {
1093
1165
  if (!pkg || !pkg.name || !pkg.user) {
1094
1166
  continue;
1095
1167
  }
@@ -1097,47 +1169,73 @@ const handleUser = (key, value, providers, options) => {
1097
1169
  log(`Provider ${pkg.name} is not in allow list`);
1098
1170
  continue;
1099
1171
  }
1100
- const variables = getProviderVariables(pkg.name);
1101
- for (const [tagName, variableSet] of Object.entries(variables)) {
1102
- if (!isProviderInstanceAllowed(providers, pkg.name, tagName)) {
1103
- log(`User not allowed for ${pkg.name} (${tagName})`);
1172
+ const variables = getProviderVariables(destination, pkg.name);
1173
+ for (const variable of variables) {
1174
+ if (!isProviderInstanceAllowed(providers, pkg.name, variable.tagName)) {
1175
+ log(`User not allowed for ${pkg.name} (${variable.tagName})`);
1104
1176
  continue;
1105
1177
  }
1106
- if (!hasUserConsent(consent, pkg.name, tagName)) {
1107
- log(`User doesn't have consent for ${pkg.name} (${tagName})`);
1178
+ if (!hasUserConsent(consent, pkg.name, variable.tagName)) {
1179
+ log(`User doesn't have consent for ${pkg.name} (${variable.tagName})`);
1108
1180
  continue;
1109
1181
  }
1110
1182
  pkg.user({
1111
1183
  userId,
1112
1184
  data: { [key]: value },
1113
- manifestVariables: variableSet,
1185
+ manifestVariables: variable.variableSet,
1114
1186
  });
1115
1187
  }
1116
1188
  }
1117
- postRequest(getUserURL(), {
1189
+ postRequest(getUserURL(destination), {
1118
1190
  key,
1119
1191
  value,
1120
1192
  providers,
1121
1193
  }, options).catch(error);
1122
1194
  };
1195
+ const handleUser = (key, value, providers, options) => {
1196
+ if (!key || !value) {
1197
+ error('Key or Value is missing in user API.');
1198
+ return;
1199
+ }
1200
+ if (options === null || options === void 0 ? void 0 : options.destination) {
1201
+ processUser(options.destination, key, value, providers, options);
1202
+ return;
1203
+ }
1204
+ getInstances().forEach((destination) => {
1205
+ processUser(destination, key, value, providers, options);
1206
+ });
1207
+ };
1123
1208
 
1124
- const handleKeys = (callback) => {
1125
- getRequest(getKeysURL())
1209
+ const processKeys = (destination, callback) => {
1210
+ getRequest(getKeysURL(destination))
1126
1211
  .then((result) => {
1127
1212
  callback((result === null || result === void 0 ? void 0 : result.result) || []);
1128
1213
  })
1129
1214
  .catch(error);
1130
1215
  };
1216
+ const handleKeys = (callback, options) => {
1217
+ if (options === null || options === void 0 ? void 0 : options.destination) {
1218
+ processKeys(options.destination, callback);
1219
+ return;
1220
+ }
1221
+ const instances = getInstances();
1222
+ if (instances.length > 1) {
1223
+ error('Multiple instances found! Please provide destination.');
1224
+ callback([]);
1225
+ return;
1226
+ }
1227
+ processKeys(instances[0], callback);
1228
+ };
1131
1229
 
1132
- const handleGetConsent = (callback) => {
1133
- getRequest(getConsentURL())
1230
+ const processGetConsent = (destination, callback) => {
1231
+ getRequest(getConsentURL(destination))
1134
1232
  .then((result) => {
1135
1233
  // this will try to return the consent data stored in Edge
1136
1234
  return result === null || result === void 0 ? void 0 : result.result;
1137
1235
  })
1138
1236
  .catch(() => undefined)
1139
1237
  .then((result) => {
1140
- const consent = result !== null && result !== void 0 ? result : getConsent$1(); // this is a default value i.e. value from local storage and memory incase Edge doesn't have consent
1238
+ const consent = result !== null && result !== void 0 ? result : getConsent$1(destination); // this is a default value i.e. value from local storage and memory incase Edge doesn't have consent
1141
1239
  if (consent) {
1142
1240
  callback(consent);
1143
1241
  }
@@ -1146,9 +1244,48 @@ const handleGetConsent = (callback) => {
1146
1244
  }
1147
1245
  });
1148
1246
  };
1247
+ const handleGetConsent = (callback, options) => {
1248
+ if (options === null || options === void 0 ? void 0 : options.destination) {
1249
+ processGetConsent(options.destination, callback);
1250
+ return;
1251
+ }
1252
+ const instances = getInstances();
1253
+ if (instances.length > 1) {
1254
+ callback(null, new Error('Multiple instances found! Please provide destination.'));
1255
+ return;
1256
+ }
1257
+ processGetConsent(instances[0], callback);
1258
+ };
1149
1259
 
1150
- const handleConfig = (config) => {
1151
- setConfig$1(config);
1260
+ const handleIsNewUser = (options) => {
1261
+ if (options === null || options === void 0 ? void 0 : options.destination) {
1262
+ return getSetting(options.destination, 'isNewUser');
1263
+ }
1264
+ const instances = getInstances();
1265
+ if (instances.length > 1) {
1266
+ error('Multiple instances found! Please provide destination.');
1267
+ return undefined;
1268
+ }
1269
+ return getSetting(instances[0], 'isNewUser');
1270
+ };
1271
+
1272
+ const processConfig = (destination, config) => {
1273
+ const existingConfig = getSetting(destination, 'config');
1274
+ setSetting({
1275
+ config: {
1276
+ ...existingConfig,
1277
+ ...config,
1278
+ },
1279
+ }, destination);
1280
+ };
1281
+ const handleConfig = (config, options) => {
1282
+ if (options === null || options === void 0 ? void 0 : options.destination) {
1283
+ processConfig(options.destination, config);
1284
+ return;
1285
+ }
1286
+ getInstances().forEach((destination) => {
1287
+ processConfig(destination, config);
1288
+ });
1152
1289
  };
1153
1290
 
1154
1291
  const init = (preferences) => {
@@ -1166,23 +1303,23 @@ const user = (key, value, providers, options) => {
1166
1303
  const data = (value, providers, options) => {
1167
1304
  handleData(value, providers, options);
1168
1305
  };
1169
- const getData = (keys, callback) => {
1170
- handleGetData(keys, callback);
1306
+ const getData = (keys, callback, options) => {
1307
+ handleGetData(keys, callback, options);
1171
1308
  };
1172
- const keys = (callback) => {
1173
- handleKeys(callback);
1309
+ const keys = (callback, options) => {
1310
+ handleKeys(callback, options);
1174
1311
  };
1175
- const getUserId = () => {
1176
- return handleGetUserId();
1312
+ const getUserId = (options) => {
1313
+ return handleGetUserId(options);
1177
1314
  };
1178
- const getConsent = (callback) => {
1179
- handleGetConsent(callback);
1315
+ const getConsent = (callback, options) => {
1316
+ handleGetConsent(callback, options);
1180
1317
  };
1181
- const isNewUser = () => {
1182
- return handleIsNewUser();
1318
+ const isNewUser = (options) => {
1319
+ return handleIsNewUser(options);
1183
1320
  };
1184
- const setConfig = (config) => {
1185
- return handleConfig(config);
1321
+ const setConfig = (config, options) => {
1322
+ handleConfig(config, options);
1186
1323
  };
1187
1324
 
1188
1325
  exports.consent = consent;