@nexushub/client 0.0.4 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1984 @@
1
+ import { LocalCache } from './chunk-BPQMAYT3.js';
2
+ export { LocalCache } from './chunk-BPQMAYT3.js';
3
+ import { onCLS, onLCP, onTTFB, onINP, onFCP } from 'web-vitals';
4
+ import { createContext, useState, useCallback, useEffect, useContext, useRef, useMemo } from 'react';
5
+ import { usePathname, useSearchParams } from 'next/navigation';
6
+ import { jsx } from 'react/jsx-runtime';
7
+
8
+ // src/config.ts
9
+ var DEFAULT_API_URL = "http://localhost:3001";
10
+ var DEFAULT_ANALYTICS_URL = "http://localhost:3002";
11
+ var LOCAL_NEST_URL = "http://localhost:3001";
12
+ var LOCAL_RUST_URL = "http://localhost:3002";
13
+ var hasEnv = () => {
14
+ return typeof process !== "undefined" && typeof process.env !== "undefined" && Object.keys(process.env).length > 0;
15
+ };
16
+ var getEnvConfig = () => {
17
+ const env = hasEnv() ? process.env : {};
18
+ const isDev = env.NODE_ENV === "development" || env.NEXT_PUBLIC_NODE_ENV === "development";
19
+ const projectId = env.NEXT_PUBLIC_NEXUS_ID ?? env.NEXUS_PROJECT_ID;
20
+ const apiKey = env.NEXT_PUBLIC_NEXUS_KEY ?? env.NEXUS_API_KEY;
21
+ const apiUrl = env.NEXT_PUBLIC_NEXUS_API_URL ?? env.NEXUS_API_URL ?? (isDev ? LOCAL_NEST_URL : DEFAULT_API_URL);
22
+ const analyticsUrl = env.NEXT_PUBLIC_NEXUS_ANALYTICS_URL ?? (apiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL);
23
+ return {
24
+ projectId,
25
+ apiKey,
26
+ apiUrl,
27
+ analyticsUrl
28
+ };
29
+ };
30
+ var mergeConfigs = (base, override) => {
31
+ const mergedApiUrl = override.apiUrl || base.apiUrl || DEFAULT_API_URL;
32
+ const mergedAnalyticsUrl = override.analyticsUrl || base.analyticsUrl || (mergedApiUrl.includes("localhost") ? LOCAL_RUST_URL : DEFAULT_ANALYTICS_URL);
33
+ return {
34
+ ...base,
35
+ ...override,
36
+ apiUrl: mergedApiUrl,
37
+ analyticsUrl: mergedAnalyticsUrl,
38
+ projectId: override.projectId || base.projectId
39
+ };
40
+ };
41
+ var getFullConfig = (partialConfig) => {
42
+ const envConfig = getEnvConfig();
43
+ return mergeConfigs(envConfig, partialConfig || {});
44
+ };
45
+ var validateConfig = (config) => {
46
+ const errors = [];
47
+ if (!config.projectId) errors.push("Missing projectId");
48
+ if (!config.apiUrl) errors.push("Missing apiUrl");
49
+ if (config.apiUrl && !config.apiUrl.startsWith("http")) {
50
+ errors.push("apiUrl must be a valid URL (http:// or https://)");
51
+ }
52
+ return errors;
53
+ };
54
+
55
+ // src/content/cache-implementations.ts
56
+ var CacheTags = {
57
+ project: (projectId) => `nexus_project_${projectId}`,
58
+ content: (slug) => `content_${slug}`,
59
+ collection: (collectionId) => `collection_${collectionId}`,
60
+ global: "nexus_global_config",
61
+ user: (userId) => `user_${userId}`,
62
+ media: (mediaId) => `media_${mediaId}`
63
+ };
64
+ var MemoryCache = class {
65
+ constructor(options = {}) {
66
+ this.cache = /* @__PURE__ */ new Map();
67
+ this.tagIndex = /* @__PURE__ */ new Map();
68
+ this.stats = {
69
+ size: 0,
70
+ hits: 0,
71
+ misses: 0,
72
+ hitRate: 0,
73
+ evictions: 0
74
+ };
75
+ this.maxSize = options.maxSize || 1e3;
76
+ this.defaultTTL = options.ttl || 5 * 60 * 1e3;
77
+ }
78
+ set(key, data, options = {}) {
79
+ if (this.cache.size >= this.maxSize) {
80
+ this.evictLRU();
81
+ }
82
+ const metadata = {
83
+ timestamp: Date.now(),
84
+ expiresAt: Date.now() + (options.ttl || this.defaultTTL),
85
+ tags: options.tags || [],
86
+ size: this.calculateSize(data)
87
+ };
88
+ this.cache.set(key, { data, metadata });
89
+ this.stats.size = this.cache.size;
90
+ metadata.tags.forEach((tag) => {
91
+ if (!this.tagIndex.has(tag)) {
92
+ this.tagIndex.set(tag, /* @__PURE__ */ new Set());
93
+ }
94
+ this.tagIndex.get(tag).add(key);
95
+ });
96
+ }
97
+ get(key) {
98
+ const entry = this.cache.get(key);
99
+ if (!entry) {
100
+ this.stats.misses++;
101
+ this.updateHitRate();
102
+ return null;
103
+ }
104
+ if (Date.now() > entry.metadata.expiresAt) {
105
+ this.delete(key);
106
+ this.stats.misses++;
107
+ this.updateHitRate();
108
+ return null;
109
+ }
110
+ entry.metadata.timestamp = Date.now();
111
+ this.stats.hits++;
112
+ this.updateHitRate();
113
+ return entry;
114
+ }
115
+ delete(key) {
116
+ const entry = this.cache.get(key);
117
+ if (!entry) return false;
118
+ entry.metadata.tags.forEach((tag) => {
119
+ const keys = this.tagIndex.get(tag);
120
+ if (keys) {
121
+ keys.delete(key);
122
+ if (keys.size === 0) {
123
+ this.tagIndex.delete(tag);
124
+ }
125
+ }
126
+ });
127
+ this.cache.delete(key);
128
+ this.stats.size = this.cache.size;
129
+ return true;
130
+ }
131
+ invalidateByTags(tags) {
132
+ const keysToDelete = /* @__PURE__ */ new Set();
133
+ tags.forEach((tag) => {
134
+ const keys = this.tagIndex.get(tag);
135
+ if (keys) {
136
+ keys.forEach((key) => keysToDelete.add(key));
137
+ this.tagIndex.delete(tag);
138
+ }
139
+ });
140
+ keysToDelete.forEach((key) => this.delete(key));
141
+ if (process.env.NODE_ENV === "development") {
142
+ console.log(
143
+ `[MemoryCache] Invalidated ${keysToDelete.size} entries by tags: ${tags.join(", ")}`
144
+ );
145
+ }
146
+ }
147
+ clear() {
148
+ this.cache.clear();
149
+ this.tagIndex.clear();
150
+ this.stats = {
151
+ size: 0,
152
+ hits: 0,
153
+ misses: 0,
154
+ hitRate: 0,
155
+ evictions: 0
156
+ };
157
+ }
158
+ getStats() {
159
+ return { ...this.stats };
160
+ }
161
+ evictLRU() {
162
+ let oldestKey = null;
163
+ let oldestTime = Infinity;
164
+ for (const [key, entry] of this.cache.entries()) {
165
+ if (entry.metadata.timestamp < oldestTime) {
166
+ oldestTime = entry.metadata.timestamp;
167
+ oldestKey = key;
168
+ }
169
+ }
170
+ if (oldestKey) {
171
+ this.delete(oldestKey);
172
+ this.stats.evictions++;
173
+ }
174
+ }
175
+ calculateSize(data) {
176
+ try {
177
+ const jsonString = JSON.stringify(data);
178
+ return new Blob([jsonString]).size;
179
+ } catch {
180
+ return 0;
181
+ }
182
+ }
183
+ updateHitRate() {
184
+ const total = this.stats.hits + this.stats.misses;
185
+ this.stats.hitRate = total > 0 ? this.stats.hits / total : 0;
186
+ }
187
+ };
188
+ var BrowserCache = class {
189
+ constructor(projectId) {
190
+ this.projectId = projectId;
191
+ this.prefix = "nexushub_";
192
+ this.maxSize = 5 * 1024 * 1024;
193
+ // 5MB standard LocalStorage limit
194
+ this.currentSize = 0;
195
+ if (typeof window !== "undefined") {
196
+ this.calculateCurrentSize();
197
+ }
198
+ }
199
+ set(key, data, ttl = 5 * 60 * 1e3) {
200
+ if (typeof window === "undefined") return;
201
+ const storageKey = this.getStorageKey(key);
202
+ const entry = {
203
+ data,
204
+ metadata: {
205
+ timestamp: Date.now(),
206
+ expiresAt: Date.now() + ttl,
207
+ size: this.calculateStorageSize(data)
208
+ }
209
+ };
210
+ const serialized = JSON.stringify(entry);
211
+ const newSize = new Blob([serialized]).size;
212
+ if (this.currentSize + newSize > this.maxSize) {
213
+ this.evictOldest();
214
+ }
215
+ try {
216
+ localStorage.setItem(storageKey, serialized);
217
+ this.currentSize += newSize;
218
+ } catch (error) {
219
+ console.warn("[BrowserCache] Failed to save to localStorage:", error);
220
+ this.evictOldest();
221
+ try {
222
+ localStorage.setItem(storageKey, serialized);
223
+ } catch (e) {
224
+ }
225
+ }
226
+ }
227
+ get(key) {
228
+ if (typeof window === "undefined") return null;
229
+ const storageKey = this.getStorageKey(key);
230
+ const item = localStorage.getItem(storageKey);
231
+ if (!item) return null;
232
+ try {
233
+ const entry = JSON.parse(item);
234
+ if (Date.now() > entry.metadata.expiresAt) {
235
+ this.delete(key);
236
+ return null;
237
+ }
238
+ return entry.data;
239
+ } catch {
240
+ this.delete(key);
241
+ return null;
242
+ }
243
+ }
244
+ delete(key) {
245
+ if (typeof window === "undefined") return;
246
+ const storageKey = this.getStorageKey(key);
247
+ const item = localStorage.getItem(storageKey);
248
+ if (item) {
249
+ this.currentSize -= new Blob([item]).size;
250
+ }
251
+ localStorage.removeItem(storageKey);
252
+ }
253
+ clear() {
254
+ if (typeof window === "undefined") return;
255
+ const keysToRemove = [];
256
+ for (let i = 0; i < localStorage.length; i++) {
257
+ const key = localStorage.key(i);
258
+ if (key?.startsWith(this.prefix)) {
259
+ keysToRemove.push(key);
260
+ }
261
+ }
262
+ keysToRemove.forEach((key) => localStorage.removeItem(key));
263
+ this.currentSize = 0;
264
+ }
265
+ getStorageKey(key) {
266
+ return `${this.prefix}${this.projectId}_${key}`;
267
+ }
268
+ calculateCurrentSize() {
269
+ this.currentSize = 0;
270
+ for (let i = 0; i < localStorage.length; i++) {
271
+ const key = localStorage.key(i);
272
+ if (key?.startsWith(this.prefix)) {
273
+ const item = localStorage.getItem(key);
274
+ if (item) {
275
+ this.currentSize += new Blob([item]).size;
276
+ }
277
+ }
278
+ }
279
+ }
280
+ calculateStorageSize(data) {
281
+ return new Blob([JSON.stringify(data)]).size;
282
+ }
283
+ evictOldest() {
284
+ let oldestKey = null;
285
+ let oldestTime = Infinity;
286
+ for (let i = 0; i < localStorage.length; i++) {
287
+ const key = localStorage.key(i);
288
+ if (key?.startsWith(this.prefix)) {
289
+ const item = localStorage.getItem(key);
290
+ if (item) {
291
+ try {
292
+ const entry = JSON.parse(item);
293
+ if (entry.metadata.timestamp < oldestTime) {
294
+ oldestTime = entry.metadata.timestamp;
295
+ oldestKey = key;
296
+ }
297
+ } catch {
298
+ localStorage.removeItem(key);
299
+ }
300
+ }
301
+ }
302
+ }
303
+ if (oldestKey) {
304
+ const item = localStorage.getItem(oldestKey);
305
+ if (item) {
306
+ this.currentSize -= new Blob([item]).size;
307
+ }
308
+ localStorage.removeItem(oldestKey);
309
+ }
310
+ }
311
+ };
312
+
313
+ // src/content/strategies.ts
314
+ var RateLimiter = class {
315
+ constructor(config) {
316
+ this.requests = [];
317
+ this.config = config;
318
+ }
319
+ async checkLimit() {
320
+ const now = Date.now();
321
+ const windowStart = now - this.config.timeWindow;
322
+ this.requests = this.requests.filter((time) => time > windowStart);
323
+ if (this.requests.length >= this.config.maxRequests) {
324
+ this.requests[0];
325
+ const waitTime = windowStart + this.config.timeWindow - now;
326
+ if (waitTime > 0) {
327
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
328
+ return this.checkLimit();
329
+ }
330
+ }
331
+ this.requests.push(now);
332
+ }
333
+ getStats() {
334
+ const now = Date.now();
335
+ const windowStart = now - this.config.timeWindow;
336
+ const currentRequests = this.requests.filter((time) => time > windowStart).length;
337
+ return {
338
+ currentRequests,
339
+ limit: this.config.maxRequests
340
+ };
341
+ }
342
+ };
343
+ var ExponentialBackoff = class {
344
+ constructor(config) {
345
+ this.config = {
346
+ jitter: true,
347
+ ...config
348
+ };
349
+ }
350
+ async execute(fn, onRetry) {
351
+ let lastError;
352
+ for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
353
+ try {
354
+ return await fn();
355
+ } catch (error) {
356
+ lastError = error;
357
+ if (this.isClientError(error) && !this.isRateLimitError(error)) {
358
+ throw error;
359
+ }
360
+ if (attempt === this.config.maxRetries) {
361
+ break;
362
+ }
363
+ const delay = this.calculateDelay(attempt);
364
+ if (onRetry) {
365
+ onRetry(attempt + 1, delay, error);
366
+ }
367
+ await new Promise((resolve) => setTimeout(resolve, delay));
368
+ }
369
+ }
370
+ throw lastError;
371
+ }
372
+ calculateDelay(attempt) {
373
+ let delay = this.config.baseDelay * Math.pow(2, attempt);
374
+ delay = Math.min(delay, this.config.maxDelay);
375
+ if (this.config.jitter) {
376
+ delay = delay * (0.5 + Math.random());
377
+ }
378
+ return delay;
379
+ }
380
+ isClientError(error) {
381
+ return error?.status >= 400 && error?.status < 500;
382
+ }
383
+ isRateLimitError(error) {
384
+ return error?.status === 429;
385
+ }
386
+ };
387
+ var CircuitBreaker = class {
388
+ constructor() {
389
+ this.state = 0 /* CLOSED */;
390
+ this.failures = 0;
391
+ this.lastFailureTime = 0;
392
+ this.failureThreshold = 5;
393
+ this.resetTimeout = 3e4;
394
+ }
395
+ // 30 seconds
396
+ isOpen() {
397
+ if (this.state === 1 /* OPEN */) {
398
+ const now = Date.now();
399
+ if (now - this.lastFailureTime > this.resetTimeout) {
400
+ this.state = 2 /* HALF_OPEN */;
401
+ return false;
402
+ }
403
+ return true;
404
+ }
405
+ return false;
406
+ }
407
+ recordSuccess() {
408
+ this.failures = 0;
409
+ this.state = 0 /* CLOSED */;
410
+ }
411
+ recordFailure() {
412
+ this.failures++;
413
+ this.lastFailureTime = Date.now();
414
+ if (this.failures >= this.failureThreshold) {
415
+ this.state = 1 /* OPEN */;
416
+ if (process.env.NODE_ENV === "development") {
417
+ console.warn(`[NexusHub] \u{1F50C} Circuit Breaker OPEN. Pausing network requests.`);
418
+ }
419
+ }
420
+ }
421
+ };
422
+ var RequestBatcher = class {
423
+ constructor(batchWindow = 10, maxBatchSize = 20) {
424
+ this.batchWindow = batchWindow;
425
+ this.maxBatchSize = maxBatchSize;
426
+ this.batch = [];
427
+ this.processing = false;
428
+ }
429
+ async schedule(key, request) {
430
+ return new Promise((resolve, reject) => {
431
+ this.batch.push({ key, resolve, reject });
432
+ if (this.batch.length >= this.maxBatchSize) {
433
+ this.processBatch(request);
434
+ } else if (!this.batchTimeout) {
435
+ this.batchTimeout = setTimeout(
436
+ () => this.processBatch(request),
437
+ this.batchWindow
438
+ );
439
+ }
440
+ });
441
+ }
442
+ async processBatch(request) {
443
+ if (this.processing || this.batch.length === 0) return;
444
+ this.processing = true;
445
+ if (this.batchTimeout) {
446
+ clearTimeout(this.batchTimeout);
447
+ this.batchTimeout = void 0;
448
+ }
449
+ const currentBatch = [...this.batch];
450
+ this.batch = [];
451
+ try {
452
+ const result = await request();
453
+ currentBatch.forEach((item) => {
454
+ item.resolve(result);
455
+ });
456
+ } catch (error) {
457
+ currentBatch.forEach((item) => {
458
+ item.reject(error);
459
+ });
460
+ } finally {
461
+ this.processing = false;
462
+ if (this.batch.length > 0) {
463
+ setTimeout(() => this.processBatch(request), 0);
464
+ }
465
+ }
466
+ }
467
+ };
468
+
469
+ // src/content/utils.ts
470
+ function validateSlug(slug) {
471
+ if (!slug || typeof slug !== "string") {
472
+ throw new Error("Slug must be a non-empty string");
473
+ }
474
+ if (!/^[a-z0-9-_]+$/.test(slug)) {
475
+ throw new Error("Slug can only contain lowercase letters, numbers, hyphens, and underscores");
476
+ }
477
+ }
478
+ function normalizeQuery(query) {
479
+ const normalized = { ...query };
480
+ normalized.page = Math.max(1, normalized.page || 1);
481
+ normalized.limit = Math.min(100, Math.max(1, normalized.limit || 10));
482
+ normalized.order = normalized.order || "desc";
483
+ if (normalized.page < 1) {
484
+ throw new Error("Page must be greater than 0");
485
+ }
486
+ if (normalized.limit < 1 || normalized.limit > 100) {
487
+ throw new Error("Limit must be between 1 and 100");
488
+ }
489
+ return normalized;
490
+ }
491
+ function buildQueryString(query) {
492
+ const params = new URLSearchParams();
493
+ if (query.page) params.append("page", query.page.toString());
494
+ if (query.limit) params.append("limit", query.limit.toString());
495
+ if (query.sort) params.append("sort", query.sort);
496
+ if (query.order) params.append("order", query.order);
497
+ if (query.search) params.append("search", query.search);
498
+ if (query.include?.length) {
499
+ params.append("include", query.include.join(","));
500
+ }
501
+ if (query.fields?.length) {
502
+ params.append("fields", query.fields.join(","));
503
+ }
504
+ if (query.filter) {
505
+ params.append("filter", JSON.stringify(query.filter));
506
+ }
507
+ return params.toString();
508
+ }
509
+ function measurePerformance(name, fn) {
510
+ const start = performance.now();
511
+ const result = fn();
512
+ const end = performance.now();
513
+ if (process.env.NODE_ENV === "development") {
514
+ console.log(`\u23F1\uFE0F ${name}: ${(end - start).toFixed(2)}ms`);
515
+ }
516
+ return { result, duration: end - start };
517
+ }
518
+
519
+ // src/content/index.ts
520
+ var ContentEngine = class {
521
+ constructor(config) {
522
+ this.config = config;
523
+ this.isServer = typeof window === "undefined";
524
+ this.localCache = new LocalCache();
525
+ this.memoryCache = new MemoryCache({
526
+ maxSize: 500,
527
+ ttl: 5 * 60 * 1e3
528
+ // 5 minutes
529
+ });
530
+ if (!this.isServer) {
531
+ this.browserCache = new BrowserCache(config.projectId);
532
+ }
533
+ this.rateLimiter = new RateLimiter({
534
+ maxRequests: config.debug ? 100 : 50,
535
+ timeWindow: 6e4
536
+ });
537
+ this.backoff = new ExponentialBackoff({
538
+ maxRetries: config.retries || 3,
539
+ baseDelay: 100,
540
+ maxDelay: 5e3,
541
+ jitter: true
542
+ });
543
+ this.requestBatcher = new RequestBatcher(20, 50);
544
+ this.circuitBreaker = new CircuitBreaker();
545
+ this.defaultRevalidate = config.revalidateTime || 60;
546
+ this.cacheStrategy = config.cacheStrategy || "memory";
547
+ if (!this.isServer) {
548
+ window.addEventListener("beforeunload", this.cleanup.bind(this));
549
+ }
550
+ }
551
+ /**
552
+ * Fetch a Single Page with full strategy pipeline
553
+ */
554
+ async getPage(slug, options = {}) {
555
+ const { result, duration } = measurePerformance(
556
+ `getPage("${slug}")`,
557
+ () => this._getPage(slug, options)
558
+ );
559
+ if (this.config.debug && duration > 100) {
560
+ console.warn(`[NexusHub] \u26A0\uFE0F getPage("${slug}") took ${duration.toFixed(2)}ms`);
561
+ }
562
+ return result;
563
+ }
564
+ async _getPage(slug, options = {}) {
565
+ validateSlug(slug);
566
+ const {
567
+ revalidate = this.defaultRevalidate,
568
+ tags = [],
569
+ forceRefresh = false,
570
+ includeMetadata = false
571
+ } = options;
572
+ const cacheKey = `page:${slug}`;
573
+ const cached = this.checkCaches(cacheKey, forceRefresh, includeMetadata);
574
+ if (cached) {
575
+ if (this.config.debug) console.log(`[NexusHub] \u26A1 Cache hit: ${slug}`);
576
+ return includeMetadata ? cached : cached.data;
577
+ }
578
+ if (this.circuitBreaker.isOpen()) {
579
+ throw new Error(`[NexusHub] Circuit open. API is unavailable.`);
580
+ }
581
+ try {
582
+ await this.rateLimiter.checkLimit();
583
+ const data = await this.backoff.execute(
584
+ async () => {
585
+ return this.fetchPage(slug, cacheKey, tags, revalidate, forceRefresh);
586
+ },
587
+ (attempt, delay, error) => {
588
+ if (this.config.debug) {
589
+ console.log(`[NexusHub] \u{1F504} Retry ${attempt} for '${slug}' after ${delay}ms: ${error.message}`);
590
+ }
591
+ }
592
+ );
593
+ this.circuitBreaker.recordSuccess();
594
+ return includeMetadata ? data : data.data;
595
+ } catch (error) {
596
+ this.circuitBreaker.recordFailure();
597
+ const staleCache = this.memoryCache.get(cacheKey);
598
+ if (staleCache && !forceRefresh) {
599
+ console.warn(`[NexusHub] \u26A0\uFE0F Serving stale content for '${slug}'`);
600
+ return includeMetadata ? staleCache : staleCache.data;
601
+ }
602
+ throw this.normalizeError(error, `Failed to fetch page '${slug}'`);
603
+ }
604
+ }
605
+ /**
606
+ * Fetch a Collection (Optimized)
607
+ */
608
+ async getCollection(collectionId, query = {}, options = {}) {
609
+ const { result, duration } = measurePerformance(
610
+ `getCollection("${collectionId}")`,
611
+ () => this._getCollection(collectionId, query, options)
612
+ );
613
+ if (this.config.debug && duration > 100) {
614
+ console.warn(`[NexusHub] \u26A0\uFE0F getCollection("${collectionId}") took ${duration.toFixed(2)}ms`);
615
+ }
616
+ return result;
617
+ }
618
+ async _getCollection(collectionId, query = {}, options = {}) {
619
+ const normalizedQuery = normalizeQuery(query);
620
+ const {
621
+ revalidate = this.defaultRevalidate,
622
+ tags = [],
623
+ forceRefresh = false,
624
+ includeMetadata = false
625
+ } = options;
626
+ const queryString = buildQueryString(normalizedQuery);
627
+ const cacheKey = `collection:${collectionId}:${queryString}`;
628
+ const cached = this.checkCaches(cacheKey, forceRefresh, includeMetadata);
629
+ if (cached) {
630
+ if (this.config.debug) {
631
+ console.log(`[NexusHub] \u26A1 Served collection '${collectionId}' from memory cache.`);
632
+ }
633
+ return includeMetadata ? cached : cached.data;
634
+ }
635
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
636
+ const localCollection = this.localCache.getCollection(collectionId);
637
+ if (localCollection) {
638
+ const result = this.applyLocalQuery(localCollection, normalizedQuery);
639
+ if (this.config.debug) {
640
+ console.log(`[NexusHub] \u{1F4C1} Served collection '${collectionId}' from local cache.`);
641
+ }
642
+ this.memoryCache.set(cacheKey, result, {
643
+ tags: [...tags, CacheTags.collection(collectionId)],
644
+ revalidate
645
+ });
646
+ return result;
647
+ }
648
+ }
649
+ if (this.circuitBreaker.isOpen()) throw new Error("Circuit open");
650
+ try {
651
+ await this.rateLimiter.checkLimit();
652
+ const result = await this.backoff.execute(async () => {
653
+ return this.fetchCollection(collectionId, normalizedQuery, cacheKey, tags, revalidate);
654
+ });
655
+ this.circuitBreaker.recordSuccess();
656
+ return includeMetadata ? result : result.data;
657
+ } catch (error) {
658
+ this.circuitBreaker.recordFailure();
659
+ const staleCache = this.memoryCache.get(cacheKey);
660
+ if (staleCache && !forceRefresh) {
661
+ console.warn(`[NexusHub] \u26A0\uFE0F Using stale cache for collection '${collectionId}'`);
662
+ return includeMetadata ? staleCache : staleCache.data;
663
+ }
664
+ throw this.normalizeError(error, `Failed to fetch collection '${collectionId}'`);
665
+ }
666
+ }
667
+ /**
668
+ * Fetch Global Settings with nested includes support
669
+ */
670
+ async getGlobals(options = {}) {
671
+ const {
672
+ include = [],
673
+ revalidate = this.defaultRevalidate,
674
+ forceRefresh = false
675
+ } = options;
676
+ const cacheKey = `globals:${include.join(",")}`;
677
+ if (!forceRefresh && this.cacheStrategy === "memory") {
678
+ const cached = this.memoryCache.get(cacheKey);
679
+ if (cached && this.isCacheValid(cached.metadata)) {
680
+ if (this.config.debug) console.log("[NexusHub] \u26A1 Served globals from memory cache.");
681
+ return cached.data;
682
+ }
683
+ }
684
+ if (!forceRefresh && !this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
685
+ const cached = this.browserCache.get(cacheKey);
686
+ if (cached) {
687
+ return cached;
688
+ }
689
+ }
690
+ if (!forceRefresh && process.env.NODE_ENV === "development") {
691
+ const localGlobals = this.localCache.getGlobals();
692
+ if (localGlobals) {
693
+ this.memoryCache.set(cacheKey, localGlobals, {
694
+ tags: [CacheTags.global],
695
+ revalidate
696
+ });
697
+ return localGlobals;
698
+ }
699
+ }
700
+ try {
701
+ await this.rateLimiter.checkLimit();
702
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/globals`;
703
+ const params = include.length > 0 ? `?include=${include.join(",")}` : "";
704
+ const res = await this.fetchWithTimeout(
705
+ `${url}${params}`,
706
+ {
707
+ method: "GET",
708
+ headers: this.getHeaders()
709
+ }
710
+ );
711
+ if (!res.ok) {
712
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
713
+ }
714
+ const json = await res.json();
715
+ const data = json.data || json;
716
+ this.writeCache(cacheKey, data, {
717
+ revalidate,
718
+ tags: [CacheTags.project(this.config.projectId), CacheTags.global]
719
+ });
720
+ return data;
721
+ } catch (error) {
722
+ const staleCache = this.memoryCache.get(cacheKey);
723
+ if (staleCache && !forceRefresh) {
724
+ console.warn("[NexusHub] \u26A0\uFE0F Using stale cache for globals");
725
+ return staleCache.data;
726
+ }
727
+ throw this.normalizeError(error, "Failed to fetch globals");
728
+ }
729
+ }
730
+ /**
731
+ * Get a single item from a collection (Uses Request Batching)
732
+ * If you call this 10 times in a loop, it sends 1 HTTP request.
733
+ */
734
+ async getItem(collectionId, itemId, options = {}) {
735
+ const cacheKey = `item:${collectionId}:${itemId}`;
736
+ if (this.cacheStrategy === "memory") {
737
+ const cached = this.memoryCache.get(cacheKey);
738
+ if (cached && this.isCacheValid(cached.metadata)) {
739
+ if (this.config.debug) {
740
+ console.log(`[NexusHub] \u26A1 Served item '${itemId}' from cache.`);
741
+ }
742
+ return cached.data;
743
+ }
744
+ }
745
+ return this.requestBatcher.schedule(cacheKey, async () => {
746
+ const params = new URLSearchParams();
747
+ if (options.include?.length) {
748
+ params.append("include", options.include.join(","));
749
+ }
750
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}/${itemId}?${params}`;
751
+ const res = await this.fetchWithTimeout(url, {
752
+ method: "GET",
753
+ headers: this.getHeaders()
754
+ });
755
+ if (!res.ok) {
756
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
757
+ }
758
+ const json = await res.json();
759
+ const data = json.data || json;
760
+ this.writeCache(cacheKey, data, {
761
+ revalidate: options.revalidate || this.defaultRevalidate,
762
+ tags: [
763
+ CacheTags.project(this.config.projectId),
764
+ CacheTags.collection(collectionId),
765
+ `item_${itemId}`,
766
+ ...options.tags || []
767
+ ]
768
+ });
769
+ return data;
770
+ });
771
+ }
772
+ /**
773
+ * Search across collections
774
+ */
775
+ async search(query, options = {}) {
776
+ const params = new URLSearchParams({
777
+ q: query,
778
+ limit: (options.limit || 20).toString()
779
+ });
780
+ if (options.collections?.length) {
781
+ params.append("collections", options.collections.join(","));
782
+ }
783
+ if (options.fields?.length) {
784
+ params.append("fields", options.fields.join(","));
785
+ }
786
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/search?${params}`;
787
+ const res = await this.fetchWithTimeout(url, {
788
+ method: "GET",
789
+ headers: this.getHeaders()
790
+ });
791
+ if (!res.ok) {
792
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
793
+ }
794
+ return await res.json();
795
+ }
796
+ /**
797
+ * Prefetch content for better performance
798
+ */
799
+ async prefetch(urls) {
800
+ if (typeof window !== "undefined" && "requestIdleCallback" in window) {
801
+ requestIdleCallback(async () => {
802
+ await Promise.allSettled(
803
+ urls.map((url) => fetch(url, { priority: "low" }))
804
+ );
805
+ });
806
+ }
807
+ }
808
+ /**
809
+ * Robust Real-time Subscriptions (SSE) with Auto-Reconnect
810
+ */
811
+ subscribeToUpdates(callback) {
812
+ if (this.isServer || typeof EventSource === "undefined") {
813
+ console.warn("[NexusHub] EventSource not supported in this environment");
814
+ return () => {
815
+ };
816
+ }
817
+ let eventSource = null;
818
+ let retryCount = 0;
819
+ let isClosed = false;
820
+ const connect = () => {
821
+ if (isClosed) return;
822
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/updates?key=${this.config.apiKey}`;
823
+ eventSource = new EventSource(url);
824
+ eventSource.onopen = () => {
825
+ retryCount = 0;
826
+ if (this.config.debug) console.log("[NexusHub] \u{1F7E2} Real-time stream connected");
827
+ };
828
+ eventSource.onmessage = (event) => {
829
+ try {
830
+ const data = JSON.parse(event.data);
831
+ if (data.type === "content.updated" && data.slug) {
832
+ this.invalidateCache([CacheTags.content(data.slug)]);
833
+ }
834
+ if (data.type === "collection.updated") {
835
+ this.invalidateCache([CacheTags.collection(data.collectionId)]);
836
+ }
837
+ callback(data);
838
+ } catch (e) {
839
+ console.error("[NexusHub] SSE Parse Error", e);
840
+ }
841
+ };
842
+ eventSource.onerror = () => {
843
+ eventSource?.close();
844
+ if (isClosed) return;
845
+ const timeout = Math.min(1e3 * Math.pow(2, retryCount), 1e4);
846
+ retryCount++;
847
+ console.warn(`[NexusHub] \u{1F534} Stream disconnected. Reconnecting in ${timeout}ms...`);
848
+ setTimeout(connect, timeout);
849
+ };
850
+ };
851
+ connect();
852
+ return () => {
853
+ isClosed = true;
854
+ eventSource?.close();
855
+ };
856
+ }
857
+ // --- CACHE MANAGEMENT ---
858
+ /**
859
+ * Check all caches in order of speed
860
+ */
861
+ checkCaches(key, forceRefresh, includeMetadata) {
862
+ if (forceRefresh) return null;
863
+ if (this.cacheStrategy === "memory") {
864
+ const cached = this.memoryCache.get(key);
865
+ if (cached && this.isCacheValid(cached.metadata)) {
866
+ return cached;
867
+ }
868
+ }
869
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
870
+ const cached = this.browserCache.get(key);
871
+ if (cached) {
872
+ return {
873
+ data: cached,
874
+ metadata: {
875
+ timestamp: 0,
876
+ expiresAt: Infinity,
877
+ tags: [],
878
+ etag: void 0
879
+ }
880
+ };
881
+ }
882
+ }
883
+ if (process.env.NODE_ENV === "development") {
884
+ if (key.startsWith("page:")) {
885
+ const slug = key.split(":")[1];
886
+ const local = this.localCache.getPage(slug);
887
+ if (local) {
888
+ return {
889
+ data: local,
890
+ metadata: {
891
+ timestamp: 0,
892
+ expiresAt: Infinity,
893
+ tags: [],
894
+ etag: void 0
895
+ }
896
+ };
897
+ }
898
+ }
899
+ }
900
+ return null;
901
+ }
902
+ writeCache(key, data, options) {
903
+ if (this.cacheStrategy === "memory") {
904
+ this.memoryCache.set(key, data, {
905
+ tags: options.tags,
906
+ revalidate: options.revalidate
907
+ });
908
+ }
909
+ if (!this.isServer && this.cacheStrategy === "localStorage" && this.browserCache) {
910
+ this.browserCache.set(key, data, options.revalidate * 1e3);
911
+ }
912
+ }
913
+ /**
914
+ * Invalidate cache by tags
915
+ */
916
+ invalidateCache(tags) {
917
+ this.memoryCache.invalidateByTags(tags);
918
+ if (this.config.debug) {
919
+ console.log(`[NexusHub] \u267B\uFE0F Invalidated cache for tags: ${tags.join(", ")}`);
920
+ }
921
+ }
922
+ /**
923
+ * Clear all caches
924
+ */
925
+ clearCache() {
926
+ this.memoryCache.clear();
927
+ if (this.browserCache) {
928
+ this.browserCache.clear();
929
+ }
930
+ if (this.config.debug) {
931
+ console.log("[NexusHub] \u{1F9F9} Cleared all caches");
932
+ }
933
+ }
934
+ /**
935
+ * Get cache statistics
936
+ */
937
+ getCacheStats() {
938
+ const stats = {
939
+ memory: this.memoryCache.getStats(),
940
+ local: { loaded: this.localCache.isLoaded() }
941
+ };
942
+ if (this.browserCache) {
943
+ stats.browser = { size: 0 };
944
+ }
945
+ return stats;
946
+ }
947
+ // --- REQUEST METHODS ---
948
+ async fetchPage(slug, cacheKey, tags, revalidate, forceRefresh) {
949
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/page/${slug}`;
950
+ if (this.config.debug) {
951
+ console.log(`[NexusHub] \u{1F310} Fetching: ${url}`);
952
+ }
953
+ const res = await this.fetchWithTimeout(url, {
954
+ method: "GET",
955
+ headers: this.getHeaders()
956
+ });
957
+ if (!res.ok) {
958
+ if (res.status === 404) {
959
+ throw new Error(`Page '${slug}' not found. Check your Dashboard or Seed data.`);
960
+ }
961
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
962
+ }
963
+ const json = await res.json();
964
+ const etag = res.headers.get("etag");
965
+ const cacheEntry = {
966
+ data: json.data,
967
+ metadata: {
968
+ timestamp: Date.now(),
969
+ etag: etag || void 0,
970
+ expiresAt: Date.now() + revalidate * 1e3,
971
+ tags: [...tags, CacheTags.content(slug)]
972
+ }
973
+ };
974
+ this.writeCache(cacheKey, cacheEntry.data, {
975
+ revalidate,
976
+ tags: [CacheTags.project(this.config.projectId), CacheTags.content(slug), ...tags]
977
+ });
978
+ return cacheEntry;
979
+ }
980
+ async fetchCollection(collectionId, query, cacheKey, tags, revalidate) {
981
+ const params = buildQueryString(query);
982
+ const url = `${this.config.apiUrl}/content/${this.config.projectId}/collection/${collectionId}?${params}`;
983
+ if (this.config.debug) {
984
+ console.log(`[NexusHub] \u{1F310} Fetching Collection: ${url}`);
985
+ }
986
+ const res = await this.fetchWithTimeout(url, {
987
+ method: "GET",
988
+ headers: this.getHeaders()
989
+ });
990
+ if (!res.ok) {
991
+ throw new Error(`API Error ${res.status}: ${res.statusText}`);
992
+ }
993
+ const json = await res.json();
994
+ const etag = res.headers.get("etag");
995
+ const cacheEntry = {
996
+ data: json,
997
+ metadata: {
998
+ timestamp: Date.now(),
999
+ etag: etag || void 0,
1000
+ expiresAt: Date.now() + revalidate * 1e3,
1001
+ tags: [...tags, CacheTags.collection(collectionId)]
1002
+ }
1003
+ };
1004
+ this.writeCache(cacheKey, cacheEntry.data, {
1005
+ revalidate,
1006
+ tags: [CacheTags.project(this.config.projectId), CacheTags.collection(collectionId), ...tags]
1007
+ });
1008
+ return cacheEntry;
1009
+ }
1010
+ // --- HELPER METHODS ---
1011
+ applyLocalQuery(items, query) {
1012
+ let filtered = [...items];
1013
+ if (query.search) {
1014
+ const searchLower = query.search.toLowerCase();
1015
+ filtered = filtered.filter(
1016
+ (item) => JSON.stringify(item).toLowerCase().includes(searchLower)
1017
+ );
1018
+ }
1019
+ if (query.filter) {
1020
+ filtered = filtered.filter((item) => {
1021
+ return Object.entries(query.filter).every(([key, value]) => {
1022
+ const itemValue = item[key];
1023
+ if (itemValue === void 0) return false;
1024
+ if (Array.isArray(value)) {
1025
+ return value.includes(itemValue);
1026
+ }
1027
+ return itemValue === value;
1028
+ });
1029
+ });
1030
+ }
1031
+ if (query.sort) {
1032
+ filtered.sort((a, b) => {
1033
+ const aVal = a[query.sort];
1034
+ const bVal = b[query.sort];
1035
+ const order = query.order === "asc" ? 1 : -1;
1036
+ if (aVal < bVal) return -1 * order;
1037
+ if (aVal > bVal) return 1 * order;
1038
+ return 0;
1039
+ });
1040
+ }
1041
+ const page = query.page || 1;
1042
+ const limit = query.limit || 10;
1043
+ const start = (page - 1) * limit;
1044
+ const end = start + limit;
1045
+ const total = filtered.length;
1046
+ return {
1047
+ items: filtered.slice(start, end),
1048
+ total,
1049
+ page,
1050
+ limit,
1051
+ totalPages: Math.ceil(total / limit),
1052
+ hasNext: end < total,
1053
+ hasPrev: start > 0
1054
+ };
1055
+ }
1056
+ async fetchWithTimeout(url, options = {}) {
1057
+ const { timeout = this.config.timeout || 1e4, ...fetchOptions } = options;
1058
+ const controller = new AbortController();
1059
+ const id = setTimeout(() => controller.abort(), timeout);
1060
+ try {
1061
+ const response = await fetch(url, {
1062
+ ...fetchOptions,
1063
+ signal: controller.signal
1064
+ });
1065
+ clearTimeout(id);
1066
+ return response;
1067
+ } catch (error) {
1068
+ clearTimeout(id);
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ getHeaders() {
1073
+ const headers = {
1074
+ "Content-Type": "application/json",
1075
+ "X-Nexus-Client": "client-sdk/1.0.0",
1076
+ "X-Nexus-Project": this.config.projectId
1077
+ };
1078
+ if (this.config.apiKey) {
1079
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
1080
+ }
1081
+ return headers;
1082
+ }
1083
+ isCacheValid(metadata) {
1084
+ return Date.now() < metadata.expiresAt;
1085
+ }
1086
+ normalizeError(error, context) {
1087
+ if (error instanceof Error) {
1088
+ if (error.name === "AbortError") {
1089
+ return new Error(`${context}: Request timeout`);
1090
+ }
1091
+ return error;
1092
+ }
1093
+ return new Error(`${context}: ${String(error)}`);
1094
+ }
1095
+ /**
1096
+ * Cancel ongoing requests
1097
+ */
1098
+ cancelRequests() {
1099
+ if (this.abortController) {
1100
+ this.abortController.abort();
1101
+ this.abortController = new AbortController();
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Cleanup resources
1106
+ */
1107
+ cleanup() {
1108
+ this.cancelRequests();
1109
+ if (!this.isServer) {
1110
+ window.removeEventListener("beforeunload", this.cleanup.bind(this));
1111
+ }
1112
+ }
1113
+ };
1114
+
1115
+ // src/analytics/fingerprint.ts
1116
+ var getDeviceEntropy = async () => {
1117
+ if (typeof window === "undefined") return {};
1118
+ const nav = window.navigator;
1119
+ return {
1120
+ screen_resolution: `${window.screen.width}x${window.screen.height}`,
1121
+ color_depth: window.screen.colorDepth,
1122
+ pixel_ratio: window.devicePixelRatio || 1,
1123
+ hardware_concurrency: nav.hardwareConcurrency,
1124
+ device_memory: nav.deviceMemory,
1125
+ // Only available in Chrome/Edge
1126
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
1127
+ platform: nav.platform,
1128
+ language: nav.language,
1129
+ touch_support: "ontouchstart" in window || nav.maxTouchPoints > 0,
1130
+ // Optional: Calculate Canvas Fingerprint for high-security modes
1131
+ canvas_hash: await generateCanvasHash()
1132
+ };
1133
+ };
1134
+ var generateCanvasHash = async () => {
1135
+ try {
1136
+ const canvas = document.createElement("canvas");
1137
+ const ctx = canvas.getContext("2d");
1138
+ if (!ctx) return "";
1139
+ canvas.width = 200;
1140
+ canvas.height = 50;
1141
+ ctx.textBaseline = "top";
1142
+ ctx.font = '16px "Arial"';
1143
+ ctx.textBaseline = "alphabetic";
1144
+ ctx.fillStyle = "#f60";
1145
+ ctx.fillRect(125, 1, 62, 20);
1146
+ ctx.fillStyle = "#069";
1147
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 2, 15);
1148
+ ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
1149
+ ctx.fillText("NexusHub Rocks! <canvas> 1.0", 4, 17);
1150
+ const dataUrl = canvas.toDataURL();
1151
+ let hash = 0;
1152
+ for (let i = 0; i < dataUrl.length; i++) {
1153
+ const char = dataUrl.charCodeAt(i);
1154
+ hash = (hash << 5) - hash + char;
1155
+ hash = hash & hash;
1156
+ }
1157
+ return hash.toString(16);
1158
+ } catch {
1159
+ return "";
1160
+ }
1161
+ };
1162
+ var getVisitorId = async () => {
1163
+ if (typeof window === "undefined") return "server_visitor";
1164
+ const STORAGE_KEY = "nexus_vid";
1165
+ let vid = localStorage.getItem(STORAGE_KEY);
1166
+ if (!vid) {
1167
+ const entropy = await getDeviceEntropy();
1168
+ const random = Math.random().toString(36).substring(2, 15);
1169
+ const timestamp = Date.now().toString(36);
1170
+ const fingerprint = [
1171
+ entropy.screen_resolution,
1172
+ entropy.hardware_concurrency,
1173
+ entropy.timezone_offset,
1174
+ entropy.platform,
1175
+ entropy.canvas_hash
1176
+ ].join("|");
1177
+ let hash = 0;
1178
+ for (let i = 0; i < fingerprint.length; i++) {
1179
+ hash = (hash << 5) - hash + fingerprint.charCodeAt(i);
1180
+ hash |= 0;
1181
+ }
1182
+ vid = `vis_${hash.toString(16)}_${timestamp}_${random}`;
1183
+ localStorage.setItem(STORAGE_KEY, vid);
1184
+ }
1185
+ return vid;
1186
+ };
1187
+ var METRIC_KEY_MAP = {
1188
+ CLS: "cls",
1189
+ LCP: "lcp",
1190
+ INP: "inp",
1191
+ TTFB: "ttfb",
1192
+ FCP: "fcp"
1193
+ };
1194
+ var VitalsCollector = class {
1195
+ constructor() {
1196
+ this.metrics = {};
1197
+ this.hasUpdates = false;
1198
+ if (typeof window !== "undefined") {
1199
+ this.init();
1200
+ }
1201
+ }
1202
+ init() {
1203
+ const recordMetric = (metric) => {
1204
+ const key = METRIC_KEY_MAP[metric.name];
1205
+ this.metrics[key] = metric.value;
1206
+ this.hasUpdates = true;
1207
+ };
1208
+ onCLS(recordMetric);
1209
+ onLCP(recordMetric);
1210
+ onTTFB(recordMetric);
1211
+ onINP(recordMetric);
1212
+ onFCP(recordMetric);
1213
+ const navEntry = performance.getEntriesByType("navigation")[0];
1214
+ if (navEntry) {
1215
+ this.metrics.navigation_timing = {
1216
+ dns_lookup: navEntry.domainLookupEnd - navEntry.domainLookupStart,
1217
+ tcp_connect: navEntry.connectEnd - navEntry.connectStart,
1218
+ request_time: navEntry.responseEnd - navEntry.requestStart,
1219
+ dom_load: navEntry.domComplete - navEntry.domInteractive
1220
+ };
1221
+ this.hasUpdates = true;
1222
+ }
1223
+ }
1224
+ getMetricsSnapshot() {
1225
+ if (!this.hasUpdates) return null;
1226
+ this.hasUpdates = false;
1227
+ return { ...this.metrics };
1228
+ }
1229
+ };
1230
+ var vitalsCollector = new VitalsCollector();
1231
+ var initVitals = (tracker) => {
1232
+ if (process.env.NODE_ENV === "development") {
1233
+ console.log("[NexusHub] Web Vitals monitoring active");
1234
+ }
1235
+ };
1236
+
1237
+ // src/analytics/storage.ts
1238
+ var DB_NAME = "NexusHub_Analytics";
1239
+ var STORE_NAME = "events_queue";
1240
+ var DB_VERSION = 1;
1241
+ var EventStorage = class {
1242
+ constructor() {
1243
+ this.db = null;
1244
+ this.isReady = this.init();
1245
+ }
1246
+ init() {
1247
+ if (typeof window === "undefined" || !window.indexedDB) {
1248
+ return Promise.resolve();
1249
+ }
1250
+ return new Promise((resolve, reject) => {
1251
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
1252
+ request.onerror = () => {
1253
+ console.warn("[NexusHub] Failed to open IndexedDB. Falling back to memory.");
1254
+ resolve();
1255
+ };
1256
+ request.onsuccess = (event) => {
1257
+ this.db = event.target.result;
1258
+ resolve();
1259
+ };
1260
+ request.onupgradeneeded = (event) => {
1261
+ const db = event.target.result;
1262
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
1263
+ db.createObjectStore(STORE_NAME, { keyPath: "id", autoIncrement: true });
1264
+ }
1265
+ };
1266
+ });
1267
+ }
1268
+ /**
1269
+ * Add an event to the persistent queue
1270
+ */
1271
+ async enqueue(payload) {
1272
+ await this.isReady;
1273
+ if (!this.db) return;
1274
+ return new Promise((resolve, reject) => {
1275
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1276
+ const store = transaction.objectStore(STORE_NAME);
1277
+ const request = store.add({
1278
+ payload,
1279
+ timestamp: Date.now(),
1280
+ retryCount: 0
1281
+ });
1282
+ request.onsuccess = () => resolve();
1283
+ request.onerror = () => reject(request.error);
1284
+ });
1285
+ }
1286
+ /**
1287
+ * Get a batch of oldest events
1288
+ */
1289
+ async peek(limit = 20) {
1290
+ await this.isReady;
1291
+ if (!this.db) return [];
1292
+ return new Promise((resolve) => {
1293
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1294
+ const store = transaction.objectStore(STORE_NAME);
1295
+ const request = store.getAll(null, limit);
1296
+ request.onsuccess = () => resolve(request.result);
1297
+ request.onerror = () => resolve([]);
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Remove events after successful upload
1302
+ */
1303
+ async remove(ids) {
1304
+ await this.isReady;
1305
+ if (!this.db || ids.length === 0) return;
1306
+ return new Promise((resolve, reject) => {
1307
+ const transaction = this.db.transaction([STORE_NAME], "readwrite");
1308
+ const store = transaction.objectStore(STORE_NAME);
1309
+ transaction.oncomplete = () => resolve();
1310
+ transaction.onerror = () => reject(transaction.error);
1311
+ ids.forEach((id) => {
1312
+ store.delete(id);
1313
+ });
1314
+ });
1315
+ }
1316
+ /**
1317
+ * Count pending events
1318
+ */
1319
+ async count() {
1320
+ await this.isReady;
1321
+ if (!this.db) return 0;
1322
+ return new Promise((resolve) => {
1323
+ const transaction = this.db.transaction([STORE_NAME], "readonly");
1324
+ const store = transaction.objectStore(STORE_NAME);
1325
+ const request = store.count();
1326
+ request.onsuccess = () => resolve(request.result);
1327
+ request.onerror = () => resolve(0);
1328
+ });
1329
+ }
1330
+ };
1331
+ var eventStorage = new EventStorage();
1332
+
1333
+ // src/analytics/tracker.ts
1334
+ var Tracker = class {
1335
+ // 🆕
1336
+ constructor(config) {
1337
+ this.sessionId = "";
1338
+ this.visitorId = "";
1339
+ // FIX: Add this property
1340
+ this.isFlushing = false;
1341
+ this.config = config;
1342
+ this.config.apiUrl.replace("/v1", "").replace(/\/$/, "");
1343
+ this.endpoint = `${this.config.analyticsUrl}/api/collect`;
1344
+ this.circuitBreaker = new CircuitBreaker();
1345
+ this.sessionStart = Date.now();
1346
+ if (typeof window !== "undefined") {
1347
+ this.initSession();
1348
+ this.startFlushing();
1349
+ }
1350
+ }
1351
+ async initSession() {
1352
+ this.visitorId = await getVisitorId();
1353
+ let sid = localStorage.getItem("nexus_sid");
1354
+ let lastActivity = localStorage.getItem("nexus_last_active");
1355
+ const now = Date.now();
1356
+ const SESSION_TIMEOUT = 30 * 60 * 1e3;
1357
+ if (!sid || !lastActivity || now - parseInt(lastActivity) > SESSION_TIMEOUT) {
1358
+ sid = `sess_${Math.random().toString(36).substring(2, 9)}_${now}`;
1359
+ localStorage.setItem("nexus_sid", sid);
1360
+ this.sessionStart = now;
1361
+ }
1362
+ localStorage.setItem("nexus_last_active", now.toString());
1363
+ this.sessionId = sid;
1364
+ }
1365
+ async send(eventType, data = {}, eventName) {
1366
+ if (typeof window === "undefined") return;
1367
+ localStorage.setItem("nexus_last_active", Date.now().toString());
1368
+ const entropy = await getDeviceEntropy();
1369
+ const perfMetrics = vitalsCollector.getMetricsSnapshot();
1370
+ const payload = {
1371
+ project_id: this.config.projectId,
1372
+ session_id: this.sessionId,
1373
+ // We send this, Rust verifies it
1374
+ url: window.location.href,
1375
+ referrer: document.referrer,
1376
+ user_agent: window.navigator.userAgent,
1377
+ screen_width: window.screen.width,
1378
+ screen_height: window.screen.height,
1379
+ language: window.navigator.language,
1380
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
1381
+ event_type: eventType,
1382
+ event_name: eventName,
1383
+ event_data: data,
1384
+ // 3. Attach Performance Data (Rust: Option<PerformanceMetrics>)
1385
+ performance: perfMetrics || void 0,
1386
+ // 4. Attach Hardware Signals for Anomaly Detection (Rust: DeviceData)
1387
+ context: {
1388
+ device: {
1389
+ hardware_concurrency: entropy.hardware_concurrency,
1390
+ device_memory: entropy.device_memory,
1391
+ pixel_ratio: entropy.pixel_ratio,
1392
+ canvas_fingerprint: entropy.canvas_hash,
1393
+ platform: entropy.platform
1394
+ },
1395
+ visitor_id_local: this.visitorId
1396
+ // Hint for stitching
1397
+ },
1398
+ client_timestamp: (/* @__PURE__ */ new Date()).toISOString()
1399
+ };
1400
+ await eventStorage.enqueue(payload);
1401
+ const count = await eventStorage.count();
1402
+ if (count >= 10 || eventType === "purchase" || eventType === "identify") {
1403
+ this.flushQueue();
1404
+ }
1405
+ }
1406
+ startFlushing() {
1407
+ this.flushInterval = setInterval(() => this.flushQueue(), 5e3);
1408
+ window.addEventListener("visibilitychange", () => {
1409
+ if (document.visibilityState === "hidden") this.flushQueue(true);
1410
+ });
1411
+ }
1412
+ async flushQueue(useBeacon = false) {
1413
+ if (this.isFlushing) return;
1414
+ if (this.circuitBreaker.isOpen()) {
1415
+ return;
1416
+ }
1417
+ this.isFlushing = true;
1418
+ try {
1419
+ const storedEvents = await eventStorage.peek(20);
1420
+ if (storedEvents.length === 0) {
1421
+ this.isFlushing = false;
1422
+ return;
1423
+ }
1424
+ const payloads = storedEvents.map((e) => e.payload);
1425
+ const promises = payloads.map(
1426
+ (event) => fetch(this.endpoint, {
1427
+ method: "POST",
1428
+ headers: {
1429
+ "Content-Type": "application/json",
1430
+ Authorization: `Bearer ${this.config.apiKey}`
1431
+ },
1432
+ body: JSON.stringify(event),
1433
+ keepalive: useBeacon
1434
+ })
1435
+ );
1436
+ const results = await Promise.allSettled(promises);
1437
+ const successIds = [];
1438
+ let failureCount = 0;
1439
+ results.forEach((res, index) => {
1440
+ if (res.status === "fulfilled" && res.value.ok) {
1441
+ successIds.push(storedEvents[index].id);
1442
+ } else {
1443
+ failureCount++;
1444
+ }
1445
+ });
1446
+ if (successIds.length > 0) {
1447
+ await eventStorage.remove(successIds);
1448
+ this.circuitBreaker.recordSuccess();
1449
+ }
1450
+ if (failureCount > 0) {
1451
+ this.circuitBreaker.recordFailure();
1452
+ }
1453
+ } catch (err) {
1454
+ console.error("[NexusHub] Network Error:", err);
1455
+ this.circuitBreaker.recordFailure();
1456
+ } finally {
1457
+ this.isFlushing = false;
1458
+ if (!this.circuitBreaker.isOpen() && await eventStorage.count() > 0) {
1459
+ setTimeout(() => this.flushQueue(), 100);
1460
+ }
1461
+ }
1462
+ }
1463
+ getSession() {
1464
+ return this.sessionId;
1465
+ }
1466
+ // FIX: Add this method to satisfy AnalyticsEngine
1467
+ getSessionDuration() {
1468
+ return Date.now() - this.sessionStart;
1469
+ }
1470
+ // FIX: Add this method to satisfy AnalyticsEngine
1471
+ stop() {
1472
+ if (this.flushInterval) {
1473
+ clearInterval(this.flushInterval);
1474
+ }
1475
+ this.flushQueue(true);
1476
+ }
1477
+ };
1478
+
1479
+ // src/analytics/index.ts
1480
+ var AnalyticsEngine = class {
1481
+ constructor(config) {
1482
+ this.cleanupFns = [];
1483
+ this.isInitialized = false;
1484
+ this.tracker = new Tracker(config);
1485
+ }
1486
+ start() {
1487
+ if (this.isInitialized || typeof window === "undefined") return;
1488
+ this.isInitialized = true;
1489
+ this.pageView();
1490
+ initVitals(this.tracker);
1491
+ this.setupClickTracking();
1492
+ this.setupFormTracking();
1493
+ this.setupRouteTracking();
1494
+ this.setupShareTracking();
1495
+ console.log("[NexusHub] \u{1F680} Analytics Engine Started");
1496
+ }
1497
+ pageView() {
1498
+ if (typeof window === "undefined") return;
1499
+ this.tracker.send("page_view", {
1500
+ path: window.location.pathname,
1501
+ search: window.location.search,
1502
+ title: document.title,
1503
+ timezone_offset: (/* @__PURE__ */ new Date()).getTimezoneOffset()
1504
+ });
1505
+ }
1506
+ // 🆕 PRIVATE: Track "Dark Social" Intent
1507
+ setupShareTracking() {
1508
+ if (typeof window === "undefined") return;
1509
+ const copyHandler = () => {
1510
+ this.tracker.send("social_share", {
1511
+ method: "clipboard_copy",
1512
+ url: window.location.href
1513
+ });
1514
+ };
1515
+ if (navigator.share) {
1516
+ const originalShare = navigator.share;
1517
+ navigator.share = (data) => {
1518
+ this.tracker.send("social_share", {
1519
+ method: "native_share_menu",
1520
+ url: data?.url || window.location.href,
1521
+ title: data?.title
1522
+ });
1523
+ return originalShare.apply(navigator, [data]);
1524
+ };
1525
+ }
1526
+ window.addEventListener("copy", copyHandler, { passive: true });
1527
+ this.cleanupFns.push(() => window.removeEventListener("copy", copyHandler));
1528
+ }
1529
+ // --- IDENTITY & B2B (The Missing Pieces) ---
1530
+ /**
1531
+ * 1. IDENTIFY: Link anonymous session to a User ID
1532
+ */
1533
+ async identify(userId, traits = {}) {
1534
+ return this.sendIdentityRequest("identify", {
1535
+ user_id: userId,
1536
+ traits
1537
+ });
1538
+ }
1539
+ /**
1540
+ * 2. GROUP: Link the current user to a Company/Organization (B2B)
1541
+ * Required for the /api/group Rust route.
1542
+ */
1543
+ async group(groupId, traits = {}) {
1544
+ return this.sendIdentityRequest("group", {
1545
+ group_id: groupId,
1546
+ // The Rust backend handles looking up the user from the session if not provided,
1547
+ // but passing the user_id if known is safer.
1548
+ traits
1549
+ });
1550
+ }
1551
+ /**
1552
+ * 3. ALIAS: Merge two identities (e.g. "Guest_123" -> "User_99")
1553
+ * Required for the /api/alias Rust route.
1554
+ */
1555
+ async alias(newId) {
1556
+ return this.sendIdentityRequest("alias", {
1557
+ previous_id: this.tracker.getSession(),
1558
+ // Or the old visitor_id
1559
+ user_id: newId
1560
+ });
1561
+ }
1562
+ /**
1563
+ * 4. RESET: Clear local data and (optionally) request GDPR scrub
1564
+ */
1565
+ reset(performGdprScrub = false) {
1566
+ const config = this.tracker["config"];
1567
+ this.tracker.stop();
1568
+ localStorage.removeItem("nexus_sid");
1569
+ localStorage.removeItem("nexus_vid");
1570
+ if (performGdprScrub) {
1571
+ const endpoint = `${config.analyticsUrl}/api/privacy/scrub`;
1572
+ const userId = this.tracker.visitorId;
1573
+ fetch(endpoint, {
1574
+ method: "DELETE",
1575
+ headers: {
1576
+ "Content-Type": "application/json",
1577
+ Authorization: `Bearer ${config.apiKey}`
1578
+ },
1579
+ body: JSON.stringify({
1580
+ project_id: config.projectId,
1581
+ user_id: userId
1582
+ })
1583
+ }).catch((err) => console.error("[NexusHub] Privacy scrub failed:", err));
1584
+ }
1585
+ window.location.reload();
1586
+ }
1587
+ // --- E-COMMERCE & CUSTOM ---
1588
+ track(eventName, properties = {}) {
1589
+ this.tracker.send(
1590
+ "custom_event",
1591
+ { event_name: eventName, ...properties },
1592
+ eventName
1593
+ );
1594
+ }
1595
+ trackPurchase(orderData) {
1596
+ this.tracker.send("purchase", {
1597
+ ...orderData,
1598
+ currency: orderData.currency || "USD",
1599
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1600
+ });
1601
+ }
1602
+ trackError(error, context) {
1603
+ this.tracker.send("error", {
1604
+ message: error.message,
1605
+ stack: error.stack,
1606
+ context,
1607
+ url: typeof window !== "undefined" ? window.location.href : ""
1608
+ });
1609
+ }
1610
+ // --- INTERNAL HELPER ---
1611
+ async sendIdentityRequest(type, data) {
1612
+ try {
1613
+ const config = this.tracker["config"];
1614
+ const endpoint = `${config.analyticsUrl}/api/${type}`;
1615
+ const payload = {
1616
+ project_id: this.tracker["config"].projectId,
1617
+ session_id: this.tracker.getSession(),
1618
+ visitor_id: this.tracker.visitorId,
1619
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1620
+ ...data
1621
+ };
1622
+ if (type === "group" && !payload.user_id) {
1623
+ }
1624
+ const response = await fetch(endpoint, {
1625
+ method: "POST",
1626
+ headers: {
1627
+ "Content-Type": "application/json",
1628
+ Authorization: `Bearer ${this.tracker["config"].apiKey}`
1629
+ },
1630
+ body: JSON.stringify(payload)
1631
+ });
1632
+ if (response.ok) {
1633
+ this.tracker.send(type, data);
1634
+ return true;
1635
+ }
1636
+ return false;
1637
+ } catch (error) {
1638
+ console.error(`[NexusHub] ${type} failed:`, error);
1639
+ return false;
1640
+ }
1641
+ }
1642
+ // --- PRIVATE EVENT LISTENERS (Keep existing setupClickTracking, setupFormTracking, setupRouteTracking) ---
1643
+ setupClickTracking() {
1644
+ if (typeof window === "undefined") return;
1645
+ const clickHandler = (e) => {
1646
+ const target = e.target;
1647
+ const link = target.closest("a");
1648
+ if (link) {
1649
+ this.tracker.send("click", {
1650
+ element_type: "link",
1651
+ href: link.href,
1652
+ text: link.innerText?.substring(0, 50),
1653
+ id: link.id,
1654
+ classes: link.className,
1655
+ dataset: { ...link.dataset }
1656
+ });
1657
+ }
1658
+ const button = target.closest("button");
1659
+ if (button) {
1660
+ this.tracker.send("click", {
1661
+ element_type: "button",
1662
+ text: button.innerText?.substring(0, 50),
1663
+ id: button.id,
1664
+ classes: button.className,
1665
+ coordinates: { x: e.clientX, y: e.clientY }
1666
+ });
1667
+ }
1668
+ };
1669
+ window.addEventListener("click", clickHandler, { passive: true });
1670
+ this.cleanupFns.push(
1671
+ () => window.removeEventListener("click", clickHandler)
1672
+ );
1673
+ }
1674
+ setupFormTracking() {
1675
+ if (typeof document === "undefined") return;
1676
+ const submitHandler = (e) => {
1677
+ const form = e.target;
1678
+ if (form) {
1679
+ this.tracker.send("form_submit", {
1680
+ form_id: form.id || form.name || "unknown_form",
1681
+ action: form.action,
1682
+ method: form.method,
1683
+ field_count: form.elements.length
1684
+ });
1685
+ }
1686
+ };
1687
+ document.addEventListener("submit", submitHandler, { passive: true });
1688
+ this.cleanupFns.push(
1689
+ () => document.removeEventListener("submit", submitHandler)
1690
+ );
1691
+ }
1692
+ setupRouteTracking() {
1693
+ if (typeof window === "undefined" || typeof window.history === "undefined")
1694
+ return;
1695
+ const originalPushState = history.pushState;
1696
+ const originalReplaceState = history.replaceState;
1697
+ history.pushState = (...args) => {
1698
+ originalPushState.apply(history, args);
1699
+ this.pageView();
1700
+ };
1701
+ history.replaceState = (...args) => {
1702
+ originalReplaceState.apply(history, args);
1703
+ this.pageView();
1704
+ };
1705
+ const popStateHandler = () => this.pageView();
1706
+ window.addEventListener("popstate", popStateHandler);
1707
+ this.cleanupFns.push(
1708
+ () => window.removeEventListener("popstate", popStateHandler)
1709
+ );
1710
+ }
1711
+ getSessionId() {
1712
+ return this.tracker.getSession();
1713
+ }
1714
+ stop() {
1715
+ this.cleanupFns.forEach((fn) => fn());
1716
+ this.cleanupFns = [];
1717
+ this.tracker.send("session_end", {
1718
+ session_id: this.tracker.getSession(),
1719
+ duration: this.tracker.getSessionDuration()
1720
+ });
1721
+ this.tracker.stop();
1722
+ this.isInitialized = false;
1723
+ }
1724
+ };
1725
+
1726
+ // src/client.ts
1727
+ var NexusClient = class {
1728
+ // Make this public/accessible
1729
+ constructor(config) {
1730
+ const fullConfig = getFullConfig(config);
1731
+ this.config = {
1732
+ debug: config?.debug || false,
1733
+ cacheStrategy: config?.cacheStrategy || "memory",
1734
+ revalidateTime: config?.revalidateTime || 60,
1735
+ timeout: config?.timeout || 1e4,
1736
+ retries: config?.retries || 3,
1737
+ ...fullConfig
1738
+ };
1739
+ this.content = new ContentEngine(this.config);
1740
+ if (typeof window !== "undefined") {
1741
+ this.analytics = new AnalyticsEngine(this.config);
1742
+ this.analytics.start();
1743
+ }
1744
+ const errors = validateConfig(this.config);
1745
+ if (errors.length > 0) {
1746
+ console.warn("\u26A0\uFE0F NexusHub: Configuration issues:", errors.join(", "));
1747
+ if (!this.config.projectId) {
1748
+ console.warn("\u26A0\uFE0F NexusHub: No Project ID found. Content fetching will fail.");
1749
+ }
1750
+ }
1751
+ this.content = new ContentEngine(this.config);
1752
+ }
1753
+ // Helper alias for cleaner code
1754
+ getPage(slug, options) {
1755
+ return this.content.getPage(slug, options);
1756
+ }
1757
+ // Get current config (readonly)
1758
+ getConfig() {
1759
+ return { ...this.config };
1760
+ }
1761
+ };
1762
+ var nexus = new NexusClient();
1763
+ var createNexusClient = (config) => new NexusClient(config);
1764
+ var AuthContext = createContext(null);
1765
+ var AuthProvider = ({
1766
+ children,
1767
+ config
1768
+ }) => {
1769
+ const [user, setUser] = useState(null);
1770
+ const [isLoading, setIsLoading] = useState(true);
1771
+ const [error, setError] = useState(null);
1772
+ const AUTH_BASE = `${config.apiUrl}/auth/project/${config.projectId}`;
1773
+ const checkSession = useCallback(async () => {
1774
+ try {
1775
+ const res = await fetch(`${AUTH_BASE}/me`, {
1776
+ headers: getHeaders(config)
1777
+ });
1778
+ if (res.ok) {
1779
+ const data = await res.json();
1780
+ setUser(data.user);
1781
+ if (nexus.analytics) {
1782
+ nexus.analytics.identify(data.user.id, {
1783
+ email: data.user.email,
1784
+ role: data.user.role,
1785
+ ...data.user.metadata
1786
+ });
1787
+ }
1788
+ } else {
1789
+ setUser(null);
1790
+ }
1791
+ } catch (err) {
1792
+ console.debug("[NexusHub Auth] Session check failed:", err);
1793
+ setUser(null);
1794
+ } finally {
1795
+ setIsLoading(false);
1796
+ }
1797
+ }, [AUTH_BASE, config]);
1798
+ useEffect(() => {
1799
+ checkSession();
1800
+ }, [checkSession]);
1801
+ const login = async (creds) => {
1802
+ setIsLoading(true);
1803
+ setError(null);
1804
+ try {
1805
+ const res = await fetch(`${AUTH_BASE}/login`, {
1806
+ method: "POST",
1807
+ headers: getHeaders(config),
1808
+ body: JSON.stringify(creds)
1809
+ });
1810
+ if (!res.ok) throw await parseError(res);
1811
+ const data = await res.json();
1812
+ setUser(data.user);
1813
+ if (nexus.analytics) {
1814
+ await nexus.analytics.identify(data.user.id, {
1815
+ email: data.user.email,
1816
+ role: data.user.role,
1817
+ login_method: "email",
1818
+ ...data.user.metadata
1819
+ });
1820
+ }
1821
+ } catch (err) {
1822
+ setError(err);
1823
+ throw err;
1824
+ } finally {
1825
+ setIsLoading(false);
1826
+ }
1827
+ };
1828
+ const register = async (creds) => {
1829
+ setIsLoading(true);
1830
+ setError(null);
1831
+ try {
1832
+ const res = await fetch(`${AUTH_BASE}/register`, {
1833
+ method: "POST",
1834
+ headers: getHeaders(config),
1835
+ body: JSON.stringify(creds)
1836
+ });
1837
+ if (!res.ok) throw await parseError(res);
1838
+ const data = await res.json();
1839
+ setUser(data.user);
1840
+ if (nexus.analytics) {
1841
+ nexus.analytics.track("signup", { method: "email" });
1842
+ nexus.analytics.identify(data.user.id, {
1843
+ email: data.user.email,
1844
+ role: data.user.role,
1845
+ ...data.user.metadata
1846
+ });
1847
+ }
1848
+ } catch (err) {
1849
+ setError(err);
1850
+ throw err;
1851
+ } finally {
1852
+ setIsLoading(false);
1853
+ }
1854
+ };
1855
+ const logout = async () => {
1856
+ setIsLoading(true);
1857
+ try {
1858
+ await fetch(`${AUTH_BASE}/logout`, { method: "POST", headers: getHeaders(config) });
1859
+ } catch (e) {
1860
+ console.warn("Logout network error", e);
1861
+ } finally {
1862
+ setUser(null);
1863
+ setIsLoading(false);
1864
+ if (nexus.analytics) {
1865
+ nexus.analytics.track("logout");
1866
+ }
1867
+ }
1868
+ };
1869
+ const updateProfile = async (updates) => {
1870
+ try {
1871
+ const res = await fetch(`${AUTH_BASE}/profile`, {
1872
+ method: "PATCH",
1873
+ headers: getHeaders(config),
1874
+ body: JSON.stringify(updates)
1875
+ });
1876
+ if (!res.ok) throw await parseError(res);
1877
+ const data = await res.json();
1878
+ setUser(data.user);
1879
+ if (nexus.analytics) {
1880
+ nexus.analytics.identify(data.user.id, updates);
1881
+ }
1882
+ } catch (err) {
1883
+ setError(err);
1884
+ throw err;
1885
+ }
1886
+ };
1887
+ const requestPasswordReset = async (email) => {
1888
+ const res = await fetch(`${AUTH_BASE}/password/reset-request`, {
1889
+ method: "POST",
1890
+ headers: getHeaders(config),
1891
+ body: JSON.stringify({ email })
1892
+ });
1893
+ if (!res.ok) throw await parseError(res);
1894
+ };
1895
+ return /* @__PURE__ */ jsx(AuthContext.Provider, { value: {
1896
+ user,
1897
+ isLoading,
1898
+ error,
1899
+ isAuthenticated: !!user,
1900
+ login,
1901
+ register,
1902
+ logout,
1903
+ updateProfile,
1904
+ requestPasswordReset
1905
+ }, children });
1906
+ };
1907
+ var useNexusAuth = () => {
1908
+ const context = useContext(AuthContext);
1909
+ if (!context) {
1910
+ throw new Error("useNexusAuth must be used within a NexusProvider");
1911
+ }
1912
+ return context;
1913
+ };
1914
+ function getHeaders(config) {
1915
+ return {
1916
+ "Content-Type": "application/json",
1917
+ "x-nexus-project": config.projectId
1918
+ // Note: We do NOT send the Master API Key here.
1919
+ // This is client-side. The backend uses Cookies or public tokens.
1920
+ };
1921
+ }
1922
+ async function parseError(res) {
1923
+ try {
1924
+ const json = await res.json();
1925
+ return {
1926
+ status: res.status,
1927
+ code: json.code || "UNKNOWN_ERROR",
1928
+ message: json.message || "An error occurred during authentication"
1929
+ };
1930
+ } catch {
1931
+ return {
1932
+ status: res.status,
1933
+ code: "NETWORK_ERROR",
1934
+ message: res.statusText
1935
+ };
1936
+ }
1937
+ }
1938
+ var NexusContext = createContext(nexus);
1939
+ var NexusProvider = ({
1940
+ children,
1941
+ projectId,
1942
+ disableAnalytics = false
1943
+ }) => {
1944
+ const pathname = usePathname();
1945
+ const searchParams = useSearchParams();
1946
+ const isInitialized = useRef(false);
1947
+ const config = useMemo(() => {
1948
+ const currentConfig = nexus.getConfig();
1949
+ if (projectId && currentConfig.projectId !== projectId) {
1950
+ nexus.config.projectId = projectId;
1951
+ }
1952
+ return nexus.getConfig();
1953
+ }, [projectId]);
1954
+ useEffect(() => {
1955
+ if (typeof window === "undefined" || disableAnalytics) return;
1956
+ if (!isInitialized.current) {
1957
+ if (!nexus.analytics) {
1958
+ nexus.analytics = new AnalyticsEngine(nexus.getConfig());
1959
+ }
1960
+ nexus.analytics.start();
1961
+ isInitialized.current = true;
1962
+ if (nexus.getConfig().debug) {
1963
+ console.log("[NexusHub] \u{1F680} Provider initialized analytics");
1964
+ }
1965
+ }
1966
+ return () => {
1967
+ if (nexus.analytics) {
1968
+ nexus.analytics.stop();
1969
+ isInitialized.current = false;
1970
+ }
1971
+ };
1972
+ }, [disableAnalytics]);
1973
+ useEffect(() => {
1974
+ if (nexus.analytics && !disableAnalytics) {
1975
+ nexus.analytics.pageView();
1976
+ }
1977
+ }, [pathname, searchParams, disableAnalytics]);
1978
+ return /* @__PURE__ */ jsx(NexusContext.Provider, { value: nexus, children: /* @__PURE__ */ jsx(AuthProvider, { config, children }) });
1979
+ };
1980
+
1981
+ // src/index.ts
1982
+ var VERSION = "0.0.1";
1983
+
1984
+ export { AnalyticsEngine, AuthProvider, BrowserCache, CacheTags, ContentEngine, DEFAULT_ANALYTICS_URL, DEFAULT_API_URL, LOCAL_NEST_URL, LOCAL_RUST_URL, MemoryCache, NexusClient, NexusProvider, VERSION, createNexusClient, getEnvConfig, getFullConfig, mergeConfigs, nexus, useNexusAuth, validateConfig };