@jitsu/js 1.1.0-canary.391.20230523080206 → 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/web/p.js.txt CHANGED
@@ -111,7 +111,7 @@
111
111
  });
112
112
  }
113
113
 
114
- var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
114
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
115
115
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
116
116
  return new (P || (P = Promise))(function (resolve, reject) {
117
117
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -120,10 +120,18 @@
120
120
  step((generator = generator.apply(thisArg, _arguments || [])).next());
121
121
  });
122
122
  };
123
+ function satisfyFilter(filter, subject) {
124
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
125
+ }
126
+ function applyFilters(event, creds) {
127
+ const { hosts = ["*"], events = ["*"] } = creds;
128
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
129
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
130
+ }
123
131
  const tagPlugin = {
124
132
  id: "tag",
125
133
  handle(config, payload) {
126
- return __awaiter$3(this, void 0, void 0, function* () {
134
+ return __awaiter$1(this, void 0, void 0, function* () {
127
135
  if (!applyFilters(payload, config)) {
128
136
  return;
129
137
  }
@@ -131,96 +139,6 @@
131
139
  });
132
140
  },
133
141
  };
134
- function insertTags(code, event, opts = {}) {
135
- let tag;
136
- try {
137
- tag = JSON.parse(code);
138
- }
139
- catch (e) {
140
- tag = { code, lang: "javascript" };
141
- }
142
- const debug = opts.debug || false;
143
- if (isInBrowser()) {
144
- if (tag.lang === "javascript") {
145
- execJs(tag.code, event);
146
- }
147
- else {
148
- const codeHolder = document.createElement("span");
149
- codeHolder.innerHTML = replaceMacro(tag.code, event);
150
- document.body.insertAdjacentElement("beforeend", codeHolder);
151
- const scripts = codeHolder.querySelectorAll("script");
152
- scripts.forEach(script => {
153
- const scriptClone = document.createElement("script");
154
- scriptClone.type = scriptClone.type || "text/javascript";
155
- if (script.hasAttribute("src")) {
156
- scriptClone.src = script.src;
157
- }
158
- scriptClone.text = script.text;
159
- if (debug) {
160
- console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
161
- }
162
- document.head.appendChild(scriptClone);
163
- document.head.removeChild(scriptClone);
164
- });
165
- }
166
- }
167
- else {
168
- if (debug) {
169
- console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
170
- }
171
- }
172
- }
173
- function execJs(code, event) {
174
- const varName = `jitsu_event_${randomId()}`;
175
- window[varName] = event;
176
- const iif = `(function(){
177
- const event = ${varName};
178
- ${code}
179
- })()`;
180
- try {
181
- eval(iif);
182
- }
183
- catch (e) {
184
- console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
185
- }
186
- finally {
187
- delete window[varName];
188
- }
189
- return iif;
190
- }
191
- function replaceMacro(code, event) {
192
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
193
- }
194
-
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
142
  function getLogRocketState() {
225
143
  return window["__jitsuLrState"] || "fresh";
226
144
  }
@@ -246,7 +164,7 @@
246
164
  }
247
165
  }
248
166
  function initLogrocketIfNeeded(appId) {
249
- return __awaiter$2(this, void 0, void 0, function* () {
167
+ return __awaiter$1(this, void 0, void 0, function* () {
250
168
  if (getLogRocketState() !== "fresh") {
251
169
  return;
252
170
  }
@@ -271,126 +189,94 @@
271
189
  });
272
190
  });
273
191
  }
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",
192
+ const logrocketPlugin = {
193
+ id: "logrocket",
287
194
  handle(config, payload) {
288
- var _a, _b;
289
195
  return __awaiter$1(this, void 0, void 0, function* () {
290
196
  if (!applyFilters(payload, config)) {
291
197
  return;
292
198
  }
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;
199
+ initLogrocketIfNeeded(config.appId);
200
+ const action = logRocket => {
201
+ if (payload.type === "identify" && payload.userId) {
202
+ logRocket.identify(payload.userId, payload.traits || {});
203
+ }
204
+ };
205
+ getLogRocketQueue().push(action);
206
+ if (getLogRocketState() === "loaded") {
207
+ flushLogRocketQueue(window["LogRocket"]);
337
208
  }
338
209
  });
339
210
  },
340
211
  };
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;
212
+ function insertTags(code, event, opts = {}) {
213
+ let tag;
214
+ try {
215
+ tag = JSON.parse(code);
216
+ }
217
+ catch (e) {
218
+ tag = { code, lang: "javascript" };
219
+ }
220
+ const debug = opts.debug || false;
221
+ if (isInBrowser()) {
222
+ if (tag.lang === "javascript") {
223
+ execJs(tag.code, event);
351
224
  }
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);
362
- };
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
- });
375
- });
225
+ else {
226
+ const codeHolder = document.createElement("span");
227
+ codeHolder.innerHTML = replaceMacro(tag.code, event);
228
+ document.body.insertAdjacentElement("beforeend", codeHolder);
229
+ const scripts = codeHolder.querySelectorAll("script");
230
+ scripts.forEach(script => {
231
+ const scriptClone = document.createElement("script");
232
+ scriptClone.type = scriptClone.type || "text/javascript";
233
+ if (script.hasAttribute("src")) {
234
+ scriptClone.src = script.src;
235
+ }
236
+ scriptClone.text = script.text;
237
+ if (debug) {
238
+ console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
239
+ }
240
+ document.head.appendChild(scriptClone);
241
+ document.head.removeChild(scriptClone);
242
+ });
243
+ }
244
+ }
245
+ else {
246
+ if (debug) {
247
+ console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
248
+ }
249
+ }
376
250
  }
