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