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/esm/index.js CHANGED
@@ -1,5 +1,321 @@
1
- import { _ as getAssetPayloadByteLength, a as CalmLensError, b as _asyncToGenerator, c as DOMAIN, d as getRejectedUploadMimeTypeError, f as isRejectedUploadMimeType, g as assetToData, i as _objectWithoutProperties, m as stringifyJsonCanonical, n as verifyWebhookSignature, o as SDK_ERRORS, p as PUBLIC_ERROR_CODES, r as _objectSpread2, s as calmLensError, t as toTextAssetOptions, v as getRawBase64, y as validateAssetPayload } from "./CalmLensUtils-B3Eiz2Ro.js";
2
- import { Api, RequestCoalescingMiddleware, RequestEvent, getErrorResponse, isRequestError } from "api-def";
1
+ import { _ as validateAssetPayload, a as calmLensError, c as MIN_MULTIPART_IMAGE_UPLOAD_BYTES, d as PUBLIC_ERROR_CODES, f as stringifyJsonCanonical, g as getRawBase64, h as getAssetPayloadByteLength, i as SDK_ERRORS, l as getRejectedUploadMimeTypeError, m as assetToData, n as _objectWithoutProperties, o as DOMAIN, r as CalmLensError, s as MAX_IMAGE_UPLOAD_BYTES, t as toTextAssetOptions, u as isRejectedUploadMimeType, v as _asyncToGenerator, y as _objectSpread2 } from "./CalmLensUtils-BQEgxGWk.js";
2
+ import * as zod from "zod";
3
+ import "zod/v4";
4
+ import { Api, FetchRequestBackend, RequestCoalescingMiddleware, RequestEvent, getErrorResponse, isRequestError } from "api-def";
5
+ //#region ../shared/src/ModerationCategoryDefinitions.ts
6
+ const MODERATION_CATEGORY_DEFINITIONS = {
7
+ sexual: {
8
+ summary: "Sexual acts, explicit sexual anatomy, sexual services, sexual assault depictions and clearly erotic material.",
9
+ definition: "covers sexual acts, explicit sexual anatomy, sexual services and clearly erotic material. Descriptions of sexual assault can qualify without erotic intent. Fictional, illustrated and generated depictions can also qualify.",
10
+ exclusions: "Ordinary affection, swimwear, fitness, fashion, non-erotic medical diagrams and general sexual-health education do not qualify on their own. A person accepting money or wearing revealing clothing does not establish sexual content without a qualifying act, display or offer.",
11
+ docsHref: "/docs/guides/moderation-categories#sexual-content"
12
+ },
13
+ violence: {
14
+ summary: "Physical attacks, injury, death, threats against others, and planning or encouraging physical violence.",
15
+ definition: "covers physical attacks, bodily injury, death and threats against others. Accidental or medical injuries and natural death also count; an attacker or intent to harm is not required. It also includes planning, requesting, encouraging or praising physical violence. A depicted or described act can qualify in fiction or news reporting even when the author condemns it.",
16
+ exclusions: "Solely intentional self-injury or suicide belongs under self-harm. Property damage alone, figurative language, abstract discussion of violence, injury or death and merely possessing a weapon do not establish violence. Consensual sport or training without injury or abuse is excluded.",
17
+ docsHref: "/docs/guides/moderation-categories#violence"
18
+ },
19
+ "self-harm": {
20
+ summary: "Intentional self-injury, suicide, preparation, methods or encouragement; text also includes current or recurring self-harm thoughts.",
21
+ definition: "covers intentional self-injury, suicide, current self-harm risk, preparation, methods and encouragement. For text, it also includes current or recurring self-harm thoughts and an explicitly expressed desire to die. Asking for support does not cancel a separate disclosure of current risk or behavior.",
22
+ exclusions: "For images, require evidence of a self-directed act, preparation, harmful methods or encouragement. An injury or covered body does not establish that harm was self-inflicted. General sadness, neutral statistics, prevention, recovery and healed scars alone are excluded.",
23
+ docsHref: "/docs/guides/moderation-categories#self-harm"
24
+ },
25
+ harassment: {
26
+ summary: "Targeted personal abuse, humiliation, bullying or serious intimidation; ordinary criticism and neutral reporting are excluded.",
27
+ definition: "covers personal abuse, humiliation, bullying and serious intimidation directed at a person or identifiable group. The target can be named, implied or defined by an activity or affiliation. A protected identity is not required.",
28
+ exclusions: "Disagreement, ordinary criticism of conduct or competence, untargeted profanity and neutral reporting of abuse do not qualify without a separate personal attack. Criticism can still qualify when it also contains personal degradation.",
29
+ docsHref: "/docs/guides/moderation-categories#harassment-and-bullying"
30
+ },
31
+ hate: {
32
+ summary: "Identity-based abuse, dehumanization, discriminatory exclusion or threats against people because of protected characteristics.",
33
+ definition: "covers attacks on people because of race, ethnicity, nationality, religion, caste, sex, gender identity, sexual orientation or disability. It includes dehumanization, asserted inferiority, discriminatory exclusion, identity-based abuse and threats.",
34
+ exclusions: "Both the protected target and the identity-based attack must be supported. Identity mentions, cultural clothing, religious imagery, criticism of beliefs or an unrelated threat do not establish hate. Neutral reporting, condemnation and opposition to hate are excluded unless a separate attack is expressed or endorsed.",
35
+ docsHref: "/docs/guides/moderation-categories#hate-and-identity-abuse"
36
+ },
37
+ "criminal-activity": {
38
+ summary: "Planning, assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act.",
39
+ definition: "covers planning, requests for assistance, instructions, encouragement or facilitation of a concrete criminal or seriously dangerous act. A request can qualify even when no act occurs and a later reply refuses it. Dangerous activity requires a concrete serious risk of physical harm.",
40
+ exclusions: "Neutral reporting, prevention, lawful safety advice, fiction without criminal assistance, and vague dangerous references do not qualify. Masks, computers, payment cards, detention or ordinary tools do not establish criminal facilitation by themselves. A clear visual demonstration of how to carry out a crime can qualify.",
41
+ docsHref: "/docs/guides/moderation-categories#criminal-and-dangerous-activity"
42
+ }
43
+ };
44
+ //#endregion
45
+ //#region ../shared/src/ModerationPolicyDimensions.ts
46
+ const MODERATION_QUALIFIERS = [
47
+ "nudity",
48
+ "sexual-activity",
49
+ "explicit-sexual-language",
50
+ "sexual-solicitation",
51
+ "physical-attack",
52
+ "violent-threat",
53
+ "violent-preparation",
54
+ "violent-encouragement",
55
+ "injury",
56
+ "death",
57
+ "graphic",
58
+ "self-harm-thoughts",
59
+ "self-harm-preparation",
60
+ "self-harm-act",
61
+ "self-harm-methods",
62
+ "self-harm-encouragement",
63
+ "personal-abuse",
64
+ "targeted-intimidation",
65
+ "harassment-threat",
66
+ "sexual-harassment",
67
+ "harassment-encouragement",
68
+ "identity-abuse",
69
+ "dehumanization",
70
+ "identity-inferiority",
71
+ "discriminatory-exclusion",
72
+ "hate-threat",
73
+ "criminal-demonstration",
74
+ "criminal-preparation",
75
+ "criminal-request",
76
+ "criminal-instructions",
77
+ "criminal-promotion",
78
+ "historical",
79
+ "documentary",
80
+ "fictional",
81
+ "support-prevention"
82
+ ];
83
+ const SHARED_QUALIFIERS = [
84
+ "historical",
85
+ "documentary",
86
+ "fictional",
87
+ "support-prevention"
88
+ ];
89
+ [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS], [...SHARED_QUALIFIERS];
90
+ //#endregion
91
+ //#region ../../node_modules/zod-meta/esm/index.js
92
+ const createMetaType = (type) => {
93
+ return Object.assign((value) => {
94
+ return {
95
+ type,
96
+ data: value !== null && value !== void 0 ? value : {}
97
+ };
98
+ }, type);
99
+ };
100
+ createMetaType({ id: "docPropertyInfo" });
101
+ //#endregion
102
+ //#region ../shared/src/ZodUtils.ts
103
+ const SIZE_LIMITS = {
104
+ small: 64,
105
+ medium: 200,
106
+ large: 1500
107
+ };
108
+ const saneStringField = (options) => {
109
+ return zod.string().transform((value) => value.trim()).refine((value) => {
110
+ if ((options === null || options === void 0 ? void 0 : options.minWidth) && value.length < options.minWidth) return false;
111
+ return true;
112
+ }, "Not long enough").refine((value) => {
113
+ var _options$type;
114
+ const sizeLimit = SIZE_LIMITS[(_options$type = options === null || options === void 0 ? void 0 : options.type) !== null && _options$type !== void 0 ? _options$type : "medium"];
115
+ return typeof value === "string" && value.length < sizeLimit;
116
+ }, "Too long");
117
+ };
118
+ const CLASSIFICATION_INPUT_TYPE_SCHEMA = zod.enum(["text", "image"]);
119
+ const CLASSIFICATION_CATEGORIES = [
120
+ "sexual",
121
+ "violence",
122
+ "self-harm",
123
+ "harassment",
124
+ "hate",
125
+ "criminal-activity"
126
+ ];
127
+ const CLASSIFICATION_CATEGORY_SCHEMA = zod.enum(CLASSIFICATION_CATEGORIES);
128
+ zod.object({
129
+ category: CLASSIFICATION_CATEGORY_SCHEMA,
130
+ displayName: saneStringField(),
131
+ description: saneStringField(),
132
+ supportedInputTypes: zod.array(CLASSIFICATION_INPUT_TYPE_SCHEMA).min(1)
133
+ });
134
+ MODERATION_CATEGORY_DEFINITIONS.sexual.summary, MODERATION_CATEGORY_DEFINITIONS.violence.summary, MODERATION_CATEGORY_DEFINITIONS["self-harm"].summary, MODERATION_CATEGORY_DEFINITIONS.harassment.summary, MODERATION_CATEGORY_DEFINITIONS.hate.summary, MODERATION_CATEGORY_DEFINITIONS["criminal-activity"].summary;
135
+ const LIKELIHOOD_SCHEMA = zod.enum([
136
+ "very-unlikely",
137
+ "unlikely",
138
+ "possible",
139
+ "likely",
140
+ "very-likely"
141
+ ]);
142
+ const CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA = zod.enum(["not-supported", "unavailable"]);
143
+ const CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA = zod.partialRecord(zod.enum(MODERATION_QUALIFIERS), zod.discriminatedUnion("status", [zod.object({
144
+ status: zod.literal("evaluated"),
145
+ score: zod.number().min(0).max(1),
146
+ scopeScore: zod.number().min(0).max(1).optional(),
147
+ likelihood: LIKELIHOOD_SCHEMA
148
+ }).strict().refine(({ score, scopeScore }) => scopeScore === void 0 || scopeScore <= score, {
149
+ message: "Only confidence cannot exceed Any confidence",
150
+ path: ["scopeScore"]
151
+ }), zod.object({
152
+ status: zod.literal("not-evaluated"),
153
+ reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA
154
+ }).strict()]));
155
+ const CLASSIFICATION_CATEGORY_REPORT_SCHEMA = zod.discriminatedUnion("status", [
156
+ zod.object({
157
+ status: zod.literal("evaluated"),
158
+ likelihood: LIKELIHOOD_SCHEMA,
159
+ score: zod.number().min(0).max(1),
160
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
161
+ }).strict(),
162
+ zod.object({
163
+ status: zod.literal("partial"),
164
+ likelihood: LIKELIHOOD_SCHEMA,
165
+ score: zod.number().min(0).max(1),
166
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
167
+ }).strict(),
168
+ zod.object({
169
+ status: zod.literal("not-evaluated"),
170
+ reason: CLASSIFICATION_NOT_EVALUATED_REASON_SCHEMA,
171
+ qualifiers: CLASSIFICATION_QUALIFIER_RESULTS_SCHEMA.optional()
172
+ }).strict()
173
+ ]);
174
+ const CATEGORIES_SCHEMA = zod.object({
175
+ sexual: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
176
+ violence: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
177
+ "self-harm": CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
178
+ harassment: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
179
+ hate: CLASSIFICATION_CATEGORY_REPORT_SCHEMA,
180
+ "criminal-activity": CLASSIFICATION_CATEGORY_REPORT_SCHEMA
181
+ }).strict();
182
+ const CLASSIFICATION_LABEL_SCHEMA = zod.object({
183
+ description: saneStringField(),
184
+ score: zod.number(),
185
+ topicalityScore: zod.number().nullish(),
186
+ likelihood: LIKELIHOOD_SCHEMA,
187
+ knowledgeBaseId: saneStringField().nullish()
188
+ });
189
+ zod.object({
190
+ processedAt: zod.number(),
191
+ categories: CATEGORIES_SCHEMA,
192
+ flagged: zod.boolean(),
193
+ score: zod.number(),
194
+ notes: saneStringField().nullish(),
195
+ media: zod.object({
196
+ durationSeconds: zod.number().positive(),
197
+ frameIntervalSeconds: zod.number().positive().optional(),
198
+ sampledFrames: zod.number().int().nonnegative(),
199
+ audioTranscribed: zod.boolean(),
200
+ segments: zod.array(zod.object({
201
+ source: zod.enum([
202
+ "frame",
203
+ "speech",
204
+ "frame-text"
205
+ ]),
206
+ startSeconds: zod.number().nonnegative(),
207
+ endSeconds: zod.number().nonnegative(),
208
+ categories: CATEGORIES_SCHEMA
209
+ }).strict())
210
+ }).strict().optional(),
211
+ labels: zod.array(CLASSIFICATION_LABEL_SCHEMA).nullish()
212
+ }).strict();
213
+ //#endregion
214
+ //#region ../shared/src/MediaTestTriggers.ts
215
+ const MEDIA_TEST_SIGNALS = [...CLASSIFICATION_CATEGORIES, "violence.graphic"];
216
+ const HEX_WORDS = [
217
+ "zero",
218
+ "one",
219
+ "two",
220
+ "three",
221
+ "four",
222
+ "five",
223
+ "six",
224
+ "seven",
225
+ "eight",
226
+ "nine",
227
+ "alpha",
228
+ "bravo",
229
+ "charlie",
230
+ "delta",
231
+ "echo",
232
+ "foxtrot"
233
+ ];
234
+ /** Read this aloud, or render it as large, high-contrast text in a video frame. */
235
+ function generateMediaTestCode(signal, projectId) {
236
+ if (!MEDIA_TEST_SIGNALS.includes(signal)) throw new Error("Unsupported media test signal");
237
+ const suffix = projectId.slice(-8).toLowerCase();
238
+ if (!/^[a-f0-9]{8}$/.test(suffix)) throw new Error("Expected a project ID with an eight-character hexadecimal suffix");
239
+ return `Calm Lens test ${[...suffix].map((character) => HEX_WORDS[Number.parseInt(character, 16)]).join(" ")} ${signal.replace(/[.-]/g, " ")} end test`;
240
+ }
241
+ //#endregion
242
+ //#region src/client/CalmLensWebhooks.ts
243
+ const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
244
+ const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
245
+ const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
246
+ /** Deliveries whose timestamp is further than this from the receiver's clock are rejected. */
247
+ const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300;
248
+ const encoder = new TextEncoder();
249
+ const hmacSha256Hex = function() {
250
+ var _ref = _asyncToGenerator(function* (secret, message) {
251
+ const key = yield crypto.subtle.importKey("raw", encoder.encode(secret), {
252
+ name: "HMAC",
253
+ hash: "SHA-256"
254
+ }, false, ["sign"]);
255
+ const signature = yield crypto.subtle.sign("HMAC", key, encoder.encode(message));
256
+ return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
257
+ });
258
+ return function hmacSha256Hex(_x, _x2) {
259
+ return _ref.apply(this, arguments);
260
+ };
261
+ }();
262
+ /** Constant-time comparison of two strings of the same length. */
263
+ const timingSafeEqual = (a, b) => {
264
+ if (a.length !== b.length) return false;
265
+ let diff = 0;
266
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
267
+ return diff === 0;
268
+ };
269
+ /** `v1=<hex HMAC-SHA256 of "<timestamp>.<body>">`, the `x-calmlens-signature` header value. */
270
+ const createWebhookSignatureHeader = function() {
271
+ var _ref2 = _asyncToGenerator(function* (secret, timestamp, body) {
272
+ return `v1=${yield hmacSha256Hex(secret, `${timestamp}.${body}`)}`;
273
+ });
274
+ return function createWebhookSignatureHeader(_x3, _x4, _x5) {
275
+ return _ref2.apply(this, arguments);
276
+ };
277
+ }();
278
+ (function() {
279
+ var _ref3 = _asyncToGenerator(function* (options) {
280
+ var _options$timestampSec;
281
+ const timestamp = (_options$timestampSec = options.timestampSeconds) !== null && _options$timestampSec !== void 0 ? _options$timestampSec : Math.floor(Date.now() / 1e3);
282
+ return {
283
+ "content-type": "application/json",
284
+ [WEBHOOK_DELIVERY_HEADER]: options.deliveryId,
285
+ [WEBHOOK_TIMESTAMP_HEADER]: String(timestamp),
286
+ [WEBHOOK_SIGNATURE_HEADER]: yield createWebhookSignatureHeader(options.secret, timestamp, options.body)
287
+ };
288
+ });
289
+ return function createWebhookHeaders(_x6) {
290
+ return _ref3.apply(this, arguments);
291
+ };
292
+ })();
293
+ /**
294
+ * Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
295
+ * `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
296
+ * (default 300) of now. Returns `false` for anything missing or malformed.
297
+ */
298
+ function verifyWebhookSignature(_x7) {
299
+ return _verifyWebhookSignature.apply(this, arguments);
300
+ }
301
+ function _verifyWebhookSignature() {
302
+ _verifyWebhookSignature = _asyncToGenerator(function* ({ payload, signature, timestamp, secret, toleranceSeconds = 300, now }) {
303
+ if (!secret || !signature || timestamp === null || timestamp === void 0) return false;
304
+ const timestampText = String(timestamp).trim();
305
+ if (!/^\d+$/.test(timestampText)) return false;
306
+ const nowMs = now === void 0 ? Date.now() : now instanceof Date ? now.getTime() : now;
307
+ if (Math.abs(Math.floor(nowMs / 1e3) - Number(timestampText)) > toleranceSeconds) return false;
308
+ const candidates = signature.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).map((part) => part.slice(3).toLowerCase());
309
+ if (candidates.length === 0) return false;
310
+ const body = typeof payload === "string" ? payload : JSON.stringify(payload);
311
+ const expected = yield hmacSha256Hex(secret, `${timestampText}.${body}`);
312
+ let matched = false;
313
+ for (const candidate of candidates) if (timingSafeEqual(expected, candidate)) matched = true;
314
+ return matched;
315
+ });
316
+ return _verifyWebhookSignature.apply(this, arguments);
317
+ }
318
+ //#endregion
3
319
  //#region src/client/CalmLensClient.ts