377
-
378
- function satisfyFilter(filter, subject) {
379
- return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
251
+ function execJs(code, event) {
252
+ const varName = `jitsu_event_${randomId()}`;
253
+ window[varName] = event;
254
+ const iif = `(function(){
255
+ const event = ${varName};
256
+ ${code}
257
+ })()`;
258
+ try {
259
+ eval(iif);
260
+ }
261
+ catch (e) {
262
+ console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
263
+ }
264
+ finally {
265
+ delete window[varName];
266
+ }
267
+ return iif;
380
268
  }
381
- function applyFilters(event, creds) {
382
- const { hosts = "*", events = "*" } = creds;
383
- const eventsArray = events.split("\n");
384
- return (!!hosts.split("\n").find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
385
- (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
386
- !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event))));
269
+ function replaceMacro(code, event) {
270
+ return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
387
271
  }
388
272
  const internalDestinationPlugins = {
389
273
  [tagPlugin.id]: tagPlugin,
390
- [gtmPlugin.id]: gtmPlugin,
391
274
  [logrocketPlugin.id]: logrocketPlugin,
392
275
  };
393
276
 
277
+ var name = "@jitsu/js";
278
+ var version = "0.0.0";
279
+
394
280
  /* global analytics */
395
281
  var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
396
282
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
@@ -628,8 +514,8 @@
628
514
  const referrer = runtime.referrer();
629
515
  const context = {
630
516
  library: {
631
- name: "jitsu-js",
632
- version: "1.0.0",
517
+ name: name,
518
+ version: version,
633
519
  },
634
520
  userAgent: runtime.userAgent(),
635
521
  locale: runtime.language(),
@@ -647,7 +533,7 @@
647
533
  },
648
534
  campaign: parseUtms(query),
649
535
  };
650
- 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) });
536
+ 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) });
651
537
  delete withContext.meta;
652
538
  delete withContext.options;
653
539
  return withContext;
@@ -661,7 +547,6 @@
661
547
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
662
548
  if (plugin) {
663
549
  try {
664
- //to support old versions, where credentials were stored in root
665
550
  promises.push(plugin.handle(credentials, event));
666
551
  }
667
552
  catch (e) {
@@ -709,6 +594,15 @@
709
594
  }
710
595
  });
711
596
  }
