@nexushub/client 0.4.0 → 0.4.2

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,2643 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
2
+
3
+ // src/config.ts
4
+ var DEFAULT_API_URL = "https://endpoints.gnexus.co.tz";
5
+ var DEFAULT_ANALYTICS_URL = "https://sentry.gnexus.co.tz";
6
+ var LOCAL_NEST_URL = "https://endpoints.gnexus.co.tz";
7
+ var LOCAL_RUST_URL = "https://sentry.gnexus.co.tz";
8
+ var getEnvConfig = () => {
9
+ const NEXT_PUBLIC_ID = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_ID : void 0;
10
+ const NEXT_PUBLIC_KEY = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_KEY : void 0;
11
+ const NEXT_PUBLIC_URL = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_NEXUS_API_URL : void 0;
12
+ const NODE_ID = typeof process !== "undefined" ? process.env.NEXUS_PROJECT_ID : void 0;
13
+ const NODE_KEY = typeof process !== "undefined" ? process.env.NEXUS_API_KEY : void 0;
14
+ const NODE_URL = typeof process !== "undefined" ? process.env.NEXUS_API_URL : void 0;
15
+ const NODE_ENV = typeof process !== "undefined" ? process.env.NODE_ENV : "production";
16
+ const isDev = NODE_ENV === "development" || typeof window !== "undefined" && window.location.hostname === "localhost";
17
+ const projectId = _nullishCoalesce(NEXT_PUBLIC_ID, () => ( NODE_ID));
18
+ const apiKey = _nullishCoalesce(NEXT_PUBLIC_KEY, () => ( NODE_KEY));
19
+ const apiUrl = _nullishCoalesce(_nullishCoalesce(NEXT_PUBLIC_URL, () => ( NODE_URL)), () => ( (isDev ? LOCAL_NEST_URL : DEFAULT_API_URL)));
20
+ const analyticsUrl = apiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL;
21
+ return {
22
+ projectId,
23
+ apiKey,
24
+ apiUrl,
25
+ analyticsUrl
26
+ };
27
+ };
28
+ var mergeConfigs = (base, override) => {
29
+ const mergedApiUrl = override.apiUrl || base.apiUrl || DEFAULT_API_URL;
30
+ const mergedAnalyticsUrl = override.analyticsUrl || base.analyticsUrl || (mergedApiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL);
31
+ return {
32
+ ...base,
33
+ ...override,
34
+ apiUrl: mergedApiUrl,
35
+ analyticsUrl: mergedAnalyticsUrl,
36
+ projectId: override.projectId || base.projectId,
37
+ apiKey: override.apiKey || base.apiKey
38
+ };
39
+ };
40
+ var getFullConfig = (partialConfig) => {
41
+ const envConfig = getEnvConfig();
42
+ return mergeConfigs(envConfig, partialConfig || {});
43
+ };
44
+ var validateConfig = (config) => {
45
+ const errors = [];
46
+ if (!config.projectId) errors.push("Missing projectId");
47
+ if (!config.apiUrl) errors.push("Missing apiUrl");
48
+ return errors;
49
+ };
50
+
51
+ // src/content/cache-implementations.ts
52
+ var CacheTags = {
53
+ project: (projectId) => `nexus_project_${projectId}`,
54
+ content: (slug) => `content_${slug}`,
55
+ collection: (collectionId) => `collection_${collectionId}`,
56
+ global: "nexus_global_config",
57
+ user: (userId) => `user_${userId}`,
58
+ media: (mediaId) => `media_${mediaId}`
59
+ };
60
+ var MemoryCache = class {
61
+ constructor(options = {}) {
62
+ this.cache = /* @__PURE__ */ new Map();
63
+ this.tagIndex = /* @__PURE__ */ new Map();
64
+ this.stats = {
65
+ size: 0,
66
+ hits: 0,
67
+ misses: 0,
68
+ hitRate: 0,
69
+ evictions: 0
70
+ };
71
+ this.maxSize = options.maxSize || 1e3;
72
+ this.defaultTTL = options.ttl || 5 * 60 * 1e3;
73
+ }
74
+ set(key, data, options = {}) {
75
+ if (this.cache.size >= this.maxSize) {
76
+ this.evictLRU();
77
+ }
78
+ const metadata = {
79
+ timestamp: Date.now(),
80
+ expiresAt: Date.now() + (options.ttl || this.defaultTTL),
81
+ tags: options.tags || [],
82
+ size: this.calculateSize(data)
83
+ };
84
+ this.cache.set(key, { data, metadata });
85
+ this.stats.size = this.cache.size;
86
+ metadata.tags.forEach((tag) => {
87
+ if (!this.tagIndex.has(tag)) {
88
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
89
+ }
90
+ this.tagIndex.get(tag).add(key);
91
+ });
92
+ }
93
+ get(key) {
94
+ const entry = this.cache.get(key);
95
+ if (!entry) {
96
+ this.stats.misses++;
97
+ this.updateHitRate();
98
+ return null;
99
+ }
100
+ if (Date.now() > entry.metadata.expiresAt) {
101
+ this.delete(key);
102
+ this.stats.misses++;
103
+ this.updateHitRate();
104
+ return null;
105
+ }
106
+ entry.metadata.timestamp = Date.now();
107
+ this.stats.hits++;
108
+ this.updateHitRate();
109
+ return entry;
110
+ }
111
+ delete(key) {
112
+ const entry = this.cache.get(key);
113
+ if (!entry) return false;
114
+ entry.metadata.tags.forEach((tag) => {
115
+ const keys = this.tagIndex.get(tag);
116
+ if (keys) {
117
+ keys.delete(key);
118
+ if (keys.size === 0) {
119
+ this.tagIndex.delete(tag);
120
+ }
121
+ }
122
+ });
123
+ this.cache.delete(key);
124
+ this.stats.size = this.cache.size;
125
+ return true;
126
+ }
127
+ invalidateByTags(tags) {
128
+ const keysToDelete = /* @__PURE__ */ new Set();
129
+ tags.forEach((tag) => {
130
+ const keys = this.tagIndex.get(tag);
131
+ if (keys) {
132
+ keys.forEach((key) => keysToDelete.add(key));
133
+ this.tagIndex.delete(tag);
134
+ }
135
+ });
136
+ keysToDelete.forEach((key) => this.delete(key));
137
+ if (process.env.NODE_ENV === "development") {
138
+ console.log(
139
+ `[MemoryCache] Invalidated ${keysToDelete.size} entries by tags: ${tags.join(", ")}`
140
+ );
141
+ }
142
+ }
143
+ clear() {
144
+ this.cache.clear();
145
+ this.tagIndex.clear();
146
+ this.stats = {
147
+ size: 0,
148
+ hits: 0,
149
+ misses: 0,
150
+ hitRate: 0,
151
+ evictions: 0
152
+ };
153
+ }
154
+ getStats() {
155
+ return { ...this.stats };
156
+ }
157
+ evictLRU() {
158
+ let oldestKey = null;
159
+ let oldestTime = Infinity;
160
+ for (const [key, entry] of this.cache.entries()) {
161
+ if (entry.metadata.timestamp < oldestTime) {
162
+ oldestTime = entry.metadata.timestamp;
163
+ oldestKey = key;
164
+ }
165
+ }
166
+ if (oldestKey) {
167
+ this.delete(oldestKey);
168
+ this.stats.evictions++;
169
+ }
170
+ }
171
+ calculateSize(data) {
172
+ try {
173
+ const jsonString = JSON.stringify(data);
174
+ return new Blob([jsonString]).size;
175
+ } catch (e2) {
176
+ return 0;
177
+ }
178
+ }
179
+ updateHitRate() {
180
+ const total = this.stats.hits + this.stats.misses;
181
+ this.stats.hitRate = total > 0 ? this.stats.hits / total : 0;
182
+ }
183
+ };
184
+ var BrowserCache = class {
185
+ constructor(projectId) {
186
+ this.projectId = projectId;
187
+ this.prefix = "nexushub_";
188
+ this.maxSize = 5 * 1024 * 1024;
189
+ // 5MB standard LocalStorage limit
190
+ this.currentSize = 0;
191
+ if (typeof window !== "undefined") {
192
+ this.calculateCurrentSize();
193
+ }
194
+ }
195
+ set(key, data, ttl = 5 * 60 * 1e3) {
196
+ if (typeof window === "undefined") return;
197
+ const storageKey = this.getStorageKey(key);
198
+ const entry = {
199
+ data,
200
+ metadata: {
201
+ timestamp: Date.now(),
202
+ expiresAt: Date.now() + ttl,
203
+ size: this.calculateStorageSize(data)
204
+ }
205
+ };
206
+ const serialized = JSON.stringify(entry);
207
+ const newSize = new Blob([serialized]).size;
208
+ if (this.currentSize + newSize > this.maxSize) {
209
+ this.evictOldest();
210
+ }
211
+ try {
212
+ localStorage.setItem(storageKey, serialized);
213
+ this.currentSize += newSize;
214
+ } catch (error) {
215
+ console.warn("[BrowserCache] Failed to save to localStorage:", error);
216
+ this.evictOldest();
217
+ try {
218
+ localStorage.setItem(storageKey, serialized);
219
+ } catch (e) {
220
+ }
221
+ }
222
+ }
223
+ get(key) {
224
+ if (typeof window === "undefined") return null;
225
+ const storageKey = this.getStorageKey(key);
226
+ const item = localStorage.getItem(storageKey);
227
+ if (!item) return null;
228
+ try {
229
+ const entry = JSON.parse(item);
230
+ if (Date.now() > entry.metadata.expiresAt) {
231
+ this.delete(key);
232
+ return null;
233
+ }
234
+ return entry.data;
235
+ } catch (e3) {
236
+ this.delete(key);
237
+ return null;
238
+ }
239
+ }
240
+ delete(key) {
241
+ if (typeof window === "undefined") return;
242
+ const storageKey = this.getStorageKey(key);
243
+ const item = localStorage.getItem(storageKey);
244
+ if (item) {
245
+ this.currentSize -= new Blob([item]).size;
246
+ }
247
+ localStorage.removeItem(storageKey);
248
+ }
249
+ clear() {
250
+ if (typeof window === "undefined") return;
251
+ const keysToRemove = [];
252
+ for (let i = 0; i < localStorage.length; i++) {
253
+ const key = localStorage.key(i);
254
+ if (_optionalChain([key, 'optionalAccess', _ => _.startsWith, 'call', _2 => _2(this.prefix)])) {
255
+ keysToRemove.push(key);
256
+ }
257
+ }
258
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
259
+ this.currentSize = 0;
260
+ }
261
+ getStorageKey(key) {
262
+ return `${this.prefix}${this.projectId}_${key}`;
263
+ }
264
+ calculateCurrentSize() {
265
+ this.currentSize = 0;
266
+ for (let i = 0; i < localStorage.length; i++) {
267
+ const key = localStorage.key(i);
268
+ if (_optionalChain([key, 'optionalAccess', _3 => _3.startsWith, 'call', _4 => _4(this.prefix)])) {
269
+ const item = localStorage.getItem(key);
270
+ if (item) {
271
+ this.currentSize += new Blob([item]).size;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ calculateStorageSize(data) {
277
+ return new Blob([JSON.stringify(data)]).size;
278
+ }
279
+ evictOldest() {
280
+ let oldestKey = null;
281
+ let oldestTime = Infinity;
282
+ for (let i = 0; i < localStorage.length; i++) {
283
+ const key = localStorage.key(i);
284
+ if (_optionalChain([key, 'optionalAccess', _5 => _5.startsWith, 'call', _6 => _6(this.prefix)])) {
285
+ const item = localStorage.getItem(key);
286
+ if (item) {
287
+ try {
288
+ const entry = JSON.parse(item);
289
+ if (entry.metadata.timestamp < oldestTime) {
290
+ oldestTime = entry.metadata.timestamp;
291
+ oldestKey = key;
292
+ }
293
+ } catch (e4) {
294
+ localStorage.removeItem(key);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ if (oldestKey) {
300
+ const item = localStorage.getItem(oldestKey);
301
+ if (item) {
302
+ this.currentSize -= new Blob([item]).size;
303
+ }
304
+ localStorage.removeItem(oldestKey);
305
+ }
306
+ }
307
+ };
308
+
309
+ // src/content/cache.ts
310
+ var LocalCacheProxy = class {
311
+ constructor(cachePath) {
312
+ this.instance = null;
313
+ this.cachePath = cachePath;
314
+ }
315
+ async getInstance() {
316
+ if (this.instance) return this.instance;
317
+ if (typeof window === "undefined") {
318
+ const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./content/local-cache-server.cjs")));
319
+ this.instance = new mod.LocalCache(this.cachePath);
320
+ } else {
321
+ const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("./content/local-cache-client.cjs")));
322
+ this.instance = new mod.LocalCache(this.cachePath);
323
+ }
324
+ return this.instance;
325
+ }
326
+ isLoaded() {
327
+ return _optionalChain([this, 'access', _7 => _7.instance, 'optionalAccess', _8 => _8.isLoaded, 'call', _9 => _9()]) || false;
328
+ }
329
+ async getPage(slug) {
330
+ const inst = await this.getInstance();
331
+ return inst.getPage(slug);
332
+ }
333
+ async getCollection(id) {
334
+ const inst = await this.getInstance();
335
+ return inst.getCollection(id);
336
+ }
337
+ async getGlobals() {
338
+ const inst = await this.getInstance();
339
+ return inst.getGlobals();
340
+ }
341
+ async getAllData() {
342
+ const inst = await this.getInstance();
343
+ return inst.getAllData();
344
+ }
345
+ };
346
+
347
+ // src/content/strategies.ts
348
+ var RateLimiter = class {
349
+ constructor(config) {
350
+ this.requests = [];
351
+ this.config = config;
352
+ }
353
+ async checkLimit() {
354
+ while (true) {
355
+ const now = Date.now();
356
+ const windowStart = now - this.config.timeWindow;
357
+ this.requests = this.requests.filter((time) => time > windowStart);
358
+ if (this.requests.length < this.config.maxRequests) {
359
+ this.requests.push(now);
360
+ return;
361
+ }
362
+ const oldestRequest = this.requests[0];
363
+ const waitTime = oldestRequest + this.config.timeWindow - now;
364
+ if (waitTime > 0) {
365
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
366
+ } else {
367
+ }
368
+ }
369
+ }
370
+ getStats() {
371
+ const now = Date.now();
372
+ const windowStart = now - this.config.timeWindow;
373
+ const currentRequests = this.requests.filter(
374
+ (time) => time > windowStart
375
+ ).length;
376
+ return { currentRequests, limit: this.config.maxRequests };
377
+ }
378
+ };
379
+ var ExponentialBackoff = class {
380
+ constructor(config) {
381
+ this.config = { jitter: true, ...config };
382
+ }
383
+ async execute(fn, onRetry) {
384
+ let lastError = new Error("Unknown error");
385
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
386
+ try {
387
+ return await fn();
388
+ } catch (error) {
389
+ lastError = error;
390
+ if (this.isClientError(error) && !this.isRateLimitError(error)) {
391
+ throw error;
392
+ }
393
+ if (attempt === this.config.maxRetries) break;
394
+ const delay = this.calculateDelay(attempt);
395
+ if (onRetry) onRetry(attempt + 1, delay, error);
396
+ await new Promise((resolve) => setTimeout(resolve, delay));
397
+ }
398
+ }
399
+ throw lastError;
400
+ }
401
+ calculateDelay(attempt) {
402
+ let delay = this.config.baseDelay * Math.pow(2, attempt);
403
+ delay = Math.min(delay, this.config.maxDelay);
404
+ if (this.config.jitter) {
405
+ delay = delay * (0.5 + Math.random());
406
+ }
407
+ return delay;
408
+ }
409
+ isClientError(error) {
410
+ return _optionalChain([error, 'optionalAccess', _10 => _10.status]) >= 400 && _optionalChain([error, 'optionalAccess', _11 => _11.status]) < 500;
411
+ }
412
+ isRateLimitError(error) {
413
+ return _optionalChain([error, 'optionalAccess', _12 => _12.status]) === 429;
414
+ }
415
+ };
416
+ var CircuitBreaker = class {
417
+ constructor() {
418
+ this.state = 0 /* CLOSED */;
419
+ this.failures = 0;
420
+ this.lastFailureTime = 0;
421
+ this.failureThreshold = 5;
422
+ this.resetTimeout = 3e4;
423
+ }
424
+ // 30 seconds
425
+ isOpen() {
426
+ if (this.state === 1 /* OPEN */) {
427
+ if (Date.now() - this.lastFailureTime > this.resetTimeout) {
428
+ this.state = 2 /* HALF_OPEN */;
429
+ return false;
430
+ }
431
+ return true;
432
+ }
433
+ return false;
434
+ }
435
+ recordSuccess() {
436
+ this.failures = 0;
437
+ this.state = 0 /* CLOSED */;
438
+ }
439
+ recordFailure() {
440
+ this.failures++;
441
+ this.lastFailureTime = Date.now();
442
+ if (this.failures >= this.failureThreshold) {
443
+ this.state = 1 /* OPEN */;
444
+ if (process.env.NODE_ENV === "development") {
445
+ console.warn(
446
+ "[NexusHub] \u{1F50C} Circuit Breaker OPEN. Pausing network requests."
447
+ );
448
+ }
449
+ }
450
+ }
451
+ };
452
+ var RequestBatcher = class {
453
+ constructor(batchWindow = 10, maxBatchSize = 20) {
454
+ this.batchWindow = batchWindow;
455
+ this.maxBatchSize = maxBatchSize;
456
+ this.batch = [];
457
+ this.processing = false;
458
+ }
459
+ async schedule(key, request) {
460
+ return new Promise((resolve, reject) => {
461
+ this.batch.push({ key, resolve, reject });
462
+ if (this.batch.length >= this.maxBatchSize) {
463
+ this.processBatch(request);
464
+ } else if (!this.batchTimeout) {
465
+ this.batchTimeout = setTimeout(
466
+ () => this.processBatch(request),
467
+ this.batchWindow
468
+ );
469
+ }
470
+ });
471
+ }
472
+ async processBatch(request) {
473
+ if (this.processing || this.batch.length === 0) return;
474
+ this.processing = true;
475
+ if (this.batchTimeout) {
476
+ clearTimeout(this.batchTimeout);
477
+ this.batchTimeout = void 0;
478
+ }
479
+ const currentBatch = [...this.batch];
480
+ this.batch = [];
481
+ try {
482
+ const result = await request();
483
+ currentBatch.forEach((item) => item.resolve(result));
484
+ } catch (error) {
485
+ currentBatch.forEach((item) => item.reject(error));
486
+ } finally {
487
+ this.processing = false;
488
+ if (this.batch.length > 0) {
489
+ setTimeout(() => this.processBatch(request), 0);
490
+ }
491
+ }
492
+ }
493
+ };
494
+
495
+ // src/content/utils.ts
496
+ function validateSlug(slug) {
497
+ if (!slug || typeof slug !== "string") {
498
+ throw new Error("Slug must be a non-empty string");
499
+ }
500
+ if (!/^[a-z0-9-_]+$/.test(slug)) {
501
+ throw new Error("Slug can only contain lowercase letters, numbers, hyphens, and underscores");
502
+ }
503
+ }
504
+ function normalizeQuery(query) {
505
+ const normalized = { ...query };
506
+ normalized.page = Math.max(1, normalized.page || 1);
507
+ normalized.limit = Math.min(100, Math.max(1, normalized.limit || 10));
508
+ normalized.order = normalized.order || "desc";
509
+ if (normalized.page < 1) {
510
+ throw new Error("Page must be greater than 0");
511
+ }
512
+ if (normalized.limit < 1 || normalized.limit > 100) {
513
+ throw new Error("Limit must be between 1 and 100");
514
+ }
515
+ return normalized;
516
+ }
517
+ function buildQueryString(query) {
518
+ const params = new URLSearchParams();
519
+ if (query.page) params.append("page", query.page.toString());
520
+ if (query.limit) params.append("limit", query.limit.toString());
521
+ if (query.sort) params.append("sort", query.sort);
522
+ if (query.order) params.append("order", query.order);
523
+ if (query.search) params.append("search", query.search);
524
+ if (_optionalChain([query, 'access', _13 => _13.include, 'optionalAccess', _14 => _14.length])) {
525
+ params.append("include", query.include.join(","));
526
+ }
527
+ if (_optionalChain([query, 'access', _15 => _15.fields, 'optionalAccess', _16 => _16.length])) {
528
+ params.append("fields", query.fields.join(","));
529
+ }
530
+ if (query.filter) {
531
+ params.append("filter", JSON.stringify(query.filter));
532
+ }
533
+ return params.toString();
534
+ }
535
+ function measurePerformance(name, fn) {
536
+ const start = performance.now();
537
+ const result = fn();
538
+ const end = performance.now();
539
+ if (process.env.NODE_ENV === "development") {
540
+ console.log(`\u23F1\uFE0F ${name}: ${(end - start).toFixed(2)}ms`);
541
+ }
542
+ return { result, duration: end - start };
543
+ }
544
+
545
+ // src/content/index.ts
546
+ var ContentEngine = class {
547
+ constructor(config) {
548
+ this.config = config;
549
+ this.isServer = typeof window === "undefined";
550
+ this.localCache = new LocalCacheProxy();
551
+ this.memoryCache = new MemoryCache({
552
+ maxSize: 500,
553
+ ttl: 5 * 60 * 1e3
554
+ // 5 minutes
555
+ });
556
+ if (!this.isServer) {
557
+ this.browserCache = new BrowserCache(config.projectId);
558
+ }
559
+ this.rateLimiter = new RateLimiter({
560
+ maxRequests: config.debug ? 100 : 50,
561
+ timeWindow: 6e4
562
+ });
563
+ this.backoff = new ExponentialBackoff({
564
+ maxRetries: config.retries || 3,
565
+ baseDelay: 100,
566
+ maxDelay: 5e3,
567
+ jitter: true
568
+ });
569
+ this.requestBatcher = new RequestBatcher(20, 50);
570
+ this.circuitBreaker = new CircuitBreaker();
571
+ this.defaultRevalidate = config.revalidateTime || 60;
572
+ this.cacheStrategy = config.cacheStrategy || "memory";
573
+ if (!this.isServer) {
574
+ window.addEventListener("beforeunload", this.cleanup.bind(this));
575
+ }
576
+ }
577
+ /**
578
+ * Fetch a Single Page with full strategy pipeline
579
+ */
580
+ async getPage(slug, options = {}) {
581
+ const { result, duration } = measurePerformance(
582
+ `getPage("${slug}")`,
583
+ () => this._getPage(slug, options)
584
+ );
585
+ if (this.config.debug && duration > 100) {
586
+ console.warn(
587
+ `[NexusHub] \u26A0\uFE0F getPage("${slug}") took ${duration.toFixed(2)}ms`
588
+ );
589
+ }
590
+ return result;
591
+ }
592
+ async _getPage(slug, options = {}) {
593
+ validateSlug(slug);
594
+ const {
595
+ revalidate = this.defaultRevalidate,
596
+ tags = [],
597
+ forceRefresh = false,
598
+ includeMetadata = false
599
+ } = options;
600
+ const cacheKey = `page:${slug}`;
601
+ const cached = await this.checkCaches(
602
+ cacheKey,
603
+ forceRefresh,
604
+ includeMetadata
605
+ );
606
+ if (cached) {
607
+ if (this.config.debug) console.log(`[NexusHub] \u26A1 Cache hit: ${slug}`);
608
+ return includeMetadata ? cached : cached.data;
609
+ }
610
+ if (this.circuitBreaker.isOpen()) {
611
+ throw new Error(`[NexusHub] Circuit open. API is unavailable.`);
612
+ }
613
+ try {
614
+ await this.rateLimiter.checkLimit();
615
+ const data = await this.backoff.execute(
616
+ async () => {
617
+ return this.fetchPage(
618
+ slug,
619
+ cacheKey,
620
+ tags,
621
+ revalidate,
622
+ forceRefresh
623
+ );
624
+ },
625
+ (attempt, delay, error) => {
626
+ if (this.config.debug) {
627
+ console.log(
628
+ `[NexusHub] \u{1F504} Retry ${attempt} for '${slug}' after ${delay}ms: ${error.message}`
629
+ );
630
+ }
631
+ }
632
+ );
633
+ this.circuitBreaker.recordSuccess();
634
+ return includeMetadata ? data : data.data;
635
+ } catch (error) {
636
+ this.circuitBreaker.recordFailure();
637
+ const staleCache = this.memoryCache.get(cacheKey);
638
+ if (staleCache && !forceRefresh) {
639
+ console.warn(`[NexusHub] \u26A0\uFE0F Serving stale content for '${slug}'`);
640
+ return includeMetadata ? staleCache : staleCache.data;
641
+ }
642
+ throw this.normalizeError(error, `Failed to fetch page '${slug}'`);
643
+ }
644
+ }
645
+ /**
646
+ * Fetch a Collection (Optimized)
647
+ */
648
+ async getCollection(collectionId, query = {}, options = {}) {
649
+ const { result, duration } = measurePerformance(
650
+ `getCollection("${collectionId}")`,
651
+ () => this._getCollection(collectionId, query, options)
652
+ );
653
+ if (this.config.debug && duration > 100) {
654
+ console.warn(
655
+ `[NexusHub] \u26A0\uFE0F getCollection("${collectionId}") took ${duration.toFixed(2)}ms`
656
+ );
657
+ }
658
+ return result;
659
+ }
660
+ async _getCollection(collectionId, query = {}, options = {}) {
661
+ const normalizedQuery = normalizeQuery(query);
662
+ const {
663
+ revalidate = this.defaultRevalidate,
664
+ tags = [],
665
+ forceRefresh = false,
666
+ includeMetadata = false
667
+ } = options;
668
+ const queryString = buildQueryString(normalizedQuery);
669
+ const cacheKey = `collection:${collectionId}:${queryString}`;
670
+ const cached = await this.checkCaches(
671
+ cacheKey,
672
+ forceRefresh,
673
+ includeMetadata
674
+ );
675
+ if (cached) {
676
+ if (this.config.debug) {
677
+ console.log(
678
+ `[NexusHub] \u26A1 Served collection '${collectionId}' from memory cache.`
679
+ );
680
+ }
681
+ return includeMetadata ? cached : cached.data;
682
+ }
683
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
684
+ const localCollection = await this.localCache.getCollection(collectionId);
685
+ if (localCollection) {
686
+ const result = this.applyLocalQuery(
687
+ localCollection,
688
+ normalizedQuery
689
+ );
690
+ if (this.config.debug) {
691
+ console.log(
692
+ `[NexusHub] \u{1F4C1} Served collection '${collectionId}' from local cache.`
693
+ );
694
+ }
695
+ this.memoryCache.set(cacheKey, result, {
696
+ tags: [...tags, CacheTags.collection(collectionId)],
697
+ revalidate
698
+ });
699
+ return result;
700
+ }
701
+ }
702
+ if (this.circuitBreaker.isOpen()) throw new Error("Circuit open");
703
+ try {
704
+ await this.rateLimiter.checkLimit();
705
+ const result = await this.backoff.execute(async () => {
706
+ return this.fetchCollection(
707
+ collectionId,
708
+ normalizedQuery,
709
+ cacheKey,
710
+ tags,
711
+ revalidate
712
+ );
713
+ });
714
+ this.circuitBreaker.recordSuccess();
715
+ return includeMetadata ? result : result.data;
716
+ } catch (error) {
717
+ this.circuitBreaker.recordFailure();
718
+ const staleCache = this.memoryCache.get(cacheKey);
719
+ if (staleCache && !forceRefresh) {
720
+ console.warn(
721
+ `[NexusHub] \u26A0\uFE0F Using stale cache for collection '${collectionId}'`
722
+ );
723
+ return includeMetadata ? staleCache : staleCache.data;
724
+ }
725
+ throw this.normalizeError(
726
+ error,
727
+ `Failed to fetch collection '${collectionId}'`
728
+ );
729
+ }
730
+ }
731
+ /**
732
+ * Fetch Global Settings with nested includes support
733
+ */
734
+ async getGlobals(options = {}) {
735
+ const {
736
+ include = [],
737
+ revalidate = this.defaultRevalidate,
738
+ forceRefresh = false
739
+ } = options;
740
+ const cacheKey = `globals:${include.join(",")}`;
741
+ if (!forceRefresh && this.cacheStrategy === "memory") {
742
+ const cached = this.memoryCache.get(cacheKey);
743
+ if (cached && this.isCacheValid(cached.metadata)) {
744
+ if (this.config.debug)
745
+ console.log("[NexusHub] \u26A1 Served globals from memory cache.");
746
+ return cached.data;
747
+ }
748
+ }
749
+ if (!forceRefresh && !this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
750
+ const cached = this.browserCache.get(cacheKey);
751
+ if (cached) {
752
+ return cached;
753
+ }
754
+ }
755
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
756
+ const localGlobals = this.localCache.getGlobals();
757
+ if (localGlobals) {
758
+ this.memoryCache.set(cacheKey, localGlobals, {
759
+ tags: [CacheTags.global],
760
+ revalidate
761
+ });
762
+ return localGlobals;
763
+ }
764
+ }
765
+ try {
766
+ await this.rateLimiter.checkLimit();
767
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/globals`;
768
+ const params = include.length > 0 ? `?include=${include.join(",")}` : "";
769
+ const res = await this.fetchWithTimeout(`${url}${params}`, {
770
+ method: "GET",
771
+ headers: this.getHeaders()
772
+ });
773
+ if (!res.ok) {
774
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
775
+ }
776
+ const json = await res.json();
777
+ const data = json.data || json;
778
+ this.writeCache(cacheKey, data, {
779
+ revalidate,
780
+ tags: [CacheTags.project(this.config.projectId), CacheTags.global]
781
+ });
782
+ return data;
783
+ } catch (error) {
784
+ const staleCache = this.memoryCache.get(cacheKey);
785
+ if (staleCache && !forceRefresh) {
786
+ console.warn("[NexusHub] \u26A0\uFE0F Using stale cache for globals");
787
+ return staleCache.data;
788
+ }
789
+ throw this.normalizeError(error, "Failed to fetch globals");
790
+ }
791
+ }
792
+ /**
793
+ * Get a single item from a collection (Uses Request Batching)
794
+ * If you call this 10 times in a loop, it sends 1 HTTP request.
795
+ */
796
+ async getItem(collectionId, itemId, options = {}) {
797
+ const cacheKey = `item:${collectionId}:${itemId}`;
798
+ if (this.cacheStrategy === "memory") {
799
+ const cached = this.memoryCache.get(cacheKey);
800
+ if (cached && this.isCacheValid(cached.metadata)) {
801
+ if (this.config.debug) {
802
+ console.log(`[NexusHub] \u26A1 Served item '${itemId}' from cache.`);
803
+ }
804
+ return cached.data;
805
+ }
806
+ }
807
+ return this.requestBatcher.schedule(cacheKey, async () => {
808
+ const params = new URLSearchParams();
809
+ if (_optionalChain([options, 'access', _17 => _17.include, 'optionalAccess', _18 => _18.length])) {
810
+ params.append("include", options.include.join(","));
811
+ }
812
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}/${itemId}?${params}`;
813
+ const res = await this.fetchWithTimeout(url, {
814
+ method: "GET",
815
+ headers: this.getHeaders()
816
+ });
817
+ if (!res.ok) {
818
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
819
+ }
820
+ const json = await res.json();
821
+ const data = json.data || json;
822
+ this.writeCache(cacheKey, data, {
823
+ revalidate: options.revalidate || this.defaultRevalidate,
824
+ tags: [
825
+ CacheTags.project(this.config.projectId),
826
+ CacheTags.collection(collectionId),
827
+ `item_${itemId}`,
828
+ ...options.tags || []
829
+ ]
830
+ });
831
+ return data;
832
+ });
833
+ }
834
+ /**
835
+ * Search across collections
836
+ */
837
+ async search(query, options = {}) {
838
+ const params = new URLSearchParams({
839
+ q: query,
840
+ limit: (options.limit || 20).toString()
841
+ });
842
+ if (_optionalChain([options, 'access', _19 => _19.collections, 'optionalAccess', _20 => _20.length])) {
843
+ params.append("collections", options.collections.join(","));
844
+ }
845
+ if (_optionalChain([options, 'access', _21 => _21.fields, 'optionalAccess', _22 => _22.length])) {
846
+ params.append("fields", options.fields.join(","));
847
+ }
848
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/search?${params}`;
849
+ const res = await this.fetchWithTimeout(url, {
850
+ method: "GET",
851
+ headers: this.getHeaders()
852
+ });
853
+ if (!res.ok) {
854
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
855
+ }
856
+ return await res.json();
857
+ }
858
+ /**
859
+ * Prefetch content for better performance
860
+ */
861
+ async prefetch(urls) {
862
+ if (typeof window !== "undefined" && "requestIdleCallback" in window) {
863
+ requestIdleCallback(async () => {
864
+ await Promise.allSettled(
865
+ urls.map((url) => fetch(url, { priority: "low" }))
866
+ );
867
+ });
868
+ }
869
+ }
870
+ /**
871
+ * Robust Real-time Subscriptions (SSE) with Auto-Reconnect
872
+ */
873
+ subscribeToUpdates(callback) {
874
+ if (this.isServer || typeof EventSource === "undefined") {
875
+ console.warn("[NexusHub] EventSource not supported in this environment");
876
+ return () => {
877
+ };
878
+ }
879
+ let eventSource = null;
880
+ let retryCount = 0;
881
+ let isClosed = false;
882
+ const connect = () => {
883
+ if (isClosed) return;
884
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/updates?key=${this.config.apiKey}`;
885
+ eventSource = new EventSource(url);
886
+ eventSource.onopen = () => {
887
+ retryCount = 0;
888
+ if (this.config.debug)
889
+ console.log("[NexusHub] \u{1F7E2} Real-time stream connected");
890
+ };
891
+ eventSource.onmessage = (event) => {
892
+ try {
893
+ const data = JSON.parse(event.data);
894
+ if (data.type === "content.updated" && data.slug) {
895
+ this.invalidateCache([CacheTags.content(data.slug)]);
896
+ }
897
+ if (data.type === "collection.updated") {
898
+ this.invalidateCache([CacheTags.collection(data.collectionId)]);
899
+ }
900
+ callback(data);
901
+ } catch (e) {
902
+ console.error("[NexusHub] SSE Parse Error", e);
903
+ }
904
+ };
905
+ eventSource.onerror = () => {
906
+ _optionalChain([eventSource, 'optionalAccess', _23 => _23.close, 'call', _24 => _24()]);
907
+ if (isClosed) return;
908
+ const timeout = Math.min(1e3 * Math.pow(2, retryCount), 1e4);
909
+ retryCount++;
910
+ console.warn(
911
+ `[NexusHub] \u{1F534} Stream disconnected. Reconnecting in ${timeout}ms...`
912
+ );
913
+ setTimeout(connect, timeout);
914
+ };
915
+ };
916
+ connect();
917
+ return () => {
918
+ isClosed = true;
919
+ _optionalChain([eventSource, 'optionalAccess', _25 => _25.close, 'call', _26 => _26()]);
920
+ };
921
+ }
922
+ // --- CACHE MANAGEMENT ---
923
+ /**
924
+ * Check all caches in order of speed
925
+ */
926
+ async checkCaches(key, forceRefresh, includeMetadata) {
927
+ if (forceRefresh) return null;
928
+ if (this.cacheStrategy === "memory") {
929
+ const cached = this.memoryCache.get(key);
930
+ if (cached && this.isCacheValid(cached.metadata)) {
931
+ return cached;
932
+ }
933
+ }
934
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
935
+ const cached = this.browserCache.get(key);
936
+ if (cached) {
937
+ return {
938
+ data: cached,
939
+ metadata: {
940
+ timestamp: 0,
941
+ expiresAt: Infinity,
942
+ tags: [],
943
+ etag: void 0
944
+ }
945
+ };
946
+ }
947
+ }
948
+ if (process.env.NODE_ENV === "development") {
949
+ if (key.startsWith("page:")) {
950
+ const slug = key.split(":")[1];
951
+ const local = await this.localCache.getPage(slug);
952
+ if (local) {
953
+ return {
954
+ data: local,
955
+ metadata: {
956
+ timestamp: 0,
957
+ expiresAt: Infinity,
958
+ tags: [],
959
+ etag: void 0
960
+ }
961
+ };
962
+ }
963
+ }
964
+ }
965
+ return null;
966
+ }
967
+ writeCache(key, data, options) {
968
+ if (this.cacheStrategy === "memory") {
969
+ this.memoryCache.set(key, data, {
970
+ tags: options.tags,
971
+ revalidate: options.revalidate
972
+ });
973
+ }
974
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
975
+ this.browserCache.set(key, data, options.revalidate * 1e3);
976
+ }
977
+ }
978
+ // packages/client-sdk/src/content/index.ts
979
+ /**
980
+ * ⚡ THE PULSE: Next.js Cache Revalidation Receiver
981
+ * Used in app/api/nexus-revalidate/route.ts to handle instant updates from the NexusHub backend.
982
+ *
983
+ * @param req The incoming Request object from Next.js
984
+ * @param revalidateFn The revalidateTag function imported from 'next/cache'
985
+ */
986
+ async handleRevalidation(req, revalidateFn) {
987
+ try {
988
+ if (!req.body) {
989
+ return { success: false, message: "Missing Pulse Payload" };
990
+ }
991
+ const body = await req.json();
992
+ const { secret, tag } = body;
993
+ if (!secret || secret !== this.config.projectId) {
994
+ if (this.config.debug) {
995
+ console.warn(`[NexusHub] \u26A0\uFE0F Blocked unauthorized Pulse request.`);
996
+ }
997
+ return { success: false, message: "Invalid Pulse Signature" };
998
+ }
999
+ const targetTag = tag || "content_all";
1000
+ revalidateFn(targetTag);
1001
+ this.invalidateCache([targetTag]);
1002
+ if (this.config.debug) {
1003
+ console.log(
1004
+ `[NexusHub] \u26A1 Pulse Received: Successfully revalidated tag [${targetTag}]`
1005
+ );
1006
+ }
1007
+ return { success: true, now: Date.now() };
1008
+ } catch (e) {
1009
+ if (this.config.debug) {
1010
+ console.error(`[NexusHub] \u274C Pulse Processing Error:`, e.message);
1011
+ }
1012
+ return {
1013
+ success: false,
1014
+ message: "Malformed Pulse Payload or Processing Error"
1015
+ };
1016
+ }
1017
+ }
1018
+ /**
1019
+ * Invalidate cache by tags
1020
+ */
1021
+ invalidateCache(tags) {
1022
+ this.memoryCache.invalidateByTags(tags);
1023
+ if (this.config.debug) {
1024
+ console.log(
1025
+ `[NexusHub] \u267B\uFE0F Invalidated cache for tags: ${tags.join(", ")}`
1026
+ );
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Clear all caches
1031
+ */
1032
+ clearCache() {
1033
+ this.memoryCache.clear();
1034
+ if (this.browserCache) {
1035
+ this.browserCache.clear();
1036
+ }
1037
+ if (this.config.debug) {
1038
+ console.log("[NexusHub] \u{1F9F9} Cleared all caches");
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Get cache statistics
1043
+ */
1044
+ getCacheStats() {
1045
+ const stats = {
1046
+ memory: this.memoryCache.getStats(),
1047
+ local: { loaded: this.localCache.isLoaded() }
1048
+ };
1049
+ if (this.browserCache) {
1050
+ stats.browser = { size: 0 };
1051
+ }
1052
+ return stats;
1053
+ }
1054
+ // --- REQUEST METHODS ---
1055
+ async fetchPage(slug, cacheKey, tags, revalidate, forceRefresh) {
1056
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/page/${slug}`;
1057
+ if (this.config.debug) {
1058
+ console.log(`[NexusHub] \u{1F310} Fetching: ${url}`);
1059
+ }
1060
+ const res = await this.fetchWithTimeout(url, {
1061
+ method: "GET",
1062
+ headers: this.getHeaders(),
1063
+ tags,
1064
+ revalidate
1065
+ });
1066
+ if (!res.ok) {
1067
+ if (res.status === 404) {
1068
+ throw new Error(
1069
+ `Page '${slug}' not found. Check your Dashboard or Seed data.`
1070
+ );
1071
+ }
1072
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1073
+ }
1074
+ const json = await res.json();
1075
+ const etag = res.headers.get("etag");
1076
+ const cacheEntry = {
1077
+ data: json.data,
1078
+ metadata: {
1079
+ timestamp: Date.now(),
1080
+ etag: etag || void 0,
1081
+ expiresAt: Date.now() + revalidate * 1e3,
1082
+ tags: [...tags, CacheTags.content(slug)]
1083
+ }
1084
+ };
1085
+ this.writeCache(cacheKey, cacheEntry.data, {
1086
+ revalidate,
1087
+ tags: [
1088
+ CacheTags.project(this.config.projectId),
1089
+ CacheTags.content(slug),
1090
+ ...tags
1091
+ ]
1092
+ });
1093
+ return cacheEntry;
1094
+ }
1095
+ async fetchCollection(collectionId, query, cacheKey, tags, revalidate) {
1096
+ const params = buildQueryString(query);
1097
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}?${params}`;
1098
+ if (this.config.debug) {
1099
+ console.log(`[NexusHub] \u{1F310} Fetching Collection: ${url}`);
1100
+ }
1101
+ const res = await this.fetchWithTimeout(url, {
1102
+ method: "GET",
1103
+ headers: this.getHeaders(),
1104
+ tags,
1105
+ revalidate
1106
+ });
1107
+ if (!res.ok) {
1108
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
1109
+ }
1110
+ const json = await res.json();
1111
+ const etag = res.headers.get("etag");
1112
+ const cacheEntry = {
1113
+ data: json,
1114
+ metadata: {
1115
+ timestamp: Date.now(),
1116
+ etag: etag || void 0,
1117
+ expiresAt: Date.now() + revalidate * 1e3,
1118
+ tags: [...tags, CacheTags.collection(collectionId)]
1119
+ }
1120
+ };
1121
+ this.writeCache(cacheKey, cacheEntry.data, {
1122
+ revalidate,
1123
+ tags: [
1124
+ CacheTags.project(this.config.projectId),
1125
+ CacheTags.collection(collectionId),
1126
+ ...tags
1127
+ ]
1128
+ });
1129
+ return cacheEntry;
1130
+ }
1131
+ // --- HELPER METHODS ---
1132
+ applyLocalQuery(items, query) {
1133
+ let filtered = [...items];
1134
+ if (query.search) {
1135
+ const searchLower = query.search.toLowerCase();
1136
+ filtered = filtered.filter(
1137
+ (item) => JSON.stringify(item).toLowerCase().includes(searchLower)
1138
+ );
1139
+ }
1140
+ if (query.filter) {
1141
+ filtered = filtered.filter((item) => {
1142
+ return Object.entries(query.filter).every(([key, value]) => {
1143
+ const itemValue = item[key];
1144
+ if (itemValue === void 0) return false;
1145
+ if (Array.isArray(value)) {
1146
+ return value.includes(itemValue);
1147
+ }
1148
+ return itemValue === value;
1149
+ });
1150
+ });
1151
+ }
1152
+ if (query.sort) {
1153
+ filtered.sort((a, b) => {
1154
+ const aVal = a[query.sort];
1155
+ const bVal = b[query.sort];
1156
+ const order = query.order === "asc" ? 1 : -1;
1157
+ if (aVal < bVal) return -1 * order;
1158
+ if (aVal > bVal) return 1 * order;
1159
+ return 0;
1160
+ });
1161
+ }
1162
+ const page = query.page || 1;
1163
+ const limit = query.limit || 10;
1164
+ const start = (page - 1) * limit;
1165
+ const end = start + limit;
1166
+ const total = filtered.length;
1167
+ return {
1168
+ items: filtered.slice(start, end),
1169
+ total,
1170
+ page,
1171
+ limit,
1172
+ totalPages: Math.ceil(total / limit),
1173
+ hasNext: end < total,
1174
+ hasPrev: start > 0
1175
+ };
1176
+ }
1177
+ async fetchWithTimeout(url, options = {}) {
1178
+ const {
1179
+ timeout = this.config.timeout || 1e4,
1180
+ tags = [],
1181
+ revalidate,
1182
+ ...fetchOptions
1183
+ } = options;
1184
+ const controller = new AbortController();
1185
+ const id = setTimeout(() => controller.abort(), timeout);
1186
+ const nextConfig = this.isServer ? { next: { tags, revalidate } } : {};
1187
+ try {
1188
+ const response = await fetch(url, {
1189
+ ...fetchOptions,
1190
+ ...nextConfig,
1191
+ // Inject Next.js tags
1192
+ signal: controller.signal
1193
+ });
1194
+ clearTimeout(id);
1195
+ return response;
1196
+ } catch (error) {
1197
+ clearTimeout(id);
1198
+ throw error;
1199
+ }
1200
+ }
1201
+ getHeaders() {
1202
+ const headers = {
1203
+ "Content-Type": "application/json",
1204
+ "X-Nexus-Client": "client-sdk/1.0.0",
1205
+ "X-Nexus-Project": this.config.projectId
1206
+ };
1207
+ if (this.config.apiKey) {
1208
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1209
+ }
1210
+ return headers;
1211
+ }
1212
+ isCacheValid(metadata) {
1213
+ return Date.now() < metadata.expiresAt;
1214
+ }
1215
+ normalizeError(error, context) {
1216
+ if (error instanceof Error) {
1217
+ if (error.name === "AbortError") {
1218
+ return new Error(`${context}: Request timeout`);
1219
+ }
1220
+ return error;
1221
+ }
1222
+ return new Error(`${context}: ${String(error)}`);
1223
+ }
1224
+ /**
1225
+ * Cancel ongoing requests
1226
+ */
1227
+ cancelRequests() {
1228
+ if (this.abortController) {
1229
+ this.abortController.abort();
1230
+ this.abortController = new AbortController();
1231
+ }
1232
+ }
1233
+ /**
1234
+ * Cleanup resources
1235
+ */
1236
+ cleanup() {
1237
+ this.cancelRequests();
1238
+ if (!this.isServer) {
1239
+ window.removeEventListener("beforeunload", this.cleanup.bind(this));
1240
+ }
1241
+ }
1242
+ };
1243
+
1244
+ // src/analytics/fingerprint.ts
1245
+ var cachedEntropy = null;
1246
+ var getDeviceEntropy = async () => {
1247
+ if (cachedEntropy) return cachedEntropy;
1248
+ if (typeof window === "undefined") return {};
1249
+ const nav = window.navigator;
1250
+ cachedEntropy = {
1251
+ screen_resolution: `${window.screen.width}x${window.screen.height}`,
1252
+ color_depth: window.screen.colorDepth,
1253
+ pixel_ratio: window.devicePixelRatio || 1,
1254
+ hardware_concurrency: nav.hardwareConcurrency,
1255
+ device_memory: nav.deviceMemory,
1256
+ // Chrome/Edge only
1257
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1258
+ platform: nav.platform,
1259
+ language: nav.language,
1260
+ touch_support: "ontouchstart" in window || nav.maxTouchPoints > 0,
1261
+ canvas_hash: await generateCanvasHash()
1262
+ };
1263
+ return cachedEntropy;
1264
+ };
1265
+ var generateCanvasHash = async () => {
1266
+ try {
1267
+ const canvas = document.createElement("canvas");
1268
+ const ctx = canvas.getContext("2d");
1269
+ if (!ctx) return "";
1270
+ canvas.width = 200;
1271
+ canvas.height = 50;
1272
+ ctx.textBaseline = "top";
1273
+ ctx.font = '16px "Arial"';
1274
+ ctx.textBaseline = "alphabetic";
1275
+ ctx.fillStyle = "#f60";
1276
+ ctx.fillRect(125, 1, 62, 20);
1277
+ ctx.fillStyle = "#069";
1278
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 2, 15);
1279
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
1280
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 4, 17);
1281
+ const dataUrl = canvas.toDataURL();
1282
+ let hash = 0;
1283
+ for (let i = 0; i < dataUrl.length; i++) {
1284
+ const char = dataUrl.charCodeAt(i);
1285
+ hash = (hash << 5) - hash + char;
1286
+ hash = hash & hash;
1287
+ }
1288
+ return hash.toString(16);
1289
+ } catch (e5) {
1290
+ return "";
1291
+ }
1292
+ };
1293
+ var getVisitorId = async () => {
1294
+ if (typeof window === "undefined") return "server_visitor";
1295
+ const STORAGE_KEY = "nexus_vid";
1296
+ let vid = localStorage.getItem(STORAGE_KEY);
1297
+ if (!vid) {
1298
+ const entropy = await getDeviceEntropy();
1299
+ const random = Math.random().toString(36).substring(2, 15);
1300
+ const timestamp = Date.now().toString(36);
1301
+ const fingerprint = [
1302
+ entropy.screen_resolution,
1303
+ entropy.hardware_concurrency,
1304
+ entropy.timezone_offset,
1305
+ entropy.platform,
1306
+ entropy.canvas_hash
1307
+ ].join("|");
1308
+ let hash = 0;
1309
+ for (let i = 0; i < fingerprint.length; i++) {
1310
+ hash = (hash << 5) - hash + fingerprint.charCodeAt(i);
1311
+ hash |= 0;
1312
+ }
1313
+ vid = `vis_${hash.toString(16)}_${timestamp}_${random}`;
1314
+ localStorage.setItem(STORAGE_KEY, vid);
1315
+ }
1316
+ return vid;
1317
+ };
1318
+
1319
+ // src/analytics/vitals.ts
1320
+ var _webvitals = require('web-vitals');
1321
+ var METRIC_KEY_MAP = {
1322
+ CLS: "cls",
1323
+ LCP: "lcp",
1324
+ INP: "inp",
1325
+ TTFB: "ttfb",
1326
+ FCP: "fcp"
1327
+ };
1328
+ var VitalsCollector = class {
1329
+ constructor() {
1330
+ this.metrics = {};
1331
+ this.hasUpdates = false;
1332
+ if (typeof window !== "undefined") {
1333
+ this.init();
1334
+ }
1335
+ }
1336
+ init() {
1337
+ const recordMetric = (metric) => {
1338
+ const key = METRIC_KEY_MAP[metric.name];
1339
+ this.metrics[key] = metric.value;
1340
+ this.hasUpdates = true;
1341
+ };
1342
+ _webvitals.onCLS.call(void 0, recordMetric);
1343
+ _webvitals.onLCP.call(void 0, recordMetric);
1344
+ _webvitals.onTTFB.call(void 0, recordMetric);
1345
+ _webvitals.onINP.call(void 0, recordMetric);
1346
+ _webvitals.onFCP.call(void 0, recordMetric);
1347
+ const navEntry = performance.getEntriesByType("navigation")[0];
1348
+ if (navEntry) {
1349
+ this.metrics.navigation_timing = {
1350
+ dns_lookup: navEntry.domainLookupEnd - navEntry.domainLookupStart,
1351
+ tcp_connect: navEntry.connectEnd - navEntry.connectStart,
1352
+ request_time: navEntry.responseEnd - navEntry.requestStart,
1353
+ dom_load: navEntry.domComplete - navEntry.domInteractive,
1354
+ // NEW: raw fields matching Rust NavigationTiming struct
1355
+ domain_lookup_start: navEntry.domainLookupStart,
1356
+ domain_lookup_end: navEntry.domainLookupEnd,
1357
+ connect_start: navEntry.connectStart,
1358
+ connect_end: navEntry.connectEnd,
1359
+ secure_connection_start: navEntry.secureConnectionStart > 0 ? navEntry.secureConnectionStart : void 0
1360
+ };
1361
+ this.hasUpdates = true;
1362
+ }
1363
+ const resourceEntries = performance.getEntriesByType(
1364
+ "resource"
1365
+ );
1366
+ if (resourceEntries.length > 0) {
1367
+ this.metrics.resources = resourceEntries.filter((r) => !r.name.includes("/api/collect")).sort((a, b) => b.duration - a.duration).slice(0, 20).map((r) => ({
1368
+ name: r.name,
1369
+ initiatorType: r.initiatorType,
1370
+ duration: Math.round(r.duration),
1371
+ transferSize: r.transferSize > 0 ? r.transferSize : void 0,
1372
+ encodedBodySize: r.encodedBodySize > 0 ? r.encodedBodySize : void 0,
1373
+ decodedBodySize: r.decodedBodySize > 0 ? r.decodedBodySize : void 0,
1374
+ startTime: Math.round(r.startTime),
1375
+ responseEnd: Math.round(r.responseEnd)
1376
+ }));
1377
+ this.hasUpdates = true;
1378
+ }
1379
+ const mem = performance.memory;
1380
+ if (mem) {
1381
+ this.metrics.memory_usage = {
1382
+ used_js_heap_size: mem.usedJSHeapSize,
1383
+ total_js_heap_size: mem.totalJSHeapSize,
1384
+ js_heap_size_limit: mem.jsHeapSizeLimit
1385
+ };
1386
+ this.hasUpdates = true;
1387
+ }
1388
+ }
1389
+ getMetricsSnapshot() {
1390
+ if (!this.hasUpdates) return null;
1391
+ this.hasUpdates = false;
1392
+ const snapshot = { ...this.metrics };
1393
+ this.metrics.resources = void 0;
1394
+ return snapshot;
1395
+ }
1396
+ };
1397
+ var vitalsCollector = new VitalsCollector();
1398
+ var initVitals = (_tracker) => {
1399
+ if (process.env.NODE_ENV === "development") {
1400
+ console.log("[NexusHub] Web Vitals monitoring active");
1401
+ }
1402
+ };
1403
+
1404
+ // src/analytics/storage.ts
1405
+ var DB_NAME = "NexusHub_Analytics";
1406
+ var STORE_NAME = "events_queue";
1407
+ var DB_VERSION = 2;
1408
+ var MAX_QUEUE_SIZE = 500;
1409
+ var EventStorage = class {
1410
+ constructor() {
1411
+ this.db = null;
1412
+ this.isReady = this.init();
1413
+ }
1414
+ init() {
1415
+ if (typeof window === "undefined" || !window.indexedDB) {
1416
+ return Promise.resolve();
1417
+ }
1418
+ return new Promise((resolve) => {
1419
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
1420
+ request.onerror = () => {
1421
+ console.warn(
1422
+ "[NexusHub] Failed to open IndexedDB. Falling back to memory."
1423
+ );
1424
+ resolve();
1425
+ };
1426
+ request.onsuccess = (event) => {
1427
+ this.db = event.target.result;
1428
+ resolve();
1429
+ };
1430
+ request.onupgradeneeded = (event) => {
1431
+ const db = event.target.result;
1432
+ if (db.objectStoreNames.contains(STORE_NAME)) {
1433
+ db.deleteObjectStore(STORE_NAME);
1434
+ }
1435
+ db.createObjectStore(STORE_NAME, {
1436
+ keyPath: "id",
1437
+ autoIncrement: true
1438
+ });
1439
+ };
1440
+ });
1441
+ }
1442
+ /**
1443
+ * Add an event to the persistent queue.
1444
+ * Evicts the oldest entry if the queue is already at MAX_QUEUE_SIZE.
1445
+ */
1446
+ async enqueue(payload) {
1447
+ await this.isReady;
1448
+ if (!this.db) return;
1449
+ const currentCount = await this.count();
1450
+ if (currentCount >= MAX_QUEUE_SIZE) {
1451
+ const oldest = await this.peek(1);
1452
+ if (oldest.length > 0 && oldest[0].id !== void 0) {
1453
+ await this.remove([oldest[0].id]);
1454
+ }
1455
+ }
1456
+ return new Promise((resolve, reject) => {
1457
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1458
+ const store = transaction.objectStore(STORE_NAME);
1459
+ const request = store.add({
1460
+ payload,
1461
+ timestamp: Date.now(),
1462
+ retryCount: 0
1463
+ });
1464
+ request.onsuccess = () => resolve();
1465
+ request.onerror = () => reject(request.error);
1466
+ });
1467
+ }
1468
+ /**
1469
+ * Get a batch of the oldest events without removing them.
1470
+ */
1471
+ async peek(limit = 20) {
1472
+ await this.isReady;
1473
+ if (!this.db) return [];
1474
+ return new Promise((resolve) => {
1475
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1476
+ const store = transaction.objectStore(STORE_NAME);
1477
+ const request = store.getAll(null, limit);
1478
+ request.onsuccess = () => resolve(request.result);
1479
+ request.onerror = () => resolve([]);
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Remove events by ID after a successful upload.
1484
+ */
1485
+ async remove(ids) {
1486
+ await this.isReady;
1487
+ if (!this.db || ids.length === 0) return;
1488
+ return new Promise((resolve, reject) => {
1489
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1490
+ const store = transaction.objectStore(STORE_NAME);
1491
+ transaction.oncomplete = () => resolve();
1492
+ transaction.onerror = () => reject(transaction.error);
1493
+ transaction.onabort = () => reject(new Error("Delete transaction aborted"));
1494
+ ids.forEach((id) => {
1495
+ store.delete(id);
1496
+ });
1497
+ });
1498
+ }
1499
+ /**
1500
+ * Count pending events in the queue.
1501
+ */
1502
+ async count() {
1503
+ await this.isReady;
1504
+ if (!this.db) return 0;
1505
+ return new Promise((resolve) => {
1506
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1507
+ const store = transaction.objectStore(STORE_NAME);
1508
+ const request = store.count();
1509
+ request.onsuccess = () => resolve(request.result);
1510
+ request.onerror = () => resolve(0);
1511
+ });
1512
+ }
1513
+ };
1514
+ var eventStorage = new EventStorage();
1515
+
1516
+ // src/analytics/tracker.ts
1517
+ var SDK_VERSION = "0.1.0";
1518
+ var safeGetItem = (key) => {
1519
+ try {
1520
+ return localStorage.getItem(key);
1521
+ } catch (e6) {
1522
+ return null;
1523
+ }
1524
+ };
1525
+ var safeSetItem = (key, value) => {
1526
+ try {
1527
+ localStorage.setItem(key, value);
1528
+ } catch (e7) {
1529
+ }
1530
+ };
1531
+ var safeRemoveItem = (key) => {
1532
+ try {
1533
+ localStorage.removeItem(key);
1534
+ } catch (e8) {
1535
+ }
1536
+ };
1537
+ var generateUUID = () => {
1538
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1539
+ return crypto.randomUUID();
1540
+ }
1541
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1542
+ const r = Math.random() * 16 | 0;
1543
+ const v = c === "x" ? r : r & 3 | 8;
1544
+ return v.toString(16);
1545
+ });
1546
+ };
1547
+ var Tracker = class {
1548
+ constructor(config) {
1549
+ this.sessionId = "";
1550
+ this.visitorId = "";
1551
+ this.anonymousId = "";
1552
+ this.isFlushing = false;
1553
+ this.config = config;
1554
+ this.endpoint = `${this.config.analyticsUrl}/api/collect`;
1555
+ this.circuitBreaker = new CircuitBreaker();
1556
+ this.sessionStart = Date.now();
1557
+ if (typeof window !== "undefined") {
1558
+ this.initSession();
1559
+ this.startFlushing();
1560
+ }
1561
+ }
1562
+ async initSession() {
1563
+ this.visitorId = await getVisitorId();
1564
+ let anonId = safeGetItem("nexus_anon_id");
1565
+ if (!anonId) {
1566
+ anonId = `anon_${generateUUID().replace(/-/g, "")}`;
1567
+ safeSetItem("nexus_anon_id", anonId);
1568
+ }
1569
+ this.anonymousId = anonId;
1570
+ let sid = safeGetItem("nexus_sid");
1571
+ const lastActivity = safeGetItem("nexus_last_active");
1572
+ const now = Date.now();
1573
+ const SESSION_TIMEOUT = 30 * 60 * 1e3;
1574
+ const isExpired = !sid || !lastActivity || now - parseInt(lastActivity, 10) > SESSION_TIMEOUT;
1575
+ if (isExpired) {
1576
+ const uuid = generateUUID().replace(/-/g, "").substring(0, 16);
1577
+ sid = `sess_${uuid}_${now}`;
1578
+ safeSetItem("nexus_sid", sid);
1579
+ this.sessionStart = now;
1580
+ }
1581
+ safeSetItem("nexus_last_active", now.toString());
1582
+ this.sessionId = sid;
1583
+ }
1584
+ async send(eventType, data = {}, eventName, ecommerce) {
1585
+ if (typeof window === "undefined") return;
1586
+ safeSetItem("nexus_last_active", Date.now().toString());
1587
+ const entropy = await getDeviceEntropy();
1588
+ const perfMetrics = vitalsCollector.getMetricsSnapshot();
1589
+ const utmParams = extractUtmParams(window.location.href);
1590
+ const payload = {
1591
+ projectId: this.config.projectId,
1592
+ sessionId: this.sessionId,
1593
+ visitorId: this.visitorId,
1594
+ anonymousId: this.anonymousId,
1595
+ messageId: generateUUID(),
1596
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
1597
+ version: SDK_VERSION,
1598
+ url: window.location.href,
1599
+ referrer: document.referrer,
1600
+ userAgent: window.navigator.userAgent,
1601
+ screenWidth: window.screen.width,
1602
+ screenHeight: window.screen.height,
1603
+ language: window.navigator.language,
1604
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1605
+ eventType,
1606
+ eventName,
1607
+ eventData: data,
1608
+ ecommerce: _nullishCoalesce(ecommerce, () => ( void 0)),
1609
+ performance: perfMetrics || void 0,
1610
+ context: {
1611
+ device: {
1612
+ hardwareConcurrency: entropy.hardware_concurrency,
1613
+ deviceMemory: entropy.device_memory,
1614
+ pixelRatio: entropy.pixel_ratio,
1615
+ canvasFingerprint: entropy.canvas_hash,
1616
+ platform: entropy.platform
1617
+ },
1618
+ visitorIdLocal: this.visitorId,
1619
+ utm: utmParams
1620
+ },
1621
+ clientTimestamp: (/* @__PURE__ */ new Date()).toISOString()
1622
+ };
1623
+ await eventStorage.enqueue(payload);
1624
+ const count = await eventStorage.count();
1625
+ if (count >= 10 || eventType === "purchase" || eventType === "identify") {
1626
+ this.flushQueue();
1627
+ }
1628
+ }
1629
+ startFlushing() {
1630
+ this.flushInterval = setInterval(() => this.flushQueue(), 5e3);
1631
+ window.addEventListener("visibilitychange", () => {
1632
+ if (document.visibilityState === "hidden") this.flushQueue(true);
1633
+ });
1634
+ }
1635
+ async flushQueue(useBeacon = false) {
1636
+ if (this.isFlushing) return;
1637
+ if (this.circuitBreaker.isOpen()) return;
1638
+ this.isFlushing = true;
1639
+ try {
1640
+ const storedEvents = await eventStorage.peek(20);
1641
+ if (storedEvents.length === 0) {
1642
+ this.isFlushing = false;
1643
+ return;
1644
+ }
1645
+ const payloads = storedEvents.map((e) => e.payload);
1646
+ const promises = payloads.map(
1647
+ (event) => fetch(this.endpoint, {
1648
+ method: "POST",
1649
+ headers: {
1650
+ "Content-Type": "application/json",
1651
+ Authorization: `Bearer ${this.config.apiKey}`
1652
+ },
1653
+ body: JSON.stringify(event),
1654
+ keepalive: useBeacon
1655
+ })
1656
+ );
1657
+ const results = await Promise.allSettled(promises);
1658
+ const successIds = [];
1659
+ let failureCount = 0;
1660
+ results.forEach((res, index) => {
1661
+ if (res.status === "fulfilled" && res.value.ok) {
1662
+ successIds.push(storedEvents[index].id);
1663
+ } else {
1664
+ failureCount++;
1665
+ }
1666
+ });
1667
+ if (successIds.length > 0) {
1668
+ await eventStorage.remove(successIds);
1669
+ this.circuitBreaker.recordSuccess();
1670
+ }
1671
+ if (failureCount > 0) {
1672
+ this.circuitBreaker.recordFailure();
1673
+ }
1674
+ } catch (err) {
1675
+ console.error("[NexusHub] Network Error:", err);
1676
+ this.circuitBreaker.recordFailure();
1677
+ } finally {
1678
+ this.isFlushing = false;
1679
+ if (!this.circuitBreaker.isOpen() && await eventStorage.count() > 0) {
1680
+ setTimeout(() => this.flushQueue(), 100);
1681
+ }
1682
+ }
1683
+ }
1684
+ getSession() {
1685
+ return this.sessionId;
1686
+ }
1687
+ getVisitorId() {
1688
+ return this.visitorId;
1689
+ }
1690
+ getAnonymousId() {
1691
+ return this.anonymousId;
1692
+ }
1693
+ getSessionDuration() {
1694
+ return Date.now() - this.sessionStart;
1695
+ }
1696
+ clearIdentity() {
1697
+ safeRemoveItem("nexus_anon_id");
1698
+ this.anonymousId = "";
1699
+ }
1700
+ stop() {
1701
+ if (this.flushInterval) {
1702
+ clearInterval(this.flushInterval);
1703
+ }
1704
+ this.flushQueue(true);
1705
+ }
1706
+ };
1707
+ function extractUtmParams(url) {
1708
+ try {
1709
+ const params = new URL(url).searchParams;
1710
+ const utmKeys = [
1711
+ "utm_source",
1712
+ "utm_medium",
1713
+ "utm_campaign",
1714
+ "utm_term",
1715
+ "utm_content"
1716
+ ];
1717
+ const result = {};
1718
+ utmKeys.forEach((key) => {
1719
+ const val = params.get(key);
1720
+ if (val) result[key] = val;
1721
+ });
1722
+ return result;
1723
+ } catch (e9) {
1724
+ return {};
1725
+ }
1726
+ }
1727
+
1728
+ // src/analytics/index.ts
1729
+ var safeRemoveItem2 = (key) => {
1730
+ try {
1731
+ localStorage.removeItem(key);
1732
+ } catch (e10) {
1733
+ }
1734
+ };
1735
+ var AnalyticsEngine = class {
1736
+ constructor(config) {
1737
+ this.cleanupFns = [];
1738
+ this.isInitialized = false;
1739
+ this.maxScrollDepth = 0;
1740
+ this.scrollThresholdsFired = /* @__PURE__ */ new Set();
1741
+ this.lastPath = typeof window !== "undefined" ? window.location.pathname : "";
1742
+ this.clickBuffer = [];
1743
+ this.tracker = new Tracker(config);
1744
+ }
1745
+ start() {
1746
+ if (this.isInitialized || typeof window === "undefined") return;
1747
+ this.isInitialized = true;
1748
+ this.pageView();
1749
+ initVitals(this.tracker);
1750
+ this.setupClickTracking();
1751
+ this.setupFormTracking();
1752
+ this.setupRouteTracking();
1753
+ this.setupShareTracking();
1754
+ this.setupScrollTracking();
1755
+ this.setupOutboundTracking();
1756
+ this.setupVideoTracking();
1757
+ this.setupErrorTracking();
1758
+ if (process.env.NODE_ENV === "development") {
1759
+ console.log("[NexusHub] \u{1F680} Analytics Engine Started");
1760
+ }
1761
+ }
1762
+ pageView(customReferrer) {
1763
+ if (typeof window === "undefined") return;
1764
+ const currentPath = window.location.pathname;
1765
+ this.maxScrollDepth = 0;
1766
+ this.scrollThresholdsFired.clear();
1767
+ this.tracker.send("page_view", {
1768
+ path: currentPath,
1769
+ search: window.location.search,
1770
+ title: document.title,
1771
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1772
+ referrer: customReferrer || (this.lastPath !== currentPath ? this.lastPath : document.referrer)
1773
+ });
1774
+ this.lastPath = currentPath;
1775
+ }
1776
+ setupShareTracking() {
1777
+ if (typeof window === "undefined") return;
1778
+ const copyHandler = () => {
1779
+ this.tracker.send("social_share", {
1780
+ method: "clipboard_copy",
1781
+ url: window.location.href
1782
+ });
1783
+ };
1784
+ window.addEventListener("copy", copyHandler, { passive: true });
1785
+ this.cleanupFns.push(() => window.removeEventListener("copy", copyHandler));
1786
+ if (typeof navigator !== "undefined" && navigator.share) {
1787
+ const originalShare = navigator.share.bind(navigator);
1788
+ navigator.share = (data) => {
1789
+ this.tracker.send("social_share", {
1790
+ method: "native_share_menu",
1791
+ url: _optionalChain([data, 'optionalAccess', _27 => _27.url]) || window.location.href,
1792
+ title: _optionalChain([data, 'optionalAccess', _28 => _28.title])
1793
+ });
1794
+ return originalShare(data);
1795
+ };
1796
+ this.cleanupFns.push(() => {
1797
+ navigator.share = originalShare;
1798
+ });
1799
+ }
1800
+ }
1801
+ setupScrollTracking() {
1802
+ if (typeof window === "undefined") return;
1803
+ const THRESHOLDS = [25, 50, 75, 100];
1804
+ const scrollHandler = () => {
1805
+ const scrollTop = window.scrollY || document.documentElement.scrollTop;
1806
+ const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
1807
+ if (docHeight <= 0) return;
1808
+ const pct = Math.round(scrollTop / docHeight * 100);
1809
+ if (pct > this.maxScrollDepth) {
1810
+ this.maxScrollDepth = pct;
1811
+ }
1812
+ clearTimeout(this.scrollTimer);
1813
+ this.scrollTimer = setTimeout(() => {
1814
+ for (const threshold of THRESHOLDS) {
1815
+ if (this.maxScrollDepth >= threshold && !this.scrollThresholdsFired.has(threshold)) {
1816
+ this.scrollThresholdsFired.add(threshold);
1817
+ this.tracker.send("scroll", {
1818
+ depth: threshold / 100,
1819
+ depth_percent: threshold,
1820
+ path: window.location.pathname
1821
+ });
1822
+ }
1823
+ }
1824
+ }, 300);
1825
+ };
1826
+ window.addEventListener("scroll", scrollHandler, { passive: true });
1827
+ this.cleanupFns.push(() => {
1828
+ window.removeEventListener("scroll", scrollHandler);
1829
+ clearTimeout(this.scrollTimer);
1830
+ });
1831
+ }
1832
+ setupClickTracking() {
1833
+ if (typeof window === "undefined") return;
1834
+ const clickHandler = (e) => {
1835
+ const target = e.target;
1836
+ const link = target.closest("a");
1837
+ if (link) {
1838
+ this.tracker.send("click", {
1839
+ element_type: "link",
1840
+ href: link.href,
1841
+ text: _optionalChain([link, 'access', _29 => _29.innerText, 'optionalAccess', _30 => _30.substring, 'call', _31 => _31(0, 50)]),
1842
+ id: link.id,
1843
+ classes: link.className,
1844
+ dataset: { ...link.dataset },
1845
+ coordinates: { x: e.clientX, y: e.clientY }
1846
+ });
1847
+ }
1848
+ const button = target.closest("button");
1849
+ if (button) {
1850
+ this.tracker.send("click", {
1851
+ element_type: "button",
1852
+ text: _optionalChain([button, 'access', _32 => _32.innerText, 'optionalAccess', _33 => _33.substring, 'call', _34 => _34(0, 50)]),
1853
+ id: button.id,
1854
+ classes: button.className,
1855
+ coordinates: { x: e.clientX, y: e.clientY }
1856
+ });
1857
+ }
1858
+ const now = Date.now();
1859
+ const ZONE = 400;
1860
+ const WINDOW_MS = 1e3;
1861
+ const RAGE_THRESHOLD = 3;
1862
+ this.clickBuffer.push({ x: e.clientX, y: e.clientY, t: now });
1863
+ this.clickBuffer = this.clickBuffer.filter((c) => now - c.t < WINDOW_MS);
1864
+ const zone = {
1865
+ x: Math.floor(e.clientX / ZONE),
1866
+ y: Math.floor(e.clientY / ZONE)
1867
+ };
1868
+ const zoneClicks = this.clickBuffer.filter(
1869
+ (c) => Math.floor(c.x / ZONE) === zone.x && Math.floor(c.y / ZONE) === zone.y
1870
+ );
1871
+ if (zoneClicks.length >= RAGE_THRESHOLD) {
1872
+ this.tracker.send(
1873
+ "click",
1874
+ {
1875
+ element_type: target.tagName.toLowerCase(),
1876
+ event_name: "rage_click",
1877
+ coordinates: { x: e.clientX, y: e.clientY },
1878
+ click_count: zoneClicks.length,
1879
+ path: window.location.pathname
1880
+ },
1881
+ "rage_click"
1882
+ );
1883
+ this.clickBuffer = [];
1884
+ }
1885
+ const isInteractive = target.closest(
1886
+ "a, button, input, select, textarea, [onclick], [role='button']"
1887
+ );
1888
+ if (!isInteractive) {
1889
+ const pathBefore = window.location.pathname;
1890
+ setTimeout(() => {
1891
+ const pathAfter = window.location.pathname;
1892
+ if (pathBefore === pathAfter) {
1893
+ this.tracker.send(
1894
+ "click",
1895
+ {
1896
+ element_type: target.tagName.toLowerCase(),
1897
+ event_name: "dead_click",
1898
+ selector: getSelector(target),
1899
+ coordinates: { x: e.clientX, y: e.clientY },
1900
+ path: window.location.pathname
1901
+ },
1902
+ "dead_click"
1903
+ );
1904
+ }
1905
+ }, 300);
1906
+ }
1907
+ };
1908
+ window.addEventListener("click", clickHandler, { passive: true });
1909
+ this.cleanupFns.push(
1910
+ () => window.removeEventListener("click", clickHandler)
1911
+ );
1912
+ }
1913
+ setupFormTracking() {
1914
+ if (typeof document === "undefined") return;
1915
+ const submitHandler = (e) => {
1916
+ const form = e.target;
1917
+ if (form) {
1918
+ this.tracker.send("form_submit", {
1919
+ form_id: form.id || form.name || "unknown_form",
1920
+ action: form.action,
1921
+ method: form.method,
1922
+ field_count: form.elements.length
1923
+ });
1924
+ }
1925
+ };
1926
+ document.addEventListener("submit", submitHandler, { passive: true });
1927
+ this.cleanupFns.push(
1928
+ () => document.removeEventListener("submit", submitHandler)
1929
+ );
1930
+ }
1931
+ setupOutboundTracking() {
1932
+ if (typeof window === "undefined") return;
1933
+ const outboundHandler = (e) => {
1934
+ const link = e.target.closest("a");
1935
+ if (!link || !link.href) return;
1936
+ try {
1937
+ const linkHost = new URL(link.href).hostname;
1938
+ if (linkHost && linkHost !== window.location.hostname) {
1939
+ this.tracker.send(
1940
+ "click",
1941
+ {
1942
+ event_name: "outbound_click",
1943
+ href: link.href,
1944
+ text: _optionalChain([link, 'access', _35 => _35.innerText, 'optionalAccess', _36 => _36.substring, 'call', _37 => _37(0, 50)]),
1945
+ destination_host: linkHost,
1946
+ coordinates: { x: e.clientX, y: e.clientY }
1947
+ },
1948
+ "outbound_click"
1949
+ );
1950
+ }
1951
+ } catch (e11) {
1952
+ }
1953
+ };
1954
+ window.addEventListener("click", outboundHandler, { passive: true });
1955
+ this.cleanupFns.push(
1956
+ () => window.removeEventListener("click", outboundHandler)
1957
+ );
1958
+ }
1959
+ setupVideoTracking() {
1960
+ if (typeof document === "undefined") return;
1961
+ const attachVideoListeners = (video) => {
1962
+ if (video.__nexus_tracked) return;
1963
+ video.__nexus_tracked = true;
1964
+ const src = video.src || video.currentSrc || "unknown";
1965
+ let milestone50Fired = false;
1966
+ video.addEventListener("play", () => {
1967
+ this.tracker.send(
1968
+ "custom_event",
1969
+ { event_name: "video_play", src },
1970
+ "video_play"
1971
+ );
1972
+ });
1973
+ video.addEventListener("pause", () => {
1974
+ this.tracker.send(
1975
+ "custom_event",
1976
+ {
1977
+ event_name: "video_pause",
1978
+ src,
1979
+ position_seconds: Math.round(video.currentTime)
1980
+ },
1981
+ "video_pause"
1982
+ );
1983
+ });
1984
+ video.addEventListener("timeupdate", () => {
1985
+ if (!video.duration || video.duration === Infinity) return;
1986
+ const pct = video.currentTime / video.duration;
1987
+ if (pct >= 0.5 && !milestone50Fired) {
1988
+ milestone50Fired = true;
1989
+ this.tracker.send(
1990
+ "custom_event",
1991
+ {
1992
+ event_name: "video_50_percent",
1993
+ src
1994
+ },
1995
+ "video_50_percent"
1996
+ );
1997
+ }
1998
+ });
1999
+ video.addEventListener("ended", () => {
2000
+ this.tracker.send(
2001
+ "custom_event",
2002
+ {
2003
+ event_name: "video_complete",
2004
+ src,
2005
+ duration_seconds: Math.round(video.duration)
2006
+ },
2007
+ "video_complete"
2008
+ );
2009
+ });
2010
+ };
2011
+ document.querySelectorAll("video").forEach((v) => attachVideoListeners(v));
2012
+ const observer = new MutationObserver((mutations) => {
2013
+ mutations.forEach((m) => {
2014
+ m.addedNodes.forEach((node) => {
2015
+ if (node instanceof HTMLVideoElement) {
2016
+ attachVideoListeners(node);
2017
+ }
2018
+ if (node instanceof Element) {
2019
+ node.querySelectorAll("video").forEach((v) => attachVideoListeners(v));
2020
+ }
2021
+ });
2022
+ });
2023
+ });
2024
+ observer.observe(document.body, { childList: true, subtree: true });
2025
+ this.cleanupFns.push(() => observer.disconnect());
2026
+ }
2027
+ setupErrorTracking() {
2028
+ if (typeof window === "undefined") return;
2029
+ const errorHandler = (e) => {
2030
+ this.tracker.send("error", {
2031
+ message: e.message,
2032
+ filename: e.filename,
2033
+ lineno: e.lineno,
2034
+ colno: e.colno,
2035
+ stack: _optionalChain([e, 'access', _38 => _38.error, 'optionalAccess', _39 => _39.stack]),
2036
+ url: window.location.href,
2037
+ type: "uncaught_error"
2038
+ });
2039
+ };
2040
+ const rejectionHandler = (e) => {
2041
+ const reason = e.reason instanceof Error ? e.reason.message : String(e.reason);
2042
+ const stack = e.reason instanceof Error ? e.reason.stack : void 0;
2043
+ this.tracker.send("error", {
2044
+ message: reason,
2045
+ stack,
2046
+ url: window.location.href,
2047
+ type: "unhandled_rejection"
2048
+ });
2049
+ };
2050
+ window.addEventListener("error", errorHandler);
2051
+ window.addEventListener("unhandledrejection", rejectionHandler);
2052
+ this.cleanupFns.push(() => {
2053
+ window.removeEventListener("error", errorHandler);
2054
+ window.removeEventListener("unhandledrejection", rejectionHandler);
2055
+ });
2056
+ }
2057
+ setupRouteTracking() {
2058
+ if (typeof window === "undefined" || typeof window.history === "undefined")
2059
+ return;
2060
+ const originalPushState = history.pushState.bind(history);
2061
+ const originalReplaceState = history.replaceState.bind(history);
2062
+ history.pushState = (...args) => {
2063
+ const prevPath = window.location.pathname;
2064
+ originalPushState(...args);
2065
+ if (!this.isInitializedByReactProvider()) {
2066
+ this.pageView(prevPath);
2067
+ }
2068
+ };
2069
+ history.replaceState = (...args) => {
2070
+ originalReplaceState(...args);
2071
+ };
2072
+ const popStateHandler = () => {
2073
+ if (!this.isInitializedByReactProvider()) {
2074
+ this.pageView();
2075
+ }
2076
+ };
2077
+ window.addEventListener("popstate", popStateHandler);
2078
+ this.cleanupFns.push(() => {
2079
+ history.pushState = originalPushState;
2080
+ history.replaceState = originalReplaceState;
2081
+ window.removeEventListener("popstate", popStateHandler);
2082
+ });
2083
+ }
2084
+ isInitializedByReactProvider() {
2085
+ return !!document.getElementById("__nexus_react_active");
2086
+ }
2087
+ async identify(userId, traits = {}) {
2088
+ return this.sendIdentityRequest("identify", { user_id: userId, traits });
2089
+ }
2090
+ async group(groupId, traits = {}) {
2091
+ return this.sendIdentityRequest("group", { group_id: groupId, traits });
2092
+ }
2093
+ async alias(newId) {
2094
+ return this.sendIdentityRequest("alias", {
2095
+ previous_id: this.tracker.getSession(),
2096
+ user_id: newId
2097
+ });
2098
+ }
2099
+ reset(performGdprScrub = false) {
2100
+ const config = this.tracker.config;
2101
+ this.tracker.stop();
2102
+ localStorage.removeItem("nexus_sid");
2103
+ localStorage.removeItem("nexus_vid");
2104
+ safeRemoveItem2("nexus_anon_id");
2105
+ this.tracker.clearIdentity();
2106
+ if (performGdprScrub) {
2107
+ const endpoint = `${config.analyticsUrl}/api/privacy/scrub`;
2108
+ const userId = this.tracker.getVisitorId();
2109
+ fetch(endpoint, {
2110
+ method: "DELETE",
2111
+ headers: {
2112
+ "Content-Type": "application/json",
2113
+ Authorization: `Bearer ${config.apiKey}`
2114
+ },
2115
+ body: JSON.stringify({
2116
+ project_id: config.projectId,
2117
+ user_id: userId
2118
+ })
2119
+ }).catch((err) => console.error("[NexusHub] Privacy scrub failed:", err));
2120
+ }
2121
+ window.location.reload();
2122
+ }
2123
+ track(eventName, properties = {}) {
2124
+ this.tracker.send(
2125
+ "custom_event",
2126
+ { event_name: eventName, ...properties },
2127
+ eventName
2128
+ );
2129
+ }
2130
+ trackPurchase(orderData) {
2131
+ const ecommerce = {
2132
+ orderId: orderData.orderId,
2133
+ total: orderData.total,
2134
+ revenue: _nullishCoalesce(orderData.revenue, () => ( orderData.total)),
2135
+ currency: orderData.currency || "USD",
2136
+ products: orderData.products.map((p) => ({
2137
+ productId: p.id,
2138
+ sku: p.sku,
2139
+ name: p.name,
2140
+ price: p.price,
2141
+ quantity: p.quantity
2142
+ }))
2143
+ };
2144
+ this.tracker.send(
2145
+ "purchase",
2146
+ { order_id: orderData.orderId },
2147
+ "purchase",
2148
+ ecommerce
2149
+ );
2150
+ }
2151
+ trackError(error, context) {
2152
+ this.tracker.send("error", {
2153
+ message: error.message,
2154
+ stack: error.stack,
2155
+ context,
2156
+ url: typeof window !== "undefined" ? window.location.href : "",
2157
+ type: "manual"
2158
+ });
2159
+ }
2160
+ async sendIdentityRequest(type, data) {
2161
+ try {
2162
+ const config = this.tracker.config;
2163
+ const endpoint = `${config.analyticsUrl}/api/${type}`;
2164
+ const payload = {
2165
+ projectId: config.projectId,
2166
+ sessionId: this.tracker.getSession(),
2167
+ visitorId: this.tracker.getVisitorId(),
2168
+ anonymousId: this.tracker.getAnonymousId(),
2169
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2170
+ ...data
2171
+ };
2172
+ const response = await fetch(endpoint, {
2173
+ method: "POST",
2174
+ headers: {
2175
+ "Content-Type": "application/json",
2176
+ Authorization: `Bearer ${config.apiKey}`
2177
+ },
2178
+ body: JSON.stringify(payload)
2179
+ });
2180
+ return response.ok;
2181
+ } catch (error) {
2182
+ console.error(`[NexusHub] ${type} failed:`, error);
2183
+ return false;
2184
+ }
2185
+ }
2186
+ getSessionId() {
2187
+ return this.tracker.getSession();
2188
+ }
2189
+ stop(isFinalShutdown = false) {
2190
+ this.cleanupFns.forEach((fn) => fn());
2191
+ this.cleanupFns = [];
2192
+ if (isFinalShutdown) {
2193
+ this.tracker.send("session_end", {
2194
+ session_id: this.tracker.getSession(),
2195
+ duration: this.tracker.getSessionDuration(),
2196
+ max_scroll_depth: this.maxScrollDepth / 100
2197
+ });
2198
+ }
2199
+ this.tracker.stop();
2200
+ this.isInitialized = false;
2201
+ }
2202
+ };
2203
+ function getSelector(el, depth = 0) {
2204
+ if (!el || depth > 2) return "";
2205
+ const tag = el.tagName.toLowerCase();
2206
+ const id = el.id ? `#${el.id}` : "";
2207
+ const cls = el.className && typeof el.className === "string" ? `.${el.className.trim().split(/\s+/).slice(0, 2).join(".")}` : "";
2208
+ const self = `${tag}${id}${cls}`;
2209
+ const parent = el.parentElement && depth < 2 ? `${getSelector(el.parentElement, depth + 1)} > ` : "";
2210
+ return `${parent}${self}`;
2211
+ }
2212
+
2213
+ // src/client.ts
2214
+ var NexusClient = class {
2215
+ constructor(config) {
2216
+ const fullConfig = getFullConfig(config);
2217
+ this.config = {
2218
+ debug: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _40 => _40.debug]), () => ( false)),
2219
+ cacheStrategy: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _41 => _41.cacheStrategy]), () => ( "memory")),
2220
+ revalidateTime: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _42 => _42.revalidateTime]), () => ( 60)),
2221
+ timeout: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _43 => _43.timeout]), () => ( 1e4)),
2222
+ retries: _nullishCoalesce(_optionalChain([config, 'optionalAccess', _44 => _44.retries]), () => ( 3)),
2223
+ ...fullConfig
2224
+ };
2225
+ const errors = validateConfig(this.config);
2226
+ if (errors.length > 0) {
2227
+ console.warn("\u26A0\uFE0F NexusHub: Configuration issues:", errors.join(", "));
2228
+ if (!this.config.projectId) {
2229
+ console.warn("\u26A0\uFE0F NexusHub: No Project ID found. Tracking will fail.");
2230
+ }
2231
+ }
2232
+ this.content = new ContentEngine(this.config);
2233
+ if (typeof window !== "undefined") {
2234
+ this.analytics = new AnalyticsEngine(this.config);
2235
+ this.analytics.start();
2236
+ }
2237
+ }
2238
+ /**
2239
+ * Helper alias for cleaner content fetching.
2240
+ */
2241
+ getPage(slug, options) {
2242
+ return this.content.getPage(slug, options);
2243
+ }
2244
+ /**
2245
+ * Returns a readonly snapshot of the current config.
2246
+ */
2247
+ getConfig() {
2248
+ return { ...this.config };
2249
+ }
2250
+ /**
2251
+ * Updates specific config fields at runtime.
2252
+ * Replaces the previous pattern of `(nexus as any).config.projectId = x`
2253
+ * which bypassed TypeScript and mutated internal state unsafely.
2254
+ */
2255
+ updateConfig(updates) {
2256
+ this.config = { ...this.config, ...updates };
2257
+ }
2258
+ };
2259
+ var nexus = new NexusClient();
2260
+ var createNexusClient = (config) => new NexusClient(config);
2261
+
2262
+ // src/auth/context.tsx
2263
+
2264
+
2265
+
2266
+
2267
+
2268
+
2269
+ var _react = require('react'); var _react2 = _interopRequireDefault(_react);
2270
+ var _jsxruntime = require('react/jsx-runtime');
2271
+ var AuthContext = _react.createContext.call(void 0, null);
2272
+ var AuthProvider = ({
2273
+ children,
2274
+ config
2275
+ }) => {
2276
+ const [user, setUser] = _react.useState.call(void 0, null);
2277
+ const [isLoading, setIsLoading] = _react.useState.call(void 0, true);
2278
+ const [error, setError] = _react.useState.call(void 0, null);
2279
+ const AUTH_BASE = `${config.apiUrl}/auth/project/${config.projectId}`;
2280
+ const checkSession = _react.useCallback.call(void 0, async () => {
2281
+ try {
2282
+ const res = await fetch(`${AUTH_BASE}/me`, {
2283
+ headers: getHeaders(config)
2284
+ });
2285
+ if (res.ok) {
2286
+ const data = await res.json();
2287
+ setUser(data.user);
2288
+ if (nexus.analytics) {
2289
+ nexus.analytics.identify(data.user.id, {
2290
+ email: data.user.email,
2291
+ role: data.user.role,
2292
+ ...data.user.metadata
2293
+ });
2294
+ }
2295
+ } else {
2296
+ setUser(null);
2297
+ }
2298
+ } catch (err) {
2299
+ console.debug("[NexusHub Auth] Session check failed:", err);
2300
+ setUser(null);
2301
+ } finally {
2302
+ setIsLoading(false);
2303
+ }
2304
+ }, [AUTH_BASE, config]);
2305
+ _react.useEffect.call(void 0, () => {
2306
+ checkSession();
2307
+ }, [checkSession]);
2308
+ const login = async (creds) => {
2309
+ setIsLoading(true);
2310
+ setError(null);
2311
+ try {
2312
+ const res = await fetch(`${AUTH_BASE}/login`, {
2313
+ method: "POST",
2314
+ headers: getHeaders(config),
2315
+ body: JSON.stringify(creds)
2316
+ });
2317
+ if (!res.ok) throw await parseError(res);
2318
+ const data = await res.json();
2319
+ setUser(data.user);
2320
+ if (nexus.analytics) {
2321
+ await nexus.analytics.identify(data.user.id, {
2322
+ email: data.user.email,
2323
+ role: data.user.role,
2324
+ login_method: "email",
2325
+ ...data.user.metadata
2326
+ });
2327
+ }
2328
+ } catch (err) {
2329
+ setError(err);
2330
+ throw err;
2331
+ } finally {
2332
+ setIsLoading(false);
2333
+ }
2334
+ };
2335
+ const register = async (creds) => {
2336
+ setIsLoading(true);
2337
+ setError(null);
2338
+ try {
2339
+ const res = await fetch(`${AUTH_BASE}/register`, {
2340
+ method: "POST",
2341
+ headers: getHeaders(config),
2342
+ body: JSON.stringify(creds)
2343
+ });
2344
+ if (!res.ok) throw await parseError(res);
2345
+ const data = await res.json();
2346
+ setUser(data.user);
2347
+ if (nexus.analytics) {
2348
+ nexus.analytics.track("signup", { method: "email" });
2349
+ nexus.analytics.identify(data.user.id, {
2350
+ email: data.user.email,
2351
+ role: data.user.role,
2352
+ ...data.user.metadata
2353
+ });
2354
+ }
2355
+ } catch (err) {
2356
+ setError(err);
2357
+ throw err;
2358
+ } finally {
2359
+ setIsLoading(false);
2360
+ }
2361
+ };
2362
+ const logout = async () => {
2363
+ setIsLoading(true);
2364
+ try {
2365
+ await fetch(`${AUTH_BASE}/logout`, {
2366
+ method: "POST",
2367
+ headers: getHeaders(config)
2368
+ });
2369
+ } catch (e) {
2370
+ console.warn("Logout network error", e);
2371
+ } finally {
2372
+ setUser(null);
2373
+ setIsLoading(false);
2374
+ if (nexus.analytics) {
2375
+ nexus.analytics.track("logout");
2376
+ }
2377
+ }
2378
+ };
2379
+ const updateProfile = async (updates) => {
2380
+ try {
2381
+ const res = await fetch(`${AUTH_BASE}/profile`, {
2382
+ method: "PATCH",
2383
+ headers: getHeaders(config),
2384
+ body: JSON.stringify(updates)
2385
+ });
2386
+ if (!res.ok) throw await parseError(res);
2387
+ const data = await res.json();
2388
+ setUser(data.user);
2389
+ if (nexus.analytics) {
2390
+ nexus.analytics.identify(data.user.id, updates);
2391
+ }
2392
+ } catch (err) {
2393
+ setError(err);
2394
+ throw err;
2395
+ }
2396
+ };
2397
+ const requestPasswordReset = async (email) => {
2398
+ const res = await fetch(`${AUTH_BASE}/password/reset-request`, {
2399
+ method: "POST",
2400
+ headers: getHeaders(config),
2401
+ body: JSON.stringify({ email })
2402
+ });
2403
+ if (!res.ok) throw await parseError(res);
2404
+ };
2405
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
2406
+ AuthContext.Provider,
2407
+ {
2408
+ value: {
2409
+ user,
2410
+ isLoading,
2411
+ error,
2412
+ isAuthenticated: !!user,
2413
+ login,
2414
+ register,
2415
+ logout,
2416
+ updateProfile,
2417
+ requestPasswordReset
2418
+ },
2419
+ children
2420
+ }
2421
+ );
2422
+ };
2423
+ var useNexusAuth = () => {
2424
+ const context = _react.useContext.call(void 0, AuthContext);
2425
+ if (!context) {
2426
+ throw new Error("useNexusAuth must be used within a NexusProvider");
2427
+ }
2428
+ return context;
2429
+ };
2430
+ function getHeaders(config) {
2431
+ return {
2432
+ "Content-Type": "application/json",
2433
+ "x-nexus-project": config.projectId,
2434
+ Authorization: `Bearer ${config.apiKey}`
2435
+ // 👈 CRITICAL: Send the nx_pk_ key
2436
+ // Note: We do NOT send the Master API Key here.
2437
+ // This is client-side. The backend uses Cookies or public tokens.
2438
+ };
2439
+ }
2440
+ async function parseError(res) {
2441
+ try {
2442
+ const json = await res.json();
2443
+ return {
2444
+ status: res.status,
2445
+ code: json.code || "UNKNOWN_ERROR",
2446
+ message: json.message || "An error occurred during authentication"
2447
+ };
2448
+ } catch (e12) {
2449
+ return {
2450
+ status: res.status,
2451
+ code: "NETWORK_ERROR",
2452
+ message: res.statusText
2453
+ };
2454
+ }
2455
+ }
2456
+
2457
+ // src/components/NexusProvider.tsx
2458
+
2459
+
2460
+
2461
+
2462
+
2463
+
2464
+
2465
+
2466
+
2467
+ var _navigation = require('next/navigation');
2468
+
2469
+ var NexusContext = _react.createContext.call(void 0, nexus);
2470
+ var NexusLiveFeedContext = _react.createContext.call(void 0, {
2471
+ latestEvent: null,
2472
+ isConnected: false
2473
+ });
2474
+ var useNexusLiveFeed = () => _react2.default.useContext(NexusLiveFeedContext);
2475
+ function NexusAnalyticsTracker({
2476
+ disableAnalytics
2477
+ }) {
2478
+ const pathname = _navigation.usePathname.call(void 0, );
2479
+ const searchParams = _navigation.useSearchParams.call(void 0, );
2480
+ const prevPathRef = _react.useRef.call(void 0, "");
2481
+ const searchParamsString = searchParams.toString();
2482
+ _react.useEffect.call(void 0, () => {
2483
+ if (nexus.analytics && !disableAnalytics) {
2484
+ nexus.analytics.pageView(prevPathRef.current || document.referrer);
2485
+ prevPathRef.current = pathname;
2486
+ }
2487
+ }, [pathname, searchParamsString, disableAnalytics]);
2488
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "div", { id: "__nexus_react_active", style: { display: "none" } });
2489
+ }
2490
+ var NexusProvider = ({
2491
+ children,
2492
+ projectId,
2493
+ disableAnalytics = false,
2494
+ hasConsent = true,
2495
+ // NEW: default true to preserve existing behaviour
2496
+ enableLiveFeed = false,
2497
+ // NEW
2498
+ onLiveEvent
2499
+ // NEW
2500
+ }) => {
2501
+ const isInitialized = _react.useRef.call(void 0, false);
2502
+ const socketRef = _react.useRef.call(void 0, null);
2503
+ const [latestEvent, setLatestEvent] = _react.useState.call(void 0,
2504
+ null
2505
+ );
2506
+ const [isConnected, setIsConnected] = _react.useState.call(void 0, false);
2507
+ const liveFeedValue = _react.useMemo.call(void 0,
2508
+ () => ({ latestEvent, isConnected }),
2509
+ [latestEvent, isConnected]
2510
+ );
2511
+ const config = _react.useMemo.call(void 0, () => {
2512
+ if (projectId && nexus.getConfig().projectId !== projectId) {
2513
+ nexus.updateConfig({ projectId });
2514
+ }
2515
+ return nexus.getConfig();
2516
+ }, [projectId]);
2517
+ _react.useEffect.call(void 0, () => {
2518
+ if (typeof window === "undefined" || disableAnalytics || !hasConsent)
2519
+ return;
2520
+ if (!isInitialized.current) {
2521
+ if (!nexus.analytics) {
2522
+ nexus.analytics = new AnalyticsEngine(nexus.getConfig());
2523
+ }
2524
+ nexus.analytics.start();
2525
+ isInitialized.current = true;
2526
+ if (nexus.getConfig().debug) {
2527
+ console.log("[NexusHub] \u{1F680} Provider initialized analytics");
2528
+ }
2529
+ }
2530
+ return () => {
2531
+ if (nexus.analytics) {
2532
+ nexus.analytics.stop();
2533
+ isInitialized.current = false;
2534
+ }
2535
+ };
2536
+ }, [disableAnalytics, hasConsent]);
2537
+ const connectLiveFeed = _react.useCallback.call(void 0, async () => {
2538
+ if (typeof window === "undefined" || !enableLiveFeed) return;
2539
+ try {
2540
+ const { io } = await Promise.resolve().then(() => _interopRequireWildcard(require("socket.io-client")));
2541
+ const cfg = nexus.getConfig();
2542
+ const wsUrl = cfg.apiUrl || "http://localhost:3001";
2543
+ const socket = io(`${wsUrl}/analytics`, {
2544
+ auth: { token: cfg.apiKey },
2545
+ query: { projectId: cfg.projectId },
2546
+ transports: ["websocket"],
2547
+ reconnectionAttempts: 5,
2548
+ reconnectionDelay: 2e3
2549
+ });
2550
+ socket.on("connect", () => {
2551
+ setIsConnected(true);
2552
+ if (cfg.debug) console.log("[NexusHub] \u{1F534} Live feed connected");
2553
+ });
2554
+ socket.on("disconnect", () => {
2555
+ setIsConnected(false);
2556
+ if (cfg.debug) console.log("[NexusHub] Live feed disconnected");
2557
+ });
2558
+ socket.on("live_event", (event) => {
2559
+ setLatestEvent(event);
2560
+ _optionalChain([onLiveEvent, 'optionalCall', _45 => _45(event)]);
2561
+ });
2562
+ socketRef.current = socket;
2563
+ } catch (err) {
2564
+ console.error("[NexusHub] Live feed connection failed:", err);
2565
+ }
2566
+ }, [enableLiveFeed, onLiveEvent]);
2567
+ _react.useEffect.call(void 0, () => {
2568
+ if (enableLiveFeed) {
2569
+ connectLiveFeed();
2570
+ }
2571
+ return () => {
2572
+ if (socketRef.current) {
2573
+ socketRef.current.disconnect();
2574
+ socketRef.current = null;
2575
+ setIsConnected(false);
2576
+ }
2577
+ };
2578
+ }, [enableLiveFeed, connectLiveFeed]);
2579
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, NexusContext.Provider, { value: nexus, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, NexusLiveFeedContext.Provider, { value: liveFeedValue, children: /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, AuthProvider, { config, children: [
2580
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _react.Suspense, { fallback: null, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, NexusAnalyticsTracker, { disableAnalytics }) }),
2581
+ children
2582
+ ] }) }) });
2583
+ };
2584
+ var useNexus = () => {
2585
+ const context = _react2.default.useContext(NexusContext);
2586
+ if (!context) {
2587
+ throw new Error("useNexus must be used within a NexusProvider");
2588
+ }
2589
+ return context;
2590
+ };
2591
+ var useNexusAnalytics = () => {
2592
+ const client = useNexus();
2593
+ if (!client.analytics) {
2594
+ return {
2595
+ track: () => {
2596
+ },
2597
+ identify: async () => false,
2598
+ group: async () => false,
2599
+ alias: async () => false,
2600
+ trackPurchase: () => {
2601
+ },
2602
+ trackError: () => {
2603
+ },
2604
+ reset: () => {
2605
+ }
2606
+ };
2607
+ }
2608
+ return {
2609
+ track: client.analytics.track.bind(client.analytics),
2610
+ identify: client.analytics.identify.bind(client.analytics),
2611
+ group: client.analytics.group.bind(client.analytics),
2612
+ alias: client.analytics.alias.bind(client.analytics),
2613
+ trackPurchase: client.analytics.trackPurchase.bind(client.analytics),
2614
+ trackError: client.analytics.trackError.bind(client.analytics),
2615
+ reset: client.analytics.reset.bind(client.analytics)
2616
+ };
2617
+ };
2618
+
2619
+
2620
+
2621
+
2622
+
2623
+
2624
+
2625
+
2626
+
2627
+
2628
+
2629
+
2630
+
2631
+
2632
+
2633
+
2634
+
2635
+
2636
+
2637
+
2638
+
2639
+
2640
+
2641
+
2642
+
2643
+ exports.DEFAULT_API_URL = DEFAULT_API_URL; exports.DEFAULT_ANALYTICS_URL = DEFAULT_ANALYTICS_URL; exports.LOCAL_NEST_URL = LOCAL_NEST_URL; exports.LOCAL_RUST_URL = LOCAL_RUST_URL; exports.getEnvConfig = getEnvConfig; exports.mergeConfigs = mergeConfigs; exports.getFullConfig = getFullConfig; exports.validateConfig = validateConfig; exports.CacheTags = CacheTags; exports.MemoryCache = MemoryCache; exports.BrowserCache = BrowserCache; exports.LocalCacheProxy = LocalCacheProxy; exports.ContentEngine = ContentEngine; exports.AnalyticsEngine = AnalyticsEngine; exports.NexusClient = NexusClient; exports.nexus = nexus; exports.createNexusClient = createNexusClient; exports.AuthProvider = AuthProvider; exports.useNexusAuth = useNexusAuth; exports.useNexusLiveFeed = useNexusLiveFeed; exports.NexusProvider = NexusProvider; exports.useNexus = useNexus; exports.useNexusAnalytics = useNexusAnalytics;