@jitsu/js 1.1.0-canary.388.20230519133920 → 1.1.0-canary.404.20230526224724

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
@@ -108,7 +108,7 @@ function loadScript(src, attributes) {
108
108
  });
109
109
  }
110
110
 
111
- var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
111
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
112
112
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
113
113
  return new (P || (P = Promise))(function (resolve, reject) {
114
114
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -117,10 +117,18 @@ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _argu
117
117
  step((generator = generator.apply(thisArg, _arguments || [])).next());
118
118
  });
119
119
  };
120
+ function satisfyFilter(filter, subject) {
121
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
122
+ }
123
+ function applyFilters(event, creds) {
124
+ const { hosts = ["*"], events = ["*"] } = creds;
125
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
126
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
127
+ }
120
128
  const tagPlugin = {
121
129
  id: "tag",
122
130
  handle(config, payload) {
123
- return __awaiter$3(this, void 0, void 0, function* () {
131
+ return __awaiter$1(this, void 0, void 0, function* () {
124
132
  if (!applyFilters(payload, config)) {
125
133
  return;
126
134
  }
@@ -128,96 +136,6 @@ const tagPlugin = {
128
136
  });
129
137
  },
130
138
  };
131
- function insertTags(code, event, opts = {}) {
132
- let tag;
133
- try {
134
- tag = JSON.parse(code);
135
- }
136
- catch (e) {
137
- tag = { code, lang: "javascript" };
138
- }
139
- const debug = opts.debug || false;
140
- if (isInBrowser()) {
141
- if (tag.lang === "javascript") {
142
- execJs(tag.code, event);
143
- }
144
- else {
145
- const codeHolder = document.createElement("span");
146
- codeHolder.innerHTML = replaceMacro(tag.code, event);
147
- document.body.insertAdjacentElement("beforeend", codeHolder);
148
- const scripts = codeHolder.querySelectorAll("script");
149
- scripts.forEach(script => {
150
- const scriptClone = document.createElement("script");
151
- scriptClone.type = scriptClone.type || "text/javascript";
152
- if (script.hasAttribute("src")) {
153
- scriptClone.src = script.src;
154
- }
155
- scriptClone.text = script.text;
156
- if (debug) {
157
- console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
158
- }
159
- document.head.appendChild(scriptClone);
160
- document.head.removeChild(scriptClone);
161
- });
162
- }
163
- }
164
- else {
165
- if (debug) {
166
- console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
167
- }
168
- }
169
- }
170
- function execJs(code, event) {
171
- const varName = `jitsu_event_${randomId()}`;
172
- window[varName] = event;
173
- const iif = `(function(){
174
- const event = ${varName};
175
- ${code}
176
- })()`;
177
- try {
178
- eval(iif);
179
- }
180
- catch (e) {
181
- console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
182
- }
183
- finally {
184
- delete window[varName];
185
- }
186
- return iif;
187
- }
188
- function replaceMacro(code, event) {
189
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
190
- }
191
-
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
139
  function getLogRocketState() {
222
140
  return window["__jitsuLrState"] || "fresh";
223
141
  }
@@ -243,7 +161,7 @@ function flushLogRocketQueue(lr) {
243
161
  }
244
162
  }
245
163
  function initLogrocketIfNeeded(appId) {
246
- return __awaiter$2(this, void 0, void 0, function* () {
164
+ return __awaiter$1(this, void 0, void 0, function* () {
247
165
  if (getLogRocketState() !== "fresh") {
248
166
  return;
249
167
  }
@@ -268,113 +186,94 @@ function initLogrocketIfNeeded(appId) {
268
186
  });
269
187
  });
270
188
  }
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",
189
+ const logrocketPlugin = {
190
+ id: "logrocket",
284
191
  handle(config, payload) {
285
192
  return __awaiter$1(this, void 0, void 0, function* () {
286
193
  if (!applyFilters(payload, config)) {
287
194
  return;
288
195
  }
289
- yield initGtmIfNeeded(config);
290
- const dataLayer = window[config.dataLayerName || "dataLayer"];
291
- switch (payload.type) {
292
- case "page":
293
- const { properties: pageProperties } = payload;
294
- const pageEvent = Object.assign({ event: "page_view" }, pageProperties);
295
- if (config.debug) {
296
- console.log("gtag push", pageEvent);
297
- }
298
- dataLayer.push(pageEvent);
299
- break;
300
- case "track":
301
- const { properties: trackProperties } = payload;
302
- const trackEvent = Object.assign({ event: payload.event }, trackProperties);
303
- if (config.debug) {
304
- console.log("gtag push", trackEvent);
305
- }
306
- dataLayer.push(trackEvent);
307
- break;
308
- case "identify":
309
- const { anonymousId, userId, traits } = payload;
310
- const user = traits;
311
- if (userId) {
312
- user.userId = userId;
313
- }
314
- if (anonymousId) {
315
- user.anonymousId = anonymousId;
316
- }
317
- const identifyEvent = { event: "identify", user: user };
318
- if (config.debug) {
319
- console.log("gtag push", identifyEvent);
320
- }
321
- dataLayer.push(identifyEvent);
322
- break;
196
+ initLogrocketIfNeeded(config.appId);
197
+ const action = logRocket => {
198
+ if (payload.type === "identify" && payload.userId) {
199
+ logRocket.identify(payload.userId, payload.traits || {});
200
+ }
201
+ };
202
+ getLogRocketQueue().push(action);
203
+ if (getLogRocketState() === "loaded") {
204
+ flushLogRocketQueue(window["LogRocket"]);
323
205
  }
324
206
  });
325
207
  },
326
208
  };
327
- function getGtmState() {
328
- return window["__jitsuGtmState"] || "fresh";
329
- }
330
- function setGtmState(s) {
331
- window["__jitsuGtmState"] = s;
332
- }
333
- function initGtmIfNeeded(config) {
334
- return __awaiter$1(this, void 0, void 0, function* () {
335
- if (getGtmState() !== "fresh") {
336
- return;
209
+ function insertTags(code, event, opts = {}) {
210
+ let tag;
211
+ try {
212
+ tag = JSON.parse(code);
213
+ }
214
+ catch (e) {
215
+ tag = { code, lang: "javascript" };
216
+ }
217
+ const debug = opts.debug || false;
218
+ if (isInBrowser()) {
219
+ if (tag.lang === "javascript") {
220
+ execJs(tag.code, event);
337
221
  }
338
- setGtmState("loading");
339
- const dlName = config.dataLayerName || "dataLayer";
340
- const dlParam = dlName !== "dataLayer" ? "&l=" + dlName : "";
341
- const previewParams = config.preview
342
- ? `&gtm_preview=${config.preview}&gtm_auth=${config.auth}&gtm_cookies_win=x`
343
- : "";
344
- const scriptSrc = `${config.customScriptSrc || defaultScriptSrc}?id=${config.containerId}${dlParam}${previewParams}`;
345
- window[dlName] = window[dlName] || [];
346
- const gtag = function () {
347
- window[dlName].push(arguments);
348
- };
349
- // @ts-ignore
350
- gtag("js", new Date());
351
- // @ts-ignore
352
- gtag("config", config.containerId);
353
- loadScript(scriptSrc)
354
- .then(() => {
355
- setGtmState("loaded");
356
- })
357
- .catch(e => {
358
- console.warn(`GTM (containerId=${config.containerId}) init failed: ${e.message}`, e);
359
- setGtmState("failed");
360
- });
361
- });
222
+ else {
223
+ const codeHolder = document.createElement("span");
224
+ codeHolder.innerHTML = replaceMacro(tag.code, event);
225
+ document.body.insertAdjacentElement("beforeend", codeHolder);
226
+ const scripts = codeHolder.querySelectorAll("script");
227
+ scripts.forEach(script => {
228
+ const scriptClone = document.createElement("script");
229
+ scriptClone.type = scriptClone.type || "text/javascript";
230
+ if (script.hasAttribute("src")) {
231
+ scriptClone.src = script.src;
232
+ }
233
+ scriptClone.text = script.text;
234
+ if (debug) {
235
+ console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
236
+ }
237
+ document.head.appendChild(scriptClone);
238
+ document.head.removeChild(scriptClone);
239
+ });
240
+ }
241
+ }
242
+ else {
243
+ if (debug) {
244
+ console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
245
+ }
246
+ }
362
247
  }
363
-
364
- function satisfyFilter(filter, subject) {
365
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
248
+ function execJs(code, event) {
249
+ const varName = `jitsu_event_${randomId()}`;
250
+ window[varName] = event;
251
+ const iif = `(function(){
252
+ const event = ${varName};
253
+ ${code}
254
+ })()`;
255
+ try {
256
+ eval(iif);
257
+ }
258
+ catch (e) {
259
+ console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
260
+ }
261
+ finally {
262
+ delete window[varName];
263
+ }
264
+ return iif;
366
265
  }
367
- function applyFilters(event, creds) {
368
- const { hosts = ["*"], events = ["*"] } = creds;
369
- return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
370
- !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
266
+ function replaceMacro(code, event) {
267
+ return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
371
268
  }
372
269
  const internalDestinationPlugins = {
373
270
  [tagPlugin.id]: tagPlugin,
374
- [gtmPlugin.id]: gtmPlugin,
375
271
  [logrocketPlugin.id]: logrocketPlugin,
376
272
  };
377
273
 
274
+ var name = "@jitsu/js";
275
+ var version = "0.0.0";
276
+
378
277
  /* global analytics */
379
278
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
380
279
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -612,8 +511,8 @@ function adjustPayload(payload, config, storage) {
612
511
  const referrer = runtime.referrer();
613
512
  const context = {
614
513
  library: {
615
- name: "jitsu-js",
616
- version: "1.0.0",
514
+ name: name,
515
+ version: version,
617
516
  },
618
517
  userAgent: runtime.userAgent(),
619
518
  locale: runtime.language(),
@@ -631,7 +530,7 @@ function adjustPayload(payload, config, storage) {
631
530
  },
632
531
  campaign: parseUtms(query),
633
532
  };
634
- 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) });
533
+ 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) });
635
534
  delete withContext.meta;
636
535
  delete withContext.options;
637
536
  return withContext;
@@ -640,12 +539,11 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
640
539
  return __awaiter(this, void 0, void 0, function* () {
641
540
  const promises = [];
642
541
  for (const destination of destinations) {
542
+ const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
643
543
  if (destination.deviceOptions.type === "internal-plugin") {
644
544
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
645
545
  if (plugin) {
646
546
  try {
647
- //to support old versions, where credentials were stored in root
648
- const credentials = destination.credentials || destination;
649
547
  promises.push(plugin.handle(credentials, event));
650
548
  }
651
549
  catch (e) {
@@ -665,7 +563,7 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
665
563
  else {
666
564
  let pluginInstance;
667
565
  try {
668
- pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(destination.credentials);
566
+ pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(credentials);
669
567
  }
670
568
  catch (e) {
671
569
  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);
@@ -693,6 +591,15 @@ function processDestinations(destinations, method, event, debug, analyticsInstan
693
591
  }
694
592
  });
695
593
  }
594
+ function validateWriteKey(writeKey) {
595
+ if (writeKey) {
596
+ const [, secret] = writeKey.split(":", 2);
597
+ if (!secret) {
598
+ 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`);
599
+ }
600
+ }
601
+ return writeKey;
602
+ }
696
603
  function send(method, payload, jitsuConfig, instance, store) {
697
604
  if (jitsuConfig.echoEvents) {
698
605
  console.log(`[JITSU] sending '${method}' event:`, payload);
@@ -708,7 +615,7 @@ function send(method, payload, jitsuConfig, instance, store) {
708
615
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
709
616
  // }
710
617
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
711
- const authHeader = adjustedPayload.writeKey ? { "X-Write-Key": adjustedPayload.writeKey } : {};
618
+ const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
712
619
  return fetch(url, {
713
620
  method: "POST",
714
621
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
@@ -0,0 +1,2 @@
1
+ import { name as jitsuLibraryName, version as jitsuVersion } from "../package.json";
2
+ export { jitsuVersion, jitsuLibraryName };