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