@frontal-labs/data 0.1.1 → 0.1.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/index.cjs +34 -1150
- package/dist/index.js +11 -1120
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +6 -5
package/dist/index.js
CHANGED
|
@@ -1,1123 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
}
|
|
8
|
-
function parseWithDictionary(dictionary, value) {
|
|
9
|
-
const result = {};
|
|
10
|
-
const issues = [];
|
|
11
|
-
for (const key in dictionary) {
|
|
12
|
-
const propResult = dictionary[key]["~standard"].validate(value[key]);
|
|
13
|
-
ensureSynchronous(propResult, `Validation must be synchronous, but ${key} returned a Promise.`);
|
|
14
|
-
if (propResult.issues) {
|
|
15
|
-
issues.push(...propResult.issues.map((issue) => ({
|
|
16
|
-
...issue,
|
|
17
|
-
message: issue.message,
|
|
18
|
-
path: [key, ...issue.path ?? []]
|
|
19
|
-
})));
|
|
20
|
-
continue;
|
|
21
|
-
}
|
|
22
|
-
result[key] = propResult.value;
|
|
23
|
-
}
|
|
24
|
-
if (issues.length) return { issues };
|
|
25
|
-
return { value: result };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// ../../node_modules/.bun/@t3-oss+env-core@0.13.11+dcb9db7a51b27bde/node_modules/@t3-oss/env-core/dist/index.js
|
|
29
|
-
function createEnv(opts) {
|
|
30
|
-
const runtimeEnv = opts.runtimeEnvStrict ?? opts.runtimeEnv ?? process.env;
|
|
31
|
-
if (opts.emptyStringAsUndefined ?? false) {
|
|
32
|
-
for (const [key, value] of Object.entries(runtimeEnv)) if (value === "") delete runtimeEnv[key];
|
|
33
|
-
}
|
|
34
|
-
if (!!opts.skipValidation) {
|
|
35
|
-
if (opts.extends) for (const preset of opts.extends) preset.skipValidation = true;
|
|
36
|
-
return runtimeEnv;
|
|
37
|
-
}
|
|
38
|
-
const _client = typeof opts.client === "object" ? opts.client : {};
|
|
39
|
-
const _server = typeof opts.server === "object" ? opts.server : {};
|
|
40
|
-
const _shared = typeof opts.shared === "object" ? opts.shared : {};
|
|
41
|
-
const isServer = opts.isServer ?? (typeof window === "undefined" || "Deno" in window);
|
|
42
|
-
const finalSchemaShape = isServer ? {
|
|
43
|
-
..._server,
|
|
44
|
-
..._shared,
|
|
45
|
-
..._client
|
|
46
|
-
} : {
|
|
47
|
-
..._client,
|
|
48
|
-
..._shared
|
|
49
|
-
};
|
|
50
|
-
const parsed = opts.createFinalSchema?.(finalSchemaShape, isServer)?.["~standard"].validate(runtimeEnv) ?? parseWithDictionary(finalSchemaShape, runtimeEnv);
|
|
51
|
-
ensureSynchronous(parsed, "Validation must be synchronous");
|
|
52
|
-
const onValidationError = opts.onValidationError ?? ((issues) => {
|
|
53
|
-
console.error("\u274C Invalid environment variables:", issues);
|
|
54
|
-
throw new Error("Invalid environment variables");
|
|
55
|
-
});
|
|
56
|
-
const onInvalidAccess = opts.onInvalidAccess ?? (() => {
|
|
57
|
-
throw new Error("\u274C Attempted to access a server-side environment variable on the client");
|
|
58
|
-
});
|
|
59
|
-
if (parsed.issues) return onValidationError(parsed.issues);
|
|
60
|
-
const isServerAccess = (prop) => {
|
|
61
|
-
if (!opts.clientPrefix) return true;
|
|
62
|
-
return !prop.startsWith(opts.clientPrefix) && !(prop in _shared);
|
|
63
|
-
};
|
|
64
|
-
const isValidServerAccess = (prop) => {
|
|
65
|
-
return isServer || !isServerAccess(prop);
|
|
66
|
-
};
|
|
67
|
-
const ignoreProp = (prop) => {
|
|
68
|
-
return prop === "__esModule" || prop === "$$typeof";
|
|
69
|
-
};
|
|
70
|
-
const extendedObj = (opts.extends ?? []).reduce((acc, curr) => {
|
|
71
|
-
return Object.assign(acc, curr);
|
|
72
|
-
}, {});
|
|
73
|
-
const fullObj = Object.assign(extendedObj, parsed.value);
|
|
74
|
-
return new Proxy(fullObj, { get(target, prop) {
|
|
75
|
-
if (typeof prop !== "string") return void 0;
|
|
76
|
-
if (ignoreProp(prop)) return void 0;
|
|
77
|
-
if (!isValidServerAccess(prop)) return onInvalidAccess(prop);
|
|
78
|
-
return Reflect.get(target, prop);
|
|
79
|
-
} });
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// ../core/dist/index.js
|
|
83
|
-
import { z as z2 } from "zod";
|
|
84
|
-
import { z as z3 } from "zod";
|
|
85
|
-
import { z as z4 } from "zod";
|
|
86
|
-
var DEFAULT_BASE_URL = "https://api.frontal.dev/v1";
|
|
87
|
-
var API_KEY_PREFIX = "frt_";
|
|
88
|
-
var BACKOFF_STRATEGIES = [
|
|
89
|
-
"exponential",
|
|
90
|
-
"linear",
|
|
91
|
-
"constant"
|
|
92
|
-
];
|
|
93
|
-
var DEFAULT_RETRY_ON = [429, 500, 502, 503, 504];
|
|
94
|
-
var EXPONENTIAL_BASE = 2;
|
|
95
|
-
var JITTER_MAX = 200;
|
|
96
|
-
var SDK_VERSION = "1.0.1";
|
|
97
|
-
var timestampSchema = z.date().transform((date) => new Date(date));
|
|
98
|
-
var responseMetaSchema = z.object({
|
|
99
|
-
requestId: z.string().min(1),
|
|
100
|
-
timestamp: timestampSchema,
|
|
101
|
-
version: z.string().optional(),
|
|
102
|
-
substrate: z.string().optional(),
|
|
103
|
-
latency: z.object({
|
|
104
|
-
total: z.number().int().min(0),
|
|
105
|
-
substrate: z.number().int().min(0).optional()
|
|
106
|
-
}).optional()
|
|
107
|
-
}).strict();
|
|
108
|
-
var paginationMetaSchema = z.object({
|
|
109
|
-
cursor: z.string().min(1),
|
|
110
|
-
hasMore: z.boolean(),
|
|
111
|
-
limit: z.number().int().positive().optional(),
|
|
112
|
-
total: z.number().int().min(0).optional(),
|
|
113
|
-
offset: z.number().int().min(0).optional()
|
|
114
|
-
}).strict();
|
|
115
|
-
var errorFieldSchema = z.object({
|
|
116
|
-
field: z.string().describe("Field name"),
|
|
117
|
-
code: z.string().describe("Error code"),
|
|
118
|
-
message: z.string().describe("Error message")
|
|
119
|
-
}).strict();
|
|
120
|
-
var docsUrlSchema = z.string().url().refine((url) => /^https?:\/\//.test(url), {
|
|
121
|
-
message: "docs must be an http or https URL"
|
|
122
|
-
});
|
|
123
|
-
var errorResponseSchema = z.object({
|
|
124
|
-
code: z.string().min(1).describe("Error code"),
|
|
125
|
-
message: z.string().min(1).describe("Error message"),
|
|
126
|
-
requestId: z.string().min(1).describe("Request ID"),
|
|
127
|
-
docs: docsUrlSchema.optional().describe("Documentation URL"),
|
|
128
|
-
fields: z.array(errorFieldSchema).optional().describe("Array of error fields")
|
|
129
|
-
}).strict();
|
|
130
|
-
var retryStatusCodeSchema = z.number().int().refine((status) => status === 429 || status >= 500 && status <= 599, {
|
|
131
|
-
message: "Retry status codes must be 429 or 5xx"
|
|
132
|
-
});
|
|
133
|
-
var retryConfigSchema = z.object({
|
|
134
|
-
maxAttempts: z.number().int().positive().default(3),
|
|
135
|
-
baseDelay: z.number().int().positive().default(1e3),
|
|
136
|
-
strategy: z.enum(BACKOFF_STRATEGIES).default("exponential"),
|
|
137
|
-
on: z.array(retryStatusCodeSchema).default(DEFAULT_RETRY_ON),
|
|
138
|
-
jitter: z.boolean().default(true)
|
|
139
|
-
}).strict().default({
|
|
140
|
-
maxAttempts: 3,
|
|
141
|
-
baseDelay: 1e3,
|
|
142
|
-
strategy: "exponential",
|
|
143
|
-
on: DEFAULT_RETRY_ON,
|
|
144
|
-
jitter: true
|
|
145
|
-
});
|
|
146
|
-
var numericValueSchema = z.union([
|
|
147
|
-
z.number(),
|
|
148
|
-
z.literal(Number.POSITIVE_INFINITY),
|
|
149
|
-
z.literal(Number.NEGATIVE_INFINITY)
|
|
150
|
-
]);
|
|
151
|
-
var arrayFilterValueSchema = z.union([
|
|
152
|
-
z.array(z.string()),
|
|
153
|
-
z.array(numericValueSchema)
|
|
154
|
-
]);
|
|
155
|
-
var scalarFilterValueSchema = z.union([
|
|
156
|
-
z.string(),
|
|
157
|
-
numericValueSchema,
|
|
158
|
-
z.boolean(),
|
|
159
|
-
z.date(),
|
|
160
|
-
z.null(),
|
|
161
|
-
arrayFilterValueSchema
|
|
162
|
-
]);
|
|
163
|
-
var comparableValueSchema = z.union([numericValueSchema, z.date()]);
|
|
164
|
-
var filterOperatorSchema = z.object({
|
|
165
|
-
eq: scalarFilterValueSchema.optional(),
|
|
166
|
-
ne: scalarFilterValueSchema.optional(),
|
|
167
|
-
gt: comparableValueSchema.optional(),
|
|
168
|
-
gte: comparableValueSchema.optional(),
|
|
169
|
-
lt: comparableValueSchema.optional(),
|
|
170
|
-
lte: comparableValueSchema.optional(),
|
|
171
|
-
in: arrayFilterValueSchema.optional(),
|
|
172
|
-
nin: arrayFilterValueSchema.optional(),
|
|
173
|
-
contains: z.string().optional(),
|
|
174
|
-
startsWith: z.string().optional(),
|
|
175
|
-
endsWith: z.string().optional()
|
|
176
|
-
}).strict().refine(
|
|
177
|
-
(value) => Object.values(value).some((entry) => entry !== void 0),
|
|
178
|
-
{
|
|
179
|
-
message: "At least one filter operator is required"
|
|
180
|
-
}
|
|
181
|
-
);
|
|
182
|
-
var filterValueSchema = z.union([
|
|
183
|
-
scalarFilterValueSchema,
|
|
184
|
-
filterOperatorSchema
|
|
185
|
-
]);
|
|
186
|
-
var filterConditionsSchema = z.record(z.string(), filterValueSchema);
|
|
187
|
-
var pageResultSchema = z.object({
|
|
188
|
-
data: z.array(z.unknown()),
|
|
189
|
-
meta: responseMetaSchema.optional(),
|
|
190
|
-
pagination: paginationMetaSchema
|
|
191
|
-
}).strict();
|
|
192
|
-
var FrontalError = class extends Error {
|
|
193
|
-
code;
|
|
194
|
-
requestId;
|
|
195
|
-
statusCode;
|
|
196
|
-
docs;
|
|
197
|
-
rateLimit;
|
|
198
|
-
/**
|
|
199
|
-
* @param response - The parsed error response from the API.
|
|
200
|
-
* @param statusCode - The HTTP status code.
|
|
201
|
-
* @param rateLimit - Optional rate-limit headers from the response.
|
|
202
|
-
*/
|
|
203
|
-
constructor(response, statusCode, rateLimit) {
|
|
204
|
-
super(response.message);
|
|
205
|
-
this.name = "FrontalError";
|
|
206
|
-
this.code = response.code;
|
|
207
|
-
this.requestId = response.requestId;
|
|
208
|
-
this.statusCode = statusCode;
|
|
209
|
-
this.docs = response.docs;
|
|
210
|
-
this.rateLimit = rateLimit;
|
|
211
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
212
|
-
if (Error.captureStackTrace) {
|
|
213
|
-
Error.captureStackTrace(this);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
var NotFoundError = class extends FrontalError {
|
|
218
|
-
constructor(r, rateLimit) {
|
|
219
|
-
super(r, 404, rateLimit);
|
|
220
|
-
this.name = "NotFoundError";
|
|
221
|
-
}
|
|
222
|
-
};
|
|
223
|
-
var UnauthorizedError = class extends FrontalError {
|
|
224
|
-
constructor(r, rateLimit) {
|
|
225
|
-
super(r, 401, rateLimit);
|
|
226
|
-
this.name = "UnauthorizedError";
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
var ForbiddenError = class extends FrontalError {
|
|
230
|
-
constructor(r, rateLimit) {
|
|
231
|
-
super(r, 403, rateLimit);
|
|
232
|
-
this.name = "ForbiddenError";
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
var ValidationError = class extends FrontalError {
|
|
236
|
-
/** Per-field validation errors returned by the API. */
|
|
237
|
-
fields;
|
|
238
|
-
constructor(r, rateLimit) {
|
|
239
|
-
super(r, 400, rateLimit);
|
|
240
|
-
this.name = "ValidationError";
|
|
241
|
-
this.fields = r.fields ?? [];
|
|
242
|
-
}
|
|
243
|
-
};
|
|
244
|
-
var ConflictError = class extends FrontalError {
|
|
245
|
-
constructor(r, rateLimit) {
|
|
246
|
-
super(r, 409, rateLimit);
|
|
247
|
-
this.name = "ConflictError";
|
|
248
|
-
}
|
|
249
|
-
};
|
|
250
|
-
var RateLimitError = class extends FrontalError {
|
|
251
|
-
/** Recommended delay in seconds before retrying. */
|
|
252
|
-
retryAfter;
|
|
253
|
-
constructor(r, retryAfter, rateLimit) {
|
|
254
|
-
super(r, 429, rateLimit);
|
|
255
|
-
this.name = "RateLimitError";
|
|
256
|
-
this.retryAfter = retryAfter;
|
|
257
|
-
}
|
|
258
|
-
};
|
|
259
|
-
var ServiceError = class extends FrontalError {
|
|
260
|
-
constructor(r, status, rateLimit) {
|
|
261
|
-
super(r, status, rateLimit);
|
|
262
|
-
this.name = "ServiceError";
|
|
263
|
-
}
|
|
264
|
-
};
|
|
265
|
-
var NetworkError = class extends Error {
|
|
266
|
-
constructor(cause) {
|
|
267
|
-
super("Network error \u2014 could not reach Frontal API");
|
|
268
|
-
this.cause = cause;
|
|
269
|
-
this.name = "NetworkError";
|
|
270
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
271
|
-
if (Error.captureStackTrace) {
|
|
272
|
-
Error.captureStackTrace(this, new.target);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
function normalizeErrorBody(body) {
|
|
277
|
-
const parsed = errorResponseSchema.safeParse(body);
|
|
278
|
-
if (parsed.success) return parsed.data;
|
|
279
|
-
const fallback = typeof body === "object" && body !== null ? body : {};
|
|
280
|
-
const code = typeof fallback.code === "string" && fallback.code.length > 0 ? fallback.code : "UNKNOWN_ERROR";
|
|
281
|
-
const hasExplicitCode = typeof fallback.code === "string" && fallback.code.length > 0;
|
|
282
|
-
const message = hasExplicitCode && typeof fallback.message === "string" && fallback.message.length > 0 ? fallback.message : "An unknown error occurred";
|
|
283
|
-
return {
|
|
284
|
-
code,
|
|
285
|
-
message,
|
|
286
|
-
requestId: typeof fallback.requestId === "string" && fallback.requestId.length > 0 ? fallback.requestId : "unknown",
|
|
287
|
-
docs: typeof fallback.docs === "string" ? fallback.docs : void 0,
|
|
288
|
-
fields: Array.isArray(fallback.fields) ? fallback.fields : void 0
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
function parseFrontalError(body, status, retryAfter, rateLimit) {
|
|
292
|
-
const normalized = normalizeErrorBody(body);
|
|
293
|
-
switch (status) {
|
|
294
|
-
case 400:
|
|
295
|
-
return new ValidationError(normalized, rateLimit);
|
|
296
|
-
case 401:
|
|
297
|
-
return new UnauthorizedError(normalized, rateLimit);
|
|
298
|
-
case 403:
|
|
299
|
-
return new ForbiddenError(normalized, rateLimit);
|
|
300
|
-
case 404:
|
|
301
|
-
return new NotFoundError(normalized, rateLimit);
|
|
302
|
-
case 409:
|
|
303
|
-
return new ConflictError(normalized, rateLimit);
|
|
304
|
-
case 429: {
|
|
305
|
-
const parsedRetry = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;
|
|
306
|
-
return new RateLimitError(
|
|
307
|
-
normalized,
|
|
308
|
-
Number.isFinite(parsedRetry) ? parsedRetry : 60,
|
|
309
|
-
rateLimit
|
|
310
|
-
);
|
|
311
|
-
}
|
|
312
|
-
default:
|
|
313
|
-
return new ServiceError(normalized, status, rateLimit);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
var CircuitBreaker = class {
|
|
317
|
-
failures = 0;
|
|
318
|
-
lastFailureTime = 0;
|
|
319
|
-
state = "CLOSED";
|
|
320
|
-
config;
|
|
321
|
-
constructor(config) {
|
|
322
|
-
this.config = config;
|
|
323
|
-
}
|
|
324
|
-
/** Returns the current circuit state. */
|
|
325
|
-
getState() {
|
|
326
|
-
return this.state;
|
|
327
|
-
}
|
|
328
|
-
/** Returns the current consecutive failure count. */
|
|
329
|
-
getFailures() {
|
|
330
|
-
return this.failures;
|
|
331
|
-
}
|
|
332
|
-
reset() {
|
|
333
|
-
this.failures = 0;
|
|
334
|
-
this.state = "CLOSED";
|
|
335
|
-
this.config.onClose?.();
|
|
336
|
-
}
|
|
337
|
-
/**
|
|
338
|
-
* Executes an async function through the circuit breaker.
|
|
339
|
-
* Throws CircuitBreakerOpenError immediately if the circuit is OPEN
|
|
340
|
-
* and the reset timeout has not elapsed. On success in HALF_OPEN state,
|
|
341
|
-
* resets the circuit to CLOSED.
|
|
342
|
-
*
|
|
343
|
-
* @param fn - The async operation to protect.
|
|
344
|
-
* @throws {CircuitBreakerOpenError} If the circuit is OPEN.
|
|
345
|
-
*/
|
|
346
|
-
async execute(fn) {
|
|
347
|
-
if (this.state === "OPEN") {
|
|
348
|
-
if (Date.now() - this.lastFailureTime > this.config.resetTimeoutMs) {
|
|
349
|
-
this.state = "HALF_OPEN";
|
|
350
|
-
this.config.onHalfOpen?.();
|
|
351
|
-
} else {
|
|
352
|
-
throw new CircuitBreakerOpenError(
|
|
353
|
-
this.config.resetTimeoutMs - (Date.now() - this.lastFailureTime)
|
|
354
|
-
);
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
try {
|
|
358
|
-
const result = await fn();
|
|
359
|
-
if (this.state === "HALF_OPEN") {
|
|
360
|
-
this.reset();
|
|
361
|
-
}
|
|
362
|
-
return result;
|
|
363
|
-
} catch (error) {
|
|
364
|
-
this.failures++;
|
|
365
|
-
this.lastFailureTime = Date.now();
|
|
366
|
-
if (this.failures >= this.config.failureThreshold) {
|
|
367
|
-
this.state = "OPEN";
|
|
368
|
-
this.config.onOpen?.();
|
|
369
|
-
}
|
|
370
|
-
throw error;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
/** Manually forces the circuit into the OPEN state. */
|
|
374
|
-
forceOpen() {
|
|
375
|
-
this.state = "OPEN";
|
|
376
|
-
this.lastFailureTime = Date.now();
|
|
377
|
-
}
|
|
378
|
-
/** Manually resets the circuit to the CLOSED state. */
|
|
379
|
-
forceClose() {
|
|
380
|
-
this.reset();
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
var CircuitBreakerOpenError = class extends Error {
|
|
384
|
-
/** Milliseconds remaining until the circuit transitions to HALF_OPEN. */
|
|
385
|
-
retryAfterMs;
|
|
386
|
-
constructor(retryAfterMs) {
|
|
387
|
-
super(
|
|
388
|
-
`Circuit breaker is open \u2014 retry after ${Math.ceil(retryAfterMs / 1e3)}s`
|
|
389
|
-
);
|
|
390
|
-
this.name = "CircuitBreakerOpenError";
|
|
391
|
-
this.retryAfterMs = retryAfterMs;
|
|
392
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
393
|
-
}
|
|
394
|
-
};
|
|
395
|
-
function computeBaseDelay(attempt, strategy, baseDelay) {
|
|
396
|
-
const normalizedAttempt = Math.floor(attempt);
|
|
397
|
-
switch (strategy) {
|
|
398
|
-
case "linear":
|
|
399
|
-
return Math.max(0, baseDelay * (normalizedAttempt + 1));
|
|
400
|
-
case "constant":
|
|
401
|
-
return baseDelay;
|
|
402
|
-
default:
|
|
403
|
-
return baseDelay * EXPONENTIAL_BASE ** normalizedAttempt;
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
function calculateDelay(attempt, strategyOrConfig, baseDelay, withJitter = false) {
|
|
407
|
-
if (typeof strategyOrConfig === "object") {
|
|
408
|
-
const strategy = "strategy" in strategyOrConfig ? strategyOrConfig.strategy : strategyOrConfig.backoff;
|
|
409
|
-
const delayBase = "baseDelay" in strategyOrConfig ? strategyOrConfig.baseDelay : strategyOrConfig.retryDelay;
|
|
410
|
-
const delay2 = computeBaseDelay(attempt, strategy, delayBase);
|
|
411
|
-
const shouldJitter = "jitter" in strategyOrConfig ? Boolean(strategyOrConfig.jitter) : true;
|
|
412
|
-
if (!shouldJitter) return delay2;
|
|
413
|
-
return delay2 + Math.random() * (JITTER_MAX / 2);
|
|
414
|
-
}
|
|
415
|
-
const delay = computeBaseDelay(
|
|
416
|
-
attempt,
|
|
417
|
-
strategyOrConfig,
|
|
418
|
-
Math.max(0, baseDelay ?? 0)
|
|
419
|
-
);
|
|
420
|
-
if (!withJitter) return delay;
|
|
421
|
-
return delay + Math.random() * (JITTER_MAX / 2);
|
|
422
|
-
}
|
|
423
|
-
function snakeToCamel(str) {
|
|
424
|
-
const prefix = str.match(/^_+/)?.[0] ?? "";
|
|
425
|
-
const body = str.slice(prefix.length);
|
|
426
|
-
if (!body) return str;
|
|
427
|
-
return prefix + body.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
428
|
-
}
|
|
429
|
-
function camelToSnake(str) {
|
|
430
|
-
return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
431
|
-
}
|
|
432
|
-
var NEVER_TRANSFORM_KEYS = /* @__PURE__ */ new Set(["$ref", "$schema", "$id"]);
|
|
433
|
-
function isStream(obj) {
|
|
434
|
-
return typeof obj === "object" && obj !== null && (typeof obj.pipe === "function" || typeof obj.getReader === "function");
|
|
435
|
-
}
|
|
436
|
-
function deepTransformKeys(obj, transform, skipKeys) {
|
|
437
|
-
if (obj === null || obj === void 0) return obj;
|
|
438
|
-
if (typeof obj !== "object") return obj;
|
|
439
|
-
if (obj instanceof Date || typeof Buffer !== "undefined" && obj instanceof Buffer || obj instanceof RegExp || obj instanceof FormData || obj instanceof File || obj instanceof Blob)
|
|
440
|
-
return obj;
|
|
441
|
-
if (isStream(obj)) return obj;
|
|
442
|
-
if (Array.isArray(obj)) {
|
|
443
|
-
return obj.map(
|
|
444
|
-
(item) => deepTransformKeys(item, transform, skipKeys)
|
|
445
|
-
);
|
|
446
|
-
}
|
|
447
|
-
const proto = Object.getPrototypeOf(obj);
|
|
448
|
-
if (proto !== Object.prototype && proto !== null) return obj;
|
|
449
|
-
const result = {};
|
|
450
|
-
for (const key of Object.keys(obj)) {
|
|
451
|
-
const shouldSkip = skipKeys?.has(key) || NEVER_TRANSFORM_KEYS.has(key);
|
|
452
|
-
const newKey = shouldSkip ? key : transform(key);
|
|
453
|
-
result[newKey] = deepTransformKeys(
|
|
454
|
-
obj[key],
|
|
455
|
-
transform,
|
|
456
|
-
skipKeys
|
|
457
|
-
);
|
|
458
|
-
}
|
|
459
|
-
return result;
|
|
460
|
-
}
|
|
461
|
-
function deepCamelToSnake(obj, skipKeys) {
|
|
462
|
-
return deepTransformKeys(obj, camelToSnake, skipKeys);
|
|
463
|
-
}
|
|
464
|
-
function deepSnakeToCamel(obj, skipKeys) {
|
|
465
|
-
return deepTransformKeys(obj, snakeToCamel, skipKeys);
|
|
466
|
-
}
|
|
467
|
-
var HttpClient = class {
|
|
468
|
-
constructor(config) {
|
|
469
|
-
this.config = config;
|
|
470
|
-
if (config.circuitBreaker) {
|
|
471
|
-
this.breaker = new CircuitBreaker({
|
|
472
|
-
failureThreshold: config.circuitBreaker.failureThreshold,
|
|
473
|
-
resetTimeoutMs: config.circuitBreaker.resetTimeoutMs
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
breaker;
|
|
478
|
-
/**
|
|
479
|
-
* Sends a GET request.
|
|
480
|
-
* @param path - API endpoint path.
|
|
481
|
-
* @param params - Optional query parameters.
|
|
482
|
-
* @param schema - Optional Zod schema for response validation.
|
|
483
|
-
*/
|
|
484
|
-
async get(path, params, schema) {
|
|
485
|
-
return this.request("GET", path, void 0, params, schema);
|
|
486
|
-
}
|
|
487
|
-
/**
|
|
488
|
-
* Sends a POST request with a JSON body.
|
|
489
|
-
* @param path - API endpoint path.
|
|
490
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
491
|
-
* @param schema - Optional Zod schema for response validation.
|
|
492
|
-
*/
|
|
493
|
-
async post(path, body, schema) {
|
|
494
|
-
return this.request("POST", path, body ?? {}, void 0, schema);
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* Sends a PUT request with a JSON body.
|
|
498
|
-
* @param path - API endpoint path.
|
|
499
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
500
|
-
* @param schema - Optional Zod schema for response validation.
|
|
501
|
-
*/
|
|
502
|
-
async put(path, body, schema) {
|
|
503
|
-
return this.request("PUT", path, body ?? {}, void 0, schema);
|
|
504
|
-
}
|
|
505
|
-
/**
|
|
506
|
-
* Sends a PATCH request with a JSON body.
|
|
507
|
-
* @param path - API endpoint path.
|
|
508
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
509
|
-
* @param schema - Optional Zod schema for response validation.
|
|
510
|
-
*/
|
|
511
|
-
async patch(path, body, schema) {
|
|
512
|
-
return this.request("PATCH", path, body ?? {}, void 0, schema);
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* Sends a DELETE request.
|
|
516
|
-
* @param path - API endpoint path.
|
|
517
|
-
* @param params - Optional query parameters.
|
|
518
|
-
* @param schema - Optional Zod schema for response validation.
|
|
519
|
-
*/
|
|
520
|
-
async delete(path, params, schema) {
|
|
521
|
-
return this.request("DELETE", path, {}, params, schema);
|
|
522
|
-
}
|
|
523
|
-
/**
|
|
524
|
-
* Sends a raw PUT request with a binary/stream body.
|
|
525
|
-
* @param path - API endpoint path.
|
|
526
|
-
* @param body - Binary buffer or readable stream.
|
|
527
|
-
* @param contentType - MIME type of the body.
|
|
528
|
-
* @param headers - Additional request headers.
|
|
529
|
-
* @returns The parsed JSON response with keys converted to camelCase.
|
|
530
|
-
*/
|
|
531
|
-
async putRaw(path, body, contentType, headers = {}) {
|
|
532
|
-
const url = this.buildUrl(path);
|
|
533
|
-
const res = await this.fetchWithTimeout(url, {
|
|
534
|
-
method: "PUT",
|
|
535
|
-
headers: this.buildHeaders({ "Content-Type": contentType, ...headers }),
|
|
536
|
-
body
|
|
537
|
-
});
|
|
538
|
-
if (!res.ok) await this.throwError(res);
|
|
539
|
-
if (res.status === 204) return void 0;
|
|
540
|
-
const json = await res.json();
|
|
541
|
-
return typeof json === "object" && json !== null ? deepSnakeToCamel(json) : json;
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Opens a GET SSE stream, yielding parsed server-sent events.
|
|
545
|
-
* @param path - API endpoint path.
|
|
546
|
-
* @param params - Optional query parameters.
|
|
547
|
-
* @yields SSE event objects with `type`, `data`, and optional `id` fields.
|
|
548
|
-
*/
|
|
549
|
-
async *stream(path, params) {
|
|
550
|
-
const url = this.buildUrl(path, params);
|
|
551
|
-
const res = await this.fetchWithTimeout(url, {
|
|
552
|
-
method: "GET",
|
|
553
|
-
headers: this.buildHeaders({ Accept: "text/event-stream" })
|
|
554
|
-
});
|
|
555
|
-
if (!res.ok) await this.throwError(res);
|
|
556
|
-
yield* this.parseSSEResponse(res);
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* Sends a POST request that returns an SSE stream.
|
|
560
|
-
* @param path - API endpoint path.
|
|
561
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
562
|
-
* @yields SSE event objects with `type`, `data`, and optional `id` fields.
|
|
563
|
-
*/
|
|
564
|
-
async *postStream(path, body) {
|
|
565
|
-
const url = this.buildUrl(path);
|
|
566
|
-
const res = await this.fetchWithTimeout(url, {
|
|
567
|
-
method: "POST",
|
|
568
|
-
headers: this.buildHeaders({ Accept: "text/event-stream" }),
|
|
569
|
-
body: JSON.stringify(body ?? {})
|
|
570
|
-
});
|
|
571
|
-
if (!res.ok) await this.throwError(res);
|
|
572
|
-
yield* this.parseSSEResponse(res);
|
|
573
|
-
}
|
|
574
|
-
/**
|
|
575
|
-
* Sends a POST request and returns the raw Response object.
|
|
576
|
-
* @param path - API endpoint path.
|
|
577
|
-
* @param body - Request payload.
|
|
578
|
-
* @param headers - Additional request headers.
|
|
579
|
-
* @returns The raw fetch Response (caller must handle parsing).
|
|
580
|
-
*/
|
|
581
|
-
async postRaw(path, body, headers = {}) {
|
|
582
|
-
const url = this.buildUrl(path);
|
|
583
|
-
const res = await this.fetchWithTimeout(url, {
|
|
584
|
-
method: "POST",
|
|
585
|
-
headers: new Headers(this.buildHeaders(headers)),
|
|
586
|
-
body: JSON.stringify(body ?? {})
|
|
587
|
-
});
|
|
588
|
-
if (!res.ok) await this.throwError(res);
|
|
589
|
-
return res;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* Sends a POST request with a FormData body (multipart/form-data).
|
|
593
|
-
* Automatically removes the Content-Type header so the browser sets the
|
|
594
|
-
* correct multipart boundary.
|
|
595
|
-
* @param path - API endpoint path.
|
|
596
|
-
* @param formData - FormData payload.
|
|
597
|
-
* @param headers - Additional request headers.
|
|
598
|
-
* @returns The parsed JSON response with keys converted to camelCase.
|
|
599
|
-
*/
|
|
600
|
-
async postFormData(path, formData, headers = {}) {
|
|
601
|
-
const url = this.buildUrl(path);
|
|
602
|
-
const merged = new Headers(this.buildHeaders(headers));
|
|
603
|
-
merged.delete("Content-Type");
|
|
604
|
-
const res = await this.fetchWithTimeout(url, {
|
|
605
|
-
method: "POST",
|
|
606
|
-
headers: merged,
|
|
607
|
-
body: formData
|
|
608
|
-
});
|
|
609
|
-
if (!res.ok) await this.throwError(res);
|
|
610
|
-
const json = await res.json();
|
|
611
|
-
return deepSnakeToCamel(json);
|
|
612
|
-
}
|
|
613
|
-
/**
|
|
614
|
-
* Sends a raw GET request and returns the Response object directly.
|
|
615
|
-
* @param path - API endpoint path.
|
|
616
|
-
* @param params - Optional query parameters.
|
|
617
|
-
* @param headers - Additional request headers.
|
|
618
|
-
* @returns The raw fetch Response (caller must handle parsing).
|
|
619
|
-
*/
|
|
620
|
-
async getRaw(path, params, headers = {}) {
|
|
621
|
-
const url = this.buildUrl(path, params);
|
|
622
|
-
const res = await this.fetchWithTimeout(url, {
|
|
623
|
-
method: "GET",
|
|
624
|
-
headers: this.buildHeaders(headers)
|
|
625
|
-
});
|
|
626
|
-
if (!res.ok) await this.throwError(res);
|
|
627
|
-
return res;
|
|
628
|
-
}
|
|
629
|
-
async *parseSSEResponse(res) {
|
|
630
|
-
if (!res.body) return;
|
|
631
|
-
const reader = res.body.getReader();
|
|
632
|
-
const decoder = new TextDecoder();
|
|
633
|
-
let buffer = "";
|
|
634
|
-
while (true) {
|
|
635
|
-
const { done, value } = await reader.read();
|
|
636
|
-
if (done) break;
|
|
637
|
-
buffer += decoder.decode(value, { stream: true });
|
|
638
|
-
const lines = buffer.split("\n");
|
|
639
|
-
buffer = lines.pop() ?? "";
|
|
640
|
-
let event = {
|
|
641
|
-
type: "message",
|
|
642
|
-
data: null
|
|
643
|
-
};
|
|
644
|
-
for (const rawLine of lines) {
|
|
645
|
-
const line = rawLine.trimEnd();
|
|
646
|
-
if (line.startsWith("id:")) {
|
|
647
|
-
event.id = line.slice(3).trim();
|
|
648
|
-
} else if (line.startsWith("event:")) {
|
|
649
|
-
event.type = line.slice(6).trim();
|
|
650
|
-
} else if (line.startsWith("data:")) {
|
|
651
|
-
const payload = line.slice(5).trim();
|
|
652
|
-
try {
|
|
653
|
-
const parsed = JSON.parse(payload);
|
|
654
|
-
event.data = typeof parsed === "object" && parsed !== null ? deepSnakeToCamel(parsed) : parsed;
|
|
655
|
-
} catch {
|
|
656
|
-
event.data = payload;
|
|
657
|
-
}
|
|
658
|
-
} else if (line === "") {
|
|
659
|
-
if (event.data !== null) yield event;
|
|
660
|
-
event = { type: "message", data: null };
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
async request(method, path, body, params, schema, attempt = 0) {
|
|
666
|
-
const url = this.buildUrl(path, params);
|
|
667
|
-
const requestId = crypto.randomUUID();
|
|
668
|
-
const transformedBody = body !== void 0 && body !== null ? deepCamelToSnake(body) : body;
|
|
669
|
-
const reqInit = {
|
|
670
|
-
method,
|
|
671
|
-
headers: this.buildHeaders({ "X-Request-Id": requestId }),
|
|
672
|
-
...method !== "GET" ? { body: JSON.stringify(transformedBody ?? {}) } : { body: void 0 }
|
|
673
|
-
};
|
|
674
|
-
this.config.logger?.request?.(method, url, reqInit);
|
|
675
|
-
const executeRequest = async () => {
|
|
676
|
-
try {
|
|
677
|
-
return await this.fetchWithTimeout(url, reqInit);
|
|
678
|
-
} catch (error) {
|
|
679
|
-
this.config.logger?.error?.(error);
|
|
680
|
-
throw new NetworkError(error);
|
|
681
|
-
}
|
|
682
|
-
};
|
|
683
|
-
let res;
|
|
684
|
-
try {
|
|
685
|
-
res = this.breaker ? await this.breaker.execute(executeRequest) : await executeRequest();
|
|
686
|
-
} catch (error) {
|
|
687
|
-
if (error instanceof CircuitBreakerOpenError) {
|
|
688
|
-
throw new Error(
|
|
689
|
-
`Circuit breaker is open. Retry after ${Math.ceil(error.retryAfterMs / 1e3)}s.`
|
|
690
|
-
);
|
|
691
|
-
}
|
|
692
|
-
throw error;
|
|
693
|
-
}
|
|
694
|
-
this.config.logger?.response?.(res);
|
|
695
|
-
if (!res.ok) {
|
|
696
|
-
const shouldRetry = [429, 500, 502, 503, 504].includes(res.status) && attempt < this.config.maxRetries;
|
|
697
|
-
if (shouldRetry) {
|
|
698
|
-
const retryAfterValue = res.headers.get("Retry-After");
|
|
699
|
-
const retryAfterSeconds = retryAfterValue ? Number.parseInt(retryAfterValue, 10) : Number.NaN;
|
|
700
|
-
const delay = Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1e3 : calculateDelay(
|
|
701
|
-
attempt,
|
|
702
|
-
"exponential",
|
|
703
|
-
this.config.retryDelay,
|
|
704
|
-
true
|
|
705
|
-
);
|
|
706
|
-
await sleep(delay);
|
|
707
|
-
return this.request(method, path, body, params, schema, attempt + 1);
|
|
708
|
-
}
|
|
709
|
-
await this.throwError(res);
|
|
710
|
-
}
|
|
711
|
-
if (res.status === 204) return void 0;
|
|
712
|
-
const contentType = (res.headers.get("content-type") || "").toLowerCase();
|
|
713
|
-
const payload = contentType.includes("application/json") ? await res.json() : await res.text();
|
|
714
|
-
const transformedPayload = typeof payload === "object" && payload !== null ? deepSnakeToCamel(payload) : payload;
|
|
715
|
-
if (schema) {
|
|
716
|
-
try {
|
|
717
|
-
const parsed = schema.safeParse(transformedPayload);
|
|
718
|
-
if (!parsed.success) {
|
|
719
|
-
this.config.logger?.error?.(parsed.error);
|
|
720
|
-
throw parsed.error;
|
|
721
|
-
}
|
|
722
|
-
return parsed.data;
|
|
723
|
-
} catch (error) {
|
|
724
|
-
if (error instanceof Error && error.message.includes("_zod")) {
|
|
725
|
-
return transformedPayload;
|
|
726
|
-
}
|
|
727
|
-
throw error;
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return transformedPayload;
|
|
731
|
-
}
|
|
732
|
-
parseRateLimit(res) {
|
|
733
|
-
const limit = res.headers.get("X-RateLimit-Limit");
|
|
734
|
-
const remaining = res.headers.get("X-RateLimit-Remaining");
|
|
735
|
-
const reset = res.headers.get("X-RateLimit-Reset");
|
|
736
|
-
if (limit && remaining && reset) {
|
|
737
|
-
return {
|
|
738
|
-
limit: Number.parseInt(limit, 10),
|
|
739
|
-
remaining: Number.parseInt(remaining, 10),
|
|
740
|
-
reset: Number.parseInt(reset, 10)
|
|
741
|
-
};
|
|
742
|
-
}
|
|
743
|
-
return void 0;
|
|
744
|
-
}
|
|
745
|
-
async throwError(res) {
|
|
746
|
-
let body;
|
|
747
|
-
try {
|
|
748
|
-
body = await res.json();
|
|
749
|
-
} catch {
|
|
750
|
-
body = {};
|
|
751
|
-
}
|
|
752
|
-
const retryAfter = res.headers.get("Retry-After") ?? void 0;
|
|
753
|
-
const rateLimit = this.parseRateLimit(res);
|
|
754
|
-
throw parseFrontalError(body, res.status, retryAfter, rateLimit);
|
|
755
|
-
}
|
|
756
|
-
buildUrl(path, params) {
|
|
757
|
-
const base = this.config.baseUrl.replace(/\/$/, "");
|
|
758
|
-
let normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
759
|
-
if (base.endsWith("/v1") && normalizedPath.startsWith("/v1/")) {
|
|
760
|
-
if (this.config.debug) {
|
|
761
|
-
console.warn(
|
|
762
|
-
`[SDK] Double /v1/ prefix detected and normalized. The base URL already includes "/v1" but the route "${normalizedPath}" also starts with "/v1/". Write routes without a leading "/v1".`
|
|
763
|
-
);
|
|
764
|
-
}
|
|
765
|
-
normalizedPath = normalizedPath.slice("/v1".length);
|
|
766
|
-
}
|
|
767
|
-
const url = `${base}${normalizedPath}`;
|
|
768
|
-
const transformedParams = params ? deepCamelToSnake(params) : params;
|
|
769
|
-
if (!transformedParams || Object.keys(transformedParams).length === 0) {
|
|
770
|
-
return url;
|
|
771
|
-
}
|
|
772
|
-
const query = Object.entries(transformedParams).filter(([, value]) => value !== void 0 && value !== null).map(
|
|
773
|
-
([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
|
|
774
|
-
).join("&");
|
|
775
|
-
return query ? `${url}?${query}` : url;
|
|
776
|
-
}
|
|
777
|
-
buildHeaders(extra = {}) {
|
|
778
|
-
return {
|
|
779
|
-
// The opaque API key (`frt_…`) is the sole public credential. The platform
|
|
780
|
-
// edge validates it and exchanges it for a short-lived JWT before reaching
|
|
781
|
-
// any service — the SDK never sees or sends a JWT.
|
|
782
|
-
Authorization: `Bearer ${this.config.apiKey}`,
|
|
783
|
-
"Content-Type": "application/json",
|
|
784
|
-
Accept: "application/json",
|
|
785
|
-
"User-Agent": "@frontal-labs/core",
|
|
786
|
-
"X-Frontal-Core": `typescript@${SDK_VERSION}`,
|
|
787
|
-
"X-Frontal-Environment": this.config.environment,
|
|
788
|
-
...this.config.headers,
|
|
789
|
-
...extra
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
async fetchWithTimeout(url, init) {
|
|
793
|
-
const controller = new AbortController();
|
|
794
|
-
const timer = setTimeout(() => controller.abort(), this.config.timeout);
|
|
795
|
-
try {
|
|
796
|
-
return await (this.config.fetch ?? fetch)(url, {
|
|
797
|
-
...init,
|
|
798
|
-
signal: controller.signal
|
|
799
|
-
});
|
|
800
|
-
} finally {
|
|
801
|
-
clearTimeout(timer);
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
var sleep = async (ms) => new Promise((resolve) => {
|
|
806
|
-
setTimeout(resolve, ms);
|
|
807
|
-
});
|
|
808
|
-
var apiKeySchema = z2.string().min(9, "FRONTAL_API_KEY must be at least 9 characters").max(128, "FRONTAL_API_KEY must be at most 128 characters").refine(
|
|
809
|
-
(val) => /^frt_[A-Za-z0-9_]+$/.test(val) || /^fr_typed[A-Za-z0-9_]+$/.test(val),
|
|
810
|
-
"FRONTAL_API_KEY must start with frt_"
|
|
811
|
-
);
|
|
812
|
-
var debugSchema = z2.union([
|
|
813
|
-
z2.literal("true"),
|
|
814
|
-
z2.literal("false"),
|
|
815
|
-
z2.literal("1"),
|
|
816
|
-
z2.literal("0")
|
|
817
|
-
]).optional().default("false").transform((val) => val === "true" || val === "1");
|
|
818
|
-
var env = createEnv({
|
|
819
|
-
server: {
|
|
820
|
-
FRONTAL_ENV: z2.enum(["development", "test", "production"]).default("development"),
|
|
821
|
-
FRONTAL_API_KEY: apiKeySchema.optional(),
|
|
822
|
-
FRONTAL_API_URL: z2.url("FRONTAL_API_URL must be a valid URL").optional(),
|
|
823
|
-
FRONTAL_DEBUG: debugSchema
|
|
824
|
-
},
|
|
825
|
-
runtimeEnv: {
|
|
826
|
-
FRONTAL_ENV: process.env.FRONTAL_ENV,
|
|
827
|
-
FRONTAL_API_KEY: process.env.FRONTAL_API_KEY,
|
|
828
|
-
FRONTAL_API_URL: process.env.FRONTAL_API_URL,
|
|
829
|
-
FRONTAL_DEBUG: process.env.FRONTAL_DEBUG
|
|
830
|
-
},
|
|
831
|
-
emptyStringAsUndefined: true
|
|
832
|
-
});
|
|
833
|
-
var unwrapClientError = (error) => {
|
|
834
|
-
if (error instanceof NetworkError) {
|
|
835
|
-
if (error.cause instanceof Error) {
|
|
836
|
-
throw error.cause;
|
|
837
|
-
}
|
|
838
|
-
throw new Error(String(error.cause));
|
|
839
|
-
}
|
|
840
|
-
throw error;
|
|
841
|
-
};
|
|
842
|
-
var FrontalClient = class {
|
|
843
|
-
config;
|
|
844
|
-
_http;
|
|
845
|
-
/**
|
|
846
|
-
* @param config - Validated client configuration output from clientConfigSchema.
|
|
847
|
-
*/
|
|
848
|
-
constructor(config) {
|
|
849
|
-
Object.defineProperty(this, "config", {
|
|
850
|
-
value: config,
|
|
851
|
-
writable: false,
|
|
852
|
-
enumerable: true
|
|
853
|
-
});
|
|
854
|
-
const http = new HttpClient(config);
|
|
855
|
-
Object.defineProperty(this, "_http", {
|
|
856
|
-
value: http,
|
|
857
|
-
writable: false,
|
|
858
|
-
enumerable: true
|
|
859
|
-
});
|
|
860
|
-
Object.defineProperty(this, "httpClient", {
|
|
861
|
-
get() {
|
|
862
|
-
return http;
|
|
863
|
-
},
|
|
864
|
-
enumerable: true
|
|
865
|
-
});
|
|
866
|
-
}
|
|
867
|
-
/** Public accessor for the underlying HttpClient. */
|
|
868
|
-
get httpClient() {
|
|
869
|
-
return this._http;
|
|
870
|
-
}
|
|
871
|
-
/**
|
|
872
|
-
* Sends a GET request and optionally validates the response against a schema.
|
|
873
|
-
* @param path - API endpoint path.
|
|
874
|
-
* @param schema - Optional Zod schema for response validation.
|
|
875
|
-
*/
|
|
876
|
-
async get(path, schema) {
|
|
877
|
-
try {
|
|
878
|
-
return await this._http.get(path, void 0, schema);
|
|
879
|
-
} catch (error) {
|
|
880
|
-
throw unwrapClientError(error);
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
/**
|
|
884
|
-
* Sends a POST request with an optional JSON body and response schema.
|
|
885
|
-
* @param path - API endpoint path.
|
|
886
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
887
|
-
* @param schema - Optional Zod schema for response validation.
|
|
888
|
-
*/
|
|
889
|
-
async post(path, body, schema) {
|
|
890
|
-
try {
|
|
891
|
-
return await this._http.post(path, body, schema);
|
|
892
|
-
} catch (error) {
|
|
893
|
-
throw unwrapClientError(error);
|
|
894
|
-
}
|
|
895
|
-
}
|
|
896
|
-
/**
|
|
897
|
-
* Sends a PUT request with an optional JSON body and response schema.
|
|
898
|
-
* @param path - API endpoint path.
|
|
899
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
900
|
-
* @param schema - Optional Zod schema for response validation.
|
|
901
|
-
*/
|
|
902
|
-
async put(path, body, schema) {
|
|
903
|
-
try {
|
|
904
|
-
return await this._http.put(path, body, schema);
|
|
905
|
-
} catch (error) {
|
|
906
|
-
throw unwrapClientError(error);
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
/**
|
|
910
|
-
* Sends a PATCH request with an optional JSON body and response schema.
|
|
911
|
-
* @param path - API endpoint path.
|
|
912
|
-
* @param body - Request payload (converted to snake_case automatically).
|
|
913
|
-
* @param schema - Optional Zod schema for response validation.
|
|
914
|
-
*/
|
|
915
|
-
async patch(path, body, schema) {
|
|
916
|
-
try {
|
|
917
|
-
return await this._http.patch(path, body, schema);
|
|
918
|
-
} catch (error) {
|
|
919
|
-
throw unwrapClientError(error);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
/**
|
|
923
|
-
* Sends a DELETE request with optional query parameters and response schema.
|
|
924
|
-
* @param path - API endpoint path.
|
|
925
|
-
* @param params - Query parameters (converted to snake_case automatically).
|
|
926
|
-
* @param schema - Optional Zod schema for response validation.
|
|
927
|
-
*/
|
|
928
|
-
async delete(path, params, schema) {
|
|
929
|
-
try {
|
|
930
|
-
return await this._http.delete(path, params, schema);
|
|
931
|
-
} catch (error) {
|
|
932
|
-
throw unwrapClientError(error);
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
/**
|
|
936
|
-
* Opens a GET SSE stream and yields parsed server-sent events.
|
|
937
|
-
* @param path - API endpoint path.
|
|
938
|
-
* @param params - Optional query parameters.
|
|
939
|
-
* @yields Objects with `type`, `data`, and optional `id` fields from SSE events.
|
|
940
|
-
*/
|
|
941
|
-
async *stream(path, params) {
|
|
942
|
-
try {
|
|
943
|
-
yield* this._http.stream(path, params);
|
|
944
|
-
} catch (error) {
|
|
945
|
-
throw unwrapClientError(error);
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
/**
|
|
949
|
-
* Sends a raw PUT request with a binary/stream body and custom content type.
|
|
950
|
-
* @param path - API endpoint path.
|
|
951
|
-
* @param body - Binary buffer or readable stream to upload.
|
|
952
|
-
* @param contentType - MIME type of the body.
|
|
953
|
-
* @param headers - Additional request headers.
|
|
954
|
-
* @returns The parsed JSON response (keys converted to camelCase).
|
|
955
|
-
*/
|
|
956
|
-
async putRaw(path, body, contentType, headers = {}) {
|
|
957
|
-
try {
|
|
958
|
-
return await this._http.putRaw(path, body, contentType, headers);
|
|
959
|
-
} catch (error) {
|
|
960
|
-
throw unwrapClientError(error);
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
};
|
|
964
|
-
var getDefaultClient = () => {
|
|
965
|
-
if (!env.FRONTAL_API_KEY) {
|
|
966
|
-
throw new Error(
|
|
967
|
-
"FRONTAL_API_KEY environment variable is required. Set it in your environment or pass apiKey explicitly to new FrontalClient()."
|
|
968
|
-
);
|
|
969
|
-
}
|
|
970
|
-
return new FrontalClient({
|
|
971
|
-
apiKey: env.FRONTAL_API_KEY,
|
|
972
|
-
baseUrl: env.FRONTAL_API_URL ?? DEFAULT_BASE_URL,
|
|
973
|
-
timeout: 3e4,
|
|
974
|
-
maxRetries: 3,
|
|
975
|
-
retryDelay: 1e3,
|
|
976
|
-
headers: {},
|
|
977
|
-
environment: env.FRONTAL_ENV,
|
|
978
|
-
debug: env.FRONTAL_DEBUG
|
|
979
|
-
});
|
|
980
|
-
};
|
|
981
|
-
var API_KEY_PATTERN = new RegExp(`^${API_KEY_PREFIX}[A-Za-z0-9_-]+$`);
|
|
982
|
-
var loggerFnSchema = z3.custom(
|
|
983
|
-
(value) => typeof value === "function",
|
|
984
|
-
"Expected function"
|
|
985
|
-
);
|
|
986
|
-
var headersSchema = z3.record(z3.string(), z3.string()).superRefine((headers, ctx) => {
|
|
987
|
-
for (const key of Object.keys(headers)) {
|
|
988
|
-
if (key.trim().length === 0) {
|
|
989
|
-
ctx.addIssue({
|
|
990
|
-
code: z3.ZodIssueCode.custom,
|
|
991
|
-
message: "Header names must be non-empty",
|
|
992
|
-
path: []
|
|
993
|
-
});
|
|
994
|
-
return;
|
|
995
|
-
}
|
|
996
|
-
}
|
|
997
|
-
}).default({});
|
|
998
|
-
var clientConfigSchema = z3.object({
|
|
999
|
-
apiKey: z3.string().min(9, "apiKey is required").regex(API_KEY_PATTERN, `apiKey must start with "${API_KEY_PREFIX}"`),
|
|
1000
|
-
baseUrl: z3.string().url().refine(
|
|
1001
|
-
(value) => value.startsWith("https://") || value.startsWith("http://"),
|
|
1002
|
-
{
|
|
1003
|
-
message: "baseUrl must use http or https"
|
|
1004
|
-
}
|
|
1005
|
-
).default(DEFAULT_BASE_URL),
|
|
1006
|
-
timeout: z3.number().int().positive().default(3e4),
|
|
1007
|
-
maxRetries: z3.number().int().min(0).max(10).default(3),
|
|
1008
|
-
retryDelay: z3.number().int().positive().default(1e3),
|
|
1009
|
-
headers: headersSchema,
|
|
1010
|
-
environment: z3.string().default("production"),
|
|
1011
|
-
debug: z3.boolean().default(false),
|
|
1012
|
-
fetch: z3.custom((value) => typeof value === "function").optional(),
|
|
1013
|
-
logger: z3.object({
|
|
1014
|
-
request: loggerFnSchema.optional(),
|
|
1015
|
-
response: loggerFnSchema.optional(),
|
|
1016
|
-
error: loggerFnSchema.optional()
|
|
1017
|
-
}).optional(),
|
|
1018
|
-
circuitBreaker: z3.object({
|
|
1019
|
-
failureThreshold: z3.number().int().positive().default(5),
|
|
1020
|
-
resetTimeoutMs: z3.number().int().positive().default(3e4)
|
|
1021
|
-
}).optional()
|
|
1022
|
-
}).strict();
|
|
1023
|
-
function asPagePayload(raw) {
|
|
1024
|
-
return raw;
|
|
1025
|
-
}
|
|
1026
|
-
var paginationSchema = z4.object({
|
|
1027
|
-
cursor: z4.string().min(1),
|
|
1028
|
-
hasMore: z4.boolean(),
|
|
1029
|
-
total: z4.number().int().min(0).optional(),
|
|
1030
|
-
limit: z4.number().int().positive().optional(),
|
|
1031
|
-
offset: z4.number().int().min(0).optional()
|
|
1032
|
-
}).strict();
|
|
1033
|
-
function buildPageResult(data2, pagination, fetchNext, meta) {
|
|
1034
|
-
let nextPagePromise = null;
|
|
1035
|
-
const page = {
|
|
1036
|
-
data: data2,
|
|
1037
|
-
meta,
|
|
1038
|
-
pagination,
|
|
1039
|
-
_fetchNextPage: fetchNext,
|
|
1040
|
-
async nextPage() {
|
|
1041
|
-
if (!this.pagination.hasMore) return null;
|
|
1042
|
-
if (!nextPagePromise) {
|
|
1043
|
-
nextPagePromise = (async () => {
|
|
1044
|
-
let result = await this._fetchNextPage();
|
|
1045
|
-
if (!result && this._fallbackFetchNextPage) {
|
|
1046
|
-
result = await this._fallbackFetchNextPage();
|
|
1047
|
-
}
|
|
1048
|
-
if (result) {
|
|
1049
|
-
const mutableResult = result;
|
|
1050
|
-
mutableResult._fallbackFetchNextPage = this._fallbackFetchNextPage ?? this._fetchNextPage;
|
|
1051
|
-
}
|
|
1052
|
-
return result;
|
|
1053
|
-
})().finally(() => {
|
|
1054
|
-
nextPagePromise = null;
|
|
1055
|
-
});
|
|
1056
|
-
}
|
|
1057
|
-
return nextPagePromise;
|
|
1058
|
-
},
|
|
1059
|
-
async all() {
|
|
1060
|
-
const items = [...this.data];
|
|
1061
|
-
let current = this;
|
|
1062
|
-
while (current) {
|
|
1063
|
-
if (!current.pagination.hasMore) break;
|
|
1064
|
-
current = await current.nextPage();
|
|
1065
|
-
if (!current) break;
|
|
1066
|
-
items.push(...current.data);
|
|
1067
|
-
}
|
|
1068
|
-
return items;
|
|
1069
|
-
},
|
|
1070
|
-
[Symbol.asyncIterator]() {
|
|
1071
|
-
let current = this;
|
|
1072
|
-
let index = 0;
|
|
1073
|
-
return {
|
|
1074
|
-
async next() {
|
|
1075
|
-
while (current) {
|
|
1076
|
-
if (index < current.data.length) {
|
|
1077
|
-
return { done: false, value: current.data[index++] };
|
|
1078
|
-
}
|
|
1079
|
-
if (!current.pagination.hasMore) {
|
|
1080
|
-
current = null;
|
|
1081
|
-
break;
|
|
1082
|
-
}
|
|
1083
|
-
current = await current.nextPage();
|
|
1084
|
-
index = 0;
|
|
1085
|
-
}
|
|
1086
|
-
return { done: true, value: void 0 };
|
|
1087
|
-
}
|
|
1088
|
-
};
|
|
1089
|
-
}
|
|
1090
|
-
};
|
|
1091
|
-
return page;
|
|
1092
|
-
}
|
|
1093
|
-
function createPageResult(dataOrRaw, paginationOrFetchNext, fetchNextOrMeta, meta) {
|
|
1094
|
-
if (Array.isArray(dataOrRaw)) {
|
|
1095
|
-
const data2 = dataOrRaw;
|
|
1096
|
-
const pagination = paginationOrFetchNext;
|
|
1097
|
-
const fetchNextPage2 = fetchNextOrMeta;
|
|
1098
|
-
const fetchNext2 = async () => {
|
|
1099
|
-
if (!fetchNextPage2) return null;
|
|
1100
|
-
return fetchNextPage2.length > 0 ? fetchNextPage2(
|
|
1101
|
-
pagination.cursor
|
|
1102
|
-
) : fetchNextPage2();
|
|
1103
|
-
};
|
|
1104
|
-
return buildPageResult(data2, pagination, fetchNext2, meta);
|
|
1105
|
-
}
|
|
1106
|
-
const raw = dataOrRaw;
|
|
1107
|
-
const fetchNextPage = paginationOrFetchNext;
|
|
1108
|
-
const fetchNext = async () => {
|
|
1109
|
-
if (!fetchNextPage) return null;
|
|
1110
|
-
return fetchNextPage.length > 0 ? fetchNextPage(
|
|
1111
|
-
raw.pagination.cursor
|
|
1112
|
-
) : fetchNextPage();
|
|
1113
|
-
};
|
|
1114
|
-
return buildPageResult(
|
|
1115
|
-
Array.isArray(raw.data) ? raw.data : [],
|
|
1116
|
-
raw.pagination,
|
|
1117
|
-
fetchNext,
|
|
1118
|
-
raw.meta
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import {
|
|
3
|
+
FrontalClient,
|
|
4
|
+
getDefaultClient,
|
|
5
|
+
HttpClient
|
|
6
|
+
} from "@frontal-labs/core";
|
|
1121
7
|
|
|
1122
8
|
// src/constants.ts
|
|
1123
9
|
var DEFAULT_DATA_BASE_URL = "https://api.frontal.dev/v1";
|
|
@@ -1127,6 +13,10 @@ var DEFAULT_MAX_RETRIES = 3;
|
|
|
1127
13
|
var DEFAULT_RETRY_DELAY = 1e3;
|
|
1128
14
|
|
|
1129
15
|
// src/sdk.ts
|
|
16
|
+
import {
|
|
17
|
+
asPagePayload,
|
|
18
|
+
createPageResult
|
|
19
|
+
} from "@frontal-labs/core";
|
|
1130
20
|
var DataSdk = class {
|
|
1131
21
|
/** Aggregation management subdomain. */
|
|
1132
22
|
aggregations;
|
|
@@ -1524,6 +414,7 @@ var SchemasNamespace = class extends SubdomainBase {
|
|
|
1524
414
|
};
|
|
1525
415
|
|
|
1526
416
|
// src/client.ts
|
|
417
|
+
import { env } from "@frontal-labs/core";
|
|
1527
418
|
function createDataClient(clientOrConfig) {
|
|
1528
419
|
if (clientOrConfig instanceof FrontalClient) {
|
|
1529
420
|
return new DataSdk(clientOrConfig.httpClient);
|