@blotoutio/edgetag-sdk-browser 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,470 +1,377 @@
1
1
  (function (factory) {
2
- typeof define === 'function' && define.amd ? define(factory) :
3
- factory();
4
- }((function () { 'use strict';
2
+ typeof define === 'function' && define.amd ? define(factory) :
3
+ factory();
4
+ })((function () { 'use strict';
5
+
6
+ const tagStorage = 'edgeTag';
7
+ const consentKey = 'consent';
8
+ const providersKey = 'providers';
9
+ const keyPrefix = `_worker`;
10
+
11
+ const initKey = `${keyPrefix}Store`;
12
+ const saveDataPerKey = (persistType, provider, value, key) => {
13
+ const storage = getData(persistType);
14
+ if (!storage[provider]) {
15
+ storage[provider] = {};
16
+ }
17
+ storage[provider][key] = value;
18
+ saveData(persistType, storage);
19
+ };
20
+ const getDataPerKey = (persistType, provider, key) => {
21
+ const storage = getData(persistType);
22
+ if (!storage[provider]) {
23
+ return undefined;
24
+ }
25
+ return storage[provider][key];
26
+ };
27
+ const saveData = (persistType, value, key = initKey) => {
28
+ if (persistType === 'session') {
29
+ saveSession(value, key);
30
+ return;
31
+ }
32
+ saveLocal(value, key);
33
+ };
34
+ const getData = (persistType, key = initKey) => {
35
+ if (persistType === 'session') {
36
+ return getSession(key);
37
+ }
38
+ return getLocal(key);
39
+ };
40
+ const saveLocal = (value, key) => {
41
+ localStorage.setItem(key, JSON.stringify(value));
42
+ };
43
+ const getLocal = (key) => {
44
+ return JSON.parse(localStorage.getItem(key)) || {};
45
+ };
46
+ const saveSession = (value, key) => {
47
+ sessionStorage.setItem(key, JSON.stringify(value));
48
+ };
49
+ const getSession = (key) => {
50
+ return JSON.parse(sessionStorage.getItem(key)) || {};
51
+ };
5
52
 
6
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
7
- // require the crypto API and do not support built-in fallback to lower quality random number
8
- // generators (like Math.random()).
9
- var getRandomValues;
10
- var rnds8 = new Uint8Array(16);
11
- function rng() {
12
- // lazy load so that environments that need to polyfill have a chance to do so
13
- if (!getRandomValues) {
14
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
15
- // find the complete implementation of crypto (msCrypto) on IE11.
16
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
53
+ const getUserAgent = () => {
54
+ const nav = navigator;
55
+ let ua = nav.userAgent;
56
+ ua += nav.brave ? `${ua} Brave` : '';
57
+ return ua;
58
+ };
59
+ const allowTag = (providers) => {
60
+ const consent = getDataPerKey('local', tagStorage, consentKey);
61
+ if (!consent) {
62
+ return false;
63
+ }
64
+ if (consent.all === true) {
65
+ return true;
66
+ }
67
+ if (!providers) {
68
+ return Object.values(consent).find((isAllowed) => isAllowed);
69
+ }
70
+ const allProviders = getDataPerKey('local', tagStorage, providersKey) || [];
71
+ for (const provider of allProviders) {
72
+ const tagProviderSetting = providers[provider];
73
+ if (tagProviderSetting ||
74
+ (providers.all === true && tagProviderSetting == undefined) ||
75
+ (providers.all === false && tagProviderSetting === true)) {
76
+ if (consent[provider]) {
77
+ return true;
78
+ }
79
+ }
80
+ }
81
+ return false;
82
+ };
17
83
 
18
- if (!getRandomValues) {
19
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
20
- }
84
+ const beacon = (url, payload) => {
85
+ let blob;
86
+ if (payload) {
87
+ blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
88
+ }
89
+ return navigator.sendBeacon(url, blob);
90
+ };
91
+ const ajax = async (method, url, payload) => {
92
+ return await fetch(url, {
93
+ method,
94
+ headers: {
95
+ 'Content-type': 'application/json; charset=utf-8',
96
+ Accept: 'application/json; charset=utf-8',
97
+ credentials: 'include',
98
+ },
99
+ body: JSON.stringify(payload),
100
+ })
101
+ .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
102
+ .then((data) => {
103
+ if (data.status < 200 || data.status >= 300) {
104
+ // Q: do we need to retry?
105
+ return Promise.reject(new Error(JSON.stringify(data.body)));
106
+ }
107
+ return Promise.resolve(data.body);
108
+ })
109
+ .catch((error) => {
110
+ // Q: do we need to retry?
111
+ return Promise.reject(new Error(error));
112
+ });
113
+ };
114
+ const getStandardPayload = (payload) => {
115
+ const data = {
116
+ pageUrl: window.location.href,
117
+ userAgent: getUserAgent(),
118
+ ...payload,
119
+ };
120
+ let storage = {};
121
+ const session = getData('session');
122
+ if (session) {
123
+ storage = {
124
+ ...storage,
125
+ ...session,
126
+ };
127
+ }
128
+ const local = getData('local');
129
+ if (local) {
130
+ storage = {
131
+ ...storage,
132
+ ...local,
133
+ };
134
+ }
135
+ data.storage = storage;
136
+ return data;
137
+ };
138
+ async function postRequest(url, data, options) {
139
+ if (!url) {
140
+ return Promise.reject(new Error('URL is empty'));
141
+ }
142
+ const payload = getStandardPayload(data);
143
+ if (options && options.method === 'beacon' && navigator.sendBeacon) {
144
+ return Promise.resolve(beacon(url, payload));
145
+ }
146
+ return await ajax('POST', url, payload);
147
+ }
148
+ async function getRequest(url, options) {
149
+ if (!url) {
150
+ return Promise.reject(new Error('URL is empty'));
151
+ }
152
+ if (options && options.method === 'beacon' && navigator.sendBeacon) {
153
+ return Promise.resolve(beacon(url));
154
+ }
155
+ return await ajax('GET', url);
21
156
  }
22
157
 
23
- return getRandomValues(rnds8);
24
- }
25
-
26
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
27
-
28
- function validate(uuid) {
29
- return typeof uuid === 'string' && REGEX.test(uuid);
30
- }
31
-
32
- /**
33
- * Convert array of 16 byte values to UUID string format of the form:
34
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
35
- */
158
+ let endpointUrl = '';
159
+ const generateUrl = (path) => {
160
+ const endpoint = getUrl();
161
+ if (!endpoint) {
162
+ console.log('URL is not valid');
163
+ return '';
164
+ }
165
+ return `${endpoint}${path}`;
166
+ };
167
+ const getUrl = () => {
168
+ return endpointUrl;
169
+ };
170
+ const setUrl = (url) => {
171
+ if (url == null) {
172
+ return;
173
+ }
174
+ endpointUrl = url;
175
+ };
176
+ const getTagURL = () => {
177
+ return generateUrl('/tag');
178
+ };
179
+ const getInitURL = () => {
180
+ return generateUrl('/init');
181
+ };
182
+ const getConsentURL = () => {
183
+ return generateUrl('/consent');
184
+ };
36
185
 
37
- var byteToHex = [];
186
+ const info = (data) => {
187
+ {
188
+ console.info(data);
189
+ }
190
+ };
38
191
 
39
- for (var i = 0; i < 256; ++i) {
40
- byteToHex.push((i + 0x100).toString(16).substr(1));
41
- }
192
+ const handleConsent = (consent) => {
193
+ const payload = {
194
+ consentString: consent,
195
+ };
196
+ saveDataPerKey('local', tagStorage, consent, consentKey);
197
+ postRequest(getConsentURL(), payload).catch(info);
198
+ };
42
199
 
43
- function stringify(arr) {
44
- var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
45
- // Note: Be careful editing this code! It's been tuned for performance
46
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
47
- var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
48
- // of the following:
49
- // - One or more input array values don't map to a hex octet (leading to
50
- // "undefined" in the uuid)
51
- // - Invalid input values for the RFC `version` or `variant` fields
200
+ const handleTag = (name, data, providers) => {
201
+ let payload = {
202
+ eventName: name,
203
+ };
204
+ if (data) {
205
+ payload.data = data;
206
+ }
207
+ if (providers) {
208
+ payload.providers = providers;
209
+ }
210
+ if (!allowTag(providers)) {
211
+ console.log('No consent');
212
+ return;
213
+ }
214
+ postRequest(getTagURL(), payload).catch(info);
215
+ };
52
216
 
53
- if (!validate(uuid)) {
54
- throw TypeError('Stringified UUID is invalid');
55
- }
217
+ const setPreferences = (preferences) => {
218
+ if (!preferences) {
219
+ return false;
220
+ }
221
+ if (!preferences.edgeURL) {
222
+ console.info('Please provide URL for EdgeTag');
223
+ return false;
224
+ }
225
+ setUrl(preferences.edgeURL);
226
+ return true;
227
+ };
56
228
 
57
- return uuid;
58
- }
229
+ const getCookieValue = (key) => {
230
+ let name = `${key}=`;
231
+ let decodedCookie = decodeURIComponent(document.cookie);
232
+ let ca = decodedCookie.split(';');
233
+ for (let i = 0; i < ca.length; i++) {
234
+ let c = ca[i];
235
+ while (c.charAt(0) == ' ') {
236
+ c = c.substring(1);
237
+ }
238
+ if (c.indexOf(name) == 0) {
239
+ return c.substring(name.length, c.length);
240
+ }
241
+ }
242
+ return '';
243
+ };
244
+ const handleCaptureQuery = (provider, key, persistType) => {
245
+ const params = new URLSearchParams(window.location.search);
246
+ if (!params || !params.get(key)) {
247
+ return;
248
+ }
249
+ saveDataPerKey(persistType, provider, params.get(key), key);
250
+ };
251
+ const handleCaptureStorage = (provider, location, key, persistType) => {
252
+ let data;
253
+ switch (location) {
254
+ case 'cookie': {
255
+ data = getCookieValue(key);
256
+ break;
257
+ }
258
+ case 'local': {
259
+ data = sessionStorage.getItem(key);
260
+ break;
261
+ }
262
+ case 'session': {
263
+ data = localStorage.getItem(key);
264
+ break;
265
+ }
266
+ }
267
+ if (!data) {
268
+ return;
269
+ }
270
+ saveDataPerKey(persistType, provider, data, key);
271
+ };
272
+ const handleCapture = (provider, params) => {
273
+ switch (params.type) {
274
+ case 'query': {
275
+ handleCaptureQuery(provider, params.key, params.persist);
276
+ break;
277
+ }
278
+ case 'storage': {
279
+ handleCaptureStorage(provider, params.location, params.key, params.persist);
280
+ break;
281
+ }
282
+ }
283
+ };
59
284
 
60
- function v4(options, buf, offset) {
61
- options = options || {};
62
- var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
285
+ const handleManifest = (manifest) => {
286
+ const providers = [];
287
+ manifest.forEach((provider) => {
288
+ providers.push(provider.package);
289
+ Object.entries(provider.rules).forEach(([name, recipe]) => {
290
+ switch (name) {
291
+ case 'capture': {
292
+ handleCapture(provider.package, recipe);
293
+ return;
294
+ }
295
+ }
296
+ });
297
+ });
298
+ saveDataPerKey('local', tagStorage, providers, providersKey);
299
+ };
63
300
 
64
- rnds[6] = rnds[6] & 0x0f | 0x40;
65
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
301
+ const handleInit = (preferences) => {
302
+ const success = setPreferences(preferences);
303
+ if (!success) {
304
+ return;
305
+ }
306
+ getRequest(getInitURL())
307
+ .then((result) => {
308
+ if (!result) {
309
+ console.log('init failed');
310
+ return;
311
+ }
312
+ handleManifest(result.result);
313
+ })
314
+ .catch(info);
315
+ };
66
316
 
67
- if (buf) {
68
- offset = offset || 0;
317
+ const init = (preferences) => {
318
+ handleInit(preferences);
319
+ };
320
+ const tag = (name, data, providers) => {
321
+ handleTag(name, data, providers);
322
+ };
323
+ const consent = (consent) => {
324
+ handleConsent(consent);
325
+ };
69
326
 
70
- for (var i = 0; i < 16; ++i) {
71
- buf[offset + i] = rnds[i];
327
+ class API {
328
+ init(preferences) {
329
+ init(preferences);
72
330
  }
73
331
 
74
- return buf;
75
- }
76
-
77
- return stringify(rnds);
78
- }
79
-
80
- const tagStorage = 'edgeTag';
81
- const consentKey = 'consent';
82
- const keyPrefix = `_worker`;
83
-
84
- const initKey = `${keyPrefix}Store`;
85
- const saveDataPerKey = (persistType, provider, value, key) => {
86
- const storage = getData(persistType);
87
- if (!storage[provider]) {
88
- storage[provider] = {};
89
- }
90
- storage[provider][key] = value;
91
- saveData(persistType, storage);
92
- };
93
- const getDataPerKey = (persistType, provider, key) => {
94
- const storage = getData(persistType);
95
- if (!storage[provider]) {
96
- return undefined;
97
- }
98
- return storage[provider][key];
99
- };
100
- const saveData = (persistType, value, key = initKey) => {
101
- if (persistType === 'session') {
102
- saveSession(value, key);
103
- return;
104
- }
105
- saveLocal(value, key);
106
- };
107
- const getData = (persistType, key = initKey) => {
108
- if (persistType === 'session') {
109
- return getSession(key);
110
- }
111
- return getLocal(key);
112
- };
113
- const saveLocal = (value, key) => {
114
- localStorage.setItem(key, JSON.stringify(value));
115
- };
116
- const getLocal = (key) => {
117
- return JSON.parse(localStorage.getItem(key)) || {};
118
- };
119
- const saveSession = (value, key) => {
120
- sessionStorage.setItem(key, JSON.stringify(value));
121
- };
122
- const getSession = (key) => {
123
- return JSON.parse(sessionStorage.getItem(key)) || {};
124
- };
125
-
126
- const getUserAgent = () => {
127
- const nav = navigator;
128
- let ua = nav.userAgent;
129
- ua += nav.brave ? `${ua} Brave` : '';
130
- return ua;
131
- };
132
- const allowTag = (providers = {}) => {
133
- const consent = getDataPerKey('local', tagStorage, consentKey) || {};
134
- const manifest = Object.keys(getData('local'));
135
- let allow = false;
136
- manifest.forEach((provider) => {
137
- const tagProviderSetting = providers[provider];
138
- if (allow || tagProviderSetting === false) {
139
- return;
140
- }
141
- if (providers.all === true || // we allow not defined provider
142
- Object.keys(providers).length === 0 || // providers were not specified
143
- (!providers.all && tagProviderSetting) // you need to specify provider and it's allowed
144
- ) {
145
- if (consent[provider] === true) {
146
- allow = true;
147
- }
148
- }
149
- });
150
- return allow;
151
- };
152
-
153
- const generateUserID = () => {
154
- let time = Date.now();
155
- if (typeof performance !== 'undefined' &&
156
- typeof performance.now === 'function') {
157
- time += performance.now();
158
- }
159
- time = parseInt(time.toString(), 10);
160
- return `${v4()}-${time}-${v4()}`;
161
- };
162
- const getUserIDKey = () => {
163
- return `${keyPrefix}User`;
164
- };
165
- const checkUser = () => {
166
- let user = getData('local', getUserIDKey());
167
- if (user && user.id) {
168
- return user.id;
169
- }
170
- const userID = generateUserID();
171
- saveData('local', { id: userID }, getUserIDKey());
172
- return userID;
173
- };
174
-
175
- const beacon = (url, payload) => {
176
- let blob;
177
- if (payload) {
178
- blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
179
- }
180
- return navigator.sendBeacon(url, blob);
181
- };
182
- const ajax = async (method, url, payload) => {
183
- return await fetch(url, {
184
- method,
185
- headers: {
186
- 'Content-type': 'application/json; charset=utf-8',
187
- Accept: 'application/json; charset=utf-8',
188
- },
189
- body: JSON.stringify(payload),
190
- })
191
- .then((response) => response.json().then((data) => ({ status: response.status, body: data })))
192
- .then((data) => {
193
- if (data.status < 200 || data.status >= 300) {
194
- // Q: do we need to retry?
195
- return Promise.reject(new Error(JSON.stringify(data.body)));
196
- }
197
- return Promise.resolve(data.body);
198
- })
199
- .catch((error) => {
200
- // Q: do we need to retry?
201
- return Promise.reject(new Error(error));
202
- });
203
- };
204
- const getStandardPayload = (payload) => {
205
- const data = {
206
- userID: checkUser(),
207
- pageUrl: window.location.href,
208
- userAgent: getUserAgent(),
209
- ...payload,
210
- };
211
- let storage = {};
212
- const session = getData('session');
213
- if (session) {
214
- storage = {
215
- ...storage,
216
- ...session,
217
- };
218
- }
219
- const local = getData('local');
220
- if (local) {
221
- storage = {
222
- ...storage,
223
- ...local,
224
- };
225
- }
226
- data.storage = storage;
227
- return data;
228
- };
229
- async function postRequest(url, data, options) {
230
- if (!url) {
231
- return Promise.reject(new Error('URL is empty'));
232
- }
233
- const payload = getStandardPayload(data);
234
- if (options && options.method === 'beacon' && navigator.sendBeacon) {
235
- return Promise.resolve(beacon(url, payload));
236
- }
237
- return await ajax('POST', url, payload);
238
- }
239
- async function getRequest(url, options) {
240
- if (!url) {
241
- return Promise.reject(new Error('URL is empty'));
242
- }
243
- if (options && options.method === 'beacon' && navigator.sendBeacon) {
244
- return Promise.resolve(beacon(url));
245
- }
246
- return await ajax('GET', url);
247
- }
248
-
249
- let endpointUrl = '';
250
- const generateUrl = (path) => {
251
- const endpoint = getUrl();
252
- if (!endpoint) {
253
- console.log('URL is not valid');
254
- return '';
255
- }
256
- return `${endpoint}${path}`;
257
- };
258
- const getUrl = () => {
259
- return endpointUrl;
260
- };
261
- const setUrl = (url) => {
262
- if (url == null) {
263
- return;
264
- }
265
- endpointUrl = url;
266
- };
267
- const getTagURL = () => {
268
- return generateUrl('/tag');
269
- };
270
- const getInitURL = () => {
271
- return generateUrl('/init');
272
- };
273
- const getConsentURL = () => {
274
- return generateUrl('/consent');
275
- };
276
-
277
- const info = (data) => {
278
- {
279
- console.info(data);
280
- }
281
- };
282
-
283
- const handleConsent = (consent) => {
284
- const payload = {
285
- consentString: consent,
286
- };
287
- saveDataPerKey('local', tagStorage, consent, consentKey);
288
- postRequest(getConsentURL(), payload).catch(info);
289
- };
290
-
291
- const handleTag = (name, data, providers) => {
292
- let payload = {
293
- eventName: name,
294
- };
295
- if (data) {
296
- payload.data = data;
297
- }
298
- if (providers) {
299
- payload.providers = providers;
300
- }
301
- if (!allowTag(providers)) {
302
- console.log('No consent');
303
- return;
304
- }
305
- postRequest(getTagURL(), payload).catch(info);
306
- };
307
-
308
- const setPreferences = (preferences) => {
309
- if (!preferences) {
310
- return false;
311
- }
312
- if (!preferences.edgeURL) {
313
- console.info('Please provide URL for EdgeTag');
314
- return false;
315
- }
316
- setUrl(preferences.edgeURL);
317
- const user = checkUser();
318
- if (!user) {
319
- console.info('User was not created.');
320
- return false;
321
- }
322
- return true;
323
- };
324
-
325
- const getCookieValue = (key) => {
326
- let name = `${key}=`;
327
- let decodedCookie = decodeURIComponent(document.cookie);
328
- let ca = decodedCookie.split(';');
329
- for (let i = 0; i < ca.length; i++) {
330
- let c = ca[i];
331
- while (c.charAt(0) == ' ') {
332
- c = c.substring(1);
333
- }
334
- if (c.indexOf(name) == 0) {
335
- return c.substring(name.length, c.length);
336
- }
337
- }
338
- return '';
339
- };
340
- const handleCaptureQuery = (provider, key, persistType) => {
341
- const params = new URLSearchParams(window.location.search);
342
- if (!params || !params.get(key)) {
343
- return;
344
- }
345
- saveDataPerKey(persistType, provider, params.get(key), key);
346
- };
347
- const handleCaptureStorage = (provider, location, key, persistType) => {
348
- let data;
349
- switch (location) {
350
- case 'cookie': {
351
- data = getCookieValue(key);
352
- break;
353
- }
354
- case 'local': {
355
- data = sessionStorage.getItem(key);
356
- break;
357
- }
358
- case 'session': {
359
- data = localStorage.getItem(key);
360
- break;
361
- }
362
- }
363
- if (!data) {
364
- return;
365
- }
366
- saveDataPerKey(persistType, provider, data, key);
367
- };
368
- const handleCapture = (provider, params) => {
369
- switch (params.type) {
370
- case 'query': {
371
- handleCaptureQuery(provider, params.key, params.persist);
372
- break;
373
- }
374
- case 'storage': {
375
- handleCaptureStorage(provider, params.location, params.key, params.persist);
376
- break;
377
- }
378
- }
379
- };
380
-
381
- const handleManifest = (manifest) => {
382
- manifest.forEach((provider) => {
383
- Object.entries(provider.rules).forEach(([name, recipe]) => {
384
- switch (name) {
385
- case 'capture': {
386
- handleCapture(provider.package, recipe);
387
- return;
388
- }
389
- }
390
- });
391
- });
392
- };
393
-
394
- const handleInit = (preferences) => {
395
- const success = setPreferences(preferences);
396
- if (!success) {
397
- return;
398
- }
399
- getRequest(getInitURL())
400
- .then((result) => {
401
- if (!result) {
402
- console.log('init failed');
403
- return;
404
- }
405
- handleManifest(result.result);
406
- })
407
- .catch(info);
408
- };
409
-
410
- const init = (preferences) => {
411
- handleInit(preferences);
412
- };
413
- const tag = (name, data, providers) => {
414
- handleTag(name, data, providers);
415
- };
416
- const consent = (consent) => {
417
- handleConsent(consent);
418
- };
419
-
420
- class API {
421
- init(preferences) {
422
- init(preferences);
423
- }
424
-
425
- tag(name, data, providers) {
426
- tag(name, data, providers);
427
- }
428
-
429
- consent(consentString) {
430
- consent(consentString);
431
- }
432
- }
433
-
434
- var api = new API();
332
+ tag(name, data, providers) {
333
+ tag(name, data, providers);
334
+ }
435
335
 
436
- (function () {
437
- const handleFunction = (arg) => {
438
- const sliced = [].slice.call(arg);
439
- if (!Array.isArray(sliced)) {
440
- return
336
+ consent(consentString) {
337
+ consent(consentString);
441
338
  }
339
+ }
442
340
 
443
- try {
341
+ var api = new API();
342
+
343
+ (function () {
344
+ const handleFunction = (arg) => {
345
+ const sliced = [].slice.call(arg);
346
+ if (!Array.isArray(sliced)) {
347
+ return
348
+ }
349
+
350
+ try {
351
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
352
+ // @ts-ignore
353
+ return library[sliced[0]](...sliced.slice(1))
354
+ } catch (e) {
355
+ console.error(e);
356
+ }
357
+ };
358
+
359
+ const library = api;
360
+ let stubs = [];
361
+ if (window.edgetag) {
444
362
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
445
363
  // @ts-ignore
446
- return library[sliced[0]](...sliced.slice(1))
447
- } catch (e) {
448
- console.error(e);
364
+ stubs = window.edgetag.stubs || [];
449
365
  }
450
- };
451
366
 
452
- const library = api;
453
- let stubs = [];
454
- if (window.edgetag) {
455
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
456
- // @ts-ignore
457
- stubs = window.edgetag.stubs || [];
458
- }
459
-
460
- // this needs to be regular function for arguments to work
461
- window.edgetag = function () {
462
- // eslint-disable-next-line prefer-rest-params
463
- return handleFunction(arguments)
464
- };
367
+ // this needs to be regular function for arguments to work
368
+ window.edgetag = function () {
369
+ // eslint-disable-next-line prefer-rest-params
370
+ return handleFunction(arguments)
371
+ };
465
372
 
466
- // restore calls that were triggered before lib was ready
467
- stubs.forEach(handleFunction);
468
- })();
373
+ // restore calls that were triggered before lib was ready
374
+ stubs.forEach(handleFunction);
375
+ })();
469
376
 
470
- })));
377
+ }));
package/index.min.js CHANGED
@@ -1 +1 @@
1
- !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e,t=new Uint8Array(16);function n(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(t)}var r=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function o(e){return"string"==typeof e&&r.test(e)}for(var s=[],a=0;a<256;++a)s.push((a+256).toString(16).substr(1));function i(e,t,r){var a=(e=e||{}).random||(e.rng||n)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=a[i];return t}return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(s[e[t+0]]+s[e[t+1]]+s[e[t+2]]+s[e[t+3]]+"-"+s[e[t+4]]+s[e[t+5]]+"-"+s[e[t+6]]+s[e[t+7]]+"-"+s[e[t+8]]+s[e[t+9]]+"-"+s[e[t+10]]+s[e[t+11]]+s[e[t+12]]+s[e[t+13]]+s[e[t+14]]+s[e[t+15]]).toLowerCase();if(!o(n))throw TypeError("Stringified UUID is invalid");return n}(a)}const c="edgeTag",l="consent",u="_workerStore",f=(e,t,n,r)=>{const o=d(e);o[t]||(o[t]={}),o[t][r]=n,g(e,o)},g=(e,t,n=u)=>{"session"!==e?p(t,n):m(t,n)},d=(e,t=u)=>"session"===e?h(t):y(t),p=(e,t)=>{localStorage.setItem(t,JSON.stringify(e))},y=e=>JSON.parse(localStorage.getItem(e))||{},m=(e,t)=>{sessionStorage.setItem(t,JSON.stringify(e))},h=e=>JSON.parse(sessionStorage.getItem(e))||{},w=()=>{const e=navigator;let t=e.userAgent;return t+=e.brave?`${t} Brave`:"",t},v=(e={})=>{const t=((e,t,n)=>{const r=d(e);if(r[t])return r[t][n]})("local",c,l)||{},n=Object.keys(d("local"));let r=!1;return n.forEach((n=>{const o=e[n];r||!1===o||(!0===e.all||0===Object.keys(e).length||!e.all&&o)&&!0===t[n]&&(r=!0)})),r},b=()=>{let e=d("local","_workerUser");if(e&&e.id)return e.id;const t=(()=>{let e=Date.now();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),e=parseInt(e.toString(),10),`${i()}-${e}-${i()}`})();return g("local",{id:t},"_workerUser"),t},S=(e,t)=>{let n;return t&&(n=new Blob([JSON.stringify(t)],{type:"application/json"})),navigator.sendBeacon(e,n)},U=async(e,t,n)=>await fetch(t,{method:e,headers:{"Content-type":"application/json; charset=utf-8",Accept:"application/json; charset=utf-8"},body:JSON.stringify(n)}).then((e=>e.json().then((t=>({status:e.status,body:t}))))).then((e=>e.status<200||e.status>=300?Promise.reject(new Error(JSON.stringify(e.body))):Promise.resolve(e.body))).catch((e=>Promise.reject(new Error(e))));async function k(e,t,n){if(!e)return Promise.reject(new Error("URL is empty"));const r=(e=>{const t={userID:b(),pageUrl:window.location.href,userAgent:w(),...e};let n={};const r=d("session");r&&(n={...n,...r});const o=d("local");return o&&(n={...n,...o}),t.storage=n,t})(t);return n&&"beacon"===n.method&&navigator.sendBeacon?Promise.resolve(S(e,r)):await U("POST",e,r)}let R="";const j=e=>{const t=E();return t?`${t}${e}`:(console.log("URL is not valid"),"")},E=()=>R,O=e=>{},I=e=>{const t={consentString:e};f("local",c,e,l),k(j("/consent"),t).catch(O)},P=(e,t,n)=>{let r={eventName:e};t&&(r.data=t),n&&(r.providers=n),v(n)?k(j("/tag"),r).catch(O):console.log("No consent")},N=e=>{if(!e)return!1;if(!e.edgeURL)return console.info("Please provide URL for EdgeTag"),!1;var t;null!=(t=e.edgeURL)&&(R=t);return!!b()||(console.info("User was not created."),!1)},L=(e,t,n,r)=>{let o;switch(t){case"cookie":o=(e=>{let t=`${e}=`,n=decodeURIComponent(document.cookie).split(";");for(let e=0;e<n.length;e++){let r=n[e];for(;" "==r.charAt(0);)r=r.substring(1);if(0==r.indexOf(t))return r.substring(t.length,r.length)}return""})(n);break;case"local":o=sessionStorage.getItem(n);break;case"session":o=localStorage.getItem(n)}o&&f(r,e,o,n)},$=(e,t)=>{switch(t.type){case"query":((e,t,n)=>{const r=new URLSearchParams(window.location.search);r&&r.get(t)&&f(n,e,r.get(t),t)})(e,t.key,t.persist);break;case"storage":L(e,t.location,t.key,t.persist)}},A=e=>{N(e)&&async function(e,t){return e?t&&"beacon"===t.method&&navigator.sendBeacon?Promise.resolve(S(e)):await U("GET",e):Promise.reject(new Error("URL is empty"))}(j("/init")).then((e=>{e?e.result.forEach((e=>{Object.entries(e.rules).forEach((([t,n])=>{switch(t){case"capture":return void $(e.package,n)}}))})):console.log("init failed")})).catch(O)};var C=new class{init(e){(e=>{A(e)})(e)}tag(e,t,n){((e,t,n)=>{P(e,t,n)})(e,t,n)}consent(e){(e=>{I(e)})(e)}};!function(){const e=e=>{const n=[].slice.call(e);if(Array.isArray(n))try{return t[n[0]](...n.slice(1))}catch(e){console.error(e)}},t=C;let n=[];window.edgetag&&(n=window.edgetag.stubs||[]),window.edgetag=function(){return e(arguments)},n.forEach(e)}()}));
1
+ !function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";const e="edgeTag",t="consent",n="providers",o="_workerStore",r=(e,t,n,o)=>{const r=c(e);r[t]||(r[t]={}),r[t][o]=n,a(e,r)},s=(e,t,n)=>{const o=c(e);if(o[t])return o[t][n]},a=(e,t,n=o)=>{"session"!==e?i(t,n):g(t,n)},c=(e,t=o)=>"session"===e?u(t):l(t),i=(e,t)=>{localStorage.setItem(t,JSON.stringify(e))},l=e=>JSON.parse(localStorage.getItem(e))||{},g=(e,t)=>{sessionStorage.setItem(t,JSON.stringify(e))},u=e=>JSON.parse(sessionStorage.getItem(e))||{},d=()=>{const e=navigator;let t=e.userAgent;return t+=e.brave?`${t} Brave`:"",t},f=(e,t)=>{let n;return t&&(n=new Blob([JSON.stringify(t)],{type:"application/json"})),navigator.sendBeacon(e,n)},h=async(e,t,n)=>await fetch(t,{method:e,headers:{"Content-type":"application/json; charset=utf-8",Accept:"application/json; charset=utf-8",credentials:"include"},body:JSON.stringify(n)}).then((e=>e.json().then((t=>({status:e.status,body:t}))))).then((e=>e.status<200||e.status>=300?Promise.reject(new Error(JSON.stringify(e.body))):Promise.resolve(e.body))).catch((e=>Promise.reject(new Error(e))));async function p(e,t,n){if(!e)return Promise.reject(new Error("URL is empty"));const o=(e=>{const t={pageUrl:window.location.href,userAgent:d(),...e};let n={};const o=c("session");o&&(n={...n,...o});const r=c("local");return r&&(n={...n,...r}),t.storage=n,t})(t);return n&&"beacon"===n.method&&navigator.sendBeacon?Promise.resolve(f(e,o)):await h("POST",e,o)}let w="";const y=e=>{const t=m();return t?`${t}${e}`:(console.log("URL is not valid"),"")},m=()=>w,v=e=>{},S=n=>{const o={consentString:n};r("local",e,n,t),p(y("/consent"),o).catch(v)},b=(o,r,a)=>{let c={eventName:o};r&&(c.data=r),a&&(c.providers=a),(o=>{const r=s("local",e,t);if(!r)return!1;if(!0===r.all)return!0;if(!o)return Object.values(r).find((e=>e));const a=s("local",e,n)||[];for(const e of a){const t=o[e];if((t||!0===o.all&&null==t||!1===o.all&&!0===t)&&r[e])return!0}return!1})(a)?p(y("/tag"),c).catch(v):console.log("No consent")},O=e=>{return!!e&&(e.edgeURL?(null!=(t=e.edgeURL)&&(w=t),!0):(console.info("Please provide URL for EdgeTag"),!1));var t},j=(e,t,n,o)=>{let s;switch(t){case"cookie":s=(e=>{let t=`${e}=`,n=decodeURIComponent(document.cookie).split(";");for(let e=0;e<n.length;e++){let o=n[e];for(;" "==o.charAt(0);)o=o.substring(1);if(0==o.indexOf(t))return o.substring(t.length,o.length)}return""})(n);break;case"local":s=sessionStorage.getItem(n);break;case"session":s=localStorage.getItem(n)}s&&r(o,e,s,n)},k=(e,t)=>{switch(t.type){case"query":((e,t,n)=>{const o=new URLSearchParams(window.location.search);o&&o.get(t)&&r(n,e,o.get(t),t)})(e,t.key,t.persist);break;case"storage":j(e,t.location,t.key,t.persist)}},P=t=>{O(t)&&async function(e,t){return e?t&&"beacon"===t.method&&navigator.sendBeacon?Promise.resolve(f(e)):await h("GET",e):Promise.reject(new Error("URL is empty"))}(y("/init")).then((t=>{t?(t=>{const o=[];t.forEach((e=>{o.push(e.package),Object.entries(e.rules).forEach((([t,n])=>{switch(t){case"capture":return void k(e.package,n)}}))})),r("local",e,o,n)})(t.result):console.log("init failed")})).catch(v)};var E=new class{init(e){(e=>{P(e)})(e)}tag(e,t,n){((e,t,n)=>{b(e,t,n)})(e,t,n)}consent(e){(e=>{S(e)})(e)}};!function(){const e=e=>{const n=[].slice.call(e);if(Array.isArray(n))try{return t[n[0]](...n.slice(1))}catch(e){console.error(e)}},t=E;let n=[];window.edgetag&&(n=window.edgetag.stubs||[]),window.edgetag=function(){return e(arguments)},n.forEach(e)}()}));
package/index.min.js.gz CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-browser",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Browser package for edge sdk",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",