@jitsu/js 1.0.0-canary-20230219230449 → 1.1.0-canary.14.20230602211353

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/dist/web/p.js.txt CHANGED
@@ -68,7 +68,50 @@
68
68
  return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
69
69
  }
70
70
 
71
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
71
+ function findScript(src) {
72
+ const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
73
+ return scripts.find(s => s.src === src);
74
+ }
75
+ function loadScript(src, attributes) {
76
+ const found = findScript(src);
77
+ if (found !== undefined) {
78
+ const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
79
+ if (status === "loaded") {
80
+ return Promise.resolve(found);
81
+ }
82
+ if (status === "loading") {
83
+ return new Promise((resolve, reject) => {
84
+ found.addEventListener("load", () => resolve(found));
85
+ found.addEventListener("error", err => reject(err));
86
+ });
87
+ }
88
+ }
89
+ return new Promise((resolve, reject) => {
90
+ var _a;
91
+ const script = window.document.createElement("script");
92
+ script.type = "text/javascript";
93
+ script.src = src;
94
+ script.async = true;
95
+ script.setAttribute("status", "loading");
96
+ for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
97
+ script.setAttribute(k, v);
98
+ }
99
+ script.onload = () => {
100
+ script.onerror = script.onload = null;
101
+ script.setAttribute("status", "loaded");
102
+ resolve(script);
103
+ };
104
+ script.onerror = () => {
105
+ script.onerror = script.onload = null;
106
+ script.setAttribute("status", "error");
107
+ reject(new Error(`Failed to load ${src}`));
108
+ };
109
+ const tag = window.document.getElementsByTagName("script")[0];
110
+ (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
111
+ });
112
+ }
113
+
114
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
72
115
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
73
116
  return new (P || (P = Promise))(function (resolve, reject) {
74
117
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -77,18 +120,10 @@
77
120
  step((generator = generator.apply(thisArg, _arguments || [])).next());
78
121
  });
79
122
  };
