@journium/react 0.1.0-alpha.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,1407 @@
1
+ import React, { createContext, useRef, useEffect, useContext, useCallback } from 'react';
2
+
3
+ /**
4
+ * uuidv7: A JavaScript implementation of UUID version 7
5
+ *
6
+ * Copyright 2021-2024 LiosK
7
+ *
8
+ * @license Apache-2.0
9
+ * @packageDocumentation
10
+ */
11
+ const DIGITS = "0123456789abcdef";
12
+ /** Represents a UUID as a 16-byte byte array. */
13
+ class UUID {
14
+ /** @param bytes - The 16-byte byte array representation. */
15
+ constructor(bytes) {
16
+ this.bytes = bytes;
17
+ }
18
+ /**
19
+ * Creates an object from the internal representation, a 16-byte byte array
20
+ * containing the binary UUID representation in the big-endian byte order.
21
+ *
22
+ * This method does NOT shallow-copy the argument, and thus the created object
23
+ * holds the reference to the underlying buffer.
24
+ *
25
+ * @throws TypeError if the length of the argument is not 16.
26
+ */
27
+ static ofInner(bytes) {
28
+ if (bytes.length !== 16) {
29
+ throw new TypeError("not 128-bit length");
30
+ }
31
+ else {
32
+ return new UUID(bytes);
33
+ }
34
+ }
35
+ /**
36
+ * Builds a byte array from UUIDv7 field values.
37
+ *
38
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
39
+ * @param randA - A 12-bit `rand_a` field value.
40
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
41
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
42
+ * @throws RangeError if any field value is out of the specified range.
43
+ */
44
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
45
+ if (!Number.isInteger(unixTsMs) ||
46
+ !Number.isInteger(randA) ||
47
+ !Number.isInteger(randBHi) ||
48
+ !Number.isInteger(randBLo) ||
49
+ unixTsMs < 0 ||
50
+ randA < 0 ||
51
+ randBHi < 0 ||
52
+ randBLo < 0 ||
53
+ unixTsMs > 281474976710655 ||
54
+ randA > 0xfff ||
55
+ randBHi > 1073741823 ||
56
+ randBLo > 4294967295) {
57
+ throw new RangeError("invalid field value");
58
+ }
59
+ const bytes = new Uint8Array(16);
60
+ bytes[0] = unixTsMs / 2 ** 40;
61
+ bytes[1] = unixTsMs / 2 ** 32;
62
+ bytes[2] = unixTsMs / 2 ** 24;
63
+ bytes[3] = unixTsMs / 2 ** 16;
64
+ bytes[4] = unixTsMs / 2 ** 8;
65
+ bytes[5] = unixTsMs;
66
+ bytes[6] = 0x70 | (randA >>> 8);
67
+ bytes[7] = randA;
68
+ bytes[8] = 0x80 | (randBHi >>> 24);
69
+ bytes[9] = randBHi >>> 16;
70
+ bytes[10] = randBHi >>> 8;
71
+ bytes[11] = randBHi;
72
+ bytes[12] = randBLo >>> 24;
73
+ bytes[13] = randBLo >>> 16;
74
+ bytes[14] = randBLo >>> 8;
75
+ bytes[15] = randBLo;
76
+ return new UUID(bytes);
77
+ }
78
+ /**
79
+ * Builds a byte array from a string representation.
80
+ *
81
+ * This method accepts the following formats:
82
+ *
83
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
84
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
85
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
86
+ * - RFC 9562 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
87
+ *
88
+ * Leading and trailing whitespaces represents an error.
89
+ *
90
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
91
+ */
92
+ static parse(uuid) {
93
+ var _a, _b, _c, _d;
94
+ let hex = undefined;
95
+ switch (uuid.length) {
96
+ case 32:
97
+ hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
98
+ break;
99
+ case 36:
100
+ hex =
101
+ (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
102
+ .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
103
+ break;
104
+ case 38:
105
+ hex =
106
+ (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
107
+ .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
108
+ break;
109
+ case 45:
110
+ hex =
111
+ (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
112
+ .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
113
+ break;
114
+ }
115
+ if (hex) {
116
+ const inner = new Uint8Array(16);
117
+ for (let i = 0; i < 16; i += 4) {
118
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
119
+ inner[i + 0] = n >>> 24;
120
+ inner[i + 1] = n >>> 16;
121
+ inner[i + 2] = n >>> 8;
122
+ inner[i + 3] = n;
123
+ }
124
+ return new UUID(inner);
125
+ }
126
+ else {
127
+ throw new SyntaxError("could not parse UUID string");
128
+ }
129
+ }
130
+ /**
131
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
132
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
133
+ */
134
+ toString() {
135
+ let text = "";
136
+ for (let i = 0; i < this.bytes.length; i++) {
137
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
138
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
139
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
140
+ text += "-";
141
+ }
142
+ }
143
+ return text;
144
+ }
145
+ /**
146
+ * @returns The 32-digit hexadecimal representation without hyphens
147
+ * (`0189dcd553117d408db09496a2eef37b`).
148
+ */
149
+ toHex() {
150
+ let text = "";
151
+ for (let i = 0; i < this.bytes.length; i++) {
152
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
153
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
154
+ }
155
+ return text;
156
+ }
157
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
158
+ toJSON() {
159
+ return this.toString();
160
+ }
161
+ /**
162
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
163
+ * "MAX".
164
+ *
165
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
166
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
167
+ * subsumed under the variants `0b0` and `0b111`, respectively.
168
+ */
169
+ getVariant() {
170
+ const n = this.bytes[8] >>> 4;
171
+ if (n < 0) {
172
+ throw new Error("unreachable");
173
+ }
174
+ else if (n <= 0b0111) {
175
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
176
+ }
177
+ else if (n <= 0b1011) {
178
+ return "VAR_10";
179
+ }
180
+ else if (n <= 0b1101) {
181
+ return "VAR_110";
182
+ }
183
+ else if (n <= 0b1111) {
184
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
185
+ }
186
+ else {
187
+ throw new Error("unreachable");
188
+ }
189
+ }
190
+ /**
191
+ * Returns the version field value of the UUID or `undefined` if the UUID does
192
+ * not have the variant field value of `0b10`.
193
+ */
194
+ getVersion() {
195
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
196
+ }
197
+ /** Creates an object from `this`. */
198
+ clone() {
199
+ return new UUID(this.bytes.slice(0));
200
+ }
201
+ /** Returns true if `this` is equivalent to `other`. */
202
+ equals(other) {
203
+ return this.compareTo(other) === 0;
204
+ }
205
+ /**
206
+ * Returns a negative integer, zero, or positive integer if `this` is less
207
+ * than, equal to, or greater than `other`, respectively.
208
+ */
209
+ compareTo(other) {
210
+ for (let i = 0; i < 16; i++) {
211
+ const diff = this.bytes[i] - other.bytes[i];
212
+ if (diff !== 0) {
213
+ return Math.sign(diff);
214
+ }
215
+ }
216
+ return 0;
217
+ }
218
+ }
219
+ /**
220
+ * Encapsulates the monotonic counter state.
221
+ *
222
+ * This class provides APIs to utilize a separate counter state from that of the
223
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
224
+ * the default {@link generate} method, this class has {@link generateOrAbort}
225
+ * that is useful to absolutely guarantee the monotonically increasing order of
226
+ * generated UUIDs. See their respective documentation for details.
227
+ */
228
+ class V7Generator {
229
+ /**
230
+ * Creates a generator object with the default random number generator, or
231
+ * with the specified one if passed as an argument. The specified random
232
+ * number generator should be cryptographically strong and securely seeded.
233
+ */
234
+ constructor(randomNumberGenerator) {
235
+ this.timestamp = 0;
236
+ this.counter = 0;
237
+ this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
238
+ }
239
+ /**
240
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
241
+ * generator upon significant timestamp rollback.
242
+ *
243
+ * This method returns a monotonically increasing UUID by reusing the previous
244
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
245
+ * preceding UUID's. However, when such a clock rollback is considered
246
+ * significant (i.e., by more than ten seconds), this method resets the
247
+ * generator and returns a new UUID based on the given timestamp, breaking the
248
+ * increasing order of UUIDs.
249
+ *
250
+ * See {@link generateOrAbort} for the other mode of generation and
251
+ * {@link generateOrResetCore} for the low-level primitive.
252
+ */
253
+ generate() {
254
+ return this.generateOrResetCore(Date.now(), 10000);
255
+ }
256
+ /**
257
+ * Generates a new UUIDv7 object from the current timestamp, or returns
258
+ * `undefined` upon significant timestamp rollback.
259
+ *
260
+ * This method returns a monotonically increasing UUID by reusing the previous
261
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
262
+ * preceding UUID's. However, when such a clock rollback is considered
263
+ * significant (i.e., by more than ten seconds), this method aborts and
264
+ * returns `undefined` immediately.
265
+ *
266
+ * See {@link generate} for the other mode of generation and
267
+ * {@link generateOrAbortCore} for the low-level primitive.
268
+ */
269
+ generateOrAbort() {
270
+ return this.generateOrAbortCore(Date.now(), 10000);
271
+ }
272
+ /**
273
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
274
+ * generator upon significant timestamp rollback.
275
+ *
276
+ * This method is equivalent to {@link generate} except that it takes a custom
277
+ * timestamp and clock rollback allowance.
278
+ *
279
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
280
+ * considered significant. A suggested value is `10_000` (milliseconds).
281
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
282
+ */
283
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
284
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
285
+ if (value === undefined) {
286
+ // reset state and resume
287
+ this.timestamp = 0;
288
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
289
+ }
290
+ return value;
291
+ }
292
+ /**
293
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
294
+ * `undefined` upon significant timestamp rollback.
295
+ *
296
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
297
+ * custom timestamp and clock rollback allowance.
298
+ *
299
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
300
+ * considered significant. A suggested value is `10_000` (milliseconds).
301
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
302
+ */
303
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
304
+ const MAX_COUNTER = 4398046511103;
305
+ if (!Number.isInteger(unixTsMs) ||
306
+ unixTsMs < 1 ||
307
+ unixTsMs > 281474976710655) {
308
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
309
+ }
310
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
311
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
312
+ }
313
+ if (unixTsMs > this.timestamp) {
314
+ this.timestamp = unixTsMs;
315
+ this.resetCounter();
316
+ }
317
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
318
+ // go on with previous timestamp if new one is not much smaller
319
+ this.counter++;
320
+ if (this.counter > MAX_COUNTER) {
321
+ // increment timestamp at counter overflow
322
+ this.timestamp++;
323
+ this.resetCounter();
324
+ }
325
+ }
326
+ else {
327
+ // abort if clock went backwards to unbearable extent
328
+ return undefined;
329
+ }
330
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
331
+ }
332
+ /** Initializes the counter at a 42-bit random integer. */
333
+ resetCounter() {
334
+ this.counter =
335
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
336
+ }
337
+ /**
338
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
339
+ *
340
+ * @internal
341
+ */
342
+ generateV4() {
343
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
344
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
345
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
346
+ return UUID.ofInner(bytes);
347
+ }
348
+ }
349
+ /** Returns the default random number generator available in the environment. */
350
+ const getDefaultRandom = () => {
351
+ // detect Web Crypto API
352
+ if (typeof crypto !== "undefined" &&
353
+ typeof crypto.getRandomValues !== "undefined") {
354
+ return new BufferedCryptoRandom();
355
+ }
356
+ else {
357
+ // fall back on Math.random() unless the flag is set to true
358
+ if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
359
+ throw new Error("no cryptographically strong RNG available");
360
+ }
361
+ return {
362
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
363
+ Math.trunc(Math.random() * 65536),
364
+ };
365
+ }
366
+ };
367
+ /**
368
+ * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
369
+ * buffer by default to avoid both unbearable throughput decline in some
370
+ * environments and the waste of time and space for unused values.
371
+ */
372
+ class BufferedCryptoRandom {
373
+ constructor() {
374
+ this.buffer = new Uint32Array(8);
375
+ this.cursor = 0xffff;
376
+ }
377
+ nextUint32() {
378
+ if (this.cursor >= this.buffer.length) {
379
+ crypto.getRandomValues(this.buffer);
380
+ this.cursor = 0;
381
+ }
382
+ return this.buffer[this.cursor++];
383
+ }
384
+ }
385
+ let defaultGenerator;
386
+ /**
387
+ * Generates a UUIDv7 string.
388
+ *
389
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
390
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
391
+ */
392
+ const uuidv7 = () => uuidv7obj().toString();
393
+ /** Generates a UUIDv7 object. */
394
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
395
+
396
+ const generateId = () => {
397
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
398
+ };
399
+ const generateUuidv7 = () => {
400
+ return uuidv7();
401
+ };
402
+ const getCurrentTimestamp = () => {
403
+ return new Date().toISOString();
404
+ };
405
+ const getCurrentUrl = () => {
406
+ if (typeof window !== 'undefined') {
407
+ return window.location.href;
408
+ }
409
+ return '';
410
+ };
411
+ const getPageTitle = () => {
412
+ if (typeof document !== 'undefined') {
413
+ return document.title;
414
+ }
415
+ return '';
416
+ };
417
+ const getReferrer = () => {
418
+ if (typeof document !== 'undefined') {
419
+ return document.referrer;
420
+ }
421
+ return '';
422
+ };
423
+ const isBrowser = () => {
424
+ return typeof window !== 'undefined';
425
+ };
426
+ const isNode = () => {
427
+ var _a;
428
+ return typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
429
+ };
430
+ const fetchRemoteConfig = async (apiHost, token, configEndpoint, fetchFn) => {
431
+ const endpoint = configEndpoint || '/configs';
432
+ const url = `${apiHost}${endpoint}?ingestion_key=${encodeURIComponent(token)}`;
433
+ try {
434
+ let fetch = fetchFn;
435
+ if (!fetch) {
436
+ if (isNode()) {
437
+ // For Node.js environments, expect fetch to be passed in
438
+ throw new Error('Fetch function must be provided in Node.js environment');
439
+ }
440
+ else {
441
+ // Use native fetch in browser
442
+ fetch = window.fetch;
443
+ }
444
+ }
445
+ const response = await fetch(url, {
446
+ method: 'GET',
447
+ headers: {
448
+ 'Content-Type': 'application/json',
449
+ },
450
+ });
451
+ if (!response.ok) {
452
+ throw new Error(`Config fetch failed: ${response.status} ${response.statusText}`);
453
+ }
454
+ const data = await response.json();
455
+ return data;
456
+ }
457
+ catch (error) {
458
+ console.warn('Failed to fetch remote config:', error);
459
+ return null;
460
+ }
461
+ };
462
+ const mergeConfigs = (localConfig, remoteConfig) => {
463
+ if (!remoteConfig) {
464
+ return localConfig;
465
+ }
466
+ // Deep merge remote config into local config
467
+ // Remote config takes precedence over local config
468
+ const merged = { ...localConfig };
469
+ // Handle primitive values
470
+ Object.keys(remoteConfig).forEach(key => {
471
+ if (remoteConfig[key] !== undefined && remoteConfig[key] !== null) {
472
+ if (typeof remoteConfig[key] === 'object' && !Array.isArray(remoteConfig[key])) {
473
+ // Deep merge objects
474
+ merged[key] = {
475
+ ...(merged[key] || {}),
476
+ ...remoteConfig[key]
477
+ };
478
+ }
479
+ else {
480
+ // Override primitive values and arrays
481
+ merged[key] = remoteConfig[key];
482
+ }
483
+ }
484
+ });
485
+ return merged;
486
+ };
487
+
488
+ const DEFAULT_SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes in ms
489
+ class BrowserIdentityManager {
490
+ constructor(sessionTimeout, token) {
491
+ this.identity = null;
492
+ this.sessionTimeout = DEFAULT_SESSION_TIMEOUT;
493
+ if (sessionTimeout) {
494
+ this.sessionTimeout = sessionTimeout;
495
+ }
496
+ // Generate storage key with token pattern: jrnm_<token>_journium
497
+ this.storageKey = token ? `jrnm_${token}_journium` : '__journium_identity';
498
+ this.loadOrCreateIdentity();
499
+ }
500
+ loadOrCreateIdentity() {
501
+ if (!this.isBrowser())
502
+ return;
503
+ try {
504
+ const stored = localStorage.getItem(this.storageKey);
505
+ if (stored) {
506
+ const parsedIdentity = JSON.parse(stored);
507
+ // Check if session is expired
508
+ const now = Date.now();
509
+ const sessionAge = now - parsedIdentity.session_timestamp;
510
+ if (sessionAge > this.sessionTimeout) {
511
+ // Session expired, create new session but keep device and distinct IDs
512
+ this.identity = {
513
+ distinct_id: parsedIdentity.distinct_id,
514
+ $device_id: parsedIdentity.$device_id,
515
+ $session_id: generateUuidv7(),
516
+ session_timestamp: now,
517
+ };
518
+ }
519
+ else {
520
+ // Session still valid
521
+ this.identity = parsedIdentity;
522
+ }
523
+ }
524
+ else {
525
+ // First time, create all new IDs
526
+ const newId = generateUuidv7();
527
+ this.identity = {
528
+ distinct_id: newId,
529
+ $device_id: newId,
530
+ $session_id: newId,
531
+ session_timestamp: Date.now(),
532
+ };
533
+ }
534
+ // Save to localStorage
535
+ this.saveIdentity();
536
+ }
537
+ catch (error) {
538
+ console.warn('Journium: Failed to load/create identity:', error);
539
+ // Fallback: create temporary identity without localStorage
540
+ const newId = generateUuidv7();
541
+ this.identity = {
542
+ distinct_id: newId,
543
+ $device_id: newId,
544
+ $session_id: newId,
545
+ session_timestamp: Date.now(),
546
+ };
547
+ }
548
+ }
549
+ saveIdentity() {
550
+ if (!this.isBrowser() || !this.identity)
551
+ return;
552
+ try {
553
+ localStorage.setItem(this.storageKey, JSON.stringify(this.identity));
554
+ }
555
+ catch (error) {
556
+ console.warn('Journium: Failed to save identity to localStorage:', error);
557
+ }
558
+ }
559
+ isBrowser() {
560
+ return typeof window !== 'undefined' && typeof localStorage !== 'undefined';
561
+ }
562
+ getIdentity() {
563
+ return this.identity;
564
+ }
565
+ updateSessionTimeout(timeoutMs) {
566
+ this.sessionTimeout = timeoutMs;
567
+ }
568
+ refreshSession() {
569
+ if (!this.identity)
570
+ return;
571
+ this.identity = {
572
+ ...this.identity,
573
+ $session_id: generateUuidv7(),
574
+ session_timestamp: Date.now(),
575
+ };
576
+ this.saveIdentity();
577
+ }
578
+ getUserAgentInfo() {
579
+ if (!this.isBrowser()) {
580
+ return {
581
+ $raw_user_agent: '',
582
+ $browser: 'Unknown',
583
+ $os: 'Unknown',
584
+ $device_type: 'Unknown',
585
+ };
586
+ }
587
+ const userAgent = navigator.userAgent;
588
+ return {
589
+ $raw_user_agent: userAgent,
590
+ $browser: this.parseBrowser(userAgent),
591
+ $os: this.parseOS(userAgent),
592
+ $device_type: this.parseDeviceType(userAgent),
593
+ };
594
+ }
595
+ parseBrowser(userAgent) {
596
+ if (userAgent.includes('Chrome') && !userAgent.includes('Edg'))
597
+ return 'Chrome';
598
+ if (userAgent.includes('Firefox'))
599
+ return 'Firefox';
600
+ if (userAgent.includes('Safari') && !userAgent.includes('Chrome'))
601
+ return 'Safari';
602
+ if (userAgent.includes('Edg'))
603
+ return 'Edge';
604
+ if (userAgent.includes('Opera') || userAgent.includes('OPR'))
605
+ return 'Opera';
606
+ return 'Unknown';
607
+ }
608
+ parseOS(userAgent) {
609
+ if (userAgent.includes('Windows'))
610
+ return 'Windows';
611
+ if (userAgent.includes('Macintosh') || userAgent.includes('Mac OS'))
612
+ return 'Mac OS';
613
+ if (userAgent.includes('Linux'))
614
+ return 'Linux';
615
+ if (userAgent.includes('Android'))
616
+ return 'Android';
617
+ if (userAgent.includes('iPhone') || userAgent.includes('iPad'))
618
+ return 'iOS';
619
+ return 'Unknown';
620
+ }
621
+ parseDeviceType(userAgent) {
622
+ if (userAgent.includes('Mobile') || userAgent.includes('Android') || userAgent.includes('iPhone')) {
623
+ return 'Mobile';
624
+ }
625
+ if (userAgent.includes('iPad') || userAgent.includes('Tablet')) {
626
+ return 'Tablet';
627
+ }
628
+ return 'Desktop';
629
+ }
630
+ }
631
+
632
+ class JourniumClient {
633
+ constructor(config) {
634
+ this.queue = [];
635
+ this.flushTimer = null;
636
+ this.initialized = false;
637
+ // Validate required configuration
638
+ if (!config.token) {
639
+ console.error('Journium: token is required but not provided. SDK will not function.');
640
+ return;
641
+ }
642
+ if (!config.apiHost) {
643
+ console.error('Journium: apiHost is required but not provided. SDK will not function.');
644
+ return;
645
+ }
646
+ this.config = config;
647
+ // Generate storage key for config caching
648
+ this.configStorageKey = `jrnm_${config.token}_config`;
649
+ // Initialize identity manager
650
+ this.identityManager = new BrowserIdentityManager(this.config.sessionTimeout, this.config.token);
651
+ // Initialize synchronously with cached config, fetch fresh config in background
652
+ this.initialize();
653
+ }
654
+ loadCachedConfig() {
655
+ if (typeof window === 'undefined' || !window.localStorage) {
656
+ return null;
657
+ }
658
+ try {
659
+ const cached = window.localStorage.getItem(this.configStorageKey);
660
+ return cached ? JSON.parse(cached) : null;
661
+ }
662
+ catch (error) {
663
+ if (this.config.debug) {
664
+ console.warn('Journium: Failed to load cached config:', error);
665
+ }
666
+ return null;
667
+ }
668
+ }
669
+ saveCachedConfig(config) {
670
+ if (typeof window === 'undefined' || !window.localStorage) {
671
+ return;
672
+ }
673
+ try {
674
+ window.localStorage.setItem(this.configStorageKey, JSON.stringify(config));
675
+ }
676
+ catch (error) {
677
+ if (this.config.debug) {
678
+ console.warn('Journium: Failed to save config to cache:', error);
679
+ }
680
+ }
681
+ }
682
+ async initialize() {
683
+ var _a, _b, _c;
684
+ // Step 1: Load cached config from localStorage (synchronous)
685
+ const cachedConfig = this.loadCachedConfig();
686
+ // Step 2: Apply cached config immediately, or use defaults
687
+ const localOnlyConfig = {
688
+ apiHost: this.config.apiHost,
689
+ token: this.config.token,
690
+ configEndpoint: this.config.configEndpoint,
691
+ };
692
+ if (cachedConfig) {
693
+ // Use cached remote config
694
+ this.config = {
695
+ ...localOnlyConfig,
696
+ ...cachedConfig,
697
+ };
698
+ if (this.config.debug) {
699
+ console.log('Journium: Using cached configuration:', cachedConfig);
700
+ }
701
+ }
702
+ else {
703
+ // Use defaults for first-time initialization
704
+ this.config = {
705
+ ...this.config,
706
+ debug: (_a = this.config.debug) !== null && _a !== void 0 ? _a : false,
707
+ flushAt: (_b = this.config.flushAt) !== null && _b !== void 0 ? _b : 20,
708
+ flushInterval: (_c = this.config.flushInterval) !== null && _c !== void 0 ? _c : 10000,
709
+ };
710
+ if (this.config.debug) {
711
+ console.log('Journium: No cached config found, using defaults');
712
+ }
713
+ }
714
+ // Update session timeout from config
715
+ if (this.config.sessionTimeout) {
716
+ this.identityManager.updateSessionTimeout(this.config.sessionTimeout);
717
+ }
718
+ // Step 3: Mark as initialized immediately - no need to wait for remote fetch
719
+ this.initialized = true;
720
+ // Step 4: Start flush timer immediately
721
+ if (this.config.flushInterval && this.config.flushInterval > 0) {
722
+ this.startFlushTimer();
723
+ }
724
+ if (this.config.debug) {
725
+ console.log('Journium: Client initialized immediately with config:', this.config);
726
+ }
727
+ // Step 5: Fetch fresh config in background (don't await)
728
+ if (this.config.token) {
729
+ this.fetchAndCacheRemoteConfig();
730
+ }
731
+ }
732
+ async fetchAndCacheRemoteConfig() {
733
+ try {
734
+ if (this.config.debug) {
735
+ console.log('Journium: Fetching remote configuration in background...');
736
+ }
737
+ const remoteConfigResponse = await fetchRemoteConfig(this.config.apiHost, this.config.token, this.config.configEndpoint);
738
+ if (remoteConfigResponse && remoteConfigResponse.success) {
739
+ // Save to cache for next session
740
+ this.saveCachedConfig(remoteConfigResponse.config);
741
+ // Apply fresh config to current session
742
+ const localOnlyConfig = {
743
+ apiHost: this.config.apiHost,
744
+ token: this.config.token,
745
+ configEndpoint: this.config.configEndpoint,
746
+ };
747
+ this.config = {
748
+ ...localOnlyConfig,
749
+ ...remoteConfigResponse.config,
750
+ };
751
+ // Update session timeout if provided in fresh config
752
+ if (remoteConfigResponse.config.sessionTimeout) {
753
+ this.identityManager.updateSessionTimeout(remoteConfigResponse.config.sessionTimeout);
754
+ }
755
+ if (this.config.debug) {
756
+ console.log('Journium: Background remote configuration applied:', remoteConfigResponse.config);
757
+ }
758
+ }
759
+ }
760
+ catch (error) {
761
+ if (this.config.debug) {
762
+ console.warn('Journium: Background remote config fetch failed:', error);
763
+ }
764
+ }
765
+ }
766
+ startFlushTimer() {
767
+ if (this.flushTimer) {
768
+ clearInterval(this.flushTimer);
769
+ }
770
+ this.flushTimer = window.setInterval(() => {
771
+ this.flush();
772
+ }, this.config.flushInterval);
773
+ }
774
+ async sendEvents(events) {
775
+ if (!events.length)
776
+ return;
777
+ try {
778
+ const response = await fetch(`${this.config.apiHost}/ingest_event`, {
779
+ method: 'POST',
780
+ headers: {
781
+ 'Content-Type': 'application/json',
782
+ 'Authorization': `Bearer ${this.config.token}`,
783
+ },
784
+ body: JSON.stringify({
785
+ events,
786
+ }),
787
+ });
788
+ if (!response.ok) {
789
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
790
+ }
791
+ if (this.config.debug) {
792
+ console.log('Journium: Successfully sent events', events);
793
+ }
794
+ }
795
+ catch (error) {
796
+ if (this.config.debug) {
797
+ console.error('Journium: Failed to send events', error);
798
+ }
799
+ throw error;
800
+ }
801
+ }
802
+ track(event, properties = {}) {
803
+ // Don't track if SDK is not properly configured
804
+ if (!this.config || !this.config.token || !this.config.apiHost || !this.initialized) {
805
+ return;
806
+ }
807
+ const identity = this.identityManager.getIdentity();
808
+ const userAgentInfo = this.identityManager.getUserAgentInfo();
809
+ // Create standardized event properties
810
+ const eventProperties = {
811
+ $device_id: identity === null || identity === void 0 ? void 0 : identity.$device_id,
812
+ distinct_id: identity === null || identity === void 0 ? void 0 : identity.distinct_id,
813
+ $session_id: identity === null || identity === void 0 ? void 0 : identity.$session_id,
814
+ $current_url: typeof window !== 'undefined' ? window.location.href : '',
815
+ $pathname: typeof window !== 'undefined' ? window.location.pathname : '',
816
+ ...userAgentInfo,
817
+ $lib_version: '0.1.0', // TODO: Get from package.json
818
+ $platform: 'web',
819
+ ...properties, // User-provided properties override defaults
820
+ };
821
+ const journiumEvent = {
822
+ uuid: generateUuidv7(),
823
+ ingestion_key: this.config.token,
824
+ client_timestamp: getCurrentTimestamp(),
825
+ event,
826
+ properties: eventProperties,
827
+ };
828
+ this.queue.push(journiumEvent);
829
+ if (this.config.debug) {
830
+ console.log('Journium: Event tracked', journiumEvent);
831
+ }
832
+ if (this.queue.length >= this.config.flushAt) {
833
+ this.flush();
834
+ }
835
+ }
836
+ async flush() {
837
+ // Don't flush if SDK is not properly configured
838
+ if (!this.config || !this.config.token || !this.config.apiHost) {
839
+ return;
840
+ }
841
+ if (this.queue.length === 0)
842
+ return;
843
+ const events = [...this.queue];
844
+ this.queue = [];
845
+ try {
846
+ await this.sendEvents(events);
847
+ }
848
+ catch (error) {
849
+ this.queue.unshift(...events);
850
+ throw error;
851
+ }
852
+ }
853
+ destroy() {
854
+ if (this.flushTimer) {
855
+ clearInterval(this.flushTimer);
856
+ this.flushTimer = null;
857
+ }
858
+ this.flush();
859
+ }
860
+ }
861
+
862
+ class PageviewTracker {
863
+ constructor(client) {
864
+ this.lastUrl = '';
865
+ this.originalPushState = null;
866
+ this.originalReplaceState = null;
867
+ this.popStateHandler = null;
868
+ this.client = client;
869
+ }
870
+ capturePageview(customProperties = {}) {
871
+ const currentUrl = getCurrentUrl();
872
+ const url = new URL(currentUrl);
873
+ const properties = {
874
+ $current_url: currentUrl,
875
+ $host: url.host,
876
+ $pathname: url.pathname,
877
+ $search: url.search,
878
+ $title: getPageTitle(),
879
+ $referrer: getReferrer(),
880
+ ...customProperties,
881
+ };
882
+ this.client.track('$pageview', properties);
883
+ this.lastUrl = currentUrl;
884
+ }
885
+ startAutoCapture() {
886
+ this.capturePageview();
887
+ if (typeof window !== 'undefined') {
888
+ // Store original methods for cleanup
889
+ this.originalPushState = window.history.pushState;
890
+ this.originalReplaceState = window.history.replaceState;
891
+ window.history.pushState = (...args) => {
892
+ this.originalPushState.apply(window.history, args);
893
+ setTimeout(() => this.capturePageview(), 0);
894
+ };
895
+ window.history.replaceState = (...args) => {
896
+ this.originalReplaceState.apply(window.history, args);
897
+ setTimeout(() => this.capturePageview(), 0);
898
+ };
899
+ this.popStateHandler = () => {
900
+ setTimeout(() => this.capturePageview(), 0);
901
+ };
902
+ window.addEventListener('popstate', this.popStateHandler);
903
+ }
904
+ }
905
+ stopAutoCapture() {
906
+ if (typeof window !== 'undefined') {
907
+ // Restore original methods
908
+ if (this.originalPushState) {
909
+ window.history.pushState = this.originalPushState;
910
+ this.originalPushState = null;
911
+ }
912
+ if (this.originalReplaceState) {
913
+ window.history.replaceState = this.originalReplaceState;
914
+ this.originalReplaceState = null;
915
+ }
916
+ if (this.popStateHandler) {
917
+ window.removeEventListener('popstate', this.popStateHandler);
918
+ this.popStateHandler = null;
919
+ }
920
+ }
921
+ }
922
+ }
923
+
924
+ class AutocaptureTracker {
925
+ constructor(client, config = {}) {
926
+ this.listeners = new Map();
927
+ this.isActive = false;
928
+ this.client = client;
929
+ this.config = {
930
+ captureClicks: true,
931
+ captureFormSubmits: true,
932
+ captureFormChanges: true,
933
+ captureTextSelection: false,
934
+ ignoreClasses: ['journium-ignore'],
935
+ ignoreElements: ['script', 'style', 'noscript'],
936
+ captureContentText: true,
937
+ ...config,
938
+ };
939
+ }
940
+ start() {
941
+ if (!isBrowser() || this.isActive) {
942
+ return;
943
+ }
944
+ this.isActive = true;
945
+ if (this.config.captureClicks) {
946
+ this.addClickListener();
947
+ }
948
+ if (this.config.captureFormSubmits) {
949
+ this.addFormSubmitListener();
950
+ }
951
+ if (this.config.captureFormChanges) {
952
+ this.addFormChangeListener();
953
+ }
954
+ if (this.config.captureTextSelection) {
955
+ this.addTextSelectionListener();
956
+ }
957
+ }
958
+ stop() {
959
+ if (!isBrowser() || !this.isActive) {
960
+ return;
961
+ }
962
+ this.isActive = false;
963
+ this.listeners.forEach((listener, event) => {
964
+ document.removeEventListener(event, listener, true);
965
+ });
966
+ this.listeners.clear();
967
+ }
968
+ addClickListener() {
969
+ const clickListener = (event) => {
970
+ const target = event.target;
971
+ if (this.shouldIgnoreElement(target)) {
972
+ return;
973
+ }
974
+ const properties = this.getElementProperties(target, 'click');
975
+ this.client.track('$autocapture', {
976
+ $event_type: 'click',
977
+ ...properties,
978
+ });
979
+ };
980
+ document.addEventListener('click', clickListener, true);
981
+ this.listeners.set('click', clickListener);
982
+ }
983
+ addFormSubmitListener() {
984
+ const submitListener = (event) => {
985
+ const target = event.target;
986
+ if (this.shouldIgnoreElement(target)) {
987
+ return;
988
+ }
989
+ const properties = this.getFormProperties(target, 'submit');
990
+ this.client.track('$autocapture', {
991
+ $event_type: 'submit',
992
+ ...properties,
993
+ });
994
+ };
995
+ document.addEventListener('submit', submitListener, true);
996
+ this.listeners.set('submit', submitListener);
997
+ }
998
+ addFormChangeListener() {
999
+ const changeListener = (event) => {
1000
+ const target = event.target;
1001
+ if (this.shouldIgnoreElement(target) || !this.isFormElement(target)) {
1002
+ return;
1003
+ }
1004
+ const properties = this.getInputProperties(target, 'change');
1005
+ this.client.track('$autocapture', {
1006
+ $event_type: 'change',
1007
+ ...properties,
1008
+ });
1009
+ };
1010
+ document.addEventListener('change', changeListener, true);
1011
+ this.listeners.set('change', changeListener);
1012
+ }
1013
+ addTextSelectionListener() {
1014
+ const selectionListener = () => {
1015
+ const selection = window.getSelection();
1016
+ if (!selection || selection.toString().trim().length === 0) {
1017
+ return;
1018
+ }
1019
+ const selectedText = selection.toString().trim();
1020
+ if (selectedText.length < 3) { // Ignore very short selections
1021
+ return;
1022
+ }
1023
+ this.client.track('$autocapture', {
1024
+ $event_type: 'text_selection',
1025
+ $selected_text: selectedText.substring(0, 200), // Limit text length
1026
+ $selection_length: selectedText.length,
1027
+ });
1028
+ };
1029
+ document.addEventListener('mouseup', selectionListener);
1030
+ this.listeners.set('mouseup', selectionListener);
1031
+ }
1032
+ shouldIgnoreElement(element) {
1033
+ var _a, _b, _c;
1034
+ if (!element || !element.tagName) {
1035
+ return true;
1036
+ }
1037
+ // Check if element should be ignored by tag name
1038
+ if ((_a = this.config.ignoreElements) === null || _a === void 0 ? void 0 : _a.includes(element.tagName.toLowerCase())) {
1039
+ return true;
1040
+ }
1041
+ // Check if element has ignore classes
1042
+ if ((_b = this.config.ignoreClasses) === null || _b === void 0 ? void 0 : _b.some(cls => element.classList.contains(cls))) {
1043
+ return true;
1044
+ }
1045
+ // Check parent elements for ignore classes
1046
+ let parent = element.parentElement;
1047
+ while (parent) {
1048
+ if ((_c = this.config.ignoreClasses) === null || _c === void 0 ? void 0 : _c.some(cls => parent.classList.contains(cls))) {
1049
+ return true;
1050
+ }
1051
+ parent = parent.parentElement;
1052
+ }
1053
+ return false;
1054
+ }
1055
+ isFormElement(element) {
1056
+ const formElements = ['input', 'select', 'textarea'];
1057
+ return formElements.includes(element.tagName.toLowerCase());
1058
+ }
1059
+ getElementProperties(element, eventType) {
1060
+ const properties = {
1061
+ $element_tag: element.tagName.toLowerCase(),
1062
+ $element_type: this.getElementType(element),
1063
+ };
1064
+ // Element identifiers
1065
+ if (element.id) {
1066
+ properties.$element_id = element.id;
1067
+ }
1068
+ if (element.className) {
1069
+ properties.$element_classes = Array.from(element.classList);
1070
+ }
1071
+ // Element attributes
1072
+ const relevantAttributes = ['name', 'role', 'aria-label', 'data-testid', 'data-track'];
1073
+ relevantAttributes.forEach(attr => {
1074
+ const value = element.getAttribute(attr);
1075
+ if (value) {
1076
+ properties[`$element_${attr.replace('-', '_')}`] = value;
1077
+ }
1078
+ });
1079
+ // Element content
1080
+ if (this.config.captureContentText) {
1081
+ const text = this.getElementText(element);
1082
+ if (text) {
1083
+ properties.$element_text = text.substring(0, 200); // Limit text length
1084
+ }
1085
+ }
1086
+ // Elements chain data
1087
+ const elementsChain = this.getElementsChain(element);
1088
+ properties.$elements_chain = elementsChain.chain;
1089
+ properties.$elements_chain_href = elementsChain.href;
1090
+ properties.$elements_chain_elements = elementsChain.elements;
1091
+ properties.$elements_chain_texts = elementsChain.texts;
1092
+ properties.$elements_chain_ids = elementsChain.ids;
1093
+ // Position information
1094
+ const rect = element.getBoundingClientRect();
1095
+ properties.$element_position = {
1096
+ x: Math.round(rect.left),
1097
+ y: Math.round(rect.top),
1098
+ width: Math.round(rect.width),
1099
+ height: Math.round(rect.height),
1100
+ };
1101
+ // Parent information
1102
+ if (element.parentElement) {
1103
+ properties.$parent_tag = element.parentElement.tagName.toLowerCase();
1104
+ if (element.parentElement.id) {
1105
+ properties.$parent_id = element.parentElement.id;
1106
+ }
1107
+ }
1108
+ // URL information
1109
+ properties.$current_url = window.location.href;
1110
+ properties.$host = window.location.host;
1111
+ properties.$pathname = window.location.pathname;
1112
+ return properties;
1113
+ }
1114
+ getFormProperties(form, eventType) {
1115
+ const properties = this.getElementProperties(form, eventType);
1116
+ // Form-specific properties
1117
+ properties.$form_method = form.method || 'get';
1118
+ properties.$form_action = form.action || '';
1119
+ // Count form elements
1120
+ const inputs = form.querySelectorAll('input, select, textarea');
1121
+ properties.$form_elements_count = inputs.length;
1122
+ // Form element types
1123
+ const elementTypes = {};
1124
+ inputs.forEach(input => {
1125
+ const type = this.getElementType(input);
1126
+ elementTypes[type] = (elementTypes[type] || 0) + 1;
1127
+ });
1128
+ properties.$form_element_types = elementTypes;
1129
+ return properties;
1130
+ }
1131
+ getInputProperties(input, eventType) {
1132
+ const properties = this.getElementProperties(input, eventType);
1133
+ // Input-specific properties
1134
+ properties.$input_type = input.type || 'text';
1135
+ if (input.name) {
1136
+ properties.$input_name = input.name;
1137
+ }
1138
+ if (input.placeholder) {
1139
+ properties.$input_placeholder = input.placeholder;
1140
+ }
1141
+ // Value information (be careful with sensitive data)
1142
+ if (this.isSafeInputType(input.type)) {
1143
+ if (input.type === 'checkbox' || input.type === 'radio') {
1144
+ properties.$input_checked = input.checked;
1145
+ }
1146
+ else if (input.value) {
1147
+ // For safe inputs, capture value length and basic characteristics
1148
+ properties.$input_value_length = input.value.length;
1149
+ properties.$input_has_value = input.value.length > 0;
1150
+ // For select elements, capture the selected value
1151
+ if (input.tagName.toLowerCase() === 'select') {
1152
+ properties.$input_selected_value = input.value;
1153
+ }
1154
+ }
1155
+ }
1156
+ // Form context
1157
+ const form = input.closest('form');
1158
+ if (form && form.id) {
1159
+ properties.$form_id = form.id;
1160
+ }
1161
+ return properties;
1162
+ }
1163
+ getElementType(element) {
1164
+ const tag = element.tagName.toLowerCase();
1165
+ if (tag === 'input') {
1166
+ return element.type || 'text';
1167
+ }
1168
+ if (tag === 'button') {
1169
+ return element.type || 'button';
1170
+ }
1171
+ return tag;
1172
+ }
1173
+ getElementText(element) {
1174
+ var _a, _b;
1175
+ // For buttons and links, get the visible text
1176
+ if (['button', 'a'].includes(element.tagName.toLowerCase())) {
1177
+ return ((_a = element.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1178
+ }
1179
+ // For inputs, get placeholder or label
1180
+ if (element.tagName.toLowerCase() === 'input') {
1181
+ const input = element;
1182
+ return input.placeholder || input.value || '';
1183
+ }
1184
+ // For other elements, get text content but limit it
1185
+ const text = ((_b = element.textContent) === null || _b === void 0 ? void 0 : _b.trim()) || '';
1186
+ return text.length > 50 ? text.substring(0, 47) + '...' : text;
1187
+ }
1188
+ getElementsChain(element) {
1189
+ var _a;
1190
+ const elements = [];
1191
+ const texts = [];
1192
+ const ids = [];
1193
+ let href = '';
1194
+ let current = element;
1195
+ while (current && current !== document.body) {
1196
+ // Element selector
1197
+ let selector = current.tagName.toLowerCase();
1198
+ // Add ID if present
1199
+ if (current.id) {
1200
+ selector += `#${current.id}`;
1201
+ ids.push(current.id);
1202
+ }
1203
+ else {
1204
+ ids.push('');
1205
+ }
1206
+ // Add classes if present
1207
+ if (current.className && typeof current.className === 'string') {
1208
+ const classes = current.className.trim().split(/\s+/).slice(0, 3); // Limit to first 3 classes
1209
+ if (classes.length > 0 && classes[0] !== '') {
1210
+ selector += '.' + classes.join('.');
1211
+ }
1212
+ }
1213
+ // Add nth-child if no ID (to make selector more specific)
1214
+ if (!current.id && current.parentElement) {
1215
+ const siblings = Array.from(current.parentElement.children)
1216
+ .filter(child => child.tagName === current.tagName);
1217
+ if (siblings.length > 1) {
1218
+ const index = siblings.indexOf(current) + 1;
1219
+ selector += `:nth-child(${index})`;
1220
+ }
1221
+ }
1222
+ elements.push(selector);
1223
+ // Extract text content
1224
+ let text = '';
1225
+ if (current.tagName.toLowerCase() === 'a') {
1226
+ text = ((_a = current.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
1227
+ // Capture href for links
1228
+ if (!href && current.getAttribute('href')) {
1229
+ href = current.getAttribute('href') || '';
1230
+ }
1231
+ }
1232
+ else if (['button', 'span', 'div'].includes(current.tagName.toLowerCase())) {
1233
+ // For buttons and text elements, get direct text content (not including children)
1234
+ const directText = Array.from(current.childNodes)
1235
+ .filter(node => node.nodeType === Node.TEXT_NODE)
1236
+ .map(node => { var _a; return (_a = node.textContent) === null || _a === void 0 ? void 0 : _a.trim(); })
1237
+ .join(' ')
1238
+ .trim();
1239
+ text = directText || '';
1240
+ }
1241
+ else if (current.tagName.toLowerCase() === 'input') {
1242
+ const input = current;
1243
+ text = input.placeholder || input.value || '';
1244
+ }
1245
+ // Limit text length and clean it
1246
+ text = text.substring(0, 100).replace(/\s+/g, ' ').trim();
1247
+ texts.push(text);
1248
+ current = current.parentElement;
1249
+ }
1250
+ // Build the chain string (reverse order so it goes from parent to child)
1251
+ const chain = elements.reverse().join(' > ');
1252
+ return {
1253
+ chain,
1254
+ href,
1255
+ elements: elements,
1256
+ texts: texts.reverse(),
1257
+ ids: ids.reverse()
1258
+ };
1259
+ }
1260
+ isSafeInputType(type) {
1261
+ // Don't capture values for sensitive input types
1262
+ const sensitiveTypes = ['password', 'email', 'tel', 'credit-card-number'];
1263
+ return !sensitiveTypes.includes(type.toLowerCase());
1264
+ }
1265
+ }
1266
+
1267
+ class Journium {
1268
+ constructor(config) {
1269
+ this.config = config;
1270
+ this.client = new JourniumClient(config);
1271
+ this.pageviewTracker = new PageviewTracker(this.client);
1272
+ const autocaptureConfig = this.resolveAutocaptureConfig(config.autocapture);
1273
+ this.autocaptureTracker = new AutocaptureTracker(this.client, autocaptureConfig);
1274
+ }
1275
+ resolveAutocaptureConfig(autocapture) {
1276
+ if (autocapture === false || autocapture === undefined) {
1277
+ return {
1278
+ captureClicks: false,
1279
+ captureFormSubmits: false,
1280
+ captureFormChanges: false,
1281
+ captureTextSelection: false,
1282
+ };
1283
+ }
1284
+ if (autocapture === true) {
1285
+ return {}; // Use default configuration
1286
+ }
1287
+ return autocapture;
1288
+ }
1289
+ track(event, properties) {
1290
+ this.client.track(event, properties);
1291
+ }
1292
+ capturePageview(properties) {
1293
+ this.pageviewTracker.capturePageview(properties);
1294
+ }
1295
+ startAutoCapture() {
1296
+ this.pageviewTracker.startAutoCapture();
1297
+ if (this.config.autocapture) {
1298
+ this.autocaptureTracker.start();
1299
+ }
1300
+ }
1301
+ stopAutoCapture() {
1302
+ this.pageviewTracker.stopAutoCapture();
1303
+ this.autocaptureTracker.stop();
1304
+ }
1305
+ // Aliases for consistency (deprecated - use startAutoCapture)
1306
+ /** @deprecated Use startAutoCapture() instead */
1307
+ startAutocapture() {
1308
+ this.startAutoCapture();
1309
+ }
1310
+ /** @deprecated Use stopAutoCapture() instead */
1311
+ stopAutocapture() {
1312
+ this.stopAutoCapture();
1313
+ }
1314
+ async flush() {
1315
+ return this.client.flush();
1316
+ }
1317
+ destroy() {
1318
+ this.pageviewTracker.stopAutoCapture();
1319
+ this.autocaptureTracker.stop();
1320
+ this.client.destroy();
1321
+ }
1322
+ }
1323
+ const init = (config) => {
1324
+ return new Journium(config);
1325
+ };
1326
+
1327
+ const JourniumContext = createContext({ journium: null });
1328
+ const JourniumProvider = ({ children, config, autoCapture = true, }) => {
1329
+ const journiumRef = useRef(null);
1330
+ useEffect(() => {
1331
+ if (!journiumRef.current) {
1332
+ journiumRef.current = new Journium(config);
1333
+ if (autoCapture) {
1334
+ journiumRef.current.startAutoCapture();
1335
+ }
1336
+ }
1337
+ return () => {
1338
+ if (journiumRef.current) {
1339
+ journiumRef.current.destroy();
1340
+ journiumRef.current = null;
1341
+ }
1342
+ };
1343
+ }, [config, autoCapture]);
1344
+ // Note: All pageview tracking is handled by startAutoCapture() when autoCapture=true
1345
+ // When autoCapture=false, users should call capturePageview() manually as needed
1346
+ return (React.createElement(JourniumContext.Provider, { value: { journium: journiumRef.current } }, children));
1347
+ };
1348
+ const useJournium = () => {
1349
+ const context = useContext(JourniumContext);
1350
+ if (!context) {
1351
+ throw new Error('useJournium must be used within a JourniumProvider');
1352
+ }
1353
+ return context;
1354
+ };
1355
+
1356
+ const useTrackEvent = () => {
1357
+ const { journium } = useJournium();
1358
+ return useCallback((event, properties) => {
1359
+ if (journium) {
1360
+ journium.track(event, properties);
1361
+ }
1362
+ }, [journium]);
1363
+ };
1364
+ const useTrackPageview = () => {
1365
+ const { journium } = useJournium();
1366
+ return useCallback((properties) => {
1367
+ if (journium) {
1368
+ journium.capturePageview(properties);
1369
+ }
1370
+ }, [journium]);
1371
+ };
1372
+ const useAutoTrackPageview = (dependencies = [], properties) => {
1373
+ const trackPageview = useTrackPageview();
1374
+ useEffect(() => {
1375
+ trackPageview(properties);
1376
+ }, dependencies);
1377
+ };
1378
+ const useAutocapture = () => {
1379
+ const { journium } = useJournium();
1380
+ const startAutocapture = useCallback(() => {
1381
+ if (journium) {
1382
+ journium.startAutocapture();
1383
+ }
1384
+ }, [journium]);
1385
+ const stopAutocapture = useCallback(() => {
1386
+ if (journium) {
1387
+ journium.stopAutocapture();
1388
+ }
1389
+ }, [journium]);
1390
+ return { startAutocapture, stopAutocapture };
1391
+ };
1392
+ const useAutoTrackClicks = (enabled = true, config) => {
1393
+ const { journium } = useJournium();
1394
+ useEffect(() => {
1395
+ if (journium && enabled) {
1396
+ // Use startAutoCapture for consistency (includes both pageview + clicks)
1397
+ journium.startAutoCapture();
1398
+ return () => {
1399
+ journium.stopAutoCapture();
1400
+ };
1401
+ }
1402
+ return undefined;
1403
+ }, [journium, enabled]);
1404
+ };
1405
+
1406
+ export { AutocaptureTracker, BrowserIdentityManager, Journium, JourniumClient, JourniumProvider, PageviewTracker, fetchRemoteConfig, generateId, generateUuidv7, getCurrentTimestamp, getCurrentUrl, getPageTitle, getReferrer, init, isBrowser, isNode, mergeConfigs, useAutoTrackClicks, useAutoTrackPageview, useAutocapture, useJournium, useTrackEvent, useTrackPageview };
1407
+ //# sourceMappingURL=index.esm.js.map