calmlens 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -39
- package/bin/calmlens.js +240 -79
- package/cjs/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/cjs/{CalmLensUtils-DocJkqQj.js → CalmLensUtils-0QaxbI3A.js} +105 -93
- package/cjs/index.d.ts +2607 -24
- package/cjs/index.js +548 -120
- package/cjs/testing.d.ts +3 -2
- package/cjs/testing.js +39 -45
- package/esm/CalmLensTypes-DG_kHVqY.d.ts +3521 -0
- package/esm/{CalmLensUtils--N_91gHC.js → CalmLensUtils-BQEgxGWk.js} +78 -88
- package/esm/index.d.ts +2607 -24
- package/esm/index.js +541 -120
- package/esm/testing.d.ts +3 -2
- package/esm/testing.js +38 -22
- package/package.json +2 -2
- package/cjs/CalmLensTypes-Bnq4u8HJ.d.ts +0 -1758
- package/esm/CalmLensTypes-Bnq4u8HJ.d.ts +0 -1758
package/esm/index.js
CHANGED
|
@@ -1,5 +1,321 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
import
|
|
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
|
|
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
|
|
64
|
-
if (!options.name) throw
|
|
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 >
|
|
80
|
-
if (options.part.isFinal && partSizeInBytes <
|
|
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
|
|
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), {}, {
|
|
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({
|
|
@@ -217,6 +585,11 @@ const createEndpoints = (api) => {
|
|
|
217
585
|
method: "post",
|
|
218
586
|
path: "/assets/:assetId/move"
|
|
219
587
|
});
|
|
588
|
+
const retryAsset = api.endpoint().paramsOf().responseOf().build({
|
|
589
|
+
id: "retryAsset",
|
|
590
|
+
method: "post",
|
|
591
|
+
path: "/assets/:assetId/retry"
|
|
592
|
+
});
|
|
220
593
|
const getEvents = api.endpoint().paramsOf().queryOf().responseOf().build({
|
|
221
594
|
id: "getEvents",
|
|
222
595
|
method: "get",
|
|
@@ -237,6 +610,7 @@ const createEndpoints = (api) => {
|
|
|
237
610
|
postAssetSignedUrl,
|
|
238
611
|
postAssetPart,
|
|
239
612
|
moveAsset,
|
|
613
|
+
retryAsset,
|
|
240
614
|
ensureLens: api.endpoint().bodyOf().paramsOf().responseOf().build({
|
|
241
615
|
id: "ensureLens",
|
|
242
616
|
method: "put",
|
|
@@ -250,29 +624,35 @@ const createEndpoints = (api) => {
|
|
|
250
624
|
getEvents
|
|
251
625
|
};
|
|
252
626
|
};
|
|
253
|
-
var CalmLensClient = class {
|
|
627
|
+
var CalmLensClient = class CalmLensClient {
|
|
254
628
|
/**
|
|
255
|
-
*
|
|
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.
|
|
256
632
|
*
|
|
257
|
-
* @param payload - The
|
|
258
|
-
* @param
|
|
259
|
-
* @param
|
|
260
|
-
* @
|
|
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
|
|
261
640
|
*
|
|
262
641
|
* @example
|
|
263
642
|
* ```javascript
|
|
264
|
-
* // In your webhook handler
|
|
265
|
-
* const
|
|
266
|
-
* const payload = req.body;
|
|
643
|
+
* // In your webhook handler (e.g. a Fetch API Request)
|
|
644
|
+
* const payload = await request.text();
|
|
267
645
|
* const isValid = await CalmLensClient.verifyWebhookSignature({
|
|
268
646
|
* payload,
|
|
269
|
-
*
|
|
647
|
+
* signature: request.headers.get('x-calmlens-signature'),
|
|
648
|
+
* timestamp: request.headers.get('x-calmlens-timestamp'),
|
|
270
649
|
* secret: WEBHOOK_SECRET,
|
|
271
650
|
* });
|
|
272
651
|
*
|
|
273
652
|
* if (!isValid) {
|
|
274
|
-
* return
|
|
653
|
+
* return new Response('Unauthorized', { status: 401 });
|
|
275
654
|
* }
|
|
655
|
+
* const event = JSON.parse(payload); // { id, type, createdAt, projectId, data }
|
|
276
656
|
* ```
|
|
277
657
|
*/
|
|
278
658
|
static verifyWebhookSignature(options) {
|
|
@@ -287,19 +667,28 @@ var CalmLensClient = class {
|
|
|
287
667
|
this.pendingEnsureLenses = /* @__PURE__ */ new Map();
|
|
288
668
|
this.multipartImageUploadSizes = /* @__PURE__ */ new Map();
|
|
289
669
|
this.multipartUploadQueues = /* @__PURE__ */ new Map();
|
|
290
|
-
if (!options.apiKey) throw
|
|
291
|
-
if (!options.projectId) throw
|
|
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);
|
|
292
674
|
this.options.baseUrl = (_this$options$baseUrl = this.options.baseUrl) !== null && _this$options$baseUrl !== void 0 ? _this$options$baseUrl : `https://api.${DOMAIN}/v1`;
|
|
293
675
|
this.options.cdnBaseUrl = (_this$options$cdnBase = this.options.cdnBaseUrl) !== null && _this$options$cdnBase !== void 0 ? _this$options$cdnBase : `https://cdn.${DOMAIN}/v1`;
|
|
294
676
|
this.api = createApi(this.options);
|
|
295
677
|
this.endpoints = createEndpoints(this.api);
|
|
296
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
|
+
}
|
|
297
686
|
getUploadFetch() {
|
|
298
|
-
var _this$options$request,
|
|
687
|
+
var _this$options$request, _ref2, _this$options$uploadF;
|
|
299
688
|
const requestBackendFetch = (_this$options$request = this.options.requestBackend) === null || _this$options$request === void 0 ? void 0 : _this$options$request.fetch;
|
|
300
|
-
const fetchImpl = (
|
|
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;
|
|
301
690
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
302
|
-
return fetchImpl;
|
|
691
|
+
return safeFetch(fetchImpl, this.options);
|
|
303
692
|
}
|
|
304
693
|
submitRawAssetUpload(options, queue) {
|
|
305
694
|
var _this = this;
|
|
@@ -384,20 +773,43 @@ var CalmLensClient = class {
|
|
|
384
773
|
}
|
|
385
774
|
parseRawUploadResponse(response) {
|
|
386
775
|
return _asyncToGenerator(function* () {
|
|
387
|
-
|
|
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
|
+
}
|
|
388
786
|
if (!response.ok) {
|
|
389
787
|
if (isApiErrorPayload(data)) throw calmLensError({
|
|
390
788
|
id: data.code,
|
|
391
789
|
defaultMessage: data.message
|
|
392
790
|
}, {
|
|
393
791
|
message: data.message,
|
|
792
|
+
status: response.status,
|
|
394
793
|
details: _objectSpread2(_objectSpread2({}, data.details), {}, {
|
|
395
794
|
traceId: data.traceId,
|
|
396
795
|
network: true
|
|
397
796
|
})
|
|
398
797
|
});
|
|
399
|
-
throw
|
|
798
|
+
throw calmLensError({ id: "sdk/http-error" }, {
|
|
799
|
+
message: `HTTP ${response.status}`,
|
|
800
|
+
status: response.status
|
|
801
|
+
});
|
|
400
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
|
+
});
|
|
401
813
|
return data;
|
|
402
814
|
})();
|
|
403
815
|
}
|
|
@@ -408,10 +820,10 @@ var CalmLensClient = class {
|
|
|
408
820
|
* Create a CDN URL for asset content or previews.
|
|
409
821
|
* Private assets require an authenticated request or signed URL.
|
|
410
822
|
*/
|
|
411
|
-
getAssetUrl: (
|
|
823
|
+
getAssetUrl: (_ref3) => {
|
|
412
824
|
var _options$resource;
|
|
413
|
-
let { assetIdentifier } =
|
|
414
|
-
if (!assetIdentifier) throw
|
|
825
|
+
let { assetIdentifier } = _ref3, options = _objectWithoutProperties(_ref3, _excluded3);
|
|
826
|
+
if (!assetIdentifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset identifier is required" });
|
|
415
827
|
const resource = (_options$resource = options.resource) !== null && _options$resource !== void 0 ? _options$resource : "content";
|
|
416
828
|
const url = `${this.options.cdnBaseUrl.replace(/\/$/, "")}/assets/${encodeURIComponent(this.options.projectId)}/${encodeURIComponent(assetIdentifier)}/${resource}`;
|
|
417
829
|
return appendCdnSelector(url, options);
|
|
@@ -421,33 +833,27 @@ var CalmLensClient = class {
|
|
|
421
833
|
* Private assets are authenticated with the client's API key.
|
|
422
834
|
*/
|
|
423
835
|
serve: function() {
|
|
424
|
-
var
|
|
836
|
+
var _ref5 = _asyncToGenerator(function* (_ref4) {
|
|
425
837
|
var _this$options$cdnFetc;
|
|
426
|
-
let { assetIdentifier, init } =
|
|
838
|
+
let { assetIdentifier, init } = _ref4, urlOptions = _objectWithoutProperties(_ref4, _excluded4);
|
|
427
839
|
const fetchImpl = (_this$options$cdnFetc = _this3.options.cdnFetch) !== null && _this$options$cdnFetc !== void 0 ? _this$options$cdnFetc : globalThis.fetch;
|
|
428
840
|
if (!fetchImpl) throw calmLensError(SDK_ERRORS.NO_CDN_FETCH);
|
|
429
|
-
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));
|
|
430
842
|
});
|
|
431
|
-
return function serve(
|
|
432
|
-
return
|
|
843
|
+
return function serve(_x3) {
|
|
844
|
+
return _ref5.apply(this, arguments);
|
|
433
845
|
};
|
|
434
846
|
}()
|
|
435
847
|
};
|
|
436
848
|
}
|
|
437
849
|
get text() {
|
|
438
850
|
var _this4 = this;
|
|
439
|
-
return {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
* decision. Check `status` (`"approved"` or `"rejected"`) and `report.flagged`.
|
|
443
|
-
* The text is not retained after classification unless `processingOptions` says so.
|
|
444
|
-
*/
|
|
445
|
-
moderate: function() {
|
|
446
|
-
var _ref5 = _asyncToGenerator(function* (options) {
|
|
447
|
-
return _this4.assets.analyze(toTextAssetOptions(options));
|
|
851
|
+
return { moderate: function() {
|
|
852
|
+
var _ref6 = _asyncToGenerator(function* (options) {
|
|
853
|
+
return _this4.assets.moderate(toTextAssetOptions(options));
|
|
448
854
|
});
|
|
449
|
-
return function moderate(
|
|
450
|
-
return
|
|
855
|
+
return function moderate(_x4) {
|
|
856
|
+
return _ref6.apply(this, arguments);
|
|
451
857
|
};
|
|
452
858
|
}() };
|
|
453
859
|
}
|
|
@@ -460,15 +866,15 @@ moderate: function() {
|
|
|
460
866
|
* @returns Promise with paginated assets
|
|
461
867
|
*/
|
|
462
868
|
list: function() {
|
|
463
|
-
var
|
|
869
|
+
var _ref7 = _asyncToGenerator(function* (options) {
|
|
464
870
|
var _options$pageIndex;
|
|
465
871
|
return (yield _this5.endpoints.getAssetsPage.submit({
|
|
466
872
|
params: { projectId: _this5.options.projectId },
|
|
467
873
|
query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex = options.pageIndex) !== null && _options$pageIndex !== void 0 ? _options$pageIndex : 0 })
|
|
468
874
|
})).data;
|
|
469
875
|
});
|
|
470
|
-
return function list(
|
|
471
|
-
return
|
|
876
|
+
return function list(_x5) {
|
|
877
|
+
return _ref7.apply(this, arguments);
|
|
472
878
|
};
|
|
473
879
|
}(),
|
|
474
880
|
/**
|
|
@@ -477,25 +883,25 @@ moderate: function() {
|
|
|
477
883
|
* @returns Promise with asset data
|
|
478
884
|
*/
|
|
479
885
|
retrieve: function() {
|
|
480
|
-
var
|
|
481
|
-
if (!assetId) throw
|
|
886
|
+
var _ref8 = _asyncToGenerator(function* ({ assetId }) {
|
|
887
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
482
888
|
return (yield _this5.endpoints.getAsset.submit({ params: { assetId } })).data;
|
|
483
889
|
});
|
|
484
|
-
return function retrieve(
|
|
485
|
-
return
|
|
890
|
+
return function retrieve(_x6) {
|
|
891
|
+
return _ref8.apply(this, arguments);
|
|
486
892
|
};
|
|
487
893
|
}(),
|
|
488
894
|
update: function() {
|
|
489
|
-
var
|
|
490
|
-
let { assetId } =
|
|
491
|
-
if (!assetId) throw
|
|
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" });
|
|
492
898
|
return (yield _this5.endpoints.patchAsset.submit({
|
|
493
899
|
params: { assetId },
|
|
494
900
|
body
|
|
495
901
|
})).data;
|
|
496
902
|
});
|
|
497
|
-
return function update(
|
|
498
|
-
return
|
|
903
|
+
return function update(_x7) {
|
|
904
|
+
return _ref10.apply(this, arguments);
|
|
499
905
|
};
|
|
500
906
|
}(),
|
|
501
907
|
/**
|
|
@@ -505,17 +911,17 @@ moderate: function() {
|
|
|
505
911
|
* @returns Promise with paginated child assets
|
|
506
912
|
*/
|
|
507
913
|
listChildren: function() {
|
|
508
|
-
var
|
|
914
|
+
var _ref12 = _asyncToGenerator(function* (_ref11) {
|
|
509
915
|
var _options$pageIndex2;
|
|
510
|
-
let { assetId } =
|
|
511
|
-
if (!assetId) throw
|
|
916
|
+
let { assetId } = _ref11, options = _objectWithoutProperties(_ref11, _excluded6);
|
|
917
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
512
918
|
return (yield _this5.endpoints.getAssetChildren.submit({
|
|
513
919
|
params: { assetId },
|
|
514
920
|
query: _objectSpread2(_objectSpread2({}, options), {}, { pageIndex: (_options$pageIndex2 = options.pageIndex) !== null && _options$pageIndex2 !== void 0 ? _options$pageIndex2 : 0 })
|
|
515
921
|
})).data;
|
|
516
922
|
});
|
|
517
|
-
return function listChildren(
|
|
518
|
-
return
|
|
923
|
+
return function listChildren(_x8) {
|
|
924
|
+
return _ref12.apply(this, arguments);
|
|
519
925
|
};
|
|
520
926
|
}(),
|
|
521
927
|
/**
|
|
@@ -525,7 +931,7 @@ moderate: function() {
|
|
|
525
931
|
* @returns Promise with created asset
|
|
526
932
|
*/
|
|
527
933
|
create: function() {
|
|
528
|
-
var
|
|
934
|
+
var _ref13 = _asyncToGenerator(function* (options) {
|
|
529
935
|
const body = prepareSubmitAssetOptions(options);
|
|
530
936
|
if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, true);
|
|
531
937
|
return (yield _this5.endpoints.postUploadAsset.submit({
|
|
@@ -534,19 +940,20 @@ moderate: function() {
|
|
|
534
940
|
query: { queue: true }
|
|
535
941
|
})).data;
|
|
536
942
|
});
|
|
537
|
-
return function create(
|
|
538
|
-
return
|
|
943
|
+
return function create(_x9) {
|
|
944
|
+
return _ref13.apply(this, arguments);
|
|
539
945
|
};
|
|
540
946
|
}(),
|
|
541
947
|
/**
|
|
542
|
-
* Submit a new asset and
|
|
948
|
+
* Submit a new asset and moderate it synchronously
|
|
543
949
|
* The asset will be classified immediately before the response is returned.
|
|
544
950
|
* This may take longer but ensures the asset is fully processed.
|
|
545
951
|
* @param options - Asset submission options
|
|
546
952
|
* @returns Promise with created and analyzed asset
|
|
547
953
|
*/
|
|
548
|
-
|
|
549
|
-
var
|
|
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" });
|
|
550
957
|
const body = prepareSubmitAssetOptions(options);
|
|
551
958
|
if ("content" in body || "part" in body) return yield _this5.submitRawAssetUpload(body, false);
|
|
552
959
|
return (yield _this5.endpoints.postUploadAsset.submit({
|
|
@@ -555,8 +962,8 @@ moderate: function() {
|
|
|
555
962
|
query: { queue: false }
|
|
556
963
|
})).data;
|
|
557
964
|
});
|
|
558
|
-
return function
|
|
559
|
-
return
|
|
965
|
+
return function moderate(_x10) {
|
|
966
|
+
return _ref14.apply(this, arguments);
|
|
560
967
|
};
|
|
561
968
|
}(),
|
|
562
969
|
/**
|
|
@@ -566,10 +973,10 @@ moderate: function() {
|
|
|
566
973
|
* @returns Promise with asset data
|
|
567
974
|
*/
|
|
568
975
|
uploadPart: function() {
|
|
569
|
-
var
|
|
976
|
+
var _ref15 = _asyncToGenerator(function* ({ assetId, part }) {
|
|
570
977
|
var _part$sizeInBytes3, _this$multipartUpload;
|
|
571
|
-
if (!assetId) throw
|
|
572
|
-
if (!part) throw
|
|
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" });
|
|
573
980
|
const validation = validateAssetPayload(part, {
|
|
574
981
|
multipart: true,
|
|
575
982
|
isFinal: part.isFinal
|
|
@@ -579,13 +986,13 @@ moderate: function() {
|
|
|
579
986
|
const partSizeInBytes = (_part$sizeInBytes3 = part.sizeInBytes) !== null && _part$sizeInBytes3 !== void 0 ? _part$sizeInBytes3 : getAssetPayloadByteLength(part);
|
|
580
987
|
if (existingImageSizeInBytes !== void 0 && partSizeInBytes !== void 0) {
|
|
581
988
|
const totalSizeInBytes = existingImageSizeInBytes + partSizeInBytes;
|
|
582
|
-
if (totalSizeInBytes >
|
|
583
|
-
if (part.isFinal && totalSizeInBytes <
|
|
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);
|
|
584
991
|
}
|
|
585
992
|
return yield _this5.submitRawAssetPart(assetId, part, (_this$multipartUpload = _this5.multipartUploadQueues.get(assetId)) !== null && _this$multipartUpload !== void 0 ? _this$multipartUpload : false);
|
|
586
993
|
});
|
|
587
|
-
return function uploadPart(
|
|
588
|
-
return
|
|
994
|
+
return function uploadPart(_x11) {
|
|
995
|
+
return _ref15.apply(this, arguments);
|
|
589
996
|
};
|
|
590
997
|
}(),
|
|
591
998
|
/**
|
|
@@ -594,11 +1001,11 @@ moderate: function() {
|
|
|
594
1001
|
* auth cookies or API keys to the CDN on every media request.
|
|
595
1002
|
*/
|
|
596
1003
|
createSignedUrl: function() {
|
|
597
|
-
var
|
|
1004
|
+
var _ref17 = _asyncToGenerator(function* (_ref16) {
|
|
598
1005
|
var _options$resource2, _options$expiresInSec;
|
|
599
|
-
let { assetId } =
|
|
600
|
-
if (!assetId) throw
|
|
601
|
-
if (options.lens && options.transform) throw
|
|
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" });
|
|
602
1009
|
return (yield _this5.endpoints.postAssetSignedUrl.submit({
|
|
603
1010
|
body: {
|
|
604
1011
|
resource: (_options$resource2 = options.resource) !== null && _options$resource2 !== void 0 ? _options$resource2 : "content",
|
|
@@ -609,20 +1016,33 @@ moderate: function() {
|
|
|
609
1016
|
params: { assetId }
|
|
610
1017
|
})).data;
|
|
611
1018
|
});
|
|
612
|
-
return function createSignedUrl(
|
|
613
|
-
return
|
|
1019
|
+
return function createSignedUrl(_x12) {
|
|
1020
|
+
return _ref17.apply(this, arguments);
|
|
614
1021
|
};
|
|
615
1022
|
}(),
|
|
616
1023
|
move: function() {
|
|
617
|
-
var
|
|
618
|
-
if (!assetId) throw
|
|
1024
|
+
var _ref18 = _asyncToGenerator(function* ({ assetId, folderId }) {
|
|
1025
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
619
1026
|
return (yield _this5.endpoints.moveAsset.submit({
|
|
620
1027
|
params: { assetId },
|
|
621
1028
|
body: { folderId }
|
|
622
1029
|
})).data;
|
|
623
1030
|
});
|
|
624
|
-
return function move(
|
|
625
|
-
return
|
|
1031
|
+
return function move(_x13) {
|
|
1032
|
+
return _ref18.apply(this, arguments);
|
|
1033
|
+
};
|
|
1034
|
+
}(),
|
|
1035
|
+
/**
|
|
1036
|
+
* Processes an asset that failed (status `error`) again. It returns to `pending` and is
|
|
1037
|
+
* moderated like a new upload; its content must still be stored.
|
|
1038
|
+
*/
|
|
1039
|
+
retry: function() {
|
|
1040
|
+
var _ref19 = _asyncToGenerator(function* ({ assetId }) {
|
|
1041
|
+
if (!assetId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Asset ID is required" });
|
|
1042
|
+
return (yield _this5.endpoints.retryAsset.submit({ params: { assetId } })).data;
|
|
1043
|
+
});
|
|
1044
|
+
return function retry(_x14) {
|
|
1045
|
+
return _ref19.apply(this, arguments);
|
|
626
1046
|
};
|
|
627
1047
|
}()
|
|
628
1048
|
};
|
|
@@ -632,17 +1052,18 @@ moderate: function() {
|
|
|
632
1052
|
return {
|
|
633
1053
|
/**
|
|
634
1054
|
* List project events after a cursor, oldest first. Call without `after` to get a cursor
|
|
635
|
-
* for "now", then poll with the returned `cursor`.
|
|
1055
|
+
* for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
|
|
1056
|
+
* reshaped as `{ id, type, createdAt, projectId, data }`.
|
|
636
1057
|
*/
|
|
637
1058
|
list: function() {
|
|
638
|
-
var
|
|
1059
|
+
var _ref20 = _asyncToGenerator(function* (options = {}) {
|
|
639
1060
|
return (yield _this6.endpoints.getEvents.submit({
|
|
640
1061
|
params: { projectId: _this6.options.projectId },
|
|
641
1062
|
query: options
|
|
642
1063
|
})).data;
|
|
643
1064
|
});
|
|
644
1065
|
return function list() {
|
|
645
|
-
return
|
|
1066
|
+
return _ref20.apply(this, arguments);
|
|
646
1067
|
};
|
|
647
1068
|
}() };
|
|
648
1069
|
}
|
|
@@ -650,65 +1071,65 @@ list: function() {
|
|
|
650
1071
|
var _this7 = this;
|
|
651
1072
|
return {
|
|
652
1073
|
list: function() {
|
|
653
|
-
var
|
|
1074
|
+
var _ref21 = _asyncToGenerator(function* () {
|
|
654
1075
|
return (yield _this7.endpoints.getFolders.submit({ params: { projectId: _this7.options.projectId } })).data.folders;
|
|
655
1076
|
});
|
|
656
1077
|
return function list() {
|
|
657
|
-
return
|
|
1078
|
+
return _ref21.apply(this, arguments);
|
|
658
1079
|
};
|
|
659
1080
|
}(),
|
|
660
1081
|
retrieve: function() {
|
|
661
|
-
var
|
|
662
|
-
if (!folderId) throw
|
|
1082
|
+
var _ref22 = _asyncToGenerator(function* ({ folderId }) {
|
|
1083
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
663
1084
|
return (yield _this7.endpoints.getFolder.submit({ params: { folderId } })).data;
|
|
664
1085
|
});
|
|
665
|
-
return function retrieve(
|
|
666
|
-
return
|
|
1086
|
+
return function retrieve(_x15) {
|
|
1087
|
+
return _ref22.apply(this, arguments);
|
|
667
1088
|
};
|
|
668
1089
|
}(),
|
|
669
1090
|
create: function() {
|
|
670
|
-
var
|
|
1091
|
+
var _ref23 = _asyncToGenerator(function* (options) {
|
|
671
1092
|
return (yield _this7.endpoints.postFolder.submit({
|
|
672
1093
|
params: { projectId: _this7.options.projectId },
|
|
673
1094
|
body: options
|
|
674
1095
|
})).data;
|
|
675
1096
|
});
|
|
676
|
-
return function create(
|
|
677
|
-
return
|
|
1097
|
+
return function create(_x16) {
|
|
1098
|
+
return _ref23.apply(this, arguments);
|
|
678
1099
|
};
|
|
679
1100
|
}(),
|
|
680
1101
|
update: function() {
|
|
681
|
-
var
|
|
682
|
-
let { folderId } =
|
|
683
|
-
if (!folderId) throw
|
|
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" });
|
|
684
1105
|
return (yield _this7.endpoints.patchFolder.submit({
|
|
685
1106
|
params: { folderId },
|
|
686
1107
|
body
|
|
687
1108
|
})).data;
|
|
688
1109
|
});
|
|
689
|
-
return function update(
|
|
690
|
-
return
|
|
1110
|
+
return function update(_x17) {
|
|
1111
|
+
return _ref25.apply(this, arguments);
|
|
691
1112
|
};
|
|
692
1113
|
}(),
|
|
693
1114
|
delete: function() {
|
|
694
|
-
var
|
|
695
|
-
if (!folderId) throw
|
|
1115
|
+
var _ref26 = _asyncToGenerator(function* ({ folderId }) {
|
|
1116
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
696
1117
|
yield _this7.endpoints.deleteFolder.submit({ params: { folderId } });
|
|
697
1118
|
});
|
|
698
|
-
return function _delete(
|
|
699
|
-
return
|
|
1119
|
+
return function _delete(_x18) {
|
|
1120
|
+
return _ref26.apply(this, arguments);
|
|
700
1121
|
};
|
|
701
1122
|
}(),
|
|
702
1123
|
move: function() {
|
|
703
|
-
var
|
|
704
|
-
if (!folderId) throw
|
|
1124
|
+
var _ref27 = _asyncToGenerator(function* ({ folderId, parentId }) {
|
|
1125
|
+
if (!folderId) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Folder ID is required" });
|
|
705
1126
|
return (yield _this7.endpoints.moveFolder.submit({
|
|
706
1127
|
params: { folderId },
|
|
707
1128
|
body: { parentId }
|
|
708
1129
|
})).data;
|
|
709
1130
|
});
|
|
710
|
-
return function move(
|
|
711
|
-
return
|
|
1131
|
+
return function move(_x19) {
|
|
1132
|
+
return _ref27.apply(this, arguments);
|
|
712
1133
|
};
|
|
713
1134
|
}()
|
|
714
1135
|
};
|
|
@@ -720,7 +1141,7 @@ list: function() {
|
|
|
720
1141
|
ensureLens(options) {
|
|
721
1142
|
var _this8 = this;
|
|
722
1143
|
return _asyncToGenerator(function* () {
|
|
723
|
-
if (!options.identifier) throw
|
|
1144
|
+
if (!options.identifier) throw calmLensError({ id: "upload/invalid-payload" }, { message: "Lens identifier is required" });
|
|
724
1145
|
const [lens] = yield _this8.ensureLenses({ lenses: [options] });
|
|
725
1146
|
return lens;
|
|
726
1147
|
})();
|
|
@@ -732,8 +1153,8 @@ list: function() {
|
|
|
732
1153
|
ensureLenses({ lenses }) {
|
|
733
1154
|
var _this9 = this;
|
|
734
1155
|
return _asyncToGenerator(function* () {
|
|
735
|
-
if (lenses.length === 0) throw
|
|
736
|
-
if (lenses.some((option) => !option.identifier)) throw
|
|
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" });
|
|
737
1158
|
const missingOptions = [];
|
|
738
1159
|
const missingKeys = /* @__PURE__ */ new Set();
|
|
739
1160
|
for (const option of lenses) {
|
|
@@ -764,7 +1185,7 @@ list: function() {
|
|
|
764
1185
|
});
|
|
765
1186
|
for (const [index, lens] of result.data.lenses.entries()) {
|
|
766
1187
|
const optionsForLens = options[index];
|
|
767
|
-
if (!optionsForLens) throw
|
|
1188
|
+
if (!optionsForLens) throw calmLensError({ id: "sdk/invalid-response" }, { message: "CalmLens returned an unexpected lens response" });
|
|
768
1189
|
for (const [cacheKey, cachedLens] of _this10.ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) _this10.ensuredLenses.delete(cacheKey);
|
|
769
1190
|
_this10.ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
|
|
770
1191
|
}
|
|
@@ -772,4 +1193,4 @@ list: function() {
|
|
|
772
1193
|
}
|
|
773
1194
|
};
|
|
774
1195
|
//#endregion
|
|
775
|
-
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 };
|