80
- function satisfyFilter(filter, subject) {
81
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
82
- }
83
- function applyFilters(event, creds) {
84
- const { hosts = ["*"], events = ["*"] } = creds;
85
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
86
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
87
- }
88
123
  const tagPlugin = {
89
124
  id: "tag",
90
125
  handle(config, payload) {
91
- return __awaiter$1(this, void 0, void 0, function* () {
126
+ return __awaiter$3(this, void 0, void 0, function* () {
92
127
  if (!applyFilters(payload, config)) {
93
128
  return;
94
129
  }
@@ -156,53 +191,221 @@
156
191
  function replaceMacro(code, event) {
157
192
  return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
158
193
  }
159
- const internalDestinationPlugins = {
160
- [tagPlugin.id]: tagPlugin,
161
- };
162
194
 
163
- function findScript(src) {
164
- const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
165
- return scripts.find(s => s.src === src);
195
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
196
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
197
+ return new (P || (P = Promise))(function (resolve, reject) {
198
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
199
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
200
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
201
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
202
+ });
203
+ };
204
+ const logrocketPlugin = {
205
+ id: "logrocket",
206
+ handle(config, payload) {
207
+ return __awaiter$2(this, void 0, void 0, function* () {
208
+ if (!applyFilters(payload, config)) {
209
+ return;
210
+ }
211
+ initLogrocketIfNeeded(config.appId);
212
+ const action = logRocket => {
213
+ if (payload.type === "identify" && payload.userId) {
214
+ logRocket.identify(payload.userId, payload.traits || {});
215
+ }
216
+ };
217
+ getLogRocketQueue().push(action);
218
+ if (getLogRocketState() === "loaded") {
219
+ flushLogRocketQueue(window["LogRocket"]);
220
+ }
221
+ });
222
+ },
223
+ };
224
+ function getLogRocketState() {
225
+ return window["__jitsuLrState"] || "fresh";
166
226
  }
167
- function loadScript(src, attributes) {
168
- const found = findScript(src);
169
- if (found !== undefined) {
170
- const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
171
- if (status === "loaded") {
172
- return Promise.resolve(found);
227
+ function setLogRocketState(s) {
228
+ window["__jitsuLrState"] = s;
229
+ }
230
+ function getLogRocketQueue() {
231
+ return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
232
+ }
233
+ function flushLogRocketQueue(lr) {
234
+ const queue = getLogRocketQueue();
235
+ while (queue.length > 0) {
236
+ const method = queue.shift();
237
+ try {
238
+ const res = method(lr);
239
+ if (res) {
240
+ res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
241
+ }
173
242
  }
174
- if (status === "loading") {
175
- return new Promise((resolve, reject) => {
176
- found.addEventListener("load", () => resolve(found));
177
- found.addEventListener("error", err => reject(err));
178
- });
243
+ catch (e) {
244
+ console.warn(`LogRocket method failed: ${e.message}`, e);
179
245
  }
180
246
  }
181
- return new Promise((resolve, reject) => {
182
- var _a;
183
- const script = window.document.createElement("script");
184
- script.type = "text/javascript";
185
- script.src = src;
186
- script.async = true;
187
- script.setAttribute("status", "loading");
188
- for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
189
- script.setAttribute(k, v);
247
+ }
248
+ function initLogrocketIfNeeded(appId) {
249
+ return __awaiter$2(this, void 0, void 0, function* () {
250
+ if (getLogRocketState() !== "fresh") {
251
+ return;
190
252
  }
191
- script.onload = () => {
192
- script.onerror = script.onload = null;
193
- script.setAttribute("status", "loaded");
194
- resolve(script);
195
- };
196
- script.onerror = () => {
197
- script.onerror = script.onload = null;
198
- script.setAttribute("status", "error");
199
- reject(new Error(`Failed to load ${src}`));
253
+ setLogRocketState("loading");
254
+ loadScript(`https://cdn.lr-ingest.io/LogRocket.min.js`, { crossOrigin: "anonymous" })
255
+ .then(() => {
256
+ if (window["LogRocket"]) {
257
+ try {
258
+ window["LogRocket"].init(appId);
259
+ }
260
+ catch (e) {
261
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
262
+ setLogRocketState("failed");
263
+ }
264
+ setLogRocketState("loaded");
265
+ flushLogRocketQueue(window["LogRocket"]);
266
+ }
267
+ })
268
+ .catch(e => {
269
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
270
+ setLogRocketState("failed");
271
+ });
272
+ });
273
+ }
274
+
275
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
276
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
277
+ return new (P || (P = Promise))(function (resolve, reject) {
278
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
279
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
280
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
281
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
282
+ });
283
+ };
284
+ const defaultScriptSrc = "https://www.googletagmanager.com/gtag/js";
285
+ const gtmPlugin = {
286
+ id: "gtm",
287
+ handle(config, payload) {
288
+ var _a, _b;
289
+ return __awaiter$1(this, void 0, void 0, function* () {
290
+ if (!applyFilters(payload, config)) {
291
+ return;
292
+ }
293
+ yield initGtmIfNeeded(config);
294
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
295
+ switch (payload.type) {
296
+ case "page":
297
+ const { properties: pageProperties, context } = payload;
298
+ const pageEvent = {
299
+ event: "page_view",
300
+ url: pageProperties.url,
301
+ title: pageProperties.title,
302
+ referer: (_b = (_a = context === null || context === void 0 ? void 0 : context.page) === null || _a === void 0 ? void 0 : _a.referrer) !== null && _b !== void 0 ? _b : "",
303
+ };
304
+ if (config.debug) {
305
+ console.log("gtag push", pageEvent);
306
+ }
307
+ dataLayer.push(pageEvent);
308
+ break;
309
+ case "track":
310
+ const { properties: trackProperties } = payload;
311
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
312
+ if (payload.userId) {
313
+ trackEvent.userId = payload.userId;
314
+ }
315
+ if (payload.anonymousId) {
316
+ trackEvent.anonymousId = payload.anonymousId;
317
+ }
318
+ if (config.debug) {
319
+ console.log("gtag push", trackEvent);
320
+ }
321
+ dataLayer.push(trackEvent);
322
+ break;
323
+ case "identify":
324
+ const { traits } = payload;
325
+ const identifyEvent = Object.assign({ event: "identify" }, traits);
326
+ if (payload.userId) {
327
+ identifyEvent.userId = payload.userId;
328
+ }
329
+ if (payload.anonymousId) {
330
+ identifyEvent.anonymousId = payload.anonymousId;
331
+ }
332
+ if (config.debug) {
333
+ console.log("gtag push", identifyEvent);
334
+ }
335
+ dataLayer.push(identifyEvent);
336
+ break;
337
+ }
338
+ });
339
+ },
340
+ };
341
+ function getGtmState() {
342
+ return window["__jitsuGtmState"] || "fresh";
343
+ }
344
+ function setGtmState(s) {
345
+ window["__jitsuGtmState"] = s;
346
+ }
347
+ function initGtmIfNeeded(config) {
348
+ return __awaiter$1(this, void 0, void 0, function* () {
349
+ if (getGtmState() !== "fresh") {
350
+ return;
351
+ }
352
+ setGtmState("loading");
353
+ const dlName = config.dataLayerName || "dataLayer";
354
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
355
+ const previewParams = config.preview
356
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
357
+ : "";
358
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
359
+ window[dlName] = window[dlName] || [];
360
+ const gtag = function () {
361
+ window[dlName].push(arguments);
200
362
  };
201
- const tag = window.document.getElementsByTagName("script")[0];
202
- (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
363
+ // @ts-ignore
364
+ gtag("js", new Date());
365
+ // @ts-ignore
366
+ gtag("config", config.containerId);
367
+ loadScript(scriptSrc)
368
+ .then(() => {
369
+ setGtmState("loaded");
370
+ })
371
+ .catch(e => {
372
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
373
+ setGtmState("failed");
374
+ });
203
375
  });
204
376
  }
205
377
 
378
+ function satisfyFilter(filter, subject) {
379
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
380
+ }
381
+ function satisfyDomainFilter(filter, subject) {
382
+ if (filter === "*") {
383
+ return true;
384
+ }
385
+ subject = subject || "";
386
+ if (filter.startsWith("*.")) {
387
+ return subject.endsWith(filter.substring(1));
388
+ }
389
+ else {
390
+ return filter === subject;
391
+ }
392
+ }
393
+ function applyFilters(event, creds) {
394
+ const { hosts = "*", events = "*" } = creds;
395
+ const eventsArray = events.split("\n");
396
+ return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyDomainFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
397
+ (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
398
+ !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
399
+ }
400
+ const internalDestinationPlugins = {
401
+ [tagPlugin.id]: tagPlugin,
402
+ [gtmPlugin.id]: gtmPlugin,
403
+ [logrocketPlugin.id]: logrocketPlugin,
404
+ };
405
+
406
+ var name = "@jitsu/js";
407
+ var version = "0.0.0";
408
+
206
409
  /* global analytics */
207
410
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
208
411
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -213,7 +416,7 @@
213
416
  step((generator = generator.apply(thisArg, _arguments || [])).next());
214
417
  });
215
418
  };
216
- const config = {
419
+ const defaultConfig = {
217
420
  /* Your segment writeKey */
218
421
  writeKey: null,
219
422
  /* Disable anonymous MTU */
@@ -221,6 +424,8 @@
221
424
  debug: false,
222
425
  fetch: null,
223
426
  echoEvents: false,
427
+ cookieDomain: undefined,
428
+ runtime: undefined,
224
429
  };
225
430
  const parseQuery = (qs) => {
226
431
  if (!qs) {
@@ -438,13 +643,13 @@
438
643
  const referrer = runtime.referrer();
439
644
  const context = {
440
645
  library: {
441
- name: "jitsu-js",
442
- version: "1.0.0",
646
+ name: name,
647
+ version: version,
443
648
  },
444
649
  userAgent: runtime.userAgent(),
445
650
  locale: runtime.language(),
446
651
  screen: runtime.screen(),
447
- traits: payload.type != "identify" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
652
+ traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
448
653
  page: {
449
654
  path: properties.path || (parsedUrl && parsedUrl.pathname),
450
655
  referrer: referrer,
@@ -453,11 +658,11 @@
453
658
  search: properties.search || (parsedUrl && parsedUrl.search),
454
659
  title: properties.title || runtime.pageTitle(),
455
660
  url: properties.url || url,
456
- enconding: properties.enconding || runtime.documentEncoding(),
661
+ encoding: properties.encoding || runtime.documentEncoding(),
457
662
  },
458
663
  campaign: parseUtms(query),
459
664
  };
460
- const withContext = Object.assign(Object.assign({}, payload), { timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: config.writeKey, context: deepMerge(context, customContext) });
665
+ const withContext = Object.assign(Object.assign({}, payload), { timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: validateWriteKey(config.writeKey), context: deepMerge(context, customContext) });
461
666
  delete withContext.meta;
462
667
  delete withContext.options;
463
668
  return withContext;
@@ -466,11 +671,12 @@
466
671
  return __awaiter(this, void 0, void 0, function* () {
467
672
  const promises = [];
468
673
  for (const destination of destinations) {
674
+ const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
469
675
  if (destination.deviceOptions.type === "internal-plugin") {
470
676
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
471
677
  if (plugin) {
472
678
  try {
473
- promises.push(plugin.handle(destination.credentials, event));
679
+ promises.push(plugin.handle(credentials, event));
474
680
  }
475
681
  catch (e) {
476
682
  console.warn(`[JITSU] Error processing event with internal plugin '${destination.deviceOptions.name}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
@@ -489,7 +695,7 @@
489
695
  else {
490
696
  let pluginInstance;
491
697
  try {
492
- pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(destination.credentials);
698
+ pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
493
699
  }
494
700
  catch (e) {
495
701
  console.warn(`[JITSU] Error creating plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
@@ -517,6 +723,18 @@
517
723
  }
518
724
  });
519
725
  }
726
+ function looksLikeCuid(id) {
727
+ return id.length === 25 && id.charAt(0) === "c";
728
+ }
729
+ function validateWriteKey(writeKey) {
730
+ if (writeKey) {
731
+ const [, secret] = writeKey.split(":", 2);
732
+ if (!secret && !looksLikeCuid(writeKey)) {
733
+ throw new Error(`Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`);
734
+ }
735
+ }
736
+ return writeKey;
737
+ }
520
738
  function send(method, payload, jitsuConfig, instance, store) {
521
739
  if (jitsuConfig.echoEvents) {
522
740
  console.log(`[JITSU] sending '${method}' event:`, payload);
@@ -527,12 +745,12 @@
527
745
  if (!fetch) {
528
746
  throw new Error("Please specify fetch function in jitsu plugin initialization, fetch isn't available in global scope");
529
747
  }
530
- const authHeader = {};
531
748
  const debugHeader = jitsuConfig.debug ? { "X-Enable-Debug": "true" } : {};
532
749
  // if (jitsuConfig.debug) {
533
750
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
534
751
  // }
535
752
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
753
+ const authHeader = jitsuConfig.writeKey ? { "X-Write-Key": validateWriteKey(jitsuConfig.writeKey) } : {};
536
754
  return fetch(url, {
537
755
  method: "POST",
538
756
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
@@ -559,7 +777,7 @@
559
777
  }
560
778
  if (response.destinations) {
561
779
  if (jitsuConfig.debug) {
562
- console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
780
+ console.log(`[JITSU] Processing device destinations: `, JSON.stringify(response.destinations, null, 2));
563
781
  }
564
782
  return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
565
783
  }
@@ -588,9 +806,10 @@
588
806
  persistentStorage.removeItem(key);
589
807
  },
590
808
  });
809
+ const instanceConfig = Object.assign(Object.assign({}, defaultConfig), pluginConfig);
591
810
  return {
592
811
  name: "jitsu",
593
- config: Object.assign(Object.assign({}, config), pluginConfig),
812
+ config: instanceConfig,
594
813
  initialize: args => {
595
814
  const { config } = args;
596
815
  if (config.debug) {
@@ -618,6 +837,16 @@
618
837
  //clear storage cache
619
838
  Object.keys(storageCache).forEach(key => delete storageCache[key]);
620
839
  },
840
+ methods: {
841
+ //analytics doesn't support group as a base method, so we need to add it manually
842
+ group(groupId, traits, options, callback) {
843
+ const analyticsInstance = this.instance;
844
+ const user = analyticsInstance.user();
845
+ const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
846
+ const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId);
847
+ return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), instanceConfig, analyticsInstance, cachingStorageWrapper(analyticsInstance.storage));
848
+ },
849
+ },
621
850
  };
622
851
  };
623
852
  function getSeed() {
@@ -681,7 +910,14 @@
681
910
  return originalPage(...args);
682
911
  }
683
912
  };
684
- return analytics;
913
+ return Object.assign(Object.assign({}, analytics), { group(groupId, traits, options, callback) {
914
+ for (const plugin of Object.values(analytics.plugins)) {
915
+ if (plugin["group"]) {
916
+ plugin["group"](groupId, traits, options, callback);
917
+ }
918
+ }
919
+ return Promise.resolve({});
920
+ } });
685
921
  }
686
922
  function jitsuAnalytics(opts) {
687
923
  const inBrowser = isInBrowser();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jitsu/js",
3
- "version": "1.0.0-canary-20230219230449",
3
+ "version": "1.1.0-canary.14.20230602211353",
4
4
  "description": "",
5
5
  "author": "Jitsu Dev Team <dev@jitsu.com>",
6
6
  "main": "dist/jitsu.cjs.js",
@@ -12,7 +12,7 @@
12
12
  "license": "MIT",
13
13
  "private": false,
14
14
  "devDependencies": {
15
- "@playwright/test": "^1.30.0",
15
+ "@playwright/test": "1.31.2",
16
16
  "@rollup/plugin-commonjs": "^23.0.2",
17
17
  "@rollup/plugin-json": "^5.0.1",
18
18
  "@rollup/plugin-multi-entry": "^6.0.0",
@@ -32,11 +32,12 @@
32
32
  "node-forge": "^1.3.1",
33
33
  "raw-loader": "^4.0.2",
34
34
  "rollup": "^3.2.5",
35
- "ts-jest": "^29.0.3"
35
+ "ts-jest": "29.0.5",
36
+ "typescript": "^4.9.5",
37
+ "@jitsu/protocols": "1.1.0-canary.14.20230602211353"
36
38
  },
37
39
  "dependencies": {
38
- "analytics": "^0.8.1",
39
- "@jitsu/protocols": "0.0.0"
40
+ "analytics": "^0.8.1"
40
41
  },
41
42
  "scripts": {
42
43
  "clean": "rm -rf ./dist",