@jitsu/js 1.1.0-canary.344.20230430234929 → 1.1.0-canary.391.20230523080206

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/jitsu.es.js CHANGED
@@ -65,7 +65,50 @@ function analyticsLib() {
65
65
  return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
66
66
  }
67
67
 
68
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
68
+ function findScript(src) {
69
+ const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
70
+ return scripts.find(s => s.src === src);
71
+ }
72
+ function loadScript(src, attributes) {
73
+ const found = findScript(src);
74
+ if (found !== undefined) {
75
+ const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
76
+ if (status === "loaded") {
77
+ return Promise.resolve(found);
78
+ }
79
+ if (status === "loading") {
80
+ return new Promise((resolve, reject) => {
81
+ found.addEventListener("load", () => resolve(found));
82
+ found.addEventListener("error", err => reject(err));
83
+ });
84
+ }
85
+ }
86
+ return new Promise((resolve, reject) => {
87
+ var _a;
88
+ const script = window.document.createElement("script");
89
+ script.type = "text/javascript";
90
+ script.src = src;
91
+ script.async = true;
92
+ script.setAttribute("status", "loading");
93
+ for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
94
+ script.setAttribute(k, v);
95
+ }
96
+ script.onload = () => {
97
+ script.onerror = script.onload = null;
98
+ script.setAttribute("status", "loaded");
99
+ resolve(script);
100
+ };
101
+ script.onerror = () => {
102
+ script.onerror = script.onload = null;
103
+ script.setAttribute("status", "error");
104
+ reject(new Error(`Failed to load ${src}`));
105
+ };
106
+ const tag = window.document.getElementsByTagName("script")[0];
107
+ (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
108
+ });
109
+ }
110
+
111
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
69
112
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
70
113
  return new (P || (P = Promise))(function (resolve, reject) {
71
114
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -74,18 +117,10 @@ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _argu
74
117
  step((generator = generator.apply(thisArg, _arguments || [])).next());
75
118
  });
76
119
  };
