calmlens 0.4.0 → 0.5.0
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/README.md +61 -39
- package/bin/calmlens.js +217 -80
- package/cjs/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/cjs/{CalmLensUtils-CjdO9v--.js → CalmLensUtils-0QaxbI3A.js} +95 -93
- package/cjs/index.d.ts +2602 -24
- package/cjs/index.js +533 -124
- package/cjs/testing.d.ts +2 -2
- package/cjs/testing.js +6 -27
- package/esm/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/esm/{CalmLensUtils-B3Eiz2Ro.js → CalmLensUtils-BQEgxGWk.js} +68 -88
- package/esm/index.d.ts +2602 -24
- package/esm/index.js +526 -124
- package/esm/testing.d.ts +2 -2
- package/esm/testing.js +5 -4
- package/package.json +2 -2
- package/cjs/CalmLensTypes-DkqoKBwF.d.ts +0 -1761
- package/esm/CalmLensTypes-DkqoKBwF.d.ts +0 -1761
package/bin/calmlens.js
CHANGED
|
@@ -107,7 +107,7 @@ const PUBLIC_ERROR_CODES = {
|
|
|
107
107
|
}),
|
|
108
108
|
FILE_TOO_LARGE: new sendable_error.ErrorCode({
|
|
109
109
|
id: "upload/file-too-large",
|
|
110
|
-
defaultMessage: "File size exceeds limit. Maximum
|
|
110
|
+
defaultMessage: "File size exceeds limit. Maximum direct image size is 10MB, audio/video size is 50MiB, and other files is 5GB.",
|
|
111
111
|
status: 400
|
|
112
112
|
}),
|
|
113
113
|
IMAGE_REQUIRES_MULTIPART_UPLOAD: new sendable_error.ErrorCode({
|
|
@@ -237,6 +237,8 @@ const PUBLIC_ERROR_CODES = {
|
|
|
237
237
|
})
|
|
238
238
|
};
|
|
239
239
|
PUBLIC_ERROR_CODES.MISSING_TOKEN, PUBLIC_ERROR_CODES.INVALID_API_KEY, PUBLIC_ERROR_CODES.API_KEY_PROJECT_MISMATCH;
|
|
240
|
+
const MAX_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 20971520)();
|
|
241
|
+
const MIN_MULTIPART_IMAGE_UPLOAD_BYTES = /* @__PURE__ */ (() => 10485760)();
|
|
240
242
|
const REJECTED_UPLOAD_MIME_TYPE_SET = /* @__PURE__ */ new Set([
|
|
241
243
|
"application/octet-stream",
|
|
242
244
|
"multipart/form-data",
|
|
@@ -259,18 +261,18 @@ var CalmLensError = class extends Error {
|
|
|
259
261
|
constructor(errorCode, options) {
|
|
260
262
|
const code = "getId" in errorCode ? errorCode.getId() : errorCode.id;
|
|
261
263
|
const defaultMessage = "getDefaultMessage" in errorCode ? errorCode.getDefaultMessage() : errorCode.defaultMessage;
|
|
262
|
-
super(`[calmlens] ${options?.message ?? defaultMessage ?? code}
|
|
264
|
+
super(`[calmlens] ${options?.message ?? defaultMessage ?? code}`, { cause: options?.cause });
|
|
263
265
|
this.name = "CalmLensError";
|
|
264
266
|
this.code = code;
|
|
265
267
|
this.details = options?.details;
|
|
268
|
+
this.status = options?.status;
|
|
266
269
|
}
|
|
267
270
|
};
|
|
268
271
|
const calmLensError = (errorCode, options) => new CalmLensError(errorCode, options);
|
|
269
272
|
//#endregion
|
|
270
273
|
//#region src/client/CalmLensUtils.ts
|
|
271
|
-
/** Converts `text.moderate()` options into a plain-text asset submission. */
|
|
272
274
|
const toTextAssetOptions = ({ text, name, ...options }) => {
|
|
273
|
-
if (typeof text !== "string" || text.trim()
|
|
275
|
+
if (typeof text !== "string" || !text.trim()) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
|
|
274
276
|
return {
|
|
275
277
|
...options,
|
|
276
278
|
name: name ?? "text",
|
|
@@ -280,19 +282,72 @@ const toTextAssetOptions = ({ text, name, ...options }) => {
|
|
|
280
282
|
}
|
|
281
283
|
};
|
|
282
284
|
};
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region src/client/CalmLensWebhooks.ts
|
|
287
|
+
const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
|
|
288
|
+
const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
|
|
289
|
+
const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
|
|
290
|
+
/** The JSON body of a webhook delivery for a stored event. */
|
|
291
|
+
const toWebhookEventPayload = (event) => ({
|
|
292
|
+
id: event.id,
|
|
293
|
+
type: event.type,
|
|
294
|
+
createdAt: event.createdAt,
|
|
295
|
+
projectId: event.projectId,
|
|
296
|
+
data: {
|
|
297
|
+
severity: event.severity,
|
|
298
|
+
title: event.title,
|
|
299
|
+
description: event.description ?? null,
|
|
300
|
+
assetId: event.assetId ?? null,
|
|
301
|
+
asset: event.asset ?? null,
|
|
302
|
+
facts: event.facts
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
const encoder = new TextEncoder();
|
|
306
|
+
const hmacSha256Hex = async (secret, message) => {
|
|
286
307
|
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
287
308
|
name: "HMAC",
|
|
288
309
|
hash: "SHA-256"
|
|
289
310
|
}, false, ["sign"]);
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
311
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
|
|
312
|
+
return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
313
|
+
};
|
|
314
|
+
/** Constant-time comparison of two strings of the same length. */
|
|
315
|
+
const timingSafeEqual = (a, b) => {
|
|
316
|
+
if (a.length !== b.length) return false;
|
|
293
317
|
let diff = 0;
|
|
294
|
-
for (let i = 0; i <
|
|
318
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
295
319
|
return diff === 0;
|
|
320
|
+
};
|
|
321
|
+
/** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
|
|
322
|
+
const createWebhookSignatureHeader = async (secret, timestamp, body) => `v1=${await hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
|
|
323
|
+
/** Headers for one signed delivery of `body`. */
|
|
324
|
+
const createWebhookHeaders = async (options) => {
|
|
325
|
+
const timestamp = options.timestampSeconds ?? Math.floor(Date.now() / 1e3);
|
|
326
|
+
return {
|
|
327
|
+
"content-type": "application/json",
|
|
328
|
+
[WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
|
|
329
|
+
[WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
|
|
330
|
+
[WEBHOOK_SIGNATURE_HEADER]: await createWebhookSignatureHeader(options.secret, timestamp, options.body)
|
|
331
|
+
};
|
|
332
|
+
};
|
|
333
|
+
/**
|
|
334
|
+
* Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
|
|
335
|
+
* `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
|
|
336
|
+
* (default 300) of now. Returns `false` for anything missing or malformed.
|
|
337
|
+
*/
|
|
338
|
+
async function verifyWebhookSignature({ payload, signature, timestamp, secret, toleranceSeconds = 300, now }) {
|
|
339
|
+
if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
|
|
340
|
+
const timestampText = String(timestamp).trim();
|
|
341
|
+
if (!/^\d+$/.test(timestampText)) return false;
|
|
342
|
+
const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
|
|
343
|
+
if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
|
|
344
|
+
const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
|
|
345
|
+
if (candidates.length === 0) return false;
|
|
346
|
+
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
347
|
+
const expected = await hmacSha256Hex(secret, `${timestampText}.${body}`);
|
|
348
|
+
let matched = false;
|
|
349
|
+
for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
|
|
350
|
+
return matched;
|
|
296
351
|
}
|
|
297
352
|
//#endregion
|
|
298
353
|
//#region src/client/CalmLensClient.ts
|
|
@@ -347,7 +402,7 @@ const normalizeAssetOptionsForRequest = (options) => {
|
|
|
347
402
|
const toRawUploadBody = (payload) => {
|
|
348
403
|
const data = assetToData(normalizePayloadForRequest(payload));
|
|
349
404
|
if (data instanceof Response) {
|
|
350
|
-
if (!data.body) throw
|
|
405
|
+
if (!data.body) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Response upload data must have a body" });
|
|
351
406
|
return data.body;
|
|
352
407
|
}
|
|
353
408
|
if (data instanceof ArrayBuffer || data instanceof Blob) return data;
|
|
@@ -365,8 +420,8 @@ const assertValidUploadMimeType = (mimeType) => {
|
|
|
365
420
|
};
|
|
366
421
|
const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
|
|
367
422
|
const prepareSubmitAssetOptions = (options) => {
|
|
368
|
-
if (!("content" in options) && !("url" in options) && !("part" in options)) throw
|
|
369
|
-
if (!options.name) throw
|
|
423
|
+
if (!("content" in options) && !("url" in options) && !("part" in options)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Either file content, URL, or multipart part is required" });
|
|
424
|
+
if (!options.name) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset name is required" });
|
|
370
425
|
if (!("part" in options) && "isFinal" in options) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
|
|
371
426
|
if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw calmLensError(PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
|
|
372
427
|
if ("content" in options) {
|
|
@@ -380,8 +435,8 @@ const prepareSubmitAssetOptions = (options) => {
|
|
|
380
435
|
assertValidUploadMimeType(options.part.type);
|
|
381
436
|
const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
|
|
382
437
|
if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
|
|
383
|
-
if (partSizeInBytes >
|
|
384
|
-
if (options.part.isFinal && partSizeInBytes <
|
|
438
|
+
if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
439
|
+
if (options.part.isFinal && partSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
385
440
|
}
|
|
386
441
|
const validation = validateAssetPayload(options.part, {
|
|
387
442
|
multipart: true,
|
|
@@ -392,7 +447,7 @@ const prepareSubmitAssetOptions = (options) => {
|
|
|
392
447
|
return options;
|
|
393
448
|
};
|
|
394
449
|
const appendCdnSelector = (url, options) => {
|
|
395
|
-
if (options.lens && options.transform) throw
|
|
450
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
396
451
|
if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
|
|
397
452
|
if (!options.transform) return url;
|
|
398
453
|
return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
|
|
@@ -411,9 +466,34 @@ const withApiKeyHeader = (init, apiKey) => {
|
|
|
411
466
|
headers.set("X-Api-Key", apiKey);
|
|
412
467
|
return {
|
|
413
468
|
...init,
|
|
469
|
+
redirect: "error",
|
|
414
470
|
headers: Object.fromEntries(headers.entries())
|
|
415
471
|
};
|
|
416
472
|
};
|
|
473
|
+
const requestSignal = (options, signal) => {
|
|
474
|
+
const signals = [
|
|
475
|
+
options.signal,
|
|
476
|
+
signal,
|
|
477
|
+
AbortSignal.timeout(options.timeoutMs ?? 12e4)
|
|
478
|
+
].filter((value) => value != null);
|
|
479
|
+
return AbortSignal.any(signals);
|
|
480
|
+
};
|
|
481
|
+
const safeFetch = (fetchImpl, options) => (async (input, init) => {
|
|
482
|
+
const signal = requestSignal(options, init?.signal ?? (input instanceof Request ? input.signal : void 0));
|
|
483
|
+
try {
|
|
484
|
+
signal.throwIfAborted();
|
|
485
|
+
return await fetchImpl(input, {
|
|
486
|
+
...init,
|
|
487
|
+
redirect: "error",
|
|
488
|
+
signal
|
|
489
|
+
});
|
|
490
|
+
} catch (cause) {
|
|
491
|
+
throw calmLensError({ id: signal.aborted ? signal.reason?.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : "sdk/transport-error" }, {
|
|
492
|
+
message: signal.aborted ? "Request aborted" : "Request failed",
|
|
493
|
+
cause
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
});
|
|
417
497
|
const createApi = (options) => {
|
|
418
498
|
return new api_def.Api({
|
|
419
499
|
name: "Calm Lens",
|
|
@@ -427,13 +507,24 @@ const createApi = (options) => {
|
|
|
427
507
|
if (context.error) throw normalizeApiError(context.error);
|
|
428
508
|
} }
|
|
429
509
|
],
|
|
430
|
-
requestBackend: options.requestBackend
|
|
510
|
+
requestBackend: options.requestBackend ? Object.assign(Object.create(options.requestBackend), "fetch" in options.requestBackend && typeof options.requestBackend.fetch === "function" ? { fetch: safeFetch(options.requestBackend.fetch, options) } : {}) : new api_def.FetchRequestBackend(safeFetch(globalThis.fetch, options))
|
|
431
511
|
});
|
|
432
512
|
};
|
|
433
513
|
const isApiErrorPayload = (value) => {
|
|
434
514
|
return !!value && typeof value === "object" && typeof value.code === "string";
|
|
435
515
|
};
|
|
436
516
|
const normalizeApiError = (error) => {
|
|
517
|
+
let cause = error;
|
|
518
|
+
const seen = /* @__PURE__ */ new Set();
|
|
519
|
+
while (cause instanceof Error && !seen.has(cause)) {
|
|
520
|
+
seen.add(cause);
|
|
521
|
+
if (cause instanceof CalmLensError) return cause;
|
|
522
|
+
if (cause.name === "AbortError" || cause.name === "TimeoutError") return calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
|
|
523
|
+
message: "Request aborted",
|
|
524
|
+
cause
|
|
525
|
+
});
|
|
526
|
+
cause = cause.cause;
|
|
527
|
+
}
|
|
437
528
|
const response = error instanceof Error ? (0, api_def.getErrorResponse)(error) : void 0;
|
|
438
529
|
if (error instanceof Error && (0, api_def.isRequestError)(error) && isApiErrorPayload(response?.data)) {
|
|
439
530
|
const { code, message, details, traceId } = response.data;
|
|
@@ -442,6 +533,8 @@ const normalizeApiError = (error) => {
|
|
|
442
533
|
defaultMessage: message
|
|
443
534
|
}, {
|
|
444
535
|
message,
|
|
536
|
+
status: response?.status,
|
|
537
|
+
cause: error,
|
|
445
538
|
details: {
|
|
446
539
|
...details,
|
|
447
540
|
traceId,
|
|
@@ -449,7 +542,12 @@ const normalizeApiError = (error) => {
|
|
|
449
542
|
}
|
|
450
543
|
});
|
|
451
544
|
}
|
|
452
|
-
return error;
|
|
545
|
+
if (error instanceof CalmLensError) return error;
|
|
546
|
+
return calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
|
|
547
|
+
message: response ? `HTTP ${response.status}` : error.message,
|
|
548
|
+
status: response?.status,
|
|
549
|
+
cause: error
|
|
550
|
+
});
|
|
453
551
|
};
|
|
454
552
|
const createEndpoints = (api) => {
|
|
455
553
|
const getFolders = api.endpoint().paramsOf().responseOf().build({
|
|
@@ -561,29 +659,35 @@ const createEndpoints = (api) => {
|
|
|
561
659
|
getEvents
|
|
562
660
|
};
|
|
563
661
|
};
|
|
564
|
-
var CalmLensClient = class {
|
|
662
|
+
var CalmLensClient = class CalmLensClient {
|
|
565
663
|
/**
|
|
566
|
-
*
|
|
664
|
+
* Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
|
|
665
|
+
* `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
|
|
666
|
+
* more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
|
|
567
667
|
*
|
|
568
|
-
* @param payload - The
|
|
569
|
-
* @param
|
|
570
|
-
* @param
|
|
571
|
-
* @
|
|
668
|
+
* @param options.payload - The raw request body, exactly as received (verify before parsing)
|
|
669
|
+
* @param options.signature - The 'x-calmlens-signature' header value
|
|
670
|
+
* @param options.timestamp - The 'x-calmlens-timestamp' header value
|
|
671
|
+
* @param options.secret - The connector's signing secret
|
|
672
|
+
* @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
|
|
673
|
+
* @param options.now - Override the current time (Date or epoch milliseconds), for tests
|
|
674
|
+
* @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
|
|
572
675
|
*
|
|
573
676
|
* @example
|
|
574
677
|
* ```javascript
|
|
575
|
-
* // In your webhook handler
|
|
576
|
-
* const
|
|
577
|
-
* const payload = req.body;
|
|
678
|
+
* // In your webhook handler (e.g. a Fetch API Request)
|
|
679
|
+
* const payload = await request.text();
|
|
578
680
|
* const isValid = await CalmLensClient.verifyWebhookSignature({
|
|
579
681
|
* payload,
|
|
580
|
-
*
|
|
682
|
+
* signature: request.headers.get('x-calmlens-signature'),
|
|
683
|
+
* timestamp: request.headers.get('x-calmlens-timestamp'),
|
|
581
684
|
* secret: WEBHOOK_SECRET,
|
|
582
685
|
* });
|
|
583
686
|
*
|
|
584
687
|
* if (!isValid) {
|
|
585
|
-
* return
|
|
688
|
+
* return new Response('Unauthorized', { status: 401 });
|
|
586
689
|
* }
|
|
690
|
+
* const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
|
|
587
691
|
* ```
|
|
588
692
|
*/
|
|
589
693
|
static async verifyWebhookSignature(options) {
|
|
@@ -595,18 +699,30 @@ var CalmLensClient = class {
|
|
|
595
699
|
this.pendingEnsureLenses = /* @__PURE__ */ new Map();
|
|
596
700
|
this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
|
|
597
701
|
this.multipartUploadQueues = /* @__PURE__ */ new Map();
|
|
598
|
-
if (!options.apiKey) throw
|
|
599
|
-
if (!options.projectId) throw
|
|
702
|
+
if (!options.apiKey) throw calmLensError({ id: "upload/invalid-payload" }, { message: "API key is required" });
|
|
703
|
+
if (!options.projectId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Project ID is required" });
|
|
704
|
+
if (options.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "timeoutMs must be a positive integer" });
|
|
705
|
+
this.options = { ...options };
|
|
600
706
|
this.options.baseUrl = this.options.baseUrl ?? `https://api.calmlens.com/v1`;
|
|
601
707
|
this.options.cdnBaseUrl = this.options.cdnBaseUrl ?? `https://cdn.calmlens.com/v1`;
|
|
602
708
|
this.api = createApi(this.options);
|
|
603
709
|
this.endpoints = createEndpoints(this.api);
|
|
604
710
|
}
|
|
711
|
+
/** Scope cancellation/timeout to an operation without changing this client's defaults. */
|
|
712
|
+
withRequestOptions(options) {
|
|
713
|
+
const client = new CalmLensClient({
|
|
714
|
+
...this.options,
|
|
715
|
+
...options
|
|
716
|
+
});
|
|
717
|
+
client.multipartUploadQueues = this.multipartUploadQueues;
|
|
718
|
+
client.multipartImageUploadSizes = this.multipartImageUploadSizes;
|
|
719
|
+
return client;
|
|
720
|
+
}
|
|
605
721
|
getUploadFetch() {
|
|
606
722
|
const requestBackendFetch = this.options.requestBackend?.fetch;
|
|
607
723
|
const fetchImpl = this.options.uploadFetch ?? requestBackendFetch ?? globalThis.fetch;
|
|
608
724
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
609
|
-
return fetchImpl;
|
|
725
|
+
return safeFetch(fetchImpl, this.options);
|
|
610
726
|
}
|
|
611
727
|
async submitRawAssetUpload(options, queue) {
|
|
612
728
|
const query = new URLSearchParams();
|
|
@@ -676,21 +792,44 @@ var CalmLensClient = class {
|
|
|
676
792
|
return asset;
|
|
677
793
|
}
|
|
678
794
|
async parseRawUploadResponse(response) {
|
|
679
|
-
|
|
795
|
+
let data;
|
|
796
|
+
try {
|
|
797
|
+
data = await response.json();
|
|
798
|
+
} catch (cause) {
|
|
799
|
+
throw calmLensError({ id: cause instanceof Error && ["TimeoutError", "AbortError"].includes(cause.name) ? cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : response.ok ? "sdk/invalid-response" : "sdk/http-error" }, {
|
|
800
|
+
message: `Invalid JSON response (HTTP ${response.status})`,
|
|
801
|
+
status: response.status,
|
|
802
|
+
cause
|
|
803
|
+
});
|
|
804
|
+
}
|
|
680
805
|
if (!response.ok) {
|
|
681
806
|
if (isApiErrorPayload(data)) throw calmLensError({
|
|
682
807
|
id: data.code,
|
|
683
808
|
defaultMessage: data.message
|
|
684
809
|
}, {
|
|
685
810
|
message: data.message,
|
|
811
|
+
status: response.status,
|
|
686
812
|
details: {
|
|
687
813
|
...data.details,
|
|
688
814
|
traceId: data.traceId,
|
|
689
815
|
network: true
|
|
690
816
|
}
|
|
691
817
|
});
|
|
692
|
-
throw
|
|
818
|
+
throw calmLensError({ id: "sdk/http-error" }, {
|
|
819
|
+
message: `HTTP ${response.status}`,
|
|
820
|
+
status: response.status
|
|
821
|
+
});
|
|
693
822
|
}
|
|
823
|
+
if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !data.id || !("status" in data) || ![
|
|
824
|
+
"uploading",
|
|
825
|
+
"pending",
|
|
826
|
+
"approved",
|
|
827
|
+
"rejected",
|
|
828
|
+
"error"
|
|
829
|
+
].includes(String(data.status))) throw calmLensError({ id: "sdk/invalid-response" }, {
|
|
830
|
+
message: "Expected an asset response",
|
|
831
|
+
status: response.status
|
|
832
|
+
});
|
|
694
833
|
return data;
|
|
695
834
|
}
|
|
696
835
|
get cdn() {
|
|
@@ -700,7 +839,7 @@ var CalmLensClient = class {
|
|
|
700
839
|
* Private assets require an authenticated request or signed URL.
|
|
701
840
|
*/
|
|
702
841
|
getAssetUrl: ({ assetIdentifier, ...options }) => {
|
|
703
|
-
if (!assetIdentifier) throw
|
|
842
|
+
if (!assetIdentifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
|
|
704
843
|
const resource = options.resource ?? "content";
|
|
705
844
|
const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
|
|
706
845
|
return appendCdnSelector(url, options);
|
|
@@ -712,7 +851,7 @@ var CalmLensClient = class {
|
|
|
712
851
|
serve: async ({ assetIdentifier, init, ...urlOptions }) => {
|
|
713
852
|
const fetchImpl = this.options.cdnFetch ?? globalThis.fetch;
|
|
714
853
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
715
|
-
return fetchImpl(this.cdn.getAssetUrl({
|
|
854
|
+
return safeFetch(fetchImpl, this.options)(this.cdn.getAssetUrl({
|
|
716
855
|
assetIdentifier,
|
|
717
856
|
...urlOptions
|
|
718
857
|
}), withApiKeyHeader(init, this.options.apiKey));
|
|
@@ -720,13 +859,7 @@ var CalmLensClient = class {
|
|
|
720
859
|
};
|
|
721
860
|
}
|
|
722
861
|
get text() {
|
|
723
|
-
return {
|
|
724
|
-
/**
|
|
725
|
-
* Moderate a short piece of text, such as a comment, caption or bio, and wait for the
|
|
726
|
-
* decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
|
|
727
|
-
* The text is not retained after classification unless `processingOptions` says so.
|
|
728
|
-
*/
|
|
729
|
-
moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
862
|
+
return { moderate: async (options) => this.assets.moderate(toTextAssetOptions(options)) };
|
|
730
863
|
}
|
|
731
864
|
get assets() {
|
|
732
865
|
return {
|
|
@@ -750,11 +883,11 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
750
883
|
* @returns Promise with asset data
|
|
751
884
|
*/
|
|
752
885
|
retrieve: async ({ assetId }) => {
|
|
753
|
-
if (!assetId) throw
|
|
886
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
754
887
|
return (await this.endpoints.getAsset.submit({ params: { assetId } })).data;
|
|
755
888
|
},
|
|
756
889
|
update: async ({ assetId, ...body }) => {
|
|
757
|
-
if (!assetId) throw
|
|
890
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
758
891
|
return (await this.endpoints.patchAsset.submit({
|
|
759
892
|
params: { assetId },
|
|
760
893
|
body
|
|
@@ -767,7 +900,7 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
767
900
|
* @returns Promise with paginated child assets
|
|
768
901
|
*/
|
|
769
902
|
listChildren: async ({ assetId, ...options }) => {
|
|
770
|
-
if (!assetId) throw
|
|
903
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
771
904
|
return (await this.endpoints.getAssetChildren.submit({
|
|
772
905
|
params: { assetId },
|
|
773
906
|
query: {
|
|
@@ -792,13 +925,14 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
792
925
|
})).data;
|
|
793
926
|
},
|
|
794
927
|
/**
|
|
795
|
-
* Submit a new asset and
|
|
928
|
+
* Submit a new asset and moderate it synchronously
|
|
796
929
|
* The asset will be classified immediately before the response is returned.
|
|
797
930
|
* This may take longer but ensures the asset is fully processed.
|
|
798
931
|
* @param options - Asset submission options
|
|
799
932
|
* @returns Promise with created and analyzed asset
|
|
800
933
|
*/
|
|
801
|
-
|
|
934
|
+
moderate: async (options) => {
|
|
935
|
+
if ("content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
|
|
802
936
|
const body = prepareSubmitAssetOptions(options);
|
|
803
937
|
if ("content" in body || "part" in body) return await this.submitRawAssetUpload(body, false);
|
|
804
938
|
return (await this.endpoints.postUploadAsset.submit({
|
|
@@ -814,8 +948,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
814
948
|
* @returns Promise with asset data
|
|
815
949
|
*/
|
|
816
950
|
uploadPart: async ({ assetId, part }) => {
|
|
817
|
-
if (!assetId) throw
|
|
818
|
-
if (!part) throw
|
|
951
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
952
|
+
if (!part) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
|
|
819
953
|
const validation = validateAssetPayload(part, {
|
|
820
954
|
multipart: true,
|
|
821
955
|
isFinal: part.isFinal
|
|
@@ -825,8 +959,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
825
959
|
const partSizeInBytes = part.sizeInBytes ?? getAssetPayloadByteLength(part);
|
|
826
960
|
if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
|
|
827
961
|
const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
|
|
828
|
-
if (totalSizeInBytes >
|
|
829
|
-
if (part.isFinal && totalSizeInBytes <
|
|
962
|
+
if (totalSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
|
|
963
|
+
if (part.isFinal && totalSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
|
|
830
964
|
}
|
|
831
965
|
return await this.submitRawAssetPart(assetId, part, this.multipartUploadQueues.get(assetId) ?? false);
|
|
832
966
|
},
|
|
@@ -836,8 +970,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
836
970
|
* auth cookies or API keys to the CDN on every media request.
|
|
837
971
|
*/
|
|
838
972
|
createSignedUrl: async ({ assetId, ...options }) => {
|
|
839
|
-
if (!assetId) throw
|
|
840
|
-
if (options.lens && options.transform) throw
|
|
973
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
974
|
+
if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
|
|
841
975
|
return (await this.endpoints.postAssetSignedUrl.submit({
|
|
842
976
|
body: {
|
|
843
977
|
resource: options.resource ?? "content",
|
|
@@ -849,7 +983,7 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
849
983
|
})).data;
|
|
850
984
|
},
|
|
851
985
|
move: async ({ assetId, folderId }) => {
|
|
852
|
-
if (!assetId) throw
|
|
986
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
853
987
|
return (await this.endpoints.moveAsset.submit({
|
|
854
988
|
params: { assetId },
|
|
855
989
|
body: { folderId }
|
|
@@ -860,7 +994,7 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
860
994
|
* moderated like a new upload; its content must still be stored.
|
|
861
995
|
*/
|
|
862
996
|
retry: async ({ assetId }) => {
|
|
863
|
-
if (!assetId) throw
|
|
997
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
864
998
|
return (await this.endpoints.retryAsset.submit({ params: { assetId } })).data;
|
|
865
999
|
}
|
|
866
1000
|
};
|
|
@@ -869,7 +1003,8 @@ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
|
|
|
869
1003
|
return {
|
|
870
1004
|
/**
|
|
871
1005
|
* List project events after a cursor, oldest first. Call without `after` to get a cursor
|
|
872
|
-
* for "now", then poll with the returned `cursor`.
|
|
1006
|
+
* for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
|
|
1007
|
+
* reshaped as `{ id, type, createdAt, projectId, data }`.
|
|
873
1008
|
*/
|
|
874
1009
|
list: async (options = {}) => {
|
|
875
1010
|
return (await this.endpoints.getEvents.submit({
|
|
@@ -884,7 +1019,7 @@ list: async (options = {}) => {
|
|
|
884
1019
|
return (await this.endpoints.getFolders.submit({ params: { projectId: this.options.projectId } })).data.folders;
|
|
885
1020
|
},
|
|
886
1021
|
retrieve: async ({ folderId }) => {
|
|
887
|
-
if (!folderId) throw
|
|
1022
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
888
1023
|
return (await this.endpoints.getFolder.submit({ params: { folderId } })).data;
|
|
889
1024
|
},
|
|
890
1025
|
create: async (options) => {
|
|
@@ -894,18 +1029,18 @@ list: async (options = {}) => {
|
|
|
894
1029
|
})).data;
|
|
895
1030
|
},
|
|
896
1031
|
update: async ({ folderId, ...body }) => {
|
|
897
|
-
if (!folderId) throw
|
|
1032
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
898
1033
|
return (await this.endpoints.patchFolder.submit({
|
|
899
1034
|
params: { folderId },
|
|
900
1035
|
body
|
|
901
1036
|
})).data;
|
|
902
1037
|
},
|
|
903
1038
|
delete: async ({ folderId }) => {
|
|
904
|
-
if (!folderId) throw
|
|
1039
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
905
1040
|
await this.endpoints.deleteFolder.submit({ params: { folderId } });
|
|
906
1041
|
},
|
|
907
1042
|
move: async ({ folderId, parentId }) => {
|
|
908
|
-
if (!folderId) throw
|
|
1043
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
909
1044
|
return (await this.endpoints.moveFolder.submit({
|
|
910
1045
|
params: { folderId },
|
|
911
1046
|
body: { parentId }
|
|
@@ -918,7 +1053,7 @@ list: async (options = {}) => {
|
|
|
918
1053
|
* Supplying the same definition and version is idempotent.
|
|
919
1054
|
*/
|
|
920
1055
|
async ensureLens(options) {
|
|
921
|
-
if (!options.identifier) throw
|
|
1056
|
+
if (!options.identifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
922
1057
|
const [lens] = await this.ensureLenses({ lenses: [options] });
|
|
923
1058
|
return lens;
|
|
924
1059
|
}
|
|
@@ -927,8 +1062,8 @@ list: async (options = {}) => {
|
|
|
927
1062
|
* Each lens follows the same versioning and idempotency rules as ensureLens().
|
|
928
1063
|
*/
|
|
929
1064
|
async ensureLenses({ lenses }) {
|
|
930
|
-
if (lenses.length === 0) throw
|
|
931
|
-
if (lenses.some((option) => !option.identifier)) throw
|
|
1065
|
+
if (lenses.length === 0) throw calmLensError({ id: "upload/invalid-payload" }, { message: "At least one lens is required" });
|
|
1066
|
+
if (lenses.some((option) => !option.identifier)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
932
1067
|
const missingOptions = [];
|
|
933
1068
|
const missingKeys = /* @__PURE__ */ new Set();
|
|
934
1069
|
for (const option of lenses) {
|
|
@@ -956,7 +1091,7 @@ list: async (options = {}) => {
|
|
|
956
1091
|
});
|
|
957
1092
|
for (const [index, lens] of result.data.lenses.entries()) {
|
|
958
1093
|
const optionsForLens = options[index];
|
|
959
|
-
if (!optionsForLens) throw
|
|
1094
|
+
if (!optionsForLens) throw calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
|
|
960
1095
|
for (const [cacheKey, cachedLens] of this.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) this.ensuredLenses.delete(cacheKey);
|
|
961
1096
|
this.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
962
1097
|
}
|
|
@@ -974,20 +1109,18 @@ const FATAL_ERROR_CODES = new Set([
|
|
|
974
1109
|
PUBLIC_ERROR_CODES.PROJECT_NOT_FOUND
|
|
975
1110
|
].map((code) => code.getId()));
|
|
976
1111
|
const createLocalSigningSecret = () => `whsec_local_${(0, node_crypto.randomBytes)(24).toString("hex")}`;
|
|
977
|
-
/** HMAC-SHA256 of the exact body, as lowercase hex: the same scheme as real deliveries. */
|
|
978
|
-
const signWebhookBody = (secret, body) => (0, node_crypto.createHmac)("sha256", secret).update(body).digest("hex");
|
|
979
1112
|
const forwardEvent = async (event, options) => {
|
|
980
|
-
const body = JSON.stringify(event);
|
|
1113
|
+
const body = JSON.stringify(toWebhookEventPayload(event));
|
|
981
1114
|
const startedAt = Date.now();
|
|
982
1115
|
try {
|
|
1116
|
+
const headers = await createWebhookHeaders({
|
|
1117
|
+
secret: options.secret,
|
|
1118
|
+
body,
|
|
1119
|
+
deliveryId: `cli_${(0, node_crypto.randomUUID)()}`
|
|
1120
|
+
});
|
|
983
1121
|
const response = await (options.fetchImpl ?? fetch)(options.forwardTo, {
|
|
984
1122
|
method: "POST",
|
|
985
|
-
headers
|
|
986
|
-
"content-type": "application/json",
|
|
987
|
-
"x-calmlens-delivery": `cli_${(0, node_crypto.randomUUID)()}`,
|
|
988
|
-
"x-calmlens-delivery-attempt": "1",
|
|
989
|
-
"x-calmlens-signature": signWebhookBody(options.secret, body)
|
|
990
|
-
},
|
|
1123
|
+
headers,
|
|
991
1124
|
body,
|
|
992
1125
|
signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
|
|
993
1126
|
});
|
|
@@ -1064,8 +1197,9 @@ Usage:
|
|
|
1064
1197
|
Run it with \`npx calmlens\`, or install it with \`npm install -g calmlens\`.
|
|
1065
1198
|
|
|
1066
1199
|
Commands:
|
|
1067
|
-
listen Forward your project's events to a local webhook handler
|
|
1068
|
-
|
|
1200
|
+
listen Forward your project's events to a local webhook handler with the same body
|
|
1201
|
+
({ id, type, createdAt, projectId, data }) and headers (x-calmlens-timestamp,
|
|
1202
|
+
x-calmlens-signature: v1=...) as real deliveries. No public URL needed.
|
|
1069
1203
|
trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
|
|
1070
1204
|
counts as one upload.
|
|
1071
1205
|
|
|
@@ -1170,9 +1304,12 @@ const main = async () => {
|
|
|
1170
1304
|
if (!TRIGGER_KINDS.includes(kind)) fail(`Unknown trigger "${kind}". Use one of: ${TRIGGER_KINDS.join(", ")}.`);
|
|
1171
1305
|
const text = kind === "clean" ? "Hello from the CalmLens CLI" : `<!calmlens-test ${projectId.slice(-8)} ${kind}>`;
|
|
1172
1306
|
try {
|
|
1173
|
-
const asset = await client.
|
|
1174
|
-
|
|
1175
|
-
|
|
1307
|
+
const asset = await client.assets.moderate({
|
|
1308
|
+
name: `cli-trigger-${kind}`,
|
|
1309
|
+
content: {
|
|
1310
|
+
plainText: text,
|
|
1311
|
+
type: "text/plain"
|
|
1312
|
+
}
|
|
1176
1313
|
});
|
|
1177
1314
|
process.stdout.write(`Created asset ${asset.id}: status ${asset.status}${asset.report?.flagged ? ", flagged" : ""}.\n`);
|
|
1178
1315
|
} catch (error) {
|