@journium/js 1.1.0 → 1.1.1

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.
@@ -0,0 +1,1871 @@
1
+ /* Journium Analytics SDK - Browser CDN Build */
2
+ (function (exports) {
3
+ 'use strict';
4
+
5
+ /**
6
+ * uuidv7: A JavaScript implementation of UUID version 7
7
+ *
8
+ * Copyright 2021-2024 LiosK
9
+ *
10
+ * @license Apache-2.0
11
+ * @packageDocumentation
12
+ */
13
+ const DIGITS = "0123456789abcdef";
14
+ /** Represents a UUID as a 16-byte byte array. */
15
+ class UUID {
16
+ /** @param bytes - The 16-byte byte array representation. */
17
+ constructor(bytes) {
18
+ this.bytes = bytes;
19
+ }
20
+ /**
21
+ * Creates an object from the internal representation, a 16-byte byte array
22
+ * containing the binary UUID representation in the big-endian byte order.
23
+ *
24
+ * This method does NOT shallow-copy the argument, and thus the created object
25
+ * holds the reference to the underlying buffer.
26
+ *
27
+ * @throws TypeError if the length of the argument is not 16.
28
+ */
29
+ static ofInner(bytes) {
30
+ if (bytes.length !== 16) {
31
+ throw new TypeError("not 128-bit length");
32
+ }
33
+ else {
34
+ return new UUID(bytes);
35
+ }
36
+ }
37
+ /**
38
+ * Builds a byte array from UUIDv7 field values.
39
+ *
40
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
41
+ * @param randA - A 12-bit `rand_a` field value.
42
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
43
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
44
+ * @throws RangeError if any field value is out of the specified range.
45
+ */
46
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
47
+ if (!Number.isInteger(unixTsMs) ||
48
+ !Number.isInteger(randA) ||
49
+ !Number.isInteger(randBHi) ||
50
+ !Number.isInteger(randBLo) ||
51
+ unixTsMs < 0 ||
52
+ randA < 0 ||
53
+ randBHi < 0 ||
54
+ randBLo < 0 ||
55
+ unixTsMs > 281474976710655 ||
56
+ randA > 0xfff ||
57
+ randBHi > 1073741823 ||
58
+ randBLo > 4294967295) {
59
+ throw new RangeError("invalid field value");
60
+ }
61
+ const bytes = new Uint8Array(16);
62
+ bytes[0] = unixTsMs / 2 ** 40;
63
+ bytes[1] = unixTsMs / 2 ** 32;
64
+ bytes[2] = unixTsMs / 2 ** 24;
65
+ bytes[3] = unixTsMs / 2 ** 16;
66
+ bytes[4] = unixTsMs / 2 ** 8;
67
+ bytes[5] = unixTsMs;
68
+ bytes[6] = 0x70 | (randA >>> 8);
69
+ bytes[7] = randA;
70
+ bytes[8] = 0x80 | (randBHi >>> 24);
71
+ bytes[9] = randBHi >>> 16;
72
+ bytes[10] = randBHi >>> 8;
73
+ bytes[11] = randBHi;
74
+ bytes[12] = randBLo >>> 24;
75
+ bytes[13] = randBLo >>> 16;
76
+ bytes[14] = randBLo >>> 8;
77
+ bytes[15] = randBLo;
78
+ return new UUID(bytes);
79
+ }
80
+ /**
81
+ * Builds a byte array from a string representation.
82
+ *
83
+ * This method accepts the following formats:
84
+ *
85
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
86
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
87
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
88
+ * - RFC 9562 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
89
+ *
90
+ * Leading and trailing whitespaces represents an error.
91
+ *
92
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
93
+ */
94
+ static parse(uuid) {
95
+ var _a, _b, _c, _d;
96
+ let hex = undefined;
97
+ switch (uuid.length) {
98
+ case 32:
99
+ hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
100
+ break;
101
+ case 36:
102
+ hex =
103
+ (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
104
+ .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
105
+ break;
106
+ case 38:
107
+ hex =
108
+ (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
109
+ .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
110
+ break;
111
+ case 45:
112
+ hex =
113
+ (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
114
+ .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
115
+ break;
116
+ }
117
+ if (hex) {
118
+ const inner = new Uint8Array(16);
119
+ for (let i = 0; i < 16; i += 4) {
120
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
121
+ inner[i + 0] = n >>> 24;
122
+ inner[i + 1] = n >>> 16;
123
+ inner[i + 2] = n >>> 8;
124
+ inner[i + 3] = n;
125
+ }
126
+ return new UUID(inner);
127
+ }
128
+ else {
129
+ throw new SyntaxError("could not parse UUID string");
130
+ }
131
+ }
132
+ /**
133
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
134
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
135
+ */
136
+ toString() {
137
+ let text = "";
138
+ for (let i = 0; i < this.bytes.length; i++) {
139
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
140
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
141
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
142
+ text += "-";
143
+ }
144
+ }
145
+ return text;
146
+ }
147
+ /**
148
+ * @returns The 32-digit hexadecimal representation without hyphens
149
+ * (`0189dcd553117d408db09496a2eef37b`).
150
+ */
151
+ toHex() {
152
+ let text = "";
153
+ for (let i = 0; i < this.bytes.length; i++) {
154
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
155
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
156
+ }
157
+ return text;
158
+ }
159
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
160
+ toJSON() {
161
+ return this.toString();
162
+ }
163
+ /**
164
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
165
+ * "MAX".
166
+ *
167
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
168
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
169
+ * subsumed under the variants `0b0` and `0b111`, respectively.
170
+ */
171
+ getVariant() {
172
+ const n = this.bytes[8] >>> 4;
173
+ if (n < 0) {
174
+ throw new Error("unreachable");
175
+ }
176
+ else if (n <= 0b0111) {
177
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
178
+ }
179
+ else if (n <= 0b1011) {
180
+ return "VAR_10";
181
+ }
182
+ else if (n <= 0b1101) {
183
+ return "VAR_110";
184
+ }
185
+ else if (n <= 0b1111) {
186
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
187
+ }
188
+ else {
189
+ throw new Error("unreachable");
190
+ }
191
+ }
192
+ /**
193
+ * Returns the version field value of the UUID or `undefined` if the UUID does
194
+ * not have the variant field value of `0b10`.
195
+ */
196
+ getVersion() {
197
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
198
+ }
199
+ /** Creates an object from `this`. */
200
+ clone() {
201
+ return new UUID(this.bytes.slice(0));
202
+ }
203
+ /** Returns true if `this` is equivalent to `other`. */
204
+ equals(other) {
205
+ return this.compareTo(other) === 0;
206
+ }
207
+ /**
208
+ * Returns a negative integer, zero, or positive integer if `this` is less
209
+ * than, equal to, or greater than `other`, respectively.
210
+ */
211
+ compareTo(other) {
212
+ for (let i = 0; i < 16; i++) {
213
+ const diff = this.bytes[i] - other.bytes[i];
214
+ if (diff !== 0) {
215
+ return Math.sign(diff);
216
+ }
217
+ }
218
+ return 0;
219
+ }
220
+ }
221
+ /**
222
+ * Encapsulates the monotonic counter state.
223
+ *
224
+ * This class provides APIs to utilize a separate counter state from that of the
225
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
226
+ * the default {@link generate} method, this class has {@link generateOrAbort}
227
+ * that is useful to absolutely guarantee the monotonically increasing order of
228
+ * generated UUIDs. See their respective documentation for details.
229
+ */
230
+ class V7Generator {
231
+ /**
232
+ * Creates a generator object with the default random number generator, or
233
+ * with the specified one if passed as an argument. The specified random
234
+ * number generator should be cryptographically strong and securely seeded.
235
+ */
236
+ constructor(randomNumberGenerator) {
237
+ this.timestamp = 0;
238
+ this.counter = 0;
239
+ this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
240
+ }
241
+ /**
242
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
243
+ * generator upon significant timestamp rollback.
244
+ *
245
+ * This method returns a monotonically increasing UUID by reusing the previous
246
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
247
+ * preceding UUID's. However, when such a clock rollback is considered
248
+ * significant (i.e., by more than ten seconds), this method resets the
249
+ * generator and returns a new UUID based on the given timestamp, breaking the
250
+ * increasing order of UUIDs.
251
+ *
252
+ * See {@link generateOrAbort} for the other mode of generation and
253
+ * {@link generateOrResetCore} for the low-level primitive.
254
+ */
255
+ generate() {
256
+ return this.generateOrResetCore(Date.now(), 10000);
257
+ }
258
+ /**
259
+ * Generates a new UUIDv7 object from the current timestamp, or returns
260
+ * `undefined` upon significant timestamp rollback.
261
+ *
262
+ * This method returns a monotonically increasing UUID by reusing the previous
263
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
264
+ * preceding UUID's. However, when such a clock rollback is considered
265
+ * significant (i.e., by more than ten seconds), this method aborts and
266
+ * returns `undefined` immediately.
267
+ *
268
+ * See {@link generate} for the other mode of generation and
269
+ * {@link generateOrAbortCore} for the low-level primitive.
270
+ */
271
+ generateOrAbort() {
272
+ return this.generateOrAbortCore(Date.now(), 10000);
273
+ }
274
+ /**
275
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
276
+ * generator upon significant timestamp rollback.
277
+ *
278
+ * This method is equivalent to {@link generate} except that it takes a custom
279
+ * timestamp and clock rollback allowance.
280
+ *
281
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
282
+ * considered significant. A suggested value is `10_000` (milliseconds).
283
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
284
+ */
285
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
286
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
287
+ if (value === undefined) {
288
+ // reset state and resume
289
+ this.timestamp = 0;
290
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
291
+ }
292
+ return value;
293
+ }
294
+ /**
295
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
296
+ * `undefined` upon significant timestamp rollback.
297
+ *
298
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
299
+ * custom timestamp and clock rollback allowance.
300
+ *
301
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
302
+ * considered significant. A suggested value is `10_000` (milliseconds).
303
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
304
+ */
305
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
306
+ const MAX_COUNTER = 4398046511103;
307
+ if (!Number.isInteger(unixTsMs) ||
308
+ unixTsMs < 1 ||
309
+ unixTsMs > 281474976710655) {
310
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
311
+ }
312
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
313
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
314
+ }
315
+ if (unixTsMs > this.timestamp) {
316
+ this.timestamp = unixTsMs;
317
+ this.resetCounter();
318
+ }
319
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
320
+ // go on with previous timestamp if new one is not much smaller
321
+ this.counter++;
322
+ if (this.counter > MAX_COUNTER) {
323
+ // increment timestamp at counter overflow
324
+ this.timestamp++;
325
+ this.resetCounter();
326
+ }
327
+ }
328
+ else {
329
+ // abort if clock went backwards to unbearable extent
330
+ return undefined;
331
+ }
332
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
333
+ }
334
+ /** Initializes the counter at a 42-bit random integer. */
335
+ resetCounter() {
336
+ this.counter =
337
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
338
+ }
339
+ /**
340
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
341
+ *
342
+ * @internal
343
+ */
344
+ generateV4() {
345
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
346
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
347
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
348
+ return UUID.ofInner(bytes);
349
+ }
350
+ }
351
+ /** Returns the default random number generator available in the environment. */
352
+ const getDefaultRandom = () => {
353
+ // detect Web Crypto API
354
+ if (typeof crypto !== "undefined" &&
355
+ typeof crypto.getRandomValues !== "undefined") {
356
+ return new BufferedCryptoRandom();
357
+ }
358
+ else {
359
+ // fall back on Math.random() unless the flag is set to true
360
+ if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
361
+ throw new Error("no cryptographically strong RNG available");
362
+ }
363
+ return {
364
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
365
+ Math.trunc(Math.random() * 65536),
366
+ };
367
+ }
368
+ };
369
+ /**
370
+ * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
371
+ * buffer by default to avoid both unbearable throughput decline in some
372
+ * environments and the waste of time and space for unused values.
373
+ */
374
+ class BufferedCryptoRandom {
375
+ constructor() {
376
+ this.buffer = new Uint32Array(8);
377
+ this.cursor = 0xffff;
378
+ }
379
+ nextUint32() {
380
+ if (this.cursor >= this.buffer.length) {
381
+ crypto.getRandomValues(this.buffer);
382
+ this.cursor = 0;
383
+ }
384
+ return this.buffer[this.cursor++];
385
+ }
386
+ }
387
+ let defaultGenerator;
388
+ /**
389
+ * Generates a UUIDv7 string.
390
+ *
391
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
392
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
393
+ */
394
+ const uuidv7 = () => uuidv7obj().toString();
395
+ /** Generates a UUIDv7 object. */
396
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
397
+ const generateUuidv7 = () => {
398
+ return uuidv7();
399
+ };
400
+ const getCurrentTimestamp = () => {
401
+ return new Date().toISOString();
402
+ };
403
+ const getCurrentUrl = () => {
404
+ if (typeof window !== 'undefined') {
405
+ return window.location.href;
406
+ }
407
+ return '';
408
+ };
409
+ const getPageTitle = () => {
410
+ if (typeof document !== 'undefined') {
411
+ return document.title;
412
+ }
413
+ return '';
414
+ };
415
+ const getReferrer = () => {
416
+ if (typeof document !== 'undefined') {
417
+ return document.referrer;
418
+ }
419
+ return '';
420
+ };
421
+ const isBrowser = () => {
422
+ return typeof window !== 'undefined';
423
+ };
424
+ const isNode = () => {
425
+ var _a;
426
+ return typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
427
+ };
428
+ const fetchRemoteOptions = async (apiHost, publishableKey, fetchFn) => {
429
+ const endpoint = '/v1/configs';
430
+ const url = `${apiHost}${endpoint}?ingestion_key=${encodeURIComponent(publishableKey)}`;
431
+ try {
432
+ let fetch = fetchFn;
433
+ if (!fetch) {
434
+ if (isNode()) {
435
+ // For Node.js environments, expect fetch to be passed in
436
+ throw new Error('Fetch function must be provided in Node.js environment');
437
+ }
438
+ else {
439
+ // Use native fetch in browser
440
+ fetch = window.fetch;
441
+ }
442
+ }
443
+ const response = await fetch(url, {
444
+ method: 'GET',
445
+ headers: {
446
+ 'Content-Type': 'application/json',
447
+ },
448
+ });
449
+ // if (!response.ok) {
450
+ // throw new Error(`Options fetch failed: ${response.status} ${response.statusText}`);
451
+ // }
452
+ const data = await response.json();
453
+ return data;
454
+ }
455
+ catch (error) {
456
+ console.warn('Failed to fetch remote options:', error);
457
+ return null;
458
+ }
459
+ };
460
+ const mergeOptions = (localOptions, remoteOptions) => {
461
+ if (!remoteOptions && !localOptions) {
462
+ return {};
463
+ }
464
+ if (!remoteOptions) {
465
+ return localOptions;
466
+ }
467
+ if (!localOptions) {
468
+ return remoteOptions;
469
+ }
470
+ // Deep merge local options into remote options
471
+ // Local options takes precedence over remote options
472
+ const merged = { ...remoteOptions };
473
+ // Handle primitive values
474
+ Object.keys(localOptions).forEach(key => {
475
+ const localValue = localOptions[key];
476
+ if (localValue !== undefined && localValue !== null) {
477
+ if (typeof localValue === 'object' && !Array.isArray(localValue)) {
478
+ // Deep merge objects - local options overrides remote
479
+ merged[key] = {
480
+ ...(merged[key] || {}),
481
+ ...localValue
482
+ };
483
+ }
484
+ else {
485
+ // Override primitive values and arrays with local options
486
+ merged[key] = localValue;
487
+ }
488
+ }
489
+ });
490
+ return merged;
491
+ };
492
+
493
+ const DEFAULT_SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes in ms
494
+ class BrowserIdentityManager {
495
+ constructor(sessionTimeout, publishableKey) {
496
+ this.identity = null;
497
+ this.sessionTimeout = DEFAULT_SESSION_TIMEOUT;
498
+ if (sessionTimeout) {
499
+ this.sessionTimeout = sessionTimeout;
500
+ }
501
+ // Generate storage key with publishableKey pattern: jrnm_<publishableKey>_journium
502
+ this.storageKey = publishableKey ? `jrnm_${publishableKey}_journium` : '__journium_identity';
503
+ this.loadOrCreateIdentity();
504
+ }
505
+ loadOrCreateIdentity() {
506
+ if (!this.isBrowser())
507
+ return;
508
+ try {
509
+ const stored = localStorage.getItem(this.storageKey);
510
+ if (stored) {
511
+ const parsedIdentity = JSON.parse(stored);
512
+ // Check if session is expired
513
+ const now = Date.now();
514
+ const sessionAge = now - parsedIdentity.session_timestamp;
515
+ if (sessionAge > this.sessionTimeout) {
516
+ // Session expired, create new session but keep device and distinct IDs
517
+ this.identity = {
518
+ distinct_id: parsedIdentity.distinct_id,
519
+ $device_id: parsedIdentity.$device_id,
520
+ $session_id: generateUuidv7(),
521
+ session_timestamp: now,
522
+ $user_state: parsedIdentity.$user_state || 'anonymous',
523
+ };
524
+ }
525
+ else {
526
+ // Session still valid
527
+ this.identity = parsedIdentity;
528
+ // Ensure $user_state exists for backward compatibility
529
+ if (!this.identity.$user_state) {
530
+ this.identity.$user_state = 'anonymous';
531
+ }
532
+ }
533
+ }
534
+ else {
535
+ // First time, create all new IDs
536
+ const newId = generateUuidv7();
537
+ this.identity = {
538
+ distinct_id: newId,
539
+ $device_id: newId,
540
+ $session_id: newId,
541
+ session_timestamp: Date.now(),
542
+ $user_state: 'anonymous',
543
+ };
544
+ }
545
+ // Save to localStorage
546
+ this.saveIdentity();
547
+ }
548
+ catch (error) {
549
+ console.warn('Journium: Failed to load/create identity:', error);
550
+ // Fallback: create temporary identity without localStorage
551
+ const newId = generateUuidv7();
552
+ this.identity = {
553
+ distinct_id: newId,
554
+ $device_id: newId,
555
+ $session_id: newId,
556
+ session_timestamp: Date.now(),
557
+ $user_state: 'anonymous',
558
+ };
559
+ }
560
+ }
561
+ saveIdentity() {
562
+ if (!this.isBrowser() || !this.identity)
563
+ return;
564
+ try {
565
+ localStorage.setItem(this.storageKey, JSON.stringify(this.identity));
566
+ }
567
+ catch (error) {
568
+ console.warn('Journium: Failed to save identity to localStorage:', error);
569
+ }
570
+ }
571
+ isBrowser() {
572
+ return typeof window !== 'undefined' && typeof localStorage !== 'undefined';
573
+ }
574
+ getIdentity() {
575
+ return this.identity;
576
+ }
577
+ updateSessionTimeout(timeoutMs) {
578
+ this.sessionTimeout = timeoutMs;
579
+ }
580
+ refreshSession() {
581
+ if (!this.identity)
582
+ return;
583
+ this.identity = {
584
+ ...this.identity,
585
+ $session_id: generateUuidv7(),
586
+ session_timestamp: Date.now(),
587
+ };
588
+ this.saveIdentity();
589
+ }
590
+ identify(distinctId, _attributes = {}) {
591
+ if (!this.identity)
592
+ return { previousDistinctId: null };
593
+ const previousDistinctId = this.identity.distinct_id;
594
+ // Update the distinct ID and mark user as identified
595
+ this.identity = {
596
+ ...this.identity,
597
+ distinct_id: distinctId,
598
+ $user_state: 'identified',
599
+ };
600
+ this.saveIdentity();
601
+ return { previousDistinctId };
602
+ }
603
+ reset() {
604
+ if (!this.identity)
605
+ return;
606
+ // Generate new distinct ID but keep device ID
607
+ this.identity = {
608
+ ...this.identity,
609
+ distinct_id: generateUuidv7(),
610
+ $user_state: 'anonymous',
611
+ };
612
+ this.saveIdentity();
613
+ }
614
+ getUserAgentInfo() {
615
+ if (!this.isBrowser()) {
616
+ return {
617
+ $raw_user_agent: '',
618
+ $browser: 'Unknown',
619
+ $os: 'Unknown',
620
+ $device_type: 'Unknown',
621
+ };
622
+ }
623
+ const userAgent = navigator.userAgent;
624
+ return {
625
+ $raw_user_agent: userAgent,
626
+ $browser: this.parseBrowser(userAgent),
627
+ $os: this.parseOS(userAgent),
628
+ $device_type: this.parseDeviceType(userAgent),
629
+ };
630
+ }
631
+ parseBrowser(userAgent) {
632
+ if (userAgent.includes('Chrome') && !userAgent.includes('Edg'))
633
+ return 'Chrome';
634
+ if (userAgent.includes('Firefox'))
635
+ return 'Firefox';
636
+ if (userAgent.includes('Safari') && !userAgent.includes('Chrome'))
637
+ return 'Safari';
638
+ if (userAgent.includes('Edg'))
639
+ return 'Edge';
640
+ if (userAgent.includes('Opera') || userAgent.includes('OPR'))
641
+ return 'Opera';
642
+ return 'Unknown';
643
+ }
644
+ parseOS(userAgent) {
645
+ if (userAgent.includes('Windows'))
646
+ return 'Windows';
647
+ if (userAgent.includes('Macintosh') || userAgent.includes('Mac OS'))
648
+ return 'Mac OS';
649
+ if (userAgent.includes('Linux'))
650
+ return 'Linux';
651
+ if (userAgent.includes('Android'))
652
+ return 'Android';
653
+ if (userAgent.includes('iPhone') || userAgent.includes('iPad'))
654
+ return 'iOS';
655
+ return 'Unknown';
656
+ }
657
+ parseDeviceType(userAgent) {
658
+ if (userAgent.includes('Mobile') || userAgent.includes('Android') || userAgent.includes('iPhone')) {
659
+ return 'Mobile';
660
+ }
661
+ if (userAgent.includes('iPad') || userAgent.includes('Tablet')) {
662
+ return 'Tablet';
663
+ }
664
+ return 'Desktop';
665
+ }
666
+ }
667
+
668
+ class Logger {
669
+ static setDebug(enabled) {
670
+ this.isDebugEnabled = enabled;
671
+ }
672
+ static isDebug() {
673
+ return this.isDebugEnabled;
674
+ }
675
+ static log(...args) {
676
+ if (this.isDebugEnabled) {
677
+ console.log(...args);
678
+ }
679
+ }
680
+ static warn(...args) {
681
+ if (this.isDebugEnabled) {
682
+ console.warn(...args);
683
+ }
684
+ }
685
+ static error(...args) {
686
+ if (this.isDebugEnabled) {
687
+ console.error(...args);
688
+ }
689
+ }
690
+ static info(...args) {
691
+ if (this.isDebugEnabled) {
692
+ console.info(...args);
693
+ }
694
+ }
695
+ }
696
+ Logger.isDebugEnabled = false;
697
+
698
+ class JourniumClient {
699
+ constructor(config) {
700
+ var _a, _b, _c, _d;
701
+ this.queue = [];
702
+ this.stagedEvents = [];
703
+ this.flushTimer = null;
704
+ this.initializationComplete = false;
705
+ this.initializationFailed = false;
706
+ this.optionsChangeCallbacks = new Set();
707
+ // Validate required configuration
708
+ if (!config.publishableKey || config.publishableKey.trim() === '') {
709
+ // Reject initialization with clear error
710
+ const errorMsg = 'Journium: publishableKey is required but not provided or is empty. SDK cannot be initialized.';
711
+ Logger.setDebug(true);
712
+ Logger.error(errorMsg);
713
+ throw new Error(errorMsg);
714
+ }
715
+ // Set default apiHost if not provided
716
+ this.config = {
717
+ ...config,
718
+ apiHost: config.apiHost || 'https://events.journium.app'
719
+ };
720
+ // Generate storage key for options caching
721
+ this.optionsStorageKey = `jrnm_${config.publishableKey}_options`;
722
+ // Initialize with minimal defaults for identity manager
723
+ const fallbackSessionTimeout = 30 * 60 * 1000; // 30 minutes
724
+ this.effectiveOptions = {}; // Will be set after remote config
725
+ // Initialize Logger with local debug setting or false
726
+ Logger.setDebug((_b = (_a = this.config.options) === null || _a === void 0 ? void 0 : _a.debug) !== null && _b !== void 0 ? _b : false);
727
+ // Initialize identity manager with fallback timeout
728
+ this.identityManager = new BrowserIdentityManager((_d = (_c = this.config.options) === null || _c === void 0 ? void 0 : _c.sessionTimeout) !== null && _d !== void 0 ? _d : fallbackSessionTimeout, this.config.publishableKey);
729
+ // Initialize asynchronously - wait for remote config first
730
+ this.initializeAsync();
731
+ }
732
+ loadCachedOptions() {
733
+ if (typeof window === 'undefined' || !window.localStorage) {
734
+ return null;
735
+ }
736
+ try {
737
+ const cached = window.localStorage.getItem(this.optionsStorageKey);
738
+ return cached ? JSON.parse(cached) : null;
739
+ }
740
+ catch (error) {
741
+ Logger.warn('Journium: Failed to load cached config:', error);
742
+ return null;
743
+ }
744
+ }
745
+ saveCachedOptions(options) {
746
+ if (typeof window === 'undefined' || !window.localStorage) {
747
+ return;
748
+ }
749
+ try {
750
+ window.localStorage.setItem(this.optionsStorageKey, JSON.stringify(options));
751
+ }
752
+ catch (error) {
753
+ Logger.warn('Journium: Failed to save config to cache:', error);
754
+ }
755
+ }
756
+ async initializeAsync() {
757
+ var _a;
758
+ try {
759
+ Logger.log('Journium: Starting initialization - fetching fresh remote config...');
760
+ // Step 1: Try to fetch fresh remote config with timeout and retry
761
+ const remoteOptions = await this.fetchRemoteOptionsWithRetry();
762
+ if (remoteOptions) {
763
+ // Step 2: Cache the fresh remote config
764
+ this.saveCachedOptions(remoteOptions);
765
+ // Step 3: Merge local options over remote config (local overrides remote)
766
+ if (this.config.options) {
767
+ this.effectiveOptions = mergeOptions(this.config.options, remoteOptions);
768
+ Logger.log('Journium: Using fresh remote config merged with local options:', this.effectiveOptions);
769
+ }
770
+ else {
771
+ this.effectiveOptions = remoteOptions;
772
+ Logger.log('Journium: Using fresh remote config:', this.effectiveOptions);
773
+ }
774
+ }
775
+ else {
776
+ // Step 4: Fallback to cached config if fresh fetch failed
777
+ /* const cachedRemoteOptions = this.loadCachedOptions();
778
+
779
+ if (cachedRemoteOptions) {
780
+ if (this.config.options) {
781
+ this.effectiveOptions = mergeOptions(this.config.options, cachedRemoteOptions);
782
+ Logger.log('Journium: Fresh config failed, using cached remote config merged with local options:', this.effectiveOptions);
783
+ } else {
784
+ this.effectiveOptions = cachedRemoteOptions;
785
+ Logger.log('Journium: Fresh config failed, using cached remote config:', this.effectiveOptions);
786
+ }
787
+ } else {
788
+ // Step 5: No remote config and no cached config - initialization fails
789
+ Logger.error('Journium: Initialization failed - no remote config available and no cached config found');
790
+ this.initializationFailed = true;
791
+ this.initializationComplete = false;
792
+ return;
793
+ } */
794
+ }
795
+ // Step 6: Update identity manager session timeout if provided
796
+ if (this.effectiveOptions.sessionTimeout) {
797
+ this.identityManager.updateSessionTimeout(this.effectiveOptions.sessionTimeout);
798
+ }
799
+ // Step 7: Update Logger debug setting
800
+ Logger.setDebug((_a = this.effectiveOptions.debug) !== null && _a !== void 0 ? _a : false);
801
+ // Step 8: Mark initialization as complete
802
+ this.initializationComplete = true;
803
+ this.initializationFailed = false;
804
+ // Step 9: Process any staged events
805
+ this.processStagedEvents();
806
+ // Step 10: Start flush timer
807
+ if (this.effectiveOptions.flushInterval && this.effectiveOptions.flushInterval > 0) {
808
+ this.startFlushTimer();
809
+ }
810
+ Logger.log('Journium: Initialization complete with options:', this.effectiveOptions);
811
+ // Step 11: Notify callbacks about options
812
+ this.notifyOptionsChange();
813
+ }
814
+ catch (error) {
815
+ Logger.error('Journium: Initialization failed:', error);
816
+ this.initializationFailed = true;
817
+ this.initializationComplete = false;
818
+ }
819
+ }
820
+ async fetchRemoteOptionsWithRetry() {
821
+ const maxRetries = 2;
822
+ const timeoutMs = 15000; // 15 seconds
823
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
824
+ try {
825
+ Logger.log(`Journium: Fetching remote config (attempt ${attempt}/${maxRetries})...`);
826
+ // Create timeout promise
827
+ const timeoutPromise = new Promise((_, reject) => {
828
+ setTimeout(() => reject(new Error('Timeout')), timeoutMs);
829
+ });
830
+ // Race fetch against timeout
831
+ const fetchPromise = fetchRemoteOptions(this.config.apiHost, this.config.publishableKey);
832
+ const remoteOptionsResponse = await Promise.race([fetchPromise, timeoutPromise]);
833
+ if (remoteOptionsResponse && remoteOptionsResponse.status === 'success') {
834
+ Logger.log('Journium: Successfully fetched fresh remote config:', remoteOptionsResponse.config);
835
+ return remoteOptionsResponse.config || null;
836
+ }
837
+ else if (remoteOptionsResponse && remoteOptionsResponse.status === 'error' && remoteOptionsResponse.errorCode === 'J_ERR_TENANT_NOT_FOUND') {
838
+ Logger.error('Journium: Invalid publishableKey is being used.');
839
+ return null;
840
+ }
841
+ {
842
+ throw new Error('Remote config fetch unsuccessful');
843
+ }
844
+ }
845
+ catch (error) {
846
+ Logger.warn(`Journium: Remote config fetch attempt ${attempt} failed:`, error);
847
+ if (attempt === maxRetries) {
848
+ Logger.warn('Journium: All remote config fetch attempts failed, falling back to cached config');
849
+ return null;
850
+ }
851
+ // Wait 1 second before retry (except on last attempt)
852
+ if (attempt < maxRetries) {
853
+ await new Promise(resolve => setTimeout(resolve, 1000));
854
+ }
855
+ }
856
+ }
857
+ return null;
858
+ }
859
+ /**
860
+ * Register a callback to be notified when effective options change (e.g., when remote options are fetched)
861
+ */
862
+ onOptionsChange(callback) {
863
+ this.optionsChangeCallbacks.add(callback);
864
+ // Return unsubscribe function
865
+ return () => {
866
+ this.optionsChangeCallbacks.delete(callback);
867
+ };
868
+ }
869
+ notifyOptionsChange() {
870
+ this.optionsChangeCallbacks.forEach(callback => {
871
+ try {
872
+ callback(this.effectiveOptions);
873
+ }
874
+ catch (error) {
875
+ Logger.warn('Journium: Error in options change callback:', error);
876
+ }
877
+ });
878
+ }
879
+ processStagedEvents() {
880
+ if (this.stagedEvents.length === 0)
881
+ return;
882
+ Logger.log(`Journium: Processing ${this.stagedEvents.length} staged events`);
883
+ // Move staged events to main queue, adding identity properties now
884
+ const identity = this.identityManager.getIdentity();
885
+ const userAgentInfo = this.identityManager.getUserAgentInfo();
886
+ for (const stagedEvent of this.stagedEvents) {
887
+ // Add identity properties that weren't available during staging
888
+ const eventWithIdentity = {
889
+ ...stagedEvent,
890
+ properties: {
891
+ $device_id: identity === null || identity === void 0 ? void 0 : identity.$device_id,
892
+ distinct_id: identity === null || identity === void 0 ? void 0 : identity.distinct_id,
893
+ $session_id: identity === null || identity === void 0 ? void 0 : identity.$session_id,
894
+ $is_identified: (identity === null || identity === void 0 ? void 0 : identity.$user_state) === 'identified',
895
+ $current_url: typeof window !== 'undefined' ? window.location.href : '',
896
+ $pathname: typeof window !== 'undefined' ? window.location.pathname : '',
897
+ ...userAgentInfo,
898
+ $lib_version: '0.1.0', // TODO: Get from package.json
899
+ $platform: 'web',
900
+ ...stagedEvent.properties, // Original properties override system properties
901
+ },
902
+ };
903
+ this.queue.push(eventWithIdentity);
904
+ }
905
+ // Clear staged events
906
+ this.stagedEvents = [];
907
+ Logger.log('Journium: Staged events processed and moved to main queue');
908
+ // Check if we should flush immediately
909
+ if (this.queue.length >= this.effectiveOptions.flushAt) {
910
+ // console.log('1 Journium: Flushing events...'+JSON.stringify(this.effectiveOptions));
911
+ this.flush();
912
+ }
913
+ }
914
+ startFlushTimer() {
915
+ if (this.flushTimer) {
916
+ clearInterval(this.flushTimer);
917
+ }
918
+ // Use universal setInterval (works in both browser and Node.js)
919
+ this.flushTimer = setInterval(() => {
920
+ // console.log('2 Journium: Flushing events...'+JSON.stringify(this.effectiveOptions));
921
+ this.flush();
922
+ }, this.effectiveOptions.flushInterval);
923
+ }
924
+ async sendEvents(events) {
925
+ if (!events.length)
926
+ return;
927
+ try {
928
+ const response = await fetch(`${this.config.apiHost}/v1/ingest_event`, {
929
+ method: 'POST',
930
+ headers: {
931
+ 'Content-Type': 'application/json',
932
+ 'Authorization': `Bearer ${this.config.publishableKey}`,
933
+ },
934
+ body: JSON.stringify({
935
+ events,
936
+ }),
937
+ });
938
+ if (!response.ok) {
939
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
940
+ }
941
+ Logger.log('Journium: Successfully sent events', events);
942
+ }
943
+ catch (error) {
944
+ Logger.error('Journium: Failed to send events', error);
945
+ throw error;
946
+ }
947
+ }
948
+ identify(distinctId, attributes = {}) {
949
+ // Don't identify if initialization failed
950
+ if (this.initializationFailed) {
951
+ Logger.warn('Journium: identify() call rejected - initialization failed');
952
+ return;
953
+ }
954
+ // Call identify on identity manager to get previous distinct ID
955
+ const { previousDistinctId } = this.identityManager.identify(distinctId, attributes);
956
+ // Track $identify event with previous distinct ID
957
+ const identifyProperties = {
958
+ ...attributes,
959
+ $anon_distinct_id: previousDistinctId,
960
+ };
961
+ this.track('$identify', identifyProperties);
962
+ Logger.log('Journium: User identified', { distinctId, attributes, previousDistinctId });
963
+ }
964
+ reset() {
965
+ // Don't reset if initialization failed
966
+ if (this.initializationFailed) {
967
+ Logger.warn('Journium: reset() call rejected - initialization failed');
968
+ return;
969
+ }
970
+ // Reset identity in identity manager
971
+ this.identityManager.reset();
972
+ Logger.log('Journium: User identity reset');
973
+ }
974
+ track(event, properties = {}) {
975
+ // Create minimal event without identity properties (will be added later if staging)
976
+ const journiumEvent = {
977
+ uuid: generateUuidv7(),
978
+ ingestion_key: this.config.publishableKey,
979
+ client_timestamp: getCurrentTimestamp(),
980
+ event,
981
+ properties: { ...properties }, // Only user properties for now
982
+ };
983
+ // Stage events during initialization, add to queue after initialization
984
+ if (!this.initializationComplete) {
985
+ // If initialization failed, reject events
986
+ if (this.initializationFailed) {
987
+ Logger.warn('Journium: track() call rejected - initialization failed');
988
+ return;
989
+ }
990
+ this.stagedEvents.push(journiumEvent);
991
+ Logger.log('Journium: Event staged during initialization', journiumEvent);
992
+ return;
993
+ }
994
+ // If initialization failed, reject events
995
+ if (this.initializationFailed) {
996
+ Logger.warn('Journium: track() call rejected - initialization failed');
997
+ return;
998
+ }
999
+ // Add identity properties for immediate events (after initialization)
1000
+ const identity = this.identityManager.getIdentity();
1001
+ const userAgentInfo = this.identityManager.getUserAgentInfo();
1002
+ const eventWithIdentity = {
1003
+ ...journiumEvent,
1004
+ properties: {
1005
+ $device_id: identity === null || identity === void 0 ? void 0 : identity.$device_id,
1006
+ distinct_id: identity === null || identity === void 0 ? void 0 : identity.distinct_id,
1007
+ $session_id: identity === null || identity === void 0 ? void 0 : identity.$session_id,
1008
+ $is_identified: (identity === null || identity === void 0 ? void 0 : identity.$user_state) === 'identified',
1009
+ $current_url: typeof window !== 'undefined' ? window.location.href : '',
1010
+ $pathname: typeof window !== 'undefined' ? window.location.pathname : '',
1011
+ ...userAgentInfo,
1012
+ $lib_version: '0.1.0', // TODO: Get from package.json
1013
+ $platform: 'web',
1014
+ ...properties, // User-provided properties override system properties
1015
+ },
1016
+ };
1017
+ this.queue.push(eventWithIdentity);
1018
+ Logger.log('Journium: Event tracked', eventWithIdentity);
1019
+ // Only flush if we have effective options (after initialization)
1020
+ if (this.effectiveOptions.flushAt && this.queue.length >= this.effectiveOptions.flushAt) {
1021
+ // console.log('3 Journium: Flushing events...'+JSON.stringify(this.effectiveOptions));
1022
+ this.flush();
1023
+ }
1024
+ }
1025
+ async flush() {
1026
+ // Don't flush if initialization failed
1027
+ if (this.initializationFailed) {
1028
+ Logger.warn('Journium: flush() call rejected - initialization failed');
1029
+ return;
1030
+ }
1031
+ if (this.queue.length === 0)
1032
+ return;
1033
+ const events = [...this.queue];
1034
+ this.queue = [];
1035
+ try {
1036
+ await this.sendEvents(events);
1037
+ }
1038
+ catch (error) {
1039
+ this.queue.unshift(...events);
1040
+ throw error;
1041
+ }
1042
+ }
1043
+ destroy() {
1044
+ if (this.flushTimer) {
1045
+ clearInterval(this.flushTimer);
1046
+ this.flushTimer = null;
1047
+ }
1048
+ this.flush();
1049
+ }
1050
+ getEffectiveOptions() {
1051
+ return this.effectiveOptions;
1052
+ }
1053
+ }
1054
+
1055
+ class PageviewTracker {
1056
+ constructor(client) {
1057
+ this.lastUrl = '';
1058
+ this.originalPushState = null;
1059
+ this.originalReplaceState = null;
1060
+ this.popStateHandler = null;
1061
+ this.client = client;
1062
+ }
1063
+ capturePageview(customProperties = {}) {
1064
+ const currentUrl = getCurrentUrl();
1065
+ const url = new URL(currentUrl);
1066
+ const properties = {
1067
+ $current_url: currentUrl,
1068
+ $host: url.host,
1069
+ $pathname: url.pathname,
1070
+ $search: url.search,
1071
+ $title: getPageTitle(),
1072
+ $referrer: getReferrer(),
1073
+ ...customProperties,
1074
+ };
1075
+ this.client.track('$pageview', properties);
1076
+ this.lastUrl = currentUrl;
1077
+ }
1078
+ /**
1079
+ * Start automatic autocapture for pageviews
1080
+ * @returns void
1081
+ */
1082
+ startAutoPageviewTracking() {
1083
+ this.capturePageview();
1084
+ if (typeof window !== 'undefined') {
1085
+ // Store original methods for cleanup
1086
+ this.originalPushState = window.history.pushState;
1087
+ this.originalReplaceState = window.history.replaceState;
1088
+ window.history.pushState = (...args) => {
1089
+ this.originalPushState.apply(window.history, args);
1090
+ setTimeout(() => this.capturePageview(), 0);
1091
+ };
1092
+ window.history.replaceState = (...args) => {
1093
+ this.originalReplaceState.apply(window.history, args);
1094
+ setTimeout(() => this.capturePageview(), 0);
1095
+ };
1096
+ this.popStateHandler = () => {
1097
+ setTimeout(() => this.capturePageview(), 0);
1098
+ };
1099
+ window.addEventListener('popstate', this.popStateHandler);
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Stop automatic autocapture for pageviews
1104
+ * @returns void
1105
+ */
1106
+ stopAutocapture() {
1107
+ if (typeof window !== 'undefined') {
1108
+ // Restore original methods
1109
+ if (this.originalPushState) {
1110
+ window.history.pushState = this.originalPushState;
1111
+ this.originalPushState = null;
1112
+ }
1113
+ if (this.originalReplaceState) {
1114
+ window.history.replaceState = this.originalReplaceState;
1115
+ this.originalReplaceState = null;
1116
+ }
1117
+ if (this.popStateHandler) {
1118
+ window.removeEventListener('popstate', this.popStateHandler);
1119
+ this.popStateHandler = null;
1120
+ }
1121
+ }
1122
+ }
1123
+ }
1124
+
1125
+ /**
1126
+ * AutocaptureTracker is responsible for tracking user interactions and capturing them as events.
1127
+ */
1128
+ class AutocaptureTracker {
1129
+ constructor(client, options = {}) {
1130
+ this.listeners = new Map();
1131
+ this.isActive = false;
1132
+ this.client = client;
1133
+ this.options = {
1134
+ captureClicks: true,
1135
+ captureFormSubmits: true,
1136
+ captureFormChanges: true,
1137
+ captureTextSelection: false,
1138
+ ignoreClasses: ['journium-ignore'],
1139
+ ignoreElements: ['script', 'style', 'noscript'],
1140
+ captureContentText: true,
1141
+ ...options,
1142
+ };
1143
+ }
1144
+ /**
1145
+ * Update autocapture options and restart if currently active
1146
+ */
1147
+ updateOptions(options) {
1148
+ const wasActive = this.isActive;
1149
+ // Stop if currently active
1150
+ if (wasActive) {
1151
+ this.stop();
1152
+ }
1153
+ // Update options
1154
+ this.options = {
1155
+ captureClicks: true,
1156
+ captureFormSubmits: true,
1157
+ captureFormChanges: true,
1158
+ captureTextSelection: false,
1159
+ ignoreClasses: ['journium-ignore'],
1160
+ ignoreElements: ['script', 'style', 'noscript'],
1161
+ captureContentText: true,
1162
+ ...options,
1163
+ };
1164
+ // Restart if it was active before
1165
+ if (wasActive) {
1166
+ this.start();
1167
+ }
1168
+ }
1169
+ start() {
1170
+ if (!isBrowser() || this.isActive) {
1171
+ return;
1172
+ }
1173
+ this.isActive = true;
1174
+ if (this.options.captureClicks) {
1175
+ this.addClickListener();
1176
+ }
1177
+ if (this.options.captureFormSubmits) {
1178
+ this.addFormSubmitListener();
1179
+ }
1180
+ if (this.options.captureFormChanges) {
1181
+ this.addFormChangeListener();
1182
+ }
1183
+ if (this.options.captureTextSelection) {
1184
+ this.addTextSelectionListener();
1185
+ }
1186
+ }
1187
+ stop() {
1188
+ if (!isBrowser() || !this.isActive) {
1189
+ return;
1190
+ }
1191
+ this.isActive = false;
1192
+ this.listeners.forEach((listener, event) => {
1193
+ document.removeEventListener(event, listener, true);
1194
+ });
1195
+ this.listeners.clear();
1196
+ }
1197
+ addClickListener() {
1198
+ const clickListener = (event) => {
1199
+ const target = event.target;
1200
+ if (this.shouldIgnoreElement(target)) {
1201
+ return;
1202
+ }
1203
+ const properties = this.getElementProperties(target, 'click');
1204
+ this.client.track('$autocapture', {
1205
+ $event_type: 'click',
1206
+ ...properties,
1207
+ });
1208
+ };
1209
+ document.addEventListener('click', clickListener, true);
1210
+ this.listeners.set('click', clickListener);
1211
+ }
1212
+ addFormSubmitListener() {
1213
+ const submitListener = (event) => {
1214
+ const target = event.target;
1215
+ if (this.shouldIgnoreElement(target)) {
1216
+ return;
1217
+ }
1218
+ const properties = this.getFormProperties(target, 'submit');
1219
+ this.client.track('$autocapture', {
1220
+ $event_type: 'submit',
1221
+ ...properties,
1222
+ });
1223
+ };
1224
+ document.addEventListener('submit', submitListener, true);
1225
+ this.listeners.set('submit', submitListener);
1226
+ }
1227
+ addFormChangeListener() {
1228
+ const changeListener = (event) => {
1229
+ const target = event.target;
1230
+ if (this.shouldIgnoreElement(target) || !this.isFormElement(target)) {
1231
+ return;
1232
+ }
1233
+ const properties = this.getInputProperties(target, 'change');
1234
+ this.client.track('$autocapture', {
1235
+ $event_type: 'change',
1236
+ ...properties,
1237
+ });
1238
+ };
1239
+ document.addEventListener('change', changeListener, true);
1240
+ this.listeners.set('change', changeListener);
1241
+ }
1242
+ addTextSelectionListener() {
1243
+ const selectionListener = () => {
1244
+ const selection = window.getSelection();
1245
+ if (!selection || selection.toString().trim().length === 0) {
1246
+ return;
1247
+ }
1248
+ const selectedText = selection.toString().trim();
1249
+ if (selectedText.length < 3) { // Ignore very short selections
1250
+ return;
1251
+ }
1252
+ this.client.track('$autocapture', {
1253
+ $event_type: 'text_selection',
1254
+ $selected_text: selectedText.substring(0, 200), // Limit text length
1255
+ $selection_length: selectedText.length,
1256
+ });
1257
+ };
1258
+ document.addEventListener('mouseup', selectionListener);
1259
+ this.listeners.set('mouseup', selectionListener);
1260
+ }
1261
+ shouldIgnoreElement(element) {
1262
+ var _a, _b, _c;
1263
+ if (!element || !element.tagName) {
1264
+ return true;
1265
+ }
1266
+ // Check if element should be ignored by tag name
1267
+ if ((_a = this.options.ignoreElements) === null || _a === void 0 ? void 0 : _a.includes(element.tagName.toLowerCase())) {
1268
+ return true;
1269
+ }
1270
+ // Check if element has ignore classes
1271
+ if ((_b = this.options.ignoreClasses) === null || _b === void 0 ? void 0 : _b.some(cls => element.classList.contains(cls))) {
1272
+ return true;
1273
+ }
1274
+ // Check parent elements for ignore classes
1275
+ let parent = element.parentElement;
1276
+ while (parent) {
1277
+ if ((_c = this.options.ignoreClasses) === null || _c === void 0 ? void 0 : _c.some(cls => parent.classList.contains(cls))) {
1278
+ return true;
1279
+ }
1280
+ parent = parent.parentElement;
1281
+ }
1282
+ return false;
1283
+ }
1284
+ isFormElement(element) {
1285
+ const formElements = ['input', 'select', 'textarea'];
1286
+ return formElements.includes(element.tagName.toLowerCase());
1287
+ }
1288
+ getElementProperties(element, eventType) {
1289
+ const properties = {
1290
+ $element_tag: element.tagName.toLowerCase(),
1291
+ $element_type: this.getElementType(element),
1292
+ };
1293
+ // Element identifiers
1294
+ if (element.id) {
1295
+ properties.$element_id = element.id;
1296
+ }
1297
+ if (element.className) {
1298
+ properties.$element_classes = Array.from(element.classList);
1299
+ }
1300
+ // Element attributes
1301
+ const relevantAttributes = ['name', 'role', 'aria-label', 'data-testid', 'data-track'];
1302
+ relevantAttributes.forEach(attr => {
1303
+ const value = element.getAttribute(attr);
1304
+ if (value) {
1305
+ properties[`$element_${attr.replace('-', '_')}`] = value;
1306
+ }
1307
+ });
1308
+ // Element content
1309
+ if (this.options.captureContentText) {
1310
+ const text = this.getElementText(element);
1311
+ if (text) {
1312
+ properties.$element_text = text.substring(0, 200); // Limit text length
1313
+ }
1314
+ }
1315
+ // Elements chain data
1316
+ const elementsChain = this.getElementsChain(element);
1317
+ properties.$elements_chain = elementsChain.chain;
1318
+ properties.$elements_chain_href = elementsChain.href;
1319
+ properties.$elements_chain_elements = elementsChain.elements;
1320
+ properties.$elements_chain_texts = elementsChain.texts;
1321
+ properties.$elements_chain_ids = elementsChain.ids;
1322
+ // Position information
1323
+ const rect = element.getBoundingClientRect();
1324
+ properties.$element_position = {
1325
+ x: Math.round(rect.left),
1326
+ y: Math.round(rect.top),
1327
+ width: Math.round(rect.width),
1328
+ height: Math.round(rect.height),
1329
+ };
1330
+ // Parent information
1331
+ if (element.parentElement) {
1332
+ properties.$parent_tag = element.parentElement.tagName.toLowerCase();
1333
+ if (element.parentElement.id) {
1334
+ properties.$parent_id = element.parentElement.id;
1335
+ }
1336
+ }
1337
+ // URL information
1338
+ properties.$current_url = window.location.href;
1339
+ properties.$host = window.location.host;
1340
+ properties.$pathname = window.location.pathname;
1341
+ return properties;
1342
+ }
1343
+ getFormProperties(form, eventType) {
1344
+ const properties = this.getElementProperties(form, eventType);
1345
+ // Form-specific properties
1346
+ properties.$form_method = form.method || 'get';
1347
+ properties.$form_action = form.action || '';
1348
+ // Count form elements
1349
+ const inputs = form.querySelectorAll('input, select, textarea');
1350
+ properties.$form_elements_count = inputs.length;
1351
+ // Form element types
1352
+ const elementTypes = {};
1353
+ inputs.forEach(input => {
1354
+ const type = this.getElementType(input);
1355
+ elementTypes[type] = (elementTypes[type] || 0) + 1;
1356
+ });
1357
+ properties.$form_element_types = elementTypes;
1358
+ return properties;
1359
+ }
1360
+ getInputProperties(input, eventType) {
1361
+ const properties = this.getElementProperties(input, eventType);
1362
+ // Input-specific properties
1363
+ properties.$input_type = input.type || 'text';
1364
+ if (input.name) {
1365
+ properties.$input_name = input.name;
1366
+ }
1367
+ if (input.placeholder) {
1368
+ properties.$input_placeholder = input.placeholder;
1369
+ }
1370
+ // Value information (be careful with sensitive data)
1371
+ if (this.isSafeInputType(input.type)) {
1372
+ if (input.type === 'checkbox' || input.type === 'radio') {
1373
+ properties.$input_checked = input.checked;
1374
+ }
1375
+ else if (input.value) {
1376
+ // For safe inputs, capture value length and basic characteristics
1377
+ properties.$input_value_length = input.value.length;
1378
+ properties.$input_has_value = input.value.length > 0;
1379
+ // For select elements, capture the selected value
1380
+ if (input.tagName.toLowerCase() === 'select') {
1381
+ properties.$input_selected_value = input.value;
1382
+ }
1383
+ }
1384
+ }
1385
+ // Form context
1386
+ const form = input.closest('form');
1387
+ if (form && form.id) {
1388
+ properties.$form_id = form.id;
1389
+ }
1390
+ return properties;
1391
+ }
1392
+ getElementType(element) {
1393
+ const tag = element.tagName.toLowerCase();
1394
+ if (tag === 'input') {
1395
+ return element.type || 'text';
1396
+ }
1397
+ if (tag === 'button') {
1398
+ return element.type || 'button';
1399
+ }
1400
+ return tag;
1401
+ }
1402
+ getElementText(element) {
1403
+ var _a, _b;
1404
+ // For buttons and links, get the visible text
1405
+ if (['button', 'a'].includes(element.tagName.toLowerCase())) {
1406
+ return ((_a = element.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1407
+ }
1408
+ // For inputs, get placeholder or label
1409
+ if (element.tagName.toLowerCase() === 'input') {
1410
+ const input = element;
1411
+ return input.placeholder || input.value || '';
1412
+ }
1413
+ // For other elements, get text content but limit it
1414
+ const text = ((_b = element.textContent) === null || _b === void 0 ? void 0 : _b.trim()) || '';
1415
+ return text.length > 50 ? text.substring(0, 47) + '...' : text;
1416
+ }
1417
+ getElementsChain(element) {
1418
+ var _a;
1419
+ const elements = [];
1420
+ const texts = [];
1421
+ const ids = [];
1422
+ let href = '';
1423
+ let current = element;
1424
+ while (current && current !== document.body) {
1425
+ // Element selector
1426
+ let selector = current.tagName.toLowerCase();
1427
+ // Add ID if present
1428
+ if (current.id) {
1429
+ selector += `#${current.id}`;
1430
+ ids.push(current.id);
1431
+ }
1432
+ else {
1433
+ ids.push('');
1434
+ }
1435
+ // Add classes if present
1436
+ if (current.className && typeof current.className === 'string') {
1437
+ const classes = current.className.trim().split(/\s+/).slice(0, 3); // Limit to first 3 classes
1438
+ if (classes.length > 0 && classes[0] !== '') {
1439
+ selector += '.' + classes.join('.');
1440
+ }
1441
+ }
1442
+ // Add nth-child if no ID (to make selector more specific)
1443
+ if (!current.id && current.parentElement) {
1444
+ const siblings = Array.from(current.parentElement.children)
1445
+ .filter(child => child.tagName === current.tagName);
1446
+ if (siblings.length > 1) {
1447
+ const index = siblings.indexOf(current) + 1;
1448
+ selector += `:nth-child(${index})`;
1449
+ }
1450
+ }
1451
+ elements.push(selector);
1452
+ // Extract text content
1453
+ let text = '';
1454
+ if (current.tagName.toLowerCase() === 'a') {
1455
+ text = ((_a = current.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1456
+ // Capture href for links
1457
+ if (!href && current.getAttribute('href')) {
1458
+ href = current.getAttribute('href') || '';
1459
+ }
1460
+ }
1461
+ else if (['button', 'span', 'div'].includes(current.tagName.toLowerCase())) {
1462
+ // For buttons and text elements, get direct text content (not including children)
1463
+ const directText = Array.from(current.childNodes)
1464
+ .filter(node => node.nodeType === Node.TEXT_NODE)
1465
+ .map(node => { var _a; return (_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim(); })
1466
+ .join(' ')
1467
+ .trim();
1468
+ text = directText || '';
1469
+ }
1470
+ else if (current.tagName.toLowerCase() === 'input') {
1471
+ const input = current;
1472
+ text = input.placeholder || input.value || '';
1473
+ }
1474
+ // Limit text length and clean it
1475
+ text = text.substring(0, 100).replace(/\s+/g, ' ').trim();
1476
+ texts.push(text);
1477
+ current = current.parentElement;
1478
+ }
1479
+ // Build the chain string (reverse order so it goes from parent to child)
1480
+ const chain = elements.reverse().join(' > ');
1481
+ return {
1482
+ chain,
1483
+ href,
1484
+ elements: elements,
1485
+ texts: texts.reverse(),
1486
+ ids: ids.reverse()
1487
+ };
1488
+ }
1489
+ isSafeInputType(type) {
1490
+ // Don't capture values for sensitive input types
1491
+ const sensitiveTypes = ['password', 'email', 'tel', 'credit-card-number'];
1492
+ return !sensitiveTypes.includes(type.toLowerCase());
1493
+ }
1494
+ }
1495
+
1496
+ class JourniumAnalytics {
1497
+ constructor(config) {
1498
+ this.autocaptureStarted = false;
1499
+ this.config = config;
1500
+ this.client = new JourniumClient(config);
1501
+ this.pageviewTracker = new PageviewTracker(this.client);
1502
+ // Initialize autocapture tracker with effective options (may include cached remote options)
1503
+ // This ensures we use the correct initial state even if cached remote options exist
1504
+ const initialEffectiveOptions = this.client.getEffectiveOptions();
1505
+ const initialAutocaptureOptions = this.resolveAutocaptureOptions(initialEffectiveOptions.autocapture);
1506
+ this.autocaptureTracker = new AutocaptureTracker(this.client, initialAutocaptureOptions);
1507
+ // Listen for options changes (e.g., when fresh remote options are fetched)
1508
+ this.unsubscribeOptionsChange = this.client.onOptionsChange((effectiveOptions) => {
1509
+ this.handleOptionsChange(effectiveOptions);
1510
+ });
1511
+ // Start automatic autocapture immediately if initial options support it
1512
+ // This handles cached remote options or local options with autocapture enabled
1513
+ this.startAutocaptureIfEnabled(initialEffectiveOptions);
1514
+ }
1515
+ resolveAutocaptureOptions(autocapture) {
1516
+ if (autocapture === false) {
1517
+ return {
1518
+ captureClicks: false,
1519
+ captureFormSubmits: false,
1520
+ captureFormChanges: false,
1521
+ captureTextSelection: false,
1522
+ };
1523
+ }
1524
+ if (autocapture === true || autocapture === undefined) {
1525
+ return {}; // Use default configuration (enabled by default)
1526
+ }
1527
+ return autocapture;
1528
+ }
1529
+ track(event, properties) {
1530
+ this.client.track(event, properties);
1531
+ }
1532
+ identify(distinctId, attributes) {
1533
+ this.client.identify(distinctId, attributes);
1534
+ }
1535
+ reset() {
1536
+ this.client.reset();
1537
+ }
1538
+ capturePageview(properties) {
1539
+ this.pageviewTracker.capturePageview(properties);
1540
+ }
1541
+ startAutocapture() {
1542
+ // Always check effective options (which may include remote options)
1543
+ const effectiveOptions = this.client.getEffectiveOptions();
1544
+ // Only enable if effectiveOptions are loaded and autoTrackPageviews is not explicitly false
1545
+ const autoTrackPageviews = effectiveOptions && Object.keys(effectiveOptions).length > 0
1546
+ ? effectiveOptions.autoTrackPageviews !== false
1547
+ : false;
1548
+ const autocaptureEnabled = effectiveOptions && Object.keys(effectiveOptions).length > 0
1549
+ ? effectiveOptions.autocapture !== false
1550
+ : false;
1551
+ // Update autocapture tracker options if they've changed
1552
+ const autocaptureOptions = this.resolveAutocaptureOptions(effectiveOptions.autocapture);
1553
+ this.autocaptureTracker.updateOptions(autocaptureOptions);
1554
+ if (autoTrackPageviews) {
1555
+ this.pageviewTracker.startAutoPageviewTracking();
1556
+ }
1557
+ if (autocaptureEnabled) {
1558
+ this.autocaptureTracker.start();
1559
+ }
1560
+ this.autocaptureStarted = true;
1561
+ }
1562
+ stopAutocapture() {
1563
+ this.pageviewTracker.stopAutocapture();
1564
+ this.autocaptureTracker.stop();
1565
+ this.autocaptureStarted = false;
1566
+ }
1567
+ /**
1568
+ * Automatically start autocapture if enabled in options
1569
+ * Handles both initial options and empty options during remote-first initialization
1570
+ */
1571
+ startAutocaptureIfEnabled(effectiveOptions) {
1572
+ // Skip if autocapture was already started manually
1573
+ if (this.autocaptureStarted) {
1574
+ return;
1575
+ }
1576
+ // During remote-first initialization, effective options might be empty initially
1577
+ // Only auto-start if we have actual options loaded, not empty options
1578
+ const hasActualOptions = effectiveOptions && Object.keys(effectiveOptions).length > 0;
1579
+ if (hasActualOptions) {
1580
+ // Use same logic as manual startAutocapture() but only start automatically
1581
+ const autoTrackPageviews = effectiveOptions.autoTrackPageviews !== false;
1582
+ const autocaptureEnabled = effectiveOptions.autocapture !== false;
1583
+ // Update autocapture tracker options
1584
+ const autocaptureOptions = this.resolveAutocaptureOptions(effectiveOptions.autocapture);
1585
+ this.autocaptureTracker.updateOptions(autocaptureOptions);
1586
+ if (autoTrackPageviews) {
1587
+ this.pageviewTracker.startAutoPageviewTracking();
1588
+ }
1589
+ if (autocaptureEnabled) {
1590
+ this.autocaptureTracker.start();
1591
+ }
1592
+ if (autoTrackPageviews || autocaptureEnabled) {
1593
+ this.autocaptureStarted = true;
1594
+ }
1595
+ }
1596
+ // If options are empty (during initialization), wait for options change callback
1597
+ }
1598
+ /**
1599
+ * Handle effective options change (e.g., when remote options are fetched)
1600
+ */
1601
+ handleOptionsChange(effectiveOptions) {
1602
+ // Stop current autocapture if it was already started
1603
+ if (this.autocaptureStarted) {
1604
+ this.pageviewTracker.stopAutocapture();
1605
+ this.autocaptureTracker.stop();
1606
+ this.autocaptureStarted = false;
1607
+ }
1608
+ // Evaluate if autocapture should be enabled with new options
1609
+ const autoTrackPageviews = effectiveOptions.autoTrackPageviews !== false;
1610
+ const autocaptureEnabled = effectiveOptions.autocapture !== false;
1611
+ // Update autocapture tracker options
1612
+ const autocaptureOptions = this.resolveAutocaptureOptions(effectiveOptions.autocapture);
1613
+ this.autocaptureTracker.updateOptions(autocaptureOptions);
1614
+ // Start autocapture based on new options (even if it wasn't started before)
1615
+ if (autoTrackPageviews) {
1616
+ this.pageviewTracker.startAutoPageviewTracking();
1617
+ }
1618
+ if (autocaptureEnabled) {
1619
+ this.autocaptureTracker.start();
1620
+ }
1621
+ this.autocaptureStarted = autoTrackPageviews || autocaptureEnabled;
1622
+ }
1623
+ async flush() {
1624
+ return this.client.flush();
1625
+ }
1626
+ getEffectiveOptions() {
1627
+ return this.client.getEffectiveOptions();
1628
+ }
1629
+ /**
1630
+ * Register a callback to be notified when effective options change
1631
+ */
1632
+ onOptionsChange(callback) {
1633
+ return this.client.onOptionsChange(callback);
1634
+ }
1635
+ destroy() {
1636
+ this.pageviewTracker.stopAutocapture();
1637
+ this.autocaptureTracker.stop();
1638
+ if (this.unsubscribeOptionsChange) {
1639
+ this.unsubscribeOptionsChange();
1640
+ }
1641
+ this.client.destroy();
1642
+ }
1643
+ }
1644
+ const init = (config) => {
1645
+ return new JourniumAnalytics(config);
1646
+ };
1647
+
1648
+ /**
1649
+ * CDN Entry Point for Journium Analytics
1650
+ * This file provides global browser integration for script snippet usage
1651
+ * Features: auto method stubbing, error handling, improved queue processing
1652
+ */
1653
+ // Available public methods for auto-stubbing
1654
+ const STUBBED_METHODS = [
1655
+ 'track', 'identify', 'reset', 'capturePageview', 'startAutocapture',
1656
+ 'stopAutocapture', 'flush', 'getEffectiveOptions', 'onOptionsChange', 'destroy'
1657
+ ];
1658
+ /**
1659
+ * Enhanced queue processing with better error handling and edge cases
1660
+ */
1661
+ function processQueuedCalls(instance, queue) {
1662
+ if (!Array.isArray(queue) || queue.length === 0) {
1663
+ return;
1664
+ }
1665
+ const processedCount = { success: 0, error: 0, skipped: 0 };
1666
+ queue.forEach(([method, ...args], index) => {
1667
+ try {
1668
+ // Validate method call structure
1669
+ if (typeof method !== 'string') {
1670
+ console.warn(`Journium: Invalid method call at index ${index}:`, method);
1671
+ processedCount.skipped++;
1672
+ return;
1673
+ }
1674
+ // Check if method exists and is callable
1675
+ if (method in instance && typeof instance[method] === 'function') {
1676
+ // Handle async methods properly
1677
+ const result = instance[method](...args);
1678
+ // If it's a promise, handle potential rejections
1679
+ if (result && typeof result.catch === 'function') {
1680
+ result.catch((error) => {
1681
+ console.warn(`Journium: Async method '${method}' failed:`, error);
1682
+ });
1683
+ }
1684
+ processedCount.success++;
1685
+ }
1686
+ else {
1687
+ console.warn(`Journium: Unknown method '${method}' called from queue`);
1688
+ processedCount.skipped++;
1689
+ }
1690
+ }
1691
+ catch (error) {
1692
+ console.warn(`Journium: Error executing queued method '${method}':`, error);
1693
+ processedCount.error++;
1694
+ }
1695
+ });
1696
+ // Log summary for debugging
1697
+ if (processedCount.success > 0 || processedCount.error > 0) {
1698
+ console.log(`Journium: Processed ${processedCount.success} calls, ${processedCount.error} errors, ${processedCount.skipped} skipped`);
1699
+ }
1700
+ }
1701
+ /**
1702
+ * Dynamically stub all available methods
1703
+ */
1704
+ function createMethodStubs(target, queueTarget = []) {
1705
+ STUBBED_METHODS.forEach(method => {
1706
+ target[method] = function (...args) {
1707
+ queueTarget.push([method, ...args]);
1708
+ return target; // Enable method chaining
1709
+ };
1710
+ });
1711
+ }
1712
+ /**
1713
+ * Dynamically bind all available methods from instance to target
1714
+ */
1715
+ function bindInstanceMethods(instance, target) {
1716
+ STUBBED_METHODS.forEach(method => {
1717
+ if (method in instance && typeof instance[method] === 'function') {
1718
+ target[method] = instance[method].bind(instance);
1719
+ }
1720
+ });
1721
+ }
1722
+ /**
1723
+ * Create fallback object when initialization fails
1724
+ */
1725
+ function createFallbackObject(error) {
1726
+ const fallbackQueue = [];
1727
+ const fallback = {
1728
+ init: (config, instanceName) => {
1729
+ console.warn('Journium: Fallback mode - init calls will be queued');
1730
+ fallbackQueue.push(['init', config, instanceName]);
1731
+ return {};
1732
+ },
1733
+ _error: error || null,
1734
+ _fallback: true
1735
+ };
1736
+ // Create method stubs that queue calls
1737
+ createMethodStubs(fallback, fallbackQueue);
1738
+ return fallback;
1739
+ }
1740
+ /**
1741
+ * Create the global journium object with enhanced error handling
1742
+ */
1743
+ function createGlobalJournium() {
1744
+ let defaultInstance = null;
1745
+ const globalJournium = {
1746
+ init: (config, instanceName) => {
1747
+ try {
1748
+ // Validate config object
1749
+ if (!config || typeof config !== 'object') {
1750
+ throw new Error('Config object is required');
1751
+ }
1752
+ if (!config.publishableKey) {
1753
+ throw new Error('publishableKey is required in config');
1754
+ }
1755
+ // Build the config for the init function with proper structure
1756
+ const initConfig = {
1757
+ publishableKey: config.publishableKey
1758
+ };
1759
+ // Add apiHost if provided
1760
+ if (config.apiHost) {
1761
+ initConfig.apiHost = config.apiHost;
1762
+ }
1763
+ // Add options as nested object if provided
1764
+ if (config.options && typeof config.options === 'object') {
1765
+ initConfig.options = config.options;
1766
+ }
1767
+ // Create the instance using the merged config
1768
+ const instance = init(initConfig);
1769
+ if (instanceName) {
1770
+ // Multi-instance: store as journium[instanceName]
1771
+ globalJournium[instanceName] = instance;
1772
+ return instance;
1773
+ }
1774
+ else {
1775
+ // Single instance: dynamically bind all methods
1776
+ defaultInstance = instance;
1777
+ bindInstanceMethods(instance, globalJournium);
1778
+ return instance;
1779
+ }
1780
+ }
1781
+ catch (error) {
1782
+ console.error('Journium: Failed to initialize:', error);
1783
+ // Return fallback object that queues method calls
1784
+ const fallback = createFallbackObject(error);
1785
+ Object.assign(globalJournium, fallback);
1786
+ return {};
1787
+ }
1788
+ }
1789
+ };
1790
+ return globalJournium;
1791
+ }
1792
+ /**
1793
+ * Initialize from snippet with comprehensive error handling and retry logic
1794
+ */
1795
+ function initializeFromSnippet() {
1796
+ if (typeof window === 'undefined') {
1797
+ return;
1798
+ }
1799
+ const snippet = window.journium;
1800
+ let globalJournium = createGlobalJournium();
1801
+ try {
1802
+ if (snippet && snippet._i) {
1803
+ // Extract snippet initialization parameters
1804
+ const [config, instanceName] = snippet._i;
1805
+ const queuedCalls = snippet._q || [];
1806
+ // Validate config object structure
1807
+ if (!config || typeof config !== 'object') {
1808
+ throw new Error('Invalid or missing config object');
1809
+ }
1810
+ if (!config.publishableKey) {
1811
+ throw new Error('publishableKey is required in config');
1812
+ }
1813
+ // Initialize the instance with timeout protection
1814
+ const instance = globalJournium.init(config, instanceName);
1815
+ // Process queued method calls
1816
+ if (queuedCalls.length > 0) {
1817
+ // Always use the instance for processing queued calls
1818
+ setTimeout(() => processQueuedCalls(instance, queuedCalls), 0);
1819
+ }
1820
+ // Preserve snippet metadata
1821
+ globalJournium.__JV = snippet.__JV;
1822
+ globalJournium._q = [];
1823
+ globalJournium._i = snippet._i;
1824
+ globalJournium._error = null;
1825
+ }
1826
+ else if (snippet && snippet._q) {
1827
+ // Handle case where queue exists but no initialization
1828
+ console.warn('Journium: Found queued calls but no initialization data');
1829
+ globalJournium._q = snippet._q;
1830
+ }
1831
+ }
1832
+ catch (error) {
1833
+ console.error('Journium: Critical initialization failure:', error);
1834
+ // Create fallback with error tracking
1835
+ globalJournium = createFallbackObject(error);
1836
+ // Preserve original queue for potential retry
1837
+ if (snippet && snippet._q) {
1838
+ globalJournium._q = snippet._q;
1839
+ }
1840
+ // Enable retry mechanism
1841
+ globalJournium._retry = true;
1842
+ }
1843
+ finally {
1844
+ // Always replace window.journium, even in failure cases
1845
+ window.journium = globalJournium;
1846
+ // Set up retry mechanism if needed
1847
+ if (globalJournium._retry && !globalJournium._error) {
1848
+ setTimeout(() => {
1849
+ if (window.journium && window.journium._retry) {
1850
+ console.log('Journium: Attempting retry...');
1851
+ initializeFromSnippet();
1852
+ }
1853
+ }, 2000);
1854
+ }
1855
+ }
1856
+ }
1857
+ // Auto-initialize when script loads
1858
+ if (typeof window !== 'undefined') {
1859
+ initializeFromSnippet();
1860
+ }
1861
+ var cdn = { init };
1862
+
1863
+ exports.default = cdn;
1864
+ exports.init = init;
1865
+
1866
+ Object.defineProperty(exports, '__esModule', { value: true });
1867
+
1868
+ return exports;
1869
+
1870
+ })({});
1871
+ //# sourceMappingURL=journium.js.map