597
+ function validateWriteKey(writeKey) {
598
+ if (writeKey) {
599
+ const [, secret] = writeKey.split(":", 2);
600
+ if (!secret) {
601
+ 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`);
602
+ }
603
+ }
604
+ return writeKey;
605
+ }
712
606
  function send(method, payload, jitsuConfig, instance, store) {
713
607
  if (jitsuConfig.echoEvents) {
714
608
  console.log(`[JITSU] sending '${method}' event:`, payload);
@@ -724,7 +618,7 @@
724
618
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
725
619
  // }
726
620
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
727
- const authHeader = adjustedPayload.writeKey ? { "X-Write-Key": adjustedPayload.writeKey } : {};
621
+ const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
728
622
  return fetch(url, {
729
623
  method: "POST",
730
624
  headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, authHeader), debugHeader),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jitsu/js",
3
- "version": "1.1.0-canary.391.20230523080206",
3
+ "version": "1.1.0-canary.404.20230526224724",
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.31.2",
15
+ "@playwright/test": "1.30.0",
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",
@@ -34,7 +34,7 @@
34
34
  "rollup": "^3.2.5",
35
35
  "ts-jest": "29.0.5",
36
36
  "typescript": "^4.9.5",
37
- "@jitsu/protocols": "1.1.0-canary.391.20230523080206"
37
+ "@jitsu/protocols": "1.1.0-canary.404.20230526224724"
38
38
  },
39
39
  "dependencies": {
40
40
  "analytics": "^0.8.1"
@@ -6,6 +6,7 @@ import parse from "./index";
6
6
  import { AnalyticsInstance, AnalyticsPlugin } from "analytics";
7
7
  import { loadScript } from "./script-loader";
8
8
  import { internalDestinationPlugins } from "./destination-plugins";
9
+ import { jitsuLibraryName, jitsuVersion } from "./version";
9
10
 
10
11
  const config: Required<JitsuOptions> = {
11
12
  /* Your segment writeKey */
@@ -257,8 +258,8 @@ function adjustPayload(payload: any, config: JitsuOptions, storage: PersistentSt
257
258
  const referrer = runtime.referrer();
258
259
  const context = {
259
260
  library: {
260
- name: "jitsu-js",
261
- version: "1.0.0",
261
+ name: jitsuLibraryName,
262
+ version: jitsuVersion,
262
263
  },
263
264
  userAgent: runtime.userAgent(),
264
265
  locale: runtime.language(),
@@ -281,7 +282,7 @@ function adjustPayload(payload: any, config: JitsuOptions, storage: PersistentSt
281
282
  timestamp: new Date().toISOString(),
282
283
  sentAt: new Date().toISOString(),
283
284
  messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)),
284
- writeKey: config.writeKey,
285
+ writeKey: validateWriteKey(config.writeKey),
285
286
  context: deepMerge(context, customContext),
286
287
  };
287
288
  delete withContext.meta;
@@ -386,6 +387,18 @@ async function processDestinations(
386
387
  }
387
388
  }
388
389
 
390
+ function validateWriteKey(writeKey?: string): string | undefined {
391
+ if (writeKey) {
392
+ const [, secret] = writeKey.split(":", 2);
393
+ if (!secret) {
394
+ throw new Error(
395
+ `Legacy write key detected - ${writeKey}! This format doesn't work anymore, it should be 'key:secret'. Please download a new key from Jitsu UI`
396
+ );
397
+ }
398
+ }
399
+ return writeKey;
400
+ }
401
+
389
402
  function send(
390
403
  method,
391
404
  payload,
@@ -411,7 +424,7 @@ function send(
411
424
  // console.log(`[JITSU] Sending event to ${url}: `, JSON.stringify(payload, null, 2));
412
425
  // }
413
426
  const adjustedPayload = adjustPayload(payload, jitsuConfig, store);
414
- const authHeader = adjustedPayload.writeKey ? { "X-Write-Key": adjustedPayload.writeKey } : {};
427
+ const authHeader = config.writeKey ? { "X-Write-Key": validateWriteKey(config.writeKey) } : {};
415
428
  return fetch(url, {
416
429
  method: "POST",
417
430
  headers: {
@@ -17,11 +17,24 @@ export function satisfyFilter(filter: string, subject: string | undefined): bool
17
17
  return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
18
18
  }
19
19
 
20
+ export function satisfyDomainFilter(filter: string, subject: string | undefined): boolean {
21
+ if (filter === "*") {
22
+ return true;
23
+ }
24
+ subject = subject || "";
25
+
26
+ if (filter.startsWith("*.")) {
27
+ return subject.endsWith(filter.substring(1));
28
+ } else {
29
+ return filter === subject;
30
+ }
31
+ }
32
+
20
33
  export function applyFilters(event: AnalyticsClientEvent, creds: CommonDestinationCredentials): boolean {
21
34
  const { hosts = "*", events = "*" } = creds;
22
35
  const eventsArray = events.split("\n");
23
36
  return (
24
- !!hosts.split("\n").find(hostFilter => satisfyFilter(hostFilter, event.context?.host)) &&
37
+ !!hosts.split("\n").find(hostFilter => satisfyDomainFilter(hostFilter, event.context?.host)) &&
25
38
  (!!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.type)) ||
26
39
  !!eventsArray.find(eventFilter => satisfyFilter(eventFilter, event.event)))
27
40
  );
package/src/version.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { name as jitsuLibraryName, version as jitsuVersion } from "../package.json";
2
+
3
+ export { jitsuVersion, jitsuLibraryName };
package/tsconfig.json CHANGED
@@ -5,6 +5,7 @@
5
5
  "declaration": true,
6
6
  "esModuleInterop": true,
7
7
  "moduleResolution": "Node",
8
+ "resolveJsonModule": true,
8
9
  "target": "ES2015",
9
10
  "lib": ["es2017", "dom"],
10
11
  //this makes typescript igore @types/node during compilation
package/.pnpm-debug.log DELETED
@@ -1,23 +0,0 @@
1
- {
2
- "0 debug pnpm:scope": {
3
- "selected": 1,
4
- "workspacePrefix": "/Users/ildarnurislamov/Projects/onetag"
5
- },
6
- "1 error pnpm": {
7
- "code": "ELIFECYCLE",
8
- "errno": "ENOENT",
9
- "syscall": "spawn",
10
- "file": "sh",
11
- "pkgid": "@jitsu/js@0.0.0",
12
- "stage": "build",
13
- "script": "tsc -p . && rollup -c && cp src/jitsu.d.ts dist",
14
- "pkgname": "@jitsu/js",
15
- "err": {
16
- "name": "pnpm",
17
- "message": "@jitsu/js@0.0.0 build: `tsc -p . && rollup -c && cp src/jitsu.d.ts dist`\nspawn ENOENT",
18
- "code": "ELIFECYCLE",
19
- "stack": "pnpm: @jitsu/js@0.0.0 build: `tsc -p . && rollup -c && cp src/jitsu.d.ts dist`\nspawn ENOENT\n at ChildProcess.<anonymous> (/opt/homebrew/lib/node_modules/pnpm/dist/pnpm.cjs:93535:22)\n at ChildProcess.emit (node:events:527:28)\n at maybeClose (node:internal/child_process:1092:16)\n at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)"
20
- }
21
- },
22
- "2 warn pnpm:global": " Local package.json exists, but node_modules missing, did you mean to install?"
23
- }