@blotoutio/edgetag-sdk-js 0.2.0 → 0.3.0

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.umd.js ADDED
@@ -0,0 +1,487 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BlotoutEdgeTagSDKJS = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+
22
+ function __awaiter(thisArg, _arguments, P, generator) {
23
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
+ return new (P || (P = Promise))(function (resolve, reject) {
25
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
29
+ });
30
+ }
31
+
32
+ const tagStorage = 'edgeTag';
33
+ const consentKey = 'consent';
34
+ const providersKey = 'providers';
35
+ const keyPrefix = `_worker`;
36
+
37
+ const initKey = `${keyPrefix}Store`;
38
+ const saveDataPerKey = (persistType, provider, value, key) => {
39
+ const storage = getData(persistType);
40
+
41
+ if (!storage['data']) {
42
+ storage['data'] = {};
43
+ }
44
+
45
+ if (!storage['data'][provider]) {
46
+ storage['data'][provider] = {};
47
+ }
48
+
49
+ storage['data'][provider][key] = value;
50
+ saveData(persistType, storage);
51
+ };
52
+ const savePerKey = (persistType, provider, value, key) => {
53
+ const storage = getData(persistType);
54
+
55
+ if (!storage[provider]) {
56
+ storage[provider] = {};
57
+ }
58
+
59
+ storage[provider][key] = value;
60
+ saveData(persistType, storage);
61
+ };
62
+ const getDataPerKey = (persistType, provider, key) => {
63
+ const storage = getData(persistType);
64
+
65
+ if (!storage[provider]) {
66
+ return undefined;
67
+ }
68
+
69
+ return storage[provider][key];
70
+ };
71
+ const saveData = (persistType, value, key = initKey) => {
72
+ if (persistType === 'session') {
73
+ saveSession(value, key);
74
+ return;
75
+ }
76
+
77
+ saveLocal(value, key);
78
+ };
79
+ const getData = (persistType, key = initKey) => {
80
+ if (persistType === 'session') {
81
+ return getSession(key);
82
+ }
83
+
84
+ return getLocal(key);
85
+ };
86
+
87
+ const saveLocal = (value, key) => {
88
+ localStorage.setItem(key, JSON.stringify(value));
89
+ };
90
+
91
+ const getLocal = key => {
92
+ const data = localStorage.getItem(key);
93
+
94
+ if (!data) {
95
+ return {};
96
+ }
97
+
98
+ return JSON.parse(data) || {};
99
+ };
100
+
101
+ const saveSession = (value, key) => {
102
+ sessionStorage.setItem(key, JSON.stringify(value));
103
+ };
104
+
105
+ const getSession = key => {
106
+ const data = sessionStorage.getItem(key);
107
+
108
+ if (!data) {
109
+ return {};
110
+ }
111
+
112
+ return JSON.parse(data) || {};
113
+ };
114
+
115
+ let endpointUrl = '';
116
+
117
+ const generateUrl = path => {
118
+ const endpoint = getUrl();
119
+
120
+ if (!endpoint) {
121
+ console.log('URL is not valid');
122
+ return '';
123
+ }
124
+
125
+ return `${endpoint}${path}`;
126
+ };
127
+
128
+ const getUrl = () => {
129
+ return endpointUrl;
130
+ };
131
+ const setUrl = url => {
132
+ if (url == null) {
133
+ return;
134
+ }
135
+
136
+ endpointUrl = url;
137
+ };
138
+ const getTagURL = () => {
139
+ return generateUrl('/tag');
140
+ };
141
+ const getInitURL = () => {
142
+ return generateUrl('/init');
143
+ };
144
+ const getConsentURL = () => {
145
+ return generateUrl('/consent');
146
+ };
147
+ const getUserURL = () => {
148
+ return generateUrl('/user');
149
+ };
150
+
151
+ let consentDisabled = false;
152
+ const setPreferences = preferences => {
153
+ if (!preferences) {
154
+ return false;
155
+ }
156
+
157
+ if (!preferences.edgeURL) {
158
+ console.error('Please provide URL for EdgeTag');
159
+ return false;
160
+ }
161
+
162
+ consentDisabled = !!preferences.disableConsentCheck;
163
+ setUrl(preferences.edgeURL);
164
+ return true;
165
+ };
166
+ const isConsentDisabled = () => consentDisabled;
167
+
168
+ const getUserAgent = () => {
169
+ const nav = navigator;
170
+ let ua = nav.userAgent;
171
+ ua += nav.brave ? `${ua} Brave` : '';
172
+ return ua;
173
+ };
174
+ const allowTag = providers => {
175
+ const consent = getDataPerKey('local', tagStorage, consentKey);
176
+
177
+ if (isConsentDisabled()) {
178
+ return true;
179
+ }
180
+
181
+ if (!consent) {
182
+ return false;
183
+ }
184
+
185
+ if (consent['all']) {
186
+ return true;
187
+ }
188
+
189
+ if (!providers) {
190
+ return Object.values(consent).find(isAllowed => isAllowed) || false;
191
+ }
192
+
193
+ const allProviders = getDataPerKey('local', tagStorage, providersKey) || [];
194
+
195
+ for (const provider of allProviders) {
196
+ const tagProviderSetting = providers[provider];
197
+
198
+ if (tagProviderSetting || providers['all'] === true && tagProviderSetting === undefined || providers['all'] === false && tagProviderSetting === true) {
199
+ if (consent[provider]) {
200
+ return true;
201
+ }
202
+ }
203
+ }
204
+
205
+ return false;
206
+ };
207
+
208
+ const beacon = (url, payload) => {
209
+ let blob;
210
+
211
+ if (payload) {
212
+ blob = new Blob([JSON.stringify(payload)], {
213
+ type: 'application/json'
214
+ });
215
+ }
216
+
217
+ return navigator.sendBeacon(url, blob);
218
+ };
219
+
220
+ const ajax = (method, url, payload) => __awaiter(void 0, void 0, void 0, function* () {
221
+ return yield fetch(url, {
222
+ method,
223
+ headers: {
224
+ 'Content-type': 'application/json; charset=utf-8',
225
+ Accept: 'application/json; charset=utf-8'
226
+ },
227
+ body: JSON.stringify(payload),
228
+ credentials: 'include'
229
+ }).then(response => response.json().then(data => ({
230
+ status: response.status,
231
+ body: data
232
+ }))).then(data => {
233
+ if (data.status < 200 || data.status >= 300) {
234
+ // Q: do we need to retry?
235
+ return Promise.reject(new Error(JSON.stringify(data.body)));
236
+ }
237
+
238
+ return Promise.resolve(data.body);
239
+ }).catch(error => {
240
+ // Q: do we need to retry?
241
+ return Promise.reject(new Error(error));
242
+ });
243
+ });
244
+
245
+ const getStandardPayload = payload => {
246
+ const data = Object.assign({
247
+ pageUrl: window.location.href,
248
+ userAgent: getUserAgent()
249
+ }, payload || {});
250
+ let storage = {};
251
+ const session = getData('session');
252
+
253
+ if (session) {
254
+ storage = Object.assign(Object.assign({}, storage), session);
255
+ }
256
+
257
+ const local = getData('local');
258
+
259
+ if (local) {
260
+ storage = Object.assign(Object.assign({}, storage), local);
261
+ }
262
+
263
+ data.storage = storage;
264
+ return data;
265
+ };
266
+
267
+ function postRequest(url, data, options) {
268
+ return __awaiter(this, void 0, void 0, function* () {
269
+ if (!url) {
270
+ return Promise.reject(new Error('URL is empty'));
271
+ }
272
+
273
+ const payload = getStandardPayload(data);
274
+
275
+ if (options && options.method === 'beacon' && navigator.sendBeacon) {
276
+ return Promise.resolve(beacon(url, payload));
277
+ }
278
+
279
+ return yield ajax('POST', url, payload);
280
+ });
281
+ }
282
+ function getRequest(url, options) {
283
+ return __awaiter(this, void 0, void 0, function* () {
284
+ if (!url) {
285
+ return Promise.reject(new Error('URL is empty'));
286
+ }
287
+
288
+ if (options && options.method === 'beacon' && navigator.sendBeacon) {
289
+ return {
290
+ result: Promise.resolve(beacon(url))
291
+ };
292
+ }
293
+
294
+ return yield ajax('GET', url);
295
+ });
296
+ }
297
+
298
+ const info = data => {
299
+ };
300
+
301
+ const saveConsent = consent => {
302
+ savePerKey('local', tagStorage, consent, consentKey);
303
+ };
304
+ const handleConsent = consent => {
305
+ const payload = {
306
+ consentString: consent
307
+ };
308
+ saveConsent(consent);
309
+ postRequest(getConsentURL(), payload).catch(info);
310
+ };
311
+
312
+ const handleTag = (name, data, providers) => {
313
+ const payload = {
314
+ eventName: name
315
+ };
316
+
317
+ if (data) {
318
+ payload.data = data;
319
+ }
320
+
321
+ if (providers) {
322
+ payload.providers = providers;
323
+ }
324
+
325
+ if (!allowTag(providers)) {
326
+ console.log('No consent');
327
+ return;
328
+ }
329
+
330
+ postRequest(getTagURL(), payload).catch(info);
331
+ };
332
+
333
+ const getCookieValue = key => {
334
+ const name = `${key}=`;
335
+ const decodedCookie = decodeURIComponent(document.cookie);
336
+ const ca = decodedCookie.split(';');
337
+
338
+ for (let i = 0; i < ca.length; i++) {
339
+ let c = ca[i];
340
+
341
+ while (c.charAt(0) === ' ') {
342
+ c = c.substring(1);
343
+ }
344
+
345
+ if (c.indexOf(name) === 0) {
346
+ return c.substring(name.length, c.length);
347
+ }
348
+ }
349
+
350
+ return '';
351
+ };
352
+
353
+ const handleCaptureQuery = (provider, key, persistType) => {
354
+ const params = new URLSearchParams(window.location.search);
355
+
356
+ if (!params || !params.get(key)) {
357
+ return;
358
+ }
359
+
360
+ saveDataPerKey(persistType, provider, params.get(key), key);
361
+ };
362
+
363
+ const handleCaptureStorage = (provider, key, persistType, location) => {
364
+ let data;
365
+
366
+ switch (location) {
367
+ case 'cookie':
368
+ {
369
+ data = getCookieValue(key);
370
+ break;
371
+ }
372
+
373
+ case 'local':
374
+ {
375
+ data = sessionStorage.getItem(key);
376
+ break;
377
+ }
378
+
379
+ case 'session':
380
+ {
381
+ data = localStorage.getItem(key);
382
+ break;
383
+ }
384
+ }
385
+
386
+ if (!data) {
387
+ return;
388
+ }
389
+
390
+ saveDataPerKey(persistType, provider, data, key);
391
+ };
392
+
393
+ const handleCapture = (provider, params) => {
394
+ params.forEach(param => {
395
+ switch (param.type) {
396
+ case 'query':
397
+ {
398
+ handleCaptureQuery(provider, param.key, param.persist);
399
+ break;
400
+ }
401
+
402
+ case 'storage':
403
+ {
404
+ handleCaptureStorage(provider, param.key, param.persist, param.location);
405
+ break;
406
+ }
407
+ }
408
+ });
409
+ };
410
+
411
+ const handleManifest = manifest => {
412
+ const providers = [];
413
+ manifest.forEach(provider => {
414
+ providers.push(provider.package);
415
+ Object.entries(provider.rules).forEach(([name, recipe]) => {
416
+ switch (name) {
417
+ case 'capture':
418
+ {
419
+ handleCapture(provider.package, recipe);
420
+ return;
421
+ }
422
+ }
423
+ });
424
+ });
425
+ savePerKey('local', tagStorage, providers, providersKey);
426
+ };
427
+
428
+ const handleInit = preferences => {
429
+ const success = setPreferences(preferences);
430
+
431
+ if (!success) {
432
+ return;
433
+ }
434
+
435
+ let url = `${getInitURL()}`;
436
+
437
+ if (preferences.disableConsentCheck) {
438
+ url = `${url}?consentDisabled=true`;
439
+ saveConsent({
440
+ all: true
441
+ });
442
+ }
443
+
444
+ getRequest(url).then(result => {
445
+ if (!result) {
446
+ console.log('init failed');
447
+ return;
448
+ }
449
+
450
+ handleManifest(result.result);
451
+ }).catch(info);
452
+ };
453
+
454
+ const handleUser = (key, value) => {
455
+ if (!key || !value) {
456
+ console.error('Key or Value is missing in user api.');
457
+ return;
458
+ }
459
+
460
+ const payload = {
461
+ key,
462
+ value
463
+ };
464
+ postRequest(getUserURL(), payload).catch(info);
465
+ };
466
+
467
+ const init = preferences => {
468
+ handleInit(preferences);
469
+ };
470
+ const tag = (name, data, providers) => {
471
+ handleTag(name, data, providers);
472
+ };
473
+ const consent = consent => {
474
+ handleConsent(consent);
475
+ };
476
+ const user = (key, value) => {
477
+ handleUser(key, value);
478
+ };
479
+
480
+ exports.consent = consent;
481
+ exports.init = init;
482
+ exports.tag = tag;
483
+ exports.user = user;
484
+
485
+ Object.defineProperty(exports, '__esModule', { value: true });
486
+
487
+ }));
@@ -0,0 +1,10 @@
1
+ declare const _default: {
2
+ displayName: string;
3
+ preset: string;
4
+ transform: {
5
+ '^.+\\.[tj]sx?$': string;
6
+ };
7
+ moduleFileExtensions: string[];
8
+ coverageDirectory: string;
9
+ };
10
+ export default _default;
@@ -0,0 +1,2 @@
1
+ import { ManifestRule } from '../typings/internal';
2
+ export declare const handleCapture: (provider: string, params: ManifestRule[]) => void;
@@ -0,0 +1,2 @@
1
+ import { Manifest } from '../typings/internal';
2
+ export declare const handleManifest: (manifest: Manifest[]) => void;
@@ -0,0 +1,6 @@
1
+ export declare const getUrl: () => string;
2
+ export declare const setUrl: (url?: string | undefined) => void;
3
+ export declare const getTagURL: () => string;
4
+ export declare const getInitURL: () => string;
5
+ export declare const getConsentURL: () => string;
6
+ export declare const getUserURL: () => string;
@@ -0,0 +1,4 @@
1
+ import { EventOptions } from '../typings';
2
+ import { PostData } from '../typings/internal';
3
+ export declare function postRequest(url: string, data?: PostData, options?: EventOptions): Promise<unknown>;
4
+ export declare function getRequest<Payload, Response>(url: string, options?: EventOptions): Promise<Response>;
package/package.json CHANGED
@@ -1,35 +1,18 @@
1
1
  {
2
2
  "name": "@blotoutio/edgetag-sdk-js",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "JS SDK for EdgeTag",
5
5
  "author": "Blotout",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/blotoutio/edgetag-sdk",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
8
11
  "repository": {
9
12
  "type": "git",
10
13
  "url": "git+https://github.com/blotoutio/edgetag-sdk.git"
11
14
  },
12
- "files": [
13
- "cjs",
14
- "esm",
15
- "index.js",
16
- "package.json",
17
- "README.md",
18
- "index.d.ts"
19
- ],
20
- "types": "index.d.ts",
21
- "main": "index.js",
22
- "module": "esm/index.js",
23
- "scripts": {
24
- "prepublish": "npm run build",
25
- "build": "rollup --config",
26
- "lint": "prettier --check .",
27
- "start": "rollup --config --w"
28
- },
29
- "dependencies": {
30
- "uuid": "^8.3.0"
31
- },
32
- "publishConfig": {
33
- "access": "public"
34
- }
15
+ "main": "./index.umd.js",
16
+ "module": "./index.esm.js",
17
+ "typings": "./index.d.ts"
35
18
  }
