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