@nexussdk/core 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +26 -0
- package/dist/index.cjs +9 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +287 -0
- package/dist/index.d.ts +287 -0
- package/dist/index.global.js +9 -0
- package/dist/index.global.js.map +1 -0
- package/dist/index.mjs +9 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +33 -0
- package/src/env-resolver.ts +153 -0
- package/src/http-client.ts +202 -0
- package/src/index.ts +16 -0
- package/src/ring-buffer.ts +148 -0
- package/src/safe-json.ts +134 -0
- package/tsconfig.json +8 -0
- package/tsup.config.ts +19 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Resilient HTTP client with exponential backoff and jitter.
|
|
3
|
+
* Zero external dependencies — uses only native browser fetch and AbortController.
|
|
4
|
+
* @module @nexus/core/http-client
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Options for configuring a single HTTP request with retry behaviour.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const opts: HttpClientOptions = {
|
|
12
|
+
* url: 'https://api.nexus.dev/api/v1/flags/eval',
|
|
13
|
+
* method: 'GET',
|
|
14
|
+
* headers: { Authorization: 'Bearer pk_live_...' },
|
|
15
|
+
* timeoutMs: 3000,
|
|
16
|
+
* maxRetries: 3,
|
|
17
|
+
* };
|
|
18
|
+
*/
|
|
19
|
+
export interface HttpClientOptions {
|
|
20
|
+
/** Request URL. */
|
|
21
|
+
url: string;
|
|
22
|
+
/** HTTP method. Defaults to 'GET'. */
|
|
23
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
24
|
+
/** Request headers. */
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
/** Request body (will be JSON-serialized if object). */
|
|
27
|
+
body?: unknown;
|
|
28
|
+
/** Request timeout in milliseconds. Defaults to 5000ms. */
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
/** Maximum retry attempts on 5xx / network errors. Defaults to 3. */
|
|
31
|
+
maxRetries?: number;
|
|
32
|
+
/** Base delay in milliseconds for exponential backoff. Defaults to 1000ms. */
|
|
33
|
+
retryBaseMs?: number;
|
|
34
|
+
/** Maximum backoff delay in milliseconds. Defaults to 30000ms. */
|
|
35
|
+
retryMaxMs?: number;
|
|
36
|
+
/** Optional AbortSignal for external cancellation. */
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Result of a successful HTTP fetch.
|
|
42
|
+
*
|
|
43
|
+
* @template T The expected response body type.
|
|
44
|
+
*/
|
|
45
|
+
export interface HttpClientResult<T> {
|
|
46
|
+
/** Parsed response body. */
|
|
47
|
+
data: T;
|
|
48
|
+
/** HTTP status code. */
|
|
49
|
+
status: number;
|
|
50
|
+
/** Response headers. */
|
|
51
|
+
headers: Headers;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Computes the exponential backoff sleep duration with full random jitter.
|
|
56
|
+
* Formula: sleep = random(0, min(maxMs, baseMs * 2^attempt))
|
|
57
|
+
*
|
|
58
|
+
* @param attempt - Zero-based retry attempt index.
|
|
59
|
+
* @param baseMs - Base delay in milliseconds.
|
|
60
|
+
* @param maxMs - Maximum delay cap in milliseconds.
|
|
61
|
+
* @returns Sleep duration in milliseconds.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* const delay = computeBackoffMs(2, 1000, 30000); // ~0-4000ms
|
|
65
|
+
*/
|
|
66
|
+
export function computeBackoffMs(attempt: number, baseMs = 1000, maxMs = 30_000): number {
|
|
67
|
+
const exponential = baseMs * Math.pow(2, attempt);
|
|
68
|
+
const capped = Math.min(maxMs, exponential);
|
|
69
|
+
// Full jitter: random value in [0, capped]
|
|
70
|
+
return Math.random() * capped;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Sleeps for the given number of milliseconds.
|
|
75
|
+
*
|
|
76
|
+
* @param ms - Delay in milliseconds.
|
|
77
|
+
* @param signal - Optional AbortSignal to cancel the sleep.
|
|
78
|
+
* @returns Promise that resolves after delay, or rejects if aborted.
|
|
79
|
+
*/
|
|
80
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
if (signal?.aborted) {
|
|
83
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const timer = setTimeout(resolve, ms);
|
|
87
|
+
signal?.addEventListener('abort', () => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Determines if an HTTP response status warrants a retry attempt.
|
|
96
|
+
*
|
|
97
|
+
* @param status - HTTP status code.
|
|
98
|
+
* @returns `true` if the request should be retried.
|
|
99
|
+
*/
|
|
100
|
+
function isRetryableStatus(status: number): boolean {
|
|
101
|
+
return status >= 500 || status === 429;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Performs a resilient HTTP fetch with exponential backoff and jitter.
|
|
106
|
+
* Automatically retries on network failures and 5xx/429 responses.
|
|
107
|
+
*
|
|
108
|
+
* @template T The expected response body type.
|
|
109
|
+
* @param options - Request configuration options.
|
|
110
|
+
* @returns Promise resolving to {@link HttpClientResult}.
|
|
111
|
+
* @throws {Error} When all retry attempts are exhausted or request is aborted.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* const result = await fetchWithRetry<BatchFlagEvaluation>({
|
|
115
|
+
* url: 'https://api.nexus.dev/api/v1/flags/eval',
|
|
116
|
+
* method: 'GET',
|
|
117
|
+
* headers: { Authorization: 'Bearer pk_live_...' },
|
|
118
|
+
* timeoutMs: 3000,
|
|
119
|
+
* maxRetries: 3,
|
|
120
|
+
* });
|
|
121
|
+
* console.log(result.data); // { checkout_v2: { enabled: true, ... } }
|
|
122
|
+
*/
|
|
123
|
+
export async function fetchWithRetry<T = unknown>(
|
|
124
|
+
options: HttpClientOptions,
|
|
125
|
+
): Promise<HttpClientResult<T>> {
|
|
126
|
+
const {
|
|
127
|
+
url,
|
|
128
|
+
method = 'GET',
|
|
129
|
+
headers = {},
|
|
130
|
+
body,
|
|
131
|
+
timeoutMs = 5_000,
|
|
132
|
+
maxRetries = 3,
|
|
133
|
+
retryBaseMs = 1_000,
|
|
134
|
+
retryMaxMs = 30_000,
|
|
135
|
+
signal: externalSignal,
|
|
136
|
+
} = options;
|
|
137
|
+
|
|
138
|
+
let lastError: Error = new Error('Request failed');
|
|
139
|
+
|
|
140
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
141
|
+
// Abort if external signal is already triggered
|
|
142
|
+
if (externalSignal?.aborted) {
|
|
143
|
+
throw new DOMException('Request aborted by caller.', 'AbortError');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
148
|
+
|
|
149
|
+
// Merge external abort signal
|
|
150
|
+
externalSignal?.addEventListener('abort', () => controller.abort());
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
const requestInit: RequestInit = {
|
|
154
|
+
method,
|
|
155
|
+
headers: {
|
|
156
|
+
'Content-Type': 'application/json',
|
|
157
|
+
...headers,
|
|
158
|
+
},
|
|
159
|
+
signal: controller.signal,
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
if (body !== undefined) {
|
|
163
|
+
requestInit.body = typeof body === 'string' ? body : JSON.stringify(body);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const response = await fetch(url, requestInit);
|
|
167
|
+
clearTimeout(timeoutId);
|
|
168
|
+
|
|
169
|
+
if (response.ok) {
|
|
170
|
+
const data = (await response.json()) as T;
|
|
171
|
+
return { data, status: response.status, headers: response.headers };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Non-ok response: check if retryable
|
|
175
|
+
if (isRetryableStatus(response.status) && attempt < maxRetries) {
|
|
176
|
+
lastError = new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
177
|
+
const delay = computeBackoffMs(attempt, retryBaseMs, retryMaxMs);
|
|
178
|
+
await sleep(delay, externalSignal);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Non-retryable error (400, 401, 403, 404, etc.)
|
|
183
|
+
const errorBody = await response.text().catch(() => '');
|
|
184
|
+
throw new Error(`HTTP ${response.status}: ${errorBody}`);
|
|
185
|
+
} catch (err) {
|
|
186
|
+
clearTimeout(timeoutId);
|
|
187
|
+
|
|
188
|
+
if (err instanceof DOMException && err.name === 'AbortError') {
|
|
189
|
+
throw err; // Propagate abort without retry
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
193
|
+
|
|
194
|
+
if (attempt < maxRetries) {
|
|
195
|
+
const delay = computeBackoffMs(attempt, retryBaseMs, retryMaxMs);
|
|
196
|
+
await sleep(delay, externalSignal);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
throw lastError;
|
|
202
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Main entry point for @nexussdk/core.
|
|
3
|
+
* Re-exports the resilient HTTP client, in-memory RingBuffer, environment resolver, and safe JSON parser.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* import { fetchWithRetry, RingBuffer, resolveApiKey, safeStringify } from '@nexussdk/core';
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { fetchWithRetry, computeBackoffMs } from './http-client.js';
|
|
10
|
+
export type { HttpClientOptions, HttpClientResult } from './http-client.js';
|
|
11
|
+
|
|
12
|
+
export { RingBuffer } from './ring-buffer.js';
|
|
13
|
+
|
|
14
|
+
export { resolveApiKey, resolveBaseUrl } from './env-resolver.js';
|
|
15
|
+
|
|
16
|
+
export { safeStringify, safeParse } from './safe-json.js';
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Fixed-capacity ring buffer with FIFO eviction under pressure.
|
|
3
|
+
* Used by SDK Tracker for bounded breadcrumb and telemetry event storage.
|
|
4
|
+
* @module @nexus/core/ring-buffer
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A fixed-capacity circular buffer that drops the oldest entry when full.
|
|
9
|
+
* Never causes memory leaks or starvation of host applications.
|
|
10
|
+
*
|
|
11
|
+
* @template T The type of items stored in the buffer.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const buffer = new RingBuffer<string>(3);
|
|
15
|
+
* buffer.push('a'); // [a]
|
|
16
|
+
* buffer.push('b'); // [a, b]
|
|
17
|
+
* buffer.push('c'); // [a, b, c]
|
|
18
|
+
* buffer.push('d'); // [b, c, d] — 'a' evicted (FIFO)
|
|
19
|
+
* buffer.toArray(); // ['b', 'c', 'd']
|
|
20
|
+
*/
|
|
21
|
+
export class RingBuffer<T> {
|
|
22
|
+
private readonly capacity: number;
|
|
23
|
+
private readonly buffer: Array<T | undefined>;
|
|
24
|
+
private head = 0; // Points to the next write position
|
|
25
|
+
private count = 0; // Current number of items
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Creates a new RingBuffer with the given capacity.
|
|
29
|
+
*
|
|
30
|
+
* @param capacity - Maximum number of items to retain. Must be >= 1.
|
|
31
|
+
* @throws {RangeError} If capacity is less than 1.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const breadcrumbBuffer = new RingBuffer<Breadcrumb>(20);
|
|
35
|
+
*/
|
|
36
|
+
constructor(capacity: number) {
|
|
37
|
+
if (capacity < 1) {
|
|
38
|
+
throw new RangeError(`RingBuffer capacity must be >= 1, got ${capacity}`);
|
|
39
|
+
}
|
|
40
|
+
this.capacity = capacity;
|
|
41
|
+
this.buffer = new Array<T | undefined>(capacity).fill(undefined);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Appends an item to the buffer.
|
|
46
|
+
* If the buffer is at capacity, the oldest item is silently dropped.
|
|
47
|
+
*
|
|
48
|
+
* @param item - The item to insert.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* buffer.push({ timestamp: Date.now(), category: 'ui.click', message: 'Clicked #btn' });
|
|
52
|
+
*/
|
|
53
|
+
push(item: T): void {
|
|
54
|
+
this.buffer[this.head] = item;
|
|
55
|
+
this.head = (this.head + 1) % this.capacity;
|
|
56
|
+
if (this.count < this.capacity) {
|
|
57
|
+
this.count++;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Returns all stored items in chronological order (oldest first).
|
|
63
|
+
*
|
|
64
|
+
* @returns Ordered array of stored items.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* const breadcrumbs = buffer.toArray(); // [{...}, {...}]
|
|
68
|
+
*/
|
|
69
|
+
toArray(): T[] {
|
|
70
|
+
if (this.count === 0) return [];
|
|
71
|
+
|
|
72
|
+
const result: T[] = [];
|
|
73
|
+
if (this.count < this.capacity) {
|
|
74
|
+
// Buffer not yet full — read from index 0 to head-1
|
|
75
|
+
for (let i = 0; i < this.count; i++) {
|
|
76
|
+
result.push(this.buffer[i] as T);
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
// Buffer full — oldest item is at `head`
|
|
80
|
+
for (let i = 0; i < this.capacity; i++) {
|
|
81
|
+
result.push(this.buffer[(this.head + i) % this.capacity] as T);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Returns the current number of items in the buffer.
|
|
89
|
+
*
|
|
90
|
+
* @returns Item count (0 to capacity).
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* console.log(buffer.size); // 3
|
|
94
|
+
*/
|
|
95
|
+
get size(): number {
|
|
96
|
+
return this.count;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Returns the maximum capacity of the buffer.
|
|
101
|
+
*
|
|
102
|
+
* @returns Buffer capacity.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* console.log(buffer.maxCapacity); // 20
|
|
106
|
+
*/
|
|
107
|
+
get maxCapacity(): number {
|
|
108
|
+
return this.capacity;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Checks if the buffer is currently at full capacity.
|
|
113
|
+
*
|
|
114
|
+
* @returns `true` if the buffer is full.
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* if (buffer.isFull) console.log('Oldest breadcrumb will be evicted on next push.');
|
|
118
|
+
*/
|
|
119
|
+
get isFull(): boolean {
|
|
120
|
+
return this.count === this.capacity;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Removes all items from the buffer and resets internal state.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* buffer.clear(); // buffer is now empty
|
|
128
|
+
*/
|
|
129
|
+
clear(): void {
|
|
130
|
+
this.buffer.fill(undefined);
|
|
131
|
+
this.head = 0;
|
|
132
|
+
this.count = 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Peeks at the most recently added item without removing it.
|
|
137
|
+
*
|
|
138
|
+
* @returns The last item pushed, or `undefined` if empty.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* const last = buffer.peek(); // most recent item
|
|
142
|
+
*/
|
|
143
|
+
peek(): T | undefined {
|
|
144
|
+
if (this.count === 0) return undefined;
|
|
145
|
+
const lastIndex = (this.head - 1 + this.capacity) % this.capacity;
|
|
146
|
+
return this.buffer[lastIndex];
|
|
147
|
+
}
|
|
148
|
+
}
|
package/src/safe-json.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Circular-reference-safe JSON serializer using WeakSet tracking.
|
|
3
|
+
* Prevents TypeError crashes when serializing objects with circular references.
|
|
4
|
+
* @module @nexus/core/safe-json
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Recursively sanitizes an object for JSON serialization by replacing
|
|
9
|
+
* circular references with the string "[Circular]".
|
|
10
|
+
*
|
|
11
|
+
* @param value - The value to sanitize.
|
|
12
|
+
* @param seen - WeakSet tracking visited objects (used internally for recursion).
|
|
13
|
+
* @param depth - Current recursion depth.
|
|
14
|
+
* @param maxDepth - Maximum allowed recursion depth.
|
|
15
|
+
* @returns A serialization-safe copy of the value.
|
|
16
|
+
*/
|
|
17
|
+
function sanitizeForSerialization(
|
|
18
|
+
value: unknown,
|
|
19
|
+
seen: WeakSet<object>,
|
|
20
|
+
depth: number,
|
|
21
|
+
maxDepth: number,
|
|
22
|
+
): unknown {
|
|
23
|
+
if (depth > maxDepth) {
|
|
24
|
+
return '[MaxDepthExceeded]';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (value === null || value === undefined) {
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (typeof value !== 'object' && typeof value !== 'function') {
|
|
32
|
+
// Primitive value: string, number, boolean, bigint, symbol
|
|
33
|
+
if (typeof value === 'bigint') {
|
|
34
|
+
return value.toString(); // JSON cannot handle BigInt natively
|
|
35
|
+
}
|
|
36
|
+
if (typeof value === 'symbol') {
|
|
37
|
+
return value.toString();
|
|
38
|
+
}
|
|
39
|
+
if (typeof value === 'function') {
|
|
40
|
+
return '[Function]';
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Handle Error objects specially — preserve message and stack
|
|
46
|
+
if (value instanceof Error) {
|
|
47
|
+
return {
|
|
48
|
+
name: value.name,
|
|
49
|
+
message: value.message,
|
|
50
|
+
stack: value.stack,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Circular reference detection
|
|
55
|
+
if (seen.has(value as object)) {
|
|
56
|
+
return '[Circular]';
|
|
57
|
+
}
|
|
58
|
+
seen.add(value as object);
|
|
59
|
+
|
|
60
|
+
// Handle Arrays
|
|
61
|
+
if (Array.isArray(value)) {
|
|
62
|
+
const result = value.map((item) =>
|
|
63
|
+
sanitizeForSerialization(item, seen, depth + 1, maxDepth),
|
|
64
|
+
);
|
|
65
|
+
seen.delete(value as object);
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Handle plain Objects
|
|
70
|
+
const result: Record<string, unknown> = {};
|
|
71
|
+
for (const key of Object.keys(value as object)) {
|
|
72
|
+
const propValue = (value as Record<string, unknown>)[key];
|
|
73
|
+
result[key] = sanitizeForSerialization(propValue, seen, depth + 1, maxDepth);
|
|
74
|
+
}
|
|
75
|
+
seen.delete(value as object);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Serializes a value to a JSON string, gracefully handling:
|
|
81
|
+
* - Circular references (replaced with "[Circular]")
|
|
82
|
+
* - BigInt values (converted to string)
|
|
83
|
+
* - Symbol values (converted to string)
|
|
84
|
+
* - Function values (replaced with "[Function]")
|
|
85
|
+
* - Deep nesting (capped at maxDepth, replaced with "[MaxDepthExceeded]")
|
|
86
|
+
*
|
|
87
|
+
* @param value - Any value to serialize.
|
|
88
|
+
* @param maxDepth - Maximum recursion depth. Defaults to 8.
|
|
89
|
+
* @returns JSON string representation of the value.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* const obj: Record<string, unknown> = { name: 'test' };
|
|
93
|
+
* obj['self'] = obj; // circular reference
|
|
94
|
+
* const json = safeStringify(obj);
|
|
95
|
+
* // '{"name":"test","self":"[Circular]"}'
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* const err = new Error('Something failed');
|
|
99
|
+
* const json = safeStringify({ error: err, code: 500 });
|
|
100
|
+
* // '{"error":{"name":"Error","message":"Something failed","stack":"..."},"code":500}'
|
|
101
|
+
*/
|
|
102
|
+
export function safeStringify(value: unknown, maxDepth = 8): string {
|
|
103
|
+
const seen = new WeakSet<object>();
|
|
104
|
+
const sanitized = sanitizeForSerialization(value, seen, 0, maxDepth);
|
|
105
|
+
try {
|
|
106
|
+
return JSON.stringify(sanitized);
|
|
107
|
+
} catch {
|
|
108
|
+
// Absolute last resort fallback
|
|
109
|
+
return JSON.stringify({ error: '[SerializationFailed]' });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Safely parses a JSON string without throwing on invalid input.
|
|
115
|
+
*
|
|
116
|
+
* @param input - The JSON string to parse.
|
|
117
|
+
* @param fallback - Value to return if parsing fails. Defaults to `null`.
|
|
118
|
+
* @returns Parsed value or fallback.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* const data = safeParse<{ id: string }>('{"id":"123"}');
|
|
122
|
+
* // { id: '123' }
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* const data = safeParse<unknown>('{{invalid json}}', null);
|
|
126
|
+
* // null
|
|
127
|
+
*/
|
|
128
|
+
export function safeParse<T = unknown>(input: string, fallback: T | null = null): T | null {
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(input) as T;
|
|
131
|
+
} catch {
|
|
132
|
+
return fallback;
|
|
133
|
+
}
|
|
134
|
+
}
|
package/tsconfig.json
ADDED
package/tsup.config.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { defineConfig } from 'tsup';
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
entry: ['src/index.ts'],
|
|
5
|
+
format: ['esm', 'cjs', 'iife'],
|
|
6
|
+
globalName: 'NexusCore',
|
|
7
|
+
dts: true,
|
|
8
|
+
splitting: false,
|
|
9
|
+
sourcemap: true,
|
|
10
|
+
clean: true,
|
|
11
|
+
minify: true,
|
|
12
|
+
treeshake: true,
|
|
13
|
+
target: 'es2022',
|
|
14
|
+
outExtension({ format }) {
|
|
15
|
+
return {
|
|
16
|
+
js: format === 'esm' ? '.mjs' : format === 'cjs' ? '.cjs' : '.global.js',
|
|
17
|
+
};
|
|
18
|
+
},
|
|
19
|
+
});
|