4
320
  const _excluded = ["uint8Array"];
5
321
  const _excluded2 = ["buffer"];
@@ -42,7 +358,7 @@ const normalizeAssetOptionsForRequest = (options) => {
42
358
  const toRawUploadBody = (payload) => {
43
359
  const data = assetToData(normalizePayloadForRequest(payload));
44
360
  if (data instanceof Response) {
45
- if (!data.body) throw new Error("Response upload data must have a body");
361
+ if (!data.body) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Response upload data must have a body" });
46
362
  return data.body;
47
363
  }
48
364
  if (data instanceof ArrayBuffer || data instanceof Blob) return data;
@@ -60,8 +376,8 @@ const assertValidUploadMimeType = (mimeType) => {
60
376
  };
61
377
  const isImageMimeType = (mimeType) => mimeType.toLowerCase().startsWith("image/");
62
378
  const prepareSubmitAssetOptions = (options) => {
63
- if (!("content" in options) && !("url" in options) && !("part" in options)) throw new Error("Either file content, URL, or multipart part is required");
64
- if (!options.name) throw new Error("Asset name is required");
379
+ 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" });
380
+ if (!options.name) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset name is required" });
65
381
  if (!("part" in options) && "isFinal" in options) throw calmLensError(PUBLIC_ERROR_CODES.INVALID_UPLOAD_PAYLOAD, { message: "isFinal is only valid for multipart uploads" });
66
382
  if ("part" in options && options.part.partNumber && options.part.partNumber > 1) throw calmLensError(PUBLIC_ERROR_CODES.USE_UPLOAD_PART);
67
383
  if ("content" in options) {
@@ -76,8 +392,8 @@ const prepareSubmitAssetOptions = (options) => {
76
392
  assertValidUploadMimeType(options.part.type);
77
393
  const partSizeInBytes = (_options$part$sizeInB = options.part.sizeInBytes) !== null && _options$part$sizeInB !== void 0 ? _options$part$sizeInB : getAssetPayloadByteLength(options.part);
78
394
  if (isImageMimeType(options.part.type) && partSizeInBytes !== void 0) {
79
- if (partSizeInBytes > 20971520) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
80
- if (options.part.isFinal && partSizeInBytes < 10485760) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
395
+ if (partSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
396
+ if (options.part.isFinal && partSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
81
397
  }
82
398
  const validation = validateAssetPayload(options.part, {
83
399
  multipart: true,
@@ -88,7 +404,7 @@ const prepareSubmitAssetOptions = (options) => {
88
404
  return options;
89
405
  };
90
406
  const appendCdnSelector = (url, options) => {
91
- if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
407
+ if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
92
408
  if (options.lens) return `${url}/@${encodeURIComponent(options.lens)}`;
93
409
  if (!options.transform) return url;
94
410
  return `${url}/${encodeURI(options.transform.replace(/^\/+/, ""))}`;
@@ -108,8 +424,42 @@ const getEnsureLensCacheKey = (options) => {
108
424
  const withApiKeyHeader = (init, apiKey) => {
109
425
  const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
110
426
  headers.set("X-Api-Key", apiKey);
111
- return _objectSpread2(_objectSpread2({}, init), {}, { headers: Object.fromEntries(headers.entries()) });
427
+ return _objectSpread2(_objectSpread2({}, init), {}, {
428
+ redirect: "error",
429
+ headers: Object.fromEntries(headers.entries())
430
+ });
112
431
  };
432
+ const requestSignal = (options, signal) => {
433
+ var _options$timeoutMs;
434
+ const signals = [
435
+ options.signal,
436
+ signal,
437
+ AbortSignal.timeout((_options$timeoutMs = options.timeoutMs) !== null && _options$timeoutMs !== void 0 ? _options$timeoutMs : 12e4)
438
+ ].filter((value) => value != null);
439
+ return AbortSignal.any(signals);
440
+ };
441
+ const safeFetch = (fetchImpl, options) => function() {
442
+ var _ref = _asyncToGenerator(function* (input, init) {
443
+ var _init$signal;
444
+ const signal = requestSignal(options, (_init$signal = init === null || init === void 0 ? void 0 : init.signal) !== null && _init$signal !== void 0 ? _init$signal : input instanceof Request ? input.signal : void 0);
445
+ try {
446
+ signal.throwIfAborted();
447
+ return yield fetchImpl(input, _objectSpread2(_objectSpread2({}, init), {}, {
448
+ redirect: "error",
449
+ signal
450
+ }));
451
+ } catch (cause) {
452
+ var _signal$reason;
453
+ throw calmLensError({ id: signal.aborted ? ((_signal$reason = signal.reason) === null || _signal$reason === void 0 ? void 0 : _signal$reason.name) === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" : "sdk/transport-error" }, {
454
+ message: signal.aborted ? "Request aborted" : "Request failed",
455
+ cause
456
+ });
457
+ }
458
+ });
459
+ return function(_x, _x2) {
460
+ return _ref.apply(this, arguments);
461
+ };
462
+ }();
113
463
  const createApi = (options) => {
114
464
  return new Api({
115
465
  name: "Calm Lens",
@@ -123,13 +473,24 @@ const createApi = (options) => {
123
473
  if (context.error) throw normalizeApiError(context.error);
124
474
  } }
125
475
  ],
126
- requestBackend: options.requestBackend
476
+ 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 FetchRequestBackend(safeFetch(globalThis.fetch, options))
127
477
  });
128
478
  };
129
479
  const isApiErrorPayload = (value) => {
130
480
  return !!value && typeof value === "object" && typeof value.code === "string";
131
481
  };
132
482
  const normalizeApiError = (error) => {
483
+ let cause = error;
484
+ const seen = /* @__PURE__ */ new Set();
485
+ while (cause instanceof Error && !seen.has(cause)) {
486
+ seen.add(cause);
487
+ if (cause instanceof CalmLensError) return cause;
488
+ if (cause.name === "AbortError" || cause.name === "TimeoutError") return calmLensError({ id: cause.name === "TimeoutError" ? "sdk/timeout" : "sdk/cancelled" }, {
489
+ message: "Request aborted",
490
+ cause
491
+ });
492
+ cause = cause.cause;
493
+ }
133
494
  const response = error instanceof Error ? getErrorResponse(error) : void 0;
134
495
  if (error instanceof Error && isRequestError(error) && isApiErrorPayload(response === null || response === void 0 ? void 0 : response.data)) {
135
496
  const { code, message, details, traceId } = response.data;
@@ -138,13 +499,20 @@ const normalizeApiError = (error) => {
138
499
  defaultMessage: message
139
500
  }, {
140
501
  message,
502
+ status: response === null || response === void 0 ? void 0 : response.status,
503
+ cause: error,
141
504
  details: _objectSpread2(_objectSpread2({}, details), {}, {
142
505
  traceId,
143
506
  network: true
144
507
  })
145
508
  });
146
509
  }
147
- return error;
510
+ if (error instanceof CalmLensError) return error;
511
+ return calmLensError({ id: response ? response.ok ? "sdk/invalid-response" : "sdk/http-error" : "sdk/transport-error" }, {
512
+ message: response ? `HTTP ${response.status}` : error.message,
513
+ status: response === null || response === void 0 ? void 0 : response.status,
514
+ cause: error
515
+ });
148
516
  };
149
517
  const createEndpoints = (api) => {
150
518
  const getFolders = api.endpoint().paramsOf().responseOf().build({
@@ -256,29 +624,35 @@ const createEndpoints = (api) => {
256
624
  getEvents
257
625
  };
258
626
  };
259
- var CalmLensClient = class {
627
+ var CalmLensClient = class CalmLensClient {
260
628
  /**
261
- * Validates a webhook signature to ensure the webhook payload is authentic.
629
+ * Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
630
+ * `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
631
+ * more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
262
632
  *
263
- * @param payload - The webhook payload (string or object)
264
- * @param signatureHex - The signature from the 'x-calmlens-signature' header
265
- * @param secret - The webhook secret used to sign the payload
266
- * @returns Promise<boolean> - True if the signature is valid, false otherwise
633
+ * @param options.payload - The raw request body, exactly as received (verify before parsing)
634
+ * @param options.signature - The 'x-calmlens-signature' header value
635
+ * @param options.timestamp - The 'x-calmlens-timestamp' header value
636
+ * @param options.secret - The connector's signing secret
637
+ * @param options.toleranceSeconds - Allowed clock distance in seconds (default 300)
638
+ * @param options.now - Override the current time (Date or epoch milliseconds), for tests
639
+ * @returns Promise<boolean> - True if the signature is valid and fresh, false otherwise
267
640
  *
268
641
  * @example
269
642
  * ```javascript
270
- * // In your webhook handler
271
- * const signature = req.headers['x-calmlens-signature'];
272
- * const payload = req.body;
643
+ * // In your webhook handler (e.g. a Fetch API Request)
644
+ * const payload = await request.text();
273
645
  * const isValid = await CalmLensClient.verifyWebhookSignature({
274
646
  * payload,
275
- * signatureHex: signature,
647
+ * signature: request.headers.get('x-calmlens-signature'),
648
+ * timestamp: request.headers.get('x-calmlens-timestamp'),
276
649
  * secret: WEBHOOK_SECRET,
277
650
  * });
278
651
  *
279
652
  * if (!isValid) {
280
- * return res.status(401).send('Unauthorized');
653
+ * return new Response('Unauthorized', { status: 401 });
281
654
  * }
655
+ * const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
282
656
  * ```
283
657
  */
284
658
  static verifyWebhookSignature(options) {
@@ -293,19 +667,28 @@ var CalmLensClient = class {
293
667
  this.pendingEnsureLenses = /* @__PURE__ */ new Map();
294
668
  this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
295
669
  this.multipartUploadQueues = /* @__PURE__ */ new Map();
296
- if (!options.apiKey) throw new Error("API key is required");
297
- if (!options.projectId) throw new Error("Project ID is required");
670
+ if (!options.apiKey) throw calmLensError({ id: "upload/invalid-payload" }, { message: "API key is required" });
671
+ if (!options.projectId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Project ID is required" });
672
+ 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" });
673
+ this.options = _objectSpread2({}, options);
298
674
  this.options.baseUrl = (_this$options$baseUrl = this.options.baseUrl) !== null && _this$options$baseUrl !== void 0 ? _this$options$baseUrl : `https://api.${DOMAIN}/v1`;
299
675
  this.options.cdnBaseUrl = (_this$options$cdnBase = this.options.cdnBaseUrl) !== null && _this$options$cdnBase !== void 0 ? _this$options$cdnBase : `https://cdn.${DOMAIN}/v1`;
300
676
  this.api = createApi(this.options);
301
677
  this.endpoints = createEndpoints(this.api);
302
678
  }
679
+ /** Scope cancellation/timeout to an operation without changing this client's defaults. */
680
+ withRequestOptions(options) {
681
+ const client = new CalmLensClient(_objectSpread2(_objectSpread2({}, this.options), options));
682
+ client.multipartUploadQueues = this.multipartUploadQueues;
683
+ client.multipartImageUploadSizes = this.multipartImageUploadSizes;
684
+ return client;
685
+ }
303
686
  getUploadFetch() {
304
- var _this$options$request, _ref, _this$options$uploadF;
687
+ var _this$options$request, _ref2, _this$options$uploadF;
305
688
  const requestBackendFetch = (_this$options$request = this.options.requestBackend) === null || _this$options$request === void 0 ? void 0 : _this$options$request.fetch;
306
- const fetchImpl = (_ref = (_this$options$uploadF = this.options.uploadFetch) !== null && _this$options$uploadF !== void 0 ? _this$options$uploadF : requestBackendFetch) !== null && _ref !== void 0 ? _ref : globalThis.fetch;
689
+ const fetchImpl = (_ref2 = (_this$options$uploadF = this.options.uploadFetch) !== null && _this$options$uploadF !== void 0 ? _this$options$uploadF : requestBackendFetch) !== null && _ref2 !== void 0 ? _ref2 : globalThis.fetch;
307
690
  if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
308
- return fetchImpl;
691
+ return safeFetch(fetchImpl, this.options);
309
692
  }
310
693
  submitRawAssetUpload(options, queue) {
311
694
  var _this = this;
@@ -390,20 +773,43 @@ var CalmLensClient = class {
390
773
  }
391
774
  parseRawUploadResponse(response) {
392
775
  return _asyncToGenerator(function* () {
393
- const data = yield response.json().catch(() => void 0);
776
+ let data;
777
+ try {
778
+ data = yield response.json();
779
+ } catch (cause) {
780
+ 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" }, {
781
+ message: `Invalid JSON response (HTTP ${response.status})`,
782
+ status: response.status,
783
+ cause
784
+ });
785
+ }
394
786
  if (!response.ok) {
395
787
  if (isApiErrorPayload(data)) throw calmLensError({
396
788
  id: data.code,
397
789
  defaultMessage: data.message
398
790
  }, {
399
791
  message: data.message,
792
+ status: response.status,
400
793
  details: _objectSpread2(_objectSpread2({}, data.details), {}, {
401
794
  traceId: data.traceId,
402
795
  network: true
403
796
  })
404
797
  });
405
- throw new Error(`CalmLens upload failed with status ${response.status}`);
798
+ throw calmLensError({ id: "sdk/http-error" }, {
799
+ message: `HTTP ${response.status}`,
800
+ status: response.status
801
+ });
406
802
  }
803
+ if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" || !data.id || !("status" in data) || ![
804
+ "uploading",
805
+ "pending",
806
+ "approved",
807
+ "rejected",
808
+ "error"
809
+ ].includes(String(data.status))) throw calmLensError({ id: "sdk/invalid-response" }, {
810
+ message: "Expected an asset response",
811
+ status: response.status
812
+ });
407
813
  return data;
408
814
  })();
409
815
  }
@@ -414,10 +820,10 @@ var CalmLensClient = class {
414
820
  * Create a CDN URL for asset content or previews.
415
821
  * Private assets require an authenticated request or signed URL.
416
822
  */
417
- getAssetUrl: (_ref2) => {
823
+ getAssetUrl: (_ref3) => {
418
824
  var _options$resource;
419
- let { assetIdentifier } = _ref2, options = _objectWithoutProperties(_ref2, _excluded3);
420
- if (!assetIdentifier) throw new Error("Asset identifier is required");
825
+ let { assetIdentifier } = _ref3, options = _objectWithoutProperties(_ref3, _excluded3);
826
+ if (!assetIdentifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
421
827
  const resource = (_options$resource = options.resource) !== null && _options$resource !== void 0 ? _options$resource : "content";
422
828
  const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
423
829
  return appendCdnSelector(url, options);
@@ -427,33 +833,27 @@ var CalmLensClient = class {
427
833
  * Private assets are authenticated with the client's API key.
428
834
  */
429
835
  serve: function() {
430
- var _ref4 = _asyncToGenerator(function* (_ref3) {
836
+ var _ref5 = _asyncToGenerator(function* (_ref4) {
431
837
  var _this$options$cdnFetc;
432
- let { assetIdentifier, init } = _ref3, urlOptions = _objectWithoutProperties(_ref3, _excluded4);
838
+ let { assetIdentifier, init } = _ref4, urlOptions = _objectWithoutProperties(_ref4, _excluded4);
433
839
  const fetchImpl = (_this$options$cdnFetc = _this3.options.cdnFetch) !== null && _this$options$cdnFetc !== void 0 ? _this$options$cdnFetc : globalThis.fetch;
434
840
  if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
435
- return fetchImpl(_this3.cdn.getAssetUrl(_objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
841
+ return safeFetch(fetchImpl, _this3.options)(_this3.cdn.getAssetUrl(_objectSpread2({ assetIdentifier }, urlOptions)), withApiKeyHeader(init, _this3.options.apiKey));
436
842
  });
437
- return function serve(_x) {
438
- return _ref4.apply(this, arguments);
843
+ return function serve(_x3) {
844
+ return _ref5.apply(this, arguments);
439
845
  };
440
846
  }()
441
847
  };
442
848
  }
443
849
  get text() {
444
850
  var _this4 = this;
445
- return {
446
- /**
447
- * Moderate a short piece of text, such as a comment, caption or bio, and wait for the
448
- * decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
449
- * The text is not retained after classification unless `processingOptions` says so.
450
- */
451
- moderate: function() {
452
- var _ref5 = _asyncToGenerator(function* (options) {
453
- return _this4.assets.analyze(toTextAssetOptions(options));
851
+ return { moderate: function() {
852
+ var _ref6 = _asyncToGenerator(function* (options) {
853
+ return _this4.assets.moderate(toTextAssetOptions(options));
454
854
  });
455
- return function moderate(_x2) {
456
- return _ref5.apply(this, arguments);
855
+ return function moderate(_x4) {
856
+ return _ref6.apply(this, arguments);
457
857
  };
458
858
  }() };
459
859
  }
@@ -466,15 +866,15 @@ moderate: function() {
466
866
  * @returns Promise with paginated assets
467
867
  */
468
868
  list: function() {
469
- var _ref6 = _asyncToGenerator(function* (options) {
869
+ var _ref7 = _asyncToGenerator(function* (options) {
470
870
  var _options$pageIndex;
471
871
  return (yield _this5.endpoints.getAssetsPage.submit({
472
872
  params: { projectId: _this5.options.projectId },
473
873
  query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex = options.pageIndex) !== null && _options$pageIndex !== void 0 ? _options$pageIndex : 0 })
474
874
  })).data;
475
875
  });
476
- return function list(_x3) {
477
- return _ref6.apply(this, arguments);
876
+ return function list(_x5) {
877
+ return _ref7.apply(this, arguments);
478
878
  };
479
879
  }(),
480
880
  /**
@@ -483,25 +883,25 @@ moderate: function() {
483
883
  * @returns Promise with asset data
484
884
  */
485
885
  retrieve: function() {
486
- var _ref7 = _asyncToGenerator(function* ({ assetId }) {
487
- if (!assetId) throw new Error("Asset ID is required");
886
+ var _ref8 = _asyncToGenerator(function* ({ assetId }) {
887
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
488
888
  return (yield _this5.endpoints.getAsset.submit({ params: { assetId } })).data;
489
889
  });
490
- return function retrieve(_x4) {
491
- return _ref7.apply(this, arguments);
890
+ return function retrieve(_x6) {
891
+ return _ref8.apply(this, arguments);
492
892
  };
493
893
  }(),
494
894
  update: function() {
495
- var _ref9 = _asyncToGenerator(function* (_ref8) {
496
- let { assetId } = _ref8, body = _objectWithoutProperties(_ref8, _excluded5);
497
- if (!assetId) throw new Error("Asset ID is required");
895
+ var _ref10 = _asyncToGenerator(function* (_ref9) {
896
+ let { assetId } = _ref9, body = _objectWithoutProperties(_ref9, _excluded5);
897
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
498
898
  return (yield _this5.endpoints.patchAsset.submit({
499
899
  params: { assetId },
500
900
  body
501
901
  })).data;
502
902
  });
503
- return function update(_x5) {
504
- return _ref9.apply(this, arguments);
903
+ return function update(_x7) {
904
+ return _ref10.apply(this, arguments);
505
905
  };
506
906
  }(),
507
907
  /**
@@ -511,17 +911,17 @@ moderate: function() {
511
911
  * @returns Promise with paginated child assets
512
912
  */
513
913
  listChildren: function() {
514
- var _ref11 = _asyncToGenerator(function* (_ref10) {
914
+ var _ref12 = _asyncToGenerator(function* (_ref11) {
515
915
  var _options$pageIndex2;
516
- let { assetId } = _ref10, options = _objectWithoutProperties(_ref10, _excluded6);
517
- if (!assetId) throw new Error("Asset ID is required");
916
+ let { assetId } = _ref11, options = _objectWithoutProperties(_ref11, _excluded6);
917
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
518
918
  return (yield _this5.endpoints.getAssetChildren.submit({
519
919
  params: { assetId },
520
920
  query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex2 = options.pageIndex) !== null && _options$pageIndex2 !== void 0 ? _options$pageIndex2 : 0 })
521
921
  })).data;
522
922
  });
523
- return function listChildren(_x6) {
524
- return _ref11.apply(this, arguments);
923
+ return function listChildren(_x8) {
924
+ return _ref12.apply(this, arguments);
525
925
  };
526
926
  }(),
527
927
  /**
@@ -531,7 +931,7 @@ moderate: function() {
531
931
  * @returns Promise with created asset
532
932
  */
533
933
  create: function() {
534
- var _ref12 = _asyncToGenerator(function* (options) {
934
+ var _ref13 = _asyncToGenerator(function* (options) {
535
935
  const body = prepareSubmitAssetOptions(options);
536
936
  if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, true);
537
937
  return (yield _this5.endpoints.postUploadAsset.submit({
@@ -540,19 +940,20 @@ moderate: function() {
540
940
  query: { queue: true }
541
941
  })).data;
542
942
  });
543
- return function create(_x7) {
544
- return _ref12.apply(this, arguments);
943
+ return function create(_x9) {
944
+ return _ref13.apply(this, arguments);
545
945
  };
546
946
  }(),
547
947
  /**
548
- * Submit a new asset and analyze it synchronously
948
+ * Submit a new asset and moderate it synchronously
549
949
  * The asset will be classified immediately before the response is returned.
550
950
  * This may take longer but ensures the asset is fully processed.
551
951
  * @param options - Asset submission options
552
952
  * @returns Promise with created and analyzed asset
553
953
  */
554
- analyze: function() {
555
- var _ref13 = _asyncToGenerator(function* (options) {
954
+ moderate: function() {
955
+ var _ref14 = _asyncToGenerator(function* (options) {
956
+ 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" });
556
957
  const body = prepareSubmitAssetOptions(options);
557
958
  if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, false);
558
959
  return (yield _this5.endpoints.postUploadAsset.submit({
@@ -561,8 +962,8 @@ moderate: function() {
561
962
  query: { queue: false }
562
963
  })).data;
563
964
  });
564
- return function analyze(_x8) {
565
- return _ref13.apply(this, arguments);
965
+ return function moderate(_x10) {
966
+ return _ref14.apply(this, arguments);
566
967
  };
567
968
  }(),
568
969
  /**
@@ -572,10 +973,10 @@ moderate: function() {
572
973
  * @returns Promise with asset data
573
974
  */
574
975
  uploadPart: function() {
575
- var _ref14 = _asyncToGenerator(function* ({ assetId, part }) {
976
+ var _ref15 = _asyncToGenerator(function* ({ assetId, part }) {
576
977
  var _part$sizeInBytes3, _this$multipartUpload;
577
- if (!assetId) throw new Error("Asset ID is required");
578
- if (!part) throw new Error("Part options are required");
978
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
979
+ if (!part) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Part options are required" });
579
980
  const validation = validateAssetPayload(part, {
580
981
  multipart: true,
581
982
  isFinal: part.isFinal
@@ -585,13 +986,13 @@ moderate: function() {
585
986
  const partSizeInBytes = (_part$sizeInBytes3 = part.sizeInBytes) !== null && _part$sizeInBytes3 !== void 0 ? _part$sizeInBytes3 : getAssetPayloadByteLength(part);
586
987
  if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
587
988
  const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
588
- if (totalSizeInBytes > 20971520) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
589
- if (part.isFinal && totalSizeInBytes < 10485760) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
989
+ if (totalSizeInBytes > MAX_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_LARGE);
990
+ if (part.isFinal && totalSizeInBytes < MIN_MULTIPART_IMAGE_UPLOAD_BYTES) throw calmLensError(PUBLIC_ERROR_CODES.MULTIPART_IMAGE_TOO_SMALL);
590
991
  }
591
992
  return yield _this5.submitRawAssetPart(assetId, part, (_this$multipartUpload = _this5.multipartUploadQueues.get(assetId)) !== null && _this$multipartUpload !== void 0 ? _this$multipartUpload : false);
592
993
  });
593
- return function uploadPart(_x9) {
594
- return _ref14.apply(this, arguments);
994
+ return function uploadPart(_x11) {
995
+ return _ref15.apply(this, arguments);
595
996
  };
596
997
  }(),
597
998
  /**
@@ -600,11 +1001,11 @@ moderate: function() {
600
1001
  * auth cookies or API keys to the CDN on every media request.
601
1002
  */
602
1003
  createSignedUrl: function() {
603
- var _ref16 = _asyncToGenerator(function* (_ref15) {
1004
+ var _ref17 = _asyncToGenerator(function* (_ref16) {
604
1005
  var _options$resource2, _options$expiresInSec;
605
- let { assetId } = _ref15, options = _objectWithoutProperties(_ref15, _excluded7);
606
- if (!assetId) throw new Error("Asset ID is required");
607
- if (options.lens && options.transform) throw new Error("Specify either a lens or a transform, not both");
1006
+ let { assetId } = _ref16, options = _objectWithoutProperties(_ref16, _excluded7);
1007
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
1008
+ if (options.lens && options.transform) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Specify either a lens or a transform, not both" });
608
1009
  return (yield _this5.endpoints.postAssetSignedUrl.submit({
609
1010
  body: {
610
1011
  resource: (_options$resource2 = options.resource) !== null && _options$resource2 !== void 0 ? _options$resource2 : "content",
@@ -615,20 +1016,20 @@ moderate: function() {
615
1016
  params: { assetId }
616
1017
  })).data;
617
1018
  });
618
- return function createSignedUrl(_x10) {
619
- return _ref16.apply(this, arguments);
1019
+ return function createSignedUrl(_x12) {
1020
+ return _ref17.apply(this, arguments);
620
1021
  };
621
1022
  }(),
622
1023
  move: function() {
623
- var _ref17 = _asyncToGenerator(function* ({ assetId, folderId }) {
624
- if (!assetId) throw new Error("Asset ID is required");
1024
+ var _ref18 = _asyncToGenerator(function* ({ assetId, folderId }) {
1025
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
625
1026
  return (yield _this5.endpoints.moveAsset.submit({
626
1027
  params: { assetId },
627
1028
  body: { folderId }
628
1029
  })).data;
629
1030
  });
630
- return function move(_x11) {
631
- return _ref17.apply(this, arguments);
1031
+ return function move(_x13) {
1032
+ return _ref18.apply(this, arguments);
632
1033
  };
633
1034
  }(),
634
1035
  /**
@@ -636,12 +1037,12 @@ moderate: function() {
636
1037
  * moderated like a new upload; its content must still be stored.
637
1038
  */
638
1039
  retry: function() {
639
- var _ref18 = _asyncToGenerator(function* ({ assetId }) {
640
- if (!assetId) throw new Error("Asset ID is required");
1040
+ var _ref19 = _asyncToGenerator(function* ({ assetId }) {
1041
+ if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
641
1042
  return (yield _this5.endpoints.retryAsset.submit({ params: { assetId } })).data;
642
1043
  });
643
- return function retry(_x12) {
644
- return _ref18.apply(this, arguments);
1044
+ return function retry(_x14) {
1045
+ return _ref19.apply(this, arguments);
645
1046
  };
646
1047
  }()
647
1048
  };
@@ -651,17 +1052,18 @@ moderate: function() {
651
1052
  return {
652
1053
  /**
653
1054
  * List project events after a cursor, oldest first. Call without `after` to get a cursor
654
- * for "now", then poll with the returned `cursor`. Event bodies match webhook deliveries.
1055
+ * for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
1056
+ * reshaped as `{ id, type, createdAt, projectId, data }`.
655
1057
  */
656
1058
  list: function() {
657
- var _ref19 = _asyncToGenerator(function* (options = {}) {
1059
+ var _ref20 = _asyncToGenerator(function* (options = {}) {
658
1060
  return (yield _this6.endpoints.getEvents.submit({
659
1061
  params: { projectId: _this6.options.projectId },
660
1062
  query: options
661
1063
  })).data;
662
1064
  });
663
1065
  return function list() {
664
- return _ref19.apply(this, arguments);
1066
+ return _ref20.apply(this, arguments);
665
1067
  };
666
1068
  }() };
667
1069
  }
@@ -669,65 +1071,65 @@ list: function() {
669
1071
  var _this7 = this;
670
1072
  return {
671
1073
  list: function() {
672
- var _ref20 = _asyncToGenerator(function* () {
1074
+ var _ref21 = _asyncToGenerator(function* () {
673
1075
  return (yield _this7.endpoints.getFolders.submit({ params: { projectId: _this7.options.projectId } })).data.folders;
674
1076
  });
675
1077
  return function list() {
676
- return _ref20.apply(this, arguments);
1078
+ return _ref21.apply(this, arguments);
677
1079
  };
678
1080
  }(),
679
1081
  retrieve: function() {
680
- var _ref21 = _asyncToGenerator(function* ({ folderId }) {
681
- if (!folderId) throw new Error("Folder ID is required");
1082
+ var _ref22 = _asyncToGenerator(function* ({ folderId }) {
1083
+ if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
682
1084
  return (yield _this7.endpoints.getFolder.submit({ params: { folderId } })).data;
683
1085
  });
684
- return function retrieve(_x13) {
685
- return _ref21.apply(this, arguments);
1086
+ return function retrieve(_x15) {
1087
+ return _ref22.apply(this, arguments);
686
1088
  };
687
1089
  }(),
688
1090
  create: function() {
689
- var _ref22 = _asyncToGenerator(function* (options) {
1091
+ var _ref23 = _asyncToGenerator(function* (options) {
690
1092
  return (yield _this7.endpoints.postFolder.submit({
691
1093
  params: { projectId: _this7.options.projectId },
692
1094
  body: options
693
1095
  })).data;
694
1096
  });
695
- return function create(_x14) {
696
- return _ref22.apply(this, arguments);
1097
+ return function create(_x16) {
1098
+ return _ref23.apply(this, arguments);
697
1099
  };
698
1100
  }(),
699
1101
  update: function() {
700
- var _ref24 = _asyncToGenerator(function* (_ref23) {
701
- let { folderId } = _ref23, body = _objectWithoutProperties(_ref23, _excluded8);
702
- if (!folderId) throw new Error("Folder ID is required");
1102
+ var _ref25 = _asyncToGenerator(function* (_ref24) {
1103
+ let { folderId } = _ref24, body = _objectWithoutProperties(_ref24, _excluded8);
1104
+ if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
703
1105
  return (yield _this7.endpoints.patchFolder.submit({
704
1106
  params: { folderId },
705
1107
  body
706
1108
  })).data;
707
1109
  });
708
- return function update(_x15) {
709
- return _ref24.apply(this, arguments);
1110
+ return function update(_x17) {
1111
+ return _ref25.apply(this, arguments);
710
1112
  };
711
1113
  }(),
712
1114
  delete: function() {
713
- var _ref25 = _asyncToGenerator(function* ({ folderId }) {
714
- if (!folderId) throw new Error("Folder ID is required");
1115
+ var _ref26 = _asyncToGenerator(function* ({ folderId }) {
1116
+ if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
715
1117
  yield _this7.endpoints.deleteFolder.submit({ params: { folderId } });
716
1118
  });
717
- return function _delete(_x16) {
718
- return _ref25.apply(this, arguments);
1119
+ return function _delete(_x18) {
1120
+ return _ref26.apply(this, arguments);
719
1121
  };
720
1122
  }(),
721
1123
  move: function() {
722
- var _ref26 = _asyncToGenerator(function* ({ folderId, parentId }) {
723
- if (!folderId) throw new Error("Folder ID is required");
1124
+ var _ref27 = _asyncToGenerator(function* ({ folderId, parentId }) {
1125
+ if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
724
1126
  return (yield _this7.endpoints.moveFolder.submit({
725
1127
  params: { folderId },
726
1128
  body: { parentId }
727
1129
  })).data;
728
1130
  });
729
- return function move(_x17) {
730
- return _ref26.apply(this, arguments);
1131
+ return function move(_x19) {
1132
+ return _ref27.apply(this, arguments);
731
1133
  };
732
1134
  }()
733
1135
  };
@@ -739,7 +1141,7 @@ list: function() {
739
1141
  ensureLens(options) {
740
1142
  var _this8 = this;
741
1143
  return _asyncToGenerator(function* () {
742
- if (!options.identifier) throw new Error("Lens identifier is required");
1144
+ if (!options.identifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
743
1145
  const [lens] = yield _this8.ensureLenses({ lenses: [options] });
744
1146
  return lens;
745
1147
  })();
@@ -751,8 +1153,8 @@ list: function() {
751
1153
  ensureLenses({ lenses }) {
752
1154
  var _this9 = this;
753
1155
  return _asyncToGenerator(function* () {
754
- if (lenses.length === 0) throw new Error("At least one lens is required");
755
- if (lenses.some((option) => !option.identifier)) throw new Error("Lens identifier is required");
1156
+ if (lenses.length === 0) throw calmLensError({ id: "upload/invalid-payload" }, { message: "At least one lens is required" });
1157
+ if (lenses.some((option) => !option.identifier)) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
756
1158
  const missingOptions = [];
757
1159
  const missingKeys = /* @__PURE__ */ new Set();
758
1160
  for (const option of lenses) {
@@ -783,7 +1185,7 @@ list: function() {
783
1185
  });
784
1186
  for (const [index, lens] of result.data.lenses.entries()) {
785
1187
  const optionsForLens = options[index];
786
- if (!optionsForLens) throw new Error("CalmLens returned an unexpected lens response");
1188
+ if (!optionsForLens) throw calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
787
1189
  for (const [cacheKey, cachedLens] of _this10.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) _this10.ensuredLenses.delete(cacheKey);
788
1190
  _this10.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
789
1191
  }
@@ -791,4 +1193,4 @@ list: function() {
791
1193
  }
792
1194
  };
793
1195
  //#endregion
794
- export { CalmLensClient, CalmLensError, verifyWebhookSignature };
1196
+ export { CalmLensClient, CalmLensError, MEDIA_TEST_SIGNALS, WEBHOOK_DELIVERY_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, WEBHOOK_TIMESTAMP_HEADER, generateMediaTestCode, verifyWebhookSignature };