@jitsu/js 1.0.0-canary-20230211032904 → 1.0.0-canary-20230219230011

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.
@@ -1,33 +1,65 @@
1
- @jitsu/js:build: cache hit, replaying output b530f4244fe3e541
2
- @jitsu/js:build: 
3
- @jitsu/js:build: > @jitsu/js@0.0.0 build /Users/vklmn/dev2/onetag/libs/jitsu-js
4
- @jitsu/js:build: > tsc -p . && rollup -c && cp compiled/src/*.d.ts dist
5
- @jitsu/js:build: 
6
- @jitsu/js:build: 
7
- @jitsu/js:build: ./compiled/src/browser.js → dist/web/p.js.txt...
8
- @jitsu/js:build: (!) Circular dependency
9
- @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
10
- @jitsu/js:build: (!) Use of eval is strongly discouraged
11
- @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
12
- @jitsu/js:build: compiled/src/analytics-plugin.js
13
- @jitsu/js:build: 258: })()`;
14
- @jitsu/js:build: 259: try {
15
- @jitsu/js:build: 260: eval(iif);
16
- @jitsu/js:build:  ^
17
- @jitsu/js:build: 261: }
18
- @jitsu/js:build: 262: catch (e) {
19
- @jitsu/js:build: created dist/web/p.js.txt in 226ms
20
- @jitsu/js:build: 
21
- @jitsu/js:build: ./compiled/src/index.js, ./compiled/src/jitsu.js, ./compiled/src/analytics-plugin.js dist/jitsu.es.js, dist/jitsu.cjs.js...
22
- @jitsu/js:build: (!) Circular dependency
23
- @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
24
- @jitsu/js:build: (!) Use of eval is strongly discouraged
25
- @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
26
- @jitsu/js:build: compiled/src/analytics-plugin.js
27
- @jitsu/js:build: 258: })()`;
28
- @jitsu/js:build: 259: try {
29
- @jitsu/js:build: 260: eval(iif);
30
- @jitsu/js:build:  ^
31
- @jitsu/js:build: 261: }
32
- @jitsu/js:build: 262: catch (e) {
33
- @jitsu/js:build: created dist/jitsu.es.js, dist/jitsu.cjs.js in 121ms
1
+ @jitsu/js:build: cache hit, replaying output c41fba61aef5e756
2
+ @jitsu/js:build: 
3
+ @jitsu/js:build: > @jitsu/js@0.0.0 build /Users/vklmn/dev2/onetag/libs/jitsu-js
4
+ @jitsu/js:build: > tsc -p . && rollup -c && cp compiled/src/*.d.ts dist
5
+ @jitsu/js:build: 
6
+ @jitsu/js:build: 
7
+ @jitsu/js:build: ./compiled/src/browser.js → dist/web/p.js.txt...
8
+ @jitsu/js:build: (!) "this" has been rewritten to "undefined"
9
+ @jitsu/js:build: https://rollupjs.org/guide/en/#error-this-is-undefined
10
+ @jitsu/js:build: compiled/src/analytics-plugin.js
11
+ @jitsu/js:build: 1: /* global analytics */
12
+ @jitsu/js:build: 2: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ @jitsu/js:build:  ^
14
+ @jitsu/js:build: 3: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ @jitsu/js:build: 4: return new (P || (P = Promise))(function (resolve, reject) {
16
+ @jitsu/js:build: ...and 1 other occurrence
17
+ @jitsu/js:build: compiled/src/destination-plugins.js
18
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ @jitsu/js:build:  ^
20
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
22
+ @jitsu/js:build: ...and 1 other occurrence
23
+ @jitsu/js:build: (!) Circular dependencies
24
+ @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
25
+ @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins.js -> compiled/src/analytics-plugin.js
26
+ @jitsu/js:build: (!) Use of eval is strongly discouraged
27
+ @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
28
+ @jitsu/js:build: compiled/src/destination-plugins.js
29
+ @jitsu/js:build: 75: })()`;
30
+ @jitsu/js:build: 76: try {
31
+ @jitsu/js:build: 77: eval(iif);
32
+ @jitsu/js:build:  ^
33
+ @jitsu/js:build: 78: }
34
+ @jitsu/js:build: 79: catch (e) {
35
+ @jitsu/js:build: created dist/web/p.js.txt in 252ms
36
+ @jitsu/js:build: 
37
+ @jitsu/js:build: ./compiled/src/index.js, ./compiled/src/jitsu.js, ./compiled/src/analytics-plugin.js → dist/jitsu.es.js, dist/jitsu.cjs.js...
38
+ @jitsu/js:build: (!) "this" has been rewritten to "undefined"
39
+ @jitsu/js:build: https://rollupjs.org/guide/en/#error-this-is-undefined
40
+ @jitsu/js:build: compiled/src/analytics-plugin.js
41
+ @jitsu/js:build: 1: /* global analytics */
42
+ @jitsu/js:build: 2: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
43
+ @jitsu/js:build:  ^
44
+ @jitsu/js:build: 3: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
+ @jitsu/js:build: 4: return new (P || (P = Promise))(function (resolve, reject) {
46
+ @jitsu/js:build: ...and 1 other occurrence
47
+ @jitsu/js:build: compiled/src/destination-plugins.js
48
+ @jitsu/js:build: 1: var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
49
+ @jitsu/js:build:  ^
50
+ @jitsu/js:build: 2: function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
51
+ @jitsu/js:build: 3: return new (P || (P = Promise))(function (resolve, reject) {
52
+ @jitsu/js:build: ...and 1 other occurrence
53
+ @jitsu/js:build: (!) Circular dependencies
54
+ @jitsu/js:build: compiled/src/index.js -> compiled/src/analytics-plugin.js -> compiled/src/index.js
55
+ @jitsu/js:build: compiled/src/analytics-plugin.js -> compiled/src/destination-plugins.js -> compiled/src/analytics-plugin.js
56
+ @jitsu/js:build: (!) Use of eval is strongly discouraged
57
+ @jitsu/js:build: https://rollupjs.org/guide/en/#avoiding-eval
58
+ @jitsu/js:build: compiled/src/destination-plugins.js
59
+ @jitsu/js:build: 75: })()`;
60
+ @jitsu/js:build: 76: try {
61
+ @jitsu/js:build: 77: eval(iif);
62
+ @jitsu/js:build:  ^
63
+ @jitsu/js:build: 78: }
64
+ @jitsu/js:build: 79: catch (e) {
65
+ @jitsu/js:build: created dist/jitsu.es.js, dist/jitsu.cjs.js in 151ms
@@ -1,5 +1,5 @@
1
- @jitsu/js:clean: cache hit, replaying output 928bbc238fc9b4c5
2
- @jitsu/js:clean: 
3
- @jitsu/js:clean: > @jitsu/js@0.0.0 clean /Users/vklmn/dev2/onetag/libs/jitsu-js
4
- @jitsu/js:clean: > rm -rf ./dist
5
- @jitsu/js:clean: 
1
+ @jitsu/js:clean: cache hit, replaying output c648dd4be85c0190
2
+ @jitsu/js:clean: 
3
+ @jitsu/js:clean: > @jitsu/js@0.0.0 clean /Users/vklmn/dev2/onetag/libs/jitsu-js
4
+ @jitsu/js:clean: > rm -rf ./dist
5
+ @jitsu/js:clean: 
@@ -0,0 +1,66 @@
1
+ import { delayMethodExec } from "../../src/method-queue";
2
+ import { expect } from "@playwright/test";
3
+
4
+ interface ITest {
5
+ method(str: string, num: number): string;
6
+
7
+ _internalMethod(str: string, num: number): string;
8
+ }
9
+
10
+ interface AsyncInterface {
11
+ method(str: string, num: number): Promise<string>;
12
+
13
+ _internalMethod(str: string, num: number);
14
+ }
15
+
16
+ test("method-queue", async () => {
17
+ const testResult: string[] = [];
18
+ const wrap = delayMethodExec<ITest>({
19
+ method: true,
20
+ _internalMethod: false,
21
+ });
22
+ const instance = wrap.get();
23
+ const wrapPromise = instance.method("a", 1).then(res => testResult.push(res));
24
+
25
+ expect(testResult).toEqual([]);
26
+ expect(() => instance._internalMethod("a", 1)).toThrowError();
27
+
28
+ wrap.loaded({
29
+ _internalMethod(str, num) {
30
+ return `${str}${num}`;
31
+ },
32
+ method(str, num) {
33
+ const result = this._internalMethod(str, num);
34
+ testResult.push(result);
35
+ return `result:${result}`;
36
+ },
37
+ });
38
+ await wrapPromise;
39
+
40
+ expect(testResult).toEqual(["a1", "result:a1"]);
41
+
42
+ instance.method("b", 2);
43
+ expect(testResult).toEqual(["a1", "result:a1", "b2"]);
44
+ });
45
+
46
+ test("test-async", async () => {
47
+ const testResult: string[] = [];
48
+ const wrap = delayMethodExec<AsyncInterface>({
49
+ method: true,
50
+ _internalMethod: false,
51
+ });
52
+ const instance = wrap.get();
53
+ const wrapPromise = instance.method("a", 1).then(res => testResult.push(res));
54
+
55
+ wrap.loaded({
56
+ _internalMethod(str, num) {
57
+ return `${str}${num}`;
58
+ },
59
+ async method(str, num) {
60
+ await new Promise(resolve => setTimeout(resolve, 1000));
61
+ return `result:${this._internalMethod(str, num)}`;
62
+ },
63
+ });
64
+ await wrapPromise;
65
+ expect(testResult).toEqual(["result:a1"]);
66
+ });
@@ -3,7 +3,7 @@ import { createServer, SimpleSyrup } from "../simple-syrup";
3
3
  import * as fs from "fs";
4
4
  import * as path from "path";
5
5
  import ejs from "ejs";
6
- import chalk from "chalk";
6
+ // import chalk from "chalk";
7
7
  import * as process from "process";
8
8
  import * as console from "console";
9
9
  import { AnalyticsClientEvent, AnalyticsInterface } from "@jitsu/protocols/analytics.d";
@@ -14,6 +14,11 @@ test.use({
14
14
  ignoreHTTPSErrors: true,
15
15
  });
16
16
 
17
+ const chalk = {
18
+ cyan: (str: string) => str,
19
+ bold: (str: string) => str,
20
+ };
21
+
17
22
  const express = require("express");
18
23
  const cookieParser = require("cookie-parser");
19
24
  const app = express();
@@ -79,17 +84,6 @@ function sortKeysRecursively(obj: any): any {
79
84
  return obj;
80
85
  }
81
86
 
82
- function logColor(type: string) {
83
- return (
84
- {
85
- error: chalk.bgRed,
86
- warn: chalk.bgYellow,
87
- info: chalk.bgBlack,
88
- log: chalk.bgGray,
89
- }[type] || (x => x)
90
- );
91
- }
92
-
93
87
  function shouldKeepBrowserOpen() {
94
88
  return process.env.KEEP_BROWSER_OPEN === "true" || process.env.KEEP_BROWSER_OPEN === "1";
95
89
  }
@@ -5,6 +5,23 @@ export type StorageFactory = (cookieDomain: string, cookie2key: Record<string, s
5
5
  export declare function getTopLevelDomain(opts?: JitsuOptions): string;
6
6
  export declare function windowRuntime(opts: JitsuOptions): RuntimeFacade;
7
7
  export declare const emptyRuntime: (config: JitsuOptions) => RuntimeFacade;
8
+ export declare function isInBrowser(): boolean;
9
+ export type DestinationDescriptor = {
10
+ id: string;
11
+ destinationType: string;
12
+ credentials: any;
13
+ deviceOptions: DeviceOptions;
14
+ };
15
+ export type AnalyticsPluginDescriptor = {
16
+ type: "analytics-plugin";
17
+ packageCdn: string;
18
+ moduleVarName: string;
19
+ };
20
+ export type InternalPluginDescriptor = {
21
+ type: "internal-plugin";
22
+ name: string;
23
+ };
24
+ export type DeviceOptions = AnalyticsPluginDescriptor | InternalPluginDescriptor;
8
25
  declare const jitsuAnalyticsPlugin: (pluginConfig?: JitsuOptions) => AnalyticsPlugin;
9
26
  export declare function randomId(hashString?: string | undefined): string;
10
27
  export default jitsuAnalyticsPlugin;
@@ -0,0 +1,13 @@
1
+ import { AnalyticsClientEvent } from "@jitsu/protocols/analytics";
2
+ export type InternalPlugin<T> = {
3
+ id: string;
4
+ handle(config: T, payload: AnalyticsClientEvent): Promise<void>;
5
+ };
6
+ export type CommonDestinationCredentials = {
7
+ hosts?: string[];
8
+ events?: string[];
9
+ };
10
+ export type TagDestinationCredentials = {
11
+ code: string;
12
+ } & CommonDestinationCredentials;
13
+ export declare const internalDestinationPlugins: Record<string, InternalPlugin<any>>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { JitsuOptions, AnalyticsInterface } from "./jitsu";
1
+ import { AnalyticsInterface, JitsuOptions } from "./jitsu";
2
2
  export default function parse(input: any): any;
3
3
  export declare function jitsuAnalytics(opts: JitsuOptions): AnalyticsInterface;
4
4
  export * from "./jitsu";
package/dist/jitsu.cjs.js CHANGED
@@ -67,7 +67,151 @@ function analyticsLib() {
67
67
  return ke(_objectSpread2(_objectSpread2({}, defaultSettings), opts));
68
68
  }
69
69
 
70
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
71
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
72
+ return new (P || (P = Promise))(function (resolve, reject) {
73
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
74
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
75
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
76
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
77
+ });
78
+ };
79
+ function satisfyFilter(filter, subject) {
80
+ return filter === "*" || filter.toLowerCase().trim() === (subject || "").trim().toLowerCase();
81
+ }
82
+ function applyFilters(event, creds) {
83
+ const { hosts = ["*"], events = ["*"] } = creds;
84
+ return (!!hosts.find(hostFilter => { var _a; return satisfyFilter(hostFilter, (_a = event.context) === null || _a === void 0 ? void 0 : _a.host); }) &&
85
+ !!events.find(eventFilter => satisfyFilter(eventFilter, event.type)));
86
+ }
87
+ const tagPlugin = {
88
+ id: "tag",
89
+ handle(config, payload) {
90
+ return __awaiter$1(this, void 0, void 0, function* () {
91
+ if (!applyFilters(payload, config)) {
92
+ return;
93
+ }
94
+ insertTags(config.code, payload);
95
+ });
96
+ },
97
+ };
98
+ function insertTags(code, event, opts = {}) {
99
+ let tag;
100
+ try {
101
+ tag = JSON.parse(code);
102
+ }
103
+ catch (e) {
104
+ tag = { code, lang: "javascript" };
105
+ }
106
+ const debug = opts.debug || false;
107
+ if (isInBrowser()) {
108
+ if (tag.lang === "javascript") {
109
+ execJs(tag.code, event);
110
+ }
111
+ else {
112
+ const codeHolder = document.createElement("span");
113
+ codeHolder.innerHTML = replaceMacro(tag.code, event);
114
+ document.body.insertAdjacentElement("beforeend", codeHolder);
115
+ const scripts = codeHolder.querySelectorAll("script");
116
+ scripts.forEach(script => {
117
+ const scriptClone = document.createElement("script");
118
+ scriptClone.type = scriptClone.type || "text/javascript";
119
+ if (script.hasAttribute("src")) {
120
+ scriptClone.src = script.src;
121
+ }
122
+ scriptClone.text = script.text;
123
+ if (debug) {
124
+ console.log(`[JITSU] Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
125
+ }
126
+ document.head.appendChild(scriptClone);
127
+ document.head.removeChild(scriptClone);
128
+ });
129
+ }
130
+ }
131
+ else {
132
+ if (debug) {
133
+ console.log(`[JITSU] insertTags(): cannot insert tags in non-browser environment`);
134
+ }
135
+ }
136
+ }
137
+ function execJs(code, event) {
138
+ const varName = `jitsu_event_${randomId()}`;
139
+ window[varName] = event;
140
+ const iif = `(function(){
141
+ const event = ${varName};
142
+ ${code}
143
+ })()`;
144
+ try {
145
+ eval(iif);
146
+ }
147
+ catch (e) {
148
+ console.error(`[JITSU] Error executing JS code: ${e.message}. Code: `, iif);
149
+ }
150
+ finally {
151
+ delete window[varName];
152
+ }
153
+ return iif;
154
+ }
155
+ function replaceMacro(code, event) {
156
+ return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
157
+ }
158
+ const internalDestinationPlugins = {
159
+ [tagPlugin.id]: tagPlugin,
160
+ };
161
+
162
+ function findScript(src) {
163
+ const scripts = Array.prototype.slice.call(window.document.querySelectorAll("script"));
164
+ return scripts.find(s => s.src === src);
165
+ }
166
+ function loadScript(src, attributes) {
167
+ const found = findScript(src);
168
+ if (found !== undefined) {
169
+ const status = found === null || found === void 0 ? void 0 : found.getAttribute("status");
170
+ if (status === "loaded") {
171
+ return Promise.resolve(found);
172
+ }
173
+ if (status === "loading") {
174
+ return new Promise((resolve, reject) => {
175
+ found.addEventListener("load", () => resolve(found));
176
+ found.addEventListener("error", err => reject(err));
177
+ });
178
+ }
179
+ }
180
+ return new Promise((resolve, reject) => {
181
+ var _a;
182
+ const script = window.document.createElement("script");
183
+ script.type = "text/javascript";
184
+ script.src = src;
185
+ script.async = true;
186
+ script.setAttribute("status", "loading");
187
+ for (const [k, v] of Object.entries(attributes !== null && attributes !== void 0 ? attributes : {})) {
188
+ script.setAttribute(k, v);
189
+ }
190
+ script.onload = () => {
191
+ script.onerror = script.onload = null;
192
+ script.setAttribute("status", "loaded");
193
+ resolve(script);
194
+ };
195
+ script.onerror = () => {
196
+ script.onerror = script.onload = null;
197
+ script.setAttribute("status", "error");
198
+ reject(new Error(`Failed to load ${src}`));
199
+ };
200
+ const tag = window.document.getElementsByTagName("script")[0];
201
+ (_a = tag.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(script, tag);
202
+ });
203
+ }
204
+
70
205
  /* global analytics */
206
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
207
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
208
+ return new (P || (P = Promise))(function (resolve, reject) {
209
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
210
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
211
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
212
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
213
+ });
214
+ };
71
215
  const config = {
72
216
  /* Your segment writeKey */
73
217
  writeKey: null,
@@ -279,7 +423,7 @@ function deepMerge(target, source) {
279
423
  }, target);
280
424
  }
281
425
  function isInBrowser() {
282
- return typeof document !== "undefined";
426
+ return typeof document !== "undefined" && typeof window !== "undefined";
283
427
  }
284
428
  function adjustPayload(payload, config, storage) {
285
429
  var _a, _b;
@@ -317,62 +461,62 @@ function adjustPayload(payload, config, storage) {
317
461
  delete withContext.options;
318
462
  return withContext;
319
463
  }
320
- function execJs(code, event) {
321
- const varName = `jitsu_event_${randomId()}`;
322
- window[varName] = event;
323
- const iif = `(function(){
324
- ${code}
325
- onEvent(${varName});
326
- })()`;
327
- try {
328
- eval(iif);
329
- }
330
- catch (e) {
331
- console.error(`[JITSU] Error executing JS code: ${e.message}`);
332
- }
333
- finally {
334
- delete window[varName];
335
- }
336
- return iif;
337
- }
338
- function replaceMacro(code, event) {
339
- return code.replace(/{{\s*event\s*}}/g, JSON.stringify(event));
340
- }
341
- function insertTags(tags, event, opts = {}) {
342
- const debug = opts.debug || false;
343
- if (isInBrowser()) {
344
- Object.values(tags).forEach(tag => {
345
- if (tag.mode === "javascript") {
346
- execJs(tag.code, event);
464
+ function processDestinations(destinations, method, event, debug, analyticsInstance) {
465
+ return __awaiter(this, void 0, void 0, function* () {
466
+ const promises = [];
467
+ for (const destination of destinations) {
468
+ if (destination.deviceOptions.type === "internal-plugin") {
469
+ const plugin = internalDestinationPlugins[destination.deviceOptions.name];
470
+ if (plugin) {
471
+ try {
472
+ promises.push(plugin.handle(destination.credentials, event));
473
+ }
474
+ catch (e) {
475
+ console.warn(`[JITSU] Error processing event with internal plugin '${destination.deviceOptions.name}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
476
+ }
477
+ }
478
+ else {
479
+ console.warn(`[JITSU] Unknown internal plugin '${destination.deviceOptions.name}' for destination '${destination.id}'`);
480
+ }
347
481
  }
348
- else {
349
- const codeHolder = document.createElement("span");
350
- codeHolder.innerHTML = replaceMacro(tag.code, event);
351
- document.body.insertAdjacentElement("beforeend", codeHolder);
352
- const scripts = codeHolder.querySelectorAll("script");
353
- scripts.forEach(script => {
354
- const scriptClone = document.createElement("script");
355
- scriptClone.type = scriptClone.type || "text/javascript";
356
- if (script.hasAttribute("src")) {
357
- scriptClone.src = script.src;
482
+ else if (destination.deviceOptions.type === "analytics-plugin") {
483
+ yield loadScript(destination.deviceOptions.packageCdn);
484
+ const plugin = window[destination.deviceOptions.moduleVarName];
485
+ if (!plugin) {
486
+ console.warn(`[JITSU] Broken plugin '${destination.deviceOptions.packageCdn}' for destination '${destination.id}' - it doesn't export '${destination.deviceOptions.moduleVarName}' variable`);
487
+ }
488
+ else {
489
+ let pluginInstance;
490
+ try {
491
+ pluginInstance = (typeof plugin === "function" ? plugin : plugin.init)(destination.credentials);
492
+ }
493
+ catch (e) {
494
+ 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);
495
+ }
496
+ try {
497
+ if (debug) {
498
+ console.log(`[JITSU] Plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}' initialized with config:`, pluginInstance.config);
499
+ }
500
+ pluginInstance.initialize({ config: pluginInstance.config, instance: analyticsInstance });
358
501
  }
359
- scriptClone.text = script.text;
360
- if (debug) {
361
- console.log(`Executing script${script.hasAttribute("src") ? ` ${script.src}` : ""}`, scriptClone.text);
502
+ catch (e) {
503
+ console.warn(`[JITSU] Error initializing plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}. Config: ${JSON.stringify(pluginInstance.config)}`, e);
504
+ continue;
362
505
  }
363
- document.head.appendChild(scriptClone);
364
- document.head.removeChild(scriptClone);
365
- });
506
+ if (pluginInstance[method]) {
507
+ try {
508
+ pluginInstance[method]({ payload: event, config: pluginInstance.config, instance: analyticsInstance });
509
+ }
510
+ catch (e) {
511
+ console.warn(`[JITSU] Error processing ${method}() with plugin '${destination.deviceOptions.moduleVarName}@${destination.deviceOptions.packageCdn}' for destination '${destination.id}': ${e === null || e === void 0 ? void 0 : e.message}`, e);
512
+ }
513
+ }
514
+ }
366
515
  }
367
- });
368
- }
369
- else {
370
- if (debug) {
371
- console.log(`insertTags: cannot insert tags in non-browser environment`);
372
516
  }
373
- }
517
+ });
374
518
  }
375
- function send(method, payload, jitsuConfig, store) {
519
+ function send(method, payload, jitsuConfig, instance, store) {
376
520
  if (jitsuConfig.echoEvents) {
377
521
  console.log(`[JITSU] sending '${method}' event:`, payload);
378
522
  return;
@@ -405,18 +549,19 @@ function send(method, payload, jitsuConfig, store) {
405
549
  }
406
550
  })
407
551
  .then(responseText => {
552
+ let response;
408
553
  try {
409
- const response = JSON.parse(responseText);
410
- if (response.tags) {
411
- if (jitsuConfig.debug) {
412
- console.log(`[JITSU] Response Tags: `, JSON.stringify(response.tags, null, 2));
413
- }
414
- insertTags(response.tags, payload, { debug: jitsuConfig.debug });
415
- }
554
+ response = JSON.parse(responseText);
416
555
  }
417
556
  catch (e) {
418
557
  return Promise.reject(`Can't parse JSON: ${responseText}: ${e === null || e === void 0 ? void 0 : e.message}`);
419
558
  }
559
+ if (response.destinations) {
560
+ if (jitsuConfig.debug) {
561
+ console.log(`[JITSU] Processing device destianations: `, JSON.stringify(response.destinations, null, 2));
562
+ }
563
+ return processDestinations(response.destinations, method, adjustedPayload, !!jitsuConfig.debug, instance);
564
+ }
420
565
  })
421
566
  .catch(err => {
422
567
  if (jitsuConfig.debug) {
@@ -446,9 +591,9 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
446
591
  name: "jitsu",
447
592
  config: Object.assign(Object.assign({}, config), pluginConfig),
448
593
  initialize: args => {
449
- const { config, instance } = args;
594
+ const { config } = args;
450
595
  if (config.debug) {
451
- console.debug("Initializing Jitsu plugin with config: ", JSON.stringify(config));
596
+ console.debug("[JITSU] Initializing Jitsu plugin with config: ", JSON.stringify(config));
452
597
  }
453
598
  if (!config.host && !config.echoEvents) {
454
599
  throw new Error("Please specify host variable in jitsu plugin initialization, or set echoEvents to true");
@@ -456,17 +601,17 @@ const jitsuAnalyticsPlugin = (pluginConfig = {}) => {
456
601
  },
457
602
  page: args => {
458
603
  const { payload, config, instance } = args;
459
- return send("page", payload, config, cachingStorageWrapper(instance.storage));
604
+ return send("page", payload, config, instance, cachingStorageWrapper(instance.storage));
460
605
  },
461
606
  track: args => {
462
607
  const { payload, config, instance } = args;
463
- return send("track", payload, config, cachingStorageWrapper(instance.storage));
608
+ return send("track", payload, config, instance, cachingStorageWrapper(instance.storage));
464
609
  },
465
610
  identify: args => {
466
611
  const { payload, config, instance } = args;
467
612
  // Store traits in cache to be able to use them in page and track events that run asynchronously with current identify.
468
613
  storageCache["__user_traits"] = payload.traits;
469
- return send("identify", payload, config, cachingStorageWrapper(instance.storage));
614
+ return send("identify", payload, config, instance, cachingStorageWrapper(instance.storage));
470
615
  },
471
616
  reset: args => {
472
617
  //clear storage cache
@@ -519,13 +664,12 @@ function parse(input) {
519
664
  }
520
665
  return value;
521
666
  }
522
- function jitsuAnalytics(opts) {
523
- const rt = opts.runtime || (typeof window === "undefined" ? emptyRuntime(opts) : windowRuntime(opts));
667
+ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
524
668
  const analytics = analyticsLib({
525
669
  app: "test",
526
670
  debug: !!opts.debug,
527
671
  storage: rt.store(),
528
- plugins: [jitsuAnalyticsPlugin(opts)],
672
+ plugins: [jitsuAnalyticsPlugin(opts), ...plugins],
529
673
  });
530
674
  const originalPage = analytics.page;
531
675
  analytics.page = (...args) => {
@@ -538,9 +682,37 @@ function jitsuAnalytics(opts) {
538
682
  };
539
683
  return analytics;
540
684
  }
685
+ function jitsuAnalytics(opts) {
686
+ const inBrowser = isInBrowser();
687
+ const rt = opts.runtime || (inBrowser ? windowRuntime(opts) : emptyRuntime(opts));
688
+ return createUnderlyingAnalyticsInstance(opts, rt);
689
+ // if (inBrowser) {
690
+ // const fetch = opts.fetch || globalThis.fetch;
691
+ // if (!fetch) {
692
+ // throw new Error(
693
+ // "Please specify fetch function in jitsu plugin initialization, fetch isn't available in global scope"
694
+ // );
695
+ // }
696
+ // const url = `${opts.host}/api/s/cfg`;
697
+ // const authHeader = {};
698
+ // const debugHeader = opts.debug ? { "X-Enable-Debug": "true" } : {};
699
+ // fetch(url)
700
+ // .then(res => res.json())
701
+ // .then(res => {
702
+ // result.loaded(createUnderlyingAnalyticsInstance(opts, rt, []));
703
+ // })
704
+ // .catch(e => {
705
+ // console.warn(`[JITSU] error getting device-destinations from ${url}`, e);
706
+ // result.loaded(createUnderlyingAnalyticsInstance(opts, rt));
707
+ // });
708
+ // } else {
709
+ // result.loaded(createUnderlyingAnalyticsInstance(opts, rt));
710
+ // }
711
+ }
541
712
 
542
713
  exports.emptyRuntime = emptyRuntime;
543
714
  exports.getTopLevelDomain = getTopLevelDomain;
715
+ exports.isInBrowser = isInBrowser;
544
716
  exports.jitsuAnalytics = jitsuAnalytics;
545
717
  exports.parseQuery = parseQuery;
546
718
  exports.randomId = randomId;