77
- function satisfyFilter(filter, subject) {
78
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
79
- }
80
- function applyFilters(event, creds) {
81
- const { hosts = ["*"], events = ["*"] } = creds;
82
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
83
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
84
- }
85
120
  const tagPlugin = {
86
121
  id: "tag",
87
122
  handle(config, payload) {
88
- return __awaiter$1(this, void 0, void 0, function* () {
123
+ return __awaiter$3(this, void 0, void 0, function* () {
89
124
  if (!applyFilters(payload, config)) {
90
125
  return;
91
126
  }
@@ -153,53 +188,206 @@ function execJs(code, event) {
153
188
  function replaceMacro(code, event) {
154
189
  return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
155
190
  }
156
- const internalDestinationPlugins = {
157
- [tagPlugin.id]: tagPlugin,
158
- };
159
191
 
160
- function findScript(src) {
161
- const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
162
- return scripts.find(s => s.src === src);
192
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
193
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
194
+ return new (P || (P = Promise))(function (resolve, reject) {
195
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
196
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
197
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
198
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
199
+ });
200
+ };
201
+ const logrocketPlugin = {
202
+ id: "logrocket",
203
+ handle(config, payload) {
204
+ return __awaiter$2(this, void 0, void 0, function* () {
205
+ if (!applyFilters(payload, config)) {
206
+ return;
207
+ }
208
+ initLogrocketIfNeeded(config.appId);
209
+ const action = logRocket => {
210
+ if (payload.type === "identify" && payload.userId) {
211
+ logRocket.identify(payload.userId, payload.traits || {});
212
+ }
213
+ };
214
+ getLogRocketQueue().push(action);
215
+ if (getLogRocketState() === "loaded") {
216
+ flushLogRocketQueue(window["LogRocket"]);
217
+ }
218
+ });
219
+ },
220
+ };
221
+ function getLogRocketState() {
222
+ return window["__jitsuLrState"] || "fresh";
163
223
  }
164
- function loadScript(src, attributes) {
165
- const found = findScript(src);
166
- if (found !== undefined) {
167
- const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
168
- if (status === "loaded") {
169
- return Promise.resolve(found);
224
+ function setLogRocketState(s) {
225
+ window["__jitsuLrState"] = s;
226
+ }
227
+ function getLogRocketQueue() {
228
+ return window["__jitsuLrQueue"] || (window["__jitsuLrQueue"] = []);
229
+ }
230
+ function flushLogRocketQueue(lr) {
231
+ const queue = getLogRocketQueue();
232
+ while (queue.length > 0) {
233
+ const method = queue.shift();
234
+ try {
235
+ const res = method(lr);
236
+ if (res) {
237
+ res.catch(e => console.warn(`Async LogRocket method failed: ${e.message}`, e));
238
+ }
170
239
  }
171
- if (status === "loading") {
172
- return new Promise((resolve, reject) => {
173
- found.addEventListener("load", () => resolve(found));
174
- found.addEventListener("error", err => reject(err));
175
- });
240
+ catch (e) {
241
+ console.warn(`LogRocket method failed: ${e.message}`, e);
176
242
  }
177
243
  }
178
- return new Promise((resolve, reject) => {
179
- var _a;
180
- const script = window.document.createElement("script");
181
- script.type = "text/javascript";
182
- script.src = src;
183
- script.async = true;
184
- script.setAttribute("status", "loading");
185
- for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
186
- script.setAttribute(k, v);
244
+ }
245
+ function initLogrocketIfNeeded(appId) {
246
+ return __awaiter$2(this, void 0, void 0, function* () {
247
+ if (getLogRocketState() !== "fresh") {
248
+ return;
187
249
  }
188
- script.onload = () => {
189
- script.onerror = script.onload = null;
190
- script.setAttribute("status", "loaded");
191
- resolve(script);
192
- };
193
- script.onerror = () => {
194
- script.onerror = script.onload = null;
195
- script.setAttribute("status", "error");
196
- reject(new Error(`Failed to load ${src}`));
250
+ setLogRocketState("loading");
251
+ loadScript(`https://cdn.lr-ingest.io/LogRocket.min.js`, { crossOrigin: "anonymous" })
252
+ .then(() => {
253
+ if (window["LogRocket"]) {
254
+ try {
255
+ window["LogRocket"].init(appId);
256
+ }
257
+ catch (e) {
258
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
259
+ setLogRocketState("failed");
260
+ }
261
+ setLogRocketState("loaded");
262
+ flushLogRocketQueue(window["LogRocket"]);
263
+ }
264
+ })
265
+ .catch(e => {
266
+ console.warn(`LogRocket (id=${appId}) init failed: ${e.message}`, e);
267
+ setLogRocketState("failed");
268
+ });
269
+ });
270
+ }
271
+
272
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
273
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
274
+ return new (P || (P = Promise))(function (resolve, reject) {
275
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
276
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
277
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
278
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
279
+ });
280
+ };
281
+ const defaultScriptSrc = "https://www.googletagmanager.com/gtag/js";
282
+ const gtmPlugin = {
283
+ id: "gtm",
284
+ handle(config, payload) {
285
+ var _a, _b;
286
+ return __awaiter$1(this, void 0, void 0, function* () {
287
+ if (!applyFilters(payload, config)) {
288
+ return;
289
+ }
290
+ yield initGtmIfNeeded(config);
291
+ const dataLayer = window[config.dataLayerName || "dataLayer"];
292
+ switch (payload.type) {
293
+ case "page":
294
+ const { properties: pageProperties, context } = payload;
295
+ const pageEvent = {
296
+ event: "page_view",
297
+ url: pageProperties.url,
298
+ title: pageProperties.title,
299
+ 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 : "",
300
+ };
301
+ if (config.debug) {
302
+ console.log("gtag push", pageEvent);
303
+ }
304
+ dataLayer.push(pageEvent);
305
+ break;
306
+ case "track":
307
+ const { properties: trackProperties } = payload;
308
+ const trackEvent = Object.assign({ event: payload.event }, trackProperties);
309
+ if (payload.userId) {
310
+ trackEvent.userId = payload.userId;
311
+ }
312
+ if (payload.anonymousId) {
313
+ trackEvent.anonymousId = payload.anonymousId;
314
+ }
315
+ if (config.debug) {
316
+ console.log("gtag push", trackEvent);
317
+ }
318
+ dataLayer.push(trackEvent);
319
+ break;
320
+ case "identify":
321
+ const { traits } = payload;
322
+ const identifyEvent = Object.assign({ event: "identify" }, traits);
323
+ if (payload.userId) {
324
+ identifyEvent.userId = payload.userId;
325
+ }
326
+ if (payload.anonymousId) {
327
+ identifyEvent.anonymousId = payload.anonymousId;
328
+ }
329
+ if (config.debug) {
330
+ console.log("gtag push", identifyEvent);
331
+ }
332
+ dataLayer.push(identifyEvent);
333
+ break;
334
+ }
335
+ });
336
+ },
337
+ };
338
+ function getGtmState() {
339
+ return window["__jitsuGtmState"] || "fresh";
340
+ }
341
+ function setGtmState(s) {
342
+ window["__jitsuGtmState"] = s;
343
+ }
344
+ function initGtmIfNeeded(config) {
345
+ return __awaiter$1(this, void 0, void 0, function* () {
346
+ if (getGtmState() !== "fresh") {
347
+ return;
348
+ }
349
+ setGtmState("loading");
350
+ const dlName = config.dataLayerName || "dataLayer";
351
+ const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
352
+ const previewParams = config.preview
353
+ ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
354
+ : "";
355
+ const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
356
+ window[dlName] = window[dlName] || [];
357
+ const gtag = function () {
358
+ window[dlName].push(arguments);
197
359
  };
198
- const tag = window.document.getElementsByTagName("script")[0];
199
- (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
360
+ // @ts-ignore
361
+ gtag("js", new Date());
362
+ // @ts-ignore
363
+ gtag("config", config.containerId);
364
+ loadScript(scriptSrc)
365
+ .then(() => {
366
+ setGtmState("loaded");
367
+ })
368
+ .catch(e => {
369
+ console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
370
+ setGtmState("failed");
371
+ });
200
372
  });
201
373
  }
202
374
 
375
+ function satisfyFilter(filter, subject) {
376
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
377
+ }
378
+ function applyFilters(event, creds) {
379
+ const { hosts = "*", events = "*" } = creds;
380
+ const eventsArray = events.split("\n");
381
+ return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
382
+ (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
383
+ !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
384
+ }
385
+ const internalDestinationPlugins = {
386
+ [tagPlugin.id]: tagPlugin,
387
+ [gtmPlugin.id]: gtmPlugin,
388
+ [logrocketPlugin.id]: logrocketPlugin,
389
+ };
390
+
203
391
  /* global analytics */
204
392
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
205
393
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -218,6 +406,8 @@ const config = {
218
406
  debug: false,
219
407
  fetch: null,
220
408
  echoEvents: false,
409
+ cookieDomain: undefined,
410
+ runtime: undefined,
221
411
  };
222
412
  const parseQuery = (qs) => {
223
413
  if (!qs) {
@@ -441,7 +631,7 @@ function adjustPayload(payload, config, storage) {
441
631
  userAgent: runtime.userAgent(),
442
632
  locale: runtime.language(),
443
633
  screen: runtime.screen(),
444
- traits: payload.type != "identify" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
634
+ traits: payload.type != "identify" && payload.type != "group" ? Object.assign({}, (restoreTraits(storage) || {})) : undefined,
445
635
  page: {
446
636
  path: properties.path || (parsedUrl && parsedUrl.pathname),
447
637
  referrer: referrer,
@@ -450,7 +640,7 @@ function adjustPayload(payload, config, storage) {
450
640
  search: properties.search || (parsedUrl && parsedUrl.search),
451
641
  title: properties.title || runtime.pageTitle(),
452
642
  url: properties.url || url,
453
- enconding: properties.enconding || runtime.documentEncoding(),
643
+ encoding: properties.encoding || runtime.documentEncoding(),
454
644
  },
455
645
  campaign: parseUtms(query),
456
646
  };
@@ -463,12 +653,12 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
463
653
  return __awaiter(this, void 0, void 0, function* () {
464
654
  const promises = [];
465
655
  for (const destination of destinations) {
656
+ const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
466
657
  if (destination.deviceOptions.type === "internal-plugin") {
467
658
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
468
659
  if (plugin) {
469
660
  try {
470
661
  //to support old versions, where credentials were stored in root
471
- const credentials = destination.credentials || destination;
472
662
  promises.push(plugin.handle(credentials, event));
473
663
  }
474
664
  catch (e) {
@@ -488,7 +678,7 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
488
678
  else {
489
679
  let pluginInstance;
490
680
  try {
491
- pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(destination.credentials);
681
+ pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
492
682
  }
493
683
  catch (e) {
494
684
  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);
@@ -558,7 +748,7 @@ function send(method, payload, jitsuConfig, instance, store) {
558
748
  }
559
749
  if (response.destinations) {
560
750
  if (jitsuConfig.debug) {
561
- console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
751
+ console.log(`[JITSU] Processing device destinations: `, JSON.stringify(response.destinations, null, 2));
562
752
  }
563
753
  return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
564
754
  }
@@ -587,9 +777,10 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
587
777
  persistentStorage.removeItem(key);
588
778
  },
589
779
  });
780
+ const instanceConfig = Object.assign(Object.assign({}, config), pluginConfig);
590
781
  return {
591
782
  name: "jitsu",
592
- config: Object.assign(Object.assign({}, config), pluginConfig),
783
+ config: instanceConfig,
593
784
  initialize: args => {
594
785
  const { config } = args;
595
786
  if (config.debug) {
@@ -617,6 +808,16 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
617
808
  //clear storage cache
618
809
  Object.keys(storageCache).forEach(key => delete storageCache[key]);
619
810
  },
811
+ methods: {
812
+ //analytics doesn't support group as a base method, so we need to add it manually
813
+ group(groupId, traits, options, callback) {
814
+ const analyticsInstance = this.instance;
815
+ const user = analyticsInstance.user();
816
+ const userId = (options === null || options === void 0 ? void 0 : options.userId) || (user === null || user === void 0 ? void 0 : user.userId);
817
+ const anonymousId = (options === null || options === void 0 ? void 0 : options.anonymousId) || (user === null || user === void 0 ? void 0 : user.anonymousId);
818
+ return send("group", Object.assign(Object.assign({ type: "group", groupId, traits }, (anonymousId ? { anonymousId } : {})), (userId ? { userId } : {})), instanceConfig, analyticsInstance, cachingStorageWrapper(analyticsInstance.storage));
819
+ },
820
+ },
620
821
  };
621
822
  };
622
823
  function getSeed() {
@@ -669,6 +870,7 @@ const emptyAnalytics = {
669
870
  page: () => Promise.resolve(),
670
871
  user: () => ({}),
671
872
  identify: () => Promise.resolve({}),
873
+ group: () => Promise.resolve({}),
672
874
  reset: () => Promise.resolve({}),
673
875
  };
674
876
  function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
@@ -687,7 +889,14 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
687
889
  return originalPage(...args);
688
890
  }
689
891
  };
690
- return analytics;
892
+ return Object.assign(Object.assign({}, analytics), { group(groupId, traits, options, callback) {
893
+ for (const plugin of Object.values(analytics.plugins)) {
894
+ if (plugin["group"]) {
895
+ plugin["group"](groupId, traits, options, callback);
896
+ }
897
+ }
898
+ return Promise.resolve({});
899
+ } });
691
900
  }
692
901
  function jitsuAnalytics(opts) {
693
902
  const inBrowser = isInBrowser();