@blotoutio/edgetag-sdk-browser 0.6.9 → 0.7.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 (3) hide show
  1. package/README.md +1 -1
  2. package/index.js +311 -182
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
1
  # EdgeTag SDK Browser
2
2
 
3
- More info on https://app.edgetag.io/integration/js
3
+ More info on https://app.edgetag.io/docs/js
package/index.js CHANGED
@@ -38,132 +38,6 @@
38
38
  });
39
39
  }
40
40
 
41
- const tagStorage = 'edgeTag';
42
- const consentKey = 'consent';
43
- const keyPrefix = `_worker`;
44
-
45
- const initKey = `${keyPrefix}Store`;
46
- const getCookieValue = (key) => {
47
- if (!document || !document.cookie) {
48
- return '';
49
- }
50
- const name = `${key}=`;
51
- const decodedCookie = decodeURIComponent(document.cookie);
52
- const ca = decodedCookie.split(';');
53
- for (let i = 0; i < ca.length; i++) {
54
- let c = ca[i];
55
- while (c.charAt(0) === ' ') {
56
- c = c.substring(1);
57
- }
58
- if (c.indexOf(name) === 0) {
59
- return c.substring(name.length, c.length);
60
- }
61
- }
62
- return '';
63
- };
64
- const saveDataPerKey = (persistType, provider, value, key) => {
65
- const storage = getData$1(persistType);
66
- if (!storage['data']) {
67
- storage['data'] = {};
68
- }
69
- if (!storage['data'][provider]) {
70
- storage['data'][provider] = {};
71
- }
72
- storage['data'][provider][key] = value;
73
- saveData(persistType, storage);
74
- };
75
- const savePerKey = (persistType, provider, value, key) => {
76
- const storage = getData$1(persistType);
77
- if (!storage[provider]) {
78
- storage[provider] = {};
79
- }
80
- storage[provider][key] = value;
81
- saveData(persistType, storage);
82
- };
83
- const getDataPerKey = (persistType, provider, key) => {
84
- const storage = getData$1(persistType);
85
- if (!storage[provider]) {
86
- return undefined;
87
- }
88
- return storage[provider][key];
89
- };
90
- const saveData = (persistType, value, key = initKey) => {
91
- if (persistType === 'session') {
92
- saveSession(value, key);
93
- return;
94
- }
95
- saveLocal(value, key);
96
- };
97
- const getData$1 = (persistType, key = initKey) => {
98
- if (persistType === 'session') {
99
- return getSession(key);
100
- }
101
- return getLocal(key);
102
- };
103
- const saveKV = (data) => {
104
- let currentSession = getData$1('session');
105
- if (!currentSession) {
106
- currentSession = {};
107
- }
108
- if (!currentSession['kv']) {
109
- currentSession['kv'] = {};
110
- }
111
- currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
112
- saveData('session', currentSession);
113
- };
114
- const saveLocal = (value, key) => {
115
- try {
116
- if (!localStorage) {
117
- return;
118
- }
119
- localStorage.setItem(key, JSON.stringify(value));
120
- }
121
- catch (_a) {
122
- console.log('Local storage not supported');
123
- }
124
- };
125
- const getLocal = (key) => {
126
- try {
127
- if (!localStorage) {
128
- return {};
129
- }
130
- const data = localStorage.getItem(key);
131
- if (!data) {
132
- return {};
133
- }
134
- return JSON.parse(data) || {};
135
- }
136
- catch (_a) {
137
- return {};
138
- }
139
- };
140
- const saveSession = (value, key) => {
141
- try {
142
- if (!sessionStorage) {
143
- return;
144
- }
145
- sessionStorage.setItem(key, JSON.stringify(value));
146
- }
147
- catch (_a) {
148
- console.log('Session storage not supported');
149
- }
150
- };
151
- const getSession = (key) => {
152
- try {
153
- if (!sessionStorage) {
154
- return {};
155
- }
156
- const data = sessionStorage.getItem(key);
157
- if (!data) {
158
- return {};
159
- }
160
- return JSON.parse(data) || {};
161
- }
162
- catch (_a) {
163
- return {};
164
- }
165
- };
166
-
167
41
  let endpointUrl = '';
168
42
  const generateUrl = (path) => {
169
43
  const endpoint = getUrl();
@@ -224,13 +98,18 @@
224
98
  }