@@ -0,0 +1,28 @@
1
+ type UserKeys =
2
+ | 'email'
3
+ | 'phone'
4
+ | 'firstName'
5
+ | 'lastName'
6
+ | 'gender'
7
+ | 'dateOfBirth'
8
+ | 'country'
9
+ | 'state'
10
+ | 'city'
11
+ | 'zip'
12
+
13
+ type Data = Record<string, unknown>
14
+
15
+ interface InitPreferences {
16
+ edgeURL: string
17
+ disableConsentCheck?: boolean
18
+ }
19
+
20
+ interface EventOptions {
21
+ method?: 'beacon'
22
+ }
23
+
24
+ export declare const init: (preferences: InitPreferences) => void
25
+
26
+ export declare const tag: (name: string, data?: Data) => void
27
+
28
+ export declare const consent: (consent: Data) => void
@@ -0,0 +1,44 @@
1
+ import { Data, UserKeys } from "./index";
2
+
3
+ type PersistType = 'local' | 'session'
4
+
5
+ interface Navigator {
6
+ userAgent: string
7
+ brave: unknown
8
+ }
9
+
10
+ interface TagRequest {
11
+ eventName: string
12
+ data?: Data
13
+ providers?: Data
14
+ }
15
+
16
+ interface ConsentRequest {
17
+ consentString: Data
18
+ }
19
+
20
+ interface UserRequest {
21
+ key: UserKeys
22
+ value: string
23
+ }
24
+
25
+ type PostData = TagRequest | ConsentRequest | UserRequest
26
+
27
+ interface PostPayload {
28
+ pageUrl: string
29
+ userAgent: string
30
+ data?: Data
31
+ storage?: Data
32
+ }
33
+
34
+ export type ManifestRule = {
35
+ type: string
36
+ key: string
37
+ persist: PersistType
38
+ location?: string
39
+ }
40
+
41
+ export type Manifest = {
42
+ package: string
43
+ rules: Record<string, ManifestRule[]>
44
+ }