calmlens 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1157 @@
1
+ #!/usr/bin/env node
2
+ let node_util = require("node:util");
3
+ let api_def = require("api-def");
4
+ let sendable_error = require("sendable-error");
5
+ let node_crypto = require("node:crypto");
6
+ //#region ../shared/src/AssetPayload.ts
7
+ const uint8ArrayInputToNumbers = (value) => {
8
+ if (Array.isArray(value)) return value;
9
+ return Array.from(value);
10
+ };
11
+ const bufferInputToBytes = (value) => {
12
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
13
+ return Uint8Array.from(value);
14
+ };
15
+ const BASE64_PART_BOUNDARY_ERROR = "Invalid base64 part. For multipart uploads, split the original bytes first, then base64-encode each part. Do not split one full base64 string into substrings.";
16
+ const MULTIPART_PART_TOO_SMALL_ERROR = `Multipart upload parts must be at least 5MiB except the final part.`;
17
+ const getRawBase64 = (value) => {
18
+ const markerIndex = value.indexOf(";base64,");
19
+ if (markerIndex === -1) return value;
20
+ return value.slice(markerIndex + 8);
21
+ };
22
+ const validateBase64PayloadString = (payload, options) => {
23
+ const raw = getRawBase64(payload.base64).replace(/\s/g, "");
24
+ if (options?.multipart && raw.length % 4 !== 0) return {
25
+ ok: false,
26
+ error: BASE64_PART_BOUNDARY_ERROR
27
+ };
28
+ return { ok: true };
29
+ };
30
+ const assetToData = (payload) => {
31
+ if ("plainText" in payload && payload.plainText !== void 0) return new TextEncoder().encode(payload.plainText);
32
+ if ("data" in payload && payload.data) return payload.data;
33
+ if ("buffer" in payload) {
34
+ if (payload.buffer instanceof ArrayBuffer) return payload.buffer;
35
+ return bufferInputToBytes(payload.buffer);
36
+ }
37
+ if (payload.uint8Array !== void 0) return Uint8Array.from(uint8ArrayInputToNumbers(payload.uint8Array));
38
+ if (payload.base64 === void 0) throw new Error("Invalid asset payload");
39
+ const raw = getRawBase64(payload.base64);
40
+ if (typeof Buffer !== "undefined") return Uint8Array.from(Buffer.from(raw, "base64"));
41
+ const binary = atob(raw);
42
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
43
+ };
44
+ const getAssetPayloadByteLength = (payload) => {
45
+ if ("plainText" in payload && payload.plainText !== void 0) return new TextEncoder().encode(payload.plainText).byteLength;
46
+ if ("data" in payload && payload.data) {
47
+ if (payload.data instanceof Blob) return payload.data.size;
48
+ if (payload.data instanceof Response) {
49
+ const contentLength = payload.data.headers.get("content-length");
50
+ return contentLength ? Number(contentLength) : void 0;
51
+ }
52
+ return;
53
+ }
54
+ if ("buffer" in payload && payload.buffer) return payload.buffer.byteLength;
55
+ if (payload.uint8Array !== void 0) {
56
+ if (Array.isArray(payload.uint8Array)) return payload.uint8Array.length;
57
+ return payload.uint8Array.byteLength;
58
+ }
59
+ if (payload.base64 === void 0) return;
60
+ const raw = getRawBase64(payload.base64).replace(/\s/g, "");
61
+ const padding = raw.endsWith("==") ? 2 : raw.endsWith("=") ? 1 : 0;
62
+ return Math.max(0, Math.floor(raw.length * 3 / 4) - padding);
63
+ };
64
+ const validateAssetPayload = (payload, options) => {
65
+ if ("base64" in payload && payload.base64 !== void 0) {
66
+ const validation = validateBase64PayloadString(payload, options);
67
+ if (!validation.ok) return {
68
+ ok: false,
69
+ error: validation.error
70
+ };
71
+ }
72
+ const byteLength = getAssetPayloadByteLength(payload);
73
+ if (options?.multipart && !options.isFinal && byteLength !== void 0 && byteLength < 5242880) return {
74
+ ok: false,
75
+ error: MULTIPART_PART_TOO_SMALL_ERROR
76
+ };
77
+ return { ok: true };
78
+ };
79
+ //#endregion
80
+ //#region ../shared/src/JsonUtils.ts
81
+ const stringifyJsonCanonical = (value) => JSON.stringify(value, (_key, nestedValue) => {
82
+ if (!nestedValue || typeof nestedValue !== "object" || Array.isArray(nestedValue)) return nestedValue;
83
+ return Object.fromEntries(Object.keys(nestedValue).sort().map((key) => [key, nestedValue[key]]));
84
+ });
85
+ //#endregion
86
+ //#region ../shared/src/PublicErrorCodes.ts
87
+ const PUBLIC_ERROR_CODES = {
88
+ MISSING_TOKEN: new sendable_error.ErrorCode({
89
+ id: "auth/missing-token",
90
+ defaultMessage: "Authentication required. Send your project API key in the X-Api-Key header.",
91
+ status: 401
92
+ }),
93
+ INVALID_API_KEY: new sendable_error.ErrorCode({
94
+ id: "auth/invalid-api-key",
95
+ defaultMessage: "The API key is invalid, revoked or expired. Create a key under Developer → API Keys.",
96
+ status: 401
97
+ }),
98
+ API_KEY_PROJECT_MISMATCH: new sendable_error.ErrorCode({
99
+ id: "auth/project-mismatch",
100
+ defaultMessage: "This API key belongs to a different project. Use a key created for the project that owns this resource.",
101
+ status: 403
102
+ }),
103
+ FILE_TOO_LARGE: new sendable_error.ErrorCode({
104
+ id: "upload/file-too-large",
105
+ defaultMessage: "File size exceeds limit. Maximum size for images is 10MB, for other files is 5GB.",
106
+ status: 400
107
+ }),
108
+ IMAGE_REQUIRES_MULTIPART_UPLOAD: new sendable_error.ErrorCode({
109
+ id: "upload/image-requires-multipart-upload",
110
+ defaultMessage: "Images of 10MB or more must use a multipart upload.",
111
+ status: 400
112
+ }),
113
+ MULTIPART_IMAGE_TOO_SMALL: new sendable_error.ErrorCode({
114
+ id: "upload/multipart-image-too-small",
115
+ defaultMessage: "Multipart image uploads must total at least 10MB.",
116
+ status: 400
117
+ }),
118
+ MULTIPART_IMAGE_TOO_LARGE: new sendable_error.ErrorCode({
119
+ id: "upload/multipart-image-too-large",
120
+ defaultMessage: "Multipart image uploads cannot exceed 20MB.",
121
+ status: 400
122
+ }),
123
+ IMAGE_EXCEEDED_MAX_DIMENSIONS: new sendable_error.ErrorCode({
124
+ id: "upload/image-exceeded-max-dimensions",
125
+ defaultMessage: "Image exceeds maximum dimensions. Maximum dimensions are 12,000px.",
126
+ status: 400
127
+ }),
128
+ UPLOAD_LIMIT_EXCEEDED: new sendable_error.ErrorCode({
129
+ id: "upload/limit-exceeded",
130
+ defaultMessage: "Upload limit exceeded. You have used all your free uploads. Please upgrade to Plus or Pro for unlimited uploads.",
131
+ status: 403
132
+ }),
133
+ INVALID_UPLOAD_MIME_TYPE: new sendable_error.ErrorCode({
134
+ id: "upload/invalid-mime-type",
135
+ defaultMessage: "Upload file type is not supported. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain.",
136
+ status: 400
137
+ }),
138
+ INVALID_EVENT_CURSOR: new sendable_error.ErrorCode({
139
+ id: "events/invalid-cursor",
140
+ defaultMessage: "The events cursor is invalid. Use the cursor from a previous response, or omit it to start from now.",
141
+ status: 400
142
+ }),
143
+ INVALID_UPLOAD_PAYLOAD: new sendable_error.ErrorCode({
144
+ id: "upload/invalid-payload",
145
+ defaultMessage: "Upload payload is invalid.",
146
+ status: 400
147
+ }),
148
+ USE_UPLOAD_PART: new sendable_error.ErrorCode({
149
+ id: "upload/use-upload-part",
150
+ defaultMessage: "Use uploadPart for multipart upload parts after the first part",
151
+ status: 409
152
+ }),
153
+ UPLOAD_NOT_OPEN: new sendable_error.ErrorCode({
154
+ id: "upload/not-open",
155
+ defaultMessage: "Asset is not accepting additional parts",
156
+ status: 409
157
+ }),
158
+ INVALID_UPLOAD_PART_NUMBER: new sendable_error.ErrorCode({
159
+ id: "upload/invalid-part-number",
160
+ defaultMessage: "Multipart upload part number is invalid.",
161
+ status: 409
162
+ }),
163
+ UPLOAD_MISSING: new sendable_error.ErrorCode({
164
+ id: "upload/missing",
165
+ defaultMessage: "Multipart upload state is missing",
166
+ status: 409
167
+ }),
168
+ ASSET_NOT_FOUND: new sendable_error.ErrorCode({
169
+ id: "asset/not-found",
170
+ defaultMessage: "Asset not found",
171
+ status: 404
172
+ }),
173
+ PROJECT_NOT_FOUND: new sendable_error.ErrorCode({
174
+ id: "project/not-found",
175
+ defaultMessage: "Project not found",
176
+ status: 404
177
+ }),
178
+ ASSET_UPDATE_FAILED: new sendable_error.ErrorCode({
179
+ id: "asset/update-failed",
180
+ defaultMessage: "Failed to update asset",
181
+ status: 500
182
+ }),
183
+ ASSET_SAFETY_HELD: new sendable_error.ErrorCode({
184
+ id: "asset/safety-held",
185
+ defaultMessage: "Asset access is restricted by a safety hold.",
186
+ status: 423
187
+ }),
188
+ SUPPORT_TICKET_NOT_FOUND: new sendable_error.ErrorCode({
189
+ id: "support/ticket-not-found",
190
+ defaultMessage: "Support ticket not found.",
191
+ status: 404
192
+ }),
193
+ DUPLICATE_EXTERNAL_ID: new sendable_error.ErrorCode({
194
+ id: "asset/duplicate-external-id",
195
+ defaultMessage: "An asset with this externalId already exists in the project.",
196
+ status: 409
197
+ }),
198
+ FOLDER_NOT_FOUND: new sendable_error.ErrorCode({
199
+ id: "folder/not-found",
200
+ defaultMessage: "Folder not found",
201
+ status: 404
202
+ }),
203
+ DUPLICATE_FOLDER_NAME: new sendable_error.ErrorCode({
204
+ id: "folder/duplicate-name",
205
+ defaultMessage: "A folder with this name already exists in this location.",
206
+ status: 409
207
+ }),
208
+ FOLDER_NOT_EMPTY: new sendable_error.ErrorCode({
209
+ id: "folder/not-empty",
210
+ defaultMessage: "Folder must be empty before it can be deleted.",
211
+ status: 409
212
+ }),
213
+ FOLDER_PARENT_CYCLE: new sendable_error.ErrorCode({
214
+ id: "folder/parent-cycle",
215
+ defaultMessage: "A folder cannot be moved inside itself or one of its descendants.",
216
+ status: 409
217
+ }),
218
+ LENS_VERSION_CONFLICT: new sendable_error.ErrorCode({
219
+ id: "lens/version-conflict",
220
+ defaultMessage: "Lens updates require a version greater than the current version.",
221
+ status: 409
222
+ })
223
+ };
224
+ PUBLIC_ERROR_CODES.MISSING_TOKEN, PUBLIC_ERROR_CODES.INVALID_API_KEY, PUBLIC_ERROR_CODES.API_KEY_PROJECT_MISMATCH;
225
+ const REJECTED_UPLOAD_MIME_TYPE_SET = /* @__PURE__ */ new Set([
226
+ "application/octet-stream",
227
+ "multipart/form-data",
228
+ "multipart/mixed",
229
+ "multipart/alternative",
230
+ "multipart/related",
231
+ "multipart/signed",
232
+ "multipart/encrypted"
233
+ ]);
234
+ const normalizeUploadMimeType = (mimeType) => mimeType.toLowerCase().split(";")[0]?.trim() || mimeType.toLowerCase().trim();
235
+ const isRejectedUploadMimeType = (mimeType) => REJECTED_UPLOAD_MIME_TYPE_SET.has(normalizeUploadMimeType(mimeType));
236
+ const getRejectedUploadMimeTypeError = (mimeType) => `${normalizeUploadMimeType(mimeType)} is not a valid upload file type. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain.`;
237
+ //#endregion
238
+ //#region src/client/CalmLensError.ts
239
+ const SDK_ERRORS = { NO_CDN_FETCH: {
240
+ id: "sdk/no-cdn-fetch",
241
+ defaultMessage: "No fetch implementation is available for CDN requests"
242
+ } };
243
+ var CalmLensError = class extends Error {
244
+ constructor(errorCode, options) {
245
+ const code = "getId" in errorCode ? errorCode.getId() : errorCode.id;
246
+ const defaultMessage = "getDefaultMessage" in errorCode ? errorCode.getDefaultMessage() : errorCode.defaultMessage;
247
+ super(`[calmlens] ${options?.message ?? defaultMessage ?? code}`);
248
+ this.name = "CalmLensError";
249
+ this.code = code;
250
+ this.details = options?.details;
251
+ }
252
+ };
253
+ const calmLensError = (errorCode, options) => new CalmLensError(errorCode, options);
254
+ //#endregion
255
+ //#region src/client/CalmLensUtils.ts
256
+ /** Converts `text.moderate()` options into a plain-text asset submission. */
257
+ const toTextAssetOptions = ({ text, name, ...options }) => {
258
+ if (typeof text !== "string" || text.trim().length === 0) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "Text to moderate must be a non-empty string" });
259
+ return {
260
+ ...options,
261
+ name: name ?? "text",
262
+ content: {
263
+ plainText: text,
264
+ type: "text/plain"
265
+ }
266
+ };
267
+ };
268
+ async function verifyWebhookSignature({ payload, signatureHex, secret }) {
269
+ const encoder = new TextEncoder();
270
+ const normalizePayload = typeof payload === "string" ? payload : JSON.stringify(payload);
271
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
272
+ name: "HMAC",
273
+ hash: "SHA-256"
274
+ }, false, ["sign"]);
275
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(normalizePayload));
276
+ const hex = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
277
+ if (hex.length !== signatureHex.length) return false;
278
+ let diff = 0;
279
+ for (let i = 0; i < hex.length; i++) diff |= hex.charCodeAt(i) ^ signatureHex.charCodeAt(i);
280
+ return diff === 0;
281
+ }
282
+ //#endregion
283
+ //#region src/client/CalmLensClient.ts
284
+ const toBlobPartBytes = (value) => {
285
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
286
+ return Uint8Array.from(value);
287
+ };
288
+ const normalizePayloadForRequest = (payload) => {
289
+ if ("base64" in payload && payload.base64) return {
290
+ ...payload,
291
+ base64: getRawBase64(payload.base64)
292
+ };
293
+ if ("uint8Array" in payload && payload.uint8Array) {
294
+ const { uint8Array, ...rest } = payload;
295
+ return {
296
+ ...rest,
297
+ data: new Blob([toBlobPartBytes(uint8Array)])
298
+ };
299
+ }
300
+ if ("buffer" in payload && payload.buffer) {
301
+ const { buffer, ...rest } = payload;
302
+ return {
303
+ ...rest,
304
+ data: new Blob([toBlobPartBytes(buffer)])
305
+ };
306
+ }
307
+ return payload;
308
+ };
309
+ const normalizeMetadataForMultipart = (metadata) => {
310
+ if (!Array.isArray(metadata)) return metadata;
311
+ return Object.fromEntries(metadata.map((item, index) => [index, item]));
312
+ };
313
+ const normalizeMetadataOptionsForRequest = (options) => {
314
+ if (!("metadata" in options) || !Array.isArray(options.metadata)) return options;
315
+ return {
316
+ ...options,
317
+ metadata: normalizeMetadataForMultipart(options.metadata)
318
+ };
319
+ };
320
+ const normalizeAssetOptionsForRequest = (options) => {
321
+ const normalizedOptions = normalizeMetadataOptionsForRequest(options);
322
+ if ("part" in normalizedOptions) return {
323
+ ...normalizedOptions,
324
+ part: normalizePayloadForRequest(normalizedOptions.part)
325
+ };
326
+ if ("content" in normalizedOptions && !("plainText" in normalizedOptions.content)) return {
327
+ ...normalizedOptions,
328
+ content: normalizePayloadForRequest(normalizedOptions.content)
329
+ };
330
+ return normalizedOptions;
331
+ };
332
+ const toRawUploadBody = (payload) => {
333
+ const data = assetToData(normalizePayloadForRequest(payload));
334
+ if (data instanceof Response) {
335
+ if (!data.body) throw new Error("Response upload data must have a body");
336
+ return data.body;
337
+ }
338
+ if (data instanceof ArrayBuffer || data instanceof Blob) return data;
339
+ if ("getReader" in data) return data;
340
+ return new Blob([toBlobPartBytes(data)]);
341
+ };
342
+ const setOptionalQueryValue = (params, key, value) => {
343
+ if (value !== void 0 && value !== null) params.set(key, typeof value === "string" ? value : JSON.stringify(value));
344
+ };
345
+ const assertValidUploadMimeType = (mimeType) => {
346
+ if (isRejectedUploadMimeType(mimeType)) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_MIME_TYPE, {
347
+ message: getRejectedUploadMimeTypeError(mimeType),
348
+ details: { mimeType }
349
+ });
350
+ };
351
+ const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
352
+ const prepareSubmitAssetOptions = (options) => {
353
+ if (!("content" in options) && !("url" in options) && !("part" in options)) throw new Error("Either file content, URL, or multipart part is required");
354
+ if (!options.name) throw new Error("Asset name is required");
355
+ if (!("part" in options) && "isFinal" in options) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
356
+ if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw calmLensError(PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
357
+ if ("content" in options) {
358
+ assertValidUploadMimeType(options.content.type);
359
+ if (!("plainText" in options.content)) {
360
+ const validation = validateAssetPayload(options.content);
361
+ if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
362
+ }
363
+ }
364
+ if ("part" in options) {
365
+ assertValidUploadMimeType(options.part.type);
366
+ const partSizeInBytes = options.part.sizeInBytes ?? getAssetPayloadByteLength(options.part);
367
+ if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
368
+ if (partSizeInBytes > 20971520) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
369
+ if (options.part.isFinal && partSizeInBytes < 10485760) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
370
+ }
371
+ const validation = validateAssetPayload(options.part, {
372
+ multipart: true,
373
+ isFinal: options.part.isFinal
374
+ });
375
+ if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
376
+ }
377
+ return options;
378
+ };
379
+ const appendCdnSelector = (url, options) => {
380
+ if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
381
+ if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
382
+ if (!options.transform) return url;
383
+ return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
384
+ };
385
+ const getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
386
+ identifier: options.identifier,
387
+ name: options.name,
388
+ description: options.description ?? null,
389
+ type: options.type,
390
+ active: options.active,
391
+ transforms: options.transforms ?? null,
392
+ version: options.version
393
+ });
394
+ const withApiKeyHeader = (init, apiKey) => {
395
+ const headers = new Headers(init?.headers);
396
+ headers.set("X-Api-Key", apiKey);
397
+ return {
398
+ ...init,
399
+ headers: Object.fromEntries(headers.entries())
400
+ };
401
+ };
402
+ const createApi = (options) => {
403
+ return new api_def.Api({
404
+ name: "Calm Lens",
405
+ baseUrl: options.baseUrl,
406
+ middleware: [
407
+ (0, api_def.RequestCoalescingMiddleware)(),
408
+ { beforeSend: (context) => {
409
+ context.updateHeaders({ "X-Api-Key": options.apiKey });
410
+ } },
411
+ { [api_def.RequestEvent.ERROR]: (context) => {
412
+ if (context.error) throw normalizeApiError(context.error);
413
+ } }
414
+ ],
415
+ requestBackend: options.requestBackend
416
+ });
417
+ };
418
+ const isApiErrorPayload = (value) => {
419
+ return !!value && typeof value === "object" && typeof value.code === "string";
420
+ };
421
+ const normalizeApiError = (error) => {
422
+ const response = error instanceof Error ? (0, api_def.getErrorResponse)(error) : void 0;
423
+ if (error instanceof Error && (0, api_def.isRequestError)(error) && isApiErrorPayload(response?.data)) {
424
+ const { code, message, details, traceId } = response.data;
425
+ return calmLensError({
426
+ id: code,
427
+ defaultMessage: message
428
+ }, {
429
+ message,
430
+ details: {
431
+ ...details,
432
+ traceId,
433
+ network: true
434
+ }
435
+ });
436
+ }
437
+ return error;
438
+ };
439
+ const createEndpoints = (api) => {
440
+ const getFolders = api.endpoint().paramsOf().responseOf().build({
441
+ id: "getFolders",
442
+ method: "get",
443
+ path: "/projects/:projectId/folders"
444
+ });
445
+ const getFolder = api.endpoint().paramsOf().responseOf().build({
446
+ id: "getFolder",
447
+ method: "get",
448
+ path: "/folders/:folderId"
449
+ });
450
+ const postFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
451
+ id: "postFolder",
452
+ method: "post",
453
+ path: "/projects/:projectId/folders"
454
+ });
455
+ const patchFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
456
+ id: "patchFolder",
457
+ method: "patch",
458
+ path: "/folders/:folderId"
459
+ });
460
+ const deleteFolder = api.endpoint().paramsOf().responseOf().build({
461
+ id: "deleteFolder",
462
+ method: "delete",
463
+ path: "/folders/:folderId"
464
+ });
465
+ const moveFolder = api.endpoint().paramsOf().bodyOf().responseOf().build({
466
+ id: "moveFolder",
467
+ method: "post",
468
+ path: "/folders/:folderId/move"
469
+ });
470
+ const getAssetsPage = api.endpoint().queryOf().paramsOf().responseOf().build({
471
+ id: "getAssetsPage",
472
+ method: "get",
473
+ path: "/projects/:projectId/assets/page"
474
+ });
475
+ const getAsset = api.endpoint().paramsOf().responseOf().build({
476
+ id: "getAsset",
477
+ method: "get",
478
+ path: "/assets/:assetId"
479
+ });
480
+ const getAssetChildren = api.endpoint().paramsOf().queryOf().responseOf().build({
481
+ id: "getAssetChildren",
482
+ method: "get",
483
+ path: "/assets/:assetId/children"
484
+ });
485
+ const patchAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
486
+ id: "patchAsset",
487
+ method: "patch",
488
+ path: "/assets/:assetId"
489
+ });
490
+ const postUploadAsset = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
491
+ id: "postUploadAsset",
492
+ method: "post",
493
+ path: "/projects/:projectId/assets"
494
+ });
495
+ const postAssetSignedUrl = api.endpoint().bodyOf().paramsOf().responseOf().build({
496
+ id: "postAssetSignedUrl",
497
+ method: "post",
498
+ path: "/assets/:assetId/signed-url"
499
+ });
500
+ const postAssetPart = api.endpoint().bodyOf({ encoding: "multipart/form-data" }).paramsOf().queryOf().responseOf().build({
501
+ id: "postAssetPart",
502
+ method: "post",
503
+ path: "/assets/:assetId/part"
504
+ });
505
+ const moveAsset = api.endpoint().paramsOf().bodyOf().responseOf().build({
506
+ id: "moveAsset",
507
+ method: "post",
508
+ path: "/assets/:assetId/move"
509
+ });
510
+ const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
511
+ id: "getEvents",
512
+ method: "get",
513
+ path: "/projects/:projectId/events"
514
+ });
515
+ return {
516
+ getFolders,
517
+ getFolder,
518
+ postFolder,
519
+ patchFolder,
520
+ deleteFolder,
521
+ moveFolder,
522
+ getAssetsPage,
523
+ getAsset,
524
+ getAssetChildren,
525
+ patchAsset,
526
+ postUploadAsset,
527
+ postAssetSignedUrl,
528
+ postAssetPart,
529
+ moveAsset,
530
+ ensureLens: api.endpoint().bodyOf().paramsOf().responseOf().build({
531
+ id: "ensureLens",
532
+ method: "put",
533
+ path: "/lenses/:lensIdentifier"
534
+ }),
535
+ ensureLenses: api.endpoint().bodyOf().paramsOf().responseOf().build({
536
+ id: "ensureLenses",
537
+ method: "put",
538
+ path: "/projects/:projectId/lenses"
539
+ }),
540
+ getEvents
541
+ };
542
+ };
543
+ var CalmLensClient = class {
544
+ /**
545
+ * Validates a webhook signature to ensure the webhook payload is authentic.
546
+ *
547
+ * @param payload - The webhook payload (string or object)
548
+ * @param signatureHex - The signature from the 'x-calmlens-signature' header
549
+ * @param secret - The webhook secret used to sign the payload
550
+ * @returns Promise<boolean> - True if the signature is valid, false otherwise
551
+ *
552
+ * @example
553
+ * ```javascript
554
+ * // In your webhook handler
555
+ * const signature = req.headers['x-calmlens-signature'];
556
+ * const payload = req.body;
557
+ * const isValid = await CalmLensClient.verifyWebhookSignature({
558
+ * payload,
559
+ * signatureHex: signature,
560
+ * secret: WEBHOOK_SECRET,
561
+ * });
562
+ *
563
+ * if (!isValid) {
564
+ * return res.status(401).send('Unauthorized');
565
+ * }
566
+ * ```
567
+ */
568
+ static async verifyWebhookSignature(options) {
569
+ return verifyWebhookSignature(options);
570
+ }
571
+ constructor(options) {
572
+ this.options = options;
573
+ this.ensuredLenses = /* @__PURE__ */ new Map();
574
+ this.pendingEnsureLenses = /* @__PURE__ */ new Map();
575
+ this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
576
+ this.multipartUploadQueues = /* @__PURE__ */ new Map();
577
+ if (!options.apiKey) throw new Error("API key is required");
578
+ if (!options.projectId) throw new Error("Project ID is required");
579
+ this.options.baseUrl = this.options.baseUrl ?? `https://api.calmlens.com/v1`;
580
+ this.options.cdnBaseUrl = this.options.cdnBaseUrl ?? `https://cdn.calmlens.com/v1`;
581
+ this.api = createApi(this.options);
582
+ this.endpoints = createEndpoints(this.api);
583
+ }
584
+ getUploadFetch() {
585
+ const requestBackendFetch = this.options.requestBackend?.fetch;
586
+ const fetchImpl = this.options.uploadFetch ?? requestBackendFetch ?? globalThis.fetch;
587
+ if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
588
+ return fetchImpl;
589
+ }
590
+ async submitRawAssetUpload(options, queue) {
591
+ const query = new URLSearchParams();
592
+ query.set("name", options.name);
593
+ query.set("queue", String(queue));
594
+ setOptionalQueryValue(query, "description", options.description);
595
+ setOptionalQueryValue(query, "processingOptions", options.processingOptions);
596
+ setOptionalQueryValue(query, "visibility", options.visibility);
597
+ setOptionalQueryValue(query, "metadata", options.metadata);
598
+ setOptionalQueryValue(query, "externalId", options.externalId);
599
+ setOptionalQueryValue(query, "externalUrl", options.externalUrl);
600
+ setOptionalQueryValue(query, "folderId", options.folderId);
601
+ const isMultipart = "part" in options;
602
+ const payload = isMultipart ? options.part : options.content;
603
+ query.set("contentType", payload.type);
604
+ setOptionalQueryValue(query, "sizeInBytes", payload.sizeInBytes ?? getAssetPayloadByteLength(payload));
605
+ if (isMultipart) {
606
+ const part = payload;
607
+ const multipartOptions = options;
608
+ query.set("partNumber", String(part.partNumber ?? 1));
609
+ query.set("isFinal", String(part.isFinal ?? false));
610
+ setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? multipartOptions.sizeInBytes);
611
+ }
612
+ const baseUrl = this.options.baseUrl.replace(/\/$/, "");
613
+ const path = isMultipart ? "assets/multipart-upload" : "assets/upload";
614
+ const url = `${baseUrl}/projects/${encodeURIComponent(this.options.projectId)}/${path}?${query}`;
615
+ const response = await this.getUploadFetch()(url, {
616
+ method: "POST",
617
+ headers: {
618
+ "Content-Type": payload.type,
619
+ "X-Api-Key": this.options.apiKey,
620
+ "X-CalmLens-Upload": isMultipart ? "part" : "content"
621
+ },
622
+ body: toRawUploadBody(payload),
623
+ duplex: "half"
624
+ });
625
+ const asset = await this.parseRawUploadResponse(response);
626
+ if (isMultipart && asset.status === "uploading") {
627
+ this.multipartUploadQueues.set(asset.id, queue);
628
+ if (isImageMimeType(payload.type)) this.multipartImageUploadSizes.set(asset.id, asset.sizeInBytes ?? 0);
629
+ }
630
+ return asset;
631
+ }
632
+ async submitRawAssetPart(assetId, part, queue) {
633
+ const query = new URLSearchParams({
634
+ queue: String(queue),
635
+ partNumber: String(part.partNumber),
636
+ isFinal: String(part.isFinal ?? false)
637
+ });
638
+ setOptionalQueryValue(query, "sizeInBytes", part.sizeInBytes ?? getAssetPayloadByteLength(part));
639
+ const url = `${this.options.baseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(assetId)}/part?${query}`;
640
+ const response = await this.getUploadFetch()(url, {
641
+ method: "POST",
642
+ headers: {
643
+ "X-Api-Key": this.options.apiKey,
644
+ "X-CalmLens-Upload": "part"
645
+ },
646
+ body: toRawUploadBody(part),
647
+ duplex: "half"
648
+ });
649
+ const asset = await this.parseRawUploadResponse(response);
650
+ if (asset.status === "uploading") this.multipartImageUploadSizes.set(asset.id, asset.sizeInBytes ?? 0);
651
+ else {
652
+ this.multipartImageUploadSizes.delete(assetId);
653
+ this.multipartUploadQueues.delete(assetId);
654
+ }
655
+ return asset;
656
+ }
657
+ async parseRawUploadResponse(response) {
658
+ const data = await response.json().catch(() => void 0);
659
+ if (!response.ok) {
660
+ if (isApiErrorPayload(data)) throw calmLensError({
661
+ id: data.code,
662
+ defaultMessage: data.message
663
+ }, {
664
+ message: data.message,
665
+ details: {
666
+ ...data.details,
667
+ traceId: data.traceId,
668
+ network: true
669
+ }
670
+ });
671
+ throw new Error(`CalmLens upload failed with status ${response.status}`);
672
+ }
673
+ return data;
674
+ }
675
+ get cdn() {
676
+ return {
677
+ /**
678
+ * Create a CDN URL for asset content or previews.
679
+ * Private assets require an authenticated request or signed URL.
680
+ */
681
+ getAssetUrl: ({ assetIdentifier, ...options }) => {
682
+ if (!assetIdentifier) throw new Error("Asset identifier is required");
683
+ const resource = options.resource ?? "content";
684
+ const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
685
+ return appendCdnSelector(url, options);
686
+ },
687
+ /**
688
+ * Fetch asset content or previews from the CDN.
689
+ * Private assets are authenticated with the client's API key.
690
+ */
691
+ serve: async ({ assetIdentifier, init, ...urlOptions }) => {
692
+ const fetchImpl = this.options.cdnFetch ?? globalThis.fetch;
693
+ if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
694
+ return fetchImpl(this.cdn.getAssetUrl({
695
+ assetIdentifier,
696
+ ...urlOptions
697
+ }), withApiKeyHeader(init, this.options.apiKey));
698
+ }
699
+ };
700
+ }
701
+ get text() {
702
+ return {
703
+ /**
704
+ * Moderate a short piece of text, such as a comment, caption or bio, and wait for the
705
+ * decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
706
+ * The text is not retained after classification unless `processingOptions` says so.
707
+ */
708
+ moderate: async (options) => this.assets.analyze(toTextAssetOptions(options)) };
709
+ }
710
+ get assets() {
711
+ return {
712
+ /**
713
+ * List all assets for a project
714
+ * @param options - Pagination and filtering options
715
+ * @returns Promise with paginated assets
716
+ */
717
+ list: async (options) => {
718
+ return (await this.endpoints.getAssetsPage.submit({
719
+ params: { projectId: this.options.projectId },
720
+ query: {
721
+ ...options,
722
+ pageIndex: options.pageIndex ?? 0
723
+ }
724
+ })).data;
725
+ },
726
+ /**
727
+ * Retrieve a specific asset by ID
728
+ * @param assetId - The asset ID
729
+ * @returns Promise with asset data
730
+ */
731
+ retrieve: async ({ assetId }) => {
732
+ if (!assetId) throw new Error("Asset ID is required");
733
+ return (await this.endpoints.getAsset.submit({ params: { assetId } })).data;
734
+ },
735
+ update: async ({ assetId, ...body }) => {
736
+ if (!assetId) throw new Error("Asset ID is required");
737
+ return (await this.endpoints.patchAsset.submit({
738
+ params: { assetId },
739
+ body
740
+ })).data;
741
+ },
742
+ /**
743
+ * Get child assets of a parent asset
744
+ * @param assetId - The parent asset ID
745
+ * @param options - Pagination options
746
+ * @returns Promise with paginated child assets
747
+ */
748
+ listChildren: async ({ assetId, ...options }) => {
749
+ if (!assetId) throw new Error("Asset ID is required");
750
+ return (await this.endpoints.getAssetChildren.submit({
751
+ params: { assetId },
752
+ query: {
753
+ ...options,
754
+ pageIndex: options.pageIndex ?? 0
755
+ }
756
+ })).data;
757
+ },
758
+ /**
759
+ * Submit a new asset for processing (queued asynchronously)
760
+ * The asset will be queued for classification and returned immediately.
761
+ * @param options - Asset submission options
762
+ * @returns Promise with created asset
763
+ */
764
+ create: async (options) => {
765
+ const body = prepareSubmitAssetOptions(options);
766
+ if ("content" in body || "part" in body) return await this.submitRawAssetUpload(body, true);
767
+ return (await this.endpoints.postUploadAsset.submit({
768
+ body: normalizeAssetOptionsForRequest(body),
769
+ params: { projectId: this.options.projectId },
770
+ query: { queue: true }
771
+ })).data;
772
+ },
773
+ /**
774
+ * Submit a new asset and analyze it synchronously
775
+ * The asset will be classified immediately before the response is returned.
776
+ * This may take longer but ensures the asset is fully processed.
777
+ * @param options - Asset submission options
778
+ * @returns Promise with created and analyzed asset
779
+ */
780
+ analyze: async (options) => {
781
+ const body = prepareSubmitAssetOptions(options);
782
+ if ("content" in body || "part" in body) return await this.submitRawAssetUpload(body, false);
783
+ return (await this.endpoints.postUploadAsset.submit({
784
+ body: normalizeAssetOptionsForRequest(body),
785
+ params: { projectId: this.options.projectId },
786
+ query: { queue: false }
787
+ })).data;
788
+ },
789
+ /**
790
+ * Upload a part for a multipart upload
791
+ * @param assetId - The asset ID
792
+ * @param part - The part to upload
793
+ * @returns Promise with asset data
794
+ */
795
+ uploadPart: async ({ assetId, part }) => {
796
+ if (!assetId) throw new Error("Asset ID is required");
797
+ if (!part) throw new Error("Part options are required");
798
+ const validation = validateAssetPayload(part, {
799
+ multipart: true,
800
+ isFinal: part.isFinal
801
+ });
802
+ if (!validation.ok) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: validation.error });
803
+ const existingImageSizeInBytes = this.multipartImageUploadSizes.get(assetId);
804
+ const partSizeInBytes = part.sizeInBytes ?? getAssetPayloadByteLength(part);
805
+ if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
806
+ const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
807
+ if (totalSizeInBytes > 20971520) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
808
+ if (part.isFinal && totalSizeInBytes < 10485760) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
809
+ }
810
+ return await this.submitRawAssetPart(assetId, part, this.multipartUploadQueues.get(assetId) ?? false);
811
+ },
812
+ /**
813
+ * Create a short-lived signed CDN URL for an asset.
814
+ * This is useful for private assets where clients should not send app
815
+ * auth cookies or API keys to the CDN on every media request.
816
+ */
817
+ createSignedUrl: async ({ assetId, ...options }) => {
818
+ if (!assetId) throw new Error("Asset ID is required");
819
+ if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
820
+ return (await this.endpoints.postAssetSignedUrl.submit({
821
+ body: {
822
+ resource: options.resource ?? "content",
823
+ expiresInSeconds: options.expiresInSeconds ?? 900,
824
+ lens: options.lens,
825
+ transform: options.transform
826
+ },
827
+ params: { assetId }
828
+ })).data;
829
+ },
830
+ move: async ({ assetId, folderId }) => {
831
+ if (!assetId) throw new Error("Asset ID is required");
832
+ return (await this.endpoints.moveAsset.submit({
833
+ params: { assetId },
834
+ body: { folderId }
835
+ })).data;
836
+ }
837
+ };
838
+ }
839
+ get events() {
840
+ return {
841
+ /**
842
+ * List project events after a cursor, oldest first. Call without `after` to get a cursor
843
+ * for "now", then poll with the returned `cursor`. Event bodies match webhook deliveries.
844
+ */
845
+ list: async (options = {}) => {
846
+ return (await this.endpoints.getEvents.submit({
847
+ params: { projectId: this.options.projectId },
848
+ query: options
849
+ })).data;
850
+ } };
851
+ }
852
+ get folders() {
853
+ return {
854
+ list: async () => {
855
+ return (await this.endpoints.getFolders.submit({ params: { projectId: this.options.projectId } })).data.folders;
856
+ },
857
+ retrieve: async ({ folderId }) => {
858
+ if (!folderId) throw new Error("Folder ID is required");
859
+ return (await this.endpoints.getFolder.submit({ params: { folderId } })).data;
860
+ },
861
+ create: async (options) => {
862
+ return (await this.endpoints.postFolder.submit({
863
+ params: { projectId: this.options.projectId },
864
+ body: options
865
+ })).data;
866
+ },
867
+ update: async ({ folderId, ...body }) => {
868
+ if (!folderId) throw new Error("Folder ID is required");
869
+ return (await this.endpoints.patchFolder.submit({
870
+ params: { folderId },
871
+ body
872
+ })).data;
873
+ },
874
+ delete: async ({ folderId }) => {
875
+ if (!folderId) throw new Error("Folder ID is required");
876
+ await this.endpoints.deleteFolder.submit({ params: { folderId } });
877
+ },
878
+ move: async ({ folderId, parentId }) => {
879
+ if (!folderId) throw new Error("Folder ID is required");
880
+ return (await this.endpoints.moveFolder.submit({
881
+ params: { folderId },
882
+ body: { parentId }
883
+ })).data;
884
+ }
885
+ };
886
+ }
887
+ /**
888
+ * Create a named lens at any positive version, or update it with a greater version.
889
+ * Supplying the same definition and version is idempotent.
890
+ */
891
+ async ensureLens(options) {
892
+ if (!options.identifier) throw new Error("Lens identifier is required");
893
+ const [lens] = await this.ensureLenses({ lenses: [options] });
894
+ return lens;
895
+ }
896
+ /**
897
+ * Create or update several named lenses in one API request.
898
+ * Each lens follows the same versioning and idempotency rules as ensureLens().
899
+ */
900
+ async ensureLenses({ lenses }) {
901
+ if (lenses.length === 0) throw new Error("At least one lens is required");
902
+ if (lenses.some((option) => !option.identifier)) throw new Error("Lens identifier is required");
903
+ const missingOptions = [];
904
+ const missingKeys = /* @__PURE__ */ new Set();
905
+ for (const option of lenses) {
906
+ const cacheKey = getEnsureLensCacheKey(option);
907
+ if (!this.ensuredLenses.has(cacheKey) && !missingKeys.has(cacheKey)) {
908
+ missingKeys.add(cacheKey);
909
+ missingOptions.push(option);
910
+ }
911
+ }
912
+ if (missingOptions.length === 0) return lenses.map((option) => this.ensuredLenses.get(getEnsureLensCacheKey(option)));
913
+ const batchCacheKey = JSON.stringify([...missingKeys].sort());
914
+ let pending = this.pendingEnsureLenses.get(batchCacheKey);
915
+ if (!pending) {
916
+ pending = this.submitEnsureLenses(missingOptions);
917
+ this.pendingEnsureLenses.set(batchCacheKey, pending);
918
+ pending.then(() => this.pendingEnsureLenses.delete(batchCacheKey), () => this.pendingEnsureLenses.delete(batchCacheKey));
919
+ }
920
+ await pending;
921
+ return lenses.map((option) => this.ensuredLenses.get(getEnsureLensCacheKey(option)));
922
+ }
923
+ async submitEnsureLenses(options) {
924
+ const result = await this.endpoints.ensureLenses.submit({
925
+ body: { lenses: options },
926
+ params: { projectId: this.options.projectId }
927
+ });
928
+ for (const [index, lens] of result.data.lenses.entries()) {
929
+ const optionsForLens = options[index];
930
+ if (!optionsForLens) throw new Error("CalmLens returned an unexpected lens response");
931
+ for (const [cacheKey, cachedLens] of this.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) this.ensuredLenses.delete(cacheKey);
932
+ this.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
933
+ }
934
+ }
935
+ };
936
+ //#endregion
937
+ //#region src/cli/listen.ts
938
+ const FORWARD_TIMEOUT_MS = 1e4;
939
+ const MAX_BACKOFF_MS = 3e4;
940
+ /** Fatal errors stop the CLI instead of retrying: they need the user to change something. */
941
+ const FATAL_ERROR_CODES = new Set([
942
+ PUBLIC_ERROR_CODES.MISSING_TOKEN,
943
+ PUBLIC_ERROR_CODES.INVALID_API_KEY,
944
+ PUBLIC_ERROR_CODES.API_KEY_PROJECT_MISMATCH,
945
+ PUBLIC_ERROR_CODES.PROJECT_NOT_FOUND
946
+ ].map((code) => code.getId()));
947
+ const createLocalSigningSecret = () => `whsec_local_${(0, node_crypto.randomBytes)(24).toString("hex")}`;
948
+ /** HMAC-SHA256 of the exact body, as lowercase hex: the same scheme as real deliveries. */
949
+ const signWebhookBody = (secret, body) => (0, node_crypto.createHmac)("sha256", secret).update(body).digest("hex");
950
+ const forwardEvent = async (event, options) => {
951
+ const body = JSON.stringify(event);
952
+ const startedAt = Date.now();
953
+ try {
954
+ const response = await (options.fetchImpl ?? fetch)(options.forwardTo, {
955
+ method: "POST",
956
+ headers: {
957
+ "content-type": "application/json",
958
+ "x-calmlens-delivery": `cli_${(0, node_crypto.randomUUID)()}`,
959
+ "x-calmlens-delivery-attempt": "1",
960
+ "x-calmlens-signature": signWebhookBody(options.secret, body)
961
+ },
962
+ body,
963
+ signal: AbortSignal.timeout(FORWARD_TIMEOUT_MS)
964
+ });
965
+ return {
966
+ ok: response.ok,
967
+ status: response.status,
968
+ durationMs: Date.now() - startedAt
969
+ };
970
+ } catch (error) {
971
+ return {
972
+ ok: false,
973
+ error: error.cause?.code ?? (error instanceof Error ? error.message : String(error)),
974
+ durationMs: Date.now() - startedAt
975
+ };
976
+ }
977
+ };
978
+ const formatTime = (date) => date.toTimeString().slice(0, 8);
979
+ const formatForwardLine = (event, result, now = /* @__PURE__ */ new Date()) => {
980
+ const outcome = result.status ? `${result.status}${result.ok ? "" : " (handler returned an error)"}` : `failed: ${result.error}${result.error === "ECONNREFUSED" ? " (is your server running?)" : ""}`;
981
+ return `${formatTime(now)} ${event.type.padEnd(16)} ${event.id} → ${outcome} [${result.durationMs}ms]`;
982
+ };
983
+ const sleep = (ms, signal) => new Promise((resolve) => {
984
+ if (signal?.aborted) return resolve();
985
+ const timer = setTimeout(resolve, ms);
986
+ signal?.addEventListener("abort", () => {
987
+ clearTimeout(timer);
988
+ resolve();
989
+ }, { once: true });
990
+ });
991
+ /**
992
+ * Forwards new events until `signal` aborts. Resolves normally on abort; rejects with the
993
+ * underlying error for fatal API errors (bad key, wrong project).
994
+ */
995
+ const listen = async (options) => {
996
+ const { client, signal } = options;
997
+ const log = options.log ?? ((line) => process.stdout.write(`${line}\n`));
998
+ const intervalMs = options.intervalMs ?? 2e3;
999
+ const eventTypes = new Set(options.eventTypes ?? []);
1000
+ let { cursor } = await client.events.list({});
1001
+ options.onReady?.();
1002
+ let failures = 0;
1003
+ while (!signal?.aborted) try {
1004
+ const page = await client.events.list({
1005
+ after: cursor,
1006
+ limit: 100
1007
+ });
1008
+ if (failures > 0) log(`${formatTime(/* @__PURE__ */ new Date())} Reconnected to CalmLens.`);
1009
+ failures = 0;
1010
+ for (const event of page.events) {
1011
+ if (eventTypes.size > 0 && !eventTypes.has(event.type)) continue;
1012
+ log(formatForwardLine(event, await forwardEvent(event, options)));
1013
+ }
1014
+ cursor = page.cursor;
1015
+ if (!page.hasMore) await sleep(intervalMs, signal);
1016
+ } catch (error) {
1017
+ if (error instanceof CalmLensError && FATAL_ERROR_CODES.has(error.code)) throw error;
1018
+ failures++;
1019
+ const backoffMs = Math.min(MAX_BACKOFF_MS, intervalMs * 2 ** failures);
1020
+ if (failures === 1) {
1021
+ const message = error instanceof Error ? error.message : String(error);
1022
+ log(`${formatTime(/* @__PURE__ */ new Date())} Couldn't reach CalmLens (${message}). Retrying…`);
1023
+ }
1024
+ await sleep(backoffMs, signal);
1025
+ }
1026
+ };
1027
+ //#endregion
1028
+ //#region src/cli/index.ts
1029
+ const HELP = `CalmLens CLI
1030
+
1031
+ Usage:
1032
+ calmlens listen --forward-to <url> [options]
1033
+ calmlens trigger [harassment|hate|criminal-activity|clean] [options]
1034
+
1035
+ Run it with \`npx calmlens\`, or install it with \`npm install -g calmlens\`.
1036
+
1037
+ Commands:
1038
+ listen Forward your project's events to a local webhook handler, signed like real
1039
+ deliveries. No public URL needed.
1040
+ trigger Moderate a harmless test comment so CalmLens creates real events. Each trigger
1041
+ counts as one upload.
1042
+
1043
+ Options:
1044
+ --forward-to <url> Local webhook URL, e.g. http://localhost:3000/api/webhooks/calmlens
1045
+ --events <types> Comma-separated event types to forward (default: all)
1046
+ --secret <secret> Signing secret (default: $CALMLENS_WEBHOOK_SECRET, or a generated one)
1047
+ --api-key <key> Project API key (default: $CALMLENS_API_KEY)
1048
+ --project-id <id> Project ID (default: $CALMLENS_PROJECT_ID)
1049
+ --env-file <path> Load environment variables from a file, e.g. .env.local
1050
+ --interval <seconds> Seconds between checks for new events (default: 2)
1051
+ --api-url <url> API base URL (default: $CALMLENS_API_URL or https://api.calmlens.com/v1)
1052
+ -h, --help Show this help
1053
+ `;
1054
+ const TRIGGER_KINDS = [
1055
+ "harassment",
1056
+ "hate",
1057
+ "criminal-activity",
1058
+ "clean"
1059
+ ];
1060
+ const fail = (message) => {
1061
+ process.stderr.write(`${message}\n`);
1062
+ process.exit(1);
1063
+ };
1064
+ const describeError = (error) => {
1065
+ if (error instanceof CalmLensError) return `${error.message.replace(/^\[calmlens\] /, "")} (${error.code})`;
1066
+ return error instanceof Error ? error.message : String(error);
1067
+ };
1068
+ const main = async () => {
1069
+ const { values, positionals } = (0, node_util.parseArgs)({
1070
+ allowPositionals: true,
1071
+ options: {
1072
+ "forward-to": { type: "string" },
1073
+ events: { type: "string" },
1074
+ secret: { type: "string" },
1075
+ "api-key": { type: "string" },
1076
+ "project-id": { type: "string" },
1077
+ "env-file": { type: "string" },
1078
+ interval: { type: "string" },
1079
+ "api-url": { type: "string" },
1080
+ help: {
1081
+ type: "boolean",
1082
+ short: "h"
1083
+ }
1084
+ }
1085
+ });
1086
+ const [command, argument] = positionals;
1087
+ if (values.help || !command || command === "help") {
1088
+ process.stdout.write(HELP);
1089
+ return;
1090
+ }
1091
+ if (values["env-file"]) try {
1092
+ process.loadEnvFile(values["env-file"]);
1093
+ } catch {
1094
+ fail(`Couldn't read ${values["env-file"]}.`);
1095
+ }
1096
+ const apiKey = values["api-key"] ?? process.env.CALMLENS_API_KEY;
1097
+ const projectId = values["project-id"] ?? process.env.CALMLENS_PROJECT_ID;
1098
+ if (!apiKey || !projectId) fail("Set CALMLENS_API_KEY and CALMLENS_PROJECT_ID (or pass --api-key and --project-id).\nBoth are on the Developer → API Keys page of the CalmLens portal.");
1099
+ const baseUrl = values["api-url"] ?? process.env.CALMLENS_API_URL;
1100
+ const client = new CalmLensClient({
1101
+ apiKey,
1102
+ projectId,
1103
+ ...baseUrl ? { baseUrl } : {}
1104
+ });
1105
+ if (command === "listen") {
1106
+ const forwardTo = values["forward-to"];
1107
+ if (!forwardTo) fail("listen needs --forward-to <url>, e.g. http://localhost:3000/api/webhooks/calmlens");
1108
+ const intervalSeconds = Number(values.interval ?? 2);
1109
+ if (!Number.isFinite(intervalSeconds) || intervalSeconds < 1) fail("--interval must be at least 1 second.");
1110
+ const configuredSecret = values.secret ?? process.env.CALMLENS_WEBHOOK_SECRET;
1111
+ const secret = configuredSecret ?? createLocalSigningSecret();
1112
+ const eventTypes = values.events?.split(",").map((type) => type.trim()).filter(Boolean);
1113
+ const controller = new AbortController();
1114
+ process.once("SIGINT", () => controller.abort());
1115
+ process.once("SIGTERM", () => controller.abort());
1116
+ try {
1117
+ await listen({
1118
+ client,
1119
+ forwardTo,
1120
+ secret,
1121
+ eventTypes,
1122
+ intervalMs: intervalSeconds * 1e3,
1123
+ signal: controller.signal,
1124
+ onReady: () => {
1125
+ process.stdout.write([
1126
+ `Forwarding CalmLens events for project ${projectId} to ${forwardTo}`,
1127
+ configuredSecret ? "Signing with your CALMLENS_WEBHOOK_SECRET." : `Signing secret: ${secret}\n Set CALMLENS_WEBHOOK_SECRET to this value in your app, or pass --secret.`,
1128
+ eventTypes?.length ? `Event types: ${eventTypes.join(", ")}` : "Event types: all",
1129
+ "Upload something (or run `npx calmlens trigger`) to see events. Press Ctrl+C to stop.",
1130
+ ""
1131
+ ].join("\n"));
1132
+ }
1133
+ });
1134
+ } catch (error) {
1135
+ fail(error instanceof CalmLensError ? `CalmLens rejected the request: ${describeError(error)}` : `Couldn't reach CalmLens: ${describeError(error)}`);
1136
+ }
1137
+ return;
1138
+ }
1139
+ if (command === "trigger") {
1140
+ const kind = argument ?? "harassment";
1141
+ if (!TRIGGER_KINDS.includes(kind)) fail(`Unknown trigger "${kind}". Use one of: ${TRIGGER_KINDS.join(", ")}.`);
1142
+ const text = kind === "clean" ? "Hello from the CalmLens CLI" : `<!calmlens-test ${projectId.slice(-8)} ${kind}>`;
1143
+ try {
1144
+ const asset = await client.text.moderate({
1145
+ text,
1146
+ name: `cli-trigger-${kind}`
1147
+ });
1148
+ process.stdout.write(`Created asset ${asset.id}: status ${asset.status}${asset.report?.flagged ? ", flagged" : ""}.\n`);
1149
+ } catch (error) {
1150
+ fail(`Trigger failed: ${describeError(error)}`);
1151
+ }
1152
+ return;
1153
+ }
1154
+ fail(`Unknown command "${command}".\n\n${HELP}`);
1155
+ };
1156
+ main().catch((error) => fail(describeError(error)));
1157
+ //#endregion