225
99
  providersPackages[provider.name] = provider;
226
100
  });
227
- if (window && Array.isArray(window.edgetagProviders)) {
228
- window.edgetagProviders.forEach((provider) => {
229
- if (!provider.name) {
230
- return;
231
- }
232
- providersPackages[provider.name] = provider;
233
- });
101
+ try {
102
+ if (window && Array.isArray(window.edgetagProviders)) {
103
+ window.edgetagProviders.forEach((provider) => {
104
+ if (!provider.name) {
105
+ return;
106
+ }
107
+ providersPackages[provider.name] = provider;
108
+ });
109
+ }
110
+ }
111
+ catch (_b) {
112
+ // do nothing
234
113
  }
235
114
  setUrl(preferences.edgeURL);
236
115
  return true;
@@ -246,44 +125,75 @@
246
125
  allowedProvider = providers;
247
126
  };
248
127
 
249
- const getUserAgent = () => {
250
- const nav = navigator;
251
- let ua = nav.userAgent;
252
- ua += nav.brave ? `${ua} Brave` : '';
253
- return ua;
254
- };
255
- const allowTag = (providers) => {
256
- if (!allowProviders(providers)) {
257
- return false;
258
- }
259
- const consent = getDataPerKey('local', tagStorage, consentKey);
128
+ const checkConsent = (providers) => {
260
129
  if (isConsentDisabled()) {
261
130
  return true;
262
131
  }
132
+ const consent = getConsent();
263
133
  if (!consent) {
264
134
  return false;
265
135
  }
266
- if (consent['all']) {
267
- return true;
136
+ const consentLength = Object.keys(consent).length;
137
+ if (!consentLength || (consentLength === 1 && consent['all'] === false)) {
138
+ return false;
268
139
  }
269
- if (!providers) {
140
+ const providersLength = Object.keys(providers || {}).length;
141
+ if (!providers ||
142
+ providersLength === 0 ||
143
+ (providersLength === 1 && providers['all'])) {
270
144
  return (Object.values(consent).find((isAllowed) => isAllowed) || false);
271
145
  }
272
- const allProviders = getAllowedProviders();
273
- for (const provider of allProviders) {
274
- const tagProviderSetting = providers[provider];
275
- if (tagProviderSetting ||
276
- (providers['all'] === true && tagProviderSetting === undefined) ||
277
- (providers['all'] === false && tagProviderSetting === true)) {
278
- if (consent[provider]) {
146
+ for (const [key, value] of Object.entries(providers)) {
147
+ if (value === false || consent[key] === false) {
148
+ continue;
149
+ }
150
+ // we have consent
151
+ if (consent[key] ||
152
+ (consent['all'] === true && consent[key] === undefined)) {
153
+ // we have provider
154
+ if (value || (providers['all'] && providers[key] === undefined)) {
279
155
  return true;
280
156
  }
281
157
  }
282
158
  }
283
159
  return false;
284
160
  };
161
+ const getUserAgent = () => {
162
+ try {
163
+ const nav = navigator;
164
+ let ua = nav.userAgent;
165
+ ua += nav.brave ? `${ua} Brave` : '';
166
+ return ua;
167
+ }
168
+ catch (_a) {
169
+ return '';
170
+ }
171
+ };
172
+ const isProviderIncluded = (providers, providerValue) => {
173
+ return (providerValue || (providers['all'] === true && providerValue === undefined));
174
+ };
175
+ const allowTag = (providers) => {
176
+ if (!checkConsent(providers)) {
177
+ return false;
178
+ }
179
+ const providersLength = Object.values(providers || {}).length;
180
+ if (!providers || providersLength === 0) {
181
+ return true;
182
+ }
183
+ const allProviders = getAllowedProviders();
184
+ const allProvidersLength = Object.keys(allProviders || {}).length;
185
+ if (allProvidersLength === 0) {
186
+ return true;
187
+ }
188
+ for (const provider of allProviders) {
189
+ if (isProviderIncluded(providers, providers[provider])) {
190
+ return true;
191
+ }
192
+ }
193
+ return false;
194
+ };
285
195
  const allowProviders = (providers) => {
286
- if (!providers || Object.keys(providers).length === 0) {
196
+ if (!providers || Object.keys(providers).length === 0 || providers['all']) {
287
197
  return true;
288
198
  }
289
199
  const allowedProvider = getAllowedProviders();
@@ -315,41 +225,223 @@
315
225
  if (!allowProvider(providerId)) {
316
226
  return false;
317
227
  }
228
+ if (!checkConsent(providers)) {
229
+ return false;
230
+ }
318
231
  if (providers && Object.keys(providers).length) {
319
- const tagProvider = providers[providerId];
320
- if (!(tagProvider ||
321
- (providers['all'] === true && tagProvider === undefined) ||
322
- (providers['all'] === false && tagProvider === true))) {
232
+ if (!isProviderIncluded(providers, providers[providerId])) {
323
233
  return false;
324
234
  }
325
235
  }
326
- const consent = getDataPerKey('local', tagStorage, consentKey);
327
- if (isConsentDisabled()) {
328
- return true;
236
+ return true;
237
+ };
238
+
239
+ const tagStorage = 'edgeTag';
240
+ const consentKey = 'consent';
241
+ const keyPrefix = `_worker`;
242
+
243
+ const initKey = `${keyPrefix}Store`;
244
+ const getCookieValue = (key) => {
245
+ try {
246
+ if (!document || !document.cookie) {
247
+ return '';
248
+ }
249
+ const name = `${key}=`;
250
+ const decodedCookie = decodeURIComponent(document.cookie);
251
+ const ca = decodedCookie.split(';');
252
+ for (let i = 0; i < ca.length; i++) {
253
+ let c = ca[i];
254
+ while (c.charAt(0) === ' ') {
255
+ c = c.substring(1);
256
+ }
257
+ if (c.indexOf(name) === 0) {
258
+ return c.substring(name.length, c.length);
259
+ }
260
+ }
261
+ return '';
329
262
  }
330
- if (!consent) {
331
- return false;
263
+ catch (_a) {
264
+ return '';
332
265
  }
333
- if (consent['all']) {
334
- return true;
266
+ };
267
+ const saveDataPerKey = (persistType, provider, value, key) => {
268
+ const storage = getData$1(persistType);
269
+ if (!storage['data']) {
270
+ storage['data'] = {};
271
+ }
272
+ if (!storage['data'][provider]) {
273
+ storage['data'][provider] = {};
274
+ }
275
+ storage['data'][provider][key] = value;
276
+ saveData(persistType, storage);
277
+ };
278
+ const savePerKey = (persistType, provider, value, key) => {
279
+ const storage = getData$1(persistType);
280
+ if (!storage[provider]) {
281
+ storage[provider] = {};
282
+ }
283
+ storage[provider][key] = value;
284
+ saveData(persistType, storage);
285
+ };
286
+ const getDataPerKey = (persistType, provider, key) => {
287
+ const storage = getData$1(persistType);
288
+ if (!storage[provider]) {
289
+ return undefined;
290
+ }
291
+ return storage[provider][key];
292
+ };
293
+ const saveData = (persistType, value, key = initKey) => {
294
+ if (persistType === 'session') {
295
+ saveSession(value, key);
296
+ return;
335
297
  }
336
- return consent[providerId];
298
+ saveLocal(value, key);
299
+ };
300
+ const getData$1 = (persistType, key = initKey) => {
301
+ if (persistType === 'session') {
302
+ return getSession(key);
303
+ }
304
+ return getLocal(key);
305
+ };
306
+ const saveKV = (data) => {
307
+ let currentSession = getData$1('session');
308
+ if (!currentSession) {
309
+ currentSession = {};
310
+ }
311
+ if (!currentSession['kv']) {
312
+ currentSession['kv'] = {};
313
+ }
314
+ currentSession['kv'] = Object.assign(Object.assign({}, currentSession['kv']), data);
315
+ saveData('session', currentSession);
316
+ };
317
+ const saveLocal = (value, key) => {
318
+ try {
319
+ if (!localStorage) {
320
+ return;
321
+ }
322
+ localStorage.setItem(key, JSON.stringify(value));
323
+ }
324
+ catch (_a) {
325
+ console.log('Local storage not supported');
326
+ }
327
+ };
328
+ const getLocal = (key) => {
329
+ try {
330
+ if (!localStorage) {
331
+ return {};
332
+ }
333
+ const data = localStorage.getItem(key);
334
+ if (!data) {
335
+ return {};
336
+ }
337
+ return JSON.parse(data) || {};
338
+ }
339
+ catch (_a) {
340
+ return {};
341
+ }
342
+ };
343
+ const saveSession = (value, key) => {
344
+ try {
345
+ if (!sessionStorage) {
346
+ return;
347
+ }
348
+ sessionStorage.setItem(key, JSON.stringify(value));
349
+ }
350
+ catch (_a) {
351
+ console.log('Session storage not supported');
352
+ }
353
+ };
354
+ const getSession = (key) => {
355
+ try {
356
+ if (!sessionStorage) {
357
+ return {};
358
+ }
359
+ const data = sessionStorage.getItem(key);
360
+ if (!data) {
361
+ return {};
362
+ }
363
+ return JSON.parse(data) || {};
364
+ }
365
+ catch (_a) {
366
+ return {};
367
+ }
368
+ };
369
+
370
+ let initUserId = '';
371
+ const handleGetUserId = () => {
372
+ if (initUserId) {
373
+ return initUserId;
374
+ }
375
+ return getCookieValue('tag_user_id');
376
+ };
377
+ const setUserId = (userId) => {
378
+ initUserId = userId;
337
379
  };
338
380
 
381
+ const getHeaders = () => ({
382
+ 'Content-type': 'application/json; charset=utf-8',
383
+ Accept: 'application/json; charset=utf-8',
384
+ EdgeTagUserId: handleGetUserId(),
385
+ });
339
386
  const beacon = (url, payload) => {
340
- let blob;
341
- if (payload) {
342
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
387
+ try {
388
+ let blob;
389
+ if (payload) {
390
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
391
+ }
392
+ return navigator.sendBeacon(url, blob);
393
+ }
394
+ catch (e) {
395
+ console.log('Beacon not supported.');
396
+ return Promise.reject(new Error('Beacon not supported'));
343
397
  }
344
- return navigator.sendBeacon(url, blob);
345
398
  };
399
+ const fallbackAjax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
400
+ const https = yield import('https');
401
+ const options = {
402
+ method,
403
+ headers: getHeaders(),
404
+ };
405
+ return new Promise((resolve, reject) => {
406
+ const req = https.request(url, options, (res) => {
407
+ res.on('data', (data) => {
408
+ try {
409
+ data = JSON.parse(data);
410
+ }
411
+ catch (_a) {
412
+ // do nothing
413
+ }
414
+ resolve({
415
+ body: data,
416
+ status: res.statusCode || 500,
417
+ });
418
+ });
419
+ });
420
+ req.on('error', (e) => {
421
+ reject(new Error(e.message));
422
+ });
423
+ if (payload && method !== 'GET') {
424
+ req.write(JSON.stringify(payload));
425
+ }
426
+ req.end();
427
+ });
428
+ });
346
429
  const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
430
+ if (typeof fetch === 'undefined') {
431
+ return yield fallbackAjax(method, url, payload)
432
+ .then((data) => {
433
+ if (data.status < 200 || data.status >= 300) {
434
+ return Promise.reject(new Error(JSON.stringify(data.body)));
435
+ }
436
+ return Promise.resolve(data.body);
437
+ })
438
+ .catch((error) => {
439
+ return Promise.reject(new Error(error));
440
+ });
441
+ }
347
442
  return yield fetch(url, {
348
443
  method,
349
- headers: {
350
- 'Content-type': 'application/json; charset=utf-8',
351
- Accept: 'application/json; charset=utf-8',
352
- },
444
+ headers: getHeaders(),
353
445
  body: JSON.stringify(payload),
354
446
  credentials: 'include',
355
447
  })
@@ -367,7 +459,14 @@
367
459
  });
368
460
  });
369
461
  const getStandardPayload = (payload) => {
370
- const data = Object.assign({ pageUrl: window.location.href, userAgent: getUserAgent() }, (payload || {}));
462
+ let pageUrl;
463
+ try {
464
+ pageUrl = window.location.href;
465
+ }
466
+ catch (_a) {
467
+ pageUrl = '';
468
+ }
469
+ const data = Object.assign({ pageUrl, userAgent: getUserAgent() }, (payload || {}));
371
470
  let storage = {};
372
471
  const session = getData$1('session');
373
472
  if (session) {
@@ -409,7 +508,9 @@
409
508
  const info = (data) => {
410
509
  };
411
510
 
511
+ let memoryConsent;
412
512
  const saveConsent = (consent) => {
513
+ setConsent(consent);
413
514
  savePerKey('local', tagStorage, consent, consentKey);
414
515
  };
415
516
  const handleConsent = (consent) => {
@@ -419,6 +520,16 @@
419
520
  saveConsent(consent);
420
521
  postRequest(getConsentURL(), payload).catch(info);
421
522
  };
523
+ const setConsent = (newConsent) => {
524
+ memoryConsent = newConsent;
525
+ };
526
+ const getConsent = () => {
527
+ const storageConsent = getDataPerKey('local', tagStorage, consentKey);
528
+ if (storageConsent) {
529
+ return storageConsent;
530
+ }
531
+ return memoryConsent;
532
+ };
422
533
 
423
534
  // Unique ID creation requires a high quality random # generator. In the browser we therefore
424
535
  // require the crypto API and do not support built-in fallback to lower quality random number
@@ -900,6 +1011,12 @@
900
1011
 
901
1012
  v35('v5', 0x50, sha1);
902
1013
 
1014
+ const encodeString = (name) => {
1015
+ if (typeof btoa === 'undefined') {
1016
+ return Buffer.from(name).toString('base64');
1017
+ }
1018
+ return btoa(name);
1019
+ };
903
1020
  const generateEventId = (name) => {
904
1021
  let time = Date.now().toString();
905
1022
  if (typeof performance !== 'undefined' &&
@@ -909,11 +1026,7 @@
909
1026
  time = perf.toFixed(4);
910
1027
  }
911
1028
  }
912
- return `${btoa(name)}-${v4()}-${time}`;
913
- };
914
-
915
- const handleGetUserId = () => {
916
- return getCookieValue('tag_user_id');
1029
+ return `${encodeString(name)}-${v4()}-${time}`;
917
1030
  };
918
1031
 
919
1032
  const manifestVariables = {};
@@ -934,6 +1047,7 @@
934
1047
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
935
1048
  // @ts-ignore
936
1049
  stubs.forEach((stub) => api$1[stub.name](...(stub.arguments || [])));
1050
+ stubs = [];
937
1051
  }
938
1052
  catch (e) {
939
1053
  console.error(e);
@@ -942,6 +1056,7 @@
942
1056
 
943
1057
  const sendTag = ({ eventName, eventId, data, providerData, providers, options, }) => {
944
1058
  if (!allowProviders(providers)) {
1059
+ console.log('Provider is not allowed.');
945
1060
  return;
946
1061
  }
947
1062
  const payload = {
@@ -964,6 +1079,10 @@
964
1079
  });
965
1080
  return;
966
1081
  }
1082
+ if (!allowProviders(providers)) {
1083
+ console.log('Provider is not allowed.');
1084
+ return;
1085
+ }
967
1086
  if (!allowTag(providers)) {
968
1087
  console.log('No consent');
969
1088
  return;
@@ -1028,7 +1147,12 @@
1028
1147
  handleData({ [`${provider}::${key}`]: value });
1029
1148
  };
1030
1149
  const handleCaptureQuery = (provider, key, persistType) => {
1031
- if (!window) {
1150
+ try {
1151
+ if (!window) {
1152
+ return;
1153
+ }
1154
+ }
1155
+ catch (_a) {
1032
1156
  return;
1033
1157
  }
1034
1158
  const params = new URLSearchParams(window.location.search);
@@ -1130,6 +1254,7 @@
1130
1254
  saveConsent({ all: true });
1131
1255
  }
1132
1256
  if (preferences.userId) {
1257
+ setUserId(preferences.userId);
1133
1258
  url.searchParams.set('userId', preferences.userId);
1134
1259
  }
1135
1260
  getRequest(url.href)
@@ -1232,6 +1357,10 @@
1232
1357
  keys(callback) {
1233
1358
  keys(callback);
1234
1359
  }
1360
+
1361
+ getUserId() {
1362
+ return getUserId()
1363
+ }
1235
1364
  }
1236
1365
 
1237
1366
  var api = new API();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-browser",
3
- "version": "0.6.9",
3
+ "version": "0.7.1",
4
4
  "description": "Browser SDK for EdgeTag",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",